Skip to content

fix(platform): close automation run lifecycle dead-ends and races - #3158

Merged
larryro merged 4 commits into
mainfrom
fix/automation-run-lifecycle
Sep 3, 2026
Merged

larryro merged 4 commits into
mainfrom
fix/automation-run-lifecycle

Conversation

@larryro

@larryro larryro commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

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_run hint; a single stepper owns a run
via 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 projectId is validated before it lands on a run; and
deleting an automation mid-run is refused, not silently stranding.

State → transition → writer

State / event Writer (domains/automations) Emits hint Terminal contract
queued beginRunInTx (validates projectId) yes —
running (claim) claimRun (atomic claim_epoch + 1) yes —
running (progress) recordProgress yes —
waiting (ask/park) suspendRun yes —
agent result landed shim: recordAgentTurnSettled yes —
success / failed finishRun yes audit (live) + stop sess
cancelled cancelRun yes audit (live) + stop sess
delete while live deleteAutomationCascade (refuses) — 409, run untouched

Per finding

  1. Run pages never update (high/dead-end). No writer emitted an
    automation_run hint and no run query polled. Shared emitRunHint is now
    emitted from begin/claim/progress/suspend/finish/cancel + the agent settle.
    The frontend already keys run queries under automation_run and the SSE
    bridge invalidates ['backend',orgId,entity], so this is the whole fix — no
    frontend change. The stale Convex-era comment in queries.ts is corrected.
  2. Invalid cron/timezone saves green, never fires (high/ux). setTrigger
    never validated. assertTriggerValid now validates cron (parseCron) and
    timezone (wallClockIn) at the store door both the HTTP door and the engine
    door reach, refusing with AUTOMATION_TRIGGER_INVALID. The refusal reaches
    the trigger editor through the existing automationErrorMessage plumbing.
  3. Delete mid-run strands the run (high/dead-end). The wired cascade
    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 missing and looping.
  4. Claim epoch lost-update (high/reliability). claimRun read then wrote
    epoch+1 under READ COMMITTED, so two claims shared an epoch and both
    passed the fence. Now a single atomic UPDATE … claim_epoch = claim_epoch + 1 … RETURNING.
  5. Stepper double-spend twin (medium/reliability). A crash in the
    kick→cursor-persist window leaves a run running with no cursor; the
    watchdog only scans waiting, so a re-poke re-kicked a SECOND agent turn.
    Before kicking, stepAgentNode now adopts the run's still-running
    workflow-agent op (loadLiveAgentOpForRun) — rebuilds the cursor on its
    exec and parks — instead of kicking. Residual below.
  6. cancelRun without the terminal contract (medium/bug). It flipped status
    but wrote no audit row and freed no sandbox sessions. It now writes
    automation.run.cancelled (live) and stops sessions via the shared
    stopRunSandboxSessions, same as finishRun.
  7. beginRun accepts unvalidated projectId (medium/tenant). Validated only
    when bindings existed, so an unbound automation let any string (a phantom or
    another org's id) land on project_id. beginRunInTx now ALWAYS validates
    the project exists in the org (AUTOMATION_PROJECT_UNKNOWN, 404); the
    /start schema string is capped.

Divergent copies reconciled

core/automations/store.ts is the vestigial Convex-era copy (zero importers)
that documents the delete guard; the live path is the PG domains copy. The
guard 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)

  • platform typecheck (tsc --noEmit): 0 errors.
  • lint (oxlint --type-aware) on touched files: clean.
  • server vitest (automations domain): 67 passed, incl. the new
    assertTriggerValid suite (7).
  • backend:integration on a throwaway tale-db + MinIO:
    • Branch: all 7 new lifecycle checks PASS; full suite 285/286
      (the one non-pass was the object-store bucket-heal probe, environmental —
      it passed on the prior branch run with a fresh bucket).
    • Base proof (the 8 source files stashed to base, the new checks kept):
      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 sharing
      epoch 1); cron badCron=200/noCron=200/badTz=200; hints run=0; projectId
      /start=201, webhook=202; cancel audit=0, session=active; delete
      mid-run=200, survived=0; live-op no-handler. Full suite 278/286
      (the 7 class reds + 1 environmental sandbox-spawner probe).
    • Net for the class: 7 red → 7 green.

Two atomic commits (the durable run store; the stepper/shim crash-safety).
Draft — do not merge.

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.
@larryro
larryro marked this pull request as ready for review September 3, 2026 04:20
@larryro
larryro merged commit c28a5f5 into main Sep 3, 2026
23 checks passed
@larryro
larryro deleted the fix/automation-run-lifecycle branch September 3, 2026 04:20
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