Repository navigation
fix(platform): close automation run lifecycle dead-ends and races - #3158
Merged
Merged
Conversation
The durable run store had dead-ends and surprises. This makes every run state change observable and every terminal door honest, so a started run visibly progresses and never strands. - Emit an `automation_run` hint from every state writer (begin, claim, progress, suspend, finish, cancel). The frontend already keys run queries under `automation_run` and the SSE bridge invalidates by entity, so a run in flight now updates without a manual reload (no frontend change). - Validate cron + timezone at `setTrigger` (`assertTriggerValid`, via parseCron/wallClockIn) so the HTTP door and the engine door converge on one door — an invalid schedule is refused at SAVE instead of saving green and silently never firing. - Claim a run with a single atomic `claim_epoch = claim_epoch + 1` RETURNING, closing the read-then-write lost update that let two steppers share an epoch and double-step one run. - cancelRun now honors the terminal contract finishRun documents: the provenance audit row (live runs) and freeing the run's sandbox sessions, via a shared `stopRunSandboxSessions`. - beginRun ALWAYS validates a caller-supplied projectId exists in the org before it lands on the run (webhook `?projectId=` and /start passed it straight through); the /start schema string is capped. - Refuse deleting an automation while any run is live (the active-run guard the core store documents and this wired path had dropped). Tests: colocated `assertTriggerValid` unit suite; integration checks for the hint emit, the atomic-claim distinct epochs, cancel's audit + session stop, projectId refusal at both doors, and the mid-run delete guard.
The automation-agent watchdog scans only `waiting` runs, so a crash in the kick to cursor-persist window — where the run is `running` with no cursor — was invisible to it, and a liveness re-poke re-kicked a SECOND agent turn (double LLM spend, duplicate effects) while the first was still in flight, its output dropped for want of a matching cursor. - Before kicking, `stepAgentNode` queries the run's still-running workflow-agent op (`loadLiveAgentOpForRun`) and, if one exists, ADOPTS it — rebuilds the cursor on that exec and parks — instead of kicking a second turn. The in-flight turn then settles into the adopted cursor. Composes with the atomic claim, which already elects one walker per re-poke. - The agent settle (`recordAgentTurnSettled`) emits the run hint too, so the agent result landing nudges open run views. - A run whose automation was force-deleted (no document to load) is marked terminal instead of returning `missing` and looping — the liveness sweep no longer re-claims it forever, freeing its sandbox session (belt-and- suspenders behind the delete guard). Test: integration check that the live-op query adopts an in-flight turn and clears once it settles.
cancelRun now opens its own transaction (audit + session stop + hint ride the cancel atomically), but the task workflow-cancel door already runs inside a serializable tx and a postgres.js transaction handle carries no begin at runtime. Split the body out as cancelRunInTx for in-tx callers; the root-handle wrapper keeps every other door unchanged.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes a class of automation run-lifecycle dead-ends and surprises: a
started run shows frozen forever, a mistyped schedule saves but never fires,
deleting or cancelling a run leaves orphans, and two steppers can race one run.
The fixes compose into one coherent run state machine.
The lifecycle invariant
A started run visibly progresses and reaches an honest terminal state:
every state change emits an
automation_runhint; a single stepper owns a runvia an atomic claim epoch; a live agent turn is adopted, not re-kicked;
every terminal door (finish AND cancel) writes the audit row and frees the
run's sandbox sessions; a bad schedule fails loudly at save; a
caller-supplied
projectIdis validated before it lands on a run; anddeleting an automation mid-run is refused, not silently stranding.
State → transition → writer
domains/automations)beginRunInTx(validates projectId)claimRun(atomicclaim_epoch + 1)recordProgresssuspendRunshim: recordAgentTurnSettledfinishRuncancelRundeleteAutomationCascade(refuses)Per finding
automation_runhint and no run query polled. SharedemitRunHintis nowemitted from begin/claim/progress/suspend/finish/cancel + the agent settle.
The frontend already keys run queries under
automation_runand the SSEbridge invalidates
['backend',orgId,entity], so this is the whole fix — nofrontend change. The stale Convex-era comment in
queries.tsis corrected.setTriggernever validated.
assertTriggerValidnow validates cron (parseCron) andtimezone (
wallClockIn) at the store door both the HTTP door and the enginedoor reach, refusing with
AUTOMATION_TRIGGER_INVALID. The refusal reachesthe trigger editor through the existing
automationErrorMessageplumbing.dropped the active-run guard the core store documents. It now refuses
(
AUTOMATION_HAS_ACTIVE_RUNS, 409) while any run is queued/running/waiting;belt-and-suspenders, the stepper marks a version-less run terminal instead
of returning
missingand looping.claimRunread then wroteepoch+1under READ COMMITTED, so two claims shared an epoch and bothpassed the fence. Now a single atomic
UPDATE … claim_epoch = claim_epoch + 1 … RETURNING.kick→cursor-persist window leaves a run
runningwith no cursor; thewatchdog only scans
waiting, so a re-poke re-kicked a SECOND agent turn.Before kicking,
stepAgentNodenow adopts the run's still-runningworkflow-agent op (
loadLiveAgentOpForRun) — rebuilds the cursor on itsexec and parks — instead of kicking. Residual below.
but wrote no audit row and freed no sandbox sessions. It now writes
automation.run.cancelled(live) and stops sessions via the sharedstopRunSandboxSessions, same asfinishRun.when bindings existed, so an unbound automation let any string (a phantom or
another org's id) land on
project_id.beginRunInTxnow ALWAYS validatesthe project exists in the org (
AUTOMATION_PROJECT_UNKNOWN, 404); the/startschema string is capped.Divergent copies reconciled
core/automations/store.tsis the vestigial Convex-era copy (zero importers)that documents the delete guard; the live path is the PG
domainscopy. Theguard is restored in the live copy — one guard, not zero. The dead file is left
to the convex-retirement campaign (out of this class's scope).
Residual (finding 5 — documented, not a regression)
The adopt guard eliminates the CONCURRENT double-spend (two turns for one node
at once) and preserves the first turn's output. One narrow window remains: if
the first turn fully settled-and-was-dropped (op already terminal) BEFORE the
re-entry, the guard sees no running op and re-kicks once — a single wasted
turn, not a concurrent double-drive, producing the output the crash lost.
Closing it fully needs a lost-cursor turn reconstructible from the sandbox op
subsystem (out of this class).
Tests & gates (observed)
tsc --noEmit): 0 errors.oxlint --type-aware) on touched files: clean.assertTriggerValidsuite (7).(the one non-pass was the object-store bucket-heal probe, environmental —
it passed on the prior branch run with a fresh bucket).
all 7 lifecycle checks FAIL, each reproducing its bug — the claim
lost-update shows epochs
[1,1,1,1,1,1,2,2,2,2,3,3](six claimants sharingepoch 1); cron
badCron=200/noCron=200/badTz=200; hintsrun=0; projectId/start=201, webhook=202; cancelaudit=0, session=active; deletemid-run=200, survived=0; live-opno-handler. Full suite 278/286(the 7 class reds + 1 environmental sandbox-spawner probe).
Two atomic commits (the durable run store; the stepper/shim crash-safety).
Draft — do not merge.