Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/incidents.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
9 changes: 9 additions & 0 deletions infra/lib/monitoring-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"'),
Expand Down
121 changes: 118 additions & 3 deletions lambda/stuck-run-cleanup/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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 ""
Expand Down Expand Up @@ -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"},
Expand All @@ -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"
),
}
Expand All @@ -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
Expand All @@ -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")

Expand Down Expand Up @@ -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,
}
77 changes: 77 additions & 0 deletions lambda/tests/test_stuck_run_cleanup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
2 changes: 1 addition & 1 deletion selfhost/versions.json
Original file line number Diff line number Diff line change
@@ -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"
}
64 changes: 64 additions & 0 deletions services/common/src/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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((
Expand Down
Loading
Loading