Skip to content

Fix lost replies, stuck stops and stalled queue drains, with an interleaving test - #7542

Merged
ymichael merged 10 commits into
mainfrom
bb/send-and-queue-interleaving-guard-test-thr_wvem6bjenm
Nov 17, 2026
Merged

ymichael merged 10 commits into
mainfrom
bb/send-and-queue-interleaving-guard-test-thr_wvem6bjenm

Conversation

@ymichael

@ymichael ymichael commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

The interleaving test, checked against a real daemon with Codex and Claude Code, found these ways sends, queue drains and stops go wrong on main:

  1. A reply lost across a daemon disconnect. When the daemon socket drops while a turn.submit is on the daemon, the server settles it as refused (client/turn/rejected "Host is not connected", run.failed) although the daemon still runs it. Live: the message shows failed and the thread error, then the agent answers it; the next message goes out as a start, the daemon refuses it as competing_turn, and it is lost. A thread.start reply lost the same way marks a new thread error ("Command thread.start failed") while the agent runs its first message.
  2. A stop cut by a disconnect. A stop recorded while a new turn was starting, whose interrupt is lost with the connection, leaves the thread revived by the reconnect. The turn then completes normally and hasThreadStopBeforeTurnStarted (internal/events.ts) skips that completion, so the thread stays active with nothing running.
  3. A stop that lands after the agent started its own turn. A stop the daemon only receives after a reconnect, or one re-sent by reconnect reconciliation, interrupts whatever is running by then. Live with Claude Code: a background task finished during the outage and woke the agent into its own turn, and that turn was interrupted 5 ms after the daemon reconnected. When the server instead revived such a turn, the same completion rule skipped its completion and the thread hung.
  4. The turn-end drain stopping behind a plugin-held message. The drain claims one row; if a plugin defers it, the drain ends, and the next eligible message waits for the idle sweep (9.3 s live).
  5. A plugin recheck skipped by another plugin's hold (found live). Recheck pacing is per thread, so a saved draft re-queued by the drafts plugin made every recheck skip the thread's other plugin-held rows. They never sent while the draft existed.

What changed

  • ws/hub.ts, services/hosts/online-rpc.ts, errors.ts, services/hosts/live-command.ts: the hub marks RPCs it fails because their session dropped (HostOnlineRpcConnectionLostError). The API error body is unchanged, and so is isHostUnavailableApiError. Only the live-command failure report carries a distinct code, host_connection_lost, which the existing host_unavailable checks treat the same way.
  • thread-lifecycle.ts:
    • A turn.submit lost to the connection is settled through the existing unconfirmed paths instead of being rejected and failing the run. A thread.start lost to the connection moves the thread to waiting for its turn, the same way a submitted start waits.
    • Reconnect: the daemon reports, when it opens a session, the threads whose thread.start or turn.submit it is still handling (turnCommandThreadIds, from CommandRouter). Reconciliation treats those like running threads. Any other active thread the daemon does not report is interrupted, as on main, so a command that never reached the daemon fails at once ("Thread interrupted because the connection to the host was lost") instead of waiting for the turn-start deadline. The deadline stays the backstop for a command the daemon received and then dropped after reconnecting.
    • thread-send.ts: a plain message sent to an idle thread goes out as turn.submit target auto (expectedTurnId: null) instead of start. The daemon starts a turn when none runs and joins the running one when the agent started a turn meanwhile, so nothing is refused as competing_turn and nothing needs redelivering. Only a message that is not an explicit start, not a retry, and has no command or skill mention (/compact, /plan, goals, project and user commands, skills) is sent this way. The others still go out as start and are rejected as a competing turn, as on main. Edits and new threads go out as thread.start. A lost auto send with no known running turn settles like a lost start (waits); with a running turn it settles like a lost steer.
    • A stop lost to the connection is re-sent when the daemon's socket opens.
  • Aimed stops (protocol 266). thread.stop carries aimedAt: the turn that was running when the stop was requested and the messages sent since the last finished turn began, from @bb/db getLatestThreadStopAim. The daemon (command-dispatch.ts) interrupts only a running turn that is that turn or came from one of those messages. Otherwise it keeps the turn and answers activeTurnRetained, and the server marks the thread active. @bb/agent-runtime tracks which client requests started or joined the running turn, from the pending start, steers and turn/input/accepted. A release, the interrupt a stop sends after its release finds a kept turn, and stops of archived or deleted threads stay unaimed (aimedAt: null) and stop whatever runs.
  • @bb/db isTurnAimedAtByEarlierStop replaces hasThreadStopBeforeTurnStarted: a turn's start and completion are skipped only when the latest message before the turn was sent before the stop and was still unfinished (not accepted or rejected before the turn began). A turn the agent starts by itself after a stop now counts and completes. listThreadIdsStoppedSinceLastTurnRequest (renamed from …SinceLastTurnStart) still picks threads whose stop reconnect re-sends; the aim decides on the daemon.
  • queued-messages.ts: a drain whose claimed row comes back plugin-held runs one more pass.
  • dispatch-hooks.ts, queued-message-dispatch.ts: requeue pacing is also recorded per thread and plugin, and the plugin recheck pass paces per plugin.
  • HOST_DAEMON_PROTOCOL_VERSION 265 → 266 for aimedAt and the session's turnCommandThreadIds. Provider bridges, the bridge protocol and plugin APIs are unchanged: turn tracking uses the daemon's own start and steer requests plus the turn/input/accepted events bridges already emit.

Decisions for review (visible changes beyond removing the bugs)

  • A submit cut by a disconnect no longer shows "Host is not connected" at once. It resolves as delivered, or later as "The agent did not start a turn for this message" or "The turn ended before the agent confirmed this steer". A steer cut when no turn is running is still rejected at once.
  • A new thread whose thread.start reply is lost shows as running instead of failed. A message or new thread whose command never reached the daemon fails when the daemon reconnects, with "Thread interrupted because the connection to the host was lost", as on main after a reconnect.
  • A plain message sent to an idle thread is delivered into a turn the agent started before it arrived, instead of being rejected as competing_turn, including a queue-if-active send or a queued message drained just as the previous turn started. Explicit starts, retries, manual compaction and messages with commands or skills are still rejected, as on main.
  • A stop applies to the turn it was aimed at. A turn the agent starts by itself after the stop has landed keeps running, shows as active and completes, including after a reconnect. A stop still in progress when the agent starts a turn may still stop it (unchanged: the explicit stop escalates to an interrupt when its release finds a running turn).
  • A reconnect leaves a thread starting while the daemon reports its thread.start or turn.submit still in progress, up to the 5-minute deadline, instead of interrupting it at once.

Test

The interleaving test is apps/server/test/threads/send-queue-interleavings/: a shared harness.ts and six files, so the 14 scenarios run in parallel workers. It lists no known failures. The plugin recheck advances a faked clock instead of sleeping 1.05 s. Locally each file takes 13–20 s and all six together 23 s wall (the single file took 80 s). On the CI runners, with the cache bypassed, the files take 13–28 s each (medians over 10 runs per OS); the slowest is the reconnect file, bounded by its 232-ordering scenario.

New scenarios this revision: a stop aimed at a message still on its way across a reconnect, and a turn the agent starts after a stop across a reconnect. The fake daemon honours aimedAt like the real one. Invariants added: an agent turn started after a settled stop must not be interrupted, and no daemon turn may run while the thread shows idle. Proof runs: with the old completion rule the agent-turn scenario fails 14 of 195 orderings ("thread ended active"); with stops left unaimed it fails 19 of 193 ("turn-2, which the agent started after the stop, was stopped"); with per-thread recheck pacing the recheck scenario still fails under the faked clock.

Unit tests, each checked to fail without its fix:

  • the daemon interrupts only an aimed turn (real runtime and fake bridge), and turn state tracks only the running turn's requests;
  • reconnect sends the stop aimed at the turn it stopped and revives the thread when the daemon keeps the agent's turn;
  • an agent-started turn after a stop reactivates and completes;
  • a lost thread.start reply keeps the thread running and settles it; the thread fails on reconnect when the daemon never received it, and waits up to the deadline while the daemon reports it still in progress;
  • the daemon's command router reports a thread while its turn.submit runs and stops once it succeeds or fails;
  • a table of every kind of send from an idle thread: auto, steer, steer-if-active, queue-if-active and queued drains go out as auto; an explicit start, /plan, a goal command, a project command, a skill, manual compaction and a retry go out as start and are rejected when refused as competing_turn. An edit refused as competing is not redelivered.

The startup-parked stop test seeds the startup request every real thread start records, and main's competing-start test is kept unchanged.

How you verified

  • Live, pnpm start:worktree on a fresh data dir, with a second daemon behind a TCP proxy that can cut, blackhole or delay the daemon connection:
    • Cause 1, before: message failed, thread error, next message lost as competing_turn. After: no rejection, the next message steers into the turn, both delivered (Codex).
    • Cause 2, before: thread active forever. After: the stop is re-sent, the turn is interrupted, idle (Codex).
    • Cause 3, Claude Code: a stop sent during a full 32 s outage, a background task that wakes the agent into its own turn during the outage, then reconnect. Before (8a30c5f): the agent's turn was interrupted 5 ms after reconnect. After: it showed active, ran its 45 s command, replied "woke up", completed and the thread ended idle.
    • Cause 4, before: 9,267 ms. After: 279 ms. Cause 5, before: the held message never sent while a draft existed. After: sent at the plugin's recheck.
    • RPC timeouts, with LIVE_DAEMON_COMMAND_TIMEOUT_MS set to 1.5 s for the run (local patch, not committed) and daemon replies delayed 3 s: a new message and a steer into its turn both timed out at the server, were each accepted once, none rejected, no errors, thread idle (Claude Code).
    • A submit the daemon drops after reconnecting, with TURN_START_DEADLINE_MS set to 60 s for the run (local patch): a message with four 34 MB attachments, connection cut while the daemon fetched them. The daemon dropped it (attachment_unavailable, reply lost). The thread stayed active with no false rejection, then failed at the deadline with "The provider did not start the turn within 1 minutes, so bb stopped it. Send a message to try again." (the real constant reads 5 minutes).
    • A lost thread.start reply: a new Claude Code thread with the connection cut while its start ran. The daemon finished the start during the cut. The thread went active instead of error, the agent answered "started fine." and the thread ended idle, with no errors.
    • Commands that never reached the daemon (78a72f3, Claude Code, the proxy dropping the frame and cutting the socket): a turn.submit and a new thread's thread.start each failed about a second later, at reconnect, with "Thread interrupted because the connection to the host was lost". The previous revision kept the same turn.submit drop showing as running for 5 minutes (04:34:05 to 04:39:09) and then failed it at the deadline. On the same build, a turn.submit and a thread.start cut after delivery still completed with no errors ("six seven", "started fine").
  • Stop on the final build, Claude Code, each ending with the turn interrupted, the thread idle and nothing running 20 s later: Stop 150 ms after a new thread's first message, while it was still starting with no turn shown; Stop while a queued message's turn ran; Stop on a turn the agent started by itself after a background task finished, shown as running; Stop pressed twice at once.
  • The interleaving files 10 times each on the Linux and Windows CI runners, with Turbo's cache bypassed (--force, 0 of 11 tasks cached), on a throwaway branch: 20 of 20 runs passed on the four-file layout and 20 of 20 on the final six-file layout.
  • Causes 1 and 2 needed an injected delay (a codex launch shim, dropped frames). Cause 4 needed a local plugin that holds one message, since no first-party plugin defers a ready row selectively.
  • pnpm exec turbo run typecheck lint lint:type-aware for @bb/server, @bb/host-daemon, @bb/db, @bb/host-daemon-contract, @bb/agent-runtime; check:query-costs; full @bb/db, @bb/host-daemon, @bb/agent-runtime and @bb/host-daemon-contract tests; the 31 @bb/server files that touch stops, the request-path statement test, send dispatch, edit message, turn-start deadline and the interleaving files.
  • CI runs the full suites.

AGENT GENERATED

🤖 Generated with Claude Code

@ymichael ymichael changed the title Add an interleaving test for sends, queue drains and thread lifecycle Fix lost replies, stuck stops and stalled queue drains, with an interleaving test Nov 14, 2026
@ymichael
ymichael force-pushed the bb/send-and-queue-interleaving-guard-test-thr_wvem6bjenm branch 2 times, most recently from b287c6d to bf1de3e Compare November 14, 2026 14:49
ymichael and others added 9 commits November 16, 2026 19:59
Drives the real send, queue and lifecycle code against a migrated SQLite
database and a fake daemon whose replies the test holds and releases. It
explores every ordering of each scenario's sends, steers, stops, drain
wakes, turn ends, daemon reconnects and RPC timeouts, and checks that each
accepted message reaches the agent exactly once, no turn starts without
input, queued messages keep their order and the thread ends idle.

Two causes still fail on main and are recorded as known failures.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Adds the queue's Send now action as a user step and a scenario where it
races the turn end and the automatic drain while command preparation is
slow, so a drain that claims a later row behind a pending send-now shows
up as a queued message overtaking an earlier one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…aving test

Adds a limiter plugin whose message.dispatch decisions the test holds and
answers, and an add-to-queue user step. The tail now flags a row left
queued on an idle thread with nothing left to send it, before it releases
the plugin's holds.

One new cause fails on main and is recorded as a known failure: the
turn-end drain claims one row, the plugin defers it, and the drain ends
without trying the next eligible row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
On Windows CI a send queued behind the hook evaluation lock was released
together with the held decision, and the two sends then raced to start a
turn on file I/O timing, so a replay diverged. The user now acts only
while no plugin decision is held, so each step releases one dispatch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ced rechecks

The interleaving test and live repros against a real daemon and Codex
found four ways sends and stops went wrong:

- A turn.submit whose reply was lost when the daemon socket dropped was
  settled as refused (rejected, run failed) although the daemon still ran
  it, and the next message then went out as a competing start and was
  lost. The hub now marks RPCs it fails because their session dropped;
  such a submit is settled through the unconfirmed paths instead, a same
  instance reconnect no longer interrupts a thread whose turn request is
  still unresolved, and a start the daemon refuses as competing while a
  turn runs is requeued behind that turn instead of dropped.
- A stop whose interrupt was cut by a disconnect left a thread revived by
  the reconnect but whose turn completion the server skips, so it stayed
  active. Reconnect now treats a stop recorded after the running turn's
  request as still owed and re-sends it, and a stop lost to the
  connection is re-sent once the daemon's socket opens.
- The turn-end drain stopped after a plugin deferred its claimed row, so
  the next eligible message waited for the idle sweep. A drain whose row
  comes back plugin-held now runs another pass.
- A plugin recheck skipped every held row on a thread after the first
  row in the pass re-queued (for example a saved draft), so the others
  never sent. Requeue pacing is now decided once per pass.

The interleaving test lists no known failures, gains a scenario for the
recheck bug, and drops four scenarios that caught nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… test

The per-pass pacing snapshot let a group's tail re-claim the group its
lead had just re-queued, so a plugin was asked twice in one pass and the
group it postponed went out (requested-queue-drain caught it in CI).
Keep per-thread pacing everywhere, and key only the plugin recheck pass
by thread and plugin: a draft re-queued by the drafts plugin no longer
holds back rows another plugin is waiting on, while a group one plugin
postponed stays paced.

The interleaving test adds a Retry scenario against a failing turn, which
catches the double delivery that #7310 fixed, and the fake models a
draft-holding plugin separately from the limiter.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The rebase onto #7535 left its cost case and plan allowlist entry on the
old name, listThreadIdsStoppedSinceLastTurnStart.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lone

A stop re-sent after a daemon reconnect, or a stop the daemon only received
after reconnecting, interrupted whatever was running then, including a turn
the agent started by itself after the stop. The server skipped such a turn's
start and completion, so a revived thread hung. thread.stop now carries the
turn running when the stop was requested and the messages sent before it
(protocol 266). The daemon interrupts only a running turn that matches and
otherwise reports the turn as kept, and the server then marks the thread
active. A turn's start and completion are skipped only when the turn started
from a message sent before the stop that was still unfinished.

A competing-turn refusal while a turn runs now delivers the message into the
running turn instead of rejecting it, and a thread.start reply lost with the
daemon connection leaves the thread waiting for its turn, bounded by the
turn-start deadline, instead of marking it failed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…test

A start refused as competing_turn now joins the running turn only when it
is a plain message: not an explicit start, not a retry, and with no command
or skill mention (/compact, /plan, goals, project and user commands,
skills). Those keep main's behaviour and are rejected. Edits and new threads
are sent as thread.start and are never redelivered.

The interleaving test is split into a shared harness and four files so the
scenarios run in parallel workers, and the plugin recheck advances a faked
clock instead of sleeping through the requeue pacing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/send-and-queue-interleaving-guard-test-thr_wvem6bjenm branch from 3e80172 to 43b89ef Compare November 17, 2026 03:59
A send or new thread whose command never reached the daemon no longer
shows as running until the 5-minute turn-start deadline. The daemon now
reports, when it opens a session, the threads whose thread.start or
turn.submit it is still handling (turnCommandThreadIds, folded into
protocol 266). Reconnect reconciliation treats those like running
threads and interrupts any other active thread the daemon does not
report, as main does, so a lost command fails at once with "Thread
interrupted because the connection to the host was lost". This replaces
the unresolved-request check that kept every such thread waiting.

A plain message sent to an idle thread now goes out as turn.submit
target auto instead of start, so the daemon itself joins a turn the
agent started meanwhile. Explicit starts, retries and messages with a
command or skill mention still go out as start and are rejected as a
competing turn, as on main. This removes the in-memory set of starts
allowed to join a running turn and the competing-turn redelivery; a
lost auto send with no known running turn settles like a lost start.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit 1fa400d into main Nov 17, 2026
54 checks passed
@ymichael
ymichael deleted the bb/send-and-queue-interleaving-guard-test-thr_wvem6bjenm branch November 17, 2026 18:10
ymichael added a commit that referenced this pull request Nov 17, 2026
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 added a commit that referenced this pull request Nov 17, 2026
…op failing turns (#7561)

## 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. (#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.** #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 #7542's behaviour runs here.** Every rule #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 #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 (#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

- **#7542's interleaving suite**
(`apps/server/test/threads/send-queue-interleavings/`) is unchanged and
passes: 6 files, 14 scenarios.
- **#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 #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` (#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 #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 #7542.

  | Case | `main` (before #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](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 18, 2026
## Human comments

## What was wrong

Three plugins could each re-run one failed turn: provider retry,
Automations, and Workflows. Their handoff was the
`provider-retry.v1.consent` RPC. The sending plugin had to answer
"decline" within provider retry's 5 s timeout, and any miss counted as
consent.

- **Automations** misses when the run has no thread ID yet because the
spawn response is still pending (the
[report](https://get-bb.github.io/reports/issues/7708.html) forces
this), or when its answer is slow, as on a Mac waking from DarkWake.
0.48.x has no handler at all (#6677 first shipped in 0.49.0, and the
reporter is on 0.48). When it misses, provider retry resumes the thread
while the automation's 30 s quick retry spawns a fresh thread.
- **Workflows** has the same timeout miss. It then replaces the worker 1
s later in the same environment.

## What changed

One rule now covers every retrier: provider retry owns a failed turn,
and a plugin that re-runs failed work stands down while a retry is in
hand. The sync point is provider retry's recorded decision, not timing.

- **provider-retry**: no longer asks senders for consent. It records its
decision for each `turn.failed`, after queueing any retry, and
`decision.get` is now discoverable. Removed: the consent ask,
`declined-by-sender`, the consent field in diagnostics and `explain`,
and `retryConsent*` from the contract.
- **`retry-handoff.ts`**, an identical copy in `plugins/automations/src`
and `plugins/workflows/src` (plugins stay self-contained).
`readRetryHandoff` reads the steps below in this order:
  1. The thread. Gone or archived → re-run.
2. Provider retry's decision. Read before the queue, because provider
retry queues the row and then records the decision. Reading the queue
first loses that race: the live check below hit it, and the "lands
mid-check" rows guard it.
3. The queue. Any `retry` row → stand down. This covers provider retry
and core's restart resume (`bb restarted`), and the reason names
whichever it was.
4. The latest turn request. The thread isn't in `error` and the request
carries `retryOfRequestId` → stand down (overload retries fire 5–10 s
out).
5. Undecided failure → wait. Then re-run once the decision arrives,
after 60 s, or right away when provider retry is not installed.
- **Automations** (`sweep.ts`): before a quick retry of a failed
scheduled run, a wait leaves the slot due (the next sweep is 10 s
later). A stand-down records a `skipped` run, `failed run <id> is not
re-run: a retry (<reason>) is queued in thread <id>`, and `next_run_at`
moves to the next scheduled time. Automations' consent handler is
deleted. If the handoff can't be read (for example `decision.get` times
out), the sweep treats it as undecided: it waits while the failure is
under 60 s old, then re-runs, as Workflows does. Before, the error
escaped the sweep and the automation stayed due without ever running.
- **Workflows** (`service.ts`, `data.ts`): when a worker's
`thread.failed` fails a call, the call polls the handoff every second.
- On stand-down, `reopenFailedCallOnWorker` sets the call back to
`running` on the same worker. It then waits for that worker's result
instead of spawning a replacement. A later failure of that worker goes
through the handoff again.
- While a handoff is pending, worker cleanup skips the worker. Without
that, the call sitting briefly in `failed` makes cleanup archive the
worker, which failed the run (found live).
  - Workflows' consent handler is deleted.
- **Docs**: provider-retry `SKILL.md`, automations `script-runtime.md`,
workflows `runs.md`, and the `turn.failed` entry in
`docs/api_to_audit.md`.

No wire, SDK, or `HOST_DAEMON_PROTOCOL_VERSION` changes.

**The remaining bound:** a plugin re-runs on its own only if provider
retry has not recorded a decision within 60 s of the failure. Provider
retry's handler makes at most a few RPCs with 5 s timeouts, so this
needs a stuck or crashed handler, or a process suspended across the
window. Another gap: if `threads.retry` throws, provider retry records
no decision, and the plugin re-runs after 60 s.

**Left out:**
- If the Workflows plugin restarts during a handed-off wait,
`reconcileRunningCalls` fails the call ("worker is in an error state"),
and the restarted run's live suffix spawns a new worker while the old
worker's queued retry still fires. Plugin restart already replays runs
from scratch, and fixing that path means changing replay semantics.
- If a turn fails before its spawn response returns, the run stays
`running` until restart unless a provider retry finishes it. That's
pre-existing and separate.

On the #7542 pointer: it doesn't affect this. #7542 changes the daemon
`turn.submit` target to `auto`, but the persisted
`client/turn/requested` target is still `new-turn`, as the live check
below confirmed.

## How you verified

Live on main first, with `pnpm start:worktree`, Claude Code pointed at a
local 503 stub (`CLAUDE_CODE_MAX_RETRIES=0`), and real automations:
- consent declined, and the automation's quick retry spawned a second
thread. A double retry needs the consent miss, which the report's
harness reproduces;
- a target-thread send recorded target `new-turn`.

Live with this branch, same setup:
- **Automation:** one thread. Provider retry `Scheduled …: Provider
unavailable`. The run recorded `skipped — failed run arun_… is not
re-run: a retry (Provider unavailable) is queued in thread thr_…`, and
`nextRunAt` moved to the next hourly slot.
- **Automation, declined:** a 400 stub gave `not-retryable`. The
automation read the decision through `decision.get` and re-ran on its
quick retry.
- **Workflows:** one `agent()` call. The worker failed, provider retry
queued a retry, and the call stayed `running` on the same worker ("keeps
worker … a retry (Provider unavailable) is queued"). After two more
provider-retry failures it was still one thread, still `running`, with
attempt 3 queued and the worker not archived. The first two live runs
here exposed the read-order race and the cleanup race above, and both
fixes are in this branch.

Tests: the same handoff table runs in
`plugins/automations/src/server-harness.test.ts` (real sweep service)
and `plugins/workflows/src/service-policy.test.ts` (real workflow
service):
- six rows: provider retry queued, restart resume queued, retry already
ran, retry lands mid-check, provider retry declined, provider retry not
installed;
- plus "waits for provider retry to decide" in both, which in Workflows
also asserts the worker is not archived during the wait;
- plus "re-runs after a minute without a decision" and "waits while
provider retry's decision cannot be read, then re-runs after a minute"
in Automations;
- provider-retry: "publishes a failure's decision only once its retry is
queued", plus discoverability.

Against main's `sweep.ts` / `service.ts`, the four stand-down cases fail
in both plugins and the re-run controls pass. Against the old read
order, the mid-check row fails in both. Without the cleanup guard, the
Workflows wait test fails (`expected [ 'child-1' ] to not include
'child-1'`). Without the read-error catch in `sweep.ts`, the
unreadable-decision test fails (`expected [ [ { …(10) } ] ] to have a
length of 2 but got 1`): the automation never re-runs.

`pnpm exec turbo run typecheck lint test --filter=bb-plugin-automations
--filter=bb-plugin-provider-retry --filter=bb-plugin-workflows`: 16/16
tasks, 165 + 27 + 273 tests. The lint warnings are pre-existing in each
plugin's `app.tsx`.

Fixes #7708

🤖 Generated with [Claude Code](https://claude.com/claude-code)

> AGENT GENERATED

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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