Repository navigation
Persist the thread and turn lifecycle so restarts and socket drops stop failing turns - #7561
Merged
ymichael merged 1 commit intoNov 17, 2026
Conversation
ymichael
force-pushed
the
bb/prototype-persisted-thread-lifecycle-state-machi-thr_5mnyr2k583
branch
from
November 16, 2026 21:41
c6fc15c to
bc7587c
Compare
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
force-pushed
the
bb/prototype-persisted-thread-lifecycle-state-machi-thr_5mnyr2k583
branch
from
November 17, 2026 18:38
678e516 to
5902bd1
Compare
ymichael
deleted the
bb/prototype-persisted-thread-lifecycle-state-machi-thr_5mnyr2k583
branch
November 17, 2026 18:48
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.
Human comments
What was wrong
The server decides a thread's lifecycle from state that lives only in process memory. That state is:
inFlightThreadRpcGuard,inFlightTurnRequestCountByThreadId)deferredTurnCompletionByThreadId)unconfirmedSteerRequestIdsByThreadId)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 onmain. Each was reproduced live with a real daemon and real Claude Code turns: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.thread.startwhose answer is lost across a restart is failed by boot recovery. The provisioning sweep finds the threadstartingwith 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.)command_timeout), is never settled. Fix lost replies, stuck stops and stalled queue drains, with an interleaving test #7542 handles the socket-drop variant. Onmainaturn.submittimeout still returns without settling the request.mainrebuilds them from the event log (listThreadIdsStoppedSinceLastTurnRequest).What changed
One persisted state machine now owns thread and turn lifecycle on the server.
State (
packages/db, migration0157_thread_run_state):threads.status, as before.thread_turn_requests: each turn request sent to a daemon and not yet settled. Its phase issent,accepted(provider confirmed the input first) orunconfirmed(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 puretransitionThreadLifecycle(state, input) → { next state, effects }. Its inputs:thread.start,turn.submit,thread.stopinterrupt/releaseturn/started,turn/input/accepted,turn/completed, provider failureTHREAD_LIFECYCLEin@bb/domainstays as the status sub-table the machine applies; its evaluator moved into the machine.Execution:
lifecycle/run.tsloads the state and applies the input in one immediate transaction: a CAS write plus in-transaction events.lifecycle/finish.tsruns the after-commit effects: sending stops, queue drains, parent notices, held-turn follow-ups, status notifications and plugin events.applyLoggedThreadLifecycleEventnow 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
sentrequest belonged to the dead process, so it becomesunconfirmed, 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:
aimedAtfromgetLatestThreadStopAim. Releases, the interrupt after a release finds a kept turn, and stops of archived or deleted threads stay unaimed, as onmain.activeTurnRetainedclears the stop and revives an idle thread.isTurnAimedAtByEarlierStopdecides whether a turn that starts after a stop belongs to it:turn.submittargetauto, as in Fix lost replies, stuck stops and stalled queue drains, with an interleaving test #7542.host_connection_lostreport code, which replaces this PR'sdeliveryUnknownflag. Acommand_timeoutis treated the same way. A lostthread.startwith a message moves the thread to running. A lostautosend that finds a running turn settles like a steer.turnCommandThreadIdsholds off settling a thread while the daemon still handles itsthread.startorturn.submit.stopsAwaitingDaemonand the reconnect querylistThreadIdsStoppedSinceLastTurnRequest. An owed stop is re-sent when the socket opens or the daemon reports the thread running, including after a restart.Deleted:
internal/turn-completed-events.ts,services/threads/unconfirmed-turn-requests.ts,services/threads/lifecycle-outcome.ts@bb/dbqueries:getLatestThreadInterruptedReason,listThreadIdsStoppedSinceLastTurnRequest,hasStoredTurnRequestEventSince,hasStoredTerminalClientTurnRequestEvent,listThreadTurnInterruptionEventStates, with their cost cases and allowlist entriesthread-lifecycle.tsdrops from about 2,590 lines to about 1,330events.tsturn-end follow-ups (queue drain, environment-directory continuation, parent notices) moved toservices/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_VERSIONbump (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.mdis 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
mainidlewith its reply, noterror. Fixes 1.steer_unconfirmed("The turn ended before the agent confirmed this steer") when its turn ends or its daemon is lost. Fixes 3.main. A turn the stop was aimed at does not.thread.active/idle/failed/turn.failedevents andstatus-changednotifications were emitted inside the transaction and could fire for a rolled-back change. Ending pending interactions also moved after commit.thread.startwhile one is in flight is refused with 409. Before, it was sent twice.Tests
apps/server/test/threads/send-queue-interleavings/) is unchanged and passes: 6 files, 14 scenarios.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 oflistThreadIdsStoppedSinceLastTurnRequest. Assertions are unchanged.thread-send-dispatch.test.ts: the "a retry of a failed turn" row sets the thread toerrorwithmoveThreadStatusinstead of the removedapplyLoggedThreadLifecycleEvent. Assertions are unchanged.hub.test.tskeepsmain's message.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.retainedstop and release answersautosendsturnCommandThreadIdspackages/domainevaluateThreadLifecycleEventtests (5) are ported tolifecycle-machine.test.ts.packages/dbapplyThreadLifecycleEventtests (8) are ported topackages/db/test/data/thread-lifecycle.test.tsandlifecycle-run.test.ts. Two are retired: the writer only exists in transaction form, andThreadLifecycleEventNotAppliedErroris gone.thread-status-change.test.ts.test/helpers/thread-status.tsor the machine'sturn.completedinput.query-plans.test.ts"finds a terminal client turn request event through the type index" is retired with its query.How you verified
Rebased onto
mainat1fa400dec7(Fix lost replies, stuck stops and stalled queue drains, with an interleaving test #7542).pnpm exec turbo run typecheck --filter='...[origin/main]': 123 tasks passpnpm exec turbo run typecheck lint --filter=@bb/server --filter=@bb/db: pass.@bb/db#check:query-costs: pass.@bb/servertests: 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 runningsleep 30was stopped mid-command. It wentidle, with the stop row recorded and acknowledged. The next message replied AFTER, endedidleand 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
mainand 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 bySIGKILLof the supervised child. Rows 4 and the stop rows now also pass onmainthrough Fix lost replies, stuck stops and stalled queue drains, with an interleaving test #7542.main(before Fix lost replies, stuck stops and stalled queue drains, with an interleaving test #7542)error: "Thread interrupted because the connection to the host was lost" (reply TWO)idle, reply TWO, no errorthread.startanswer and events held, server killed (daemon ran it)unconfirmedat boot, thenidle, reply STARTED, no errorthread.startnever reaches the daemon, server killederror"Provisioning thread failed"; retry workserror"Thread start was interrupted"; retry workssteer_unconfirmed(bridge frozen past 30 s), server killed, daemon crashedsteer_unconfirmedclient/turn/rejected"Host is not connected" plus "Command turn.submit failed", although the reply was BRAVOidle/error"Command thread.start failed" /idleidle/error"Thread start was interrupted" /idlestartingthread whose start answer was helderror)startingwith the startunconfirmed, no errorAlso live on this branch, with the same outcome as
mainfor each: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.
unconfirmedrow 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.startingwhile its host is offline.mainre-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.🤖 Generated with Claude Code