fix(devs): the reconciler checks a random batch of stale turns
Problem
staleRunningTurns in packages/trpc/src/router/agent/reconcile.ts takes limit 50 running turns older than 2 minutes, with no order by. Postgres returns the same rows each pass (probably in agent_turns_one_running_per_session_idx order). A turn the reconciler finds healthy is skipped and stays in the next pass's set. So when 50 long, healthy turns fill the batch (task turns can run up to 2 hours), a lost turn outside the batch:
- is never settled as
lost, - is never sent again (
sendAgainonly runs for turns started in the last hour), - keeps its task session
running, which holds one of the Dev's task slots, and its parent is never told (afterTaskTurn).
Each session holds at most one running turn, so this needs about 50 busy sessions at the same time across all orgs.
Change
.orderBy(sql\random()`)` before the limit. Each stale turn now has a 50/N chance to be checked on each one-minute pass, so a lost turn waits about N/50 passes on average. With 50 or fewer stale turns nothing changes.
Options I rejected:
started_atascending: the oldest healthy turns always fill the batch.started_atdescending: old lost turns that hold task slots never get checked.- A
checked_atcolumn: needs a migration, plus a write for every healthy check every minute. - Checking every row: unbounded work inside the reconcile activity's 2-minute
startToCloseTimeout, which runs withmaximumAttempts: 1.
Validation
bun testinpackages/trpc: 1198 pass.bun run typecheckinpackages/trpcandbiome checkon the file: both clean.- Not run against a database. The trpc package has no database harness, so this PR adds no test.
Found by the Dev doctor's architecture pass (rough edge 30).
Summary by cubic
Fixes the reconciler so a lost running turn no longer gets stuck behind a full batch of healthy ones.
staleRunningTurns picked 50 rows with no ordering, so Postgres returned the same turns every pass. When 50 long but healthy turns filled the batch, a lost turn outside it was never settled as lost, never sent again, and kept its task session's slot. A random order by gives each stale turn a 50/N chance per pass and changes nothing when there are 50 or fewer.