Repository navigation
fix(platform): keep automation runs safe across restarts and redeploys - #4516
Conversation
A claim took a running run unconditionally, so a duplicate step job or a sweep re-poke started a second walker on the same step, and the epoch fence stopped the loser only after its effect. Progress, park, hand-off and finish read the run row unlocked and then wrote it by id alone, so a stop committed between the two could be overwritten by a finish. - 0160 adds the run lease (owner, expiry, the epoch it belongs to), the resume stamp and the engine protocol stamp; 0161 the append-only run events; 0162 the effect ledger (node attempts). - claimRun locks the row and refuses a live lease whoever holds it, takes over a lapsed one (counted and recorded), honours an older image's promise, and re-queues a run a newer engine stamped. - recordProgress, suspendRun, continueRun and finishRun are one statement each, fenced by the claim epoch and a live status; the node checkpoint merges in the database; a stop committed first leaves the finish landing nothing. - The heartbeat renews the lease every 10 s; new, handed-off and woken runs are born with the claim promise; the sweep re-checks each poke and records a lapsed lease; releaseOwnedRunLeases hands a stopping process's runs on. - node-attempts.ts holds the ledger's store half (begin fenced by the epoch, finish, the open in-doubt read, a person's decision) and the shim answers the two ledger mutations. - Spec AUTO-R16/AUTO-R17, manual AUTO-B12, integration probes.
A run that moved to another server, or that waits on a write which may
already have reached its service, read as an ordinary running or waiting
run: nothing said it had been handed on, and a run parked in doubt had no
way on in the app.
- The run read carries resumeCount, lastResume {reason, at} and stalled
(a lapsed lease, or a shutdown hand-off nobody claimed yet; not a
budget hand-off after a takeover, nor a row an older image claimed);
an in_doubt:<node> park reads waitingFor in_doubt. No read names the
server.
- failureCode gains engine_incompatible and effect_in_doubt.
- Contract 3.18.0: OpenAPI Run/RunSummary, regenerated document and
fingerprint, REST ?fields= for the new keys.
- App doors GET /runs/:runId/in-doubt (read rule) and POST
/runs/:runId/in-doubt/:attemptId (the stop's write gate).
- Run page: Interrupted badge, resumed line, and the in-doubt card with
Run it again and Fail the run behind a confirmation and Skip it; the
run list shows the badge and the park in words. @tale/ui exports its
existing useFocusHandoff for the card.
- Strings en/de/fr; API reference and run guide en/de/fr; spec
AUTO-R18, manual AUTO-F57, reference row, integration probe #4h.
A resumed run used to call again every write its earlier walk had made before the checkpoint landed, and one worker stepping two organizations' runs could hand one run the other's approval gate. - Live connector writes and model calls go through the effect ledger: a finished call is reused, a recorded failure replayed, and a write that may already have reached its service parks the run on `in_doubt:<node>` until a person retries, skips or fails it (`effect_in_doubt`). Model calls and actions declaring the new `idempotent` field are re-called. - Calls inside a subautomation are addressed by their nested path, and a park, a stale claim or a person's fail there acts on the calling node. - Connector keys add the pass from the second repeat pass on and the nested path, the same in the in-memory executor. - Each run carries its own approval gate; the setter now overrides every run until cleared. - Saved progress the engine cannot read fails the run (`engine_incompatible`) instead of starting it over; a progress write answering anything but a live status ends the walk. - A subautomation node pins the versions of its chain on first entry. Spec AUTO-R19 to AUTO-R21, manual AUTO-F58, AUTO-B13, AUTO-A6, the reference row, and the `idempotent` field in the connector docs.
A stopping backend gave its jobs only pg-boss's graceful stop: a walker mid-step ran on until the container's 10 s kill and was cut mid-call, and its run sat on a dead lease until another worker took it over. Shutdown now begins before anything waits (lib/shutdown.ts). A walker hands its run on at its next step boundary or forEach item, before its first step when claimed during shutdown, and when its replica is drained. A step still running at the grace (20 s, or a third of a shorter SHUTDOWN_DRAIN_MS) is cut: its model call and connector request abort, a live connector body is raced (INTERRUPTED), and the run is handed on as interrupted, never failed, its ledger attempt left open. A long loop saves its cursor every ten items or ten seconds. The process then waits for its walkers, releases what it still holds, waits out other jobs up to SHUTDOWN_DRAIN_MS (15 s api, 90 s worker) and closes its pools; a job fetched after shutdown began is handed over unstarted. Agent drive windows end running on shutdown without cutting the exec, and drive jobs carry a 60 s heartbeat. A drain counts the automation runs the drained colour holds and the drive windows that began before it. compose.yml gives backend-api 30 s and backend-worker 120 s to stop. Spec AUTO-R22 and CTRL-R5, manual box AUTO-F59, docs in en, de and fr.
The generated backend roles had Docker's 10 s stop default, so a worker was killed mid-step on every deploy. backend-api now gets 30 s and backend-worker 120 s, the same as compose.yml (the backend's drain plus 15 s), and a parity test holds both pipelines to it. A colour's containers are stopped together before they are removed, so N worker replicas no longer add up to N times their grace. The drain says it waits for chat turns and automation steps, and names the breakdown a newer backend reports; an older backend's bare count still reads.
Automation step jobs were fetched in batches and awaited whole, so one step walking its minute-long budget held every step fetched with it, and one organization's burst of runs could take every worker's step slots while other organizations' runs waited. The step queue now runs in one-job slots (WORKER_CONCURRENCY of them). Every step job carries its organization as its pg-boss group, derived in addJobInTx so no enqueue site can leave it out, and a worker gives the queue a database-counted group limit of AUTOMATION_ORG_CONCURRENCY (default 8, 0 lifts it). A drained worker's hand-over keeps the group, and a 30 s heartbeat stops a killed worker's step counting against its organization within about a minute and a half. Jobs sent by the previous image carry no group and are never held back. A booting worker also queues one liveness sweep, so a worker restarted after a crash pokes the runs the dead one left at once. Manual box AUTO-P3; the variable in .env.example, the backend README and the environment reference in en, de and fr.
The contract debt ledger now names what the run lease, effect ledger and cooperative shutdown work leaves for later: an in-doubt step is decided in the app only (no REST, MCP or task-panel door); an in-doubt park notifies nobody; no shipped connector action is marked idempotent yet; an erasure keeps the subject's id on questions answered and in-doubt steps decided in other people's runs; and the first roll onto run leases protects one way only. The manual chaos boxes AUTO-L1 to AUTO-L5 drive Convex doors that no longer exist; they are recorded as BL-8 and point testers at it.
A decision committed first and woke the run parked behind it afterwards, best effort: a wake that failed then left the run to its 30 s approval poll, and a decision that landed while the walker was between its gate read and its park found the run still walking and woke nothing. decideApproval now locks the run's row before the approval's (run, approval, audit chain: the order a stop takes) and wakes the run in the same transaction, so a wake that cannot be queued leaves the decision unrecorded and deciding again works. A park on an approval reads it after its own write holds the run, and wakes the run at once when the approval was decided meanwhile. The approval poll is now a ten-minute backstop, and the card says approving lets the step act right away (en, de, fr). Spec APV-R11 is reworded and APV-R12 added; the decide-resume integration lane proves the rollback, the retry and the park that wakes itself.
- The sweep turns the lapsed promise of a running run an image without leases left into a lapsed lease, so the step it queues takes the run over instead of being refused every sweep for good. - A write that ends after another walker parked the run on it wakes the run; the park and its poll find it due as well, so the next walker reads the end instead of waiting for a person. A walker whose own lease lapsed begins no write. - A poll moves nothing on a run its park no longer holds. - A decision lands only on the write the run's card shows. - An agent node's park keeps a result, a new exec or a later deadline written while its walker was on its way, and wakes the run for a result.
- Inside a subautomation every live call goes through the effect ledger as one that may be made again: a walk after an interruption reads what the first walk read, so its writes stay addressed to the same items — none is skipped and none sent twice. - A turn claimed while its server stops hands a loop it would resume on before its next item. - A walker cut and still not settled 30 seconds later stops renewing its lease, so another worker can take the run over. - A run a person failed at an in-doubt write says so without naming the step twice or a nested path. - The connector idempotency key comment no longer claims nested keys match earlier releases.
Two worker containers on the host's network, or given one fixed host name, reported the same host and pid, so a stopping worker released its sibling's live leases. A random per-process segment before the version keeps them apart; the colour stays last.
A generated compose file gave the backend roles a fixed 30 s and 120 s, so a longer SHUTDOWN_DRAIN_MS was cut short with no log line. Both roles now get 15 s above a longer drain, and `tale dev --stop` waits a little longer than the worker's grace instead of timing out while it drains.
- A task whose run waits on a write that may already have run says so, shows no spinner and offers the decision card to someone who can work the task; anyone else reads that it waits for a decision. - The canvas and the task's run timeline read a person's wait as waiting there and a stalled run's step as interrupted there; nothing spins on a step no server is running. - The resumed line waits until a server has the run again and sits on its own row; the stalled badge is blue, apart from the orange Live badge. - The in-doubt card is a labelled Card section with its own heading, the accent of a move that is the reader's and one polite announcement; its explanation stays mounted while loading; it says which choice fits which answer, claims nothing about how the run goes on once decided, and offers the choices again when a write run again is interrupted again. - The waiting reason reads "Waiting for a decision" instead of "Needs you".
The audit log showed the raw action for a run's end, stop, deletion and
the new decision about an interrupted step ("automation.run.in doubt
resolved"). Each now reads in words in en, de and fr.
- Concepts lists `in_doubt` among the waits that need a person, and says nobody is notified. - The upgrade guide, the environment reference and .env.example no longer promise that a step cut at shutdown always runs again: a write to an outside service waits for a person. The first roll takes over a run the old workers left after about four minutes, and may send their write again. - The `SHUTDOWN_DRAIN_MS` row says `tale deploy` keeps the stop grace above a longer drain. - The debt ledger records the in-doubt card in the task panel, the new waiting reason, the first roll's nested write keys and the lease's reliance on synchronised clocks.
AUTO-F60 decides an interrupted write from the task panel and checks the canvas reads waiting and interrupted steps without a spinner. AUTO-F57 uses a step that keeps the run running, AUTO-F59 allows the brief Interrupted read its graceful hand-off has, and AUTO-A6 adds the card's heading and announcement. The error register gains the in-doubt card's three refusals, and the automation register the review fixes the unit tests own.
The navigation fix mints AUTO-F57 and AUTO-B12 in the same suite; the run-robustness boxes move to AUTO-F58–F61 and AUTO-B13–B14.
Other suites mock the stop and remove helpers process-wide, so in a full run the teardown test reached their stubs and waited out the 30 s timeout. The test now binds both helpers to its docker spy and bounds its wait.
The step's input renders in a viewer that loads on first use; on a cold Chromium the synchronous read ran before it arrived.
Main gained the navigation fix (#4514); both changes append boxes to the automations manual suite, kept in ID order (AUTO-F57 then AUTO-F58+).
|
FINDINGS — API-only post-merge review of #4516 (TALE-1215, Codex #10). I did not implement this PR. Acceptance object:
Per-criterion disposition
CI evidence — read on 2026-10-08 at 06:05:13.329629Z (PR head, 98 checks) and 06:05:13.975151Z (main, 72 checks). Each response fits one
Security's PR-head readiness success includes skipped Bun audit and Trivy filesystem jobs; the separate Trivy result is neutral. Those are not audit execution passes. Main E2E absence is consistent with Inspected Backend integration job logs: PR job 113161293053, run 37730641125, read 06:08:06.571594Z, finished 05:24:01.8787283Z; main job 113164122245, run 37732315017, read 2026-10-08T06:08:08.949348+00:00, finished 05:33:00.7884529Z. Both explicitly report 1686/1686 checks across 235/235 lanes. Both include PASS for twelve concurrent claims/one winner, expired-lease takeover/stale-write refusal, owned shutdown release, previous-image promise recovery, and ledger race/reuse/decision wake. The logs also contain recovered serialization retries; they are retained, not hidden. Downloaded and inspected all two platform unit and four platform UI shard summaries for each of those runs: platform test tasks show cache MISS, exitCode 0, with hashes/timestamps retained. PR summaries identify checkout Known limits already recorded by the implementation
Coverage and unrun limits
The complete 166-file two-page diff is captured in The detailed source review concentrated on lease/attempt/checkpoint/stepper/shutdown/approval/queue/connector/CLI paths and the in-doubt UI. The following changed files received only a scope/hunk/test-structure skim rather than a complete semantic review; test titles establish intended cases, not independent runtime proof. Files only skimmed
Evidence delivery: |
What changes
Automation runs now survive redeploys, crashes and slow databases without silently repeating work, and the run page says when a run was interrupted and resumed.
One walker per run (a real lease). A run is claimed with a 30 s lease renewed every 10 s; a live lease is never stolen, so a duplicate step job is a cheap refused claim instead of a second walker repeating a node. Run writes (progress, park, hand-off, finish) are single fenced statements that merge the node checkpoint in the database; a cancel that lands between two writes now always wins (it was overwritten to
successbefore). Runs the previous image claimed are taken over once that image's own promise lapses (migrations0160–0162).Cooperative shutdown. A process-wide shutdown signal makes a walker hand the run on at the next step or loop-item boundary; a step still running after a 20 s grace is aborted through signals plumbed into model and connector calls; agent drive windows end as
runningand chain the next window at once instead of waiting for the watchdog. The process releases its leases in one statement, so another worker resumes in seconds.compose.ymland the CLI givebackend-worker120 s andbackend-api30 s to stop (raised further whenSHUTDOWN_DRAIN_MSis), and the drain now counts running automations, not only chats.No blind repeats of writes. A node-attempt ledger records each connector write and model call before and after it runs. On resume, a finished attempt reuses its output; an attempt that started but never finished is in doubt: a write is re-sent only when its action declares itself idempotent, otherwise the run waits (
waitingFor: in_doubt) with a card offering Retry, Skip with empty output or Fail run — on the run page and the task panel.Cross-tenant fix. The approval gate was a process global that each turn overwrote, so two organizations' live runs on one worker could fail with "asked to decide for a different organization". It now lives on each run.
Engine stamp. Runs record the engine protocol and version that stepped them; a run stamped by a newer engine is deferred, and progress this engine cannot read fails as
engine_incompatibleinstead of silently starting over. Unpinned subautomations are pinned at first execution.Throughput.
automation.stepruns in slots (no head-of-line batch) with per-organization fairness (AUTOMATION_ORG_CONCURRENCY, default 8); an approval decision wakes its run inside the decision's transaction and parked approvals poll only as a 10-minute backstop.Visible to people. The status badge reads Interrupted — resuming while a run's lease has lapsed; the run page says Resumed after a restart with when and why; the canvas and the task timeline show waiting/interrupted nodes; audit labels for
automation.run.*actions.Contract: REST/OpenAPI 3.18.0 (
waitingForgainsin_doubt). Spec rulesAUTO-R16–R22,APV-R12,CTRL-R5. Docs EN/DE/FR (execution logs, concepts, upgrades, environment reference, API reference),.env.example. Manual boxesAUTO-F58–F61,AUTO-B13–B14,AUTO-A6,AUTO-P3(numbered after #4514'sAUTO-F57/B12).Verification
backend:integrationagainst fresh Postgres (migrations applied from scratch), lanescheckAutomations,…DeadSchemaDropped,…ProjectVisibility,checkAutomationRunLifecycle(new probes optimize rag action #4–#4g: one winner of 12 concurrent claims, expired lease takeover withresume_count, shutdown release claimed at once, previous-image takeover, in-doubt park and resolution),…TriggerDelivery,checkManagedAutomationConfiguration,checkTriggerPauseAfterFailures,checkTriggerStreakLockOrder,checkApprovalGateSingleClaim,checkControlDrain,checkApprovalDecisionResume,checkAskAnswer,checkWatchdogs: 136/136 checks passed (a filtered run; CI runs the full harness).runningwith a lapsed lease from a "crashed" process and one step un-checkpointed → the run page showed Interrupted — resuming, the liveness sweep took it over within a minute, ran the remaining step and finished it, and the page read "Resumed after a restart · … the server running it stopped responding, and another one took over."lint:links,lint:manual,check-guideclean..agents/repo.md, 2 for merge/release time (below).For merge and release
0160–0162because the open API-key stack holds0154/0155; nothing enforces contiguous numbers, so whichever lands second may keep its numbers. If that stack also bumps REST to 3.18.0, the second to land takes the next minor.