Skip to content

Treat Codex steers that miss their turn as stale - #7319

Merged
ymichael merged 1 commit into
mainfrom
bb/classify-codex-no-active-turn-steer-rejections-a-thr_7qybf39nug
Nov 10, 2026
Merged

ymichael merged 1 commit into
mainfrom
bb/classify-codex-no-active-turn-steer-rejections-a-thr_7qybf39nug

Conversation

@ymichael

@ymichael ymichael commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator

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 Hold the turn until in-flight steers settle #7310's thread was wiped when that thread was archived.

AGENT GENERATED

🤖 Generated with Claude Code

Codex app-server rejects turn/steer with -32600 "no active turn to steer"
or "expected active turn id `X` but found `Y`" when the targeted turn has
already ended. The Codex bridge forwarded these as generic BRIDGE_ERRORs,
so the runtime never returned a stale steer and the daemon rejected the
message with command_failed instead of retargeting or starting the next
turn. Report them, and the bridge's own "turn to steer is no longer
active" rejection, as NO_ACTIVE_TURN with a staleTurn recovery hint, the
same contract the ACP bridge uses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit 3486aaf into main Nov 10, 2026
36 checks passed
@ymichael
ymichael deleted the bb/classify-codex-no-active-turn-steer-rejections-a-thr_7qybf39nug branch November 10, 2026 17:30
ymichael added a commit that referenced this pull request Nov 10, 2026
## Human comments

## What was wrong

A steer can lose a race with the provider. bb steers turn X, but before
the steer arrives X ends and the provider starts turn Y on its own, for
example a Codex goal continuation. The provider reports Y's start before
it rejects the steer ("expected active turn id X but found Y"), so the
runtime has already recorded Y as active by the time the rejection
arrives. The stale-steer path in `steerTurn` then called
`turnState.clearThread`, which erased Y. The daemon's retry
(`resolveLiveSubmittedTurnTarget`) saw no active turn and started a
competing turn instead of steering the user's message into Y. This came
up while reviewing #7319, which routed Codex's "found Y" rejections into
this path.

## What changed

- `packages/agent-runtime/src/runtime-turn-state.ts`: added
`clearStaleTurn(threadId, staleTurnId)`. It clears the thread only when
the recorded turn is the stale one or nothing is recorded. A newer
recorded turn is kept.
- `packages/agent-runtime/src/runtime.ts`: both stale-steer branches
(the `staleTurn` recovery hint and the `NO_ACTIVE_TURN` code) call
`clearStaleTurn` and return the active turn that remains, instead of
always returning `activeTurnId: null`. The daemon's existing retry then
re-steers into that turn.
- `tests/scripted-echo-provider`: new `steerFindsNewTurn` script option.
When a steer arrives, the fake completes the current turn, opens a new
one, then rejects the steer as stale, matching Codex's order.

No wire or protocol change: the runtime's result type is unchanged, and
`activeTurnId` was already part of the stale result.

## How you verified

- New test `keeps a newer turn that started while a stale steer was in
flight` in `packages/agent-runtime/src/runtime.input-accepted.test.ts`.
On `main`'s runtime it fails: the runtime recorded turn `t2` but
returned `{ status: "stale", activeTurnId: null }`. With this change it
passes, and `getActiveTurnId` still reports `t2`.
- `pnpm exec turbo run typecheck lint test --filter=@bb/agent-runtime
--filter=bb-plugin-scripted-echo-provider`: all 12 tasks passed.
- `pnpm exec turbo run test --filter=@bb/host-daemon --
test/command/thread-dispatch.test.ts`: 37 passed. These tests cover
retargeting a stale steer to the live 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 17, 2026
…; fix Pi turns after pi exits (#7551)

## Human comments

## What was wrong

The bridge conformance recordings had no case for settings changed
between turns or on a steer, for a steer that races the end of its turn,
or for the provider process dying mid-turn. Bridge fixes in exactly
those areas (#4789, #4794, #4922, #5141, #3299, #6939, #7319, #7321,
#4947) were each caught by hand, after users hit them. ACP was recorded
only for Cursor.

## What changed

Besides the suite, this fixes the bugs it found: Pi's crash handling,
two ACP permission bugs, where Pi keeps its session files, and a Windows
process-kill race. No protocol change. The plugin SDK is bumped to
0.6.150 because its bundled ACP bridge and replay kit changed; its
public surface did not.

- **Pi fixes (`plugins/provider-pi/src/bridge`).**
- **pi died, next message.** After the pi process died, the bridge kept
the thread's session registered with a dead child, so the next
`turn/start` failed with `No active Pi session` and the thread stayed in
error. `PiRpcSession.hasExited()` now lets `reconcileTurnOptions` treat
an exited pi like a settings change and rebuild the session from its
session file through the existing rebuild path. Users see the next
message continue the conversation. The `session/replaced` notice has
`contextLost: false` and isn't shown in the timeline.
- **Steer racing pi's death.** A steer that reached the bridge after pi
died got a generic error: the message was lost and the thread went to
error. It is now rejected with the stale-turn contract (`NO_ACTIVE_TURN`
+ `staleTurn`), as Codex and ACP do, so bb runs the message as a new
turn, which rebuilds the session.
- **Session file missing.** The rebuild silently started a blank
session. It now announces `contextLost: true`, so the timeline shows
"Provider session was replaced; provider-side context was lost. pi's
session file was missing…".
- **Session file corrupt.** pi refused to start, and every later message
failed the same way. Before rebuilding, the bridge now reads the session
file the way pi does. If it isn't a valid pi session, the bridge starts
a new pi session and announces `contextLost: true`, so the timeline
shows the context-loss note and the thread stays usable.
- **Other restart failures.** Any other failure to restart pi is
reported as an error. The thread keeps its session, and the next message
resumes it, so a one-off startup failure doesn't lose the conversation.
- New tests in `bridge.round2.test.ts` cover the steer, missing-file,
corrupt-file and failed-restart cases; each fails without its fix.
`session-cwd.test.ts` checks the session-file check against pi's own
rules (an empty file is valid, and a leading blank or unparseable line
is skipped). The fake pi now rejects an invalid session file the way
real pi does. The Pi `provider-exit` scenario cell was re-recorded
against the fixed bridge.
  - No protocol change.
- **ACP permission rule.** It used to check only that permission
requests the agent raised reached the user, so it was skipped whenever
the agent never asked. It now checks that every command an ACP agent ran
or asked to run after a change to a stricter mode went through the
user's approval. The Cursor and OpenCode `settings-steer` cells are
re-recorded with a command after the permission steer, and no rule is
skipped in any cell.
- The recording driver now answers approvals with allow-once. Cursor
turns bb's "allow for session" into `allow-always` and stores it in its
global allowlist. My earlier recordings had added
`Shell(printf|sleep|python3)` there, which made Cursor stop asking in
every thread; I removed those entries.
- **OpenCode 2 ran shell commands under Accept-edits without asking
(`packages/provider-bridge-acp`).** The bridge passed bb's policy in
`OPENCODE_PERMISSION`, which OpenCode 2.x no longer reads. When the
agent reports version 2 or later in `initialize`, the bridge now writes
bb's rules to the session with `opencode api PATCH /api/session/<id>`
before the first prompt: `edit` allow; `shell`, `webfetch` and
`external_directory` ask (all allow in Full), each on `*`. They go ahead
of the session's own rules, so additional-directory allows still apply.
OpenCode 1.x keeps the environment variable. A mode change already
restarts the session, which re-applies the rules. In Accept-edits, if
the launch command does not end in `acp` or OpenCode rejects the call,
the session fails to start instead of running unguarded. In Full Access
there is nothing to enforce, so a launch command that does not end in
`acp` logs once and the session starts. New bridge test for both modes.
New bridge test: OpenCode 2 gets the rules and keeps its directory rule,
and a switch to Full rewrites them; OpenCode 1.x gets no `api` call.
- **"Allow for session" was stored permanently by Cursor.** The bridge
answered it with the agent's `allow_always` option, which Cursor writes
to `~/.cursor/cli-config.json` for every future thread. It now answers
`allow_once` and keeps the grant in the bridge for that thread's ACP
session, including across the bridge's own rebuilds on a settings
change. Later requests with the same subject (same command, write scope
or tool) are approved without asking. `allow_always` is sent only if an
agent offers no allow-once option. New bridge test: the granted command
runs again without a prompt, a different command asks, and a new thread
asks for the granted command.
- **ACP restore after the agent dies (`packages/provider-bridge-acp`).**
- When a session rebuild failed because the agent exited during
`session/load` or `session/resume`, the bridge had already stopped the
old session and dropped the replacement. Every later message then got
"No active ACP session", and the provider session was never tried again.
The bridge now keeps the thread's settings and provider session after a
failed rebuild and restores them on the next `turn/start`, announcing
the replacement. A thread stop clears this. New bridge test: the agent
dies on its first `session/load`, the next turn resumes the same
session. It fails on the old code with "No active ACP session".
- An agent exit that landed while the bridge awaited the OpenCode 2
`opencode api` calls left a session whose agent was gone, reported as
started. The start now fails with "exited while its session was being
set up". New bridge test, which fails on the old code.
- **Pi sessions in the real `~/.bb` (`plugins/provider-pi`).** The Pi
bridge wrote session files to `~/.bb/pi-bridge-sessions` whatever bb's
data directory was, so source builds and second instances wrote into the
production data dir. Sessions now live in the plugin's
`bridge-data/sessions`. A thread whose file is still in the old place
gets a copy the first time the bridge resolves it; the old file is left
alone. New tests cover the new location, the copy, and that an existing
file is never overwritten.
- **Windows tree kills could hit an unrelated process
(`packages/process-utils`).** `stopWindowsProcessTree` checked that the
child was running, then launched `taskkill /pid <pid> /T /F`
asynchronously. If the child exited in that gap, Node handled the exit
and closed the handle, so Windows could give the PID to a new process
before taskkill ran. taskkill then killed that process and its children.
Forced Windows runs of this suite next to the Pi suite showed it:
provider processes in random cells, Codex included, died at startup with
exit code 1 and no output. With taskkill's output logged, 30 runs showed
9 kills of processes that were not the killer's children.
`stopWindowsProcessTree` now keeps the child's process handle open until
taskkill finishes. While taskkill runs, it holds back Node's internal
close of that handle (`ChildProcess._handle.close`), then makes that
close call once taskkill returns. Windows can't reuse a PID while a
handle to the process is open. The event loop isn't blocked. This
depends on Node's private `_handle`; if a child has none, the stop works
as before, without the guard. A new test checks that the handle stays
open through the child's exit until taskkill finishes, and is then
closed exactly once.
- **The recorder touched the real agent dirs.**
`scripts/provider-recordings/isolate-agent-state.mjs` runs each CLI
against temp config and state: Codex (`CODEX_HOME`), Pi
(`PI_CODING_AGENT_DIR`), Cursor (`CURSOR_CONFIG_DIR` +
`CURSOR_DATA_DIR`) and OpenCode (all four `XDG_*`, with its own service
port, a copy of its active credentials, and a warmed model catalog). A
refreshed `auth.json` is copied back. Two things can't be redirected, so
they are snapshot-and-restore or cleanup. Cursor syncs its built-in
skills into `$HOME/.cursor/skills-cursor` regardless, so that manifest
is restored. Claude Code keeps its sign-in in the keychain under its
config dir, so it can't be moved; instead the run's own `projects`,
`session-env`, `file-history`, `todos` and `debug` directories are
deleted afterwards. `~/.claude.json` is never rewritten, because other
Claude Code sessions write it concurrently.
-
`packages/provider-bridge-protocol/recordings/scenarios/<provider>/<cell>`:
20 new recordings made against the real CLIs (Codex 0.169.0, Claude Code
2.1.323, Pi 1.5.2, Cursor, and OpenCode 2.0.22 as a second ACP agent).
Four cells per provider:
- `settings-follow-up`: follow-ups that each change one setting (model,
env var, permission mode, reasoning level).
  - `settings-steer`: the same four changes, each sent with a steer.
  - `steer-race`: a steer sent as its turn ends, then a follow-up.
- `provider-exit`: the provider process killed mid-command, then a
follow-up.
- `src/testing/provider-probe-child.mjs` + `scenario-replay.ts` (new
`@bb/provider-bridge-protocol/scenarios` subpath, so the SDK bundle
stays unchanged): replay each cell through the current bridge with a
probe between the bridge and the existing replay child. The probe logs
the argv, env and stdin each provider process received, and kills the
provider where the recorded one died (`providerExit` in the manifest).
- `src/testing/recorded-scenarios.ts`: rules that hold for every bridge,
not snapshots:
- every cell: each message is accepted exactly once; every turn carries
the message that started it; every turn settles; a steer whose turn
already ended is rejected as stale.
- `settings-follow-up`: a changed model, reasoning level, env var or
permission mode reaches the provider before it gets that turn's prompt.
- `settings-steer`: a permission change sent with a steer reaches the
provider before it gets the steer. Applying a model, reasoning or env
var change mid-turn is deliberately not required: Codex, Claude Code and
Pi leave it for the next turn, ACP applies it, and both are allowed.
- `provider-exit`: the next message runs in a replacement process that
resumes the same session, or the bridge announces lost context.
- If a replay diverges from its recording, rules that depend on replayed
provider output are reported as skipped with a re-record note instead of
failing.
- `packages/provider-parity/src/scenarios.self.test.ts`: replays all 20
cells (about 15 s wall locally). It fails on any new rule failure, and
on any listed gap that now passes.
- `recordings/scenarios/known-gaps.json` is empty. It held the two
OpenCode Accept-edits gaps until the fix above; the OpenCode settings
cells are re-recorded against the fixed bridge and every rule in them
passes. The suite still fails on a new failure and on a listed gap that
starts passing.
- The replay kit answers `opencode api` calls the way it answers
`--version`, and keeps the agent's own launch args (`acp`) after the
replay args. The probe passes those calls straight through without
logging them as provider processes.
- Packaging normalizations, each noted in its manifest:
- Codex `config/read` responses trimmed to `config.model` (the rest was
the recording machine's config).
- Claude CLI 2.1.323's echoed hook-callback `control_response`s dropped.
The shared replay child would wait on them as answers to bridge
requests.
- Pi lines sent to a retiring child after its replacement spawned moved
ahead of the replacement.
- `scripts/provider-recordings/record-scenario-cell.mjs` records one
cell against the real CLI, through the gated agent-runtime harness
`src/integration.record-scenario-cells.test.ts`. It isn't run in CI.
- `scripts/provider-recordings/package-scenario-cells.mjs` redacts and
normalizes the raw recording and installs the cell. Re-packaging the raw
recordings with it reproduces every committed lane file byte-for-byte.
- The suite prints `<provider>/<cell> needs re-recording` when a replay
drifts.
- `docs/provider-bridge-protocol.md`: describes the scenario recordings,
the rules, and how to re-record.

Cut: a bb-shutdown-mid-turn cell was recorded too. Live, no provider
leaked the running command. But bridges legitimately differ: Codex sends
no interrupt and its app-server cleans up itself, while ACP, Claude and
Pi cancel. So no replay rule holds for every bridge, and the cell isn't
committed.

## Visible behaviour changes

- OpenCode 2 threads in Accept-edits now ask before shell commands, web
fetches and paths outside the workspace, as they did on OpenCode 1. A
custom OpenCode 2 agent whose launch command does not end in `acp` now
fails to start in Accept-edits with an error saying so; in Full Access
it starts as before.
- "Allow for session" on an ACP agent now lasts for that thread's
session only, and nothing is written to the agent's own config. It
covers the same command, write scope or tool. Cursor's own allow-always
covered a command prefix (`Shell(uname)`), so `uname -a` after granting
`uname -s` now asks again. After a server restart the thread asks again.
- Pi session files move under the data dir's
`plugins/provider-pi/bridge-data/sessions`. Existing threads are copied
over on first use. The old files stay in `~/.bb/pi-bridge-sessions` and
are not deleted.
- If an ACP agent dies while its session is being restored, the next
message restores the session instead of failing with "No active ACP
session".

## How you verified

- Pi, live on a source build (`pnpm start:worktree`, fresh dev data
dir). Each case plants a codeword first:
- **Killed mid-turn, then a message.** Before the fix it failed with `No
active Pi session`. After, it answers the codeword.
- **Killed while idle, then a message.** It answers the codeword, with
no context-loss note.
- **Steer racing the death** (bridge frozen with SIGSTOP, pi killed,
steer sent, then SIGCONT). Before the fix it showed "steer failed" and
the thread went to error. After, the steer runs as a new turn and
answers the codeword. The event order confirms the steer was sent while
the turn was still active.
- **Session file removed.** Before the fix it silently answered
`unknown`. After, the context-loss note shows, and the thread answers
the next message.
- **Session file corrupted.** Before the fix every message failed with
"Session file is not a valid pi session". After, the timeline shows
"pi's session file is not a valid pi session, so the conversation
continues in a new session without its earlier context." and the message
runs in a new session.
  - The `bb-plugin-provider-pi` tests, typecheck and lint pass.
- Platforms: pi's exit detection has no platform-specific branch: it
uses Node's `exit`/`close` events. The Linux and Windows CI replays run
the real Pi bridge (exit detection, rebuild, stale-steer reply) against
a replay child that the probe kills with SIGKILL, and the new unit tests
run the same bridge against the fake pi. On Windows the probe proxies
the Pi extension channel through a named pipe. The live runs above used
the real pi CLI on macOS.

- OpenCode 2 Accept-edits, live on a source build. Before the fix, a
thread ran `touch` with no approval. After, it shows "Waiting for
approval to run touch oc-accept.flag", and the file appears only once
the command is approved. The session's rules read back with `opencode
api GET` as bb's four, followed by the thread-storage directory allow. A
Full thread runs the command with no prompt.
- OpenCode 1.19.5 (installed in a temp prefix, run as a custom ACP agent
with temp `XDG_*` and `HOME`): an Accept-edits thread still asks before
`touch`, and the bridge makes no `api` call.
- "For session", verified where each part lives.
- On Cursor, the Cursor-specific part: before the fix, approving `uname
-s` for session added `Shell(uname)` to `~/.cursor/cli-config.json`, and
a new thread then ran `uname` without asking. After the fix, the same
approval leaves the file byte-identical (same sha1), and the command
runs.
- On OpenCode 2.0.22, live, the two steps that run in bridge code shared
by every ACP agent. Approving for session added no rule to OpenCode's
session. The same command in the same thread then ran with no new prompt
(one interaction in total), and a new thread asked again. The bridge
test covers them too: the granted command runs again without a prompt, a
different command asks, and a new thread asks.
- Pi sessions, live on a source build with its own data dir. A new
thread's session file is written to `<data
dir>/plugins/provider-pi/bridge-data/sessions`, and
`~/.bb/pi-bridge-sessions` is unchanged (325 files). After a server
restart the thread resumes from the new location and recalls its
codeword. Moving that file to the old location and restarting again
copies it back on resume, with the codeword kept.
- Isolation, live: one real cell each through the recorder for Codex,
Pi, Claude Code and Cursor, plus the two OpenCode settings cells.
Afterwards nothing tied to the run's workspace exists in `~/.codex`
(rollouts, `state_5.sqlite` threads), `~/.pi/agent`,
`~/.bb/pi-bridge-sessions`, `~/.claude`, `~/.cursor` (acp-sessions,
projects, `cli-config.json` sha), or OpenCode's real database. Config
and auth hashes are unchanged. Claude's own startup still rewrites
`plugins/known_marketplaces.json` (refresh timestamp) and adds one shell
snapshot, as any Claude start does; those are left.
- `@bb/provider-bridge-acp` (589 tests), `@bb/provider-bridge-protocol`
(312) and `@bb/provider-parity` (80) pass. The Pi session-file tests and
the typecheck and lint for all five touched packages pass too.
- Flakiness: a temporary workflow on a throwaway branch (this PR's head
plus only that workflow, same runners as CI) ran `turbo run test
--filter=@bb/provider-parity --filter=bb-plugin-provider-pi --force`. On
the final code: Linux 10/10; Windows 280/280 (20 runs, 20 more with
logging, and 240 looped runs). Every scenario suite was 21/21 with no
drift notices and no skipped rules, and every Pi suite passed. The
scenario suite takes about 21 s on Linux and 27 s on Windows (max 34 s).
Re-running CI jobs can't show this, because every re-run is a turbo
cache hit.
- Before the process-utils fix, Windows failed 6 of 40 runs: provider
processes in random cells died at startup and the replays stalled. The
Linux run that caught the probe-log cleanup race (`ENOTEMPTY`) was fixed
by retrying that removal.
- Windows sometimes failed `provider-exit` on `conversation-survives`:
twice on `acp-cursor` earlier, and once in 220 `acp-opencode` runs of a
loop. The loop's per-process log showed the cause. The bridge had
resumed the session correctly, but Windows had given the replacement
probe the dead probe's PID. The probe named its log after its PID, so
both processes' entries landed in one file, and the rule saw no
replacement. Logs are now named per process. Afterwards a cache-bypassed
Windows loop ran `acp-cursor/provider-exit` 1,100 times and every other
provider-exit cell 220 times. All passed, with no drift. Zero failures
in 1,100 puts the Cursor cell's failure rate below about 0.27% at 95%
confidence, and below about 1.4% for each of the others. The same run's
forced suite passed on Linux 10/10 and Windows 20/20.
- `vitest run src/scenarios.self.test.ts` in `@bb/provider-parity`:
21/21 pass, three runs, including two at load average ~40.
- Removing a known gap makes its cell fail with that rule.
- `turbo run typecheck lint lint:type-aware` for
`@bb/provider-bridge-protocol` and `@bb/provider-parity` passes.
- The existing parity fixture checks and the recordings redaction test
pass. The redaction sweep finds no survivors in the new cells.
- The scenarios were also run against the commits before and after the
past fixes listed above. Those proof runs are reported in the bb thread,
not committed.

> 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 17, 2026
…st guards (#7541)

## Human comments

## What was wrong

A paged timeline read could disagree with one full build of the same
history. The rows came back in a different order, on a different page,
or split differently. In one case the read crashed with a 500. The guard
tests in this PR found these disagreements. A walk of 336 real threads
from a production snapshot (read with SQLite only) confirms them: on
main, 3 threads mismatch at the 1500-event window budget and 5 at a
120-event budget. Replaying real threads at the points where a steer was
still pending or a warning arrived during a turn finds 6 more threads on
main.

There are two causes.

**Display order and ownership.** A page owned rows by their own
`sourceSeqStart` and ordered them using only the turns it happened to
load. A full build:

- shows a turn's rows together at its `turn/started`;
- sorts everything after the first external user message;
- splits turn summaries at user messages from other turns.

So a page could hold the wrong rows, or the right rows in the wrong
order. Real cases: thread operations recorded while a turn ran,
provisioning operations between a request and its `turn/started`, Codex
subagent child turns that never complete, and Codex delegations started
again after their turn completed.

**Missing context.** A rejected steer whose target turn starts before
the window crashed the read with a 500. The page never loaded that
turn's `turn/started` event.

## What changed

Server (`apps/server/src/services/threads/`):

- `timeline-display-ownership.ts` (new) owns each row by the greatest
`sourceSeqStart` a full build shows at or before it. It works from
whole-thread turn blocks: a block starts at `turn/started` and ends at
its last displayed row, including delegations started again after
completion. The same module decides which turns and thread rows a page
must load to show the rows it owns.
- `timeline-context-order.ts`: the ordering boundary also counts open
delegated child turns and is found in display order. The grouping
context keeps each turn's external-user split points.
- `timeline.ts` loads, for each page, the turns and standalone thread
rows it owns by display position. It also loads the `turn/started` of
any turn a steer in its context targets, including a rejected steer. It
passes the whole-thread split points to the projection.
- `timeline-pagination.ts`: row ownership is now a function passed in.
- Speed (detail below):
- `mergeStoredEventRowsById` skips the Map and the sort when its rows
are already in order;
- `listTimelineRootWindowTurnIds` checks for a root `turn/started` once
per distinct turn instead of once per row.

Other packages:

- `@bb/db`:
- new `listStoredStandaloneThreadTimelineRows`, with a query-cost case;
- `listTimelineOrderingContext` also returns delegation `item/started`
events that come after their turn completed, through
`events_thread_type_item_kind_sequence_idx`;
  - `listTimelineRootWindowTurnIds` takes distinct window turns first.
- `@bb/thread-view`: turn grouping accepts optional per-turn
external-user split points. When none are given, it computes them from
the loaded messages, as before.

Tests:

- The equivalence tests check two things on real SQLite for 30 seeded
event logs. They are split by seed group across four files over a shared
runner, `timeline-read-equivalence-runner.ts` (`-mixed-early`,
`-mixed-late`, `-interleaved` and `-extension-states`), so the groups
run in parallel workers:
  - every served latest window equals an uncached build;
  - a fresh paged walk equals one full build, rows and head fields.
- The generator keeps the four original switches on and models what real
agents record:
- Claude Code background commands nest under their command, never report
running progress, and can complete after their turn;
- background Task subagents report progress and finish inside their
turn;
  - task lifetimes follow the real distribution;
- Codex-style interleaved turns record no background tasks, as real
Codex threads do not;
- restarted delegations reach at most 20 completed turns back, the real
maximum.

The `lateBackgroundWork` and `backgroundTasksAcrossConcurrentTurns`
switches are deleted.
- `timeline-read-cost.test.ts` asserts that warm reads (pushes,
unchanged refetch, head state, first older page) read the same number of
rows when older history doubles. The doubled history is the same newer
history with an older prefix in front.
- `timeline-context-order-cache.test.ts`: the steer-boundary test was
ported with the acceptance it now needs. New cases cover the
earliest-boundary scan and open child turns.

## How you verified

- Checks:
- `pnpm exec turbo run typecheck lint:type-aware --filter=@bb/server
--filter=@bb/db --filter=@bb/thread-view --filter=@bb/client-core`
passes.
  - Targeted tests:
- `apps/server/test/services/threads/` plus the public scrollback test:
362 passed;
    - `@bb/db`: 724 passed, plus `check:query-costs`;
    - `@bb/thread-view`: 544 passed;
    - `@bb/client-core`: 234 passed, the same as main.
- Stress runs (scratch, not committed): 100 mixed, 100 interleaved and
25 extension-state seeds per range. Ranges 100–199, 500–599 and 900–999
each pass 225/225 on both checks.
- Production snapshot (VACUUM INTO of `~/.bb/bb.db`, SQLite only): a
paged walk against an uncached full build matches for 336/336 threads at
budgets 1500 and 120. On main it is 333/336 and 331/336.
- Real threads that mismatch on main and match on this PR, for the
display-order and ownership cause:
- snapshot at budget 1500: `thr_gtbhvapit2`, `thr_x4a8vhgs22`,
`thr_2wraycgcj8`;
- snapshot at budget 120: the same three, plus `thr_aa3eez5bi4` and
`thr_qnyc5qud36`;
- replayed at real moments (a steer still pending, or a warning during
an open turn; 623 points): main mismatches at 10 points at budget 120
and 12 at budget 40, on `thr_aa3eez5bi4`, `thr_gmz265vjuu`,
`thr_gtbhvapit2`, `thr_qnyc5qud36`, `thr_tvk52d9twn` and
`thr_c6vfueyv5g`. This PR matches all 623 at both budgets.
- Turning off each loading step on its own breaks real threads:
- without owned-turn loading, `thr_x4a8vhgs22` and `thr_2wraycgcj8`
mismatch;
  - without owned standalone thread rows, `thr_qnyc5qud36` mismatches.
- Live copies: walks of 506 threads from 69 copies of real Claude Code
and Codex runs match on this PR (and on main) at budgets 40 and 120.
- Read cost on the 30 largest snapshot threads. Five alternating rounds
of main, the previous head of this PR (94ac840) and this PR, three
builds per thread per round. Each figure is the sum over the 30 threads
of each thread's median, in ms, measured without the test-only
query-plan guard:

  | Read | main | previous PR head | this PR |
  |---|---|---|---|
  | Open latest, cold | 712.7 | 798.1 | 709.4 |
  | Open latest, warm | 32.1 | 37.2 | 32.1 |
  | Older page | 604.7 | 617.0 | 599.5 |
  | Push (one appended event) | 340.1 | 391.9 | 335.8 |

Against main, the 30-thread sums are −0.5%, +0.3%, −0.9% and −1.2%. Six
threads read more than 5% slower than main in that run; a second run of
main flags 4 to 7 per read. Re-timed with 40 samples per read, beside a
second run of main, five are within 5%. The sixth is `thr_quif856sdu`,
warm latest, at 5.5%: 0.05 ms on a 1.7 ms read, against 3.3% for main
against itself. With a forced GC before each build it is 3.3%, and every
re-timed read is within 5%.
- Speed changes in code this PR already touches:
- `mergeStoredEventRowsById` (420 ms of main's profile on these threads)
skips the Map and the sort when its rows are already in order;
- `listTimelineRootWindowTurnIds` checks for a root `turn/started` once
per distinct turn instead of once per row;
- the selection carries the grouping context it was built with, so a
memo-served build does not look the context up again.

## Behaviour changes you will see

- In paged views, rows now appear in the same order and on the same page
as in a full build. Thread operations recorded during a turn show after
that turn. Provisioning operations show before the turn they precede. A
delegation started again in a completed turn shows with that turn.
- A turn's "Worked for" summary splits at the same user messages as in a
full build.
- Opening a thread whose recent window holds a rejected steer no longer
fails with a 500.

## Not verified live

- A rejected steer that names a target turn was not produced live. bb
does not start Codex review turns, the one way to make Codex refuse a
steer on purpose, and provider timeouts cannot be triggered on demand.
Since #7319 and #7392, steers that miss their turn are retargeted
instead of rejected. The fix is kept because the server still records a
rejection for any steer command that fails, and the read must not crash
on it.

## Follow-up: thread-scoped notices and plugin requests

### What was wrong

A full build groups provider warnings, model fallbacks and thread-scoped
plugin interactions (for example a secrets request) into the root turn
running at their first event (`canGroupThreadMessageInTurn` in
`group-event-projection-turns.ts`). Pages did not apply this rule:

- a page holding only a later lifecycle event of an interaction showed
it as a separate row;
- the page owning the turn did not load the row;
- ownership treated the row as a thread row shown after the turn.

On a production snapshot, a paged walk of `thr_yb2r7jxqhz` moved a
secrets request about 700 events down; main shows it in place. The
equivalence generator emitted none of these events, so the guard tests
passed.

### What changed

- `timeline.ts`: a page loads the root turn a notice or interaction
joins, the thread rows that join a loaded turn
(`listStoredThreadNoticeAndInteractionRows`), and every lifecycle event
of an interaction it touches
(`listStoredThreadInteractionLifecycleRows`). Both queries use
`events_thread_type_sequence_idx` and have query-cost cases.
- `timeline-display-ownership.ts`: a joined row is owned with its turn.
- `timeline-selection-memo.ts`: the latest-window memo rebuilds instead
of appending such a row when its turn or the interaction's earlier
events are not in the held selection.
- `@bb/thread-view`: `threadEventJoinsRunningTurn` names which
thread-scoped events can join a running turn.
- Generator: emits plugin interactions (resolved or interrupted,
sometimes after their turn), provider user questions and provider
warnings.
- `timeline-read-cost.test.ts`: compares a 6,000-event older prefix with
a 12,000-event one. With no prefix, generator state carried across the
reseed (completed turns for restarted delegations) was empty, so the
"same" newer history diverged and read counts moved in both directions.
- `docs/timeline-pagination.md`: documents the rule.

### How verified

- Equivalence tests with the new generator: main 3/30, the previous head
of this PR 11/30, this head 30/30. A further 600 seeds (100 per shape in
two ranges) pass.
- Production snapshot (`VACUUM INTO` copy, SQLite only), a paged walk
against an uncached full build for every thread with more than 50
events, after rebasing on `7889bd2b5d`:

  | | main | previous head | this head |
  |---|---|---|---|
  | budget 1500 | 4542/4547 | 4546/4547 | 4553/4553 |
  | budget 120 | 4525/4547 | 4546/4547 | 4553/4553 |

(The snapshot for this head was taken later, so it has 6 more threads.)
- Rejected steer: a deterministic test with real SQLite (a steer that
targets a turn which completes before the agent confirms it, then is
rejected; the latest page holds the rejection but not the turn's
`turn/started`) returns 500 on main and 200 on this branch. No rejected
steer in the snapshot names a target turn, so this was not seen in real
data.
- `pnpm exec turbo run typecheck lint lint:type-aware
--filter=@bb/server --filter=@bb/db --filter=@bb/thread-view
--filter=@bb/client-core` passes; `@bb/db` tests (718) and
`check:query-costs`, `@bb/thread-view` tests (553), and
`apps/server/test/services/threads/` plus the public scrollback test
(409) pass.

## Follow-up: guards

### What changed

- `timeline-in-turn-window.test.ts`: a page holding a rejected steer
whose target turn started before the page builds. On main it throws
`Timeline projection found message … for turn turn-1 without
turn/started` (the 500).
- `timeline-guard-coverage.test.ts`: lists every event kind (type and
scope) a full build can display and fails when the equivalence generator
does not produce one that is not in `NOT_GENERATED` with a reason. It
also fails on stale entries. The list currently holds 9 legacy or
diagnostic kinds and 19 kinds marked "not generated yet": the remaining
blind spots of the synthetic tests.
- Generator: also emits `provider/modelFallback` and SDK model-fallback
`provider/unhandled` events, in thread or turn scope.
- `test:timeline-history`
(`apps/server/test/timeline-history/paged-walk.test.ts`): copies the
database named by `BB_TIMELINE_HISTORY_DB` with `VACUUM INTO` (source
opened read-only), migrates the copy, and compares a paged walk of every
thread with one full build at budgets 1500 and 120. It skips without the
variable; the Turbo task is uncached and passes the variables through.
Documented under "Timeline History Walk" in `docs/debugging-and-qa.md`.

### How verified

- The coverage test fails when an entry is removed and names the missing
kind.
- `BB_TIMELINE_HISTORY_DB=~/.bb/bb.db pnpm exec turbo run
test:timeline-history --filter=@bb/server` passes on this branch (every
thread, about 8 minutes). With main's server code and
`BB_TIMELINE_HISTORY_THREADS=thr_2wraycgcj8` it fails at both budgets.
- Equivalence tests 30/30 and a further 600 seeds pass with the extended
generator; `apps/server/test/services/threads/` plus the public
scrollback test pass (410); `@bb/server` typecheck and lint pass.

### Not fixed

When a steer is recorded after its target turn completed and is then
rejected, a full build groups the steer with that turn and splits the
turn's summary row (`…:turn:0`). The older page that owns the turn does
not load the steer, so its summary row is unsplit (`…:turn`). The new
crash test checks only that the page builds. The server retargets steers
that miss their turn, and no rejected steer in the production snapshot
names a target turn.

> AGENT GENERATED

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

---------

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