Skip to content

Keep the newer turn when a steer misses its turn - #7392

Merged
ymichael merged 1 commit into
mainfrom
bb/keep-newer-turn-on-stale-steer-thr_he8nqubqf7
Nov 10, 2026
Merged

ymichael merged 1 commit into
mainfrom
bb/keep-newer-turn-on-stale-steer-thr_he8nqubqf7

Conversation

@ymichael

Copy link
Copy Markdown
Collaborator

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

A steer can lose a race: the expected turn ends and the provider starts
another one before the steer arrives. The provider reports that new turn
before rejecting the steer, so the runtime has already recorded it, but
the stale-steer path cleared the thread's active turn unconditionally.
The daemon then saw no running turn and started a competing one instead
of steering into the turn that was running.

Stale steers now forget only the turn they missed and return whichever
turn is active, so the daemon's existing retry re-steers into it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit ba05ae8 into main Nov 10, 2026
34 checks passed
@ymichael
ymichael deleted the bb/keep-newer-turn-on-stale-steer-thr_he8nqubqf7 branch November 10, 2026 17:38
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