Simplify child auto-approval start path and tests

- Build the start status and lifecycle records from one match on the
  child start decision, and move the resume short-circuit into
  child_start_decision.
- Read the parent's projection without waiting for its projector to
  settle: the parent's settings are fixed at create. Keep the error
  context the projection helper provided.
- Collapse the AutoApproved projection fold into one get_or_insert.
- Resolve server.approvals.allow_child_auto_approval with the
  defaults.toml expect pattern instead of a second default.
- Keep doc-comment code spans on one line.
- Deduplicate the new server tests: create_run_with_bearer delegates to
  create_run_with_workflow_config, create_child_as_worker takes optional
  args, JWT app builders are shared, lifecycle checks reuse
  lifecycle_transition_count, and pending/managed-status assertions use
  helpers.
- Fix a needless_raw_string_hashes lint and apply rustfmt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Scott Werner 2026-10-26 21:56:15 -04:00
parent 465cc66283
commit 27df589cc8
7 changed files with 117 additions and 187 deletions

View file

@ -1,6 +1,7 @@
use std::collections::HashSet;
use std::sync::Arc;
use anyhow::Context as _;
use chrono::Utc;
use fabro_store::platform_records::{PlatformRecord, RunLifecycleKind, RunLifecycleRecord};
use tokio::time::{Instant, sleep_until};
@ -129,7 +130,8 @@ enum ChildStartDecision {
AutoApproved,
}
/// Decide whether a non-resume start of `run_state` needs operator approval.
/// Decide whether a start of `run_state` needs operator approval. A resume
/// is never gated.
///
/// A worker-started child is auto-approved only when the server enables the
/// capability and the spawning parent's persisted workflow settings opt in.
@ -140,8 +142,12 @@ enum ChildStartDecision {
async fn child_start_decision(
state: &AppState,
run_state: &fabro_store::RunProjection,
resume: bool,
actor: &Principal,
) -> Result<ChildStartDecision, ApiError> {
if resume {
return Ok(ChildStartDecision::NotGated);
}
let Principal::Worker { run_id } = actor else {
return Ok(ChildStartDecision::NotGated);
};
@ -154,15 +160,25 @@ async fn child_start_decision(
// could approve it, so operator approval is required.
return Ok(ChildStartDecision::ApprovalRequired);
}
if !state.server_settings().server.approvals.allow_child_auto_approval {
if !state
.server_settings()
.server
.approvals
.allow_child_auto_approval
{
return Ok(ChildStartDecision::ApprovalRequired);
}
// The spawning parent owns the policy: read it from the parent's own
// persisted settings, not from the child's parent link, so reassigning
// the link cannot change the decision. A parent whose projection is gone
// fails closed to the approval gate.
let parent = run_records::projection(state, *run_id)
// fails closed to the approval gate. The parent's settings are fixed at
// create, so there is no need to wait for its projector to settle.
let parent = state
.stores
.run_summaries
.load_petri_projection(run_id)
.await
.with_context(|| format!("loading the projection of parent run {run_id}"))
.map_err(|err| ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, err.to_string()))?;
let opted_in = parent.is_some_and(|parent| parent.spec.settings.run.children.auto_approve);
Ok(if opted_in {
@ -189,40 +205,30 @@ pub(super) async fn queue_run(
.root()
.to_path_buf();
let dot_source = run_state.spec.graph_source.clone().unwrap_or_default();
let decision = if resume {
ChildStartDecision::NotGated
} else {
child_start_decision(state, run_state, &actor).await?
};
let approval_required = matches!(decision, ChildStartDecision::ApprovalRequired);
let mut start_requested = RunLifecycleRecord::new(RunLifecycleKind::StartRequested);
start_requested.source = Some(if resume { "resume" } else { "start" }.to_string());
let next_status = if approval_required {
RunStatus::Pending {
reason: PendingReason::ApprovalRequired,
let (next_status, next) = match child_start_decision(state, run_state, resume, &actor).await? {
ChildStartDecision::NotGated => (RunStatus::Runnable, vec![run_records::runnable(
RunRunnableSource::StartRequested,
)]),
ChildStartDecision::ApprovalRequired => {
let status = RunStatus::Pending {
reason: PendingReason::ApprovalRequired,
};
(status, vec![run_records::transition(
RunLifecycleKind::Pending,
status,
)])
}
} else {
RunStatus::Runnable
};
let records = match decision {
ChildStartDecision::NotGated => vec![
start_requested,
run_records::runnable(RunRunnableSource::StartRequested),
],
ChildStartDecision::ApprovalRequired => vec![
start_requested,
run_records::transition(RunLifecycleKind::Pending, next_status),
],
// Policy approval is recorded as its own auditable transition before
// the runnable state, so the projection never shows a transitive
// pending state for an auto-approved child.
ChildStartDecision::AutoApproved => vec![
start_requested,
ChildStartDecision::AutoApproved => (RunStatus::Runnable, vec![
RunLifecycleRecord::new(RunLifecycleKind::AutoApproved),
run_records::runnable(RunRunnableSource::AutoApproved),
],
]),
};
for record in records {
for record in std::iter::once(start_requested).chain(next) {
if let Err(err) = run_records::lifecycle(state, id, record).await {
return Err(ApiError::new(
StatusCode::INTERNAL_SERVER_ERROR,
@ -249,7 +255,7 @@ pub(super) async fn queue_run(
);
}
if !approval_required {
if next_status == RunStatus::Runnable {
state.scheduler_notify.notify_one();
}
Ok(())

View file

@ -627,15 +627,21 @@ fn jwt_auth_mode() -> AuthMode {
}
fn jwt_auth_state() -> Arc<AppState> {
test_app_state_with_session_key(
default_test_server_settings(),
RunLayer::default(),
Some(TEST_SESSION_SECRET),
)
jwt_auth_state_with(default_test_server_settings(), RunLayer::default())
}
fn jwt_auth_state_with(
server_settings: fabro_types::ServerSettings,
run_defaults: RunLayer,
) -> Arc<AppState> {
test_app_state_with_session_key(server_settings, run_defaults, Some(TEST_SESSION_SECRET))
}
fn jwt_auth_app() -> (Arc<AppState>, Router) {
let state = jwt_auth_state();
jwt_auth_app_with_state(jwt_auth_state())
}
fn jwt_auth_app_with_state(state: Arc<AppState>) -> (Arc<AppState>, Router) {
let app = build_router(Arc::clone(&state), jwt_auth_mode());
(state, app)
}
@ -681,25 +687,7 @@ fn issue_test_run_tools_worker_token(run_id: &RunId) -> String {
}
async fn create_run_with_bearer(app: &Router, bearer: &str) -> RunId {
let response = app
.clone()
.oneshot(
Request::builder()
.method("POST")
.uri(api("/runs"))
.header(header::AUTHORIZATION, format!("Bearer {bearer}"))
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(
test_intent_with_bearer(app, "workflow.fabro", MINIMAL_DOT, None, Some(bearer))
.await
.to_string(),
))
.unwrap(),
)
.await
.unwrap();
let body = response_json!(response, StatusCode::CREATED).await;
body["id"].as_str().unwrap().parse().unwrap()
create_run_with_workflow_config(app, bearer, None).await
}
fn bearer_request(method: Method, path: &str, bearer: &str, body: Body) -> Request<Body> {
@ -8005,13 +7993,10 @@ methods = ["dev-token"]
allow_child_auto_approval = {allow_child_auto_approval}
"#
);
let state = test_app_state_with_session_key(
jwt_auth_app_with_state(jwt_auth_state_with(
server_settings_from_toml(&source),
manifest_run_defaults_from_toml(&source),
Some(TEST_SESSION_SECRET),
);
let app = build_router(Arc::clone(&state), jwt_auth_mode());
(state, app)
))
}
async fn create_run_with_workflow_config(
@ -8041,6 +8026,7 @@ async fn create_child_as_worker(
worker_token: &str,
parent_run_id: RunId,
registrar_bearer: &str,
args: Option<serde_json::Value>,
) -> RunId {
let mut child_intent = test_intent_with_bearer(
app,
@ -8051,6 +8037,9 @@ async fn create_child_as_worker(
)
.await;
child_intent["parent_id"] = json!(parent_run_id.to_string());
if let Some(args) = args {
child_intent["args"] = args;
}
let response = app
.clone()
.oneshot(json_bearer_request(
@ -8077,20 +8066,19 @@ async fn start_run_as_worker(app: &Router, worker_token: &str, run_id: RunId) ->
.unwrap()
}
async fn child_lifecycle_transitions(state: &AppState, run_id: RunId) -> Vec<String> {
state
.stores
.run_summaries
.platform_records()
.read(&run_id)
.await
.unwrap()
.iter()
.filter_map(|stored| match &stored.record {
PlatformRecord::RunLifecycle(record) => Some(record.transition.to_string()),
_ => None,
fn assert_pending_approval(body: &serde_json::Value) {
assert_eq!(
run_json_status(body),
&json!({
"kind": "pending",
"reason": "approval_required"
})
.collect()
);
}
fn assert_managed_status(state: &AppState, run_id: RunId, status: RunStatus) {
let runs = state.runs.lock().expect("runs lock poisoned");
assert_eq!(runs.get(&run_id).map(|run| run.status), Some(status));
}
#[tokio::test]
@ -8101,32 +8089,22 @@ async fn child_start_stays_pending_when_only_the_workflow_opts_in() {
create_run_with_workflow_config(&app, &user_jwt, Some(CHILD_AUTO_APPROVE_TOML)).await;
let worker_token = issue_test_run_tools_worker_token(&parent_run_id);
let child_run_id =
create_child_as_worker(&app, &worker_token, parent_run_id, &user_jwt).await;
create_child_as_worker(&app, &worker_token, parent_run_id, &user_jwt, None).await;
let pending_body = response_json!(
start_run_as_worker(&app, &worker_token, child_run_id).await,
StatusCode::OK
)
.await;
assert_eq!(
run_json_status(&pending_body),
&json!({
"kind": "pending",
"reason": "approval_required"
})
);
assert_pending_approval(&pending_body);
assert_eq!(
pending_body["lifecycle"]["approval"]["state"].as_str(),
Some("pending")
);
let runs = state.runs.lock().expect("runs lock poisoned");
assert_eq!(
runs.get(&child_run_id).map(|run| run.status),
Some(RunStatus::Pending {
reason: fabro_types::PendingReason::ApprovalRequired,
})
);
assert_managed_status(&state, child_run_id, RunStatus::Pending {
reason: fabro_types::PendingReason::ApprovalRequired,
});
}
#[tokio::test]
@ -8136,28 +8114,18 @@ async fn child_start_stays_pending_when_only_the_server_opts_in() {
let parent_run_id = create_run_with_workflow_config(&app, &user_jwt, None).await;
let worker_token = issue_test_run_tools_worker_token(&parent_run_id);
let child_run_id =
create_child_as_worker(&app, &worker_token, parent_run_id, &user_jwt).await;
create_child_as_worker(&app, &worker_token, parent_run_id, &user_jwt, None).await;
let pending_body = response_json!(
start_run_as_worker(&app, &worker_token, child_run_id).await,
StatusCode::OK
)
.await;
assert_eq!(
run_json_status(&pending_body),
&json!({
"kind": "pending",
"reason": "approval_required"
})
);
assert_pending_approval(&pending_body);
let runs = state.runs.lock().expect("runs lock poisoned");
assert_eq!(
runs.get(&child_run_id).map(|run| run.status),
Some(RunStatus::Pending {
reason: fabro_types::PendingReason::ApprovalRequired,
})
);
assert_managed_status(&state, child_run_id, RunStatus::Pending {
reason: fabro_types::PendingReason::ApprovalRequired,
});
}
#[tokio::test]
@ -8168,7 +8136,7 @@ async fn child_start_is_auto_approved_when_both_opt_ins_are_enabled() {
create_run_with_workflow_config(&app, &user_jwt, Some(CHILD_AUTO_APPROVE_TOML)).await;
let worker_token = issue_test_run_tools_worker_token(&parent_run_id);
let child_run_id =
create_child_as_worker(&app, &worker_token, parent_run_id, &user_jwt).await;
create_child_as_worker(&app, &worker_token, parent_run_id, &user_jwt, None).await;
let approved_body = response_json!(
start_run_as_worker(&app, &worker_token, child_run_id).await,
@ -8191,15 +8159,17 @@ async fn child_start_is_auto_approved_when_both_opt_ins_are_enabled() {
// The lifecycle history records one deliberate policy approval; the
// projection never shows a transient pending state.
let transitions = child_lifecycle_transitions(state.as_ref(), child_run_id).await;
assert!(transitions.contains(&"auto_approved".to_string()));
assert!(!transitions.contains(&"pending".to_string()));
let runs = state.runs.lock().expect("runs lock poisoned");
let records = platform_records(&state, child_run_id).await;
assert_eq!(
runs.get(&child_run_id).map(|run| run.status),
Some(RunStatus::Runnable)
lifecycle_transition_count(&records, RunLifecycleKind::AutoApproved),
1
);
assert_eq!(
lifecycle_transition_count(&records, RunLifecycleKind::Pending),
0
);
assert_managed_status(&state, child_run_id, RunStatus::Runnable);
}
#[tokio::test]
@ -8208,42 +8178,21 @@ async fn child_start_ignores_client_auto_approve_args_without_policy() {
let user_jwt = issue_test_user_jwt();
let parent_run_id = create_run_with_bearer(&app, &user_jwt).await;
let worker_token = issue_test_run_tools_worker_token(&parent_run_id);
let mut child_intent = test_intent_with_bearer(
let child_run_id = create_child_as_worker(
&app,
"workflow.fabro",
MINIMAL_DOT,
None,
Some(&user_jwt),
&worker_token,
parent_run_id,
&user_jwt,
Some(json!({ "auto_approve": true })),
)
.await;
child_intent["parent_id"] = json!(parent_run_id.to_string());
child_intent["args"] = json!({ "auto_approve": true });
let response = app
.clone()
.oneshot(json_bearer_request(
Method::POST,
"/runs",
&worker_token,
&child_intent,
))
.await
.unwrap();
let child_body = response_json!(response, StatusCode::CREATED).await;
let child_run_id = child_body["id"].as_str().unwrap().parse::<RunId>().unwrap();
let pending_body = response_json!(
start_run_as_worker(&app, &worker_token, child_run_id).await,
StatusCode::OK
)
.await;
assert_eq!(
run_json_status(&pending_body),
&json!({
"kind": "pending",
"reason": "approval_required"
})
);
assert_pending_approval(&pending_body);
}
#[tokio::test]
@ -8263,13 +8212,7 @@ async fn worker_start_of_runs_it_did_not_spawn_fails_closed_to_approval() {
StatusCode::OK
)
.await;
assert_eq!(
run_json_status(&pending_body),
&json!({
"kind": "pending",
"reason": "approval_required"
})
);
assert_pending_approval(&pending_body);
// Starting a run the worker did not spawn fails closed to the approval
// gate instead of skipping it.
@ -8278,23 +8221,11 @@ async fn worker_start_of_runs_it_did_not_spawn_fails_closed_to_approval() {
StatusCode::OK
)
.await;
assert_eq!(
run_json_status(&pending_body),
&json!({
"kind": "pending",
"reason": "approval_required"
})
);
let projection = state
.load_run_projection(&unrelated_run_id)
.await
.unwrap();
assert_eq!(
projection.status,
RunStatus::Pending {
reason: fabro_types::PendingReason::ApprovalRequired,
}
);
assert_pending_approval(&pending_body);
let projection = state.load_run_projection(&unrelated_run_id).await.unwrap();
assert_eq!(projection.status, RunStatus::Pending {
reason: fabro_types::PendingReason::ApprovalRequired,
});
}
#[tokio::test]

View file

@ -225,20 +225,14 @@ fn fold_lifecycle(projection: &mut RunProjection, record: &RunLifecycleRecord, a
// A child start approved by policy: no request preceded the
// decision, so the approval is created approved in one step
// rather than projected through a transient pending state.
match projection.approval.as_mut() {
Some(approval) => {
approval.state = RunApprovalState::Approved;
approval.decided_at = Some(at);
}
None => {
projection.approval = Some(RunApproval {
state: RunApprovalState::Approved,
requested_at: at,
decided_at: Some(at),
denial_reason: None,
});
}
}
let approval = projection.approval.get_or_insert(RunApproval {
state: RunApprovalState::Approved,
requested_at: at,
decided_at: None,
denial_reason: None,
});
approval.state = RunApprovalState::Approved;
approval.decided_at = Some(at);
}
Kind::Denied => {
if let Some(approval) = projection.approval.as_mut() {

View file

@ -53,10 +53,9 @@ pub use layers::{
RunModelControlsLayer, RunModelLayer, RunPrepareLayer, RunPullRequestLayer, RunRunBranchLayer,
RunScmLayer, ScmGitHubLayer, ServerApiLayer, ServerApprovalsLayer, ServerArtifactsLayer,
ServerAuthGithubLayer, ServerAuthLayer, ServerIntegrationsLayer, ServerLayer,
ServerListenLayer, ServerLoggingLayer,
ServerSandboxLayer, ServerSandboxProviderLayer, ServerSandboxProvidersLayer,
ServerSchedulerLayer, ServerStorageLayer, ServerWebLayer, SettingsLayer, SlackIntegrationLayer,
StickyMap, StringOrSplice, WorkflowLayer,
ServerListenLayer, ServerLoggingLayer, ServerSandboxLayer, ServerSandboxProviderLayer,
ServerSandboxProvidersLayer, ServerSchedulerLayer, ServerStorageLayer, ServerWebLayer,
SettingsLayer, SlackIntegrationLayer, StickyMap, StringOrSplice, WorkflowLayer,
};
pub use logging::{resolve_log_destination, resolve_log_destination_with_env};
pub use parse::ParseError;

View file

@ -55,7 +55,7 @@ pub fn resolve_server(layer: &ServerLayer, errors: &mut Vec<ResolveError>) -> Se
.approvals
.as_ref()
.and_then(|approvals| approvals.allow_child_auto_approval)
.unwrap_or(false),
.expect("defaults.toml should provide server.approvals.allow_child_auto_approval"),
},
logging: ServerLoggingSettings {
level: layer

View file

@ -2013,12 +2013,12 @@ fn run_children_auto_approve_defaults_to_false() {
#[test]
fn run_children_auto_approve_resolves_from_workflow_toml() {
let settings = super::workflow_settings_from_toml(
r#"
r"
_version = 1
[run.children]
auto_approve = true
"#,
",
)
.expect("[run.children] should resolve")
.run;

View file

@ -604,10 +604,10 @@ pub struct RunIntegrationsSettings {
///
/// This governs the child's *lifecycle* start decision (whether the child
/// waits for operator approval), not the child's own agent-interaction
/// approval posture (`run.execution.approval`, which `RunIntentArgs
/// .auto_approve` maps to). It is the workflow half of the child
/// auto-approval opt-in; the server half is `server.approvals
/// .allow_child_auto_approval`, and both must be enabled.
/// approval posture (`run.execution.approval`, which
/// `RunIntentArgs.auto_approve` maps to). It is the workflow half of the
/// child auto-approval opt-in; the server half is
/// `server.approvals.allow_child_auto_approval`, and both must be enabled.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct RunChildrenSettings {