Skip to content

Hold the turn until in-flight steers settle - #7310

Merged
ymichael merged 1 commit into
mainfrom
bb/hold-the-turn-until-in-flight-steers-settle-thr_kskphedncm
Nov 9, 2026
Merged

ymichael merged 1 commit into
mainfrom
bb/hold-the-turn-until-in-flight-steers-settle-thr_kskphedncm

Conversation

@ymichael

@ymichael ymichael commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

A steer (turn.submit with target auto/steer) is sent while a turn runs, but it can still be on its way to the daemon when that turn completes. applyTurnCompletedEvent applied the completion straight away and marked the thread idle. Two things then went wrong:

  • The daemon found no live turn and started a new turn from the steer itself (deliverSubmittedTurn → runSubmittedTurn). Meanwhile the server, seeing an idle thread, sent the user's next message as target: start. The daemon refused it as competing_turn, and the server recorded it as a client/turn/rejected. The user's message was lost.
  • If the steer missed every turn it retargeted to, the daemon answered stale_turn. The server recorded that as a rejection even though the provider never saw the input.

What changed

  • apps/server/src/internal/turn-completed-events.ts: an in-memory count of steers in flight per thread. While any is unsettled, a root turn/completed is held (stored, but its lifecycle event is not applied), so the thread stays active and new sends queue as waitingOn: turn-starting. settleInFlightSteer runs when the last steer's live command settles:
    • if the daemon started a turn from the steer, that turn continues and the held completion is dropped;
    • otherwise the held completion is applied with its usual idle follow-ups (pruning, queue drain, environment-directory continuation).
  • apps/server/src/internal/events.ts: the root-turn check moves ahead of the apply (readTurnCompletion). The idle follow-up is built up front and passed in as afterIdle, so a held completion can run it later. Parent notifications are computed exactly as before.
  • apps/server/src/services/threads/thread-send.ts: the steer path tracks the steer and settles it in onSettled.
  • apps/server/src/services/threads/thread-lifecycle.ts: when a steer comes back stale_turn and the thread is still active, it is resent as target: { mode: "auto", expectedTurnId: null } with the same request id. It is tracked as in flight while it is resent. Other steer failures, and stale_turn on a thread that has stopped, are still visible rejections.
  • packages/host-daemon-contract: STALE_TURN_ERROR_CODE is now a named constant, used by the daemon and the server. The value is unchanged, so there is no wire change and no HOST_DAEMON_PROTOCOL_VERSION bump.

Visible behaviour differences, apart from the bug:

  • A thread with a steer in flight at turn end stays "running" until the steer's RPC settles, usually one daemon round-trip.
  • A stale_turn steer is delivered instead of shown as rejected.

Not ported from the source branch: finishing a held completion when the daemon reconnects after a server restart. The hold is in memory, so if the server restarts during that round-trip window, the thread can still be active with no daemon turn. Reconcile then interrupts it with "connection to the host was lost", as it does today for any thread that was active across a restart. I left that recovery out to keep this PR on the one race. It would need a stored-completion lookup in reconcileDaemonReportedThreads.

How you verified

New describe("a steer in flight when its turn ends") in apps/server/test/threads/thread-send-dispatch.test.ts. It uses a real migrated DB and a fake daemon that follows apps/host-daemon/src/command-handlers/thread.ts: it starts a turn from a steer that finds no live turn, and refuses start with competing_turn while a turn is active. The 5 cases:

  • an auto steer, then a steer-mode steer, lands after the turn ends, and the next send goes into the turn started from the steer;
  • a steer accepted into the ending turn holds idle until it settles;
  • a stale_turn steer is redelivered and accepted;
  • a definitive failure is still rejected, and the next send starts a new turn.

On origin/main (fix reverted, same tests) all 5 fail:

× continues with the turn the daemon starts from a auto steer ...   (send B: - "accepted" + "rejected:competing_turn")
× continues with the turn the daemon starts from a steer steer ...  (same)
× finishes the idle transition once a steer acknowledged into the ending turn settles  (expected 'idle' to be 'active')
× redelivers a steer that missed every turn as the next turn         (expected 'idle' to be 'active')
× rejects a steer that fails definitively after its turn ended ...   (expected 'idle' to be 'active')
Tests  5 failed

With the fix: 5 passed. Also run:

  • pnpm exec turbo run lint typecheck --filter=@bb/server --filter=@bb/host-daemon --filter=@bb/host-daemon-contract passed.
  • 67 server test files that touch steers, turn completion, queues and compaction: 1055 tests passed.

Full suites are left to CI.

AGENT GENERATED

🤖 Generated with Claude Code

A steer sent while a turn runs can still be on its way to the daemon when that turn completes. The server marked the thread idle at once, so the next send went out as a new turn while the daemon was starting a turn from the steer itself, and the daemon refused it as competing_turn. If the steer instead missed every turn it tried, the daemon answered stale_turn and the server recorded the message as rejected.

The server now counts turn.submit steers in flight per thread. While any is unsettled, a root turn completion is recorded instead of applied, so the thread stays active and new sends queue for the starting turn. When the last steer settles, a turn the daemon started from it simply continues; otherwise the held completion is applied with its usual idle follow-ups. A stale_turn steer on a still-active thread is resent as an auto submit (same request id) instead of rejected. Other steer failures stay visible rejections. No wire change: stale_turn is now a named contract constant.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit 9f8a71c into main Nov 9, 2026
92 of 95 checks passed
@ymichael
ymichael deleted the bb/hold-the-turn-until-in-flight-steers-settle-thr_kskphedncm branch November 9, 2026 22:55
ymichael added a commit that referenced this pull request Nov 10, 2026
## Human comments

## What was wrong

#7310 holds a root `turn/completed` while a **steer** is on its way to
the daemon. A new-turn request (`turn.submit` with `target: start`, or
`thread.start` for edits and forks) has the same window, but nothing
held it. The server applies `run.started` when the message is sent. If a
different root turn ends while the start is still on its way to the
daemon, `applyTurnCompletedEvent` applies `run.succeeded` and the thread
goes idle. The next message is then sent as a second start. The daemon
starts A's turn first and refuses the second with `competing_turn`, and
the user's message is lost.

The other root turn is any turn the provider opens by itself. For Claude
Code, that includes the turn the CLI runs when a background Bash command
finishes (bb doesn't hold the turn for background shells). In the
original trace it was the Claude Code drift fixed in #7321 (dev DB of
thr_kskphedncm, thread `thr_i7fdv3ia4f`, events 501–515). That drift is
one way to trigger it, not the cause: the server window exists without
it.

## What changed

- `apps/server/src/services/threads/thread-send.ts`: the start path
tracks its live command as in flight and settles it in `onSettled`. The
history-replacement `onCommandSettled` still runs first. A root
completion that arrives while a start is in flight is held, exactly as
for steers:
- if the start's turn is running when the request settles, the held
completion is dropped;
  - otherwise it is applied with its usual idle follow-ups.
- `apps/server/src/internal/turn-completed-events.ts`,
`thread-lifecycle.ts`: the in-flight counter now covers steers and
starts, so it is renamed from `trackInFlightSteer`/`settleInFlightSteer`
to `trackInFlightTurnRequest`/`settleInFlightTurnRequest`. Its behaviour
is unchanged.

Visible difference, as in #7310: if a turn ends before its own start
command settles, the thread stays "running" until the start settles,
usually one daemon round-trip. A start that fails still settles the
thread as `error` with later sends left queued, the same as without the
race. No wire change.

## How you verified

- Two new cases in
`apps/server/test/threads/thread-send-dispatch.test.ts`, in the #7310
describe (renamed to "a turn request in flight when a turn ends"). They
use a real migrated DB and the same fake daemon, which refuses `start`
with `competing_turn` while a turn is active:
- an idle thread sends A, a provider-initiated root turn starts and ends
before A reaches the daemon, then B is sent. A and B are both accepted,
with B steered into A's turn;
- the same race, but A's start fails: the thread ends in `error` with B
queued, which matches a failed start without the race.

On `origin/main` both fail with `AssertionError: expected 'idle' to be
'active'`. With the fix, all 52 tests in the file pass.
- `npx vitest run test/threads test/public test/internal test/system
test/routes`: 168 files, 1773 tests passed. The rest of the server suite
passed: 4024 tests; one shell-script test in
`install-machine-script.test.ts` timed out under load and passes on
rerun (54/54). `pnpm exec turbo run typecheck lint --filter=@bb/server`
passed.
- Live, `pnpm start:worktree` with a Claude Code (haiku) thread. Each
round asks Claude to run `sleep 8` in the background, so the CLI later
opens its own notification turn X. It then sends start A with 20–40 × 34
MB attachments, so the daemon stages A for seconds and X runs and ends
while A is in flight. B is sent the moment X ends:
- `origin/main`: `3 round(s) raced; 3 with a rejected message`, each `A
accepted(t18); B rejected:competing_turn`;
- this branch: `6 round(s) raced; 0 with a rejected message`, each `A
accepted(t15); B accepted(t15)`, with B steered into A's turn.

> 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 10, 2026
## Human comments

## What was wrong

When a steer reaches Codex just as its target turn ends, the Codex
app-server rejects `turn/steer` with JSON-RPC `-32600` and the message
`no active turn to steer`. If another turn has already started, the
message is ``expected active turn id `X` but found `Y` ``. Both strings
appear verbatim in
`codex-rs/app-server/src/request_processors/turn_processor.rs` at
`rust-v0.167.0`, the installed version. The Codex bridge
(`handleTurnSteer` → `rejectWithCodexError`) forwarded these rejections
as a generic `BRIDGE_ERROR` (`-32000`). The bridge's own
permission-change rejection, "The turn to steer is no longer active",
went out the same way. `agent-runtime`'s `steerTurn` returns `{ status:
"stale" }` only for a `staleTurn` recovery hint or the `NO_ACTIVE_TURN`
(`-32001`) code. So the runtime rethrew, the daemon's
`steerSubmittedTurn` never retargeted or started the next turn, and the
user's message failed with `command_failed`. Seen live on Nov 9 while
working on #7310. Daemon log: `{"message":"no active turn to
steer","code":-32000,"recovery":null}`.

## What changed

- `plugins/provider-codex/src/bridge/bridge.ts`: `handleTurnSteer` now
returns these errors as `NO_ACTIVE_TURN` with a `staleTurn` recovery
hint, which is the contract the ACP bridge already uses:
- a Codex `-32600` rejection whose message exactly matches `no active
turn to steer` or ``expected active turn id `…` but found `…` ``
  - the bridge's own "The turn to steer is no longer active" rejection

Other steer rejections are unchanged. For example, `cannot steer a
review turn` is still a `BRIDGE_ERROR`. The runtime and daemon already
handle stale steers: the runtime clears the active turn, and the daemon
retargets the live turn or starts a new one.
- `fake-codex-app-server.mjs`: new scripted `steerError`, alongside the
existing `interruptError`.
- No wire field changes, so `HOST_DAEMON_PROTOCOL_VERSION` is unchanged.
No plugin SDK surface change.

## How you verified

- New `plugins/provider-codex/src/bridge/bridge.stale-steer.test.ts`
drives the real bridge against the fake app-server, using Codex's
verbatim rejection messages. Run against `origin/main`'s `bridge.ts`,
the three stale cases fail (`-32000` received, `-32001` expected) and
the negative case passes. With the fix, all 4 pass.
- Real Codex 0.167.0 probe: `codex app-server`, then `thread/start`,
then `turn/steer` with no active turn. Response:
`{"code":-32600,"message":"no active turn to steer"}`.
- `pnpm exec turbo run typecheck lint test
--filter=bb-plugin-provider-codex`: typecheck and lint are clean, and
the full bridge suite passes (25 files, 151 tests).
- The runtime's `staleTurn`/`NO_ACTIVE_TURN` → `stale` mapping is
covered by the existing `runtime.input-accepted.test.ts` tests.
- Not done: an end-to-end run on a live server. The live steer-race
harness from #7310's thread was wiped when that thread was archived.

> 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 14, 2026
… 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]>
ymichael added a commit that referenced this pull request Nov 14, 2026
… 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]>
ymichael added a commit that referenced this pull request Nov 14, 2026
… 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]>
ymichael added a commit that referenced this pull request Nov 17, 2026
… 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]>
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