Skip to content

fix(platform): recheck agent occupancy before an automated retry - #3985

Merged
yannickmonney merged 13 commits into
mainfrom
fix/agent-retry-busy-admission
Sep 30, 2026
Merged

yannickmonney merged 13 commits into
mainfrom
fix/agent-retry-busy-admission

Conversation

@yannickmonney

@yannickmonney yannickmonney commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Refs #3977, the automatic-retry part only. The issue's broader scope stays open under TALE-386: admission at every door, host headroom, resource-exhaustion attribution and backoff, and capacity sizing.

The defect

The automatic retry of a run started by an automation step or another agent (started_via, migration 0139) checked the task state, the hourly budget and the starter's authority. It then called kickAgentRun directly. The delegated start (startDelegatedAgentRun) takes the agent-row lock and refuses a second live run in the standing session (agent_busy); the retry did neither. The failing sequence:

  1. A delegated task A, In progress, fails.
  2. The manager starts the now-free agent on task B.
  3. A's delayed retry queues a second run into B's workspace (pa-<agent>).

What changed

  • One admission, one lock order.
    • The retry takes lockAgentForStart before the task row. This is the delegated start's agent-row write, now shared, and the same order the delegated start uses (agent, then task). No agent lock is ever taken after the task lock.
    • The failed run's provenance is written once at its kick, so the retry reads it unlocked to decide whether the chain is automated.
    • Every existing check is then re-read under both locks, in the same order as before: archive, status, assignee, newest run, consecutive budget, project and starter authority.
    • Isolation is unchanged: the retry stays READ COMMITTED, the delegated start stays SERIALIZABLE. The agent-row write invalidates the delegated start's stale snapshot, so its transactSerializable retry sees the other run and answers agent_busy.
  • The right workspace.
    • findAgentBusyRun, the delegated start's probe (now shared), runs on the session the retry would join (sessionIdForAgentRun): the standing one, or the member's own for a confined retry.
    • The kick gets that same session (kickAgentRun({ sessionId })), so the run lands in the workspace the probe checked.
    • The probe is scoped to the organization and the agent. Another agent's run, the agent's run in another workspace and another tenant's run do not hold it.
  • A bounded wait on the existing durable queue.
    • While the agent works another task in that workspace, the retry queues a later check of itself, 5 minutes out, in the same transaction.
    • Checks go on task.agent_retry_recheck, a queue under the documented short contract (as chat.deferred_send_poll). Each carries the key agent-retry:<org>:<task>:<failed run> (agentRetryRecheckKey), so pg-boss's unique index allows at most one queued check per failed run.
    • Any second send is dropped. That covers the arm delivered again before its ack or after a worker took the queued check, two deliveries at once, and a check that expired unacknowledged. The one check still queued re-derives every guard.
    • The arm's queue keeps its standard policy, so a keyless arm from the previous image is never shut out mid-roll. The arm and every check share one handler.
    • A check keeps the expected predecessor and startAfterMs, and counts itself in agentBusyWaits. No check is sent more than 2 hours after the failed run settled; that database-anchored age bounds the whole chain (planAgentBusyWait).
    • No run row is written while the retry waits, so neither the consecutive-failure budget nor the hourly automated-start budget changes.
  • A durable, visible, final end.
    • Once the wait is exhausted, retireBusyRetry retires the failed run's automatic retry on the run itself. The mark is auto_retry_refused_at_ms (migration 0141_project_agent_runs_auto_retry_refused.sql), a nullable column, safe to add mid-roll.
    • Only the call that sets the mark writes the timeline refusal (agent_run.refused, agent_busy: "Run refused: agent is working on another task", with the failure banner), following the circuit breaker's convention.
    • Every later delivery of that retry stands down as retry_refused, whether the agent is busy or free: the arm, a check queued before the refusal, or the refusing job itself.
    • A newer run carries no mark and starts as before: the manager's restart, or a person's Start or Retry. Its own failure retries on its own. Nothing is queued after the refusal; the manager decides again.
  • A drain hand-over that keeps the key. A draining worker (jobs/runner.ts) hands every job it claims over to the live colour.
    • It now fetches with includeMetadata.
    • handOver completes the claim and queues its successor in one transaction of the app's pool, the claim first. The successor carries the fetched job's own payload, singleton key and priority (the key is never rebuilt elsewhere), five seconds out as before.
    • On short, two failed runs whose checks are drained together both keep their next check, and a key that already has a queued job is not doubled; that job does the work.
    • An exclusive job's successor is not refused by its own claim. Keyless jobs on a standard queue hand over as before.
    • The app's per-job options are exactly startAfter, singletonKey and priority (EnqueueOptions). Retry and expiry are queue options, which apply to the successor as they did to the job.
    • main.ts passes sql with shouldDefer, and the options type requires the pair.
  • Order of judgment. Final refusals come before the busy check, so an untouched To-do standing card still answers task_moved and waits for its next occurrence. The busy check comes before the hourly budget, as in the delegated start. A person's run and its retries are unchanged.
  • Locales, docs and the manual register.
    • Locales EN/DE/FR (tasks.agentRuns.refused.agent_busy), plus a guard that every refusal code a task writer records has a label.
    • Docs EN/DE/FR (platform/projects/task-automation.md).
    • A row in the manual register (tests/manual/reference/automation.md), which also names the drain hand-over and its lane.

Review corrections at 38e36bf9d (B1, B2)

The independent review found two gaps in the delivery lifecycle; both are fixed as described above. The lock order and the same-session admission are unchanged.

  • B1 (a duplicate busy delivery forked the checks): now at most one queued check per organization, task and failed predecessor, enforced by the database.
  • B2 (a redelivery after the agent became free bypassed the refusal): the retirement mark makes the refusal final for that predecessor.

At the reviewed head, running this branch's lane code, the regressions fail:

  • B1: a replayed arm leaves 2 queued wait=1 checks; a late arm plus the taken check leaves 3; the expired check run twice leaves 2 wait=2.
  • B2: once the agent is free, the identical last check starts a retry.

Here they pass. Every duplicate, concurrent or replayed delivery leaves one queued check, and every replay after the refusal answers retry_refused.

Review correction at 66b448120 (P2, the drain hand-over)

The finding. The drain hand-over re-sent only the payload, five seconds out, so a keyed short job lost its key. Of two predecessors drained together, only one kept a next check.

The fix is the drain bullet above. It adds no second retry engine, and the key is the fetched job's own.

The new lane. checkWorkerDrainHandOff drives the actual registered worker (startWorker) through real pg-boss fetches on throwaway short, standard and exclusive queues, which are deleted with their jobs at the end.

At the reviewed head 66b448120, running this lane code, 3 of its 5 checks fail (raw, state:key:seq:priority:+delay):

  • Two keyed jobs drained together: both originals complete, but the only successors are keyless ones for one of them. Their shape is completed:∅:2:p0:+5s ×3 and created:∅:2:p0:+5s: the draining worker claims them again, and the successors of the p7 job have lost its priority. The other predecessor has no successor.
  • A claim whose key already has a queued job gains an extra keyless successor, created:∅:3:p0:+5s.
  • The exclusive job's successor loses its key: created:∅:9:p0:+5s.

The keyless standard hand-over and a worker that is not draining pass there as well; that behaviour is unchanged.

Here all 5 pass:

  • created:a-…:1:p0:+5s and created:b-…:2:p7:+5s remain once both originals are completed.
  • A job queued first under key c does the work, with no second successor, and a same-key duplicate send is dropped.
  • Keyless successors for seq 7 and 8 are queued at +5 s.
  • The exclusive successor keeps its key: created:x-…:9:p0:+5s.
  • The live worker runs its job.

runner.test.ts adds three unit tests: the hand-over's order (begin → complete → send → commit, with includeMetadata), a keyed job keeping its key and priority, and a failed hand-over keeping the claim for pg-boss to retry.

The predecessor refusal, as a migration and as a transaction. checkAutomatedRetryAgentBusy now also delivers the check that ends the wait twice at once while the agent is busy:

  • One delivery refuses (agent_busy); the other stands down on the mark (retry_refused).
  • The timeline holds one refusal and the failed run one mark. No check is queued and nothing starts.
  • The mark is read off the migration's column, a nullable bigint. 0141_project_agent_runs_auto_retry_refused.sql is recorded once in app_migrations, after the harness's two concurrent boot migrations.

How it was verified

Round discipline. Every local run was bounded and ran one at a time. Each round had databases of its own (tale389_<round>_app / _knowledge), which are kept and never dropped; the shared tale_app / tale_knowledge were never touched. Turn jobs were held inert, so no sandbox, provider or model was involved.

The 14 lanes:

  • checkAutomatedRetryAgentBusy: 21 checks.
  • checkWorkerDrainHandOff: 5 checks.
  • The 12 lanes that touch the retry, the kick or the delegated start: checkTaskAgentRuns, checkTaskAgentTurnDrive, checkOneLiveRunPerTask, checkTaskRunStartFence, checkTaskRetryProjectEligibility, checkScheduledAgentStarts, checkDelegatedAgentStartTool, checkInPlaceCompletionCycle, checkAutoRetryAndKickPlan, checkCredentialRotationRetry, checkCooledStartRetry and checkTaskRunConnectorCaller.
Round Source Result
20260930t125221_r3_branch_merged this head 5c1768948 (main 5f8dfea6b merged in) 121/121 (one skip, the old S3 half of checkTaskAgentTurnDrive)
20260930t124232_r3_branch_final2 f1ff57119 121/121
20260930t124340_r3_reviewed2_negative_final2 reviewed head 66b448120 + this lane code (sha256-identical) 118/121: exactly the 3 drain checks fail
20260930t123501_r3_branch_final / …123621_r3_reviewed2_negative_final 067b4deaa / 66b448120 + tests, before the refusal-at-once check 120/120 / 117/120 (the 3 drain checks)
20260930t122154_r3_branch_drain / …122317_r3_reviewed2_drain_negative the fix / 66b448120 + tests, drain lane only 22/22 / 19/22
20260930t104154_r2_reviewed_negative_final reviewed head 38e36bf9d + round-2 lane code lane 16/20: B1, B2 and their two follow-on checks fail
20260930t104337_r2_main_negative main c276da375 + the tests 102/115: the 12 existing lanes' 95 checks pass; the new lane fails exactly its 13 new-behaviour checks
20260930t104239_r2_branch_final / …113413_r2_branch_merged 01ef3c4d3 / 66b448120 115/115 / 115/115

The first round's evidence, which Root already holds, is unchanged: main 17cecce07 + tests gave 102/112, and 38e36bf9d gave 112/112. One round-2 run at 4bd0a63a7 scored 114/115 because of a race in the lane's own log capture, not in the product. It is kept as it is, and 01ef3c4d3 gave each delivery its own AsyncLocalStorage capture.

Raw replay outcomes at this head.

  • Queued checks per failed run after each step: task.agent_retry_recheck#1, #1, #1, #2, and the chain still moves on to #3.
  • Every replay after the refusal answers ["skipped:retry_refused"].
  • The manager's restart of the refused task answers started, its failure's retry is queued, and a person's Start answers 200.

Raw race outcomes (verbatim in each round's log):

  • Main: the reported sequence and the gated race with the delegated start first each leave two live runs (delegated + auto_retry) in pa-<agent>. All 3 unordered rounds do too: winner=none … start attempts=1 failed with=[] live=["auto_retry@retry task","delegated@start task"].
  • Branch, gated, delegated start first: the retry queues on the agent row (pg_blocking_pids) while holding no task lock (FOR UPDATE NOWAIT on the task succeeds), then waits.
  • Branch, gated, retry first: the start's first serializable attempt fails with 40001, and its second answers agent_busy.
  • Branch, all 3 unordered rounds: winner=retry … start=agent_busy start attempts=2 failed with=["40001"] live=["auto_retry@retry task"].
  • Lock order: a task-then-agent transaction deadlocks (40P01) beside a delegated restart of the same task. In that interleaving, the real retry queues on the agent row and stands down as superseded.

Unit tests at this head (server project, 102 files, 1239 tests, all passing), among them:

  • task-list.agent-retry.test.ts (49 tests). It covers:
    • the lock order and the probed session;
    • the wait and its payload, and both bounds;
    • the recheck queue's key and short policy, "already queued", and one worker for both queues;
    • the retirement election and the stand-down on a retired retry, and a newer run's retry;
    • final refusals before busy, and busy before the hourly budget.
  • runner.test.ts (8 tests).
  • task_auto_retry.test.ts (planAgentBusyWait) and agent-runs.test.ts (the kick into a caller's session).
  • The platform guards, including integration-skips and ci: run the real-Postgres integration suite in CI #3988's integration-scope, and the platform i18n suite.
  • Client: display.test.ts, with the refusal-label guard, plus the timeline and the failure banner (18 tests).

Other checks, all exit 0: scoped tsc on every changed file, oxfmt --check, oxlint --type-aware on the changed files, lint:manual, lint:conflicts and lint:links.

CI. Since #3988, CI's Backend integration job runs the whole backend:integration suite on this PR: every lane, ITEST_REQUIRE_ALL_LANES, the tale-db image built from services/db, and the object store. The two new lanes and migration 0141 are part of that run. At 5c1768948 it passes 1217/1217 checks across 206/206 lanes, including all 5 worker drain and 21 busy retry checks. The whole check set passes: 51 pass, 11 are skipped (conditional jobs) and none fail.

Not in this PR (TALE-386)

  • Every human door: Start, a move to In progress and @mention.
  • A person's own retries.
  • Host headroom, resource-exhaustion classification and backoff, and capacity sizing.
  • A queue UX for waiting work.

The automatic retry of a run an automation step or another agent started
(`started_via`) kicked straight into the agent's standing session: a
delegated task A fails, the manager starts the now-free agent on task B,
and A's retry then queues a second live run into B's workspace. The
delegated start already refuses that (`agent_busy`, one active piece of
work per agent workspace); the retry job skipped the check.

The retry now takes the same admission, in the same order:

- The agent-row write (`lockAgentForStart`, shared with the delegated
  start) is taken before the task row, so both paths lock agent, then
  task; the failed run's provenance, written once at its kick, is read
  unlocked to decide. Every task, run, budget and starter check is then
  re-read under both locks, as before. The retry stays READ COMMITTED;
  the delegated start stays SERIALIZABLE, and the row write invalidates
  its stale snapshot so its retry answers `agent_busy`.
- The busy probe (`findAgentBusyRun`, shared) looks in the workspace the
  retry would join (`sessionIdForAgentRun`: standing, or the member's own
  for a confined retry), and the kick is handed that same session.
- While the agent works another task there, the retry waits: the same
  `task.agent_retry` job, sent again five minutes later in the same
  transaction, counting its looks (`agentBusyWaits`) and bounded by the
  failure's age (two hours, `planAgentBusyWait`). No run row is written,
  so neither the consecutive-failure budget nor the hourly automated-start
  budget moves. Past the bound the retry is refused once on the timeline
  (`agent_run.refused`, `agent_busy`) and nothing is queued behind it.
- Final refusals (moved, reassigned, archived, not permitted, budget)
  are judged before the busy agent, so a To do standing card still waits
  for its next occurrence; the busy agent is judged before the hourly
  budget, as the delegated start does. A person's run, and its retries,
  are left as they were (every door's admission stays in #3977's scope).

Proof: `checkAutomatedRetryAgentBusy` (real Postgres, queue held inert)
fails 10 of its 17 checks against the unchanged implementation — two
live runs in one workspace for the reported sequence and both races —
and passes all 17 here, with the 12 lanes that touch the retry and the
delegated start unchanged (95/95 on main and branch). Unit tests pin the
lock order, the probe's session, the wait, its bounds and the refusal.

Refs #3977
The unordered rounds of checkAutomatedRetryAgentBusy now name the winner, what each side answered, the delegated start's serializable attempts and the codes that failed them, and every live run of the workspace by its trigger. The retry handler says how a look delivered twice stays bounded.
@yannickmonney

Copy link
Copy Markdown
Contributor Author

Independent review at 38e36bf9d79427f57c78f3c60a2e50f14d6c3819: two P2 delivery-lifecycle corrections remain before acceptance. The agent→task write-lock order, same-session occupancy check and inherited authority/budget gates look sound.

  1. Collapse duplicate busy deliveries durably. task-list.ts:1197–1214 sends a new delayed retry for every busy delivery, with only startAfter; task.agent_retry retains the standard queue policy and no durable per-predecessor claim. A commit-before-ack replay creates two identical wait=1 successors; delivering each creates two wait=2 chains. The newest-run guard prevents duplicate admitted retries, but does not deduplicate these future checks. The carried counter/age bound limits each branch rather than the total chain. Reuse the existing queue mechanism and prove one future check for the same org/task/failed predecessor under duplicate/concurrent delivery. A standard-policy singleton label alone would not satisfy the repository’s documented queue contract.
  2. Preserve terminal busy refusal on replay. The terminal branch records agent_run.refused / agent_busy, but that lookup only deduplicates activity while still busy. Redelivering the identical max-wait job after the agent becomes free bypasses the refusal and reaches kickAgentRun. Retire that predecessor’s automatic retry durably; a genuinely newer manager/human decision must still work.

Bounded independent probes use the actual retry handler and authored SQL fake, with a fixed predecessor settle timestamp, retained refusal state and inert kick/queue boundaries: 4 controls pass, 2 required assertions fail. These are source/handler-boundary counterexamples, not independent PostgreSQL race execution or a duplicate-paid-run claim. Focused authored tests pass 93/93. Hosted affected Unit/UI tasks executed fresh at the reviewed tree; raw author PostgreSQL archives remain pending separately.

Please add real queue replay/concurrency and after-refusal/free regressions while preserving existing human retry, guard/refusal ordering and locales. Keep the same PR/task and retain the successful lock-order evidence. No production test, grant or schedule activation is needed.

Two delivery-lifecycle corrections from the independent review of #3985
at 38e36bf (B1, B2). The agent-before-task lock order and the
same-session admission are unchanged.

B1 — one future check per failed run. A busy retry sent its next check
as another standard `task.agent_retry` job, so a commit-before-ack
replay, two deliveries at once or a replay after a worker took the
queued check each forked another chain of checks. Checks now go through
`task.agent_retry_recheck`, a queue of their own under the documented
`short` contract, every one keyed by org, task and failed run
(`agentRetryRecheckKey`): the database's unique index keeps at most one
queued per failed run, a second send is dropped (`a check is already
queued`), and the one queued still re-derives every guard. The arm's
queue keeps its standard policy, so a keyless arm from the previous
image is never shut out mid-roll. Arm and checks share one handler.

B2 — a refusal stays final. The terminal agent_busy refusal only
de-duplicated its timeline row; the same job delivered again once the
agent was free passed every guard and started the retry. The refusal
now retires the failed run's automatic retry on the run itself
(`auto_retry_refused_at_ms`, migration 0141, set once by
`retireBusyRetry`, which alone writes the timeline row), and every later
delivery of that retry — the arm, a check queued before the refusal, the
refusing job again — stands down as `retry_refused`, busy or free. A
newer run (a manager's restart, a person's Start or Retry) carries no
mark and starts as before; its own failure retries on its own.

Proof (real Postgres, retained rounds): the new lane cases fail at the
reviewed head (4 checks: two queued wait=1 checks after a replayed arm,
three after a late arm and a taken check, two wait=2 after an expired
check ran twice; a retry started after the refusal once the agent was
free) and pass here with every earlier case. Unit tests pin the queue,
the key, the one worker, the retirement election and the stand-down.

Refs #3977
Two deliveries at once swapped console.log under each other: the first restored a stale capture, which then swallowed the harness's own record lines that quote the worker, and one delivery's outcome could land in the other's list. Each delivery now collects in its own AsyncLocalStorage context, and record lines always print.
@yannickmonney

Copy link
Copy Markdown
Contributor Author

Both corrections from the independent review are in at 01ef3c4d3: 4bd0a63a7 is the fix and 01ef3c4d3 a lane-capture fix. The agent-before-task write-lock order and the same-session admission are unchanged, and so are the person's retry, the guard/refusal ordering and the locales.

B1: one future check per failed predecessor.

  • Busy checks now go through task.agent_retry_recheck, which uses the repo's documented short queue contract (the same one as chat.deferred_send_poll).
  • Every check carries the key agent-retry:<org>:<task>:<failed run>, so pg-boss's unique index keeps at most one queued check per failed predecessor. A second send is dropped, and the worker logs a check is already queued.
  • The arm stays on the standard task.agent_retry queue, so a keyless arm from the previous image can't be shut out mid-roll. The arm and the checks share one handler.
  • The failure's age, anchored in the database, bounds the whole chain.

B2: the refusal stays final.

  • retireBusyRetry sets project_agent_runs.auto_retry_refused_at_ms once, in the refusal's own transaction (migration 0141_project_agent_runs_auto_retry_refused.sql, a nullable column). Only the call that sets it writes the timeline row.
  • Every later delivery of that predecessor's retry stands down as retry_refused, whether the agent is busy or free: the arm, a check queued before the refusal, or the identical last check.
  • A newer run carries no mark: the manager's restart and a person's Start or Retry work as before.

Real-Postgres regressions (checkAutomatedRetryAgentBusy, all rounds retained, nothing dropped). The lane replays the delivery lifecycle over real pgboss.job states: fetch, ack, and expiry followed by retry.

Round Result
Reviewed head 38e36bf9d + final lane code, round 20260930t104154_r2_reviewed_negative_final 16/20
Main c276da375 + tests only, round …104337_r2_main_negative 102/115; only the new lane's 13 new-behaviour checks fail
This head 01ef3c4d3, round …104239_r2_branch_final 115/115 across the 13 retry/delegation lanes

At the reviewed head, the B1 duplicates leave 2, then 3, then 2 queued checks, and B2's identical last check starts a retry once the agent is free. At this head each step leaves one queued check (#1, #1, #1, #2), the chain moves on to #3, and every replay after the refusal answers retry_refused.

Unit tests at this head: 101 files and 1232 tests (server), 18 (client). Raw per-check details are in the task's round-2 receipts.

@yannickmonney

Copy link
Copy Markdown
Contributor Author

Exact-head review of 66b4481: the two earlier direct-handler lifecycle findings are fixed for their tested scope (14/14 independent controls versus 8/14 on 38e36bf). Final acceptance still needs one narrow drain repair and real PostgreSQL proof of the new queue/stamp behavior.

New P2: the existing worker drain handoff at services/platform/backend/jobs/runner.ts fetches without includeMetadata and re-sends only data plus startAfter:5. The new task.agent_retry_recheck short queue needs the original singletonKey. Two distinct due predecessors drained together therefore produce two null-key sends: one insert succeeds, the other conflicts with that created replacement, yet both originals are acknowledged completed. The second predecessor has no next recheck from this handoff.

The independent control executed the actual registered startWorker callback and pg-boss12.28.0 send validation/payload/SQL generation. Persistence was modeled from the exact short-policy unique index and ON CONFLICT behavior; this is not an observed live PostgreSQL job loss or deployment. The same control preserves both jobs on the prior standard queue. Revised worker controls are 2 pass / 1 failing handoff assertion; baseline is 3/3. Authored checks pass107/107 but miss this interaction.

Repair the existing drain path: fetch the metadata needed for faithful requeue and preserve its singleton key, payload and relevant scheduling metadata. Copying an undefined key without includeMetadata does not fix it. Keep the five-second delay and standard/keyless behavior; handle policy-specific conflicts carefully, because an exclusive queue can conflict with its own active job. Do not add a second retry engine or reconstruct the key in another place.

Before acceptance, use the actual registered worker and real PostgreSQL fetch/drain with two distinct keyed short-queue jobs; after both originals are acknowledged, verify both successor keys remain. Also cover duplicate/same-key collapse, an already queued predecessor successor, non-drain processing, standard/keyless handoff and the new predecessor refusal migration/transaction. Retain the completed and failed evidence, original B1/B2 expiry/refusal/new-decision proof, and exact final-head normal CI. Continue on existing PR3985 / TALE-389; no duplicate task, production test or broad capacity redesign.

Independent review of #3985 at 66b4481 (new P2): a draining worker
fetched jobs without their metadata and re-sent only the payload, five
seconds out. On a keyed queue the successor lost its singleton key: on
`short` (the new `task.agent_retry_recheck`) two distinct drained
predecessors both re-sent under the default empty key, the second insert
conflicted with the first and was dropped, and both originals were
completed — the second predecessor had no next check. An `exclusive`
queue's successor would even collide with its own still-active claim.

The worker now fetches with `includeMetadata`, and the hand-over
(`handOver`) completes the claim and queues its successor in ONE
transaction of the app's pool, the claim first: the successor keeps the
job's own payload, singleton key and priority (the fetched job's, never
reconstructed), five seconds out, so no policy refuses it for the claim
itself and a crash between the two writes loses or doubles nothing. A
successor its key finds already queued is not needed — that job does the
work. Keyless standard jobs hand over as before. main.ts passes `sql` with
`shouldDefer`, and the options type requires the pair.

Proof: `checkWorkerDrainHandOff` drives the actual registered worker
(`startWorker`) through real pg-boss fetches on throwaway `short`,
standard and `exclusive` queues. At 66b4481 it fails 3 of 5 checks:
of two keyed jobs drained together only keyless successors of the first
remain and the second has none; a drained claim gains a keyless extra
successor beside the job queued under its key; the exclusive successor
loses its key. Here all 5 pass (two keyed successors kept with their
keys and priority, +5 s; collapse onto the job already queued; keyless
standard hand-over unchanged; exclusive keeps its key; a worker that is
not draining runs the job).

Refs #3977
The automated-retry row of the automation register now names the drain
hand-over it depends on (checks of two failed runs drained together both
keep their next check) and its proof, checkWorkerDrainHandOff in
backend:integration and runner.test.ts.

Refs #3977
The review of 66b4481 asked for real Postgres proof of the predecessor
refusal's migration and transaction. checkAutomatedRetryAgentBusy now also
delivers the check that ends the wait twice at once, while the agent works
another task: one delivery refuses (agent_busy) and the other stands down
on the retirement mark (retry_refused); the timeline holds one refusal and
the failed run one mark, written together; nothing is queued and nothing
starts. The mark is read off the migration's column, a nullable bigint
recorded once in app_migrations.

Refs #3977
@yannickmonney

Copy link
Copy Markdown
Contributor Author

Re: the exact-head review of 66b448120 (#3985 (comment)).

The P2 is fixed in 5a11fac3a. This head is 5c1768948, with main 5f8dfea6b (#3988) merged in.

The fix, in jobs/runner.ts:

  • Fetch: the worker now fetches with includeMetadata.
  • One transaction, claim first: handOver completes the claim and queues its successor in one transaction of the app's pool (pg-boss's db option).
  • What the successor keeps: the fetched job's own payload, singleton key and priority, five seconds out as before. The key is never rebuilt anywhere.
  • Policy conflicts:
    • An exclusive queue never refuses the successor because of its own claim, since the claim is completed first, inside the transaction.
    • On short/stately, a key that already has a queued job gets no second one; that job does the work, as the documented collapse intends.
    • Keyless standard jobs hand over as before.
  • Per-job options: the app's are exactly startAfter, singletonKey and priority (EnqueueOptions). Retry and expiry are queue options, so they apply to the successor as they did to the job.
  • Wiring: main.ts passes sql with shouldDefer, and the options type requires the pair.

No second retry engine was added.

Proof on real PostgreSQL, with the actual registered worker. The new lane is checkWorkerDrainHandOff. It runs startWorker with real pg-boss fetches on throwaway short, standard and exclusive queues, which are deleted with their jobs at the end. Job shapes are state:key:seq:priority:+delay.

Case 66b448120 + this lane code this head
Two distinct keyed short jobs drained together FAIL: both originals completed; only keyless successors of one of them (completed:∅:2:p0:+5s ×3, created:∅:2:p0:+5s), and the p7 job's priority is lost. The other predecessor has none. PASS: created:a-…:1:p0:+5s and created:b-…:2:p7:+5s remain after both originals are completed
A successor already queued, and a same-key duplicate FAIL: an extra created:∅:3:p0:+5s sits beside the job queued first PASS: only the job queued first (created:c-…:30); the duplicate send is dropped
Standard/keyless hand-over pass PASS: seq 7 and 8, keyless, +5 s
Exclusive FAIL: created:∅:9:p0:+5s PASS: created:x-…:9:p0:+5s
Non-drain processing pass PASS: the handler ran and nothing was queued

The predecessor refusal's migration and transaction. A new check in checkAutomatedRetryAgentBusy delivers the check that ends the wait twice at once while the agent is busy. The result:

  • ["skipped:agent_busy"] and ["skipped:retry_refused"];
  • one timeline refusal and one mark on the failed run;
  • no queued check, and nothing started;
  • the column is a nullable bigint;
  • 0141_project_agent_runs_auto_retry_refused.sql appears once in app_migrations, after the harness's two concurrent boot migrations.

The B1/B2 proof is unchanged and passes at this head:

  • Queued checks after each step: #1, #1, #1, #2, and the chain moves on to #3.
  • Every replay after the refusal answers retry_refused.
  • The manager's restart answers started, its failure's retry is queued, and a person's Start answers 200.

Rounds. Each round is kept, runs on databases of its own, one at a time, and nothing was dropped.

Round Source Result
20260930t125221_r3_branch_merged this head, 14 lanes 121/121
20260930t124232_r3_branch_final2 f1ff57119 121/121
20260930t124340_r3_reviewed2_negative_final2 66b448120 + this lane code (sha256-identical) 118/121: exactly the 3 drain checks fail

The earlier round-3 rounds are kept as well: …123501 120/120, …123621 117/120, and the drain lane alone at …122154 22/22 and …122317 19/22.

Unit tests:

  • runner.test.ts has 8 tests. Three are new: the hand-over order begin → complete → send → commit with includeMetadata; a keyed job keeping its key and priority; and a failed hand-over keeping the claim for pg-boss to retry.
  • Server: 102 files, 1239 tests. Client: 18 tests.
  • Scoped tsc, oxfmt, oxlint --type-aware, lint:manual, lint:conflicts and lint:links all exit 0.

CI at this head: green: 51 checks pass, 11 are skipped (conditional jobs) and none fail; the PR is MERGEABLE / CLEAN. Backend integration (#3988: the whole suite with ITEST_REQUIRE_ALL_LANES, tale-db built from services/db, and the object store) ran on the merge ref ef8be9654: [itest] 1217/1217 checks passed across 206/206 lanes. That includes all 5 worker drain checks and all 21 busy retry checks. Job: https://github.com/tale-project/tale/actions/runs/36717738373/job/109895935201

@yannickmonney

Copy link
Copy Markdown
Contributor Author

Changes required at 5c17689489b1ce761f020216e511d00b89c1b955: the drain handoff still sends after boss.complete reports affected: 0. A cancelled or already-completed claim must not create a successor. Require confirmed affected: 1 before sending; stand down on zero and reject an unconfirmed/malformed result inside the transaction. Keep the corrected key, priority and complete-before-send ordering.

The result is discarded in the exact runner source. The pinned pg-boss completion updates active rows only. Zero is a legitimate cancellation/already-completed result, established in the retained real-Postgres controls. Independent controls importing this head's actual worker callback observe complete → send → commit for both zero-result cases; the previously reviewed local preparation sends nothing. Once no same-key successor remains, this can recreate retired work. The completed-claim replay was explicit; this is not a claim that transport redelivery or a stale active lease was reproduced.

The same result-validation repair should retain the narrow send-result guard: null is acceptable for the supported short/stately coalescence contract, while an unexplained null must abort. The standard/exclusive null probes are synthetic defensive-boundary cases, not separately observed production paths or additional findings. Reusing the existing transaction adapter would also avoid a duplicate implementation, but that is not another correctness blocker.

Validation: ten paired inert actual-runner controls pass 10/10 on the accepted preparation and 6/10 on this head. The four failing assertions are the two zero-completion cases and two injected-null cases above. These are controlled callback/transaction boundaries, not a new database run. The real hosted Backend integration job 109895935201 genuinely executes and passes 1,217/1,217 checks across 206/206 lanes, including the five drain happy-path checks and concurrent terminal refusal/migration-column check. Its tested merge is ef8be96544e2444ee74d947fc7c0237a3b595a92; the only differences from this head are the nine already-merged #3995 UI/docs/manual files. It does not cover this remaining completion-result boundary.

Please add cancelled-original and already-completed-original regressions, plus the narrow refusal controls, while preserving the existing admission and retry corrections. The older preparation's real-Postgres 9/9 receipt cannot transfer wholesale to different source. No competing patch was pushed, no production test was run, and the recurring cycle stays disabled. A fresh source review and normal CI are still required before merge.

@yannickmonney
yannickmonney merged commit c6fdc26 into main Sep 30, 2026
62 checks passed
@yannickmonney
yannickmonney deleted the fix/agent-retry-busy-admission branch September 30, 2026 13:38
@yannickmonney

Copy link
Copy Markdown
Contributor Author

Re: #3985 (comment). #3985 was merged as c6fdc26fb two minutes after this review, so the correction is in the follow-up #4003: e6bdde08b on main ea7de2e39.

What changed:

  • Completion guard. The hand-over sends the successor only after boss.complete confirms affected: 1.
    • On affected: 0 it stands down: no successor, and the empty transaction commits.
    • Any other answer throws inside the transaction and rolls back.
    • The key, priority, payload, complete-before-send order and the single transaction are all kept.
  • Send guard. A null send collapses only on a short or stately queue, per pg-boss's own record of the queue. On any other policy, or a queue it cannot find, the hand-over rolls back.
  • One adapter. bossDbInTx (jobs/enqueue.ts) now serves both addJobInTx and the hand-over.

Proof on real Postgres with the actual worker (checkWorkerDrainHandOff, retained local rounds):

  • Main ea7de2e39 plus the new lane code: 122/127.
    • The cancelled-original and already-completed-original cases each still get a successor after the real {"requested":1,"affected":0} answer.
    • The synthetic standard and exclusive refusals and the unconfirmed completion all end completed.
  • This head: 127/127.
    • No successor follows affected: 0.
    • Each synthetic case ends failed with its reason, because the hand-over was rolled back.
  • The real stately collapse passes on both.
  • The 14 new unit tests fail on main's runner and pass here.

The B1/B2 admission, the lock order and the durable retirement are untouched. #4003 has the raw lines and the source bridge (5c1768948 ≡ c6fdc26fb on #3985's paths), and its CI runs the full Backend integration suite.

yannickmonney added a commit that referenced this pull request Sep 30, 2026
The first Backend integration run on 33b8f17 passed 1225 of 1226
checks. The one failure, "busy retry, racing: while a delegated start
holds the agent row", comes from #3985's lane, which is intermittent on
main and under load and never touches model resolution. This token
cannot re-run a job, so this empty commit starts the checks again.
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.

1 participant