From a8588499ac7c146611cd02177c124cc0fa2d9a7c Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Thu, 5 Nov 2026 15:17:59 -0500 Subject: [PATCH 1/2] Runs always end: PR before the checks, rounds that survive continuations, and a ceiling on every run --- docs/incidents.md | 2 + infra/lib/monitoring-stack.ts | 9 + lambda/stuck-run-cleanup/handler.py | 121 +- lambda/tests/test_stuck_run_cleanup.py | 77 + services/common/src/messages.rs | 64 + services/common/src/usage.rs | 84 ++ services/gateway/src/routes/analytics.rs | 66 +- services/worker/src/main.rs | 22 +- services/worker/src/models.rs | 4 +- services/worker/src/passes/checks.rs | 6 +- services/worker/src/passes/feature/content.rs | 4 +- services/worker/src/passes/feature/mod.rs | 110 +- services/worker/src/passes/feedback.rs | 7 + services/worker/src/passes/implement.rs | 5 + .../worker/src/passes/incidents/f_steps.rs | 2 +- .../passes/incidents/m_data_pipeline_rules.rs | 5 +- services/worker/src/passes/incidents/mod.rs | 2 + .../passes/incidents/p_finished_work_loop.rs | 648 ++++++++ .../src/passes/incidents/q_run_ceiling.rs | 348 +++++ services/worker/src/passes/link_checks.rs | 45 +- services/worker/src/passes/mod.rs | 1042 ++++++++----- services/worker/src/passes/pr.rs | 153 ++ services/worker/src/passes/proof.rs | 211 ++- services/worker/src/passes/resume.rs | 10 + services/worker/src/passes/run_ceiling.rs | 386 +++++ services/worker/src/passes/run_guard.rs | 1314 +++++++++++++++++ services/worker/src/passes/steps.rs | 79 +- services/worker/src/passes/stop_gate.rs | 11 - services/worker/src/passes/stop_pr.rs | 86 +- services/worker/src/passes/test_fix.rs | 66 +- 30 files changed, 4411 insertions(+), 578 deletions(-) create mode 100644 services/worker/src/passes/incidents/p_finished_work_loop.rs create mode 100644 services/worker/src/passes/incidents/q_run_ceiling.rs create mode 100644 services/worker/src/passes/run_ceiling.rs create mode 100644 services/worker/src/passes/run_guard.rs diff --git a/docs/incidents.md b/docs/incidents.md index 01fde5553..397123934 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -45,6 +45,8 @@ pipeline still calls it there. | m. `m_data_pipeline_rules` | A data-pipeline PR kept one column stable by no longer advancing `updated_at` on some update and upsert paths. Two incremental readers used that timestamp (a `MAX(updated_at)` watermark and a `GREATEST(...)` change key), so edited rows refetched every run and other changes stopped reaching the search index. It also picked a winner among sibling rows with different tie-breaks from the full sync, skipped records without a parent silently, and showed nothing on real data. | The plan check sends back a plan that changes how a cursor column is written without listing its readers, or picks a winner among rows without naming the other path that makes the same choice. Before the pull request, for every ticket kind, the checklist fails a cursor write that can stop advancing, names each reader code search finds that the plan leaves out, wants a test that the column still advances, fails an ordering key that differs from the other path's, wants a test with ties and nulls, and fails a skip over records that is silent or logs per row (one warning per run with the ids, counts in the summary). With a data source connected, the proof check holds a data change until the evidence lists the ticket's records and edge cases before and after, and the description shows them in Verification. | | n. `n_suite_setup_broke` | A review fix round finished every requested change, then ran the full test suite in the sandbox. The suite came from the CI workflow, and its `uses: astral-sh/setup-uv` step was written into the setup as words. The sandbox's `/bin/sh` failed on a "(" (exit 2, no counts), and the round was held as "Full test suite FAILED". The test loop the requester named never ran. | A `uses:` step becomes real shell or is left out with a note, never words. The suite runs under bash after `bash -n`, with its setup and its tests marked apart. A command CoderHelm built that breaks before any test runs (not valid bash, a missing tool, a failed setup, exit 2 within seconds with no counts) is CoderHelm's own failure. The round then tries the requester's command, the repository's instructions, and the simplest test command, in that order. When none runs, the fix lands and the description says plainly that the tests didn't run in the sandbox and why. A command the requester named runs first and is quoted in the result. Tests that ran and failed still hold the fix. | | o. `o_mention_resumes_held_work` | A requester asked for five changes on a PR CoderHelm opened, and for no PR comments. The feedback round did all five, then the sandbox test step broke on CoderHelm's own setup, so the round was held and its WIP branch kept, with nothing about it on the run record. The next day the owner commented a bare `@coderhelm` to get the work landed. A bare mention was the re-review command, so CoderHelm posted a fresh verdict and nothing landed. | Work a round left held or unfinished on CoderHelm's own PR comes first. A held round stays on the run record (its WIP branch, where it started, what it was asked) until it lands, and a WIP branch ahead of the PR counts too. A bare mention resumes that round: the checks run again on the WIP with the current setup, and the work lands, or is fixed and then lands. Words are read by the model, told about the held work: "do it", "redo", "continue" and fix requests run a fix round on the held WIP, and only an ask for a review is a review. The person is told what CoderHelm is doing, on the run and the ticket when the requester asked for no PR comments. | +| p. `p_finished_work_loop` | A small ticket finished its 11 tasks, then spent 2.5 hours and $41.96 with no pull request: each 15-minute step re-ran the checks before the pull request from nothing and started fresh fix rounds. | The draft pull request opens before the proof check, the rules and the review, which then can't block it. A check runs once on a head and keeps its rounds across steps. A run with no real progress (tasks, the pull request, CI green, fewer findings) ends one way: a draft with Open items, waiting on a person. | +| q. `q_run_ceiling` | The same bug had been fixed in one loop at a time. | A run has an absolute ceiling on passes, continuations, worked time and spend that only a person's Retry renews, held at the worker's one entry point, at every model call, and by the stuck-run sweep, each without the others. | ## Adding a case diff --git a/infra/lib/monitoring-stack.ts b/infra/lib/monitoring-stack.ts index 9c1e745aa..6a74ae9cf 100644 --- a/infra/lib/monitoring-stack.ts +++ b/infra/lib/monitoring-stack.ts @@ -146,6 +146,15 @@ export class MonitoringStack extends cdk.Stack { metricName: "ReviewSweepRequeued", metricValue: "1", }).metric({ period: cdk.Duration.minutes(15), statistic: "Sum" }); + // Each run the run guard ended for making no progress (see `run_guard`): + // a run that loops, stopped before it spent more. + new logs.MetricFilter(this, "RunLoopStoppedFilter", { + logGroup: workerLogs, + filterPattern: logs.FilterPattern.literal('"run_loop_stopped"'), + metricNamespace: "CoderHelm/Runs", + metricName: "RunLoopStopped", + metricValue: "1", + }); const modelRequeuedMetric = new logs.MetricFilter(this, "ModelErrorRequeuedFilter", { logGroup: workerLogs, filterPattern: logs.FilterPattern.literal('"model_error_requeued"'), diff --git a/lambda/stuck-run-cleanup/handler.py b/lambda/stuck-run-cleanup/handler.py index 5123592b0..409b80a8f 100644 --- a/lambda/stuck-run-cleanup/handler.py +++ b/lambda/stuck-run-cleanup/handler.py @@ -57,6 +57,15 @@ STEP_QUEUED_FIELD = "step_queued_at" MAX_STEP_QUEUED_HOURS = int(os.environ.get("MAX_STEP_QUEUED_HOURS", "6")) ROUND_SWEEP_GRACE_SECONDS = 300 + +# The absolute ceiling of a run. Mirrors services/worker/src/passes/run_ceiling.rs +# (a test there reads these lines). The worker refuses a run over it at its one +# entry point and at every model call; this reads the same counts from outside +# the worker, so a run still stops if the worker's own checks are broken. +MAX_RUN_PASSES = 300 +MAX_RUN_CONTINUATIONS = 50 +MAX_RUN_WORKED_SECS = 57600 +MAX_RUN_SPEND_USD = 200.0 ROUND_LABELS = { "ci_fix": "CI fix round", "review_fix": "review fix round", @@ -148,6 +157,59 @@ def step_queued(run, now): return now < queued + timedelta(hours=MAX_STEP_QUEUED_HOURS) +def over_ceiling(run): + """(code, what) when the run is over its ceiling, else None.""" + def num(name): + try: + return float(run.get(name) or 0) + except (TypeError, ValueError): + return 0.0 + + if num("ceil_spend_usd") > MAX_RUN_SPEND_USD: + return ("ceiling_spend", f"the limit of ${MAX_RUN_SPEND_USD:.0f} of model use") + if num("ceil_worked_secs") > MAX_RUN_WORKED_SECS: + return ("ceiling_worked_time", f"the limit of {MAX_RUN_WORKED_SECS // 3600} hours of work") + if num("ceil_passes") > MAX_RUN_PASSES: + return ("ceiling_passes", f"the limit of {MAX_RUN_PASSES} steps of work") + if num("ceil_continuations") > MAX_RUN_CONTINUATIONS: + return ("ceiling_continuations", f"the limit of {MAX_RUN_CONTINUATIONS} continuations") + return None + + +def over_ceiling_reason(what, run, branch=""): + """The reason on the run page. The sweep has no GitHub access, so it says + where the work is; pressing Retry starts a new run from it.""" + if has_pull_request(run): + where = f"Everything it did is on its draft pull request ({run.get('pr_url') or run.get('pr_number')})." + elif branch: + where = ( + f"Everything it did is on branch `{branch}`; no pull request opened, so open one " + "from there or press Retry." + ) + else: + where = "No pull request opened." + return f"CoderHelm ended this run: it reached {what}, and nothing further runs on it. {where} Retry starts a new run from there." + + +def over_ceiling_update(run_id, code, reason, now_iso): + """The update that hands a run over its ceiling to a person. `guard_open` + keeps any queued step of it from starting again.""" + return ( + "SET #s = :new, status_run_id = :sri, error_message = :err, current_pass = :cp, " + "updated_at = :now, guard_open = :yes, loop_stop_reason = :code, " + "loop_stop_detail = :err, loop_stopped_at = :now", + { + ":new": "needs_input", + ":sri": f"needs_input#{run_id}", + ":err": reason, + ":cp": "done", + ":now": now_iso, + ":yes": True, + ":code": code, + }, + ) + + def has_pull_request(run): try: number = int(run.get("pr_number") or 0) @@ -221,6 +283,47 @@ def _checkpoint_pass(team_id, run_id): return "" +def _checkpoint_branch(team_id, run_id): + if not CHECKPOINTS_TABLE: + return "" + try: + item = ( + _db() + .Table(CHECKPOINTS_TABLE) + .get_item(Key={"team_id": team_id, "sk": f"RUN#{run_id}"}) + .get("Item") + or {} + ) + return item.get("branch", "") + except Exception as e: # best effort: the reason still says what happened + logger.warning(f"Could not read checkpoint for {run_id}: {e}") + return "" + + +def _hand_off_over_ceiling(runs_table, run, code, what, now): + team_id = run["team_id"] + run_id = run["run_id"] + reason = over_ceiling_reason(what, run, _checkpoint_branch(team_id, run_id)) + update, values = over_ceiling_update(run_id, code, reason, now.isoformat()) + values[":orig"] = run.get("status", "running") + # The metric filter in the monitoring stack counts this text. + logger.warning(f"run_loop_stopped: {run_id} over its ceiling ({code})") + try: + runs_table.update_item( + Key={"team_id": team_id, "run_id": run_id}, + UpdateExpression=update, + ExpressionAttributeNames={"#s": "status"}, + ExpressionAttributeValues=values, + ConditionExpression="#s = :orig", + ) + return True + except _db().meta.client.exceptions.ConditionalCheckFailedException: + logger.info(f"Run {run_id} already resolved (race condition)") + except Exception as e: + logger.error(f"Failed to end {run_id} over its ceiling: {e}") + return False + + def _trace_pass(team_id, run_id): if not TRACES_TABLE: return "" @@ -257,6 +360,7 @@ def handler(event, context): # webhook + lost safety-net resume). The reaper only scanned "running" # before, so awaiting_ci runs sat forever. stuck_runs = [] + over_count = 0 scan_kwargs = { "FilterExpression": "#s = :running OR #s = :awaiting", "ExpressionAttributeNames": {"#s": "status"}, @@ -266,7 +370,7 @@ def handler(event, context): }, "ProjectionExpression": ( "team_id, run_id, created_at, updated_at, title, current_pass, pass_history, #s, " - "step_queued_at, " + "step_queued_at, ceil_passes, ceil_continuations, ceil_worked_secs, ceil_spend_usd, " "#round, pr_number, pr_url" ), } @@ -278,6 +382,13 @@ def handler(event, context): updated = item.get("updated_at", item.get("created_at", "")) status = item.get("status", "") cutoff = running_cutoff if status == "running" else awaiting_cutoff + # First, whatever else is true of the run: its ceiling isn't a + # question of how long ago it last moved. + over = over_ceiling(item) + if over: + if _hand_off_over_ceiling(runs_table, item, over[0], over[1], now): + over_count += 1 + continue if status == "running" and round_in_budget(item, now): # Its fix round is still inside its own budget. continue @@ -293,7 +404,7 @@ def handler(event, context): if not stuck_runs: logger.info("No stuck runs found") - return {"stuck_count": 0} + return {"stuck_count": 0, "over_ceiling": over_count} logger.info(f"Found {len(stuck_runs)} stuck runs") @@ -378,4 +489,8 @@ def handler(event, context): logger.error(f"Failed to unstick {run_id}: {e}") logger.info(f"Unstuck {failed_count}/{len(stuck_runs)} runs") - return {"stuck_count": len(stuck_runs), "unstuck_count": failed_count} + return { + "stuck_count": len(stuck_runs), + "unstuck_count": failed_count, + "over_ceiling": over_count, + } diff --git a/lambda/tests/test_stuck_run_cleanup.py b/lambda/tests/test_stuck_run_cleanup.py index 2454ab0f7..2cff6ad63 100644 --- a/lambda/tests/test_stuck_run_cleanup.py +++ b/lambda/tests/test_stuck_run_cleanup.py @@ -13,6 +13,83 @@ _spec.loader.exec_module(sweep) +class OverCeiling(unittest.TestCase): + def test_under_every_ceiling_is_left_alone(self): + self.assertIsNone(sweep.over_ceiling({})) + self.assertIsNone( + sweep.over_ceiling( + { + "ceil_passes": sweep.MAX_RUN_PASSES, + "ceil_continuations": sweep.MAX_RUN_CONTINUATIONS, + "ceil_worked_secs": sweep.MAX_RUN_WORKED_SECS, + "ceil_spend_usd": sweep.MAX_RUN_SPEND_USD, + } + ) + ) + + def test_each_ceiling_has_its_own_code(self): + for field, value, code in [ + ("ceil_passes", sweep.MAX_RUN_PASSES + 1, "ceiling_passes"), + ("ceil_continuations", sweep.MAX_RUN_CONTINUATIONS + 1, "ceiling_continuations"), + ("ceil_worked_secs", sweep.MAX_RUN_WORKED_SECS + 1, "ceiling_worked_time"), + ("ceil_spend_usd", sweep.MAX_RUN_SPEND_USD + 1, "ceiling_spend"), + ]: + self.assertEqual(sweep.over_ceiling({field: value})[0], code) + + def test_the_reason_notes_the_pull_request_or_the_branch(self): + with_pr = sweep.over_ceiling_reason("the limit", {"pr_url": "https://x/1", "pr_number": 1}) + self.assertIn("https://x/1", with_pr) + no_pr = sweep.over_ceiling_reason("the limit", {}, "coderhelm/x") + self.assertIn("`coderhelm/x`", no_pr) + self.assertIn("Retry", no_pr) + + def test_the_handoff_waits_on_a_person_and_keeps_steps_from_restarting(self): + update, values = sweep.over_ceiling_update("R1", "ceiling_spend", "why", "now") + self.assertEqual(values[":new"], "needs_input") + self.assertEqual(values[":sri"], "needs_input#R1") + self.assertIs(values[":yes"], True) + self.assertIn("guard_open = :yes", update) + self.assertIn("loop_stop_reason = :code", update) + + def test_a_run_over_it_is_ended_whatever_its_last_update_says(self): + import datetime as dt + + now = dt.datetime.now(dt.timezone.utc).isoformat() + run = { + "team_id": "T", + "run_id": "R", + "status": "running", + "updated_at": now, + "ceil_spend_usd": sweep.MAX_RUN_SPEND_USD + 1, + } + updates = [] + + class Table: + def scan(self, **kw): + return {"Items": [run]} + + def update_item(self, **kw): + updates.append(kw) + + class Db: + class meta: + class client: + class exceptions: + ConditionalCheckFailedException = KeyError + + def Table(self, _name): + return Table() + + sweep._dynamodb = Db() + try: + out = sweep.handler({}, None) + finally: + sweep._dynamodb = None + self.assertEqual(out["over_ceiling"], 1) + self.assertEqual(len(updates), 1) + self.assertEqual(updates[0]["ExpressionAttributeValues"][":new"], "needs_input") + + class LastKnownPass(unittest.TestCase): def test_current_pass_wins(self): self.assertEqual(sweep.last_known_pass({"current_pass": "implement"}), "implement") diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index 5dbb42814..6c29517c0 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -400,6 +400,70 @@ impl WorkerMessage { /// Work that runs an agent for one team, as (team, what it is, run id): /// what "Pause all agents" holds back. Sweeps and bookkeeping aren't. + /// The run a message belongs to, for the entry guard (`run_ceiling`): a + /// continuation or retry of a ticket run, a resume, a feedback round. A + /// ticket's first message has no run yet, and a person's Retry starts a new + /// one. No catch-all on purpose: a new message kind doesn't compile until it + /// says which it is. + pub fn run_ref(&self) -> Option<(&str, &str)> { + match self { + WorkerMessage::Ticket(t) => t + .continuation_run_id + .as_deref() + .filter(|r| !r.is_empty() && (t.continuation > 0 || t.model_retries > 0)) + .map(|r| (t.team_id.as_str(), r)), + WorkerMessage::Feedback(m) => Some((m.team_id.as_str(), m.run_id.as_str())), + WorkerMessage::Resume(m) => Some((m.team_id.as_str(), m.run_id.as_str())), + WorkerMessage::ToolProposals(_) + | WorkerMessage::HiddenSuggest(_) + | WorkerMessage::Onboard(_) + | WorkerMessage::MarkReady(_) + | WorkerMessage::PlanExecute(_) + | WorkerMessage::PlanTaskContinue(_) + | WorkerMessage::InfraAnalyze(_) + | WorkerMessage::Review(_) + | WorkerMessage::ReviewReminder + | WorkerMessage::ReviewSweep + | WorkerMessage::HealthCheck(_) + | WorkerMessage::AwaitMerge(_) + | WorkerMessage::ReleaseSteps(_) + | WorkerMessage::RelayRetry(_) + | WorkerMessage::WebhookEmit(_) + | WorkerMessage::WebhookSend(_) + | WorkerMessage::TagSweep(_) + | WorkerMessage::Restack(_) + | WorkerMessage::ReleaseNotes(_) + | WorkerMessage::GraphIndex(_) + | WorkerMessage::TestIngest(_) + | WorkerMessage::TestAction(_) + | WorkerMessage::SkillSync(_) + | WorkerMessage::SkillAsk(_) + | WorkerMessage::DlqCleanup + | WorkerMessage::KnowledgeSyncSweep + | WorkerMessage::KnowledgeSync(_) + | WorkerMessage::WeeklySummary + | WorkerMessage::DeployStatsBackfill(_) + | WorkerMessage::WeeklySummaryTest(_) + | WorkerMessage::UsageReconcile(_) + | WorkerMessage::UsageRecord(_) + | WorkerMessage::Lesson(_) + | WorkerMessage::LogAutofix + | WorkerMessage::AwsPermissionsSweep + | WorkerMessage::ReviewLesson(_) + | WorkerMessage::RewardOutcome(_) + | WorkerMessage::JiraComment(_) + | WorkerMessage::AgentResumeSweep + | WorkerMessage::PluginRun(_) + | WorkerMessage::PluginPublish(_) + | WorkerMessage::PluginSync(_) + | WorkerMessage::PluginSweep + | WorkerMessage::HybridNameCheck + | WorkerMessage::SupportSync + | WorkerMessage::PluginTrigger(_) + | WorkerMessage::PluginResults(_) => None, + } + } + pub fn agent_work(&self) -> Option<(&str, String, String)> { match self { WorkerMessage::Ticket(t) => Some(( diff --git a/services/common/src/usage.rs b/services/common/src/usage.rs index 9b8091881..d8f7675ac 100644 --- a/services/common/src/usage.rs +++ b/services/common/src/usage.rs @@ -77,6 +77,81 @@ tokio::task_local! { } /// Run `fut` with every model call inside it attributed to `feature`. +/// What one message of a run may still spend on model calls. Every call asks +/// it in [`UsageMeter::admit`], so nothing in a run spends past it. +pub struct RunAllowance { + /// Millionths of a dollar left. + left: std::sync::atomic::AtomicI64, + /// Spent since the run guard last looked. + unreported: std::sync::atomic::AtomicU64, + /// Why nothing more may be spent, once something said so. + closed: std::sync::Mutex>, +} + +impl RunAllowance { + pub fn new(left_usd: f64) -> Self { + Self { + left: std::sync::atomic::AtomicI64::new((left_usd.max(0.0) * 1e6).min(9e18) as i64), + unreported: std::sync::atomic::AtomicU64::new(0), + closed: std::sync::Mutex::new(None), + } + } + + fn refused(&self) -> Option { + if let Some(why) = self + .closed + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clone() + { + return Some(why); + } + (self.left.load(std::sync::atomic::Ordering::Relaxed) <= 0) + .then(|| "This run has used all the model spend one run may".to_string()) + } +} + +tokio::task_local! { + static RUN_ALLOWANCE: std::sync::Arc; +} + +/// Runs `fut` with its model calls held to `allowance`. +pub async fn with_run_allowance( + allowance: std::sync::Arc, + fut: F, +) -> F::Output { + RUN_ALLOWANCE.scope(allowance, fut).await +} + +/// A model call's cost, against the current allowance. +pub fn note_run_spend(cost_usd: f64) { + let _ = RUN_ALLOWANCE.try_with(|a| { + let micro = (cost_usd.max(0.0) * 1e6) as u64; + a.left + .fetch_sub(micro as i64, std::sync::atomic::Ordering::Relaxed); + a.unreported + .fetch_add(micro, std::sync::atomic::Ordering::Relaxed); + }); +} + +/// What was spent since this was last asked, in USD. +pub fn take_run_spend() -> f64 { + RUN_ALLOWANCE + .try_with(|a| a.unreported.swap(0, std::sync::atomic::Ordering::Relaxed) as f64 / 1e6) + .unwrap_or(0.0) +} + +/// No more model calls in this message, and why. +pub fn close_run_allowance(why: &str) { + let _ = RUN_ALLOWANCE.try_with(|a| { + *a.closed.lock().unwrap_or_else(|e| e.into_inner()) = Some(why.to_string()); + }); +} + +fn run_allowance_refused() -> Option { + RUN_ALLOWANCE.try_with(|a| a.refused()).ok().flatten() +} + pub async fn with_feature(feature: &'static str, fut: F) -> F::Output { FEATURE.scope(feature, fut).await } @@ -973,6 +1048,15 @@ impl UsageMeter { /// flight when the limit was crossed. A meter with no team (setup /// probes, tests) and a process with no check set are never limited. pub async fn admit(&self) -> Result<(), crate::model_retry::ModelCallError> { + // A run over its ceiling makes no more calls, whatever the team's + // limit says and whoever is calling (see worker `run_ceiling`). + if let Some(reason) = run_allowance_refused() { + warn!(%reason, "Model call refused: the run is over its ceiling"); + return Err(crate::model_retry::ModelCallError::new( + crate::model_retry::ModelErrorKind::LimitReached, + reason, + )); + } if self.team_id.is_empty() { return Ok(()); } diff --git a/services/gateway/src/routes/analytics.rs b/services/gateway/src/routes/analytics.rs index 108fecb55..65f326a87 100644 --- a/services/gateway/src/routes/analytics.rs +++ b/services/gateway/src/routes/analytics.rs @@ -115,6 +115,9 @@ pub struct RunRow { pub last_pass: String, /// Why Coderhelm left a red PR to a person (worker `GaveUp`). pub ci_end: String, + /// Why the run guard ended this run (worker `run_guard::Trip`), empty + /// when it never did. + pub loop_stop_reason: String, /// Failing checks that also failed on the base branch. pub ci_red_on_base: Vec, /// Times the failed jobs of a head were re-run instead of fixed. @@ -163,6 +166,7 @@ impl RunRow { current_pass: s(i, "current_pass"), last_pass: last_history_pass(i), ci_end: s(i, "ci_end"), + loop_stop_reason: s(i, "loop_stop_reason"), ci_red_on_base: list_s(i, "ci_red_on_base"), ci_reruns: n(i, "ci_reruns") as u64, ci_flaky: b(i, "ci_flaky").unwrap_or(false), @@ -601,6 +605,38 @@ pub fn ci_outcomes(runs: &[&RunRow]) -> Value { }) } +/// What a stored `loop_stop_reason` means, for a person. +fn loop_stop_label(code: &str) -> String { + match code { + "continuations_after_work" => "Kept continuing after its tasks were done".into(), + "continuations" => "Kept continuing without finishing a task".into(), + "pass_transitions" => "Kept moving between steps without progress".into(), + "spend" => "Spent too much without progress".into(), + "ceiling_passes" => "Reached a run's limit of steps".into(), + "ceiling_continuations" => "Reached a run's limit of continuations".into(), + "ceiling_worked_time" => "Reached a run's limit of time".into(), + "ceiling_spend" => "Reached a run's limit of spend".into(), + other => other.replace('_', " "), + } +} + +/// The runs the run guard ended, by why, most common first. +pub fn loops_stopped(runs: &[&RunRow]) -> Value { + let mut reasons: BTreeMap = BTreeMap::new(); + for r in runs.iter().filter(|r| !r.loop_stop_reason.is_empty()) { + *reasons + .entry(loop_stop_label(&r.loop_stop_reason)) + .or_default() += 1; + } + let total: usize = reasons.values().sum(); + let mut reasons: Vec = reasons + .into_iter() + .map(|(reason, count)| json!({"reason": reason, "count": count})) + .collect(); + reasons.sort_by(|a, b| b["count"].as_u64().cmp(&a["count"].as_u64())); + json!({"total": total, "reasons": reasons}) +} + /// One row per pull request among `runs`: a rerun that pushed to the same PR /// does not open another. The row kept knows the most: a merged one first, /// then the latest run. @@ -1408,6 +1444,7 @@ pub fn build( "people": people, "failures": failures, "ci": ci, + "loops_stopped": loops_stopped(&cur_runs), "reviews": reviews_json, "lookups": lookups_json, "steps": steps, @@ -1446,7 +1483,7 @@ async fn load_runs(state: &AppState, team: &str, w: Window) -> Result = runs.iter().collect(); + let out = loops_stopped(&refs); + assert_eq!(out["total"], 3); + assert_eq!( + out["reasons"][0]["reason"], + "Kept continuing after its tasks were done" + ); + assert_eq!(out["reasons"][0]["count"], 2); + assert_eq!( + out["reasons"][1]["reason"], + "Spent too much without progress" + ); + assert_eq!(loops_stopped(&[])["total"], 0); + } + #[test] fn ci_outcomes_place_every_red_run_and_keep_base_failures_apart() { let red = |id: &str, status: &str| RunRow { diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 388ad886f..addb8cd93 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -198,6 +198,13 @@ async fn handle_sqs(state: Arc, event: LambdaEvent) -> Re info!(call_id = %rec.call_id, team_id = %rec.team_id, ?added, "Recovered model usage"); continue; } + // The one entry point: a run over its absolute ceiling doesn't run, + // whatever sent this. Before the pause hold and any dispatch. + if !passes::run_ceiling::admit(&passes::run_ceiling::DynamoGate { state: &state }, &message) + .await + { + continue; + } // "Pause all agents": agent work for a paused team is kept exactly as // it came and sent again when the pause ends. Nothing is dropped. let work = message @@ -216,9 +223,14 @@ async fn handle_sqs(state: Arc, event: LambdaEvent) -> Re // Every model call made while handling this message is counted under // the message's feature (spawned tasks fall back to "other"). let feature = message.usage_feature(); + let ceiling_ref = serde_json::from_value::(raw.clone())?; let (_, stopped) = agent::policy::watch_stops(common::usage::with_feature( feature, - handle_message(Arc::clone(&state), message), + passes::run_ceiling::worked( + &state, + &ceiling_ref, + handle_message(Arc::clone(&state), message), + ), )) .await; // A loop stopped because agents were paused mid-run: keep the work @@ -312,6 +324,10 @@ async fn handle_message(state: Arc, message: models::WorkerMessage) let run_id = msg.run_id.clone(); let retry_msg = msg.clone(); if let Err(e) = passes::feedback::run(&state, msg).await { + // The run guard fired: it waits on a person, one way. + if passes::run_guard::settle_open_pr(&state, &team_id, &run_id).await { + return; + } // A transient model failure is sent again later by the one // requeue policy; only a real failure marks the run failed. let err: &(dyn std::error::Error + 'static) = &*e; @@ -454,6 +470,10 @@ async fn handle_message(state: Arc, message: models::WorkerMessage) let (team_id, run_id) = (msg.team_id.clone(), msg.run_id.clone()); if let Err(e) = passes::resume::run(&state, msg).await { error!("Resume failed: {e:?}"); + // The run guard fired: it waits on a person, one way. + if passes::run_guard::settle_open_pr(&state, &team_id, &run_id).await { + return; + } // A round this resume claimed (the run is "running") ends // here: with its pull request open, the run says the round // didn't finish instead of waiting for the sweep to fail it. diff --git a/services/worker/src/models.rs b/services/worker/src/models.rs index 67876413b..8194b9474 100644 --- a/services/worker/src/models.rs +++ b/services/worker/src/models.rs @@ -223,7 +223,9 @@ impl TokenUsage { self.cache_read_tokens += call.cache_read; self.cache_write_tokens += call.cache_write(); self.cache_write_1h_tokens += call.cache_write_1h; - self.cost_usd += call.cost_usd(model_id); + let cost = call.cost_usd(model_id); + self.cost_usd += cost; + common::usage::note_run_spend(cost); } /// Add another usage's tokens and cost (tool calls are not merged). diff --git a/services/worker/src/passes/checks.rs b/services/worker/src/passes/checks.rs index 136174113..e2e3356dc 100644 --- a/services/worker/src/passes/checks.rs +++ b/services/worker/src/passes/checks.rs @@ -17,7 +17,9 @@ use serde_yaml::Value; /// A kind of check a repository's CI runs on a pull request. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +#[derive( + Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize, +)] pub enum CheckKind { /// A type-check, or a validation of the same role (`terraform validate`). Typecheck, @@ -612,7 +614,7 @@ pub struct Workflow { } /// One check command CI runs on a pull request, as the workflow writes it. -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] pub struct CiCommand { /// Its id in this run (`C1`): the judge names it, code checks it exists. pub id: String, diff --git a/services/worker/src/passes/feature/content.rs b/services/worker/src/passes/feature/content.rs index 76e1510af..328f3d235 100644 --- a/services/worker/src/passes/feature/content.rs +++ b/services/worker/src/passes/feature/content.rs @@ -572,7 +572,7 @@ pub fn mutations(n: &Need, ids: &[String]) -> Vec { /// Content CoderHelm couldn't change itself: what, why, and how to grant /// it the access so it can next time. -#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Blocked { pub what: String, pub why_person: String, @@ -622,7 +622,7 @@ fn editors_choice(n: &Need) -> (String, String) { } /// What happened to the staging content, for the description. -#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Outcome { /// What was changed on staging, one line each. pub changed: Vec, diff --git a/services/worker/src/passes/feature/mod.rs b/services/worker/src/passes/feature/mod.rs index 00a35be7a..2b6e6de3a 100644 --- a/services/worker/src/passes/feature/mod.rs +++ b/services/worker/src/passes/feature/mod.rs @@ -56,8 +56,8 @@ use crate::passes::plan::PlanResult; use crate::passes::triage::TicketIntent; use crate::WorkerState; -/// Fix rounds the gate gives before it blocks or reports. -const MAX_FIX_ROUNDS: u32 = 1; +/// Fix rounds the gate gives a run before it reports what is left. +const MAX_FIX_ROUNDS: u32 = super::run_guard::MAX_RULES_FIX_ROUNDS; /// What the planner is told, by the ticket's kind. pub fn planner_block(intent: TicketIntent) -> String { @@ -145,7 +145,7 @@ pub async fn find_attempts( } /// What the gate found, for the description and the ready check. -#[derive(Debug, Clone, Default, PartialEq)] +#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)] pub struct PrFacts { pub attempts: Vec, pub sibling: Option, @@ -861,12 +861,36 @@ pub(crate) async fn load_connection( } } -/// The check before the pull request opens. Problems get one fix round: -/// carried-over commits and missing registrations that survive it block the -/// pull request, and so does staging content that must change and can't be -/// changed here; duplicates and checklist failures go in the description -/// (the checklist keeps the pull request a draft). `Ok(None)` when nothing -/// here applies to the run. +/// What the rules left failing, as Open items. The checklist already keeps +/// the pull request a draft until it passes (`ready_hold`), so these only say +/// what is open. +pub fn open_findings(f: &PrFacts) -> Vec { + checklist::failing(&f.checklist) + .into_iter() + .chain( + f.sandbox_failed + .iter() + .filter(|l| !l.starts_with("Output:")) + .cloned(), + ) + .map(|detail| super::proof::Finding { + point: "rule_failing".to_string(), + detail, + settle: "Fix it on this branch; the pull request stays a draft until the rules pass." + .to_string(), + ..Default::default() + }) + .collect() +} + +/// The check on the open pull request. Problems get up to two fix rounds in a +/// run, and a round with no fewer problems ends them. What survives comes back +/// as an error (carried-over commits, missing registrations, staging content +/// that must change and can't be changed here) or in the facts (duplicates, +/// checklist failures), and the run lists it under Open items: the pull request +/// is already open, and stays a draft. It runs once on a head: when the code +/// hasn't changed since, its result stands. `Ok(None)` when nothing here applies +/// to the run. pub async fn gate( w: &super::proof::Work<'_>, evidence: &mut super::proof::RunEvidence, @@ -874,6 +898,42 @@ pub async fn gate( intent: TicketIntent, found: &prior::Found, has_time: impl Fn() -> bool, +) -> Result, String> { + let head = w.head().await; + let standing = w.ledger.update(|l| { + if !l.rules.unchanged(&head) { + return None; + } + l.rules.reused(); + l.rules_outcome.clone() + }); + if let Some(standing) = standing { + super::add_progress_note( + w.state, + &w.msg.team_id, + w.run_id, + "New-feature rules: the code hasn't changed since the last check, so that result stands", + ) + .await; + return standing; + } + let outcome = check_and_fix(w, evidence, usage, intent, found, has_time).await; + let head = w.head().await; + w.ledger.update(|l| { + l.rules.head = head; + l.rules_outcome = Some(outcome.clone()); + }); + w.save_ledger().await; + outcome +} + +async fn check_and_fix( + w: &super::proof::Work<'_>, + evidence: &mut super::proof::RunEvidence, + usage: &mut TokenUsage, + intent: TicketIntent, + found: &prior::Found, + has_time: impl Fn() -> bool, ) -> Result, String> { let feature = intent == TicketIntent::Feature; let (owner, repo, base) = (&w.msg.repo_owner, &w.msg.repo_name, &w.msg.base_branch); @@ -893,7 +953,6 @@ pub async fn gate( .map(|f| f.path) .collect(); let sibling = reuse::recorded_sibling(&w.plan.design); - let mut rounds = 0; let mut facts = PrFacts { attempts: found.pr_lines(), sibling: sibling.clone().filter(|_| feature), @@ -989,8 +1048,8 @@ pub async fn gate( duplicates = dups.len(), checklist_fails = static_fails.len(), sandbox_fails = sandbox_failed.len(), - rounds, - "New-feature rules checked before the pull request" + rounds = w.ledger.update(|l| l.rules.rounds), + "New-feature rules checked on the pull request" ); // A data migration released expand then contract, with a fallback // and its test (every ticket kind). @@ -1001,7 +1060,15 @@ pub async fn gate( && dups.is_empty() && static_fails.is_empty() && sandbox_failed.is_empty(); - if clean || rounds >= MAX_FIX_ROUNDS || !has_time() { + let open = release_gaps.len() + + carried.len() + + missing.len() + + dups.len() + + static_fails.len() + + sandbox_failed.len(); + w.report_findings("rules", open).await; + w.ledger.update(|l| l.rules.checked(&head, open)); + if clean || !w.ledger.update(|l| l.rules.may_fix(MAX_FIX_ROUNDS)) || !has_time() { if !release_gaps.is_empty() { return Err(format!( "the migration can't be released safely yet: {}", @@ -1074,7 +1141,8 @@ pub async fn gate( .await; return Ok((!facts.is_empty()).then_some(facts)); } - rounds += 1; + w.ledger.update(|l| l.rules.start_fix()); + w.save_ledger().await; let mut feedback = String::new(); if !release_gaps.is_empty() { feedback.push_str("\nThe migration must be released expand then contract:\n"); @@ -1117,7 +1185,7 @@ pub async fn gate( ) .await; let _ = super::update_pass(w.state, &w.msg.team_id, w.run_id, "implement").await; - match super::implement::run( + let fixed = super::implement::run( w.state, w.msg, w.github, @@ -1131,16 +1199,20 @@ pub async fn gate( usage, w.file_cache, Some(w.run_id), - None, + // A round stops at the step's deadline: left open-ended, it ran + // until the time limit cut the whole step off. + w.deadline, // Registrations and test maps live outside the diff. false, ) - .await - { + .await; + w.ledger.update(|l| l.rules.end_fix()); + w.save_ledger().await; + match fixed { Ok(r) => evidence.merge(r.evidence), Err(e) => return Err(format!("the fix round failed: {e}")), } - let _ = super::update_pass(w.state, &w.msg.team_id, w.run_id, "review").await; + let _ = super::update_pass(w.state, &w.msg.team_id, w.run_id, super::PASS_CHECKS).await; } } diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index 78360559a..0168c83ec 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -463,6 +463,13 @@ pub async fn run( hand_off_to_human(state, &github, &msg).await; return Ok(()); } + // A person asked for this: the run guard's counts start over. A cycle only + // CI asked for is a pass like any other, and the guard can stop it. + if comments.is_empty() && msg.review_body.trim().is_empty() { + super::run_guard::on_pass(state, &msg.team_id, &msg.run_id).await?; + } else { + super::run_guard::person_acted(state, &msg.team_id, &msg.run_id).await; + } let formatted = format_review_comments(&msg.review_body, &comments); diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index d90bd98b1..0bbe35769 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -155,6 +155,11 @@ pub async fn run( // parameter also carries human review comments). scope_to_pr: bool, ) -> Result> { + // Every code-writing round goes through here, so a run the guard stopped + // writes nothing more, whoever asked. + if let Some(run_id) = run_id { + super::run_guard::check(state, &msg.team_id, run_id).await?; + } let rules_block = super::format_rules_block(rules); // Trim repo instructions for simple issues to reduce per-turn token cost let trimmed_instructions = if complexity == "simple" && repo_instructions.len() > 2000 { diff --git a/services/worker/src/passes/incidents/f_steps.rs b/services/worker/src/passes/incidents/f_steps.rs index f58338025..2fda8903c 100644 --- a/services/worker/src/passes/incidents/f_steps.rs +++ b/services/worker/src/passes/incidents/f_steps.rs @@ -123,7 +123,7 @@ fn every_gate_that_lacks_time_hands_off_at_that_gate() { let pr = rp .find("opening the pull request needs more time than this step has left") .unwrap(); - assert!(rp[pr - 400..pr].contains("steps::Gate::Checks")); + assert!(rp[pr - 400..pr].contains("steps::Gate::Pr")); assert!(!rp.contains(OLD)); // A hand-off is a new message on the queue, never a retry of this one. let src = include_str!("../mod.rs"); diff --git a/services/worker/src/passes/incidents/m_data_pipeline_rules.rs b/services/worker/src/passes/incidents/m_data_pipeline_rules.rs index cf238f352..3a7eb2777 100644 --- a/services/worker/src/passes/incidents/m_data_pipeline_rules.rs +++ b/services/worker/src/passes/incidents/m_data_pipeline_rules.rs @@ -207,7 +207,10 @@ fn the_proof_check_holds_a_data_change_until_it_is_shown_on_real_data() { fn every_stage_carries_the_data_rules() { // The gate reads them for every ticket kind, before the feature-only // checks. - let gate = fn_src(include_str!("../feature/mod.rs"), "\npub async fn gate("); + let gate = fn_src( + include_str!("../feature/mod.rs"), + "\nasync fn check_and_fix(", + ); let at = gate .find("data_facts(w, &files, &tree)") .expect("gate reads the data rules"); diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index 5a54309e5..e05ae4e62 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -30,3 +30,5 @@ mod l_plan_time; mod m_data_pipeline_rules; mod n_suite_setup_broke; mod o_mention_resumes_held_work; +mod p_finished_work_loop; +mod q_run_ceiling; diff --git a/services/worker/src/passes/incidents/p_finished_work_loop.rs b/services/worker/src/passes/incidents/p_finished_work_loop.rs new file mode 100644 index 000000000..ff5999289 --- /dev/null +++ b/services/worker/src/passes/incidents/p_finished_work_loop.rs @@ -0,0 +1,648 @@ +//! p. A small ticket finished all 11 tasks, then spent 2.5 hours and $41.96 +//! with no pull request. Each 15-minute step resumed at the checks before the +//! pull request and re-ran them from nothing. Their round counters were locals, +//! so every step got new rounds; every fix was a commit, so the stall detector +//! saw progress; and the pull request came last, with whatever time was left. +//! +//! Guarantee: the draft pull request opens as soon as the work is built, before +//! the checks, which then can't hold it back. A check runs once on a head and +//! keeps its rounds for the whole run. And whatever any pass does, a run with no +//! real progress ends one way: a draft with its Open items, waiting on a person. + +use crate::passes::proof::{self, Finding, Next}; +use crate::passes::run_guard::*; +use crate::passes::steps::Gate; + +/// What that run cost, and the steps it took. +const INCIDENT_USD: f64 = 41.96; +const INCIDENT_CONTINUATIONS: usize = 11; + +fn gaps(n: usize) -> Vec { + (0..n) + .map(|i| Finding { + point: "assumption".into(), + detail: format!("gap {i}"), + ..Default::default() + }) + .collect() +} + +/// The run's recorded shape: every step `plan, implement, review, implement, +/// review`, every second one with `pr` after it, and the proof check's count in +/// each going 2, 4, 3, 1 and round again. The spend per step is the run's total +/// over its steps: only the total was recorded. +struct Replayed { + /// Where the guard stopped it, if it did. + trip: Option, + continuations: usize, + passes: usize, + usd: f64, +} + +fn replay(work_done: bool) -> Replayed { + let per_step = INCIDENT_USD / (INCIDENT_CONTINUATIONS as f64); + let counts = [2, 4, 3, 1]; + let mut g = GuardState::default(); + if work_done { + g.apply(&Progress::TasksDone(11)); + g.apply(&Progress::WorkDone); + } + let (mut passes, mut usd) = (0, 0.0); + for step in 0..INCIDENT_CONTINUATIONS { + let mut seq = vec!["plan", "implement", "review", "implement", "review"]; + if step % 2 == 1 { + seq.push("pr"); + } + let per_pass = per_step / seq.len() as f64; + for pass in &seq { + g.on_pass(per_pass); + passes += 1; + usd += per_pass; + if *pass == "review" { + g.apply(&Progress::Findings("proof", counts[step % counts.len()])); + } + if let Some(trip) = g.trip() { + return Replayed { + trip: Some(trip), + continuations: step, + passes, + usd, + }; + } + } + g.on_continuation(0.0); + if let Some(trip) = g.trip() { + return Replayed { + trip: Some(trip), + continuations: step + 1, + passes, + usd, + }; + } + } + Replayed { + trip: None, + continuations: INCIDENT_CONTINUATIONS, + passes, + usd, + } +} + +/// With nothing else changed, the guard alone stops that run at its fourth +/// continuation: 22 passes and about $15.26, 36% of what it spent. +#[test] +fn the_recorded_run_stops_at_its_fourth_continuation() { + let r = replay(true); + assert_eq!(r.trip, Some(Trip::ContinuationsAfterWork)); + assert_eq!(r.continuations, 4); + assert_eq!(r.passes, 22); + assert!((r.usd - 15.26).abs() < 0.01, "{}", r.usd); + assert!(r.usd < INCIDENT_USD / 2.0); +} + +/// Even if the run never reported its tasks done, it doesn't go the distance. +#[test] +fn the_recorded_run_stops_without_any_word_that_its_tasks_are_done() { + let r = replay(false); + assert!(r.trip.is_some()); + // The count of 1 is a new low and counts once. The spend since then stops it + // at $20, in the ninth step, at about $33.57 in all. + assert_eq!(r.trip, Some(Trip::Spend)); + assert_eq!(r.continuations, 8); + assert!((r.usd - 33.57).abs() < 0.01, "{}", r.usd); + assert!(r.usd < INCIDENT_USD, "{}", r.usd); +} + +/// The spend counts by itself: a run that burns money in few passes and never +/// continues stops at the limit, and no pass or continuation brings it down. +#[test] +fn spend_alone_stops_a_run_well_before_that_runs_total() { + let mut g = GuardState::default(); + g.apply(&Progress::WorkDone); + g.apply(&Progress::PrOpen); + g.apply(&Progress::Findings("proof", 3)); + let mut usd = 0.0; + while g.trip().is_none() { + g.on_pass(1.0); + usd += 1.0; + assert!(!g.apply(&Progress::Findings("proof", 3))); + assert!(!g.apply(&Progress::WorkDone)); + assert!(!g.apply(&Progress::PrOpen)); + assert!(usd < INCIDENT_USD); + } + assert_eq!(g.trip(), Some(Trip::Spend)); + assert!(usd <= MAX_SPEND_WITHOUT_PROGRESS_USD + 1.0); +} + +/// Across every continuation of that shape the proof check takes its two +/// rounds at most, stored across steps as it really is, and a head it has seen +/// is never judged again. +#[test] +fn a_continuation_does_not_reset_the_rounds_or_recheck_a_head() { + let mut stored = Ledger::default().to_json_bounded(); + let mut judged = 0; + let mut rounds_run = 0; + let counts = [2, 4, 3, 1]; + // A fix that changes nothing leaves the head where it is. + let mut head = 1; + for step in 0..INCIDENT_CONTINUATIONS { + let mut l: Ledger = serde_json::from_str(&stored).unwrap(); + l.on_step_start(); + let at = format!("sha{head}"); + let open = counts[step % counts.len()]; + if l.proof.unchanged(&at) { + l.proof.reused(); + } else { + judged += 1; + l.proof.checked(&at, open); + } + if l.proof.may_fix(MAX_PROOF_FIX_ROUNDS) && l.proof.open > 0 { + l.proof.start_fix(); + rounds_run += 1; + head += 1; + l.proof.end_fix(); + } + stored = l.to_json_bounded(); + } + let l: Ledger = serde_json::from_str(&stored).unwrap(); + assert!(rounds_run <= MAX_PROOF_FIX_ROUNDS); + assert_eq!(l.proof.rounds, rounds_run); + assert!(judged <= rounds_run as usize + 1, "judged {judged}"); +} + +/// The counts 2, 4: the round made things worse, and the fixing stops there. +#[test] +fn no_progress_between_rounds_stops_the_fixing_at_once() { + let mut r = CheckRecord::default(); + r.checked("a", 2); + assert!(r.may_fix(MAX_PROOF_FIX_ROUNDS)); + r.start_fix(); + r.end_fix(); + r.checked("b", 4); + assert!(!r.may_fix(MAX_PROOF_FIX_ROUNDS)); + // What was found is still reported: the gaps go under Open items. + let found = gaps(4); + assert_eq!( + proof::next(Some(&found), r.rounds, r.may_fix(MAX_PROOF_FIX_ROUNDS)), + Next::OpenWithGaps + ); + let open = proof::gaps_section(&found); + for i in 0..4 { + assert!(open.contains(&format!("gap {i}")), "{open}"); + } +} + +/// A step cut off in a fix round: the next one fixes nothing more. +#[test] +fn time_running_out_during_fixes_leaves_only_the_description_to_do() { + let mut l = Ledger { + opened: Some(OpenedPr { + number: 7, + ..Default::default() + }), + ..Default::default() + }; + l.rules.checked("a", 1); + l.rules.start_fix(); + let mut next: Ledger = serde_json::from_str(&l.to_json_bounded()).unwrap(); + next.on_step_start(); + assert_eq!(next.opened.as_ref().unwrap().number, 7, "no second PR"); + assert!(!next.rules.may_fix(MAX_RULES_FIX_ROUNDS)); + assert!(!next.proof.may_fix(MAX_PROOF_FIX_ROUNDS)); + // The rounds don't start again in the step after that either. + let mut after: Ledger = serde_json::from_str(&next.to_json_bounded()).unwrap(); + after.on_step_start(); + assert!(!after.rules.may_fix(MAX_RULES_FIX_ROUNDS)); +} + +fn fn_of<'a>(src: &'a str, start: &str, end: &str) -> &'a str { + let at = src.find(start).unwrap_or_else(|| panic!("no {start}")); + let rest = &src[at..]; + &rest[..rest.find(end).unwrap_or_else(|| panic!("no {end}"))] +} + +/// The order: the pull request, then every check, on both paths. The checks' +/// errors become Open items, never the run's error. +#[test] +fn the_pull_request_opens_before_every_check() { + let src = include_str!("../mod.rs"); + let single = fn_of(src, "\nasync fn run_passes(", "\nasync fn record_open_pr("); + let multi = fn_of( + src, + "\nasync fn run_repo_pipeline(", + "\nasync fn resume_run_to_running(", + ); + for (name, body) in [("single", single), ("multi", multi)] { + let pr = body + .find("pr::run(\n") + .unwrap_or_else(|| panic!("{name}: no pr::run")); + for check in [ + "proof::prove(", + "link_checks::gate(", + "test_fix::gate(", + "pr::apply_checks(", + ] { + let at = body + .find(check) + .unwrap_or_else(|| panic!("{name}: no {check}")); + assert!(pr < at, "{name}: {check} runs before the PR"); + } + assert!(!body.contains("blocked the pull request"), "{name}"); + assert!( + body.contains("proof::blocked_item(\"The link and redirect check\""), + "{name}" + ); + assert!( + body.contains("proof::blocked_item(\"The failing-test rules\""), + "{name}" + ); + } + let rules = single.find("feature::gate(").unwrap(); + assert!(single.find("pr::run(\n").unwrap() < rules); + assert!(single.contains("proof::blocked_item(\"The new-feature rules\"")); + // A resume after the pull request never opens or describes it again. + assert!(single.contains("let pr_result = if let Some(o) = opened {")); + assert!(multi.contains("let pr_result = if let Some(o) = already_open {")); + // Gates only go forward: the PR, then the checks. + assert!(Gate::Pr < Gate::Checks); + assert!(Gate::Generators < Gate::Pr); +} + +/// Every check keeps its result by head, and an open-ended fix round is gone. +#[test] +fn every_check_runs_once_on_a_head_and_stops_at_the_deadline() { + for (name, src) in [ + ("links", include_str!("../link_checks.rs")), + ("test_fix", include_str!("../test_fix.rs")), + ("rules", include_str!("../feature/mod.rs")), + ] { + let gate = fn_of(src, "\npub async fn gate(", "\nasync fn check_and_fix("); + assert!(gate.contains(".unchanged(&head)"), "{name}"); + assert!(gate.contains("return standing;"), "{name}"); + assert!(src.contains("start_fix()"), "{name}"); + assert!(src.contains("w.deadline,"), "{name}"); + assert!(src.contains("end_fix()"), "{name}"); + } + let proof_src = include_str!("../proof.rs"); + let prove = fn_of(proof_src, "\npub async fn prove(", "\n#[cfg(test)]"); + assert!(prove.contains("l.proof.unchanged(&head)")); + assert!(prove.contains("start_fix()")); + // Nothing counts rounds in a local any more. + for (name, src) in [ + ("proof", proof_src), + ("links", include_str!("../link_checks.rs")), + ("test_fix", include_str!("../test_fix.rs")), + ("rules", include_str!("../feature/mod.rs")), + ] { + assert!(!src.contains("let mut rounds = 0;"), "{name}"); + } +} + +/// Everything goes through the guard: every pass, every continuation, every +/// code-writing round, and a queued step of a stopped run doesn't start. +#[test] +fn every_pass_continuation_and_round_goes_through_the_guard() { + let src = include_str!("../mod.rs"); + let up = fn_of( + src, + "\npub(crate) async fn update_pass(", + "\n/// Why Coderhelm stopped", + ); + assert!(up.contains("run_guard::on_pass(")); + let cont = fn_of( + src, + "\nasync fn try_auto_continue(", + "\n/// Hard, signature-INDEPENDENT", + ); + assert!( + cont.find("run_guard::on_continuation(").unwrap() < cont.find(".send_message()").unwrap() + ); + let imp = fn_of( + include_str!("../implement.rs"), + "\npub async fn run(", + "let rules_block", + ); + assert!(imp.contains("run_guard::check(")); + let back = fn_of( + src, + "\nasync fn resume_run_to_running(", + "\n/// The reason a run that panicked", + ); + assert!(back.contains("attribute_not_exists(guard_open)")); + // Both ways a ticket step ends go to the one ending. + let orch = fn_of( + src, + "\npub async fn orchestrate_ticket(", + "\nfn run_origin_agent(", + ); + assert_eq!(orch.matches("run_guard::end_if_stopped(").count(), 2); + // So do a resume's and a feedback round's. + let main = include_str!("../../main.rs"); + assert_eq!(main.matches("run_guard::settle_open_pr(").count(), 2); + assert_eq!(main.matches("run_ceiling::worked(").count(), 1); +} + +/// One row: a checker that finds something forever, in the passes it really +/// uses. `Rounds(n)` is held by the run ledger or an existing durable cap, and +/// the run ends when they are spent; otherwise only the guard stops it. +#[derive(Clone, Copy)] +enum Bound { + Rounds(u32), + GuardOnly, +} + +struct Checker { + name: &'static str, + /// The file the loop lives in, and what proves it is covered there. + source: &'static str, + covered_by: &'static str, + /// It runs before the pull request exists. + before_pr: bool, + passes: &'static [&'static str], + usd_per_cycle: f64, + /// A cycle ends with a continuation. + continues: bool, + bound: Bound, +} + +fn checkers() -> Vec { + let fix = &["implement", "review"][..]; + vec![ + Checker { + name: "proof check", + source: include_str!("../proof.rs"), + covered_by: "update_pass(", + before_pr: false, + passes: fix, + usd_per_cycle: 4.0, + continues: true, + bound: Bound::Rounds(MAX_PROOF_FIX_ROUNDS), + }, + Checker { + name: "new-feature rules", + source: include_str!("../feature/mod.rs"), + covered_by: "update_pass(", + before_pr: false, + passes: fix, + usd_per_cycle: 4.0, + continues: true, + bound: Bound::Rounds(MAX_RULES_FIX_ROUNDS), + }, + Checker { + name: "link and redirect check", + source: include_str!("../link_checks.rs"), + covered_by: "update_pass(", + before_pr: false, + passes: fix, + usd_per_cycle: 3.0, + continues: true, + bound: Bound::Rounds(MAX_LINK_FIX_ROUNDS), + }, + Checker { + name: "failing-test rules", + source: include_str!("../test_fix.rs"), + covered_by: "update_pass(", + before_pr: false, + passes: fix, + usd_per_cycle: 4.0, + continues: true, + bound: Bound::Rounds(MAX_TEST_FIX_ROUNDS), + }, + Checker { + name: "plan check, tasks never done", + source: include_str!("../plan_coverage.rs"), + covered_by: "update_pass(", + before_pr: true, + passes: &["implement"], + usd_per_cycle: 4.0, + continues: true, + bound: Bound::GuardOnly, + }, + Checker { + name: "generator check", + source: include_str!("../generators.rs"), + covered_by: "update_pass(", + before_pr: true, + passes: &["implement"], + usd_per_cycle: 2.0, + continues: true, + bound: Bound::GuardOnly, + }, + Checker { + name: "test and security audit", + source: include_str!("../mod.rs"), + covered_by: "update_pass(state, &msg.team_id, run_id, \"security\")", + before_pr: true, + passes: &["test", "implement", "security"], + usd_per_cycle: 4.0, + continues: true, + bound: Bound::GuardOnly, + }, + Checker { + name: "CI fix loop", + source: include_str!("../resume.rs"), + covered_by: "claim_auto_fix_slot(", + before_pr: false, + passes: fix, + usd_per_cycle: 2.0, + continues: false, + bound: Bound::Rounds(crate::passes::MAX_AUTO_FIX_PUSHES), + }, + Checker { + name: "feedback, CI only", + source: include_str!("../feedback.rs"), + covered_by: "run_guard::on_pass(", + before_pr: false, + passes: fix, + usd_per_cycle: 2.0, + continues: false, + bound: Bound::Rounds(crate::passes::MAX_AUTO_FIX_PUSHES), + }, + Checker { + name: "own review", + source: include_str!("../own_review.rs"), + covered_by: "MAX_FIX_ROUNDS", + before_pr: false, + passes: fix, + usd_per_cycle: 3.0, + continues: false, + bound: Bound::Rounds(crate::passes::own_review::MAX_FIX_ROUNDS), + }, + Checker { + name: "conflict round", + source: include_str!("../resume.rs"), + covered_by: "\"conflict_fix\"", + before_pr: false, + passes: &["conflict_fix", "review"], + usd_per_cycle: 1.0, + continues: false, + bound: Bound::GuardOnly, + }, + Checker { + name: "planned work rounds", + source: include_str!("../resume.rs"), + covered_by: "update_pass(state, &msg.team_id, &msg.run_id, \"implement\")", + before_pr: false, + passes: fix, + usd_per_cycle: 4.0, + continues: false, + bound: Bound::GuardOnly, + }, + // What a pass nobody has written yet gets, only from `update_pass`. + Checker { + name: "a pass added later", + source: include_str!("../mod.rs"), + covered_by: "run_guard::on_pass(", + before_pr: false, + passes: &["some_new_pass"], + usd_per_cycle: 0.5, + continues: false, + bound: Bound::GuardOnly, + }, + ] +} + +/// How a simulated run ended. +#[derive(Debug, Default)] +struct End { + draft_prs: u32, + waiting_on_a_person: bool, + cycles: u32, + usd: f64, +} + +/// A run whose work is done (unless the checker holds it there) and whose +/// checker finds the same thing forever, driven through the real guard. +fn run_forever(c: &Checker) -> End { + let mut g = GuardState::default(); + let mut end = End::default(); + let mut ledger = Ledger::default(); + // One draft, however the run reaches it: opening is idempotent per branch. + let open = |end: &mut End, ledger: &mut Ledger| { + if ledger.opened.is_none() { + ledger.opened = Some(OpenedPr { + number: 7, + ..Default::default() + }); + end.draft_prs += 1; + } + }; + if !c.before_pr { + g.apply(&Progress::TasksDone(11)); + g.apply(&Progress::WorkDone); + open(&mut end, &mut ledger); + g.apply(&Progress::PrOpen); + } + g.apply(&Progress::Findings("checker", 5)); + for cycle in 0..1000 { + if let Bound::Rounds(max) = c.bound { + if cycle >= max { + // Its cap ended the fixing: the run goes on with the draft open + // and the findings listed. Nothing more is spent on this. + open(&mut end, &mut ledger); + return end; + } + } + end.cycles += 1; + for _ in c.passes { + g.on_pass(c.usd_per_cycle / c.passes.len() as f64); + assert!(!g.apply(&Progress::Findings("checker", 5))); + if g.trip().is_some() { + break; + } + } + end.usd += c.usd_per_cycle; + if g.trip().is_none() && c.continues { + g.on_continuation(0.0); + } + if g.trip().is_some() { + // The one ending. + open(&mut end, &mut ledger); + end.waiting_on_a_person = true; + return end; + } + } + panic!("{}: it never ended", c.name); +} + +#[test] +fn a_checker_that_finds_something_forever_ends_with_one_draft_within_the_limits() { + let table = checkers(); + assert!(table.len() >= 13); + for c in &table { + assert!(c.source.contains(c.covered_by), "{}: not covered", c.name); + let end = run_forever(c); + assert_eq!(end.draft_prs, 1, "{}: {end:?}", c.name); + assert!( + end.usd <= MAX_SPEND_WITHOUT_PROGRESS_USD + c.usd_per_cycle, + "{}: spent {}", + c.name, + end.usd + ); + assert!(end.usd < INCIDENT_USD, "{}", c.name); + match c.bound { + // Stopped by the guard: it says so and waits. + Bound::GuardOnly => assert!(end.waiting_on_a_person, "{}: {end:?}", c.name), + Bound::Rounds(max) => assert!(end.cycles <= max, "{}: {end:?}", c.name), + } + } +} + +/// A big ticket's normal run, with every fix round allowed, doesn't trip it. +#[test] +fn a_normal_large_ticket_never_trips_the_guard() { + let mut g = GuardState::default(); + let step = 3.5; + // Triage and plan, then 30 tasks over eight steps of building. + g.on_pass(1.0); + g.on_pass(2.0); + for s in 1..=8 { + g.on_pass(step); + assert!(g.apply(&Progress::TasksDone(s * 30 / 8))); + assert_eq!(g.trip(), None, "building, step {s}"); + g.on_continuation(0.0); + assert_eq!(g.trip(), None, "continuing, step {s}"); + } + g.apply(&Progress::WorkDone); + // Everything before the pull request, in a step that runs out of time. + for _ in 0..worst_normal_run().min(7) { + g.on_pass(0.5); + assert_eq!(g.trip(), None); + } + g.on_continuation(0.0); + assert_eq!(g.trip(), None); + assert!(g.apply(&Progress::PrOpen)); + // Every round of every check, each one fixing something, over two steps. + g.apply(&Progress::Findings("proof", 6)); + for open in [4, 2] { + g.on_pass(1.5); + g.on_pass(0.2); + assert!(g.apply(&Progress::Findings("proof", open))); + } + g.on_continuation(0.0); + assert_eq!(g.trip(), None); + // Every automatic push CI is allowed, no green until the last. + for push in 0..crate::passes::MAX_AUTO_FIX_PUSHES { + g.on_pass(1.5); + g.on_pass(0.2); + assert_eq!(g.trip(), None, "push {push}"); + } + assert!(g.apply(&Progress::CiGreen)); + // The own review's rounds, one fix after the other. + for round in 0..crate::passes::own_review::MAX_FIX_ROUNDS { + g.on_pass(2.0); + g.on_pass(0.2); + assert_eq!(g.trip(), None, "round {round}"); + } +} + +#[test] +fn the_steps_are_ended_by_a_reason_a_person_can_act_on() { + let r = replay(true); + let g = GuardState { + after_work: r.continuations as u32, + ..Default::default() + }; + let why = r.trip.unwrap().reason(&g); + assert!(why.contains("handed it to you"), "{why}"); +} diff --git a/services/worker/src/passes/incidents/q_run_ceiling.rs b/services/worker/src/passes/incidents/q_run_ceiling.rs new file mode 100644 index 000000000..daa9d4f5f --- /dev/null +++ b/services/worker/src/passes/incidents/q_run_ceiling.rs @@ -0,0 +1,348 @@ +//! q. The owner's requirement: a run cannot loop without end, in layers that +//! don't depend on each other. An adversarial checker that always sends the run +//! back, under every kind of run message and every pass, ends within the ceiling +//! through the real entry guard, and with any one layer removed the others still +//! end it. With all removed it doesn't end: the test has teeth. + +use std::cell::RefCell; +use std::sync::Arc; + +use common::messages::WorkerMessage; +use common::usage::RunAllowance; + +use crate::models::{ResumeMessage, TicketMessage}; +use crate::passes::run_ceiling::*; + +const TEAM: &str = "TEAM#1"; +const RUN: &str = "RUN1"; + +/// Every pass the worker records, and one nobody has written yet. +const PASSES: &[&str] = &[ + "triage", + "plan", + "implement", + "test", + "security", + "pr", + "review", + "feedback", + "conflict_fix", + "ci_fix", + "a_pass_added_later", +]; + +/// Every kind of message that belongs to a run. +fn run_messages() -> Vec<(&'static str, WorkerMessage)> { + let ticket = TicketMessage { + team_id: TEAM.into(), + ticket_id: "GH-1".into(), + continuation: 1, + continuation_run_id: Some(RUN.into()), + ..Default::default() + }; + let resume = ResumeMessage { + team_id: TEAM.into(), + run_id: RUN.into(), + installation_id: 1, + model_retries: 0, + }; + let feedback: WorkerMessage = serde_json::from_value(serde_json::json!({ + "type": "feedback", + "team_id": TEAM, + "run_id": RUN, + "installation_id": 1, + "pr_number": 7, + "repo_owner": "a", + "repo_name": "b", + "branch": "c", + "review_id": 0, + "comments": [], + "review_body": "", + })) + .expect("a feedback message"); + vec![ + ("continuation", WorkerMessage::Ticket(ticket)), + ("resume", WorkerMessage::Resume(resume)), + ("feedback", feedback), + ] +} + +/// Which layers are in place, to take each away in turn. +#[derive(Clone, Copy)] +struct Layers { + entry: bool, + model: bool, + sweep: bool, +} + +const ALL: Layers = Layers { + entry: true, + model: true, + sweep: true, +}; + +/// The run record, in memory, behind the real `EntryGate`. +#[derive(Default)] +struct Record { + totals: RefCell, + ended_by_entry: RefCell, +} + +impl EntryGate for Record { + async fn totals(&self, team_id: &str, run_id: &str) -> Option { + assert_eq!((team_id, run_id), (TEAM, RUN)); + Some(self.totals.borrow().clone()) + } + async fn end_over(&self, _message: &WorkerMessage, _over: Over) { + *self.ended_by_entry.borrow_mut() += 1; + } +} + +#[derive(Debug, PartialEq)] +enum Ended { + Entry, + ModelRefused, + Sweep, + Never, +} + +/// A message goes through the real entry guard, and the adversarial checker +/// always sends the run back: one pass, one continuation, a step's spend and +/// time, then the same message again. +async fn adversary(message: &WorkerMessage, pass: &str, layers: Layers) -> (Ended, Totals) { + let record = Record::default(); + let usd_per_step = 4.0; + for _ in 0..100_000u32 { + if layers.entry && !admit(&record, message).await { + assert_eq!(*record.ended_by_entry.borrow(), 1); + let totals = record.totals.borrow().clone(); + return (Ended::Entry, totals); + } + // The step's model allowance, as `worked` gives it. + let left = record.totals.borrow().spend_left(); + let allowance = Arc::new(RunAllowance::new(if layers.model { + left + } else { + f64::MAX + })); + let refused = common::usage::with_run_allowance(allowance, async { + // A step's calls: refused once the allowance is spent. + let client = aws_sdk_dynamodb::Client::from_conf( + aws_sdk_dynamodb::Config::builder() + .behavior_version_latest() + .build(), + ); + // No team, so `admit` asks nothing outside: only the allowance. + let meter = common::usage::UsageMeter::dynamo(client, "", ""); + for _ in 0..4 { + if meter.admit().await.is_err() { + return true; + } + common::usage::note_run_spend(usd_per_step / 4.0); + record.totals.borrow_mut().spend_usd += usd_per_step / 4.0; + } + false + }) + .await; + if refused { + let totals = record.totals.borrow().clone(); + return (Ended::ModelRefused, totals); + } + { + let mut t = record.totals.borrow_mut(); + t.passes += 1; + t.continuations += 1; + t.worked_secs += 900; + } + // The sweep runs outside all of this, on a clock of its own. + if layers.sweep && record.totals.borrow().over().is_some() { + let totals = record.totals.borrow().clone(); + return (Ended::Sweep, totals); + } + assert!(!pass.is_empty()); + } + let totals = record.totals.borrow().clone(); + (Ended::Never, totals) +} + +/// One step's overshoot at most: the ceiling is checked between steps, and a +/// message already running finishes its step unless a model call refuses it. +fn within_the_ceiling(t: &Totals) -> bool { + t.passes <= MAX_RUN_PASSES + 1 + && t.continuations <= MAX_RUN_CONTINUATIONS + 1 + && t.worked_secs <= MAX_RUN_WORKED_SECS + 900 + && t.spend_usd <= MAX_RUN_SPEND_USD + 4.0 +} + +#[tokio::test] +async fn every_message_and_pass_ends_within_the_ceiling() { + for (kind, message) in run_messages() { + assert_eq!(message.run_ref(), Some((TEAM, RUN)), "{kind}"); + for pass in PASSES { + let (ended, totals) = adversary(&message, pass, ALL).await; + assert_ne!(ended, Ended::Never, "{kind}/{pass}"); + assert!(within_the_ceiling(&totals), "{kind}/{pass}: {totals:?}"); + } + } +} + +/// Each layer taken away, and the others still end it within the ceiling. +#[tokio::test] +async fn with_any_one_layer_removed_the_others_still_end_the_run() { + let (_, message) = &run_messages()[0]; + let table = [ + ( + "no entry guard", + Layers { + entry: false, + ..ALL + }, + ), + ( + "no model refusal", + Layers { + model: false, + ..ALL + }, + ), + ( + "no sweep", + Layers { + sweep: false, + ..ALL + }, + ), + ( + "only the entry guard", + Layers { + entry: true, + model: false, + sweep: false, + }, + ), + ( + "only the model refusal", + Layers { + entry: false, + model: true, + sweep: false, + }, + ), + ( + "only the sweep", + Layers { + entry: false, + model: false, + sweep: true, + }, + ), + ]; + for (name, layers) in table { + let (ended, totals) = adversary(message, "review", layers).await; + assert_ne!(ended, Ended::Never, "{name}"); + assert!(within_the_ceiling(&totals), "{name}: {totals:?}"); + } +} + +/// With every layer gone it runs on: this test can fail. +#[tokio::test] +async fn with_every_layer_removed_it_never_ends() { + let (_, message) = &run_messages()[0]; + let none = Layers { + entry: false, + model: false, + sweep: false, + }; + let (ended, totals) = adversary(message, "review", none).await; + assert_eq!(ended, Ended::Never); + assert!(totals.over().is_some()); +} + +/// A message that isn't a run's never asks the record, and a first ticket +/// message has no run yet: its first step counts from the first pass on. +#[tokio::test] +async fn a_message_with_no_run_runs_and_a_person_retrying_gets_a_new_allowance() { + let record = Record::default(); + let fresh = WorkerMessage::Ticket(TicketMessage { + team_id: TEAM.into(), + ..Default::default() + }); + assert_eq!(fresh.run_ref(), None); + assert!(admit(&record, &fresh).await); + // A retry is a new run id, so a new record: over on the old one, fine here. + let retry = WorkerMessage::Ticket(TicketMessage { + team_id: TEAM.into(), + resume_from: Some(RUN.into()), + ..Default::default() + }); + assert_eq!(retry.run_ref(), None, "a retry is not the old run"); +} + +/// A new message kind can't skip the entry guard, and nor can a dispatch. +#[test] +fn the_entry_guard_comes_before_every_dispatch() { + let main = include_str!("../../main.rs"); + assert_eq!( + main.matches("handle_message(").count(), + 2, + "one call, one fn" + ); + let admit_at = main.find("run_ceiling::admit(").expect("the entry guard"); + let dispatch_at = main + .find("handle_message(Arc::clone(&state), message)") + .unwrap(); + assert!(admit_at < dispatch_at); + let worked_at = main.find("run_ceiling::worked(").expect("the allowance"); + assert!(admit_at < worked_at && worked_at < dispatch_at); + // `run_ref` lists every message kind: no catch-all, so a new one doesn't + // compile until it says whether it belongs to a run. + let msgs = include_str!("../../../../common/src/messages.rs"); + let at = msgs.find("pub fn run_ref(&self)").unwrap(); + let body = &msgs[at..at + msgs[at..].find("\n }\n").unwrap()]; + assert!(!body.contains("_ =>"), "run_ref has a catch-all"); + for kind in ["Ticket", "Feedback", "Resume"] { + assert!(body.contains(&format!("WorkerMessage::{kind}(")), "{kind}"); + } +} + +/// Every model call goes through `UsageMeter::admit` (`model_call_sites` fails +/// the build otherwise), and the allowance is asked first, before anything that +/// could let a call past. +#[test] +fn a_model_call_cannot_skip_the_allowance() { + let usage = include_str!("../../../../common/src/usage.rs"); + let at = usage.find("pub async fn admit(&self)").unwrap(); + let body = &usage[at..at + usage[at..].find("\n }\n").unwrap()]; + let allowance = body.find("run_allowance_refused()").expect("asks it"); + assert!(allowance < body.find("self.team_id.is_empty()").unwrap()); +} + +/// A step already queued doesn't undo the stop, and a pass notices the ceiling. +#[test] +fn the_stop_holds_and_passes_add_to_the_counts() { + let g = include_str!("../run_guard.rs"); + assert!(g.contains("ADD ceil_passes :p, ceil_continuations :c, ceil_spend_usd :s")); + assert!(g.contains("close_run_allowance(")); + // Nothing but addition ever touches the counts, anywhere. + for (name, src) in [ + ("guard", g), + ("mod", include_str!("../mod.rs")), + ("resume", include_str!("../resume.rs")), + ("feedback", include_str!("../feedback.rs")), + ] { + for f in [ + "ceil_passes", + "ceil_continuations", + "ceil_spend_usd", + "ceil_worked_secs", + ] { + for bad in [ + format!("SET {f}"), + format!("REMOVE {f}"), + format!(", {f} ="), + ] { + assert!(!src.contains(&bad), "{name} writes {bad}"); + } + } + } +} diff --git a/services/worker/src/passes/link_checks.rs b/services/worker/src/passes/link_checks.rs index ff9957c54..c63fb0454 100644 --- a/services/worker/src/passes/link_checks.rs +++ b/services/worker/src/passes/link_checks.rs @@ -52,7 +52,7 @@ pub const STALE_AFTER_HOURS: i64 = 24; /// URLs one check of a change may request (sources, targets, old targets). pub const MAX_URLS: usize = 60; /// Fix rounds a blocked check gets before the run stops. -const MAX_FIX_ROUNDS: u32 = 1; +const MAX_FIX_ROUNDS: u32 = super::run_guard::MAX_LINK_FIX_ROUNDS; /// What the coder is told about redirect and link changes. pub const CODER_NOTE: &str = "\n## Redirect and link changes\nWhen the change adds or changes a redirect or a link target, check every new target with `check_url` before you finish: it must answer 200 with a page title that is the page the ticket means. Never copy a target from the ticket unchecked; tickets get slugs wrong. Check each redirect source as it is now too. CoderHelm checks them all again before the PR opens and blocks it when a target fails. When a redirect map uses paths without a host, add a fenced ```sites.json block to your closing notes naming the site each map serves: `[{\"file\": \"the map's file\", \"map\": \"the map's name, when the file has several\", \"sources\": [\"https://the host the sources are requested on\", \"https://its staging host, if any\"], \"targets\": \"https://the host relative targets are on, when it differs\"}]`.\n"; @@ -1234,7 +1234,33 @@ pub async fn gate( usage: &mut crate::models::TokenUsage, has_time: impl Fn() -> bool, ) -> Result { - let mut rounds = 0; + let head = w.head().await; + let standing = w.ledger.update(|l| { + if !l.links.unchanged(&head) { + return None; + } + l.links.reused(); + l.links_outcome.clone() + }); + if let Some(standing) = standing { + return standing; + } + let outcome = check_and_fix(w, evidence, usage, has_time).await; + let head = w.head().await; + w.ledger.update(|l| { + l.links.head = head; + l.links_outcome = Some(outcome.clone()); + }); + w.save_ledger().await; + outcome +} + +async fn check_and_fix( + w: &super::proof::Work<'_>, + evidence: &mut super::proof::RunEvidence, + usage: &mut crate::models::TokenUsage, + has_time: impl Fn() -> bool, +) -> Result { loop { let diff = w .github @@ -1276,7 +1302,7 @@ pub async fn gate( run_id = w.run_id, entries = found.len(), blocking = blocking.len(), - rounds, + rounds = w.ledger.update(|l| l.links.rounds), "Link and redirect check complete" ); if blocking.is_empty() { @@ -1293,10 +1319,15 @@ pub async fn gate( .await; return Ok(report.section()); } - if rounds >= MAX_FIX_ROUNDS || !has_time() { + w.report_findings("links", blocking.len()).await; + let head = w.head().await; + w.ledger.update(|l| l.links.checked(&head, blocking.len())); + if !w.ledger.update(|l| l.links.may_fix(MAX_FIX_ROUNDS)) || !has_time() { + w.save_ledger().await; return Err(blocking.join("; ")); } - rounds += 1; + w.ledger.update(|l| l.links.start_fix()); + w.save_ledger().await; super::add_progress_note( w.state, &w.msg.team_id, @@ -1326,6 +1357,8 @@ pub async fn gate( true, // bot-driven link fix — scoped to the PR ) .await; + w.ledger.update(|l| l.links.end_fix()); + w.save_ledger().await; match fixed { Ok(r) => evidence.merge(r.evidence), Err(e) => { @@ -1335,7 +1368,7 @@ pub async fn gate( )) } } - let _ = super::update_pass(w.state, &w.msg.team_id, w.run_id, "review").await; + let _ = super::update_pass(w.state, &w.msg.team_id, w.run_id, super::PASS_CHECKS).await; } } diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index f54215a69..8e3fca679 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -12,9 +12,12 @@ const MIN_TIME_FOR_REMEDIATION_SECS: u64 = 240; // 4 minutes /// 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. +/// less, the run continues in a fresh step at the pull request. const MIN_TIME_FOR_PR_SECS: u64 = 150; +/// The pass the checks on the open pull request run under. +pub(crate) const PASS_CHECKS: &str = "review"; + /// 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 /// files live in a repo other than the one the run is in. @@ -167,6 +170,9 @@ async fn try_auto_continue( steps::MAX_RUN_STEPS )); } + if let Some(reason) = run_guard::on_continuation(state, &msg.team_id, run_id).await { + return Handoff::Stopped(reason); + } let now_ms = chrono::Utc::now().timestamp_millis().max(0) as u64; let first_ms = if msg.first_attempt_ms > 0 { msg.first_attempt_ms @@ -415,17 +421,18 @@ mod continuation_tests { 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", + "The proof check needs more time", + "The link and redirect check needs more time", + "The failing-test rules need more time", + "The new-feature rules need 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(why), "no hand-off for: {why}"); } + // The checks' hand-offs resume at the checks; the pull request's at it. + let m = rp.find("macro_rules! hand_off_unless_time_for").unwrap(); + assert!(rp[m..m + 700].contains("steps::Gate::Checks")); + let at = rp.find("opening the pull request needs more time").unwrap(); + assert!(rp[at - 400..at].contains("steps::Gate::Pr")); 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"); @@ -444,7 +451,8 @@ mod continuation_tests { 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 resume_gate = if can_skip_implement {")); + assert!(rp.contains("step_state.gate.map(|g| match g {")); 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) {")); @@ -472,6 +480,8 @@ mod continuation_tests { 2 ); assert_eq!(count("unfinished: ", "&unfinished,"), 2); + // On the description of the pull request already open, not a new one. + assert_eq!(count("pr::apply_", "checks("), 2); assert_eq!(count("generated: ", "&settled_generated,"), 2); let rp = run_passes_src(); assert!(rp.contains(concat!("plan_coverage::", "settle_generated("))); @@ -871,7 +881,9 @@ pub mod review_thread_reply; pub mod review_verdict; pub mod rewards; pub(crate) mod round; +pub mod run_ceiling; mod run_end; +pub mod run_guard; pub(crate) mod run_lists; mod security; #[cfg(test)] @@ -1032,6 +1044,14 @@ pub async fn orchestrate_ticket( } else { error!(run_id, error = %e, "Orchestration failed"); let checkpoint = load_checkpoint(state, &msg.team_id, &run_id).await; + // The run guard fired: one ending, always (see `run_guard`). + let guard_ended = run_guard::end_if_stopped( + state, + &msg, + &run_id, + checkpoint.as_ref().map(|c| c.1.as_str()), + ) + .await; // Budget exhausted (hit the step limit) with committed partial // work is "needs more turns", not a real failure — auto-continue // (bounded) from the branch instead of salvaging a half-finished @@ -1042,7 +1062,8 @@ pub async fn orchestrate_ticket( // salvage arm below uses the same "implement_started" signal). This // 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) + let continued = !guard_ended + && is_budget_exhausted(&err_msg) && try_auto_continue( state, &msg, @@ -1059,17 +1080,18 @@ pub async fn orchestrate_ticket( // ticket's fault: the run is sent again later (same run_id), by // the one requeue policy every pass uses. Decided from the // error's kind, never its text. - let continued = continued || { - let err: &(dyn std::error::Error + 'static) = &*e; - common::model_retry::is_transient_model_error(err) - && requeue_after_model_error(state, &msg, &run_id).await - }; + let continued = continued + || !guard_ended && { + let err: &(dyn std::error::Error + 'static) = &*e; + common::model_retry::is_transient_model_error(err) + && requeue_after_model_error(state, &msg, &run_id).await + }; // Salvage before failing: an implement that burned its turn // budget mid-task has already pushed real commits to the branch. // Only mid-implement deaths salvage: for later-pass errors a // salvage would mark the run completed and hide the real error // behind a misleading "partial work" message. - let salvaged = if continued { + let salvaged = if continued || guard_ended { false } else if let Some((ref last_pass, ref branch, _)) = checkpoint { if !branch.is_empty() && last_pass.as_str() == "implement_started" { @@ -1118,7 +1140,7 @@ pub async fn orchestrate_ticket( } else { false }; - if !continued && !salvaged { + if !continued && !salvaged && !guard_ended { let sanitized = sanitize_error(&err_msg); fail_run(state, &msg, &run_id, &sanitized, &usage, duration).await; } @@ -1174,7 +1196,16 @@ pub async fn orchestrate_ticket( // 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 { + let guard_ended = run_guard::end_if_stopped( + state, + &msg, + &run_id, + checkpoint.as_ref().map(|c| c.1.as_str()), + ) + .await; + let salvaged = if guard_ended { + true + } else if let Some((ref last_pass, ref branch, _)) = checkpoint { if !branch.is_empty() && matches!( last_pass.as_str(), @@ -2029,12 +2060,15 @@ async fn run_passes( // --- Pass 2: Plan --- check_cancelled(state, &msg.team_id, run_id).await?; - update_pass(state, &msg.team_id, run_id, "plan").await?; // How far planning got: saved from here on, so a step that runs out of // time while planning continues in a fresh step (see `steps::Gate::Plan`) // instead of failing with nothing committed. A continuation past - // planning (its own plan, no planning state) has a final plan. + // planning (its own plan, no planning state) has a final plan, and plans + // nothing: the run page shows the pass the run is really on. let plan_final = resumed_plan && plan_resume.as_ref().is_none_or(|p| p.checked); + if !plan_final { + update_pass(state, &msg.team_id, run_id, "plan").await?; + } let mut ps = plan_resume.clone().unwrap_or_else(|| { steps::PlanState::new(&msg.repo_owner, &msg.repo_name, &msg.base_branch) }); @@ -2895,8 +2929,23 @@ async fn run_passes( } else { steps::StepState::default() }; + // What the checks found and the pull request the run opened, from the + // steps before this one. + let checks_scope = format!("{}/{}", msg.repo_owner, msg.repo_name); + let ledger = if same_run { + run_guard::LedgerCell::load(state, &msg.team_id, run_id, &checks_scope).await + } else { + run_guard::LedgerCell::new(&checks_scope, Default::default()) + }; + ledger.update(|l| l.on_step_start()); + let pr_is_open = ledger.update(|l| l.opened.is_some()); let resume_gate = if can_skip_implement { - step_state.gate + // A run that stopped at the checks when they came first has no pull + // request yet: that comes first now. + step_state.gate.map(|g| match g { + steps::Gate::Checks if !pr_is_open => steps::Gate::Pr, + g => g, + }) } else { None }; @@ -2926,8 +2975,9 @@ async fn run_passes( } let impl_result = if can_skip_implement { // Resume: reconstruct impl_result from the existing branch diff + // Nothing is implemented in this step, so the run page keeps the pass + // the run is really on. info!(run_id, branch = %branch_name, "Checkpoint resume: skipping implement pass"); - update_pass(state, &msg.team_id, run_id, "implement").await?; let diff_json = github .get_diff( @@ -4089,7 +4139,7 @@ async fn run_passes( .await; // A continuation picks up the planned tasks the branch doesn't do yet. let still_to_do = if msg.continuation > 0 { - continuation_feedback(&github, msg, &plan_result, &branch_name).await + continuation_feedback(state, run_id, &github, msg, &plan_result, &branch_name).await } else { None }; @@ -4537,6 +4587,13 @@ async fn run_passes( .await }; if let Some(cov) = coverage { + run_guard::progress( + state, + &msg.team_id, + run_id, + run_guard::Progress::TasksDone(cov.done.len()), + ) + .await; // Only the tasks the branch did are checked off, so the run page and // a later attempt see the truth. save_checked_tasks( @@ -4571,8 +4628,13 @@ async fn run_passes( .await; } match plan_coverage::next(&cov, plan_coverage::MAX_ROUNDS, false) { - plan_coverage::Next::Complete => {} + plan_coverage::Next::Complete => { + run_guard::progress(state, &msg.team_id, run_id, run_guard::Progress::WorkDone) + .await; + } plan_coverage::Next::OpenWithOptional => { + run_guard::progress(state, &msg.team_id, run_id, run_guard::Progress::WorkDone) + .await; plan_optional = plan_coverage::optional_findings(&cov); } plan_coverage::Next::Round | plan_coverage::Next::Unfinished => { @@ -4699,7 +4761,12 @@ async fn run_passes( // --- Adversarial Test (multi-repo path) --- check_cancelled(state, &msg.team_id, run_id).await?; - if run_verify && has_time_for_remediation(start) { + let tested_at = github + .get_ref(&msg.repo_owner, &msg.repo_name, &branch_name) + .await + .unwrap_or_default(); + let already_tested = !tested_at.is_empty() && ledger.update(|l| l.tested_head == tested_at); + if run_verify && !already_tested && 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(); @@ -4774,6 +4841,8 @@ async fn run_passes( warn!(run_id, error = %e, "Test auto-fix failed, proceeding anyway"); } } + ledger.update(|l| l.tested_head = tested_at.clone()); + ledger.save(state, &msg.team_id, run_id).await; } // A step resuming at a later gate has the audit's verdict from the @@ -4955,9 +5024,7 @@ async fn run_passes( // Open items, marked so it stays a draft; the full audit text is not // copied into long-term memory. - // --- Proof check (before PR — what the change rests on is proven) --- 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 --- if steps::Gate::Generators.runs_from(resume_gate) { // A redelivery of this step, or the next one, resumes here. @@ -5051,17 +5118,270 @@ async fn run_passes( } } } - 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); + // What is open whatever the checks find: tasks the plan marks optional and + // the change left out, what the ticket needs that this run didn't do (a + // person's step, with why and how to grant it, or one handed out with no + // reason), and security issues not fixed yet or a check that didn't run. + let outside_open = plan_coverage::outside_findings(plan_result.fix.as_ref()); + let mut known_open: Vec = plan_optional; + known_open.extend(outside_open.iter().cloned()); + known_open.extend(security_items); + + // --- The draft pull request, as soon as the work is built --- + // It opens before the proof check, the rules and the review: they work on + // it, and can't hold it back. A step resuming after this never comes here. + let opened = ledger.update(|l| l.opened.clone()); + let pr_result = if let Some(o) = opened { + info!( + run_id, + pr_number = o.number, + "The pull request is open: on to its checks" + ); + pr::PrResult { + pr_number: o.number, + pr_url: o.url, + branch: branch_name.clone(), + draft: true, + node_id: o.node_id, + } + } else { + steps::save_gate(state, &msg.team_id, run_id, steps::Gate::Pr, Some(&carry)).await; + if !outside_open.is_empty() { + add_progress_note( + state, + &msg.team_id, + run_id, + &plan_coverage::outside_note(plan_result.fix.as_ref()), + ) + .await; + } + // --- Existing work: now that the change's own files are known, an open + // pull request (anyone's, opened while this run worked or touching the + // same files) that already does this ends the run as covered by it; the + // work stays on a branch. Once a head: a step that comes back here on + // the same code has its answer --- + let at_head = github + .get_ref(&msg.repo_owner, &msg.repo_name, &branch_name) + .await + .unwrap_or_default(); + if at_head.is_empty() || ledger.update(|l| l.existing_work_head != at_head) { + let (tests, specs, failure) = existing_work_inputs(test_ev.as_ref()); + if let Some(covered) = stop_gate::existing_work( + state, + &provider, + usage, + msg, + &github, + run_id, + &branch_name, + &own_pr_numbers(&history, &msg.repo_owner, &msg.repo_name), + &decided_prs(&history), + &tests, + &specs, + &impl_result.files_modified, + &failure, + ) + .await + { + let kept = + keep_wip_branch(&github, &msg.repo_owner, &msg.repo_name, &branch_name).await; + add_progress_note( + state, + &msg.team_id, + run_id, + &format!("No second pull request; the work so far is kept on branch `{kept}`."), + ) + .await; + stop_gate::finish_covered(state, msg, run_id, &github, &covered, usage, start) + .await; + close_memory(state, agent_memory.take()).await; + return Ok(()); + } + ledger.update(|l| l.existing_work_head = at_head.clone()); + ledger.save(state, &msg.team_id, run_id).await; + } + + 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::Pr, + Some(&carry), + "The work is built; 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 + match pr::resolve_conflicts(state, msg, &github, &branch_name, &provider, usage).await { + Ok(true) => info!(run_id, "Resolved merge conflicts with main"), + Ok(false) => {} + Err(e) => warn!(run_id, error = %e, "Conflict resolution failed, proceeding"), + } + + // How production starts the container, read from this branch, for the + // description's start-path check. + if let Some(ev) = log_ev.as_mut() { + let files = log_evidence::GithubFiles { + github: &github, + owner: &msg.repo_owner, + repo: &msg.repo_name, + git_ref: &branch_name, + }; + ev.start = Some(log_evidence::resolve_start(&files, ev).await); + log_evidence::save(state, &msg.team_id, run_id, ev).await; + } + // Never another open pull request's commits under new hashes: the + // copies are dropped and the pull request stacks on it. + let stacked_on = stack::before_pr( + state, + &github, + msg, + &branch_name, + stacked_on, + &provider, + usage, + ) + .await?; + let pass_start = std::time::Instant::now(); + let usage_before = usage.clone(); + let opening_evidence = impl_result.evidence.clone(); + let pr_result = pr::run( + state, + msg, + &github, + &branch_name, + &plan_result, + &voice, + &pr::Proof { + evidence: &opening_evidence.for_pr(), + gaps: &proof::gaps_section(&known_open), + unfinished: "", + manual: "", + ci: &opening_evidence.ci_commands, + mirrors: &completeness::parse_mirrors(&opening_evidence.notes), + log: log_ev.as_ref(), + links: "", + test_fix: None, + feature: None, + keep_commits: stacked_on + .as_ref() + .is_some_and(|d| !d.unresolved.is_empty()), + }, + &provider, + usage, + run_id, + ) + .await?; + write_pass_trace( + state, + &msg.team_id, + run_id, + "pr", + pass_start, + &usage_before, + usage, + None, + ) + .await; + info!(run_id, pr_url = %pr_result.pr_url, "Draft PR created"); + // From here a continuation resumes at the checks, on this pull request. + ledger.update(|l| { + l.opened = Some(run_guard::OpenedPr { + number: pr_result.pr_number, + url: pr_result.pr_url.clone(), + node_id: pr_result.node_id.clone(), + }); + }); + ledger.save(state, &msg.team_id, run_id).await; + steps::save_gate( + state, + &msg.team_id, + run_id, + steps::Gate::Checks, + Some(&carry), + ) + .await; + record_open_pr(state, msg, run_id, &branch_name, &pr_result).await; + run_guard::progress(state, &msg.team_id, run_id, run_guard::Progress::PrOpen).await; + // The outside steps CoderHelm does itself (a deploy, the end-to-end + // run, the confirm query) run now; the ticket and the PR report results. + if fix_route == fix_location::Route::CodeAndOutside { + if let Some(decision) = plan_result.fix.as_mut() { + after_pr_outside_work( + state, + msg, + run_id, + &github, + decision, + &branch_name, + pr_result.pr_number, + outside_until(start), + ) + .await; + } + } + if let Some(d) = &stacked_on { + stack::note_pr( + &github, + &msg.repo_owner, + &msg.repo_name, + pr_result.pr_number, + d, + ) + .await; + } + // A data migration's release steps: CoderHelm runs them from here on. + release_run::after_pr( + state, + msg, + run_id, + &github, + &plan_result, + &branch_name, + pr_result.pr_number, + ) + .await; + // The plan moved the change out of a repo an earlier run of this ticket + // opened a PR in: that PR is closed with a note naming this one. + supersede_moved_prs( + &github, + &history, + &[format!("{}/{}", msg.repo_owner, msg.repo_name)], + &pr_result.pr_url, + ) + .await; + self::webhooks::emit_pr_opened( + state, + msg, + run_id, + &format!("{}/{}", msg.repo_owner, msg.repo_name), + &pr_result, + ) + .await; + add_progress_note( + state, + &msg.team_id, + run_id, + &format!("Draft PR created: #{}", pr_result.pr_number), + ) + .await; + pr_result + }; + + // --- The checks, on the open pull request --- + // Each runs once on a head and keeps its result and its fix rounds in the + // run's ledger, so a fresh step takes up what the last one didn't reach and + // repeats nothing. What they leave goes under Open items: nothing here can + // stop the pull request, which is already there. + update_pass(state, &msg.team_id, run_id, PASS_CHECKS).await?; let mut evidence = impl_result.evidence.clone(); let work = proof::Work { state, @@ -5076,235 +5396,110 @@ async fn run_passes( run_id, deadline: implement_deadline, generated: &settled_generated, + ledger: &ledger, }; - 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: it goes - // at the top of the pull request, which stays a draft until it's done. + let has_time = || has_time_for_remediation(start); + // A check not yet run on this head needs time for its fix round: without + // it, a fresh step takes it from there. + macro_rules! hand_off_unless_time_for { + ($record:ident, $why:expr) => { + let head = work.head().await; + if !has_time() && !ledger.update(|l| l.$record.unchanged(&head)) { + close_memory(state, agent_memory.take()).await; + return hand_off_at( + state, + msg, + &github, + run_id, + &branch_name, + steps::Gate::Checks, + Some(&carry), + $why, + usage, + ) + .await; + } + }; + } + hand_off_unless_time_for!( + proof, + "The proof check needs more time than this step has left" + ); + let mut gaps = proof::prove(&work, &mut evidence, usage, has_time).await; + // Planned work the check found not done is never an Open item: it goes at + // the top of the pull request, which stays a draft until it's done. 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; - } - // A finished run always ends with a pull request: the planned work - // still not done after the fix round is listed at its top and it - // stays a draft. add_progress_note( state, &msg.team_id, run_id, &format!( - "{} planned task(s) still not done after the fix round: the pull request opens as a draft with them listed at the top", + "{} planned task(s) still not done after the fix rounds: they are listed at the top of the pull request, which stays a draft", proof::planned_work(&gaps).len() ), ) .await; } let unfinished = proof::unfinished_section(&gaps); - // Tasks the plan marks optional and the change left out, named. - gaps.extend(plan_optional); - // What the ticket needs that this run didn't do: a person's step (with - // why and how to grant it), or one handed out with no reason (not - // covered). - let outside_open = plan_coverage::outside_findings(plan_result.fix.as_ref()); - if !outside_open.is_empty() { - add_progress_note( - state, - &msg.team_id, - run_id, - &plan_coverage::outside_note(plan_result.fix.as_ref()), - ) - .await; - } - gaps.extend(outside_open); - // Security issues not fixed yet, or a check that didn't run. - 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. - budget.take_denied(); - let links = match link_checks::gate(&work, &mut evidence, usage, || budget.has_time()).await { + gaps.extend(known_open); + // Every redirect and link the change adds or changes, checked live. + hand_off_unless_time_for!( + links, + "The link and redirect check needs more time than this step has left" + ); + let links = match link_checks::gate(&work, &mut evidence, usage, 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()) + gaps.push(proof::blocked_item("The link and redirect check", &why)); + String::new() } }; // 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 = match test_fix::gate(&work, &mut evidence, usage, || budget.has_time()).await { + hand_off_unless_time_for!( + test_fix, + "The failing-test rules need more time than this step has left" + ); + let test_pr = match test_fix::gate(&work, &mut evidence, usage, 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(why) => { + gaps.push(proof::blocked_item("The failing-test rules", &why)); + None } - 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). + hand_off_unless_time_for!( + rules, + "The new-feature rules need more time than this step has left" + ); let feature_pr = match feature::gate( &work, &mut evidence, usage, triage_result.intent, &history.prior, - || budget.has_time(), + has_time, ) .await { 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()) + gaps.push(proof::blocked_item("The new-feature rules", &why)); + None } }; - - // --- Existing work, again before the PR opens: now that the change's - // own files are known, an open pull request (anyone's, opened while - // this run worked or touching the same files) that already does this - // ends the run as covered by it; the work stays on a branch --- - { - let (tests, specs, failure) = existing_work_inputs(test_ev.as_ref()); - if let Some(covered) = stop_gate::existing_work( - state, - &provider, - usage, - msg, - &github, - run_id, - &branch_name, - &own_pr_numbers(&history, &msg.repo_owner, &msg.repo_name), - &decided_prs(&history), - &tests, - &specs, - &impl_result.files_modified, - &failure, - ) - .await - { - let kept = - keep_wip_branch(&github, &msg.repo_owner, &msg.repo_name, &branch_name).await; - add_progress_note( - state, - &msg.team_id, - run_id, - &format!("No second pull request; the work so far is kept on branch `{kept}`."), - ) - .await; - stop_gate::finish_covered(state, msg, run_id, &github, &covered, usage, start).await; - close_memory(state, agent_memory.take()).await; - return Ok(()); - } - } - - // --- 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; + if let Some(f) = &feature_pr { + gaps.extend(feature::open_findings(f)); } - update_pass(state, &msg.team_id, run_id, "pr").await?; - - // Resolve conflicts with main before PR - match pr::resolve_conflicts(state, msg, &github, &branch_name, &provider, usage).await { - Ok(true) => info!(run_id, "Resolved merge conflicts with main"), - Ok(false) => {} - Err(e) => warn!(run_id, error = %e, "Conflict resolution failed, proceeding"), - } - - // How production starts the container, read from this branch, for the - // description's start-path check. - if let Some(ev) = log_ev.as_mut() { - let files = log_evidence::GithubFiles { - github: &github, - owner: &msg.repo_owner, - repo: &msg.repo_name, - git_ref: &branch_name, - }; - ev.start = Some(log_evidence::resolve_start(&files, ev).await); - log_evidence::save(state, &msg.team_id, run_id, ev).await; - } - // Never another open pull request's commits under new hashes: the - // copies are dropped and the pull request stacks on it. - let stacked_on = stack::before_pr( - state, - &github, - msg, - &branch_name, - stacked_on, - &provider, - usage, - ) - .await?; - let pass_start = std::time::Instant::now(); - let usage_before = usage.clone(); - let pr_result = pr::run( + pr::apply_checks( state, msg, &github, - &branch_name, + run_id, &plan_result, - &voice, + pr_result.pr_number, &pr::Proof { evidence: &evidence.for_pr(), gaps: &proof::gaps_section(&gaps), @@ -5316,89 +5511,12 @@ async fn run_passes( links: &links, test_fix: test_pr.as_ref(), feature: feature_pr.as_ref(), - keep_commits: stacked_on - .as_ref() - .is_some_and(|d| !d.unresolved.is_empty()), + keep_commits: false, }, - &provider, - usage, - run_id, - ) - .await?; - write_pass_trace( - state, - &msg.team_id, - run_id, - "pr", - pass_start, - &usage_before, - usage, - None, - ) - .await; - info!(run_id, pr_url = %pr_result.pr_url, "Draft PR created"); - // The outside steps CoderHelm does itself (a deploy, the end-to-end - // run, the confirm query) run now; the ticket and the PR report results. - if fix_route == fix_location::Route::CodeAndOutside { - if let Some(decision) = plan_result.fix.as_mut() { - after_pr_outside_work( - state, - msg, - run_id, - &github, - decision, - &branch_name, - pr_result.pr_number, - outside_until(start), - ) - .await; - } - } - if let Some(d) = &stacked_on { - stack::note_pr( - &github, - &msg.repo_owner, - &msg.repo_name, - pr_result.pr_number, - d, - ) - .await; - } - // A data migration's release steps: CoderHelm runs them from here on. - release_run::after_pr( - state, - msg, - run_id, - &github, - &plan_result, - &branch_name, - pr_result.pr_number, - ) - .await; - // The plan moved the change out of a repo an earlier run of this ticket - // opened a PR in: that PR is closed with a note naming this one. - supersede_moved_prs( - &github, - &history, - &[format!("{}/{}", msg.repo_owner, msg.repo_name)], - &pr_result.pr_url, - ) - .await; - self::webhooks::emit_pr_opened( - state, - msg, - run_id, - &format!("{}/{}", msg.repo_owner, msg.repo_name), - &pr_result, - ) - .await; - add_progress_note( - state, - &msg.team_id, - run_id, - &format!("Draft PR created: #{}", pr_result.pr_number), ) .await; + // A round the guard refused shows up only as that round's failure. + run_guard::check(state, &msg.team_id, run_id).await?; // Planned work still not done is finished by CoderHelm, in rounds of its // own on the pull request (`finish_planned`): the first is parked for @@ -5559,6 +5677,34 @@ async fn run_passes( Ok(()) } +/// The pull request on the run record as soon as it exists: the run page shows +/// it while the checks run, and the run still is `running`. +async fn record_open_pr( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + branch: &str, + pr: &pr::PrResult, +) { + if let Err(e) = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&msg.team_id)) + .key("run_id", attr_s(run_id)) + .update_expression("SET pr_url = :pr, pr_number = :pn, branch = :b, updated_at = :t") + .condition_expression("attribute_exists(run_id)") + .expression_attribute_values(":pr", attr_s(&pr.pr_url)) + .expression_attribute_values(":pn", attr_n(pr.pr_number)) + .expression_attribute_values(":b", attr_s(branch)) + .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) + .send() + .await + { + warn!(run_id, error = %e, "Could not record the pull request on the run"); + } +} + /// The run's error when a gate stops it (a tooling failure, a value only a /// person can set): the gate's own reason, and where the work is kept. fn stopped_keeping(why: &str, kept: &str) -> String { @@ -5688,6 +5834,8 @@ async fn save_checked_tasks(state: &WorkerState, msg: &TicketMessage, run_id: &s /// For a continuation: the planned tasks its branch doesn't do yet, as the /// implement pass's instructions. `None` when all are done or it can't tell. async fn continuation_feedback( + state: &WorkerState, + run_id: &str, github: &GitHubClient, msg: &TicketMessage, plan: &plan::PlanResult, @@ -5708,6 +5856,13 @@ async fn continuation_feedback( ) .await?; let cov = plan_coverage::coverage(&tasks, &changed); + run_guard::progress( + state, + &msg.team_id, + run_id, + run_guard::Progress::TasksDone(cov.done.len()), + ) + .await; (!cov.required_missing().is_empty()).then(|| plan_coverage::round_feedback(&cov)) } @@ -6143,33 +6298,10 @@ async fn run_repo_pipeline( .into()); } }; - update_pass(state, &msg.team_id, run_id, "review").await?; - let mut evidence = impl_result.evidence.clone(); - let work = proof::Work { - state, - msg, - github, - plan: &repo_plan, - branch: branch_name, - rules, - repo_instructions, - provider, - file_cache, - run_id, - deadline: implement_deadline, - generated: &settled_generated, - }; - let mut gaps = proof::prove(&work, &mut evidence, usage, || { - has_time_for_remediation(start) - }) - .await; - // Planned work still not done after the fix round: this repository's - // pull request opens as a draft with it listed at the top. - let unfinished = proof::unfinished_section(&gaps); - gaps.extend(plan_optional); - // What the ticket needs outside the code, counted once: in the pull - // request of the repository its steps act on (the same plan check the - // single-repository path makes). + // What is open whatever the checks find. What the ticket needs outside the + // code is counted once: in the pull request of the repository its steps act + // on (the same plan check the single-repository path makes). + let mut known_open: Vec = plan_optional; let owns_outside = outside_owner(plan_result, repo_owner, repo_name); if owns_outside { let outside_open = plan_coverage::outside_findings(plan_result.fix.as_ref()); @@ -6182,25 +6314,25 @@ async fn run_repo_pipeline( ) .await; } - gaps.extend(outside_open); + known_open.extend(outside_open); } - gaps.extend(security_items); - 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}"))?; - // 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)?; + known_open.extend(security_items); + let ledger = run_guard::LedgerCell::load( + state, + &msg.team_id, + run_id, + &format!("{repo_owner}/{repo_name}"), + ) + .await; + ledger.update(|l| l.on_step_start()); + let already_open = ledger.update(|l| l.opened.clone()); - // --- Create Draft PR --- + // --- The draft pull request, before the checks (see the single-repository + // path) --- check_cancelled(state, &msg.team_id, run_id).await?; - update_pass(state, &msg.team_id, run_id, "pr").await?; + if already_open.is_none() { + update_pass(state, &msg.team_id, run_id, "pr").await?; + } match pr::resolve_conflicts(state, msg, github, branch_name, provider, usage).await { Ok(true) => info!(run_id, "Resolved merge conflicts"), @@ -6226,13 +6358,142 @@ async fn run_repo_pipeline( } None => None, }; - let pr_result = pr::run( + let pr_result = if let Some(o) = already_open { + pr::PrResult { + pr_number: o.number, + pr_url: o.url, + branch: branch_name.to_string(), + draft: true, + node_id: o.node_id, + } + } else { + let opening_evidence = impl_result.evidence.clone(); + let pr_result = pr::run( + state, + msg, + github, + branch_name, + &repo_plan, + voice, + &pr::Proof { + evidence: &opening_evidence.for_pr(), + gaps: &proof::gaps_section(&known_open), + unfinished: "", + manual: "", + ci: &opening_evidence.ci_commands, + mirrors: &completeness::parse_mirrors(&opening_evidence.notes), + log: repo_ev.as_ref(), + links: "", + test_fix: None, + // Multi-repo runs: the new-feature rules check single-repo runs. + feature: None, + keep_commits: false, + }, + provider, + usage, + run_id, + ) + .await?; + write_pass_trace( + state, + &msg.team_id, + run_id, + "pr", + pass_start, + &usage_before, + usage, + None, + ) + .await; + info!(run_id, repo = %format!("{repo_owner}/{repo_name}"), pr_url = %pr_result.pr_url, "Draft PR created"); + ledger.update(|l| { + l.opened = Some(run_guard::OpenedPr { + number: pr_result.pr_number, + url: pr_result.pr_url.clone(), + node_id: pr_result.node_id.clone(), + }); + }); + ledger.save(state, &msg.team_id, run_id).await; + run_guard::progress(state, &msg.team_id, run_id, run_guard::Progress::PrOpen).await; + self::webhooks::emit_pr_opened( + state, + msg, + run_id, + &format!("{repo_owner}/{repo_name}"), + &pr_result, + ) + .await; + add_progress_note( + state, + &msg.team_id, + run_id, + &format!( + "Draft PR #{} created for {}/{}", + pr_result.pr_number, repo_owner, repo_name + ), + ) + .await; + pr_result + }; + + // --- The checks, on the open pull request. What they leave goes under + // Open items: nothing here can stop it --- + update_pass(state, &msg.team_id, run_id, PASS_CHECKS).await?; + let mut evidence = impl_result.evidence.clone(); + let work = proof::Work { state, msg, github, - branch_name, + plan: &repo_plan, + branch: branch_name, + rules, + repo_instructions, + provider, + file_cache, + run_id, + deadline: implement_deadline, + generated: &settled_generated, + ledger: &ledger, + }; + let mut gaps = proof::prove(&work, &mut evidence, usage, || { + has_time_for_remediation(start) + }) + .await; + // Planned work still not done after the fix rounds: this repository's + // pull request stays a draft with it listed at the top. + let unfinished = proof::unfinished_section(&gaps); + gaps.extend(known_open); + let links = match link_checks::gate(&work, &mut evidence, usage, || { + has_time_for_remediation(start) + }) + .await + { + Ok(l) => l, + Err(why) => { + gaps.push(proof::blocked_item("The link and redirect check", &why)); + String::new() + } + }; + // 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 = match test_fix::gate(&work, &mut evidence, usage, || { + has_time_for_remediation(start) + }) + .await + { + Ok(t) => t, + Err(why) => { + gaps.push(proof::blocked_item("The failing-test rules", &why)); + None + } + }; + pr::apply_checks( + state, + msg, + github, + run_id, &repo_plan, - voice, + pr_result.pr_number, &pr::Proof { evidence: &evidence.for_pr(), gaps: &proof::gaps_section(&gaps), @@ -6243,44 +6504,9 @@ async fn run_repo_pipeline( log: repo_ev.as_ref(), links: &links, test_fix: test_pr.as_ref(), - // Multi-repo runs: the new-feature rules check single-repo runs. feature: None, keep_commits: false, }, - provider, - usage, - run_id, - ) - .await?; - write_pass_trace( - state, - &msg.team_id, - run_id, - "pr", - pass_start, - &usage_before, - usage, - None, - ) - .await; - - info!(run_id, repo = %format!("{repo_owner}/{repo_name}"), pr_url = %pr_result.pr_url, "Draft PR created"); - self::webhooks::emit_pr_opened( - state, - msg, - run_id, - &format!("{repo_owner}/{repo_name}"), - &pr_result, - ) - .await; - add_progress_note( - state, - &msg.team_id, - run_id, - &format!( - "Draft PR #{} created for {}/{}", - pr_result.pr_number, repo_owner, repo_name - ), ) .await; // The outside steps CoderHelm does itself, on this repository's pull @@ -6327,8 +6553,9 @@ async fn resume_run_to_running(state: &WorkerState, team_id: &str, run_id: &str) .key("team_id", attr_s(team_id)) .key("run_id", attr_s(run_id)) .update_expression("SET #s = :r, status_run_id = :sri, updated_at = :t") + // Nor a run the guard stopped: a step already queued doesn't undo it. .condition_expression(format!( - "attribute_exists(run_id) AND {}", + "attribute_exists(run_id) AND attribute_not_exists(guard_open) AND {}", common::run_status::not_ended("#s") )) .expression_attribute_names("#s", "status") @@ -6541,7 +6768,8 @@ pub(crate) async fn update_pass( Some(("current_pass = :p", ":p", attr_s(pass))), ) .await?; - Ok(()) + // Every pass goes through here, so a pass added later is counted too. + run_guard::on_pass(state, team_id, run_id).await } /// Why Coderhelm stopped trying to get CI green and left the PR to a person. @@ -6630,6 +6858,9 @@ pub(crate) async fn record_ci_outcome( run_id: &str, outcome: CiOutcome, ) { + if matches!(outcome, CiOutcome::Passed | CiOutcome::PassedAfterRerun) { + run_guard::progress(state, team_id, run_id, run_guard::Progress::CiGreen).await; + } let mut req = state .dynamo .update_item() @@ -7271,6 +7502,39 @@ async fn mark_run_needs_input( } } +/// A run the guard stopped with nothing to open a pull request from: it still +/// waits on a person, with the reason on the run page. +pub(crate) async fn mark_run_stopped_by_guard( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + reason: &str, +) { + if let Err(e) = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&msg.team_id)) + .key("run_id", attr_s(run_id)) + .update_expression( + "SET #s = :s, status_run_id = :sri, error_message = :em, updated_at = :t, current_pass = :cp", + ) + .condition_expression(common::run_status::not_ended("#s")) + .ended_values() + .expression_attribute_names("#s", "status") + .expression_attribute_values(":s", attr_s(common::run_status::NEEDS_INPUT)) + .expression_attribute_values(":sri", attr_s(&format!("needs_input#{run_id}"))) + .expression_attribute_values(":em", attr_s(reason)) + .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) + .expression_attribute_values(":cp", attr_s("done")) + .send() + .await + { + warn!(run_id, error = %e, "Could not hand the stopped run to a person"); + } + self::webhooks::emit_run(state, &msg.team_id, run_id, "needs_input").await; +} + /// Stop a Jira run whose ticket belongs in a repo that isn't connected or /// isn't turned on for runs: tell the ticket (and the run notes) in plain /// words, and leave the run needs_input instead of re-routing it. diff --git a/services/worker/src/passes/pr.rs b/services/worker/src/passes/pr.rs index 4458097ee..14a821290 100644 --- a/services/worker/src/passes/pr.rs +++ b/services/worker/src/passes/pr.rs @@ -1476,6 +1476,106 @@ fn is_lockfile(path: &str) -> bool { /// copied, every step outside this PR with its owner, and Open items. The /// merge order is added once every PR of a multi-repo run exists /// ([`link_siblings`]). +/// Puts `items` under the Open items of a pull request that is already open. +/// The rest of the description stays as it is. +pub async fn put_open_items( + github: &GitHubClient, + owner: &str, + repo: &str, + number: u64, + body: &str, + items: &[super::proof::Finding], +) { + let (mut owned, rest) = super::completeness::take_owned(body); + owned.open_items = super::proof::gaps_section(items); + let unfinished = super::proof::unfinished_section(items); + if !unfinished.is_empty() { + owned.unfinished = unfinished; + } + let out = super::completeness::assemble(&rest, &owned); + if out != body { + if let Err(e) = github.update_pr_body(owner, repo, number, &out).await { + warn!(pr_number = number, error = %e, "Could not list the open items on the PR"); + } + } +} + +/// The description once the checks have run on the open pull request: what +/// they found goes in CoderHelm's own sections, from what they checked and not +/// through the writer, so this costs no model call. The holds that keep it a +/// draft are registered here. +pub async fn apply_checks( + state: &WorkerState, + msg: &TicketMessage, + github: &GitHubClient, + run_id: &str, + plan: &PlanResult, + number: u64, + proof: &Proof<'_>, +) { + let repo = format!("{}/{}", msg.repo_owner, msg.repo_name); + if let Some(t) = proof.test_fix { + super::test_fix::register_pr(state, msg, run_id, number, t).await; + } + if let Some(f) = proof.feature { + super::feature::register_pr(state, msg, run_id, number, f).await; + } + let body = match github + .get_pull_request(&msg.repo_owner, &msg.repo_name, number) + .await + { + Ok(p) => p["body"].as_str().unwrap_or("").to_string(), + Err(e) => { + warn!(pr_number = number, error = %e, "Could not read the PR to add the checks' results"); + return; + } + }; + let out = with_checks(&body, plan, proof, &repo); + if out != body { + if let Err(e) = github + .update_pr_body(&msg.repo_owner, &msg.repo_name, number, &out) + .await + { + warn!(pr_number = number, error = %e, "Could not add the checks' results to the PR"); + } + } +} + +/// Heading over what only a person can check, when the checks found some. +const MANUAL_HEADING: &str = "**Check by hand**"; + +/// [`apply_checks`]'s description. Running it twice gives the same text. +fn with_checks(body: &str, plan: &PlanResult, proof: &Proof<'_>, repo: &str) -> String { + let (owned, rest) = super::completeness::take_owned(body); + let rest = match proof.test_fix { + Some(t) => super::test_fix::shape_body(rest, t), + None => rest, + }; + let rest = match proof.feature { + Some(f) => super::feature::shape_body(rest, f), + None => rest, + }; + let rest = if !proof.manual.trim().is_empty() && !rest.contains(MANUAL_HEADING) { + format!( + "{}\n\n{MANUAL_HEADING}\n{}", + rest.trim_end(), + proof.manual.trim() + ) + } else { + rest + }; + let mut new = owned_sections(plan, proof, repo); + // What the run put there since the pull request opened stays. + new.review_fixes = owned.review_fixes; + new.open_findings = owned.open_findings; + new.objections = owned.objections; + new.merge_order = owned.merge_order; + if new.mirrors.is_empty() { + new.mirrors = owned.mirrors; + } + super::completeness::assemble(&rest, &new) +} + fn owned_sections(plan: &PlanResult, proof: &Proof<'_>, repo: &str) -> super::completeness::Owned { let small_test_fix = proof.test_fix.is_some_and(|t| t.small); super::completeness::Owned { @@ -1955,6 +2055,59 @@ async fn fetch_pr_template( None } +#[cfg(test)] +mod check_results_tests { + use super::{with_checks, PlanResult, Proof}; + use crate::passes::proof; + + fn empty_plan() -> PlanResult { + PlanResult { + proposal: String::new(), + tasks: String::new(), + spec: String::new(), + design: String::new(), + repo_tasks: vec![], + fix: None, + } + } + + fn proof_of<'a>(gaps: &'a str, manual: &'a str) -> Proof<'a> { + Proof { + evidence: "", + gaps, + unfinished: "", + manual, + ci: &[], + mirrors: &[], + log: None, + links: "", + test_fix: None, + feature: None, + keep_commits: false, + } + } + + /// The checks run on the open pull request: their results reach its + /// description without the writer, and a fresh step doing it again changes + /// nothing. + #[test] + fn the_checks_results_reach_the_open_descriptions_sections() { + let item = proof::blocked_item("The new-feature rules", "new items aren't registered"); + let gaps = proof::gaps_section(&[item]); + let body = "Closes #4\n\n**Summary** The change.\n\n**Verification**\n1. Open it."; + let plan = empty_plan(); + let manual = "1. Try it on a phone."; + let once = with_checks(body, &plan, &proof_of(&gaps, manual), "a/b"); + assert!(once.contains("**Summary** The change."), "{once}"); + assert!(once.contains("## Open items"), "{once}"); + assert!(once.contains("new items aren't registered"), "{once}"); + assert!(once.contains("Try it on a phone."), "{once}"); + assert!(proof::holds_blocked(&once)); + let twice = with_checks(&once, &plan, &proof_of(&gaps, manual), "a/b"); + assert_eq!(once, twice); + } +} + #[cfg(test)] mod refresh_tests { use super::{ diff --git a/services/worker/src/passes/proof.rs b/services/worker/src/passes/proof.rs index 3f313cbac..808ff744f 100644 --- a/services/worker/src/passes/proof.rs +++ b/services/worker/src/passes/proof.rs @@ -20,8 +20,9 @@ use crate::passes::plan::PlanResult; use crate::passes::FileCache; use crate::WorkerState; -/// How many fix rounds a gap gets before the PR opens with it named. -pub const MAX_FIX_ROUNDS: u32 = 1; +/// How many fix rounds a run's gaps get before the PR opens with them named, +/// across all the run's steps. +pub const MAX_FIX_ROUNDS: u32 = super::run_guard::MAX_PROOF_FIX_ROUNDS; /// What every change must do, whatever it touches. Each rule is a way a /// change shipped resting on a guess. @@ -341,7 +342,7 @@ impl RunEvidence { } /// One of the things the gate judges. -#[derive(Debug, Clone, Default, PartialEq, Deserialize)] +#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, Deserialize)] pub struct Finding { /// One of the judge's points: `external_fact`, `impact`, `logging`, /// `assumption`, `structured_field`, `survey`, `silent_fallback`, @@ -402,7 +403,7 @@ impl Finding { match self.point.trim() { "ci_pending" => Settler::Ci, "manual_check" => Settler::Person, - "end_to_end" | "optional_task" => Settler::Owner, + "end_to_end" | "optional_task" | "check_blocked" | "rule_failing" => Settler::Owner, _ => Settler::Proof, } } @@ -410,6 +411,8 @@ impl Finding { fn label(&self) -> &str { match self.point.trim() { "ci_pending" => "Waiting on CI", + "check_blocked" => "Check not passed", + "rule_failing" => "New-feature rule failing", "manual_check" => "Check by hand", "unrun_check" => "Check not run", "external_fact" => "Unconfirmed external field or behaviour", @@ -1244,16 +1247,40 @@ const CI_MARK: &str = ""; /// The mark on each security item: while one is in the description the pull /// request stays a draft (see `resume::mark_pr_ready`). pub const SECURITY_MARK: &str = ""; +/// On an Open item for a check that would once have stopped the pull request: +/// the pull request is open, and stays a draft while this line is there. +pub const BLOCKED_MARK: &str = ""; /// Whether a finding is a security issue or a security check that didn't run. fn is_security(f: &Finding) -> bool { matches!(f.point.trim(), "security" | "security_unchecked") } +/// An Open item for a check the change didn't pass. The pull request is +/// already open, so a check can't stop it: it holds the draft instead, until a +/// person deals with it. +pub fn blocked_item(check: &str, why: &str) -> Finding { + Finding { + point: "check_blocked".to_string(), + detail: format!("{check}: {}", why.trim()), + settle: "Fix it on this branch; the pull request stays a draft while this line is here \ + (delete it once it's dealt with)." + .to_string(), + ..Default::default() + } +} + +/// Whether the description lists a check the change didn't pass. +pub fn holds_blocked(body: &str) -> bool { + body.contains(BLOCKED_MARK) +} + /// One Open items line, with the mark its settler needs. fn item_line(f: &Finding) -> String { if is_security(f) { format!("{} {SECURITY_MARK}", f.line()) + } else if f.point.trim() == "check_blocked" { + format!("{} {BLOCKED_MARK}", f.line()) } else { f.line() } @@ -1566,62 +1593,134 @@ pub struct Work<'a> { /// Generated files their generator settled (`generators::GateOk`): /// never planned work left for the coder. pub generated: &'a [String], + /// What the checks found and how many fix rounds they took in this run: + /// a new step goes on from here, it doesn't start over. + pub ledger: &'a super::run_guard::LedgerCell, +} + +impl Work<'_> { + /// Saves the ledger: before a round starts and after it ends, so the count + /// survives the step being cut off in the middle. + pub async fn save_ledger(&self) { + self.ledger + .save(self.state, &self.msg.team_id, self.run_id) + .await; + } + + /// The branch head as it is now, empty when it can't be read. + pub async fn head(&self) -> String { + self.github + .get_ref(&self.msg.repo_owner, &self.msg.repo_name, self.branch) + .await + .unwrap_or_default() + } + + /// Tells the run's guard what a check reports. + pub async fn report_findings(&self, check: &'static str, open: usize) { + use super::run_guard::{progress, Progress}; + progress( + self.state, + &self.msg.team_id, + self.run_id, + Progress::Findings(check, open), + ) + .await; + } } -/// Judges the change, runs the fix round a gap earns, and judges again. +/// Judges the change, runs the fix rounds a gap earns, and judges again. /// Returns what is still open when the PR is about to open: proof gaps, /// checks the PR's CI will settle, and checks only a person can do (empty /// when everything is proven or the judge couldn't answer). `evidence` gains /// what the fix round looked up. +/// +/// The rounds and the last result are the run's, not this step's +/// ([`Work::ledger`]): the judge runs again only when the code changed since +/// the last time, and a round with no fewer gaps ends the fixing. pub async fn prove( w: &Work<'_>, evidence: &mut RunEvidence, usage: &mut TokenUsage, has_time: impl Fn() -> bool, ) -> Vec { - let mut rounds = 0; loop { - let pass_start = std::time::Instant::now(); - let usage_before = usage.clone(); - let judged = judge( - w.state, - w.msg, - w.github, - w.branch, - w.plan, - w.generated, - evidence, - w.provider, - usage, - ) - .await - .map(|f| drop_settled_generated(f, w.generated)); - let recorded = recorded_gaps(evidence).len(); - let findings = with_checklist( - with_recorded(judged, evidence), - w.plan.fix.as_ref(), - &format!("{}/{}", w.msg.repo_owner, w.msg.repo_name), - ); - super::write_pass_trace( - w.state, - &w.msg.team_id, - w.run_id, - "proof", - pass_start, - &usage_before, - usage, - None, - ) - .await; - info!( - run_id = w.run_id, - judged = findings.is_some(), - gaps = findings.as_ref().map_or(0, Vec::len), - recorded, - rounds, - "Proof check complete" - ); - match next(findings.as_deref(), rounds, has_time()) { + let head = w.head().await; + let standing = w.ledger.update(|l| { + l.proof.unchanged(&head).then(|| { + l.proof.reused(); + l.proof_findings.clone() + }) + }); + let findings = if let Some(standing) = standing { + info!(run_id = w.run_id, %head, "Proof check: the code didn't change, its result stands"); + super::add_progress_note( + w.state, + &w.msg.team_id, + w.run_id, + "Proof check: the code hasn't changed since the last check, so that result stands", + ) + .await; + // What only code sets (which CI command settles a finding) isn't + // stored: it is worked out again from this run's CI. + standing.map(|f| classify(f, evidence)) + } else { + let pass_start = std::time::Instant::now(); + let usage_before = usage.clone(); + let judged = judge( + w.state, + w.msg, + w.github, + w.branch, + w.plan, + w.generated, + evidence, + w.provider, + usage, + ) + .await + .map(|f| drop_settled_generated(f, w.generated)); + let recorded = recorded_gaps(evidence).len(); + let findings = with_checklist( + with_recorded(judged, evidence), + w.plan.fix.as_ref(), + &format!("{}/{}", w.msg.repo_owner, w.msg.repo_name), + ); + super::write_pass_trace( + w.state, + &w.msg.team_id, + w.run_id, + "proof", + pass_start, + &usage_before, + usage, + None, + ) + .await; + info!( + run_id = w.run_id, + judged = findings.is_some(), + gaps = findings.as_ref().map_or(0, Vec::len), + recorded, + rounds = w.ledger.update(|l| l.proof.rounds), + "Proof check complete" + ); + let open = findings.as_deref().map_or(0, proof_gaps); + w.ledger.update(|l| { + l.proof.checked(&head, open); + l.proof_findings = findings.clone(); + }); + w.save_ledger().await; + findings + }; + w.report_findings("proof", findings.as_deref().map_or(0, proof_gaps)) + .await; + let (rounds, may_fix) = w + .ledger + .update(|l| (l.proof.rounds, l.proof.may_fix(MAX_FIX_ROUNDS))); + // Only a round that could run asks about time: a "no" for one that + // couldn't would send the run to a fresh step for nothing. + let fix_ok = may_fix && has_time(); + match next(findings.as_deref(), rounds, fix_ok) { Next::Open => { if findings.is_some() { super::add_progress_note( @@ -1665,7 +1764,8 @@ pub async fn prove( } Next::FixRound => { let gaps = findings.unwrap_or_default(); - rounds += 1; + w.ledger.update(|l| l.proof.start_fix()); + w.save_ledger().await; super::add_progress_note( w.state, &w.msg.team_id, @@ -1713,6 +1813,8 @@ pub async fn prove( None, ) .await; + w.ledger.update(|l| l.proof.end_fix()); + w.save_ledger().await; match fixed { Ok(r) => evidence.merge(r.evidence), Err(e) => { @@ -1720,7 +1822,8 @@ pub async fn prove( return gaps; } } - let _ = super::update_pass(w.state, &w.msg.team_id, w.run_id, "review").await; + let _ = + super::update_pass(w.state, &w.msg.team_id, w.run_id, super::PASS_CHECKS).await; } } } @@ -1896,7 +1999,8 @@ mod tests { fn a_gap_earns_one_fix_round_then_opens_with_it_named() { let gaps = [finding("impact", "affected records not counted")]; assert_eq!(next(Some(&gaps), 0, true), Next::FixRound); - assert_eq!(next(Some(&gaps), 1, true), Next::OpenWithGaps); + assert_eq!(next(Some(&gaps), 1, true), Next::FixRound); + assert_eq!(next(Some(&gaps), MAX_FIX_ROUNDS, true), Next::OpenWithGaps); assert_eq!(next(Some(&gaps), 0, false), Next::OpenWithGaps); assert_eq!(next(Some(&[]), 0, true), Next::Open); // A judge that couldn't answer never holds the PR. @@ -2745,10 +2849,13 @@ mod planned_work_tests { assert_eq!(next(Some(&gaps), 0, true), Next::FixRound); // No round left: unfinished (the PR opens as a draft with it at // the top, never without a PR). - assert_eq!(next(Some(&gaps), 1, true), Next::Unfinished); + assert_eq!(next(Some(&gaps), MAX_FIX_ROUNDS, true), Next::Unfinished); assert_eq!(next(Some(&gaps), 0, false), Next::Unfinished); // Other gaps alone still open with Open items. - assert_eq!(next(Some(&gaps[1..]), 1, true), Next::OpenWithGaps); + assert_eq!( + next(Some(&gaps[1..]), MAX_FIX_ROUNDS, true), + Next::OpenWithGaps + ); let top = unfinished_section(&gaps); assert!(top.starts_with(UNFINISHED_START)); assert!(top.contains("## Not finished")); diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 2df55a0fb..e1ca956a2 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -4569,6 +4569,9 @@ pub(crate) fn draft_hold(body: &str, title: &str, proven: bool) -> Option<&'stat if super::proof::holds_unfinished(body) { return Some("planned work not done is listed in the description"); } + if super::proof::holds_blocked(body) { + return Some("a check the change didn't pass is listed in the description"); + } if super::own_review::hold(body).is_some() { return Some("CoderHelm's own review findings are open in the description"); } @@ -4783,6 +4786,13 @@ async fn record_own_review_progress( { warn!(run_id, error = %e, "Could not record own review progress (non-fatal)"); } + super::run_guard::progress( + state, + team_id, + run_id, + super::run_guard::Progress::Findings("own_review", open), + ) + .await; } /// The findings a review-fix round was asked to fix: the `- [ ]` lines diff --git a/services/worker/src/passes/run_ceiling.rs b/services/worker/src/passes/run_ceiling.rs new file mode 100644 index 000000000..878072156 --- /dev/null +++ b/services/worker/src/passes/run_ceiling.rs @@ -0,0 +1,386 @@ +//! The absolute ceiling of a run: what makes "a run cannot loop without end" +//! true whatever the code above it does. +//! +//! `run_guard` stops a run that makes no progress, and real progress resets it. +//! This doesn't reset. Each run record counts passes, continuations, spend and +//! worked time for the run's whole life (`ceil_*`), and only adds to them. A +//! person's Retry starts a new run, with a new record: that is the one new +//! allowance. The layers hold independently: +//! +//! 1. The counts, on the run record, added to by every pass and continuation +//! (`run_guard`) and every message's time ([`worked`]). +//! 2. [`admit`], at the one place the worker picks up a message, before any +//! dispatch: a message of a run over its ceiling doesn't run, whatever sent +//! it. `WorkerMessage::run_ref` has no catch-all, so a new message kind has to +//! say whether it belongs to a run or it doesn't compile. +//! 3. Model calls: `UsageMeter::admit`, which every model call must go through +//! (`common::model_call_sites` fails the build otherwise), refuses once the +//! run's allowance is spent or closed. +//! 4. The stuck-run sweep (`lambda/stuck-run-cleanup/handler.py`) reads the same +//! counts outside the worker and hands off any run over them. +//! +//! Worked time is the time the worker spent on the run, not the calendar: a +//! pull request can rightly wait days for CI or a person, and that costs nothing. +//! +//! Sized for the largest real work the caps allow, far above any loop's stop by +//! `run_guard`: the existing 50-step ceiling at about $4 and 15 minutes a step, +//! plus the rounds on the pull request. + +use std::sync::Arc; + +use aws_sdk_dynamodb::types::AttributeValue; +use common::messages::WorkerMessage; +use common::usage::RunAllowance; +use tracing::warn; + +use super::{attr_n, attr_s}; +use crate::WorkerState; + +/// Passes in a run's life. The record keeps at most 200 in its history +/// (`run_lists::MAX_PASSES`), and a 50-step run with its fix rounds and a long +/// conversation on its pull request stays under this. +pub const MAX_RUN_PASSES: u32 = 300; +/// Continuations in a run's life: the step ceiling that was already there. +pub const MAX_RUN_CONTINUATIONS: u32 = super::steps::MAX_RUN_STEPS; +/// Hours the worker spends on a run: 50 steps of 15 minutes, 12.5 hours, and +/// room for the fix rounds on the pull request. +pub const MAX_RUN_WORKED_SECS: u64 = 16 * 3600; +/// USD in a run's life: 50 steps at about $4. +pub const MAX_RUN_SPEND_USD: f64 = 200.0; + +/// What a step that never reported its end counts for: all of its time. +const STEP_SECS: u64 = 900; + +/// A run's counts, for its whole life. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Totals { + pub passes: u32, + pub continuations: u32, + pub worked_secs: u64, + pub spend_usd: f64, +} + +/// Which ceiling a run is over. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Over { + Passes, + Continuations, + WorkedTime, + Spend, +} + +impl Over { + /// What analytics counts (`loop_stop_reason`). The sweep writes the same. + pub fn code(self) -> &'static str { + match self { + Over::Passes => "ceiling_passes", + Over::Continuations => "ceiling_continuations", + Over::WorkedTime => "ceiling_worked_time", + Over::Spend => "ceiling_spend", + } + } + + pub fn reason(self) -> String { + let what = match self { + Over::Passes => format!("it reached the limit of {MAX_RUN_PASSES} steps of work"), + Over::Continuations => { + format!("it reached the limit of {MAX_RUN_CONTINUATIONS} continuations") + } + Over::WorkedTime => format!( + "it reached the limit of {} hours of work", + MAX_RUN_WORKED_SECS / 3600 + ), + Over::Spend => format!("it reached the limit of ${MAX_RUN_SPEND_USD:.0} of model use"), + }; + format!( + "CoderHelm ended this run: {what}, and nothing further runs on it. Everything it did \ + is on its branch and draft pull request. Retry starts a new run from there." + ) + } +} + +impl Totals { + /// Whether this run is over its ceiling. + pub fn over(&self) -> Option { + if self.spend_usd > MAX_RUN_SPEND_USD { + return Some(Over::Spend); + } + if self.worked_secs > MAX_RUN_WORKED_SECS { + return Some(Over::WorkedTime); + } + if self.passes > MAX_RUN_PASSES { + return Some(Over::Passes); + } + if self.continuations > MAX_RUN_CONTINUATIONS { + return Some(Over::Continuations); + } + None + } + + pub fn from_item(item: &std::collections::HashMap) -> Self { + let n = |k: &str| -> f64 { + item.get(k) + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse().ok()) + .unwrap_or(0.0) + }; + Self { + passes: n("ceil_passes") as u32, + continuations: n("ceil_continuations") as u32, + worked_secs: n("ceil_worked_secs") as u64, + spend_usd: n("ceil_spend_usd"), + } + } + + /// What is left to spend, never below nothing. + pub fn spend_left(&self) -> f64 { + (MAX_RUN_SPEND_USD - self.spend_usd).max(0.0) + } +} + +/// What the one entry point needs from the outside world. +#[allow(async_fn_in_trait)] +pub trait EntryGate { + /// The run's counts. `None` when they can't be read: the entry fails open, + /// and the model and sweep layers still hold. + async fn totals(&self, team_id: &str, run_id: &str) -> Option; + /// Ends a run over its ceiling, once, without running the message. + async fn end_over(&self, message: &WorkerMessage, over: Over); +} + +/// The entry guard: whether this message may run. Comes before any dispatch. +pub async fn admit(gate: &G, message: &WorkerMessage) -> bool { + let Some((team_id, run_id)) = message.run_ref() else { + return true; + }; + let Some(totals) = gate.totals(team_id, run_id).await else { + return true; + }; + match totals.over() { + None => true, + Some(over) => { + warn!( + team_id, + run_id, + stop_reason = over.code(), + ?totals, + "Run over its ceiling: the message doesn't run" + ); + gate.end_over(message, over).await; + false + } + } +} + +/// The real thing, on the run record. +pub struct DynamoGate<'a> { + pub state: &'a WorkerState, +} + +impl EntryGate for DynamoGate<'_> { + async fn totals(&self, team_id: &str, run_id: &str) -> Option { + load(self.state, team_id, run_id).await + } + + async fn end_over(&self, message: &WorkerMessage, over: Over) { + let Some((team_id, run_id)) = message.run_ref() else { + return; + }; + let state = self.state; + super::run_guard::record_stop(state, team_id, run_id, over.code(), &over.reason()).await; + // Fresh ticket steps have what a draft takes; the rest have their PR. + if let WorkerMessage::Ticket(msg) = message { + let checkpoint = super::load_checkpoint(state, team_id, run_id).await; + super::run_guard::end_if_stopped( + state, + msg, + run_id, + checkpoint.as_ref().map(|c| c.1.as_str()), + ) + .await; + } else { + super::run_guard::settle_open_pr(state, team_id, run_id).await; + } + } +} + +async fn load(state: &WorkerState, team_id: &str, run_id: &str) -> Option { + match state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .projection_expression("ceil_passes, ceil_continuations, ceil_worked_secs, ceil_spend_usd") + .send() + .await + { + Ok(out) => out.item().map(Totals::from_item), + Err(e) => { + warn!(run_id, error = %e, "Run ceiling: could not read the run"); + None + } + } +} + +/// Runs a message with its model calls metered against what the run has left, +/// and adds its time to the run's. A run with no record yet (a fresh ticket) has +/// its whole allowance. +pub async fn worked( + state: &WorkerState, + message: &WorkerMessage, + fut: F, +) -> F::Output { + let run = message + .run_ref() + .map(|(t, r)| (t.to_string(), r.to_string())); + let left = match &run { + Some((t, r)) => load(state, t, r) + .await + .map_or(MAX_RUN_SPEND_USD, |t| t.spend_left()), + None => MAX_RUN_SPEND_USD, + }; + if let Some((t, r)) = &run { + mark_entered(state, t, r).await; + } + let started = std::time::Instant::now(); + let out = common::usage::with_run_allowance(Arc::new(RunAllowance::new(left)), fut).await; + if let Some((t, r)) = &run { + mark_left(state, t, r, started.elapsed().as_secs()).await; + } + out +} + +/// A step is working. One still marked as working from before never reported +/// its end (the function was killed), and counts for all of its time. +async fn mark_entered(state: &WorkerState, team_id: &str, run_id: &str) { + let prior = 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 ceil_entered_at = :now") + .condition_expression("attribute_exists(run_id)") + .expression_attribute_values(":now", attr_s(&chrono::Utc::now().to_rfc3339())) + .return_values(aws_sdk_dynamodb::types::ReturnValue::UpdatedOld) + .send() + .await + .ok() + .and_then(|o| o.attributes) + .is_some_and(|a| a.contains_key("ceil_entered_at")); + if prior { + add_worked(state, team_id, run_id, STEP_SECS, false).await; + } +} + +async fn mark_left(state: &WorkerState, team_id: &str, run_id: &str, secs: u64) { + add_worked(state, team_id, run_id, secs, true).await; +} + +async fn add_worked(state: &WorkerState, team_id: &str, run_id: &str, secs: u64, left: bool) { + let expr = if left { + "ADD ceil_worked_secs :s REMOVE ceil_entered_at" + } else { + "ADD ceil_worked_secs :s" + }; + if let Err(e) = 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(expr) + .condition_expression("attribute_exists(run_id)") + .expression_attribute_values(":s", attr_n(secs)) + .send() + .await + { + warn!(run_id, error = %e, "Run ceiling: could not add the step's time"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn each_ceiling_fires_on_its_own() { + assert_eq!(Totals::default().over(), None); + let at = Totals { + passes: MAX_RUN_PASSES, + continuations: MAX_RUN_CONTINUATIONS, + worked_secs: MAX_RUN_WORKED_SECS, + spend_usd: MAX_RUN_SPEND_USD, + }; + assert_eq!(at.over(), None, "at the ceiling is still under it"); + let over = |f: fn(&mut Totals)| { + let mut t = Totals::default(); + f(&mut t); + t.over() + }; + assert_eq!(over(|t| t.passes = MAX_RUN_PASSES + 1), Some(Over::Passes)); + assert_eq!( + over(|t| t.continuations = MAX_RUN_CONTINUATIONS + 1), + Some(Over::Continuations) + ); + assert_eq!( + over(|t| t.worked_secs = MAX_RUN_WORKED_SECS + 1), + Some(Over::WorkedTime) + ); + assert_eq!( + over(|t| t.spend_usd = MAX_RUN_SPEND_USD + 0.01), + Some(Over::Spend) + ); + } + + /// The numbers are big enough for what the existing caps allow, and the + /// no-progress guard always speaks first in a loop. + #[test] + fn the_ceiling_clears_the_largest_real_work_and_sits_above_the_guard() { + use super::super::run_guard as g; + const { assert!(MAX_RUN_PASSES >= 3 * super::super::steps::MAX_RUN_STEPS) }; + const { assert!(MAX_RUN_WORKED_SECS >= 50 * 900) }; + const { assert!(MAX_RUN_PASSES > g::MAX_TRANSITIONS_WITHOUT_PROGRESS) }; + const { assert!(MAX_RUN_CONTINUATIONS > g::MAX_CONTINUATIONS_WITHOUT_PROGRESS) }; + const { assert!(MAX_RUN_SPEND_USD >= 50.0 * 4.0) }; + const { assert!(MAX_RUN_SPEND_USD > g::MAX_SPEND_WITHOUT_PROGRESS_USD) }; + } + + #[test] + fn the_sweep_reads_the_same_numbers_and_the_same_names() { + let src = include_str!("../../../../lambda/stuck-run-cleanup/handler.py"); + assert!(src.contains(&format!("MAX_RUN_PASSES = {MAX_RUN_PASSES}\n"))); + assert!(src.contains(&format!( + "MAX_RUN_CONTINUATIONS = {MAX_RUN_CONTINUATIONS}\n" + ))); + assert!(src.contains(&format!("MAX_RUN_WORKED_SECS = {MAX_RUN_WORKED_SECS}\n"))); + assert!(src.contains(&format!("MAX_RUN_SPEND_USD = {MAX_RUN_SPEND_USD:.1}\n"))); + for name in [ + "ceil_passes", + "ceil_continuations", + "ceil_worked_secs", + "ceil_spend_usd", + "guard_open", + "loop_stop_reason", + "loop_stop_detail", + ] { + assert!(src.contains(name), "{name}"); + } + for over in [ + Over::Passes, + Over::Continuations, + Over::WorkedTime, + Over::Spend, + ] { + assert!(src.contains(over.code()), "{}", over.code()); + } + } + + #[test] + fn the_reason_says_what_to_do() { + let why = Over::Spend.reason(); + assert!(why.contains("$200"), "{why}"); + assert!(why.contains("Retry starts a new run"), "{why}"); + } +} diff --git a/services/worker/src/passes/run_guard.rs b/services/worker/src/passes/run_guard.rs new file mode 100644 index 000000000..9d45595a1 --- /dev/null +++ b/services/worker/src/passes/run_guard.rs @@ -0,0 +1,1314 @@ +//! One progress guard for a whole run, and the limits it keeps. +//! +//! A small ticket once finished all its tasks and then spent 2.5 hours and +//! $41.96 without a pull request. Each 15-minute step resumed at the checks +//! before the pull request, re-ran them from nothing, and started fresh fix +//! rounds, because every round counter was a local variable of that step. Every +//! fix was a commit, so the stall detector saw progress, and the pull request +//! came last, with whatever time was left. +//! +//! The order is the first fix: once the work is built the draft pull request +//! opens, and the checks run on it. They can't hold it back, because it is +//! already there. +//! +//! The class of bug is a loop that only looks busy, so it is closed in one +//! place rather than in each pass: +//! +//! - Every pass goes through `update_pass`, every continuation through +//! `try_auto_continue`, and every code-writing round through +//! `implement::run`. Those three call this module, so a pass added later is +//! covered without knowing the guard exists. +//! - The guard counts pass transitions, continuations and spend since the last +//! real progress: a task completing, the pull request opening, CI going +//! green, or fewer open findings than a check has ever reported. A commit is +//! not progress. Each of these only moves one way (or is capped elsewhere), +//! so a checker that keeps finding something can't keep resetting the count. +//! - When the guard fires a run ends one way, always: a draft pull request +//! with what exists and its Open items, status `needs_input`, a plain reason +//! on the run page, one notification, and the reason recorded for analytics. +//! +//! [`Ledger`] is the other half: the pull request the run opened, what each +//! check found on which head, and how many fix rounds it took, kept across +//! steps. It is what makes "at most 2 rounds per run" and "no check runs twice on +//! the same head" true whichever step the run is in. +//! +//! Every limit is here. How they were sized is in [`worst_normal_run`], which a +//! test holds against them. + +use std::collections::BTreeMap; +use std::sync::Mutex; + +use aws_sdk_dynamodb::types::{AttributeValue, ReturnValue}; +use common::run_status::{self, EndedValues}; +use serde::{Deserialize, Serialize}; +use tracing::{info, warn}; + +use super::proof::{self, Finding}; +use super::run_ceiling::Totals; +use super::{add_progress_note, attr_n, attr_s, feature, test_fix}; +use crate::models::TicketMessage; +use crate::WorkerState; + +type BoxError = Box; + +// ── Limits ───────────────────────────────────────────────────────────────── + +/// Proof-check fix rounds in one run, across all its steps. +pub const MAX_PROOF_FIX_ROUNDS: u32 = 2; +/// New-feature-rule fix rounds in one run, across all its steps. +pub const MAX_RULES_FIX_ROUNDS: u32 = 2; +/// Link and redirect fix rounds in one run, across all its steps. +pub const MAX_LINK_FIX_ROUNDS: u32 = 1; +/// Failing-test fix rounds in one run, across all its steps. +pub const MAX_TEST_FIX_ROUNDS: u32 = 2; +/// Continuations a run may take once its tasks are done. Findings going down +/// don't reset this: opening the pull request and checking it take one step, +/// and three more fresh 15-minute steps are far more than finished work needs. +pub const MAX_CONTINUATIONS_AFTER_WORK: u32 = 3; +/// Continuations without progress while the tasks are still being built: one +/// task spread over six full steps (90 minutes) isn't happening. +pub const MAX_CONTINUATIONS_WITHOUT_PROGRESS: u32 = 6; +/// Pass transitions without progress. See [`worst_normal_run`]. +pub const MAX_TRANSITIONS_WITHOUT_PROGRESS: u32 = 40; +/// Spend without progress, in USD, whichever pass or step spent it. Only real +/// progress lowers it. A full 15-minute step costs about $4 (the run that +/// prompted this guard spent $41.96 in eleven), so this is five full steps with +/// nothing to show, about half of that run. +pub const MAX_SPEND_WITHOUT_PROGRESS_USD: f64 = 20.0; + +/// The most pass transitions a normal large ticket makes between two progress +/// events, with every fix round every check is allowed. A pass count is bounded +/// by the caps themselves, so this is the worst a run that isn't looping can +/// reach, and the guard must sit above both stretches. +/// +/// - From the last task done to the pull request: test, its fix, security, its +/// fix, the re-audit, a generator fix, and the pull request. +/// - From the pull request to CI's first green: the checks, every check's +/// rounds at two transitions a round (to `implement` and back), every +/// automatic push the run is allowed (`MAX_AUTO_FIX_PUSHES`) and the own-review +/// rounds, each `implement` then `review`. +pub const fn worst_normal_run() -> u32 { + let per_round = 2; + let before_pr = 7; + let after_pr = 1 + per_round + * (MAX_PROOF_FIX_ROUNDS + + MAX_RULES_FIX_ROUNDS + + MAX_LINK_FIX_ROUNDS + + MAX_TEST_FIX_ROUNDS + + super::MAX_AUTO_FIX_PUSHES + + super::own_review::MAX_FIX_ROUNDS); + if before_pr > after_pr { + before_pr + } else { + after_pr + } +} + +const _: () = assert!(MAX_TRANSITIONS_WITHOUT_PROGRESS >= worst_normal_run()); + +// ── The guard's state ────────────────────────────────────────────────────── + +/// Why the guard ended a run. The stored code is what analytics counts. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Trip { + /// Finished work kept continuing without a pull request. + ContinuationsAfterWork, + /// Continuations without progress, tasks still open. + Continuations, + /// Pass transitions without progress. + Transitions, + /// Spend without progress. + Spend, +} + +impl Trip { + pub fn code(self) -> &'static str { + match self { + Trip::ContinuationsAfterWork => "continuations_after_work", + Trip::Continuations => "continuations", + Trip::Transitions => "pass_transitions", + Trip::Spend => "spend", + } + } + + /// What the run page says, in plain words. + pub fn reason(self, g: &GuardState) -> String { + let what = match self { + Trip::ContinuationsAfterWork => format!( + "its tasks were done and it had continued {} more times without finishing", + g.after_work + ), + Trip::Continuations => format!( + "it continued {} times without finishing another task", + g.continuations + ), + Trip::Transitions => format!( + "it moved between steps {} times with no task finished, no fewer open findings \ + and no green CI", + g.transitions + ), + Trip::Spend => format!( + "it spent ${:.2} with no task finished, no fewer open findings and no green CI", + g.spend_usd + ), + }; + format!( + "CoderHelm stopped this run and handed it to you: {what}. Everything it did is on the \ + draft pull request, and what is still open is listed there under Open items. Push to \ + the branch or comment on the pull request and CoderHelm picks it up from there." + ) + } +} + +/// Real progress: what resets the guard's counts. +#[derive(Debug, Clone, PartialEq)] +pub enum Progress { + /// This many of the plan's tasks are done. + TasksDone(usize), + /// Every required task is done. + WorkDone, + /// The pull request is open. + PrOpen, + /// CI came back green. + CiGreen, + /// A check reports this many open findings. + Findings(&'static str, usize), +} + +/// The guard's counts, kept on the run record (`run_guard`). +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct GuardState { + /// Pass transitions since the last progress. + #[serde(default)] + pub transitions: u32, + /// Continuations since the last progress. + #[serde(default)] + pub continuations: u32, + /// Continuations since the tasks were done (never reset by findings). + #[serde(default)] + pub after_work: u32, + /// Spend since the last progress, from every model call of every step. + #[serde(default)] + pub spend_usd: f64, + #[serde(default)] + pub tasks_done: usize, + #[serde(default)] + pub work_done: bool, + #[serde(default)] + pub pr_open: bool, + /// Each check's lowest open-finding count so far. Only a new low counts: + /// a checker reporting 2, 4, 3, 2 has made no progress at all. + #[serde(default)] + pub low: BTreeMap, +} + +impl GuardState { + /// One pass started, with what was spent since the guard last looked. + pub fn on_pass(&mut self, spent: f64) { + self.transitions = self.transitions.saturating_add(1); + self.spend_usd += spent.max(0.0); + } + + /// One continuation, with what was spent since the guard last looked. + pub fn on_continuation(&mut self, spent: f64) { + self.continuations = self.continuations.saturating_add(1); + self.spend_usd += spent.max(0.0); + if self.work_done { + self.after_work = self.after_work.saturating_add(1); + } + } + + /// Applies a report. True (and the counts reset) when it is real progress. + /// This is the only place the spend comes down, and each kind of progress + /// moves one way, so nothing can reset it twice with the same news. + pub fn apply(&mut self, p: &Progress) -> bool { + let real = match p { + Progress::TasksDone(n) => { + let more = *n > self.tasks_done; + self.tasks_done = self.tasks_done.max(*n); + more + } + Progress::WorkDone => !std::mem::replace(&mut self.work_done, true), + Progress::PrOpen => !std::mem::replace(&mut self.pr_open, true), + Progress::CiGreen => true, + Progress::Findings(check, n) => match self.low.get(*check).copied() { + // The first report is where the check starts, not progress. + None => { + self.low.insert((*check).to_string(), *n); + false + } + Some(low) if *n < low => { + self.low.insert((*check).to_string(), *n); + true + } + Some(_) => false, + }, + }; + if real { + self.reset(); + } + real + } + + fn reset(&mut self) { + self.transitions = 0; + self.continuations = 0; + self.spend_usd = 0.0; + } + + /// A person acted on the run: everything starts again from here, and what + /// the checks have reported stands. + pub fn person_acted(&mut self) { + self.reset(); + self.after_work = 0; + } + + /// Whether the run has gone too far without progress. + pub fn trip(&self) -> Option { + if self.after_work > MAX_CONTINUATIONS_AFTER_WORK { + return Some(Trip::ContinuationsAfterWork); + } + if self.continuations > MAX_CONTINUATIONS_WITHOUT_PROGRESS { + return Some(Trip::Continuations); + } + if self.transitions > MAX_TRANSITIONS_WITHOUT_PROGRESS { + return Some(Trip::Transitions); + } + if self.spend_usd > MAX_SPEND_WITHOUT_PROGRESS_USD { + return Some(Trip::Spend); + } + None + } +} + +/// What this message's model calls cost since the guard last looked: live, +/// because a step's usage reaches the run record only at its end, and a step +/// cut off by the time limit never writes it at all. +fn take_spend() -> f64 { + common::usage::take_run_spend() +} + +/// The error a pass stops with once the guard fired. `orchestrate_ticket` and +/// the worker's resume and feedback handlers end the run on it. +#[derive(Debug)] +pub struct LoopStopped(pub String); + +impl std::fmt::Display for LoopStopped { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0) + } +} + +impl std::error::Error for LoopStopped {} + +// ── The guard on the run record ──────────────────────────────────────────── + +struct Loaded { + guard: GuardState, + /// The run's counts for its whole life (see `run_ceiling`). + totals: Totals, + /// The reason, once the guard fired and no person has acted since. + stopped: Option, +} + +/// Fails open: a read that doesn't answer never stops a run. +async fn load(state: &WorkerState, team_id: &str, run_id: &str) -> Option { + let out = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .projection_expression( + "run_guard, guard_open, loop_stop_detail, ceil_passes, ceil_continuations, \ + ceil_worked_secs, ceil_spend_usd", + ) + .send() + .await; + let out = match out { + Ok(o) => o, + Err(e) => { + warn!(run_id, error = %e, "Run guard: could not read the run"); + return None; + } + }; + let item = out.item()?; + Some(Loaded { + totals: Totals::from_item(item), + guard: item + .get("run_guard") + .and_then(|v| v.as_s().ok()) + .and_then(|s| serde_json::from_str(s).ok()) + .unwrap_or_default(), + stopped: item.get("guard_open").map(|_| { + item.get("loop_stop_detail") + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_else(|| "CoderHelm stopped this run and handed it to you.".to_string()) + }), + }) +} + +/// Saves the guard's counts and adds to the run's lifetime ones. Those are only +/// ever added to, and this is the one place that does for passes, continuations +/// and spend. +async fn save( + state: &WorkerState, + team_id: &str, + run_id: &str, + guard: &GuardState, + passes: u32, + continuations: u32, + spent: f64, +) { + let Ok(json) = serde_json::to_string(guard) else { + return; + }; + if let Err(e) = 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 run_guard = :g ADD ceil_passes :p, ceil_continuations :c, ceil_spend_usd :s", + ) + .condition_expression("attribute_exists(run_id)") + .expression_attribute_values(":g", attr_s(&json)) + .expression_attribute_values(":p", attr_n(passes)) + .expression_attribute_values(":c", attr_n(continuations)) + .expression_attribute_values(":s", attr_n(format!("{spent:.6}"))) + .send() + .await + { + warn!(run_id, error = %e, "Run guard: could not save its counts"); + } +} + +/// Records that a run was stopped, once. Only the first writer logs the metric +/// and the note. Also closes this message's model allowance. +pub(crate) async fn record_stop( + state: &WorkerState, + team_id: &str, + run_id: &str, + code: &str, + reason: &str, +) { + common::usage::close_run_allowance(reason); + let first = 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 guard_open = :yes, loop_stop_reason = :code, loop_stop_detail = :why, \ + loop_stopped_at = :now", + ) + .condition_expression("attribute_exists(run_id) AND attribute_not_exists(guard_open)") + .expression_attribute_values(":yes", AttributeValue::Bool(true)) + .expression_attribute_values(":code", attr_s(code)) + .expression_attribute_values(":why", attr_s(reason)) + .expression_attribute_values(":now", attr_s(&chrono::Utc::now().to_rfc3339())) + .send() + .await + .is_ok(); + if first { + // The metric filter in the monitoring stack counts this text. + warn!( + run_id, + team_id, + stop_reason = code, + "run_loop_stopped: the run is handed to a person" + ); + add_progress_note(state, team_id, run_id, reason).await; + } +} + +async fn fire( + state: &WorkerState, + team_id: &str, + run_id: &str, + trip: Trip, + guard: &GuardState, +) -> String { + let reason = trip.reason(guard); + info!( + run_id, + transitions = guard.transitions, + continuations = guard.continuations, + after_work = guard.after_work, + spend_usd = guard.spend_usd, + "Run guard: no progress" + ); + record_stop(state, team_id, run_id, trip.code(), &reason).await; + reason +} + +/// What the counts say now: the run's ceiling first, it is the harder stop. +async fn verdict( + state: &WorkerState, + team_id: &str, + run_id: &str, + guard: &GuardState, + totals: &Totals, +) -> Option { + if let Some(over) = totals.over() { + let why = over.reason(); + record_stop(state, team_id, run_id, over.code(), &why).await; + return Some(why); + } + match guard.trip() { + Some(trip) => Some(fire(state, team_id, run_id, trip, guard).await), + None => None, + } +} + +/// A pass started (from `update_pass`, so every pass). `Err` once the guard +/// has fired: the run must stop. +pub async fn on_pass(state: &WorkerState, team_id: &str, run_id: &str) -> Result<(), BoxError> { + let Some(mut l) = load(state, team_id, run_id).await else { + return Ok(()); + }; + if let Some(why) = l.stopped { + return Err(Box::new(LoopStopped(why))); + } + let spent = take_spend(); + l.guard.on_pass(spent); + l.totals.passes = l.totals.passes.saturating_add(1); + l.totals.spend_usd += spent; + save(state, team_id, run_id, &l.guard, 1, 0, spent).await; + match verdict(state, team_id, run_id, &l.guard, &l.totals).await { + Some(why) => Err(Box::new(LoopStopped(why))), + None => Ok(()), + } +} + +/// A step is about to hand off (from `try_auto_continue`, so every +/// continuation). `Some(reason)` when the next step must not start. +pub async fn on_continuation(state: &WorkerState, team_id: &str, run_id: &str) -> Option { + let mut l = load(state, team_id, run_id).await?; + if l.stopped.is_some() { + return l.stopped; + } + let spent = take_spend(); + l.guard.on_continuation(spent); + l.totals.continuations = l.totals.continuations.saturating_add(1); + l.totals.spend_usd += spent; + save(state, team_id, run_id, &l.guard, 0, 1, spent).await; + verdict(state, team_id, run_id, &l.guard, &l.totals).await +} + +/// Before a code-writing round (from `implement::run`): `Err` once the guard +/// has fired. This holds the rounds whose callers can't stop on a pass error. +pub async fn check(state: &WorkerState, team_id: &str, run_id: &str) -> Result<(), BoxError> { + match load(state, team_id, run_id).await.and_then(|l| l.stopped) { + Some(why) => Err(Box::new(LoopStopped(why))), + None => Ok(()), + } +} + +/// Reports what may be real progress. +pub async fn progress(state: &WorkerState, team_id: &str, run_id: &str, p: Progress) { + let Some(mut l) = load(state, team_id, run_id).await else { + return; + }; + let spent = take_spend(); + // What was spent before this news counts against the time before it: real + // progress clears the guard's count, never the run's lifetime one. + l.guard.spend_usd += spent; + if l.guard.apply(&p) { + info!(run_id, progress = ?p, "Run guard: progress"); + } + save(state, team_id, run_id, &l.guard, 0, 0, spent).await; +} + +/// A person acted on the run (a comment, a review): the counts start over and +/// an earlier stop no longer holds it. `loop_stop_reason` stays, for analytics. +pub async fn person_acted(state: &WorkerState, team_id: &str, run_id: &str) { + let Some(mut l) = load(state, team_id, run_id).await else { + return; + }; + l.guard.person_acted(); + let Ok(json) = serde_json::to_string(&l.guard) else { + return; + }; + if let Err(e) = 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 run_guard = :g REMOVE guard_open, loop_notified_at") + .condition_expression("attribute_exists(run_id)") + .expression_attribute_values(":g", attr_s(&json)) + .send() + .await + { + warn!(run_id, error = %e, "Run guard: could not start its counts over"); + } +} + +/// A message is ending, perhaps because a model call was refused: what it spent +/// is counted, and a run that has gone over its ceiling is marked as stopped. +async fn flush(state: &WorkerState, team_id: &str, run_id: &str) { + let Some(mut l) = load(state, team_id, run_id).await else { + return; + }; + if l.stopped.is_some() { + return; + } + let spent = take_spend(); + if spent > 0.0 { + l.guard.spend_usd += spent; + l.totals.spend_usd += spent; + save(state, team_id, run_id, &l.guard, 0, 0, spent).await; + } + let _ = verdict(state, team_id, run_id, &l.guard, &l.totals).await; +} + +/// Claims the one notification a stop sends. +async fn claim_notification(state: &WorkerState, team_id: &str, run_id: &str) -> bool { + 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 loop_notified_at = :now") + .condition_expression("attribute_not_exists(loop_notified_at)") + .expression_attribute_values(":now", attr_s(&chrono::Utc::now().to_rfc3339())) + .return_values(ReturnValue::None) + .send() + .await + .is_ok() +} + +/// A run stopped in a ticket step: when the guard fired, opens the draft (or +/// finds it) with what the checks left under Open items, and waits on a person. True when the guard had fired, so the caller doesn't +/// also salvage or fail the run the ordinary way. +pub async fn end_if_stopped( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + branch: Option<&str>, +) -> bool { + flush(state, &msg.team_id, run_id).await; + let Some(reason) = load(state, &msg.team_id, run_id) + .await + .and_then(|l| l.stopped) + else { + return false; + }; + let ledger = LedgerCell::load( + state, + &msg.team_id, + run_id, + &format!("{}/{}", msg.repo_owner, msg.repo_name), + ) + .await; + let mut items = ledger.update(|l| l.open_findings()); + items.push(proof::blocked_item("CoderHelm stopped this run", &reason)); + let notify = claim_notification(state, &msg.team_id, run_id).await; + let opened = match branch.filter(|b| !b.is_empty()) { + Some(branch) => { + super::stop_pr::open_with(state, msg, run_id, branch, &reason, &items, notify).await + } + None => Err("no branch to open a pull request from".into()), + }; + if let Err(e) = opened { + // Nothing to open (no work yet): still never silent. + warn!(run_id, error = %e, "Run guard: no draft pull request for the stopped run"); + super::mark_run_stopped_by_guard(state, msg, run_id, &reason).await; + } + true +} + +/// A run that already has its pull request (a resume or feedback step): when +/// the guard fired, it waits on a person with the reason on the run page. True +/// when it had fired. +pub async fn settle_open_pr(state: &WorkerState, team_id: &str, run_id: &str) -> bool { + flush(state, team_id, run_id).await; + let Some(reason) = load(state, team_id, run_id).await.and_then(|l| l.stopped) else { + return false; + }; + let now = chrono::Utc::now().to_rfc3339(); + if let Err(e) = 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 #s = :s, status_run_id = :sri, error_message = :em, updated_at = :t, \ + current_pass = :cp", + ) + .condition_expression(run_status::not_ended("#s")) + .ended_values() + .expression_attribute_names("#s", "status") + .expression_attribute_values(":s", attr_s(run_status::NEEDS_INPUT)) + .expression_attribute_values( + ":sri", + attr_s(&format!("{}#{run_id}", run_status::NEEDS_INPUT)), + ) + .expression_attribute_values(":em", attr_s(&reason)) + .expression_attribute_values(":t", attr_s(&now)) + .expression_attribute_values(":cp", attr_s("done")) + .send() + .await + { + warn!(run_id, error = %e, "Run guard: could not hand the run to a person"); + } + if claim_notification(state, team_id, run_id).await { + super::webhooks::emit_run(state, team_id, run_id, run_status::NEEDS_INPUT).await; + } + true +} + +// ── What the checks found, across steps ──────────────────────────────────── + +/// One check's fix rounds and last result, for the whole run. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct CheckRecord { + /// Fix rounds started in this run. + #[serde(default)] + pub rounds: u32, + /// The branch head the last check ran on. + #[serde(default)] + pub head: String, + /// Open findings at the last check. + #[serde(default)] + pub open: usize, + /// Open findings when the last fix round started, until the check after it. + #[serde(default)] + pub open_at_fix: Option, + /// A fix round is running. Still set when a step loads the record: that + /// round was cut off. + #[serde(default)] + pub fixing: bool, + /// No more fixing: a round made no progress, or time ran out in one. + #[serde(default)] + pub stopped: bool, +} + +impl CheckRecord { + /// A check on this head has already run: its result stands. + pub fn unchanged(&self, head: &str) -> bool { + !head.is_empty() && self.head == head + } + + /// A check ran. Same or more findings than before the fix round ends the + /// fixing at once. + pub fn checked(&mut self, head: &str, open: usize) { + if self.open_at_fix.take().is_some_and(|before| open >= before) { + self.stopped = true; + } + self.head = head.to_string(); + self.open = open; + } + + /// No check ran because the code didn't change. If a fix round just ran, + /// it changed nothing, which is no progress. + pub fn reused(&mut self) { + if self.open_at_fix.take().is_some() { + self.stopped = true; + } + } + + pub fn may_fix(&self, max_rounds: u32) -> bool { + !self.stopped && self.rounds < max_rounds + } + + pub fn start_fix(&mut self) { + self.rounds = self.rounds.saturating_add(1); + self.open_at_fix = Some(self.open); + self.fixing = true; + } + + pub fn end_fix(&mut self) { + self.fixing = false; + } +} + +/// The pull request the run opened: a step resuming after it never opens it +/// again, nor pays to describe it again. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct OpenedPr { + pub number: u64, + pub url: String, + #[serde(default)] + pub node_id: String, +} + +/// The run's checks, kept across steps on the checkpoint table. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Ledger { + #[serde(default)] + pub proof: CheckRecord, + #[serde(default)] + pub rules: CheckRecord, + #[serde(default)] + pub links: CheckRecord, + #[serde(default)] + pub test_fix: CheckRecord, + /// What the proof check last found (`None`: the judge couldn't answer). + #[serde(default)] + pub proof_findings: Option>, + /// What the new-feature rules last came to. + #[serde(default)] + pub rules_outcome: Option, String>>, + /// What the link and redirect checks last came to. + #[serde(default)] + pub links_outcome: Option>, + /// What the failing-test rules last came to. + #[serde(default)] + pub test_outcome: Option, String>>, + /// The head the adversarial test last ran on. + #[serde(default)] + pub tested_head: String, + /// The head the search for someone else's pull request last ran on. + #[serde(default)] + pub existing_work_head: String, + /// Set once the pull request is open. + #[serde(default)] + pub opened: Option, +} + +/// A record larger than this drops its longest text: DynamoDB's item limit is +/// 400 KB, and the checks' results are worth more than their evidence prose. +const MAX_LEDGER_BYTES: usize = 300 * 1024; + +impl Ledger { + /// A new step picks the ledger up. A round still marked as running was cut + /// off by the time limit, so nothing fixes any more: the checks run once if + /// the code moved, and the pull request opens with what they find. + pub fn on_step_start(&mut self) { + let records = [ + &mut self.proof, + &mut self.rules, + &mut self.links, + &mut self.test_fix, + ]; + if records.iter().any(|r| r.fixing) { + for r in records { + r.fixing = false; + r.stopped = true; + } + } + } + + /// What is still open, for a run the guard stopped. Honest about both: + /// what the checks found, and what they didn't get to. + pub fn open_findings(&self) -> Vec { + let mut open: Vec = Vec::new(); + match &self.proof_findings { + Some(f) => open.extend(f.iter().cloned()), + None if self.proof.head.is_empty() => { + open.push(proof::blocked_item( + "The proof check", + "it didn't finish, so what the change rests on isn't confirmed", + )); + } + None => {} + } + match &self.links_outcome { + Some(Err(why)) => open.push(proof::blocked_item("The link and redirect check", why)), + Some(Ok(_)) => {} + None => {} + } + match &self.test_outcome { + Some(Err(why)) => open.push(proof::blocked_item("The failing-test rules", why)), + Some(Ok(_)) => {} + None => {} + } + match &self.rules_outcome { + Some(Err(why)) => open.push(proof::blocked_item("The new-feature rules", why)), + Some(Ok(Some(facts))) => open.extend(feature::open_findings(facts)), + Some(Ok(None)) => {} + None => open.push(proof::blocked_item( + "The new-feature rules", + "they didn't finish", + )), + } + open + } + + /// As stored, within the item limit. + pub fn to_json_bounded(&self) -> String { + let json = serde_json::to_string(self).unwrap_or_default(); + if json.len() <= MAX_LEDGER_BYTES { + return json; + } + // The counts, the heads and the pull request always survive: they are + // what keep the limits. What is dropped is checked again. + let mut smaller = self.clone(); + smaller.proof_findings = None; + smaller.proof.head = String::new(); + smaller.rules_outcome = None; + smaller.rules.head = String::new(); + smaller.links_outcome = None; + smaller.links.head = String::new(); + smaller.test_outcome = None; + smaller.test_fix.head = String::new(); + serde_json::to_string(&smaller).unwrap_or_default() + } +} + +/// A run's ledger for one repository, shared by the checks of a step. +#[derive(Debug, Default)] +pub struct LedgerCell { + ledger: Mutex, + scope: String, +} + +fn ledger_sk(run_id: &str, scope: &str) -> String { + format!("RUN#{run_id}#CHECKS#{scope}") +} + +impl LedgerCell { + pub fn new(scope: &str, ledger: Ledger) -> Self { + Self { + ledger: Mutex::new(ledger), + scope: scope.to_string(), + } + } + + /// Reads, or changes, the ledger. + pub fn update(&self, f: impl FnOnce(&mut Ledger) -> R) -> R { + let mut guard = self.ledger.lock().unwrap_or_else(|e| e.into_inner()); + f(&mut guard) + } + + pub async fn load(state: &WorkerState, team_id: &str, run_id: &str, scope: &str) -> Self { + let mut ledger = Ledger::default(); + if !state.config.checkpoints_table_name.is_empty() { + if let Ok(out) = state + .dynamo + .get_item() + .table_name(&state.config.checkpoints_table_name) + .key("team_id", attr_s(team_id)) + .key("sk", attr_s(&ledger_sk(run_id, scope))) + .send() + .await + { + if let Some(saved) = out + .item() + .and_then(|i| i.get("data")) + .and_then(|v| v.as_s().ok()) + .and_then(|s| serde_json::from_str(s).ok()) + { + ledger = saved; + } + } + } + Self::new(scope, ledger) + } + + /// Saved at every change that must survive the step being cut off. + pub async fn save(&self, state: &WorkerState, team_id: &str, run_id: &str) { + if state.config.checkpoints_table_name.is_empty() { + return; + } + let json = self.update(|l| l.to_json_bounded()); + let ttl = chrono::Utc::now().timestamp() as u64 + 7 * 86400; + if let Err(e) = state + .dynamo + .put_item() + .table_name(&state.config.checkpoints_table_name) + .item("team_id", attr_s(team_id)) + .item("sk", attr_s(&ledger_sk(run_id, &self.scope))) + .item("data", attr_s(&json)) + .item("ttl", attr_n(ttl)) + .send() + .await + { + warn!(run_id, error = %e, "Could not save what the checks found"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_limit_is_close_enough_to_the_worst_normal_run_to_matter() { + const { assert!(MAX_TRANSITIONS_WITHOUT_PROGRESS <= 2 * worst_normal_run()) }; + } + + #[test] + fn a_commit_is_not_progress_only_these_are() { + let mut g = GuardState::default(); + for _ in 0..10 { + g.on_pass(0.0); + } + // A check's first report sets where it starts. + assert!(!g.apply(&Progress::Findings("proof", 2))); + assert_eq!(g.transitions, 10); + // Same or more is nothing, whatever was committed in between. + assert!(!g.apply(&Progress::Findings("proof", 2))); + assert!(!g.apply(&Progress::Findings("proof", 4))); + assert!(!g.apply(&Progress::Findings("proof", 3))); + assert_eq!(g.transitions, 10); + // A new low counts, once; going back up and down to it doesn't. + assert!(g.apply(&Progress::Findings("proof", 1))); + assert_eq!(g.transitions, 0); + assert!(!g.apply(&Progress::Findings("proof", 3))); + assert!(!g.apply(&Progress::Findings("proof", 1))); + // Another check's count is its own. + assert!(!g.apply(&Progress::Findings("rules", 1))); + // Tasks, the pull request and CI. + assert!(g.apply(&Progress::TasksDone(3))); + assert!(!g.apply(&Progress::TasksDone(3))); + assert!(g.apply(&Progress::WorkDone)); + assert!(!g.apply(&Progress::WorkDone)); + assert!(g.apply(&Progress::PrOpen)); + assert!(!g.apply(&Progress::PrOpen)); + assert!(g.apply(&Progress::CiGreen)); + } + + /// No pass and no continuation lowers the spend: only real progress does, + /// and the same news twice is not progress. + #[test] + fn nothing_but_real_progress_resets_the_spend() { + let mut g = GuardState::default(); + g.apply(&Progress::TasksDone(5)); + g.apply(&Progress::WorkDone); + g.apply(&Progress::PrOpen); + g.apply(&Progress::Findings("proof", 2)); + let mut spent = 0.0; + for i in 0..200 { + g.on_pass(0.5); + spent += 0.5; + assert!((g.spend_usd - spent).abs() < 1e-9, "pass {i}"); + if i % 3 == 0 { + g.on_continuation(0.0); + } + assert!(!g.apply(&Progress::TasksDone(5))); + assert!(!g.apply(&Progress::WorkDone)); + assert!(!g.apply(&Progress::PrOpen)); + assert!(!g.apply(&Progress::Findings("proof", 2 + (i % 3)))); + assert!((g.spend_usd - spent).abs() < 1e-9, "pass {i}"); + } + assert!(g.apply(&Progress::CiGreen)); + assert_eq!(g.spend_usd, 0.0); + } + + #[tokio::test] + async fn spend_is_metered_as_it_happens_within_a_step() { + // Outside a metered step nothing is counted, and nothing breaks. + common::usage::note_run_spend(5.0); + assert_eq!(take_spend(), 0.0); + let allowance = std::sync::Arc::new(common::usage::RunAllowance::new(100.0)); + common::usage::with_run_allowance(allowance, async { + let mut usage = crate::models::TokenUsage::default(); + usage.add_call( + "claude-opus-5-5", + &common::usage::CallUsage { + uncached_input: 1_000_000, + ..Default::default() + }, + ); + let cost = usage.cost_usd; + assert!(cost > 0.0); + assert!((take_spend() - cost).abs() < 1e-3); + assert_eq!(take_spend(), 0.0, "each dollar counted once"); + }) + .await; + } + + #[test] + fn fewer_findings_never_buy_finished_work_more_continuations() { + let mut g = GuardState::default(); + g.apply(&Progress::WorkDone); + g.apply(&Progress::Findings("proof", 9)); + for (i, open) in [8, 7, 6].into_iter().enumerate() { + g.on_continuation(1.0); + assert!(g.apply(&Progress::Findings("proof", open))); + assert_eq!(g.trip(), None, "continuation {i}"); + } + g.on_continuation(1.0); + assert_eq!(g.trip(), Some(Trip::ContinuationsAfterWork)); + } + + #[test] + fn each_limit_fires_on_its_own() { + let mut g = GuardState::default(); + for _ in 0..MAX_TRANSITIONS_WITHOUT_PROGRESS { + g.on_pass(0.0); + } + assert_eq!(g.trip(), None); + g.on_pass(0.0); + assert_eq!(g.trip(), Some(Trip::Transitions)); + + let mut g = GuardState::default(); + for _ in 0..MAX_CONTINUATIONS_WITHOUT_PROGRESS { + g.on_continuation(0.0); + } + assert_eq!(g.trip(), None); + g.on_continuation(0.0); + assert_eq!(g.trip(), Some(Trip::Continuations)); + + let mut g = GuardState::default(); + g.on_pass(MAX_SPEND_WITHOUT_PROGRESS_USD); + assert_eq!(g.trip(), None); + g.on_pass(0.01); + assert_eq!(g.trip(), Some(Trip::Spend)); + g.apply(&Progress::CiGreen); + assert_eq!(g.trip(), None); + } + + #[test] + fn a_person_acting_starts_the_counts_over_and_keeps_the_lows() { + let mut g = GuardState { + after_work: 9, + transitions: 99, + continuations: 9, + spend_usd: 99.0, + ..Default::default() + }; + g.apply(&Progress::Findings("proof", 3)); + assert!(g.trip().is_some()); + g.person_acted(); + assert_eq!(g.trip(), None); + assert!(!g.apply(&Progress::Findings("proof", 3))); + } + + #[test] + fn the_reason_is_plain_and_says_what_to_do() { + let g = GuardState { + after_work: 4, + ..Default::default() + }; + let why = Trip::ContinuationsAfterWork.reason(&g); + assert!(why.contains("tasks were done"), "{why}"); + assert!(why.contains("continued 4 more times"), "{why}"); + assert!(why.contains("Open items"), "{why}"); + assert!(why.contains("Push to the branch or comment"), "{why}"); + let g = GuardState { + spend_usd: 20.5, + ..Default::default() + }; + assert!(Trip::Spend.reason(&g).contains("$20.50")); + } + + #[test] + fn stop_codes_are_stable_for_analytics() { + assert_eq!( + [ + Trip::ContinuationsAfterWork, + Trip::Continuations, + Trip::Transitions, + Trip::Spend + ] + .map(Trip::code), + [ + "continuations_after_work", + "continuations", + "pass_transitions", + "spend" + ] + ); + } + + #[test] + fn a_round_with_no_fewer_findings_ends_the_fixing() { + let mut r = CheckRecord::default(); + r.checked("a", 2); + assert!(r.may_fix(2)); + r.start_fix(); + r.end_fix(); + r.checked("b", 2); + assert!(!r.may_fix(2), "same findings: no second round"); + + let mut r = CheckRecord::default(); + r.checked("a", 2); + r.start_fix(); + r.end_fix(); + r.checked("b", 4); + assert!(!r.may_fix(2), "more findings: no second round"); + + let mut r = CheckRecord::default(); + r.checked("a", 3); + r.start_fix(); + r.end_fix(); + r.checked("b", 1); + assert!(r.may_fix(2), "fewer findings: a second round"); + r.start_fix(); + r.end_fix(); + r.checked("c", 0); + assert!(!r.may_fix(2), "two rounds is the limit"); + } + + #[test] + fn a_round_that_changed_nothing_ends_the_fixing() { + let mut r = CheckRecord::default(); + r.checked("a", 2); + r.start_fix(); + r.end_fix(); + assert!(r.unchanged("a"), "no commit: no re-check"); + r.reused(); + assert!(!r.may_fix(2)); + } + + #[test] + fn reusing_a_result_between_steps_is_not_a_failed_round() { + let mut r = CheckRecord::default(); + r.checked("a", 3); + r.start_fix(); + r.end_fix(); + r.checked("b", 1); + assert!(r.unchanged("b")); + r.reused(); + assert!(r.may_fix(2)); + } + + #[test] + fn an_unknown_head_is_never_called_unchanged() { + let r = CheckRecord::default(); + assert!(!r.unchanged("")); + assert!(!r.unchanged("a")); + } + + #[test] + fn time_running_out_in_a_round_ends_every_checks_fixing() { + let mut l = Ledger::default(); + l.rules.checked("a", 1); + l.rules.start_fix(); + // The step is cut off here; the next one picks the ledger up. + let mut next: Ledger = serde_json::from_str(&l.to_json_bounded()).unwrap(); + next.on_step_start(); + assert!(!next.rules.may_fix(MAX_RULES_FIX_ROUNDS)); + assert!(!next.proof.may_fix(MAX_PROOF_FIX_ROUNDS)); + assert!(!next.links.may_fix(MAX_LINK_FIX_ROUNDS)); + assert!(!next.test_fix.may_fix(MAX_TEST_FIX_ROUNDS)); + // Without a round cut off, a new step changes nothing. + let mut calm = Ledger::default(); + calm.proof.checked("a", 1); + calm.on_step_start(); + assert!(calm.proof.may_fix(MAX_PROOF_FIX_ROUNDS)); + } + + #[test] + fn the_ledger_round_trips_every_checks_result() { + let l = Ledger { + proof: CheckRecord { + rounds: 2, + head: "abc".into(), + open: 3, + ..Default::default() + }, + proof_findings: Some(vec![Finding { + point: "assumption".into(), + detail: "the vendor sends cents".into(), + ..Default::default() + }]), + rules_outcome: Some(Ok(Some(feature::PrFacts { + duplicates: vec!["a helper".into()], + ..Default::default() + }))), + links_outcome: Some(Err("a redirect 404s".into())), + test_outcome: Some(Ok(None)), + opened: Some(OpenedPr { + number: 7, + url: "https://example.test/7".into(), + node_id: "n".into(), + }), + ..Default::default() + }; + let back: Ledger = serde_json::from_str(&l.to_json_bounded()).unwrap(); + assert_eq!(back, l); + // An older record without these fields still reads. + let old: Ledger = serde_json::from_str("{}").unwrap(); + assert_eq!(old, Ledger::default()); + } + + #[test] + fn a_huge_ledger_keeps_its_counts_and_its_pull_request() { + let l = Ledger { + proof: CheckRecord { + rounds: 2, + head: "abc".into(), + ..Default::default() + }, + rules_outcome: Some(Err("x".repeat(MAX_LEDGER_BYTES + 10))), + opened: Some(OpenedPr { + number: 7, + ..Default::default() + }), + ..Default::default() + }; + let json = l.to_json_bounded(); + assert!(json.len() <= MAX_LEDGER_BYTES); + let back: Ledger = serde_json::from_str(&json).unwrap(); + assert_eq!(back.proof.rounds, 2, "the counts always survive"); + assert_eq!(back.opened.unwrap().number, 7); + // What was dropped isn't called unchanged, so it is checked again. + assert!(!back.proof.unchanged("abc")); + } + + #[test] + fn open_items_report_every_finding_and_what_never_ran() { + let l = Ledger { + proof: CheckRecord { + head: "abc".into(), + ..Default::default() + }, + proof_findings: Some(vec![Finding { + point: "assumption".into(), + detail: "the vendor sends cents".into(), + ..Default::default() + }]), + rules_outcome: Some(Err("new items aren't registered".into())), + links_outcome: Some(Err("a redirect 404s".into())), + test_outcome: Some(Err("the change loosens tests".into())), + ..Default::default() + }; + let text = proof::gaps_section(&l.open_findings()); + for said in [ + "the vendor sends cents", + "new items aren't registered", + "a redirect 404s", + "the change loosens tests", + ] { + assert!(text.contains(said), "{said} in {text}"); + } + assert!(proof::holds_blocked(&text), "these keep it a draft"); + // A check that never finished says so rather than saying nothing. + let text = proof::gaps_section(&Ledger::default().open_findings()); + assert!(text.contains("proof check"), "{text}"); + assert!(text.contains("didn't finish"), "{text}"); + assert!(text.contains("new-feature rules"), "{text}"); + } + + #[test] + fn rules_left_failing_go_under_open_items_without_a_second_hold() { + let facts = feature::PrFacts { + checklist: vec![feature::checklist::Item::new( + "Tests", + feature::checklist::Status::Fail, + "no spec for the new page", + )], + sandbox_failed: vec!["The unit tests fail".into(), "Output: boom".into()], + ..Default::default() + }; + let open = feature::open_findings(&facts); + assert_eq!(open.len(), 2); + let text = proof::gaps_section(&open); + assert!(text.contains("no spec for the new page"), "{text}"); + assert!(text.contains("The unit tests fail"), "{text}"); + assert!(!text.contains("boom"), "{text}"); + // The checklist's own ready check holds the draft and clears itself. + assert!(!proof::holds_blocked(&text)); + } + + #[test] + fn a_blocked_item_holds_the_draft_until_it_is_gone() { + let text = proof::gaps_section(&[proof::blocked_item( + "The new-feature rules", + "new items aren't registered", + )]); + assert!(crate::passes::resume::draft_hold(&text, "t", true).is_some()); + assert!(crate::passes::resume::draft_hold("nothing open", "t", true).is_none()); + } +} diff --git a/services/worker/src/passes/steps.rs b/services/worker/src/passes/steps.rs index a48a5ffe5..2f6d68789 100644 --- a/services/worker/src/passes/steps.rs +++ b/services/worker/src/passes/steps.rs @@ -10,7 +10,7 @@ //! fresh step (a NEW queue message with its own receive count and its own 15 //! minutes) that resumes exactly where this one stopped: planning //! ([`Gate::Plan`]), the implement work, the generator check -//! ([`Gate::Generators`]) or the checks before the pull request +//! ([`Gate::Generators`]), the pull request ([`Gate::Pr`]) or the checks on it //! ([`Gate::Checks`]), with the branch as it is. //! //! Planning commits nothing to a branch, so it keeps its own state on the @@ -27,10 +27,9 @@ //! 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; +//! runaway ceiling, never reached by real work. A moving branch is not enough +//! on its own: `run_guard` ends a run that keeps committing with nothing to show +//! for it. use aws_sdk_dynamodb::types::AttributeValue; use tracing::{error, warn}; @@ -122,6 +121,7 @@ fn where_label(at: &str) -> &str { "verify" => "the test and security audit after the implement work", "generators" => "the generator check (regenerating generated files)", "checks" => "the checks before the pull request", + "pr" => "opening the pull request", "implement_started" | "implement" => "the implement work (planned tasks)", "security" => "the security audit", "plan" => "planning (the plan and its repository and file checks)", @@ -144,8 +144,10 @@ pub enum Gate { Verify, /// The generator check: regenerate, verify, one fix round. Generators, - /// The proof, link, test-fix and new-feature checks, then the pull - /// request. + /// The draft pull request, as soon as the work is built. + Pr, + /// The proof, link, test-fix and new-feature checks, on the open pull + /// request. What they found so far is in the run's ledger (see `run_guard`). Checks, } @@ -156,6 +158,7 @@ impl Gate { Gate::Verify => "verify", Gate::Generators => "generators", Gate::Checks => "checks", + Gate::Pr => "pr", } } @@ -165,6 +168,7 @@ impl Gate { "verify" => Some(Gate::Verify), "generators" => Some(Gate::Generators), "checks" => Some(Gate::Checks), + "pr" => Some(Gate::Pr), _ => None, } } @@ -507,43 +511,6 @@ pub async fn mark_queued(state: &WorkerState, team_id: &str, run_id: &str, step: } } -// ── 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::*; @@ -665,7 +632,17 @@ mod tests { 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::Plan, Gate::Verify, Gate::Generators, Gate::Checks] { + assert!( + !Gate::Pr.runs_from(Some(Gate::Checks)), + "the PR is never opened again" + ); + for g in [ + Gate::Plan, + Gate::Verify, + Gate::Generators, + Gate::Checks, + Gate::Pr, + ] { assert_eq!(Gate::parse(g.as_str()), Some(g)); } } @@ -693,18 +670,6 @@ mod tests { } } - #[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 diff --git a/services/worker/src/passes/stop_gate.rs b/services/worker/src/passes/stop_gate.rs index e38dd7b8a..7fc85ada9 100644 --- a/services/worker/src/passes/stop_gate.rs +++ b/services/worker/src/passes/stop_gate.rs @@ -721,17 +721,6 @@ mod tests { ); } - #[test] - fn the_gate_keeps_a_tooling_failure_in_its_own_words() { - let f = ToolingFailure::new("cd 'e2e' && pnpm exec tsc", "sh: 1: tsc: not found"); - assert_eq!( - super::super::test_fix::blocked_reason(f.reason()), - f.reason() - ); - assert!(super::super::test_fix::blocked_reason("waits added".into()) - .starts_with("The failing-test rules blocked the pull request: ")); - } - #[test] fn a_tooling_reason_records_its_kind_and_command() { let f = ToolingFailure::new("cd 'e2e' && npx --no-install tsc", "sh: 1: tsc: not found"); diff --git a/services/worker/src/passes/stop_pr.rs b/services/worker/src/passes/stop_pr.rs index 5c21642a0..42c84cf9c 100644 --- a/services/worker/src/passes/stop_pr.rs +++ b/services/worker/src/passes/stop_pr.rs @@ -17,6 +17,7 @@ use crate::clients::github::GitHubClient; use crate::models::{TicketMessage, TicketSource}; use crate::WorkerState; +use common::run_status::EndedValues; type BoxError = Box; @@ -34,15 +35,21 @@ fn ticket_line(msg: &TicketMessage) -> String { } } -/// The draft pull request's body: the ticket line, why the run stopped, and -/// what is left as the open item. -pub fn body(ticket: &str, reason: &str, files: &[String]) -> String { +/// The draft pull request's body: the ticket line, why the run stopped, what +/// is left as the open item, and what the checks left open (`open`, already +/// rendered with its own heading, or empty). +pub fn body(ticket: &str, reason: &str, files: &[String], open: &str) -> String { let reason = reason.split_whitespace().collect::>().join(" "); let shown: Vec = files.iter().take(20).map(|f| format!("- `{f}`")).collect(); let more = files.len().saturating_sub(shown.len()); + let open_items = if open.trim().is_empty() { + format!("## Open items\n\n- [ ] {reason}") + } else { + open.trim().to_string() + }; format!( "{ticket}\n\n## Summary\n\nCoderHelm did this ticket's work on this branch and stopped \ - before marking it ready: {reason}\n\n## Changes\n\n{}{}\n\n## Open items\n\n- [ ] {reason}\n\n\ + before marking it ready: {reason}\n\n## Changes\n\n{}{}\n\n{open_items}\n\n\ This is a draft. Push to this branch or comment on this pull request, and CoderHelm picks \ it up from here.", shown.join("\n"), @@ -62,6 +69,21 @@ pub async fn open( run_id: &str, branch: &str, reason: &str, +) -> Result { + open_with(state, msg, run_id, branch, reason, &[], true).await +} + +/// [`open`], with what the checks left open going under Open items (on the +/// pull request that is already there too), and the notification only when +/// `notify` says this stop hasn't sent one. +pub async fn open_with( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + branch: &str, + reason: &str, + items: &[super::proof::Finding], + notify: bool, ) -> Result { let github = GitHubClient::new( &state.secrets.github_app_id, @@ -82,14 +104,33 @@ pub async fn open( if work.is_empty() { return Err("no work on the branch".into()); } + let open_text = [ + super::proof::unfinished_section(items), + super::proof::gaps_section(items), + ] + .into_iter() + .filter(|s| !s.is_empty()) + .collect::>() + .join("\n\n"); let existing = github .find_open_pr_for_branch(&msg.repo_owner, &msg.repo_name, branch) .await?; let (number, url) = match existing { - Some(p) => ( - p["number"].as_u64().unwrap_or(0), - p["html_url"].as_str().unwrap_or("").to_string(), - ), + Some(p) => { + let number = p["number"].as_u64().unwrap_or(0); + if !items.is_empty() { + super::pr::put_open_items( + &github, + &msg.repo_owner, + &msg.repo_name, + number, + p["body"].as_str().unwrap_or(""), + items, + ) + .await; + } + (number, p["html_url"].as_str().unwrap_or("").to_string()) + } None => { let conventions = super::load_git_conventions(state, &msg.team_id, &msg.ticket_id).await; @@ -99,7 +140,7 @@ pub async fn open( &msg.repo_owner, &msg.repo_name, common::truncate_str(&title, 72), - &body(&ticket_line(msg), reason, &work), + &body(&ticket_line(msg), reason, &work, &open_text), branch, &msg.base_branch, true, @@ -120,9 +161,13 @@ pub async fn open( .key("run_id", super::attr_s(run_id)) .update_expression( "SET #s = :s, status_run_id = :sri, pr_url = :pu, pr_number = :pn, branch = :b, \ - error_message = :em, updated_at = :t", + error_message = :em, updated_at = :t, current_pass = :cp", ) + // Never over a run a person ended. + .condition_expression(common::run_status::not_ended("#s")) + .ended_values() .expression_attribute_names("#s", "status") + .expression_attribute_values(":cp", super::attr_s("done")) .expression_attribute_values(":s", super::attr_s("needs_input")) .expression_attribute_values(":sri", super::attr_s(&format!("needs_input#{run_id}"))) .expression_attribute_values(":pu", super::attr_s(&url)) @@ -139,7 +184,16 @@ pub async fn open( &format!("Stopped after the work; opened draft pull request #{number} with the reason as its open item"), ) .await; - super::webhooks::emit_run(state, &msg.team_id, run_id, "needs_input").await; + super::run_guard::progress( + state, + &msg.team_id, + run_id, + super::run_guard::Progress::PrOpen, + ) + .await; + if notify { + super::webhooks::emit_run(state, &msg.team_id, run_id, "needs_input").await; + } Ok(url) } @@ -163,10 +217,20 @@ mod tests { "Source ticket: T-1", "Stopped before opening a pull request: 2 of 9 planned tasks are not done", &["web/a.tsx".into()], + "", ); assert!(b.starts_with("Source ticket: T-1")); assert!(b.contains("## Open items\n\n- [ ] Stopped before opening a pull request: 2 of 9")); assert!(b.contains("- `web/a.tsx`")); assert!(!b.contains("Closes #0")); + // What the checks left open takes the place of the bare reason. + let b = body( + "Source ticket: T-1", + "It kept continuing", + &[], + "## Open items\n- the vendor sends cents", + ); + assert!(b.contains("## Open items\n- the vendor sends cents")); + assert_eq!(b.matches("## Open items").count(), 1); } } diff --git a/services/worker/src/passes/test_fix.rs b/services/worker/src/passes/test_fix.rs index b1e2c853c..2a2d351c3 100644 --- a/services/worker/src/passes/test_fix.rs +++ b/services/worker/src/passes/test_fix.rs @@ -73,7 +73,7 @@ const MAX_BYTES: usize = 150 * 1024 * 1024; /// Keys listed from a report location. const MAX_KEYS: usize = 10_000; /// Fix rounds the pre-PR check may send back. -const MAX_FIX_ROUNDS: u32 = 2; +const MAX_FIX_ROUNDS: u32 = super::run_guard::MAX_TEST_FIX_ROUNDS; /// The ready check runs again this often while it waits. const RECHECK_SECS: i32 = 600; /// And at most this many times (about 12 hours). @@ -1738,6 +1738,33 @@ pub async fn gate( evidence: &mut super::proof::RunEvidence, usage: &mut TokenUsage, has_time: impl Fn() -> bool, +) -> Result, String> { + let head = w.head().await; + let standing = w.ledger.update(|l| { + if !l.test_fix.unchanged(&head) { + return None; + } + l.test_fix.reused(); + l.test_outcome.clone() + }); + if let Some(standing) = standing { + return standing; + } + let outcome = check_and_fix(w, evidence, usage, has_time).await; + let head = w.head().await; + w.ledger.update(|l| { + l.test_fix.head = head; + l.test_outcome = Some(outcome.clone()); + }); + w.save_ledger().await; + outcome +} + +async fn check_and_fix( + w: &super::proof::Work<'_>, + evidence: &mut super::proof::RunEvidence, + usage: &mut TokenUsage, + has_time: impl Fn() -> bool, ) -> Result, String> { let Some(mut ev) = load(w.state, &w.msg.team_id, w.run_id).await else { return Ok(None); @@ -1753,7 +1780,6 @@ pub async fn gate( provider: w.provider, }; let target = test_target(w.state, &w.msg.team_id, &format!("{owner}/{repo}"), None).await; - let mut rounds = 0; let mut integrity_rounds = 0; let mut base_tried = ev.base_repeat.is_some(); let mut unit_seen: Option<(String, Result, String>)> = None; @@ -1920,8 +1946,8 @@ pub async fn gate( bug_problems = bug_problems.len(), views_missing = views_missing.len(), repeat = ?repeat, - rounds, - "Failing-test rules checked before the pull request" + rounds = w.ledger.update(|l| l.test_fix.rounds), + "Failing-test rules checked on the pull request" ); let blocking: Vec = refused .iter() @@ -1994,7 +2020,10 @@ pub async fn gate( blocking.join("; ") )); } - if rounds >= MAX_FIX_ROUNDS || !has_time() { + let open = blocking.len() + usize::from(repeat_red); + w.report_findings("test_fix", open).await; + w.ledger.update(|l| l.test_fix.checked(&head, open)); + if !w.ledger.update(|l| l.test_fix.may_fix(MAX_FIX_ROUNDS)) || !has_time() { if !blocking.is_empty() { return Err(blocking.join("; ")); } @@ -2013,7 +2042,8 @@ pub async fn gate( wrong, ))); } - rounds += 1; + w.ledger.update(|l| l.test_fix.start_fix()); + w.save_ledger().await; if !weak.is_empty() { integrity_rounds += 1; } @@ -2060,7 +2090,7 @@ pub async fn gate( let _ = super::update_pass(w.state, &w.msg.team_id, w.run_id, "implement").await; // A bug moved into the app needs files the branch doesn't touch yet. let scoped = bug_problems.is_empty(); - match super::implement::run( + let fixed = super::implement::run( w.state, w.msg, w.github, @@ -2074,25 +2104,19 @@ pub async fn gate( usage, w.file_cache, Some(w.run_id), - None, + // A round stops at the step's deadline: left open-ended, it ran + // until the time limit cut the whole step off. + w.deadline, scoped, ) - .await - { + .await; + w.ledger.update(|l| l.test_fix.end_fix()); + w.save_ledger().await; + match fixed { Ok(r) => evidence.merge(r.evidence), Err(e) => return Err(format!("the fix round failed: {e}")), } - let _ = super::update_pass(w.state, &w.msg.team_id, w.run_id, "review").await; - } -} - -/// The run's failure when the gate blocks the pull request. A tooling -/// failure keeps its own words, so the run records it as one. -pub fn blocked_reason(why: String) -> String { - if why.starts_with(tooling::PREFIX) { - why - } else { - format!("The failing-test rules blocked the pull request: {why}") + let _ = super::update_pass(w.state, &w.msg.team_id, w.run_id, super::PASS_CHECKS).await; } } From 6b5f66a29389ec31d4c9eb071409b70ccf78a952 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Thu, 5 Nov 2026 15:25:13 -0500 Subject: [PATCH 2/2] Pin the dashboard with the run page steps --- selfhost/versions.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/selfhost/versions.json b/selfhost/versions.json index 9b88d1337..405a90baa 100644 --- a/selfhost/versions.json +++ b/selfhost/versions.json @@ -1,4 +1,4 @@ { "about": "The dashboard commit each platform release ships: a full 40-character commit SHA of CoderHelm/coderhelm, never a branch or tag (scripts/check-dashboard-ref.mjs fails CI and the release otherwise). The release workflow builds exactly this commit (dashboard/) into dashboard.tar.gz. Move it with scripts/bump-dashboard.sh in a reviewed PR, in the same PR as any API change the dashboard needs.", - "dashboardRef": "cfe86baf0e7601e97029143c8d6895ab6d2dbfe8" + "dashboardRef": "d2df18677bb2cebd0a8b9a33e93900180f6d63d9" }