Repository navigation
fix(platform): recheck agent occupancy before an automated retry - #3985
Conversation
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.
|
Independent review at
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.
|
Both corrections from the independent review are in at B1: one future check per failed predecessor.
B2: the refusal stays final.
Real-Postgres regressions (
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 ( 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. |
|
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
|
Re: the exact-head review of The P2 is fixed in The fix, in
No second retry engine was added. Proof on real PostgreSQL, with the actual registered worker. The new lane is
The predecessor refusal's migration and transaction. A new check in
The B1/B2 proof is unchanged and passes at this head:
Rounds. Each round is kept, runs on databases of its own, one at a time, and nothing was dropped.
The earlier round-3 rounds are kept as well: Unit tests:
CI at this head: green: 51 checks pass, 11 are skipped (conditional jobs) and none fail; the PR is |
|
Changes required at 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 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 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. |
|
Re: #3985 (comment). #3985 was merged as What changed:
Proof on real Postgres with the actual worker (
The B1/B2 admission, the lock order and the durable retirement are untouched. #4003 has the raw lines and the source bridge ( |
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.
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 calledkickAgentRundirectly. 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:pa-<agent>).What changed
lockAgentForStartbefore 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.transactSerializableretry sees the other run and answersagent_busy.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.kickAgentRun({ sessionId })), so the run lands in the workspace the probe checked.task.agent_retry_recheck, a queue under the documentedshortcontract (aschat.deferred_send_poll). Each carries the keyagent-retry:<org>:<task>:<failed run>(agentRetryRecheckKey), so pg-boss's unique index allows at most one queued check per failed run.startAfterMs, and counts itself inagentBusyWaits. No check is sent more than 2 hours after the failed run settled; that database-anchored age bounds the whole chain (planAgentBusyWait).retireBusyRetryretires the failed run's automatic retry on the run itself. The mark isauto_retry_refused_at_ms(migration0141_project_agent_runs_auto_retry_refused.sql), a nullable column, safe to add mid-roll.agent_run.refused,agent_busy: "Run refused: agent is working on another task", with the failure banner), following the circuit breaker's convention.retry_refused, whether the agent is busy or free: the arm, a check queued before the refusal, or the refusing job itself.jobs/runner.ts) hands every job it claims over to the live colour.includeMetadata.handOvercompletes 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.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.exclusivejob's successor is not refused by its own claim. Keyless jobs on a standard queue hand over as before.startAfter,singletonKeyandpriority(EnqueueOptions). Retry and expiry are queue options, which apply to the successor as they did to the job.main.tspassessqlwithshouldDefer, and the options type requires the pair.task_movedand 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.tasks.agentRuns.refused.agent_busy), plus a guard that every refusal code a task writer records has a label.platform/projects/task-automation.md).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.
At the reviewed head, running this branch's lane code, the regressions fail:
wait=1checks; a late arm plus the taken check leaves 3; the expired check run twice leaves 2wait=2.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
shortjob 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.
checkWorkerDrainHandOffdrives the actual registered worker (startWorker) through real pg-boss fetches on throwawayshort, standard andexclusivequeues, 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):completed:∅:2:p0:+5s×3 andcreated:∅:2:p0:+5s: the draining worker claims them again, and the successors of thep7job have lost its priority. The other predecessor has no successor.created:∅:3:p0:+5s.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:+5sandcreated:b-…:2:p7:+5sremain once both originals arecompleted.cdoes the work, with no second successor, and a same-key duplicate send is dropped.created:x-…:9:p0:+5s.runner.test.tsadds three unit tests: the hand-over's order (begin → complete → send → commit, withincludeMetadata), 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.
checkAutomatedRetryAgentBusynow also delivers the check that ends the wait twice at once while the agent is busy:agent_busy); the other stands down on the mark (retry_refused).bigint.0141_project_agent_runs_auto_retry_refused.sqlis recorded once inapp_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 sharedtale_app/tale_knowledgewere never touched. Turn jobs were held inert, so no sandbox, provider or model was involved.The 14 lanes:
checkAutomatedRetryAgentBusy: 21 checks.checkWorkerDrainHandOff: 5 checks.checkTaskAgentRuns,checkTaskAgentTurnDrive,checkOneLiveRunPerTask,checkTaskRunStartFence,checkTaskRetryProjectEligibility,checkScheduledAgentStarts,checkDelegatedAgentStartTool,checkInPlaceCompletionCycle,checkAutoRetryAndKickPlan,checkCredentialRotationRetry,checkCooledStartRetryandcheckTaskRunConnectorCaller.20260930t125221_r3_branch_merged5c1768948(main5f8dfea6bmerged in)checkTaskAgentTurnDrive)20260930t124232_r3_branch_final2f1ff5711920260930t124340_r3_reviewed2_negative_final266b448120+ this lane code (sha256-identical)20260930t123501_r3_branch_final/…123621_r3_reviewed2_negative_final067b4deaa/66b448120+ tests, before the refusal-at-once check20260930t122154_r3_branch_drain/…122317_r3_reviewed2_drain_negative66b448120+ tests, drain lane only20260930t104154_r2_reviewed_negative_final38e36bf9d+ round-2 lane code20260930t104337_r2_main_negativec276da375+ the tests20260930t104239_r2_branch_final/…113413_r2_branch_merged01ef3c4d3/66b448120The first round's evidence, which Root already holds, is unchanged: main
17cecce07+ tests gave 102/112, and38e36bf9dgave 112/112. One round-2 run at4bd0a63a7scored 114/115 because of a race in the lane's own log capture, not in the product. It is kept as it is, and01ef3c4d3gave each delivery its ownAsyncLocalStoragecapture.Raw replay outcomes at this head.
task.agent_retry_recheck#1,#1,#1,#2, and the chain still moves on to#3.["skipped:retry_refused"].started, its failure's retry is queued, and a person's Start answers 200.Raw race outcomes (verbatim in each round's log):
delegated+auto_retry) inpa-<agent>. All 3 unordered rounds do too:winner=none … start attempts=1 failed with=[] live=["auto_retry@retry task","delegated@start task"].pg_blocking_pids) while holding no task lock (FOR UPDATE NOWAITon the task succeeds), then waits.40001, and its second answersagent_busy.winner=retry … start=agent_busy start attempts=2 failed with=["40001"] live=["auto_retry@retry task"].40P01) beside a delegated restart of the same task. In that interleaving, the real retry queues on the agent row and stands down assuperseded.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:shortpolicy, "already queued", and one worker for both queues;runner.test.ts(8 tests).task_auto_retry.test.ts(planAgentBusyWait) andagent-runs.test.ts(the kick into a caller's session).integration-skipsand ci: run the real-Postgres integration suite in CI #3988'sintegration-scope, and the platform i18n suite.display.test.ts, with the refusal-label guard, plus the timeline and the failure banner (18 tests).Other checks, all exit 0: scoped
tscon every changed file,oxfmt --check,oxlint --type-awareon the changed files,lint:manual,lint:conflictsandlint:links.CI. Since #3988, CI's Backend integration job runs the whole
backend:integrationsuite on this PR: every lane,ITEST_REQUIRE_ALL_LANES, the tale-db image built fromservices/db, and the object store. The two new lanes and migration 0141 are part of that run. At5c1768948it passes1217/1217 checks across 206/206 lanes, including all 5worker drainand 21busy retrychecks. The whole check set passes: 51 pass, 11 are skipped (conditional jobs) and none fail.Not in this PR (TALE-386)