Skip to content

Persist the thread and turn lifecycle so restarts and socket drops stop failing turns - #7561

Merged
ymichael merged 1 commit into
mainfrom
bb/prototype-persisted-thread-lifecycle-state-machi-thr_5mnyr2k583
Nov 17, 2026
Merged

ymichael merged 1 commit into
mainfrom
bb/prototype-persisted-thread-lifecycle-state-machi-thr_5mnyr2k583

Conversation

@ymichael

@ymichael ymichael commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

The server decides a thread's lifecycle from state that lives only in process memory. That state is:

  • which turn requests and stops are still waiting for a daemon answer (inFlightThreadRpcGuard, inFlightTurnRequestCountByThreadId)
  • a turn completion held back for them (deferredTurnCompletionByThreadId)
  • steers the daemon could not confirm (unconfirmedSteerRequestIdsByThreadId)
  • stops still owed to the daemon (stopsAwaitingDaemon)

Thread status is persisted, but it is written optimistically. Repair code on reconnect, in sweeps and on command failures has to guess the rest from the event log.

#7542 (now on main) fixed the socket-drop cases: a reply lost when the daemon socket drops, and a stop lost the same way. It did so with that same in-memory state and event-log reconstruction. So a server restart still loses it, and these failures remain on main. Each was reproduced live with a real daemon and real Claude Code turns:

  1. A turn completion held for an in-flight steer is lost on server restart. The thread stays active. On reconnect the daemon no longer lists it, so the server fails it with "Thread interrupted because the connection to the host was lost", although the turn completed and replied.
  2. A thread.start whose answer is lost across a restart is failed by boot recovery. The provisioning sweep finds the thread starting with no in-flight guard and records "Provisioning thread failed", although the daemon ran the start and the turn completed. (Fix lost replies, stuck stops and stalled queue drains, with an interleaving test #7542 covers this for a socket drop only.)
  3. A steer the daemon could not confirm is forgotten on restart. It never gets a terminal event.
  4. A turn request whose answer dies with the process, or times out (command_timeout), is never settled. Fix lost replies, stuck stops and stalled queue drains, with an interleaving test #7542 handles the socket-drop variant. On main a turn.submit timeout still returns without settling the request.
  5. Stops owed to the daemon are in memory. After a restart, main rebuilds them from the event log (listThreadIdsStoppedSinceLastTurnRequest).

What changed

One persisted state machine now owns thread and turn lifecycle on the server.

  • State (packages/db, migration 0157_thread_run_state):

    • threads.status, as before.
    • thread_turn_requests: each turn request sent to a daemon and not yet settled. Its phase is sent, accepted (provider confirmed the input first) or unconfirmed (the answer was lost or uncertain).
    • thread_run_states: a turn completion held for those requests, and the stop state (reason, requested, sent, acknowledged).
  • Machine (apps/server/src/services/threads/lifecycle/machine.ts): a pure transitionThreadLifecycle(state, input) → { next state, effects }. Its inputs:

    • user requests: send, steer, stop, provisioning
    • daemon command answers: thread.start, turn.submit, thread.stop interrupt/release
    • daemon events: turn/started, turn/input/accepted, turn/completed, provider failure
    • daemon reports: session opened with its running list, socket opened, daemon lost or host removed
    • the turn-start deadline
    • server restart

    THREAD_LIFECYCLE in @bb/domain stays as the status sub-table the machine applies; its evaluator moved into the machine.

  • Execution:

    • lifecycle/run.ts loads the state and applies the input in one immediate transaction: a CAS write plus in-transaction events.
    • lifecycle/finish.ts runs the after-commit effects: sending stops, queue drains, parent notices, held-turn follow-ups, status notifications and plugin events.
    • Every former caller of applyLoggedThreadLifecycleEvent now goes through it: send, provisioning, the environment engine, command results, event ingest, session open/close/removal, the deadline sweep and boot.
  • Server restart: at boot, every sent request belonged to the dead process, so it becomes unconfirmed, and a held completion with nothing left in flight is applied. The daemon's session report and its replayed events settle the rest. Turn requests are never re-sent, because the daemon does not dedupe them.

  • How Fix lost replies, stuck stops and stalled queue drains, with an interleaving test #7542's behaviour runs here. Every rule Fix lost replies, stuck stops and stalled queue drains, with an interleaving test #7542 added is kept. Where both PRs handled the same case, the machine is now the only mechanism:

    • Aimed stops. Every interrupt the machine sends, and the awaited live interrupt, carries aimedAt from getLatestThreadStopAim. Releases, the interrupt after a release finds a kept turn, and stops of archived or deleted threads stay unaimed, as on main.
    • Kept turns. A stop answered with activeTurnRetained clears the stop and revives an idle thread.
    • Which turns a stop owns. isTurnAimedAtByEarlierStop decides whether a turn that starts after a stop belongs to it:
      • An aimed turn does not revive the thread. Its non-interrupted completion is skipped, and an aimed turn that starts after the stop was acknowledged is stopped again.
      • A turn the agent starts by itself revives the thread and runs to completion. This replaces this PR's earlier rule that every turn after a stop is stopped again.
    • Sends from idle. Plain messages to an idle thread go out as turn.submit target auto, as in Fix lost replies, stuck stops and stalled queue drains, with an interleaving test #7542.
    • Lost answers. A lost answer is recognised by main's host_connection_lost report code, which replaces this PR's deliveryUnknown flag. A command_timeout is treated the same way. A lost thread.start with a message moves the thread to running. A lost auto send that finds a running turn settles like a steer.
    • Reconnect. turnCommandThreadIds holds off settling a thread while the daemon still handles its thread.start or turn.submit.
    • Owed stops. The persisted stop row replaces stopsAwaitingDaemon and the reconnect query listThreadIdsStoppedSinceLastTurnRequest. An owed stop is re-sent when the socket opens or the daemon reports the thread running, including after a restart.
  • Deleted:

    • the in-memory state above
    • internal/turn-completed-events.ts, services/threads/unconfirmed-turn-requests.ts, services/threads/lifecycle-outcome.ts
    • the thread-start deduper
    • the event-log guesses the repair code used: stopped while away, newer request since the stop, stale start activation, terminal client request
    • their now-unused @bb/db queries: getLatestThreadInterruptedReason, listThreadIdsStoppedSinceLastTurnRequest, hasStoredTurnRequestEventSince, hasStoredTerminalClientTurnRequestEvent, listThreadTurnInterruptionEventStates, with their cost cases and allowlist entries
    • thread-lifecycle.ts drops from about 2,590 lines to about 1,330
  • events.ts turn-end follow-ups (queue drain, environment-directory continuation, parent notices) moved to services/threads/turn-end-follow-ups.ts, so a released held completion runs the same follow-ups.

  • No server/daemon wire change and no HOST_DAEMON_PROTOCOL_VERSION bump (Fix lost replies, stuck stops and stalled queue drains, with an interleaving test #7542's 266 is used as is). No CLI, SDK or settings change. docs/lifecycle-diagrams.md is regenerated with the new header.

  • Size against main: apps/server/src +3,207/−3,079, packages/db/src +374/−399, packages/domain/src +33/−50, tests +2,067/−736.

Behaviour changes on top of main

  • A turn that completes during a server restart now ends idle with its reply, not error. Fixes 1.
  • A thread start whose answer was lost across a restart no longer gets a false failure at boot. If the machine runs it, the thread continues. If not, it fails with "Thread start was interrupted" instead of "Provisioning thread failed". The same message replaces "Command thread.start failed" when the host is removed mid-start. Fixes 2.
  • An unconfirmed steer survives a restart. It is rejected as steer_unconfirmed ("The turn ended before the agent confirmed this steer") when its turn ends or its daemon is lost. Fixes 3.
  • A request whose answer died with the server, or timed out, is kept as pending. It resolves when the provider accepts it, when its turn ends (steers), or when the daemon reports the thread not running. Fixes 4.
  • A stop the daemon never acknowledged survives a restart and is re-sent when the daemon is back. A stop that timed out is re-sent like one that lost its connection. Fixes 5.
  • A stop answer that arrives after a newer run started leaves that run alone, and settling a stop rejects requests it left unconfirmed.
  • A child turn that ends while its stop is in flight still notifies the parent, as on main. A turn the stop was aimed at does not.
  • Plugin events and status notifications fire after commit. Plugin thread.active / idle / failed / turn.failed events and status-changed notifications were emitted inside the transaction and could fire for a rolled-back change. Ending pending interactions also moved after commit.
  • An awaited stop of a live thread without an environment now settles it. Before, it was a no-op that left the thread active.
  • A second thread.start while one is in flight is refused with 409. Before, it was sent twice.
  • Minor:
    • The provisioning-ended queue wake fires only for stops of provisioning threads.
    • The empty-fork auto-send no longer awaits the queue drain.

Tests

  • Fix lost replies, stuck stops and stalled queue drains, with an interleaving test #7542's interleaving suite (apps/server/test/threads/send-queue-interleavings/) is unchanged and passes: 6 files, 14 scenarios.
  • Fix lost replies, stuck stops and stalled queue drains, with an interleaving test #7542's other new tests, changed only in setup:
    • background-task-reconciliation.test.ts: the two new reconnect-stop tests ("re-sends the stop for a turn that started from a request made before the stop", "aims a re-sent stop at the turn it stopped …") seed the persisted acknowledged stop row as well as the event-log rows. The reconnect now reads the owed stop from that row instead of listThreadIdsStoppedSinceLastTurnRequest. Assertions are unchanged.
    • thread-send-dispatch.test.ts: the "a retry of a failed turn" row sets the thread to error with moveThreadStatus instead of the removed applyLoggedThreadLifecycleEvent. Assertions are unchanged.
    • hub.test.ts keeps main's message.
  • This PR's tests updated for Fix lost replies, stuck stops and stalled queue drains, with an interleaving test #7542's stop rule:
    • thread-stop-races.test.ts: "a turn the provider starts by itself after a stop" now stays active and completes. "a late turn start after a second stop" seeds the request that turn came from, so the stop is aimed at it, and it is still stopped.
    • child-outcome-gaps.test.ts: the parent-silent case uses a turn the stop was aimed at.
    • Machine cases now cover:
      • aimed versus agent-started turns after an acknowledged stop
      • a stop still in flight when the agent starts a turn
      • retained stop and release answers
      • lost steers with and without a running turn
      • lost auto sends
      • lost thread starts with and without a message
      • waiting on turnCommandThreadIds
  • Earlier ports and retirements:
    • packages/domain evaluateThreadLifecycleEvent tests (5) are ported to lifecycle-machine.test.ts.
    • packages/db applyThreadLifecycleEvent tests (8) are ported to packages/db/test/data/thread-lifecycle.test.ts and lifecycle-run.test.ts. Two are retired: the writer only exists in transaction form, and ThreadLifecycleEventNotAppliedError is gone.
    • Status broadcast tests are kept as thread-status-change.test.ts.
    • About 30 setup call sites use test/helpers/thread-status.ts or the machine's turn.completed input.
    • Fixtures that relied on the event-log stop signal seed the persisted stop.
    • query-plans.test.ts "finds a terminal client turn request event through the type index" is retired with its query.
  • Restart and race cases, each checked to fail before its fix:
    • held completion across a restart
    • a steer cut off by a restart
    • a lost thread start, running or not
    • repeated provisioning stops
    • an awaited stop without an environment
    • the daemon's real stop order
    • a child turn that completes before its stop lands
    • storage deletion settling open background tasks

How you verified

  • Rebased onto main at 1fa400dec7 (Fix lost replies, stuck stops and stalled queue drains, with an interleaving test #7542).

  • pnpm exec turbo run typecheck --filter='...[origin/main]': 123 tasks pass

  • pnpm exec turbo run typecheck lint --filter=@bb/server --filter=@bb/db: pass. @bb/db#check:query-costs: pass.

  • @bb/server tests: 408 files, 4201 passed, 1 skipped. @bb/db: 718 passed. @bb/domain: 311 passed. @bb/integration-tests: 30 files, 80 passed.

  • Live after the rebase (pnpm start:worktree, Codex): a thread running sleep 30 was stopped mid-command. It went idle, with the stop row recorded and acknowledged. The next message replied AFTER, ended idle and left no stop or request rows.

  • Live before/after, run before the rebase onto Fix lost replies, stuck stops and stalled queue drains, with an interleaving test #7542. Two isolated source dev instances on fresh data dirs, one on main and one on this branch, each with a real daemon, real Claude Code (Haiku) turns, and a TCP proxy between daemon and server that could hold chosen RPC answers, requests or event posts, or cut or refuse the daemon WebSocket. Server and daemon were restarted by SIGKILL of the supervised child. Rows 4 and the stop rows now also pass on main through Fix lost replies, stuck stops and stalled queue drains, with an interleaving test #7542.

    Case main (before Fix lost replies, stuck stops and stalled queue drains, with an interleaving test #7542) this branch
    1. Steer answer held, turn completes, server killed thread error: "Thread interrupted because the connection to the host was lost" (reply TWO) idle, reply TWO, no error
    2a. thread.start answer and events held, server killed (daemon ran it) "Provisioning thread failed" written at boot, then turn completes (STARTED) start kept unconfirmed at boot, then idle, reply STARTED, no error
    2b. thread.start never reaches the daemon, server killed error "Provisioning thread failed"; retry works error "Thread start was interrupted"; retry works
    3. Steer steer_unconfirmed (bridge frozen past 30 s), server killed, daemon crashed steer never settles steer rejected steer_unconfirmed
    4. Steer answer and events held, socket cut client/turn/rejected "Host is not connected" plus "Command turn.submit failed", although the reply was BRAVO steer kept pending, then accepted; reply BRAVO, no rejection
    Stop with daemon unreachable, server restarted, daemon back turn stopped after reconnect same; owed stop persisted across the restart
    Host removed: running thread / thread start in flight / stopping thread idle / error "Command thread.start failed" / idle idle / error "Thread start was interrupted" / idle
    Imported copy with a starting thread whose start answer was held thread failed at boot (error) kept starting with the start unconfirmed, no error

    Also live on this branch, with the same outcome as main for each:

    • start, steer, stop, daemon crash mid-turn plus retry, and server kill mid-turn (Claude Code and Codex)
    • the turn-start deadline
    • queue behind a running turn; archive, unarchive and delete of a running thread
    • edit message; idle fork; clear; compact
    • provider process killed mid-turn
    • stop during worktree provisioning; provisioning failure
    • plan mode then cancel-plan
  • Review. Three review passes of the stop and reconnect paths found the regressions listed above, and each fix has a test that fails without it.

Known gaps

Both are narrow and settle on their own; neither is a regression in normal use.

  • A thread start whose answer was lost while the daemon still had events or the command to deliver keeps its unconfirmed row until the provider confirms the input, the next daemon reconnect, or the turn-start deadline. Meanwhile another thread start gets 409. Stopping the thread clears it.
  • A thread whose start was in flight when the server restarted stays starting while its host is offline. main re-runs provisioning at boot. Here the start waits for the host's report, which settles it as running or "Thread start was interrupted". Stopping the thread clears it.

AGENT GENERATED

🤖 Generated with Claude Code

@ymichael
ymichael force-pushed the bb/prototype-persisted-thread-lifecycle-state-machi-thr_5mnyr2k583 branch from c6fc15c to bc7587c Compare November 16, 2026 21:41
One pure transition function owns thread status, the turn requests still
waiting for a daemon answer, a turn completion held for them, and the stop
state. All of it is persisted in thread_run_states and thread_turn_requests,
so a server restart or a dropped daemon socket no longer loses it.

Rebased onto #7542. Its behaviour is kept and runs through the machine:
aimed stops (getLatestThreadStopAim on every sent interrupt, unaimed for
releases and archived or deleted threads), activeTurnRetained answers
reviving the thread, isTurnAimedAtByEarlierStop deciding whether a turn
that starts after a stop belongs to it, plain sends from idle going out as
target auto, the host_connection_lost report code, and turnCommandThreadIds
holding off reconnect settlement. The persisted request and stop rows
replace #7542's event-log reconstruction of owed stops
(listThreadIdsStoppedSinceLastTurnRequest) and the in-memory stop map.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/prototype-persisted-thread-lifecycle-state-machi-thr_5mnyr2k583 branch from 678e516 to 5902bd1 Compare November 17, 2026 18:38
@ymichael
ymichael merged commit 4693d1f into main Nov 17, 2026
55 checks passed
@ymichael
ymichael deleted the bb/prototype-persisted-thread-lifecycle-state-machi-thr_5mnyr2k583 branch November 17, 2026 18:48
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