diff --git a/infra/lib/api-stack.ts b/infra/lib/api-stack.ts index 4b988d03a..43a0e6dd2 100644 --- a/infra/lib/api-stack.ts +++ b/infra/lib/api-stack.ts @@ -268,6 +268,16 @@ export class ApiStack extends cdk.Stack { // --- SQS Queues --- + // Queues the worker reads (tickets, CI fix, feedback, webhooks). AWS + // asks for a visibility timeout of at least six times the function's + // timeout (900 s) and a redrive count of at least 5. A ticket run hands + // off to a NEW message before 900 s, so the visibility only matters + // after a crash: the message comes back after 90 minutes, and the + // stuck-run sweep (20 minutes without an update) has failed the run with + // a reason by then. + const WORKER_QUEUE_VISIBILITY = cdk.Duration.seconds(6 * 900); + const WORKER_QUEUE_MAX_RECEIVES = 5; + // Dead letter queue (shared) const dlq = new sqs.Queue(this, "DLQ", { queueName: `${prefix}-dlq`, @@ -278,9 +288,9 @@ export class ApiStack extends cdk.Stack { this.ticketQueue = new sqs.Queue(this, "TicketQueue", { queueName: `${prefix}-tickets`, - visibilityTimeout: cdk.Duration.minutes(16), // > Lambda timeout + visibilityTimeout: WORKER_QUEUE_VISIBILITY, encryption: sqs.QueueEncryption.SQS_MANAGED, - deadLetterQueue: { queue: dlq, maxReceiveCount: 3 }, + deadLetterQueue: { queue: dlq, maxReceiveCount: WORKER_QUEUE_MAX_RECEIVES }, }); // CoderHelm's mail relay (hosted side of hybrid only): its sending @@ -291,16 +301,16 @@ export class ApiStack extends cdk.Stack { this.ciFixQueue = new sqs.Queue(this, "CiFixQueue", { queueName: `${prefix}-ci-fix`, - visibilityTimeout: cdk.Duration.minutes(16), + visibilityTimeout: WORKER_QUEUE_VISIBILITY, encryption: sqs.QueueEncryption.SQS_MANAGED, - deadLetterQueue: { queue: dlq, maxReceiveCount: 3 }, + deadLetterQueue: { queue: dlq, maxReceiveCount: WORKER_QUEUE_MAX_RECEIVES }, }); this.feedbackQueue = new sqs.Queue(this, "FeedbackQueue", { queueName: `${prefix}-feedback`, - visibilityTimeout: cdk.Duration.minutes(16), + visibilityTimeout: WORKER_QUEUE_VISIBILITY, encryption: sqs.QueueEncryption.SQS_MANAGED, - deadLetterQueue: { queue: dlq, maxReceiveCount: 3 }, + deadLetterQueue: { queue: dlq, maxReceiveCount: WORKER_QUEUE_MAX_RECEIVES }, }); // Outbound webhooks: events the work emits (`webhook_emit`) and the @@ -308,9 +318,9 @@ export class ApiStack extends cdk.Stack { // a delivery never waits behind long runs on the tickets queue. this.webhookQueue = new sqs.Queue(this, "WebhookQueue", { queueName: `${prefix}-webhooks`, - visibilityTimeout: cdk.Duration.minutes(16), + visibilityTimeout: WORKER_QUEUE_VISIBILITY, encryption: sqs.QueueEncryption.SQS_MANAGED, - deadLetterQueue: { queue: dlq, maxReceiveCount: 3 }, + deadLetterQueue: { queue: dlq, maxReceiveCount: WORKER_QUEUE_MAX_RECEIVES }, }); // Review-reminder sweep: every 20 min, drop a constant message on the ticket diff --git a/infra/test/synth.test.ts b/infra/test/synth.test.ts index fe6071394..23c80a2a6 100644 --- a/infra/test/synth.test.ts +++ b/infra/test/synth.test.ts @@ -730,6 +730,18 @@ test("sign-in: hosted keeps its open pool (no pre-sign-up trigger) and optional assert.ok(pool.Properties.LambdaConfig.CustomMessage); }); +test("worker queues: visibility 6x the worker timeout, redrive count 5", () => { + const api = synth(selfHost())["coderhelm-prod-api"]; + for (const name of ["tickets", "ci-fix", "feedback", "webhooks"]) { + const queues = api.findResources("AWS::SQS::Queue", { + Properties: { QueueName: `coderhelm-prod-${name}` }, + }); + const q = (Object.values(queues)[0] as any).Properties; + assert.equal(q.VisibilityTimeout, 5400, name); + assert.equal(q.RedrivePolicy.maxReceiveCount, 5, name); + } +}); + test("outbound webhooks: one queue, wired to the worker, sendable by every emitter", () => { const t = synth(selfHost()); const api = t["coderhelm-prod-api"]; @@ -739,9 +751,9 @@ test("outbound webhooks: one queue, wired to the worker, sendable by every emitt const ids = Object.keys(queues); assert.equal(ids.length, 1, "one webhooks queue"); const q = (queues[ids[0]] as any).Properties; - // Visible longer than the worker can run, retried into the shared DLQ. - assert.equal(q.VisibilityTimeout, 960); - assert.equal(q.RedrivePolicy.maxReceiveCount, 3); + // AWS: visibility at least 6x the worker's 900 s, redrive count at least 5. + assert.equal(q.VisibilityTimeout, 5400); + assert.equal(q.RedrivePolicy.maxReceiveCount, 5); // Every function that emits or sends knows the queue. const gw = envOf(api, "coderhelm-prod-gateway"); assert.ok(gw.WEBHOOK_QUEUE_URL, "gateway"); diff --git a/lambda/stuck-run-cleanup/handler.py b/lambda/stuck-run-cleanup/handler.py index 3b38863b0..79c4fb741 100644 --- a/lambda/stuck-run-cleanup/handler.py +++ b/lambda/stuck-run-cleanup/handler.py @@ -50,6 +50,12 @@ ROUND_FIELD = "round" INCOMPLETE_FIELD = "round_incomplete" ROUND_BUDGET_SECONDS = 750 +# A ticket run works in steps (services/worker/src/passes/steps.rs): each +# step queues the next as a new message and records `step_queued_at`. A step +# that is queued and hasn't started (a full queue) is not stuck; past this +# long, it is. +STEP_QUEUED_FIELD = "step_queued_at" +MAX_STEP_QUEUED_HOURS = int(os.environ.get("MAX_STEP_QUEUED_HOURS", "6")) ROUND_SWEEP_GRACE_SECONDS = 300 ROUND_LABELS = { "ci_fix": "CI fix round", @@ -124,6 +130,23 @@ def round_in_budget(run, now): return now < deadline + timedelta(seconds=ROUND_SWEEP_GRACE_SECONDS) +def step_queued(run, now): + """True while the run's next step is queued and hasn't started yet. + + A step that starts updates `updated_at`, so a queued time after the last + update means no step is running and one is waiting for the queue. A step + that started and then died (a crash) has its queued time before the last + update, and the run is swept as usual. + """ + queued = _parse_time(run.get(STEP_QUEUED_FIELD)) + if queued is None: + return False + updated = _parse_time(run.get("updated_at") or run.get("created_at")) + if updated is not None and queued < updated: + return False + return now < queued + timedelta(hours=MAX_STEP_QUEUED_HOURS) + + def has_pull_request(run): try: number = int(run.get("pr_number") or 0) @@ -242,6 +265,7 @@ def handler(event, context): }, "ProjectionExpression": ( "team_id, run_id, created_at, updated_at, title, current_pass, pass_history, #s, " + "step_queued_at, " "#round, pr_number, pr_url" ), } @@ -256,6 +280,9 @@ def handler(event, context): if status == "running" and round_in_budget(item, now): # Its fix round is still inside its own budget. continue + if status == "running" and step_queued(item, now): + # Its next step is queued and hasn't started. + continue if updated and updated < cutoff: stuck_runs.append(item) diff --git a/lambda/tests/test_stuck_run_cleanup.py b/lambda/tests/test_stuck_run_cleanup.py index 5da177f96..2454ab0f7 100644 --- a/lambda/tests/test_stuck_run_cleanup.py +++ b/lambda/tests/test_stuck_run_cleanup.py @@ -119,3 +119,25 @@ def test_no_pr_means_no_pr(self): if __name__ == "__main__": unittest.main() + + +class StepQueued(unittest.TestCase): + NOW = sweep.datetime(2026, 10, 28, 12, 0, tzinfo=sweep.timezone.utc) + + def at(self, minutes): + return (self.NOW - sweep.timedelta(minutes=minutes)).isoformat() + + def test_a_queued_step_not_started_is_not_stuck(self): + run = {"updated_at": self.at(40), "step_queued_at": self.at(39)} + self.assertTrue(sweep.step_queued(run, self.NOW)) + + def test_a_started_step_that_died_is_swept(self): + run = {"updated_at": self.at(30), "step_queued_at": self.at(45)} + self.assertFalse(sweep.step_queued(run, self.NOW)) + + def test_a_step_queued_too_long_is_swept(self): + run = {"updated_at": self.at(60 * 8), "step_queued_at": self.at(60 * 7)} + self.assertFalse(sweep.step_queued(run, self.NOW)) + + def test_no_step_queued(self): + self.assertFalse(sweep.step_queued({"updated_at": self.at(30)}, self.NOW)) diff --git a/services/worker/src/clients/sandbox.rs b/services/worker/src/clients/sandbox.rs index f6e4eebb4..44f0d56f0 100644 --- a/services/worker/src/clients/sandbox.rs +++ b/services/worker/src/clients/sandbox.rs @@ -23,6 +23,8 @@ use aws_sdk_codebuild::types::{EnvironmentVariable, EnvironmentVariableType, Sta use aws_sdk_s3::presigning::PresigningConfig; const MARKER_END: &str = "CODERHELM_CHECKS_END exit="; +/// What a codegen build CodeBuild timed out reports: a tooling failure. +pub const CODEGEN_TIMED_OUT: &str = "the sandbox build timed out (CodeBuild TIMED_OUT)"; const MARKER_START: &str = "===CODERHELM_CHECKS_START==="; /// Poll cadence while a build runs. const POLL_INTERVAL: Duration = Duration::from_secs(6); @@ -615,6 +617,11 @@ impl<'a> SandboxClient<'a> { .map_err(|e| format!("codebuild batch_get_builds failed: {e}"))?; let build = builds.builds().first().ok_or("no build record")?; let status = build.build_status(); + if matches!(status, Some(StatusType::TimedOut)) { + // CodeBuild's own build timeout: the sandbox, not the change + // and not this step's time. + return Ok(CodegenOutcome::not_run(CODEGEN_TIMED_OUT)); + } if !matches!(status, Some(StatusType::InProgress)) { let (group, stream) = build .logs() diff --git a/services/worker/src/passes/generators.rs b/services/worker/src/passes/generators.rs index 2db63d8eb..5352d8cf5 100644 --- a/services/worker/src/passes/generators.rs +++ b/services/worker/src/passes/generators.rs @@ -12,9 +12,13 @@ //! or CONTRIBUTING). Each comes with the inputs it reads and, where known, the //! files it writes (globs). When the diff touches a generator's inputs, the //! generator runs in the sandbox and its output is committed with the change -//! ([`gate`]). Before the pull request opens, a generator whose inputs changed -//! while its outputs did not (or whose run still changes tracked files) blocks -//! it with a plain reason, after one fix round. +//! ([`after_step`]: the worker runs it right after the implement work, never +//! waiting for the coder to call run_codegen). Before the pull request opens, +//! [`gate`] verifies: a generator whose inputs changed while its outputs did +//! not (or whose run still changes tracked files) blocks it with a plain +//! reason, after one fix round. A step without time for a sandbox build never +//! fails the run: the gate says [`GateStop::NeedsTime`] and the run continues +//! in a fresh step at this gate. use std::collections::HashMap; @@ -1186,9 +1190,11 @@ enum Ran { /// It failed because the sandbox's network allowlist refused a host it /// needs: the run's tooling, not the change. Blocked(ToolingFailure), - /// The sandbox isn't set up, is out of time, or the team's policy holds - /// the command. + /// The sandbox isn't set up, or the team's policy holds the command. NotRun(String), + /// This step has too little time left for a sandbox build (or the build + /// ran out of it): a fresh step runs it. + OutOfTime, } /// The hosts a generator build may reach beyond the team's list, and the @@ -1229,7 +1235,7 @@ async fn run_in_sandbox( .with_egress(crate::agent::policy::sandbox_egress(state, &w.msg.team_id).await) .with_generator_hosts(net.hosts.to_vec(), net.cmds.to_vec()); if !sandbox.has_time(w.deadline) { - return Ran::NotRun("not enough time left".into()); + return Ran::OutOfTime; } let (owner, name) = (&w.msg.repo_owner, &w.msg.repo_name); let head = match w.github.get_ref(owner, name, w.branch).await { @@ -1301,11 +1307,31 @@ async fn run_in_sandbox( ), o.output, ), + // CodeBuild timed the build out: the run's tooling, not the change. + Ok(o) + if o.output + .contains(crate::clients::sandbox::CODEGEN_TIMED_OUT) => + { + Ran::Blocked(ToolingFailure::new( + cmd, + crate::clients::sandbox::CODEGEN_TIMED_OUT, + )) + } + // A build that stopped at the step's deadline didn't fail: it needs + // a step with time for it. + Ok(o) if out_of_time(&o.output, || sandbox.has_time(w.deadline)) => Ran::OutOfTime, Ok(o) => Ran::NotRun(o.output), Err(e) => Ran::NotRun(e.to_string()), } } +/// Whether a build that didn't run (or didn't finish) stopped for want of +/// this step's time: the sandbox says so, or there is no runway left now. +fn out_of_time(output: &str, has_time: impl Fn() -> bool) -> bool { + let o = output.to_ascii_lowercase(); + o.contains("exceeded the time budget") || o.contains("not enough time left") || !has_time() +} + /// What one pass over the affected generators found. enum Pass { /// Generators still out of date (empty: all up to date). @@ -1316,6 +1342,8 @@ enum Pass { /// A generator couldn't reach a host the sandbox's network allowlist /// refused: a tooling failure, never a fix round for the change. Blocked(ToolingFailure), + /// A generator needs a build and this step has too little time for one. + OutOfTime, } /// Whether a generator runs through the repository's package scripts (the @@ -1332,7 +1360,12 @@ fn is_script(g: &Generator) -> bool { /// can, and name each one still out of date. Package-script generators run /// through the worker's codegen command (`detect_codegen_command`), once, /// with the repository's public codegen environment (`load_codegen_env`). -async fn regenerate(w: &Work<'_>, attempt: usize, notes: &mut Vec) -> Option { +async fn regenerate( + w: &Work<'_>, + attempt: usize, + notes: &mut Vec, + fresh: Option<&str>, +) -> Option { let (owner, name) = (&w.msg.repo_owner, &w.msg.repo_name); let repo = load(w.github, owner, name, w.branch).await; let gens = detect(&repo); @@ -1349,6 +1382,16 @@ async fn regenerate(w: &Work<'_>, attempt: usize, notes: &mut Vec) -> Op if hits.is_empty() { return Some(Pass::Problems(Vec::new())); } + // The generators already ran with this work (right after the implement + // step) and nothing since touched what they read: verify only. + let verified = match fresh { + Some(at) => w + .github + .compare_changed_files(owner, name, at, w.branch) + .await + .is_ok_and(|since| !hits.iter().any(|(g, _)| reads_any(g, &since))), + None => false, + }; let scripts_cmd = super::detect_codegen_command(w.github, owner, name, w.branch).await; let env = super::load_codegen_env(w.state, &w.msg.team_id, owner, name).await; let hosts = required_hosts(&repo, &env); @@ -1361,6 +1404,13 @@ async fn regenerate(w: &Work<'_>, attempt: usize, notes: &mut Vec) -> Op let mut problems = Vec::new(); for (i, (g, inputs)) in hits.into_iter().enumerate() { let ran = match (&scripts_cmd, is_script(&g)) { + _ if verified => { + notes.push(format!( + "`{}` already ran with this work; nothing it reads changed since", + g.name + )); + continue; + } (Some(cmd), true) => match &shared_run { // The shared run already counted its files. Some(Ran::Regenerated(_)) => Ran::Regenerated(Vec::new()), @@ -1378,6 +1428,7 @@ async fn regenerate(w: &Work<'_>, attempt: usize, notes: &mut Vec) -> Op }; match ran { Ran::Blocked(f) => return Some(Pass::Blocked(f)), + Ran::OutOfTime => return Some(Pass::OutOfTime), Ran::Regenerated(paths) => { if paths.is_empty() { notes.push(format!( @@ -1500,22 +1551,91 @@ async fn record_missing_env(w: &Work<'_>, repo: &str, command: &str, missing: &[ } } -/// Before the pull request: generators whose inputs changed are run and -/// their output committed; one still out of date gets one fix round, then -/// blocks the pull request with a plain reason. Returns notes for the PR's -/// progress, or the reason. +/// Why the generator check didn't let the pull request open. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum GateStop { + /// The change can't open as it is: a plain reason. + Blocked(String), + /// This step has too little time left for the build the check needs: + /// the run continues in a fresh step at this gate. Never a failure. + NeedsTime, +} + +fn stop_of(p: Pass) -> Result, String)>, GateStop> { + match p { + Pass::MissingEnv(why) => Err(GateStop::Blocked(why)), + Pass::Blocked(f) => Err(GateStop::Blocked(f.reason())), + Pass::OutOfTime => Err(GateStop::NeedsTime), + Pass::Problems(p) => Ok(p), + } +} + +/// Whether any of `paths` is an input of `g` (not one of its outputs). +fn reads_any(g: &Generator, paths: &[String]) -> bool { + paths + .iter() + .any(|p| any_match(&g.inputs, p) && !any_match(&g.outputs, p)) +} + +/// What running the generators right after an implement step came to. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum AfterStep { + /// No generator reads what the step changed. + NotNeeded, + /// They ran (output committed when it changed); the branch head after, + /// for the late gate to verify against, and notes for the run page. + Fresh(String, Vec), + /// This step has too little time for the build: the next step runs it + /// first. + OutOfTime, + /// They couldn't settle it here (a failure, a blocked host, missing + /// values): the generator gate deals with it, with its fix round. + Left(Vec), +} + +/// Right after an implement step: when the branch changes files a known +/// generator reads, the worker runs that generator in the sandbox and +/// commits its output. It never depends on the coder calling run_codegen; +/// the generator gate before the pull request then only verifies. +pub async fn after_step(w: &Work<'_>) -> AfterStep { + let mut notes = Vec::new(); + match regenerate(w, 0, &mut notes, None).await { + None => AfterStep::NotNeeded, + Some(Pass::Problems(p)) if p.is_empty() && notes.is_empty() => AfterStep::NotNeeded, + Some(Pass::Problems(p)) if p.is_empty() => { + match w + .github + .get_ref(&w.msg.repo_owner, &w.msg.repo_name, w.branch) + .await + { + Ok(head) => AfterStep::Fresh(head, notes), + Err(_) => AfterStep::Left(notes), + } + } + Some(Pass::OutOfTime) => AfterStep::OutOfTime, + Some(_) => AfterStep::Left(notes), + } +} + +/// Before the pull request: generators whose inputs changed are run (or, +/// when they already ran at `fresh` and nothing they read changed since, +/// verified) and their output committed; one still out of date gets one fix +/// round, then blocks the pull request with a plain reason. Returns notes +/// for the PR's progress, or why it stops: blocked, or this step needs more +/// time (the run then continues in a fresh step at this gate). pub async fn gate( w: &Work<'_>, usage: &mut crate::models::TokenUsage, -) -> Result, String> { + fresh: Option<&str>, +) -> Result, GateStop> { let mut notes = Vec::new(); - let problems = match regenerate(w, 0, &mut notes).await { + let problems = match regenerate(w, 0, &mut notes, fresh).await { None => return Ok(notes), - Some(Pass::MissingEnv(why)) => return Err(why), - Some(Pass::Blocked(f)) => return Err(f.reason()), - Some(Pass::Problems(p)) if p.is_empty() => return Ok(notes), - Some(Pass::Problems(p)) => p, + Some(p) => stop_of(p)?, }; + if problems.is_empty() { + return Ok(notes); + } super::add_progress_note( w.state, &w.msg.team_id, @@ -1554,19 +1674,17 @@ pub async fn gate( warn!(run_id = w.run_id, error = %e, "Generator fix round failed"); } let mut notes2 = Vec::new(); - let still = match regenerate(w, 1, &mut notes2).await { - Some(Pass::MissingEnv(why)) => return Err(why), - Some(Pass::Blocked(f)) => return Err(f.reason()), - Some(Pass::Problems(p)) => p, + let still = match regenerate(w, 1, &mut notes2, None).await { + Some(p) => stop_of(p)?, None => Vec::new(), }; notes.extend(notes2); match still.first() { None => Ok(notes), - Some((g, inputs, why)) => Err(format!( + Some((g, inputs, why)) => Err(GateStop::Blocked(format!( "Stopped before opening a pull request: {}", block_reason(g, inputs, why) - )), + ))), } } @@ -1604,6 +1722,79 @@ mod tests { assert!(!glob_match("*.ts", "src/a.ts")); } + /// A step without time for the build never fails the run: the gate + /// says it needs time (the run continues in a fresh step at this gate), + /// never "couldn't run here (not enough time left)". + #[test] + fn a_gate_without_time_needs_a_step_not_a_failure() { + assert_eq!(stop_of(Pass::OutOfTime), Err(GateStop::NeedsTime)); + assert!(out_of_time("codegen exceeded the time budget", || true)); + assert!(out_of_time( + "not enough time left before the pass deadline to run codegen", + || true + )); + assert!( + out_of_time("snapshot failed", || false), + "no runway left now" + ); + assert!(!out_of_time("snapshot failed", || true)); + // CodeBuild's own timeout is the sandbox's failure, not this step's. + assert!(!out_of_time( + crate::clients::sandbox::CODEGEN_TIMED_OUT, + || true + )); + let src = include_str!("generators.rs"); + let run = &src[src.find("async fn run_in_sandbox(").unwrap()..]; + let run = &run[..run.find("\n}\n").unwrap()]; + assert!(run.contains("return Ran::OutOfTime;")); + assert!(!run.contains("Ran::NotRun(\"not enough time left\"")); + } + + /// The implement work changing a generator's inputs is what makes the + /// worker run it right after the step (`after_step`), and the late gate + /// verifies without a second build when nothing it reads changed since. + #[test] + fn implement_writing_generator_inputs_triggers_the_generator() { + let r = repo( + &[ + ( + "package.json", + r#"{"scripts":{"typegen":"sanity schema extract && sanity typegen generate"}}"#, + ), + ( + "sanity-typegen.json", + r#"{"path":"./src/**/*.{ts,tsx}","schema":"schema.json","generates":"./src/sanity.types.ts"}"#, + ), + ], + &[ + "src/sanity.types.ts", + "studio/schemaTypes/blocks/gallery.ts", + ], + ); + let gens = detect(&r); + let step_wrote = changed(&["studio/schemaTypes/blocks/gallery.ts", "README.md"]); + let hit = affected(&gens, &step_wrote); + assert_eq!( + hit.len(), + 1, + "the step's schema edit triggers the generator" + ); + assert!(reads_any(hit[0].0, &step_wrote)); + // Since the run at the fresh head only the generator's own output + // and files it doesn't read changed: verify only. + assert!(!reads_any( + hit[0].0, + &changed(&["src/sanity.types.ts", "README.md"]) + )); + // A step that touched no input runs nothing. + assert!(affected(&gens, &changed(&["README.md"])).is_empty()); + // The worker runs it itself, not through the coder's run_codegen. + let src = include_str!("generators.rs"); + let after = &src[src.find("pub async fn after_step(").unwrap()..]; + let after = &after[..after.find("\n}\n").unwrap()]; + assert!(after.contains("regenerate(w, 0, &mut notes, None)")); + } + /// The observed case: a CMS schema changed, the typegen script exists, /// the generated types didn't change. #[test] diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index b766964fb..c6879161d 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -769,6 +769,8 @@ pub async fn run( let on_tool: Option> = if let Some(rid) = run_id { let dynamo = state.dynamo.clone(); + let s3 = state.s3.clone(); + let bucket = state.config.bucket_name.clone(); let table = state.config.runs_table_name.clone(); let events_table = state.config.events_table_name.clone(); let team = msg.team_id.clone(); @@ -776,6 +778,8 @@ pub async fn run( Some(Box::new( move |tool_name: &str, duration_ms: u64, input_summary: &str, is_error: bool| { let dynamo = dynamo.clone(); + let s3 = s3.clone(); + let bucket = bucket.clone(); let table = table.clone(); let events_table = events_table.clone(); let team = team.clone(); @@ -794,27 +798,16 @@ pub async fn run( common::truncate_str(&input_summary, 100) ) }; - let entry = aws_sdk_dynamodb::types::AttributeValue::M( - std::collections::HashMap::from([ - ( - "message".to_string(), - aws_sdk_dynamodb::types::AttributeValue::S(msg), - ), - ( - "timestamp".to_string(), - aws_sdk_dynamodb::types::AttributeValue::S(now.clone()), - ), - ]), - ); - let _ = dynamo.update_item() - .table_name(&table) - .key("team_id", aws_sdk_dynamodb::types::AttributeValue::S(team.clone())) - .key("run_id", aws_sdk_dynamodb::types::AttributeValue::S(rid.clone())) - .update_expression("SET progress_notes = list_append(if_not_exists(progress_notes, :empty), :entry), updated_at = :t") - .expression_attribute_values(":entry", aws_sdk_dynamodb::types::AttributeValue::L(vec![entry])) - .expression_attribute_values(":empty", aws_sdk_dynamodb::types::AttributeValue::L(vec![])) - .expression_attribute_values(":t", aws_sdk_dynamodb::types::AttributeValue::S(now.clone())) - .send() + super::run_lists::append_note( + &super::run_lists::Target { + dynamo: &dynamo, + table: &table, + team_id: &team, + run_id: &rid, + archive: Some((&s3, &bucket)), + }, + &msg, + ) .await; // Write detailed tool event to events table for agent log live view diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 5b4b65721..bcd256578 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -10,27 +10,10 @@ const LAMBDA_TIMEOUT_SECS: u64 = 900; /// Minimum seconds remaining before we'll start a new implement cycle. const MIN_TIME_FOR_REMEDIATION_SECS: u64 = 240; // 4 minutes -/// Auto-continuation: a big ticket that times out mid-implement is re-enqueued -/// to continue from its partial (already-committed) branch state, rather than -/// stopping at a partial PR. Hard-bounded two ways so it can NEVER loop: -const MAX_CONTINUATIONS: u32 = 3; -/// ...and a wall-clock backstop across all continuations (survives a bad count). -const MAX_CONTINUATION_WALL_SECS: u64 = 45 * 60; - -/// May a timed-out run be auto-continued? Pure + total so it's unit-tested. -/// False the moment EITHER bound is hit — defense in depth against a runaway. -fn should_auto_continue(continuation: u32, first_attempt_ms: u64, now_ms: u64) -> bool { - if continuation >= MAX_CONTINUATIONS { - return false; - } - if first_attempt_ms > 0 { - let elapsed_secs = now_ms.saturating_sub(first_attempt_ms) / 1000; - if elapsed_secs >= MAX_CONTINUATION_WALL_SECS { - return false; - } - } - true -} +/// Before opening the pull request, at least this much of the step must be +/// left (conflict resolution and the description are model calls); with +/// less, the run continues in a fresh step at the checks before the PR. +const MIN_TIME_FOR_PR_SECS: u64 = 150; /// Other repos of the same owner that an agent tried to read or edit, by the /// paths it passed (`owner/other-repo/path/to/file`): a sign the ticket's @@ -125,20 +108,38 @@ async fn requeue_after_model_error(state: &WorkerState, msg: &TicketMessage, run } } -/// Auto-continue a run that ran out of budget (wall-clock OR step limit) with -/// real partial work already committed to its branch: re-enqueue the ticket to -/// resume from that branch (reusing run_id). Hard-bounded by count AND -/// wall-clock via `should_auto_continue` so it can NEVER loop, and only when a -/// partial checkpoint + ticket queue exist. Returns true iff a continuation was -/// enqueued. Shared by both orchestration death paths (timeout + error arms) so -/// they can't drift. +/// What asking for the next step came to. +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum Handoff { + /// The next step is queued. + Continued, + /// No next step, and why (no work committed, the team's usage limit, + /// the runaway ceiling, or the queue refused it). + Stopped(String), +} + +impl Handoff { + fn continued(&self) -> bool { + matches!(self, Handoff::Continued) + } +} + +/// Continue a run in a fresh step (its own invocation, its own time) from +/// the work already committed to its branch: a NEW queue message for the +/// same run_id, one step on, so every step starts with a receive count of 1 +/// (never a retry of this message, never a timeout redelivery). The run +/// keeps going as long as its steps make progress (checked when the next +/// step starts, see `steps`); only the team's usage limit, a person +/// cancelling and the runaway ceiling stop it here. `why` is what the run +/// page reads ("... continuing in step N"). async fn try_auto_continue( state: &WorkerState, msg: &TicketMessage, run_id: &str, checkpoint: &Option<(String, String, u8)>, continuable_passes: &[&str], -) -> bool { + why: &str, +) -> Handoff { // Gate on the checkpoint's pass IDENTITY, not just on there being a branch. // The wall-clock-timeout arm passes the broad set (any late pass with work // committed is worth resuming); the step-budget arm passes only @@ -147,8 +148,20 @@ async fn try_auto_continue( // checkpoint. Callers own this invariant; don't widen it here. let has_partial = matches!(checkpoint, Some((lp, br, _)) if !br.is_empty() && continuable_passes.contains(&lp.as_str())); - if !has_partial || state.config.ticket_queue_url.is_empty() { - return false; + if !has_partial { + return Handoff::Stopped("no work is committed to continue from".into()); + } + if state.config.ticket_queue_url.is_empty() { + return Handoff::Stopped("no queue to continue on".into()); + } + if let Some(reason) = check_budget_exceeded(state, &msg.team_id).await { + return Handoff::Stopped(reason); + } + if !steps::under_ceiling(msg.continuation) { + return Handoff::Stopped(format!( + "the run reached the safety ceiling of {} steps", + steps::MAX_RUN_STEPS + )); } let now_ms = chrono::Utc::now().timestamp_millis().max(0) as u64; let first_ms = if msg.first_attempt_ms > 0 { @@ -156,39 +169,41 @@ async fn try_auto_continue( } else { now_ms }; - if !should_auto_continue(msg.continuation, first_ms, now_ms) { - return false; - } - let mut cont = msg.clone(); - cont.continuation = msg.continuation + 1; - cont.continuation_run_id = Some(run_id.to_string()); - cont.first_attempt_ms = first_ms; - match serde_json::to_string(&crate::models::WorkerMessage::Ticket(cont)) { - Ok(body) => match state - .sqs - .send_message() - .queue_url(&state.config.ticket_queue_url) - .message_body(body) - .delay_seconds(5) - .send() - .await - { - Ok(_) => { - info!( - run_id, - next_continuation = msg.continuation + 1, - "Ran out of budget with partial work — auto-continuing (bounded)" - ); - true - } - Err(e) => { - warn!(run_id, error = %e, "Continuation enqueue failed — falling back to salvage"); - false - } - }, + let next = steps::next_message(msg, run_id, first_ms); + let step = steps::step_number(next.continuation); + let body = match serde_json::to_string(&crate::models::WorkerMessage::Ticket(next)) { + Ok(b) => b, Err(e) => { - warn!(run_id, error = %e, "Continuation serialize failed — falling back to salvage"); - false + warn!(run_id, error = %e, "Continuation serialize failed"); + return Handoff::Stopped(format!("the next step couldn't be written ({e})")); + } + }; + match state + .sqs + .send_message() + .queue_url(&state.config.ticket_queue_url) + .message_body(body) + .delay_seconds(steps::STEP_DELAY_SECS) + .send() + .await + { + Ok(_) => { + info!(run_id, next_step = step, "Continuing in a fresh step"); + add_progress_note( + state, + &msg.team_id, + run_id, + &format!("{why}: continuing in step {step} with its own time budget"), + ) + .await; + // Last write to the run in this step: the sweep reads a queued + // time after the last update as "a step is waiting". + steps::mark_queued(state, &msg.team_id, run_id, step).await; + Handoff::Continued + } + Err(e) => { + warn!(run_id, error = %e, "Continuation enqueue failed"); + Handoff::Stopped(format!("the next step couldn't be queued ({e})")) } } } @@ -360,9 +375,7 @@ pub(crate) async fn acquire_run_writer_guard( #[cfg(test)] mod continuation_tests { - use super::{ - is_budget_exhausted, should_auto_continue, MAX_CONTINUATIONS, MAX_CONTINUATION_WALL_SECS, - }; + use super::is_budget_exhausted; #[test] fn budget_exhausted_classifies_step_limit() { @@ -379,38 +392,90 @@ mod continuation_tests { assert!(!is_budget_exhausted("GitHub API 404: issue not found")); } - #[test] - fn stops_at_max_count() { - assert!(should_auto_continue(0, 0, 0)); - assert!(should_auto_continue(MAX_CONTINUATIONS - 1, 0, 0)); - assert!(!should_auto_continue(MAX_CONTINUATIONS, 0, 0)); // cap hit - assert!(!should_auto_continue(MAX_CONTINUATIONS + 5, 0, 0)); + fn run_passes_src() -> &'static str { + let src = include_str!("mod.rs"); + let start = src.find("\nasync fn run_passes(").unwrap(); + let end = src.find("\nasync fn hand_off_at(").unwrap(); + &src[start..end] } + /// The generator gate without time for its build hands the run to a + /// fresh step at that gate; the checks and the PR do the same. #[test] - fn stops_past_wall_clock() { - let start = 1_000_000_000u64; - // within budget → allowed - assert!(should_auto_continue(1, start, start + 10 * 60 * 1000)); - // past the wall-clock budget → stopped even though count is fine - let past = start + (MAX_CONTINUATION_WALL_SECS + 60) * 1000; - assert!(!should_auto_continue(1, start, past)); + fn a_gate_that_lacks_time_schedules_a_continuation_at_that_gate() { + let rp = run_passes_src(); + let needs = rp + .find("Err(generators::GateStop::NeedsTime) => {") + .unwrap(); + let after = &rp[needs..needs + 600]; + assert!(after.contains("hand_off_at(")); + assert!(after.contains("steps::Gate::Generators")); + for why in [ + "The proof check found planned work not done", + "The link and redirect check needs a fix round", + "The test-fix check needs a fix round", + "The new-feature check needs a fix round", + "opening the pull request needs more time", + ] { + let at = rp + .find(why) + .unwrap_or_else(|| panic!("no hand-off for: {why}")); + assert!(rp[at - 400..at].contains("steps::Gate::Checks"), "{why}"); + } + assert!(!rp.contains("not enough time left")); + // A hand-off that can't continue says why, never a bare timeout. + let src = include_str!("mod.rs"); + let h = &src[src.find("\nasync fn hand_off_at(").unwrap()..]; + let h = &h[..h.find("\n}\n").unwrap()]; + assert!(h.contains("steps::save_gate(")); + assert!(h.contains("try_auto_continue(")); + assert!(h.contains("couldn't continue in a")); } + /// A continuation resumes at the gate the last step handed off at: the + /// hand-off's checkpoint ("implement") is one a step resumes from + /// without implementing again, and the gate decides which stages run. #[test] - fn count_cap_beats_fresh_clock() { - // Even with a fresh clock, the count cap still stops it. - assert!(!should_auto_continue( - MAX_CONTINUATIONS, - 1_000_000_000, - 1_000_000_000 - )); - } - + fn a_continuation_resumes_at_the_gate() { + let rp = run_passes_src(); + let skip = rp.find("let can_skip_implement").unwrap(); + assert!(rp[skip..skip + 300].contains("\"implement\"")); + assert!(rp.contains("let resume_gate = if can_skip_implement {\n step_state.gate")); + assert!(rp.contains("let coverage = if resume_gate.is_some() {")); + assert!(rp.contains("let run_verify = steps::Gate::Verify.runs_from(resume_gate);")); + assert!(rp.contains("if steps::Gate::Generators.runs_from(resume_gate) {")); + // The security verdict a resumed step skips comes from the carry. + assert!(rp.contains("step_state.carry.clone().filter(|_| !run_verify)")); + // And the worker's own generator run comes before test and security. + let gen = rp.find("generators::after_step(&gen_work)").unwrap(); + let test = rp.find("// --- Adversarial Test").unwrap(); + let sec = rp.find("// --- Security Audit").unwrap(); + assert!(gen < test && test < sec); + } + + /// The team's usage limit stops a run between steps: the next step is + /// never queued once the meter says so (and a queued one is refused by + /// the budget gate every step starts with). #[test] - fn zero_first_attempt_ignores_wall_clock() { - // first_attempt_ms == 0 means "unset" — only the count bounds apply. - assert!(should_auto_continue(0, 0, u64::MAX)); + fn the_usage_limit_stops_a_run_between_steps() { + let src = include_str!("mod.rs"); + let start = src.find("\nasync fn try_auto_continue(").unwrap(); + let body = &src[start..start + src[start..].find("\n}\n").unwrap()]; + let budget = body + .find("check_budget_exceeded(state, &msg.team_id)") + .unwrap(); + let send = body.find(".send_message()").unwrap(); + assert!( + budget < send, + "the usage check comes before the next step is sent" + ); + assert!(body.contains("return Handoff::Stopped(reason);")); + let rp = src.find("\nasync fn run_passes(").unwrap(); + let gate = src[rp..] + .find("check_budget_exceeded(state, &msg.team_id)") + .unwrap(); + let first_pass = src[rp..].find("update_pass(").unwrap(); + assert!(gate < first_pass, "every step starts with the usage check"); } } @@ -768,12 +833,14 @@ pub mod review_verdict; pub mod rewards; pub(crate) mod round; mod run_end; +pub(crate) mod run_lists; mod security; #[cfg(test)] mod selfhost_links; pub mod skill_compat; pub mod skill_suggest; pub mod skills; +pub(crate) mod steps; pub(crate) mod stop_gate; pub mod syntax_check; pub(crate) mod terraform; @@ -934,8 +1001,16 @@ pub async fn orchestrate_ticket( // stays correct even if a future non-implement pass propagates the // same step-limit message — it won't match this checkpoint. let continued = is_budget_exhausted(&err_msg) - && try_auto_continue(state, &msg, &run_id, &checkpoint, &["implement_started"]) - .await; + && try_auto_continue( + state, + &msg, + &run_id, + &checkpoint, + &["implement_started"], + "The coder used this step's turns with work left", + ) + .await + .continued(); // A transient model failure (5xx incl. 520-524, 429, 529, no // response) that outlasted the client's own retries is not the // ticket's fault: the run is sent again later (same run_id), by @@ -1009,18 +1084,20 @@ pub async fn orchestrate_ticket( // from the already-committed partial work (bounded — see helper). A // wall-clock timeout can strand real work in any late pass, so the // full continuable set applies here. - let continued = try_auto_continue( + let handoff = try_auto_continue( state, &msg, &run_id, &checkpoint, &["implement", "implement_started", "security"], + "This step reached its time limit with work left", ) .await; - // Fallback (bounds hit, no queue, or enqueue failed): salvage the - // partial work as a draft PR, else fail. - if !continued { + // Fallback (the usage limit, no work committed, no queue, or the + // enqueue failed): salvage the partial work as a draft PR, else + // fail with why. + if let Handoff::Stopped(why) = handoff { let salvaged = if let Some((ref last_pass, ref branch, _)) = checkpoint { if !branch.is_empty() && matches!( @@ -1056,7 +1133,9 @@ pub async fn orchestrate_ticket( state, &msg, &run_id, - "Run timed out (exceeded execution time limit). The issue may need a narrower scope.", + &format!( + "The step reached its time limit and the run couldn't continue in a fresh step: {why}." + ), &usage, duration, ) @@ -2570,9 +2649,48 @@ async fn run_passes( } }; - // Set when this step's implement pass wrote no file (the run's work may - // still be on the branch from its earlier steps). - let mut step_wrote_nothing = false; + // --- Steps: a run continues while its steps make progress --- + // A step resumes where the last one handed off (a gate after implement, + // when it named one). It first compares where the run stands with + // where the last step started: the head moved or the run reached a + // later gate, or else that step made no progress; two in a row stop the + // run with what was stuck. A redelivery or model retry of this same + // step is not a new step (the mark carries its step number). + let step = steps::step_number(msg.continuation); + let step_state = if same_run { + steps::load(state, &msg.team_id, run_id).await + } else { + steps::StepState::default() + }; + let resume_gate = if can_skip_implement { + step_state.gate + } else { + None + }; + if msg.continuation > 0 && step_state.mark_step != step { + let at = resume_gate + .map(|g| g.as_str().to_string()) + .or_else(|| checkpoint.as_ref().map(|c| c.0.clone())) + .unwrap_or_default(); + let head = github + .get_ref(&msg.repo_owner, &msg.repo_name, &branch_name) + .await + .unwrap_or_default(); + let mark = steps::progress_mark(&head, &at); + let stalled = if head.is_empty() { + 0 + } else { + steps::stalled_after(step_state.mark.as_deref(), &mark, step_state.stalled) + }; + steps::save_mark(state, &msg.team_id, run_id, &mark, stalled, step).await; + if steps::stops_for_stall(stalled) { + let kept = + keep_wip_branch(&github, &msg.repo_owner, &msg.repo_name, &branch_name).await; + close_memory(state, agent_memory.take()).await; + return Err(steps::stall_reason(step, &head, &at, &kept).into()); + } + info!(run_id, step, stalled, at = %at, "Continuing the run in this step"); + } let impl_result = if can_skip_implement { // Resume: reconstruct impl_result from the existing branch diff info!(run_id, branch = %branch_name, "Checkpoint resume: skipping implement pass"); @@ -3931,7 +4049,6 @@ async fn run_passes( // continues). Only a branch with none of the work, and a ticket that // names no file, ever reaches the "add more detail" ending below. if result.files_modified.is_empty() { - step_wrote_nothing = true; let work = plan_coverage::changed_files( &github, &msg.repo_owner, @@ -4138,36 +4255,31 @@ async fn run_passes( check_cancelled(state, &msg.team_id, run_id).await?; let mut impl_result = impl_result; let mut plan_optional: Vec = Vec::new(); - // The branch head before the plan rounds: a step that wrote nothing and - // whose rounds moved nothing made no progress, and another fresh step - // would only repeat it. - let head_before_rounds = if step_wrote_nothing { - github - .get_ref(&msg.repo_owner, &msg.repo_name, &branch_name) - .await - .ok() - } else { + // A step resuming at a gate passed the plan check in an earlier step. + let coverage = if resume_gate.is_some() { + plan_optional = resumed_optional(&github, msg, &plan_result, &branch_name).await; None + } else { + plan_coverage::close_gaps( + &plan_coverage::Work { + state, + msg, + github: &github, + plan: &plan_result, + branch: &branch_name, + rules: &rules, + repo_instructions: &repo_instructions, + provider: &provider, + file_cache: &file_cache, + run_id, + deadline: implement_deadline, + }, + &mut impl_result.evidence, + usage, + || has_time_for_remediation(start), + ) + .await }; - let coverage = plan_coverage::close_gaps( - &plan_coverage::Work { - state, - msg, - github: &github, - plan: &plan_result, - branch: &branch_name, - rules: &rules, - repo_instructions: &repo_instructions, - provider: &provider, - file_cache: &file_cache, - run_id, - deadline: implement_deadline, - }, - &mut impl_result.evidence, - usage, - || has_time_for_remediation(start), - ) - .await; if let Some(cov) = coverage { // Only the tasks the branch did are checked off, so the run page and // a later attempt see the truth. @@ -4208,37 +4320,9 @@ async fn run_passes( plan_optional = plan_coverage::optional_findings(&cov); } plan_coverage::Next::Round | plan_coverage::Next::Unfinished => { - let stalled = match &head_before_rounds { - Some(before) => github - .get_ref(&msg.repo_owner, &msg.repo_name, &branch_name) - .await - .is_ok_and(|now| &now == before), - None => false, - }; - if stalled { - // This step and its rounds changed nothing for the tasks - // left: say which, and why, instead of another step. - save_checkpoint( - state, - &msg.team_id, - run_id, - "implement", - &branch_name, - 0, - usage, - ) - .await; - let kept = - keep_wip_branch(&github, &msg.repo_owner, &msg.repo_name, &branch_name) - .await; - close_memory(state, agent_memory.take()).await; - return Err(plan_coverage::stop_reason_why( - &cov, - &kept, - "the last step changed no file for them", - ) - .into()); - } + // A step whose work and rounds moved nothing is not stopped + // here: the next step sees no progress, and two such steps + // in a row stop the run with what was stuck (see `steps`). // A fresh invocation, with its own time, continues from this // branch (bounded); the continuation is told what's left. save_checkpoint( @@ -4252,23 +4336,24 @@ async fn run_passes( ) .await; let resume_from = Some(("implement_started".to_string(), branch_name.clone(), 0u8)); - if try_auto_continue(state, msg, run_id, &resume_from, &["implement_started"]).await - { - add_progress_note( - state, - &msg.team_id, - run_id, - &format!( - "{} planned task(s) not done yet: continuing in a fresh step with its own time budget", - cov.required_missing().len() - ), - ) - .await; + let handoff = try_auto_continue( + state, + msg, + run_id, + &resume_from, + &["implement_started"], + &format!( + "{} planned task(s) not done yet", + cov.required_missing().len() + ), + ) + .await; + if handoff.continued() { close_memory(state, agent_memory.take()).await; return Ok(()); } - // Out of continuations: stop without a pull request, the - // work kept on a branch a later run won't reset. + // No next step (the usage limit): stop without a pull + // request, the work kept on a branch a later run won't reset. save_checkpoint( state, &msg.team_id, @@ -4287,9 +4372,77 @@ async fn run_passes( } } + // --- After the implement work: generators, test, security --- + // Never started without the time to finish: a fresh step with its own + // budget picks the run up here. + let run_verify = steps::Gate::Verify.runs_from(resume_gate); + if run_verify && !has_time_for_remediation(start) { + close_memory(state, agent_memory.take()).await; + return hand_off_at( + state, + msg, + &github, + run_id, + &branch_name, + steps::Gate::Verify, + None, + "The work is built; its test and security audit need more time than this step has left", + usage, + ) + .await; + } + // The generators whose inputs the work changed run now, by the worker, + // and their output is committed with it: never left to the coder + // calling run_codegen. The generator check later only verifies. + let mut generated_at: Option = None; + if run_verify { + let gen_work = plan_coverage::Work { + state, + msg, + github: &github, + plan: &plan_result, + branch: &branch_name, + rules: &rules, + repo_instructions: &repo_instructions, + provider: &provider, + file_cache: &file_cache, + run_id, + deadline: implement_deadline, + }; + match generators::after_step(&gen_work).await { + generators::AfterStep::NotNeeded => {} + generators::AfterStep::Fresh(head, notes) => { + for n in notes { + add_progress_note(state, &msg.team_id, run_id, &n).await; + } + generated_at = Some(head); + } + generators::AfterStep::Left(notes) => { + for n in notes { + add_progress_note(state, &msg.team_id, run_id, &n).await; + } + } + generators::AfterStep::OutOfTime => { + close_memory(state, agent_memory.take()).await; + return hand_off_at( + state, + msg, + &github, + run_id, + &branch_name, + steps::Gate::Verify, + None, + "The work changed files a code generator reads and this step has too little time left for the generator's build", + usage, + ) + .await; + } + } + } + // --- Adversarial Test (multi-repo path) --- check_cancelled(state, &msg.team_id, run_id).await?; - if has_time_for_remediation(start) { + if run_verify && has_time_for_remediation(start) { update_pass(state, &msg.team_id, run_id, "test").await?; let pass_start = std::time::Instant::now(); let usage_before = usage.clone(); @@ -4354,7 +4507,9 @@ async fn run_passes( usage, &fix_cache, Some(run_id), - None, + // Stops at the step deadline, never relying on the + // invocation being cut off. + implement_deadline, true, // bot-driven test-fix — scoped to the PR ) .await @@ -4364,157 +4519,172 @@ async fn run_passes( } } - // --- Security Audit (before PR — ensures only security-clean code is published) --- - check_cancelled(state, &msg.team_id, run_id).await?; - update_pass(state, &msg.team_id, run_id, "security").await?; - let pass_start = std::time::Instant::now(); - let usage_before = usage.clone(); - let mut security_verdict = security::Verdict::of( - security::run( - state, - msg, - &github, - &plan_result, - &branch_name, - &repo_instructions, - &provider, - usage, - &file_cache, - Some(run_id), - ) - .await, - ); - if let security::Verdict::NotChecked(e) = &security_verdict { - warn!(run_id, error = %e, "Security pass errored: the PR opens as a draft with it under Open items"); - } - write_pass_trace( - state, - &msg.team_id, - run_id, - "security", - pass_start, - &usage_before, - usage, - None, - ) - .await; - save_checkpoint( - state, - &msg.team_id, - run_id, - "security", - &branch_name, - 0, - usage, - ) - .await; - info!( - run_id, - passed = security_verdict.passed(), - "Security audit complete" - ); - add_progress_note( - state, - &msg.team_id, - run_id, - match &security_verdict { - security::Verdict::Passed => "Security audit passed", - security::Verdict::Findings(_) => "Security issues found, fixing", - security::Verdict::NotChecked(_) => { - "The security check couldn't run; the pull request stays a draft with that under Open items" - } - }, - ) - .await; - - // What a security round on the PR is told, when the fix (or the check) - // continues in a fresh invocation after the PR opens. - let mut security_round: Option = None; - if let security::Verdict::NotChecked(why) = &security_verdict { - security_round = Some(security::recheck_feedback(why)); - } - if let security::Verdict::Findings(summary) = security_verdict.clone() { - if !has_time_for_remediation(start) { - // Too little of this invocation is left to fix them here: the fix - // is a round of its own on the pull request, with its own budget, - // and the PR stays a draft with the issues under Open items until - // it's done. Never skipped. - warn!( - run_id, - remaining_secs = remaining_secs(start), - "Security issues found with little time left: the fix continues in a fresh step" - ); - add_progress_note( - state, - &msg.team_id, - run_id, - "Security issues found with too little time left in this step: the fix continues in a fresh step on the pull request, which stays a draft until they're fixed", - ) - .await; - security_round = Some(security::fix_feedback(&summary)); - } else { - info!(run_id, "Security issues found, running remediation cycle"); - check_cancelled(state, &msg.team_id, run_id).await?; - update_pass(state, &msg.team_id, run_id, "implement").await?; - let sec_fix_result = implement::run( + // A step resuming at a later gate has the audit's verdict from the + // step that ran it. + let (security_verdict, security_round) = if let Some(c) = + step_state.carry.clone().filter(|_| !run_verify) + { + (c.security, c.security_round) + } else { + // --- Security Audit (before PR — ensures only security-clean code is published) --- + check_cancelled(state, &msg.team_id, run_id).await?; + update_pass(state, &msg.team_id, run_id, "security").await?; + let pass_start = std::time::Instant::now(); + let usage_before = usage.clone(); + let mut security_verdict = security::Verdict::of( + security::run( state, msg, &github, &plan_result, &branch_name, - &rules, &repo_instructions, - Some(&security::fix_feedback(&summary)), - &effective_complexity, &provider, usage, &file_cache, Some(run_id), - None, - true, // bot-driven security fix — scoped to the PR ) - .await?; - write_conversation_log( + .await, + ); + if let security::Verdict::NotChecked(e) = &security_verdict { + warn!(run_id, error = %e, "Security pass errored: the PR opens as a draft with it under Open items"); + } + write_pass_trace( + state, + &msg.team_id, + run_id, + "security", + pass_start, + &usage_before, + usage, + None, + ) + .await; + save_checkpoint( + state, + &msg.team_id, + run_id, + "security", + &branch_name, + 0, + usage, + ) + .await; + info!( + run_id, + passed = security_verdict.passed(), + "Security audit complete" + ); + add_progress_note( + state, + &msg.team_id, + run_id, + match &security_verdict { + security::Verdict::Passed => "Security audit passed", + security::Verdict::Findings(_) => "Security issues found, fixing", + security::Verdict::NotChecked(_) => { + "The security check couldn't run; the pull request stays a draft with that under Open items" + } + }, + ) + .await; + + // What a security round on the PR is told, when the fix (or the check) + // continues in a fresh invocation after the PR opens. + let mut security_round: Option = None; + if let security::Verdict::NotChecked(why) = &security_verdict { + security_round = Some(security::recheck_feedback(why)); + } + if let security::Verdict::Findings(summary) = security_verdict.clone() { + if !has_time_for_remediation(start) { + // Too little of this invocation is left to fix them here: the fix + // is a round of its own on the pull request, with its own budget, + // and the PR stays a draft with the issues under Open items until + // it's done. Never skipped. + warn!( + run_id, + remaining_secs = remaining_secs(start), + "Security issues found with little time left: the fix continues in a fresh step" + ); + add_progress_note( state, &msg.team_id, run_id, - "security_fix", - &sec_fix_result.conversation_log, + "Security issues found with too little time left in this step: the fix continues in a fresh step on the pull request, which stays a draft until they're fixed", ) .await; - - check_cancelled(state, &msg.team_id, run_id).await?; - update_pass(state, &msg.team_id, run_id, "security").await?; - security_verdict = security::Verdict::of( - security::run( + security_round = Some(security::fix_feedback(&summary)); + } else { + info!(run_id, "Security issues found, running remediation cycle"); + check_cancelled(state, &msg.team_id, run_id).await?; + update_pass(state, &msg.team_id, run_id, "implement").await?; + let sec_fix_result = implement::run( state, msg, &github, &plan_result, &branch_name, + &rules, &repo_instructions, + Some(&security::fix_feedback(&summary)), + &effective_complexity, &provider, usage, &file_cache, Some(run_id), + // Stops at the step deadline, never relying on the + // invocation being cut off. + implement_deadline, + true, // bot-driven security fix — scoped to the PR ) - .await, - ); - if !security_verdict.passed() { - warn!( + .await?; + write_conversation_log( + state, + &msg.team_id, + run_id, + "security_fix", + &sec_fix_result.conversation_log, + ) + .await; + + check_cancelled(state, &msg.team_id, run_id).await?; + update_pass(state, &msg.team_id, run_id, "security").await?; + security_verdict = security::Verdict::of( + security::run( + state, + msg, + &github, + &plan_result, + &branch_name, + &repo_instructions, + &provider, + usage, + &file_cache, + Some(run_id), + ) + .await, + ); + if !security_verdict.passed() { + warn!( run_id, "Security issues remain after remediation (or the re-check didn't run): they go under Open items and the PR stays a draft" ); - } - // A re-check that didn't run runs again on the PR. - if let security::Verdict::NotChecked(why) = &security_verdict { - security_round = Some(security::recheck_feedback(why)); + } + // A re-check that didn't run runs again on the PR. + if let security::Verdict::NotChecked(why) = &security_verdict { + security_round = Some(security::recheck_feedback(why)); + } } } - } + (security_verdict, security_round) + }; // What is still open goes under Open items, marked: the PR stays a draft // while any is listed. let security_items = security::open_items(&security_verdict, security_round.is_some()); + let carry = steps::Carry { + security: security_verdict.clone(), + security_round: security_round.clone(), + }; // Security issues not fixed (or a check that didn't run) are the PR's // Open items, marked so it stays a draft; the full audit text is not @@ -4524,36 +4694,74 @@ async fn run_passes( check_cancelled(state, &msg.team_id, run_id).await?; update_pass(state, &msg.team_id, run_id, "review").await?; // --- Generated files: regenerated with the change, or the PR waits --- - match generators::gate( - &plan_coverage::Work { + if steps::Gate::Generators.runs_from(resume_gate) { + // A redelivery of this step, or the next one, resumes here. + steps::save_gate( state, - msg, - github: &github, - plan: &plan_result, - branch: &branch_name, - rules: &rules, - repo_instructions: &repo_instructions, - provider: &provider, - file_cache: &file_cache, + &msg.team_id, run_id, - deadline: implement_deadline, - }, - usage, - ) - .await - { - Ok(notes) => { - for n in notes { - add_progress_note(state, &msg.team_id, run_id, &n).await; + steps::Gate::Generators, + Some(&carry), + ) + .await; + match generators::gate( + &plan_coverage::Work { + state, + msg, + github: &github, + plan: &plan_result, + branch: &branch_name, + rules: &rules, + repo_instructions: &repo_instructions, + provider: &provider, + file_cache: &file_cache, + run_id, + deadline: implement_deadline, + }, + usage, + generated_at.as_deref(), + ) + .await + { + Ok(notes) => { + for n in notes { + add_progress_note(state, &msg.team_id, run_id, &n).await; + } + } + Err(generators::GateStop::NeedsTime) => { + close_memory(state, agent_memory.take()).await; + return hand_off_at( + state, + msg, + &github, + run_id, + &branch_name, + steps::Gate::Generators, + Some(&carry), + "The generator check needs a sandbox build and this step has too little time left for one", + usage, + ) + .await; + } + Err(generators::GateStop::Blocked(why)) => { + let kept = + keep_wip_branch(&github, &msg.repo_owner, &msg.repo_name, &branch_name).await; + close_memory(state, agent_memory.take()).await; + return Err(format!("{why} The work so far is kept on branch `{kept}`.").into()); } - } - Err(why) => { - let kept = - keep_wip_branch(&github, &msg.repo_owner, &msg.repo_name, &branch_name).await; - close_memory(state, agent_memory.take()).await; - return Err(format!("{why} The work so far is kept on branch `{kept}`.").into()); } } + steps::save_gate( + state, + &msg.team_id, + run_id, + steps::Gate::Checks, + Some(&carry), + ) + .await; + // The checks' "time for a fix round?" answers: one refused for time + // hands the run to a fresh step here instead of blocking the PR. + let budget = steps::step_budget(*start); let mut evidence = impl_result.evidence.clone(); let work = proof::Work { state, @@ -4568,13 +4776,25 @@ async fn run_passes( run_id, deadline: implement_deadline, }; - let mut gaps = proof::prove(&work, &mut evidence, usage, || { - has_time_for_remediation(start) - }) - .await; + let mut gaps = proof::prove(&work, &mut evidence, usage, || budget.has_time()).await; // Planned work the check found not done is never an Open item: the pull // request doesn't open without it. if !proof::planned_work(&gaps).is_empty() { + if budget.take_denied() { + close_memory(state, agent_memory.take()).await; + return hand_off_at( + state, + msg, + &github, + run_id, + &branch_name, + steps::Gate::Checks, + Some(&carry), + "The proof check found planned work not done and this step has too little time left for its fix round", + usage, + ) + .await; + } let kept = keep_wip_branch(&github, &msg.repo_owner, &msg.repo_name, &branch_name).await; close_memory(state, agent_memory.take()).await; return Err(format!( @@ -4603,31 +4823,82 @@ async fn run_passes( gaps.extend(security_items); // Every redirect and link the change adds or changes, checked live; a // failure that survives its fix round stops the run before the PR. - let links = link_checks::gate(&work, &mut evidence, usage, || { - has_time_for_remediation(start) - }) - .await - .map_err(|why| format!("Link and redirect check blocked the pull request: {why}"))?; + budget.take_denied(); + let links = match link_checks::gate(&work, &mut evidence, usage, || budget.has_time()).await { + Ok(l) => l, + Err(_) if budget.take_denied() => { + close_memory(state, agent_memory.take()).await; + return hand_off_at( + state, + msg, + &github, + run_id, + &branch_name, + steps::Gate::Checks, + Some(&carry), + "The link and redirect check needs a fix round and this step has too little time left for it", + usage, + ) + .await; + } + Err(why) => { + return Err(format!("Link and redirect check blocked the pull request: {why}").into()) + } + }; // A failing- or flaky-test fix: no waits without evidence, no helper // that walks every row, test packages checked where they live. - let test_pr = test_fix::gate(&work, &mut evidence, usage, || { - has_time_for_remediation(start) - }) - .await - .map_err(test_fix::blocked_reason)?; + let test_pr = match test_fix::gate(&work, &mut evidence, usage, || budget.has_time()).await { + Ok(t) => t, + Err(_) if budget.take_denied() => { + close_memory(state, agent_memory.take()).await; + return hand_off_at( + state, + msg, + &github, + run_id, + &branch_name, + steps::Gate::Checks, + Some(&carry), + "The test-fix check needs a fix round and this step has too little time left for it", + usage, + ) + .await; + } + Err(e) => return Err(test_fix::blocked_reason(e).into()), + }; // New-feature rules: nothing carried over from an earlier attempt, // every registration, reuse, staging content, the verification // checklist and open product questions (see feature). - let feature_pr = feature::gate( + let feature_pr = match feature::gate( &work, &mut evidence, usage, triage_result.intent, &history.prior, - || has_time_for_remediation(start), + || budget.has_time(), ) .await - .map_err(|why| format!("The new-feature rules blocked the pull request: {why}"))?; + { + Ok(f) => f, + Err(_) if budget.take_denied() => { + close_memory(state, agent_memory.take()).await; + return hand_off_at( + state, + msg, + &github, + run_id, + &branch_name, + steps::Gate::Checks, + Some(&carry), + "The new-feature check needs a fix round and this step has too little time left for it", + usage, + ) + .await; + } + Err(why) => { + return Err(format!("The new-feature rules blocked the pull request: {why}").into()) + } + }; // --- Existing work, again before the PR opens: now that the change's // own files are known, an open pull request (anyone's, opened while @@ -4669,6 +4940,21 @@ async fn run_passes( // --- Create Draft PR (triggers CI) --- check_cancelled(state, &msg.team_id, run_id).await?; + if remaining_secs(start) < MIN_TIME_FOR_PR_SECS { + close_memory(state, agent_memory.take()).await; + return hand_off_at( + state, + msg, + &github, + run_id, + &branch_name, + steps::Gate::Checks, + Some(&carry), + "The checks passed; opening the pull request needs more time than this step has left", + usage, + ) + .await; + } update_pass(state, &msg.team_id, run_id, "pr").await?; // Resolve conflicts with main before PR @@ -4899,6 +5185,64 @@ async fn run_passes( Ok(()) } +/// Continue the run in a fresh step at `gate`, with the branch as it is: +/// the checkpoint names the gate (and what the skipped stages carry), and a +/// new message starts the next step. Only a run that can't continue (the +/// team's usage limit, the runaway ceiling, a queue error) stops here, with +/// that reason. +#[allow(clippy::too_many_arguments)] +async fn hand_off_at( + state: &WorkerState, + msg: &TicketMessage, + github: &GitHubClient, + run_id: &str, + branch: &str, + gate: steps::Gate, + carry: Option<&steps::Carry>, + why: &str, + usage: &TokenUsage, +) -> Result<(), Box> { + save_checkpoint(state, &msg.team_id, run_id, "implement", branch, 0, usage).await; + steps::save_gate(state, &msg.team_id, run_id, gate, carry).await; + let from = Some(("implement".to_string(), branch.to_string(), 0u8)); + match try_auto_continue(state, msg, run_id, &from, &["implement"], why).await { + Handoff::Continued => Ok(()), + Handoff::Stopped(reason) => { + let kept = keep_wip_branch(github, &msg.repo_owner, &msg.repo_name, branch).await; + Err(format!( + "Stopped before opening a pull request: {why}, and the run couldn't continue in a \ + fresh step ({reason}). The work so far is kept on branch `{kept}`." + ) + .into()) + } + } +} + +/// For a step resuming at a gate: the optional tasks the plan check left +/// out, read again from the branch (they go in the PR's Open items). +async fn resumed_optional( + github: &GitHubClient, + msg: &TicketMessage, + plan: &plan::PlanResult, + branch: &str, +) -> Vec { + let tasks = + plan_coverage::tasks_for(github, &msg.repo_owner, &msg.repo_name, branch, &plan.tasks) + .await; + let Some(changed) = plan_coverage::changed_files( + github, + &msg.repo_owner, + &msg.repo_name, + &msg.base_branch, + branch, + ) + .await + else { + return Vec::new(); + }; + plan_coverage::optional_findings(&plan_coverage::coverage(&tasks, &changed)) +} + /// Keeps a branch's commits on `coderhelm-wip/` when a run stops before its /// pull request: a later run of the ticket resets the run branch to its /// base, and the work must survive that. Returns the branch the work is on @@ -5393,6 +5737,7 @@ async fn run_repo_pipeline( deadline: implement_deadline, }, usage, + None, ) .await { @@ -5401,10 +5746,21 @@ async fn run_repo_pipeline( add_progress_note(state, &msg.team_id, run_id, &n).await; } } - Err(why) => { + Err(generators::GateStop::Blocked(why)) => { let kept = keep_wip_branch(github, repo_owner, repo_name, branch_name).await; return Err(format!("{why} The work so far is kept on branch `{kept}`.").into()); } + Err(generators::GateStop::NeedsTime) => { + // A multi-repo run has no fresh steps yet: say exactly that. + let kept = keep_wip_branch(github, repo_owner, repo_name, branch_name).await; + return Err(format!( + "Stopped before opening a pull request in {repo_owner}/{repo_name}: its generator \ + needs a sandbox build and this step has too little time left, and a run across \ + several repositories can't continue in a fresh step yet. The work so far is kept \ + on branch `{kept}`." + ) + .into()); + } } update_pass(state, &msg.team_id, run_id, "review").await?; let mut evidence = impl_result.evidence.clone(); @@ -5755,21 +6111,24 @@ pub(crate) async fn update_pass( ("pass".to_string(), attr_s(pass)), ("started_at".to_string(), attr_s(&now)), ])); - state - .dynamo - .update_item() - .table_name(&state.config.runs_table_name) - .key("team_id", attr_s(team_id)) - .key("run_id", attr_s(run_id)) - .update_expression( - "SET current_pass = :p, updated_at = :t, pass_history = list_append(if_not_exists(pass_history, :empty), :entry)", - ) - .expression_attribute_values(":p", attr_s(pass)) - .expression_attribute_values(":t", attr_s(&now)) - .expression_attribute_values(":entry", aws_sdk_dynamodb::types::AttributeValue::L(vec![entry])) - .expression_attribute_values(":empty", aws_sdk_dynamodb::types::AttributeValue::L(vec![])) - .send() - .await?; + // Bounded: a run of many steps never grows its record past DynamoDB's + // item limit (see run_lists). + run_lists::append( + &run_lists::Target { + dynamo: &state.dynamo, + table: &state.config.runs_table_name, + team_id, + run_id, + archive: None, + }, + "pass_history", + entry, + &now, + run_lists::MAX_PASSES, + run_lists::KEEP_PASSES, + Some(("current_pass = :p", ":p", attr_s(pass))), + ) + .await?; Ok(()) } @@ -6511,25 +6870,17 @@ pub(crate) async fn add_progress_note( run_id: &str, message: &str, ) { - let now = chrono::Utc::now().to_rfc3339(); - let entry = aws_sdk_dynamodb::types::AttributeValue::M(std::collections::HashMap::from([ - ("message".to_string(), attr_s(message)), - ("timestamp".to_string(), attr_s(&now)), - ])); - let _ = state - .dynamo - .update_item() - .table_name(&state.config.runs_table_name) - .key("team_id", attr_s(team_id)) - .key("run_id", attr_s(run_id)) - .update_expression( - "SET progress_notes = list_append(if_not_exists(progress_notes, :empty), :entry), updated_at = :t", - ) - .expression_attribute_values(":entry", aws_sdk_dynamodb::types::AttributeValue::L(vec![entry])) - .expression_attribute_values(":empty", aws_sdk_dynamodb::types::AttributeValue::L(vec![])) - .expression_attribute_values(":t", attr_s(&now)) - .send() - .await; + run_lists::append_note( + &run_lists::Target { + dynamo: &state.dynamo, + table: &state.config.runs_table_name, + team_id, + run_id, + archive: Some((&state.s3, &state.config.bucket_name)), + }, + message, + ) + .await; } /// Write a conversation log to S3 for the agent log viewer. @@ -9425,22 +9776,42 @@ pub(crate) async fn save_checkpoint( let now = chrono::Utc::now().timestamp() as u64; let ttl = now + 7 * 86400; // 7 day TTL + // An update, not a put: the step's progress mark lives on this item + // too (see `steps`). The gate a fresh step resumes at survives only the + // passes it follows (implement, security); any other pass (a new + // implement start, the PR) clears it. + let keeps_gate = matches!(last_pass, "implement" | "security"); + let expr = format!( + "SET last_pass = :lp, branch = :b, review_cycle = :rc, #tin = :ti, \ + #tout = :to, cache_read = :cr, cache_write = :cw, #cost = :c, \ + updated_at = :u, #ttl = :ttl{}", + if keeps_gate { + "" + } else { + " REMOVE gate, gate_carry" + } + ); if let Err(e) = state .dynamo - .put_item() + .update_item() .table_name(&state.config.checkpoints_table_name) - .item("team_id", AttributeValue::S(team_id.to_string())) - .item("sk", AttributeValue::S(format!("RUN#{run_id}"))) - .item("last_pass", AttributeValue::S(last_pass.to_string())) - .item("branch", AttributeValue::S(branch.to_string())) - .item("review_cycle", attr_n(review_cycle as u64)) - .item("tokens_in", attr_n(usage.input_tokens)) - .item("tokens_out", attr_n(usage.output_tokens)) - .item("cache_read", attr_n(usage.cache_read_tokens)) - .item("cache_write", attr_n(usage.cache_write_tokens)) - .item("cost_usd", attr_n(format!("{:.6}", usage.estimated_cost()))) - .item("updated_at", attr_n(now)) - .item("ttl", attr_n(ttl)) + .key("team_id", AttributeValue::S(team_id.to_string())) + .key("sk", AttributeValue::S(format!("RUN#{run_id}"))) + .update_expression(expr) + .expression_attribute_names("#ttl", "ttl") + .expression_attribute_names("#tin", "tokens_in") + .expression_attribute_names("#tout", "tokens_out") + .expression_attribute_names("#cost", "cost_usd") + .expression_attribute_values(":lp", AttributeValue::S(last_pass.to_string())) + .expression_attribute_values(":b", AttributeValue::S(branch.to_string())) + .expression_attribute_values(":rc", attr_n(review_cycle as u64)) + .expression_attribute_values(":ti", attr_n(usage.input_tokens)) + .expression_attribute_values(":to", attr_n(usage.output_tokens)) + .expression_attribute_values(":cr", attr_n(usage.cache_read_tokens)) + .expression_attribute_values(":cw", attr_n(usage.cache_write_tokens)) + .expression_attribute_values(":c", attr_n(format!("{:.6}", usage.estimated_cost()))) + .expression_attribute_values(":u", attr_n(now)) + .expression_attribute_values(":ttl", attr_n(ttl)) .send() .await { diff --git a/services/worker/src/passes/run_lists.rs b/services/worker/src/passes/run_lists.rs new file mode 100644 index 000000000..93cd2cf23 --- /dev/null +++ b/services/worker/src/passes/run_lists.rs @@ -0,0 +1,294 @@ +//! The run record's growing lists stay bounded. +//! +//! A run record is one DynamoDB item, at most 400 KB. Large runs already +//! write 28 to 47 KB with up to ~200 progress notes (every tool call adds +//! one), and a run that keeps going for many steps would pass 400 KB, after +//! which every status write to the run fails. So: +//! +//! - progress notes: an append is conditional on the list holding fewer than +//! [`MAX_NOTES`]; at the limit, the oldest are moved to S3 +//! (`runs///notes/.json`), the item keeps the newest +//! [`KEEP_NOTES`] and counts what moved (`notes_archived`), and the append +//! goes in. Each note's text is at most [`MAX_NOTE_CHARS`]. +//! - pass history: the same, at [`MAX_PASSES`], keeping [`KEEP_PASSES`]; +//! the oldest are dropped (the passes are in the traces too). +//! +//! The normal append costs nothing extra: the condition is checked by +//! DynamoDB on the write itself. + +use aws_sdk_dynamodb::types::AttributeValue; +use std::collections::HashMap; +use tracing::warn; + +/// Notes on the item at most; at this many, the oldest move to S3. +pub const MAX_NOTES: usize = 250; +/// Notes the item keeps after a move. +pub const KEEP_NOTES: usize = 200; +/// A note's text at most, in characters. +pub const MAX_NOTE_CHARS: usize = 1000; +/// Pass history entries at most. +pub const MAX_PASSES: usize = 200; +/// Pass history entries kept after a trim. +pub const KEEP_PASSES: usize = 150; + +/// How many of a list's oldest entries go before one more is appended, so +/// that it then holds `keep`. Zero below `max`. +pub fn to_trim(len: usize, max: usize, keep: usize) -> usize { + if len < max { + 0 + } else { + len + 1 - keep + } +} + +/// A note's text as stored. +pub fn note_text(message: &str) -> String { + common::truncate_str(message, MAX_NOTE_CHARS).to_string() +} + +/// Where a list is bounded and, for notes, archived. +pub struct Target<'a> { + pub dynamo: &'a aws_sdk_dynamodb::Client, + pub table: &'a str, + pub team_id: &'a str, + pub run_id: &'a str, + /// S3 for the notes moved off the item (None: they are dropped). + pub archive: Option<(&'a aws_sdk_s3::Client, &'a str)>, +} + +fn s(v: &str) -> AttributeValue { + AttributeValue::S(v.to_string()) +} + +fn conditional(e: &impl std::fmt::Debug) -> bool { + format!("{e:?}").contains("ConditionalCheckFailed") +} + +/// Append one progress note, keeping the list bounded. +pub async fn append_note(t: &Target<'_>, message: &str) { + let now = chrono::Utc::now().to_rfc3339(); + let entry = AttributeValue::M(HashMap::from([ + ("message".to_string(), s(¬e_text(message))), + ("timestamp".to_string(), s(&now)), + ])); + let _ = append( + t, + "progress_notes", + entry, + &now, + MAX_NOTES, + KEEP_NOTES, + None, + ) + .await; +} + +/// Append to `attr` (with `updated_at`, and any extra SET clause), keeping +/// it under `max` entries. Errors other than the bound are returned. +pub async fn append( + t: &Target<'_>, + attr: &str, + entry: AttributeValue, + now: &str, + max: usize, + keep: usize, + extra: Option<(&str, &str, AttributeValue)>, +) -> Result<(), aws_sdk_dynamodb::Error> { + for attempt in 0..2 { + let mut set = + "SET #l = list_append(if_not_exists(#l, :empty), :entry), updated_at = :t".to_string(); + if let Some((clause, _, _)) = &extra { + set.push_str(", "); + set.push_str(clause); + } + let mut req = t + .dynamo + .update_item() + .table_name(t.table) + .key("team_id", s(t.team_id)) + .key("run_id", s(t.run_id)) + .update_expression(set) + .condition_expression("attribute_not_exists(#l) OR size(#l) < :max") + .expression_attribute_names("#l", attr) + .expression_attribute_values(":entry", AttributeValue::L(vec![entry.clone()])) + .expression_attribute_values(":empty", AttributeValue::L(vec![])) + .expression_attribute_values(":t", s(now)) + .expression_attribute_values(":max", AttributeValue::N(max.to_string())); + if let Some((_, name, value)) = &extra { + req = req.expression_attribute_values(*name, value.clone()); + } + match req.send().await { + Ok(_) => return Ok(()), + Err(e) if conditional(&e) && attempt == 0 => trim(t, attr, max, keep).await, + Err(e) => { + if !conditional(&e) { + return Err(e.into()); + } + warn!( + run_id = t.run_id, + attr, "Run list still at its bound after a trim" + ); + return Ok(()); + } + } + } + Ok(()) +} + +/// Moves the oldest entries off the item (notes to S3), so one more fits +/// under `max` with `keep` on the item. +async fn trim(t: &Target<'_>, attr: &str, max: usize, keep: usize) { + let Ok(out) = t + .dynamo + .get_item() + .table_name(t.table) + .key("team_id", s(t.team_id)) + .key("run_id", s(t.run_id)) + .projection_expression("#l") + .expression_attribute_names("#l", attr) + .send() + .await + else { + return; + }; + let list = out + .item() + .and_then(|i| i.get(attr)) + .and_then(|v| v.as_l().ok()) + .cloned() + .unwrap_or_default(); + let n = to_trim(list.len(), max, keep); + if n == 0 { + return; + } + if let Some((s3, bucket)) = t.archive { + let moved: Vec = list[..n] + .iter() + .filter_map(|v| v.as_m().ok()) + .map(|m| { + serde_json::Value::Object( + m.iter() + .filter_map(|(k, v)| { + v.as_s() + .ok() + .map(|x| (k.clone(), serde_json::Value::String(x.clone()))) + }) + .collect(), + ) + }) + .collect(); + let key = format!( + "runs/{}/{}/notes/{}.json", + t.team_id, + t.run_id, + chrono::Utc::now().timestamp_millis() + ); + let body = serde_json::to_vec(&moved).unwrap_or_default(); + if let Err(e) = s3 + .put_object() + .bucket(bucket) + .key(&key) + .content_type("application/json") + .body(body.into()) + .send() + .await + { + // The item's limit comes first: a note lost beats every + // status write to the run failing. + warn!(run_id = t.run_id, error = %e, "Could not archive old progress notes"); + } + } + let removes: Vec = (0..n).map(|i| format!("#l[{i}]")).collect(); + let mut req = t + .dynamo + .update_item() + .table_name(t.table) + .key("team_id", s(t.team_id)) + .key("run_id", s(t.run_id)) + .expression_attribute_names("#l", attr) + // Only the list this read saw: a concurrent trim already did it. + .condition_expression("size(#l) = :len") + .expression_attribute_values(":len", AttributeValue::N(list.len().to_string())); + let mut expr = format!("REMOVE {}", removes.join(", ")); + if attr == "progress_notes" { + expr.push_str(" ADD notes_archived :n"); + req = req.expression_attribute_values(":n", AttributeValue::N(n.to_string())); + } + if let Err(e) = req.update_expression(expr).send().await { + if !conditional(&e) { + warn!(run_id = t.run_id, attr, error = %e, "Could not trim the run list"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// DynamoDB's size of an item: attribute names plus values, with a few + /// bytes per list and map element. + fn note_bytes(message: &str) -> usize { + "message".len() + message.len() + "timestamp".len() + 32 + 3 + 3 + } + + /// 2,000 notes (every one at the longest a note may be, the worst case) + /// on top of the largest run record seen (47 KB) and a full pass + /// history: the item never reaches DynamoDB's 400 KB. + #[test] + fn two_thousand_notes_keep_the_item_under_the_limit() { + const ITEM_LIMIT: usize = 400 * 1024; + let base = 47 * 1024; + let pass_entry = "pass".len() + 12 + "started_at".len() + 32 + 6; + let passes = MAX_PASSES * pass_entry; + let long = "x".repeat(5000); + let mut notes: Vec = Vec::new(); + let mut archived = 0; + for _ in 0..2000 { + let n = to_trim(notes.len(), MAX_NOTES, KEEP_NOTES); + notes.drain(..n); + archived += n; + notes.push(note_bytes(¬e_text(&long))); + assert!(notes.len() <= MAX_NOTES); + let size = base + passes + notes.iter().sum::() + "notes_archived".len() + 8; + assert!(size < ITEM_LIMIT, "item at {size} bytes"); + } + assert_eq!( + archived + notes.len(), + 2000, + "every note is kept or archived" + ); + } + + #[test] + fn trimming_starts_at_the_bound_and_keeps_the_newest() { + assert_eq!(to_trim(0, MAX_NOTES, KEEP_NOTES), 0); + assert_eq!(to_trim(MAX_NOTES - 1, MAX_NOTES, KEEP_NOTES), 0); + assert_eq!( + to_trim(MAX_NOTES, MAX_NOTES, KEEP_NOTES), + MAX_NOTES + 1 - KEEP_NOTES + ); + assert_eq!( + to_trim(MAX_PASSES, MAX_PASSES, KEEP_PASSES), + MAX_PASSES + 1 - KEEP_PASSES + ); + assert_eq!(note_text(&"y".repeat(5000)).chars().count(), MAX_NOTE_CHARS); + } + + /// Every progress note write goes through the bounded append. + #[test] + fn no_unbounded_note_or_pass_append_is_left() { + for (name, src) in [ + ("mod.rs", include_str!("mod.rs")), + ("implement.rs", include_str!("implement.rs")), + ] { + assert!( + !src.contains("progress_notes = list_append"), + "{name} appends progress notes without the bound" + ); + assert!( + !src.contains("pass_history = list_append"), + "{name} appends pass history without the bound" + ); + } + } +} diff --git a/services/worker/src/passes/steps.rs b/services/worker/src/passes/steps.rs new file mode 100644 index 000000000..7013c80f3 --- /dev/null +++ b/services/worker/src/passes/steps.rs @@ -0,0 +1,531 @@ +//! A ticket run works in steps, and a step's time is never a reason to fail. +//! +//! One worker invocation (a step) has at most 15 minutes. A new-feature run +//! once triaged, planned (with ~6 minutes of plan review), built eight files, +//! and reached the generator check with 30 seconds left: the check declined +//! to start a build and the run failed "not enough time left", with the work +//! done and the generator never run. +//! +//! Now every place that lacks time hands off instead: the run continues in a +//! fresh step (a NEW queue message with its own receive count and its own 15 +//! minutes) that resumes exactly where this one stopped: the implement work, +//! the generator check ([`Gate::Generators`]) or the checks before the pull +//! request ([`Gate::Checks`]), with the branch as it is. +//! +//! A run keeps going as long as its steps make progress ([`stalled_after`]): +//! the branch head moved, or the run reached a later gate. It stops when two +//! steps in a row make none (with what was stuck), when the team's usage +//! limit stops it, or when a person cancels it. [`MAX_RUN_STEPS`] is only a +//! runaway ceiling, never reached by real work. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Instant; + +use aws_sdk_dynamodb::types::AttributeValue; +use tracing::{error, warn}; + +use crate::models::TicketMessage; +use crate::passes::security; +use crate::WorkerState; + +/// A runaway ceiling only: a run whose steps keep making progress is never +/// stopped by a count, but no loop can run forever. Logged loudly when hit. +pub const MAX_RUN_STEPS: u32 = 50; + +/// Steps in a row that make no progress before the run stops. +pub const MAX_STALLED_STEPS: u32 = 2; + +/// Seconds between steps: the next one starts right away (SQS allows up to +/// 900). +pub const STEP_DELAY_SECS: i32 = 5; + +/// The step a message runs: the first invocation is step 1. +pub fn step_number(continuation: u32) -> u32 { + continuation.saturating_add(1) +} + +/// May the step after `continuation` start? Only the runaway ceiling says +/// no; a stalled run is stopped by [`stalled_after`]. +pub fn under_ceiling(continuation: u32) -> bool { + let next = step_number(continuation).saturating_add(1); + if next > MAX_RUN_STEPS { + error!( + next_step = next, + ceiling = MAX_RUN_STEPS, + "RUNAWAY CEILING HIT: a ticket run reached the step ceiling; this never happens in normal work" + ); + return false; + } + true +} + +/// The next step's message: a new message (never a retry of this one), the +/// same run, one step on. SQS counts receives per message, so every step +/// starts at a receive count of 1, however many steps the run takes. +pub fn next_message(msg: &TicketMessage, run_id: &str, first_attempt_ms: u64) -> TicketMessage { + let mut next = msg.clone(); + next.continuation = msg.continuation.saturating_add(1); + next.continuation_run_id = Some(run_id.to_string()); + next.first_attempt_ms = first_attempt_ms; + next +} + +// ── Progress ──────────────────────────────────────────────────────────────── + +/// Where a run stands at the start of a step: its branch head and the point +/// it resumes at. A step made progress when the next step's mark differs: +/// a commit (implement work, a fix round, regenerated files) moves the head, +/// and a gate passed moves the resume point. +pub fn progress_mark(head: &str, at: &str) -> String { + format!("{head}|{at}") +} + +/// Steps in a row without progress, after the step that just ended: zero +/// when its mark moved (or there is no earlier mark), else one more. +pub fn stalled_after(prev: Option<&str>, now: &str, stalled: u32) -> u32 { + match prev { + Some(p) if !p.is_empty() && p == now => stalled.saturating_add(1), + _ => 0, + } +} + +/// Whether a run with this many stalled steps stops. +pub fn stops_for_stall(stalled: u32) -> bool { + stalled >= MAX_STALLED_STEPS +} + +/// Why a stalled run stops, in a sentence. +pub fn stall_reason(step: u32, head: &str, at: &str, kept: &str) -> String { + let short: String = head.chars().take(7).collect(); + format!( + "Stopped: steps {} and {} made no progress. The branch stayed at {short} and the run was \ + stuck at {}. The work so far is kept on branch `{kept}`.", + step.saturating_sub(2).max(1), + step.saturating_sub(1).max(1), + where_label(at) + ) +} + +fn where_label(at: &str) -> &str { + match at { + "verify" => "the test and security audit after the implement work", + "generators" => "the generator check (regenerating generated files)", + "checks" => "the checks before the pull request", + "implement_started" | "implement" => "the implement work (planned tasks)", + "security" => "the security audit", + other => other, + } +} + +// ── Resume points ────────────────────────────────────────────────────────── + +/// A point after implement where a fresh step can pick the run up. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum Gate { + /// Everything after the implement work and its plan check: the + /// generators run with the work, the adversarial test, the security + /// audit, then the gates below. + Verify, + /// The generator check: regenerate, verify, one fix round. + Generators, + /// The proof, link, test-fix and new-feature checks, then the pull + /// request. + Checks, +} + +impl Gate { + pub fn as_str(self) -> &'static str { + match self { + Gate::Verify => "verify", + Gate::Generators => "generators", + Gate::Checks => "checks", + } + } + + pub fn parse(s: &str) -> Option { + match s { + "verify" => Some(Gate::Verify), + "generators" => Some(Gate::Generators), + "checks" => Some(Gate::Checks), + _ => None, + } + } + + /// Whether a run resuming at `resume` runs the stage at `self`. Stages + /// before every gate (plan check, test, security) run only without one. + pub fn runs_from(self, resume: Option) -> bool { + resume.is_none_or(|r| self >= r) + } +} + +/// What a run resuming at a gate needs from the stages it skips: the +/// security verdict (its open items go in the pull request) and the +/// security round parked for after the pull request opens. +#[derive(Debug, Clone, PartialEq)] +pub struct Carry { + pub security: security::Verdict, + pub security_round: Option, +} + +impl Carry { + pub fn to_json(&self) -> String { + let (kind, text) = match &self.security { + security::Verdict::Passed => ("passed", ""), + security::Verdict::Findings(t) => ("findings", t.as_str()), + security::Verdict::NotChecked(t) => ("not_checked", t.as_str()), + }; + serde_json::json!({ + "security": kind, + "text": text, + "round": self.security_round, + }) + .to_string() + } + + pub fn from_json(s: &str) -> Option { + let v: serde_json::Value = serde_json::from_str(s).ok()?; + let text = v["text"].as_str().unwrap_or("").to_string(); + let security = match v["security"].as_str()? { + "passed" => security::Verdict::Passed, + "findings" => security::Verdict::Findings(text), + "not_checked" => security::Verdict::NotChecked(text), + _ => return None, + }; + Some(Carry { + security, + security_round: v["round"].as_str().map(str::to_string), + }) + } +} + +/// What the run's checkpoint says about steps: the gate to resume at (with +/// what it carries), and the progress mark and stalled count of the last +/// step. +#[derive(Debug, Clone, Default)] +pub struct StepState { + pub gate: Option, + pub carry: Option, + pub mark: Option, + /// The step that saved `mark`. + pub mark_step: u32, + pub stalled: u32, +} + +fn key(run_id: &str) -> AttributeValue { + AttributeValue::S(format!("RUN#{run_id}")) +} + +pub async fn load(state: &WorkerState, team_id: &str, run_id: &str) -> StepState { + if state.config.checkpoints_table_name.is_empty() { + return StepState::default(); + } + let Ok(out) = state + .dynamo + .get_item() + .table_name(&state.config.checkpoints_table_name) + .key("team_id", AttributeValue::S(team_id.to_string())) + .key("sk", key(run_id)) + .send() + .await + else { + return StepState::default(); + }; + let Some(item) = out.item() else { + return StepState::default(); + }; + let s = |k: &str| item.get(k).and_then(|v| v.as_s().ok()).cloned(); + StepState { + gate: s("gate").as_deref().and_then(Gate::parse), + carry: s("gate_carry").as_deref().and_then(Carry::from_json), + mark: s("step_mark"), + mark_step: item + .get("step_mark_step") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse().ok()) + .unwrap_or(0), + stalled: item + .get("stalled_steps") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse().ok()) + .unwrap_or(0), + } +} + +/// The run resumes at `gate` in its next step (or after a redelivery). +pub async fn save_gate( + state: &WorkerState, + team_id: &str, + run_id: &str, + gate: Gate, + carry: Option<&Carry>, +) { + if state.config.checkpoints_table_name.is_empty() { + return; + } + if let Err(e) = state + .dynamo + .update_item() + .table_name(&state.config.checkpoints_table_name) + .key("team_id", AttributeValue::S(team_id.to_string())) + .key("sk", key(run_id)) + .update_expression("SET gate = :g, gate_carry = :c") + .expression_attribute_values(":g", AttributeValue::S(gate.as_str().to_string())) + .expression_attribute_values( + ":c", + AttributeValue::S(carry.map(Carry::to_json).unwrap_or_default()), + ) + .send() + .await + { + warn!(run_id, error = %e, "Could not save the gate the run resumes at"); + } +} + +/// This step's progress mark and the stalled count so far. +pub async fn save_mark( + state: &WorkerState, + team_id: &str, + run_id: &str, + mark: &str, + stalled: u32, + step: u32, +) { + if state.config.checkpoints_table_name.is_empty() { + return; + } + if let Err(e) = state + .dynamo + .update_item() + .table_name(&state.config.checkpoints_table_name) + .key("team_id", AttributeValue::S(team_id.to_string())) + .key("sk", key(run_id)) + .update_expression("SET step_mark = :m, stalled_steps = :n, step_mark_step = :s") + .expression_attribute_values(":m", AttributeValue::S(mark.to_string())) + .expression_attribute_values(":s", AttributeValue::N(step.to_string())) + .expression_attribute_values(":n", AttributeValue::N(stalled.to_string())) + .send() + .await + { + warn!(run_id, error = %e, "Could not save the step's progress mark"); + } +} + +/// On the run record: step `step` is queued. The stuck-run sweep leaves a +/// run alone while a step is queued and hasn't started (a full queue can +/// hold it past the sweep's cutoff); the run page shows the step. +pub async fn mark_queued(state: &WorkerState, team_id: &str, run_id: &str, step: u32) { + if let Err(e) = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", AttributeValue::S(team_id.to_string())) + .key("run_id", AttributeValue::S(run_id.to_string())) + .update_expression("SET run_step = :s, step_queued_at = :t") + .expression_attribute_values(":s", AttributeValue::N(step.to_string())) + .expression_attribute_values(":t", AttributeValue::S(chrono::Utc::now().to_rfc3339())) + .send() + .await + { + warn!(run_id, error = %e, "Could not record the queued step on the run"); + } +} + +// ── Time ───────────────────────────────────────────────────────────────── + +/// The "is there time for a fix round" answer the checks get, remembering +/// when it said no: a check that then blocks the pull request blocked it +/// for want of time, and the run continues in a fresh step instead. +pub struct TimeBudget bool> { + has_time: F, + denied: AtomicBool, +} + +impl bool> TimeBudget { + pub fn new(has_time: F) -> Self { + Self { + has_time, + denied: AtomicBool::new(false), + } + } + + pub fn has_time(&self) -> bool { + let ok = (self.has_time)(); + if !ok { + self.denied.store(true, Ordering::SeqCst); + } + ok + } + + /// Whether a round was refused for time since the last call. + pub fn take_denied(&self) -> bool { + self.denied.swap(false, Ordering::SeqCst) + } +} + +/// A time budget over this step's start. +pub fn step_budget(start: Instant) -> TimeBudget bool> { + TimeBudget::new(move || super::has_time_for_remediation(&start)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn progress_keeps_a_run_going_past_the_old_bounds() { + // The old bounds stopped at 3 continuations or 45 minutes. A run + // whose every step moves its branch keeps going at step 20. + let mut stalled = 0; + let mut prev: Option = None; + for step in 1..=20u32 { + let mark = progress_mark(&format!("sha{step}"), "implement_started"); + stalled = stalled_after(prev.as_deref(), &mark, stalled); + assert!(!stops_for_stall(stalled), "step {step} stopped"); + assert!(under_ceiling(step - 1), "ceiling at step {step}"); + prev = Some(mark); + } + // A step that only passes a gate (no commit) is progress too. + let a = progress_mark("same", "generators"); + let b = progress_mark("same", "checks"); + assert_eq!(stalled_after(Some(&a), &b, 1), 0); + } + + #[test] + fn two_stalled_steps_stop_with_what_was_stuck() { + let mark = progress_mark("abcdef1234", "generators"); + let s1 = stalled_after(Some(&mark), &mark, 0); + assert_eq!(s1, 1); + assert!(!stops_for_stall(s1), "one stalled step keeps going"); + let s2 = stalled_after(Some(&mark), &mark, s1); + assert!(stops_for_stall(s2)); + let why = stall_reason(7, "abcdef1234", "generators", "coderhelm-wip/x"); + assert!(why.contains("steps 5 and 6 made no progress"), "{why}"); + assert!(why.contains("abcdef1"), "{why}"); + assert!(why.contains("generator check"), "{why}"); + assert!(why.contains("coderhelm-wip/x"), "{why}"); + } + + #[test] + fn the_first_step_and_a_missing_mark_are_progress() { + assert_eq!(stalled_after(None, "a|b", 5), 0); + assert_eq!(stalled_after(Some(""), "a|b", 5), 0); + } + + #[test] + fn the_ceiling_is_a_runaway_guard_far_above_real_work() { + assert!(under_ceiling(0)); + assert!(under_ceiling(MAX_RUN_STEPS - 2)); + assert!(!under_ceiling(MAX_RUN_STEPS - 1)); + const { assert!(MAX_RUN_STEPS >= 50) }; + } + + #[test] + fn gates_order_the_resume() { + assert!(Gate::Generators.runs_from(None)); + assert!(Gate::Checks.runs_from(Some(Gate::Generators))); + assert!(!Gate::Generators.runs_from(Some(Gate::Checks))); + assert!(Gate::Verify.runs_from(Some(Gate::Verify))); + assert!(!Gate::Verify.runs_from(Some(Gate::Generators))); + for g in [Gate::Verify, Gate::Generators, Gate::Checks] { + assert_eq!(Gate::parse(g.as_str()), Some(g)); + } + } + + #[test] + fn carry_round_trips() { + for c in [ + Carry { + security: security::Verdict::Passed, + security_round: None, + }, + Carry { + security: security::Verdict::Findings("### SQLi\nFile: a.rs".into()), + security_round: Some("fix them".into()), + }, + Carry { + security: security::Verdict::NotChecked("api down".into()), + security_round: Some("recheck".into()), + }, + ] { + assert_eq!(Carry::from_json(&c.to_json()), Some(c)); + } + } + + #[test] + fn a_denied_round_is_remembered_once() { + let b = TimeBudget::new(|| false); + assert!(!b.take_denied()); + assert!(!b.has_time()); + assert!(b.take_denied()); + assert!(!b.take_denied()); + let ok = TimeBudget::new(|| true); + assert!(ok.has_time()); + assert!(!ok.take_denied()); + } + + /// SQS: visibility 960 s, maxReceiveCount 3 to the DLQ. A run of ten + /// steps sends ten new messages; each is received once and deleted (the + /// handler never errors a ticket message back to the queue), so no + /// message comes near the redrive count however long the run. + #[test] + fn a_ten_step_run_never_reuses_a_message() { + const MAX_RECEIVE_COUNT: u32 = 3; + struct Queued { + body: String, + receives: u32, + } + let mut queue: Vec = Vec::new(); + let mut seen: Vec = Vec::new(); + let first = TicketMessage { + team_id: "TEAM#1".into(), + ticket_id: "GH-1".into(), + ..Default::default() + }; + let body = |m: &TicketMessage| { + serde_json::to_string(&crate::models::WorkerMessage::Ticket(m.clone())).unwrap() + }; + queue.push(Queued { + body: body(&first), + receives: 0, + }); + let mut steps = 0; + while let Some(mut q) = queue.pop() { + q.receives += 1; + assert!(q.receives < MAX_RECEIVE_COUNT); + assert!(!seen.contains(&q.body), "a message was re-used"); + seen.push(q.body.clone()); + let msg = match serde_json::from_str(&q.body).unwrap() { + crate::models::WorkerMessage::Ticket(m) => m, + _ => unreachable!(), + }; + steps += 1; + assert_eq!(step_number(msg.continuation), steps); + if steps > 1 { + assert_eq!(msg.continuation_run_id.as_deref(), Some("RUN1")); + } + // The step ends: the next step is a new message; this one is + // deleted (dropped here), never made visible again. + if steps < 10 && under_ceiling(msg.continuation) { + let next = next_message(&msg, "RUN1", 1); + queue.push(Queued { + body: body(&next), + receives: 0, + }); + } + } + assert_eq!(steps, 10); + assert_eq!(seen.len(), 10); + } + + /// Continuations are sent as new messages, never by leaving this one to + /// time out and come back. + #[test] + fn continuations_are_sent_not_redelivered() { + let src = include_str!("mod.rs"); + let start = src.find("\nasync fn try_auto_continue(").unwrap(); + let body = &src[start..start + src[start..].find("\n}\n").unwrap()]; + assert!(body.contains(".send_message()")); + assert!(body.contains("steps::next_message(")); + assert!(!body.contains("change_message_visibility")); + } +}