Skip to content

fix: park input the provider is too busy to take instead of failing the run - #2417

Closed
SawyerHood wants to merge 1 commit into
mainfrom
fix-2370-tell-auto-busy-queue
Closed

SawyerHood wants to merge 1 commit into
mainfrom
fix-2370-tell-auto-busy-queue

Conversation

@SawyerHood

@SawyerHood SawyerHood commented Aug 25, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

A turn submission the thread could not take was a generic failure at every layer. bb thread tell --mode auto into a thread whose turn the daemon still holds (a start whose turn/started is in flight, the pending-start wait, #2379's admission assert) or whose provider refuses input mid-run (pi while it compacts) came back as command_failed. The server appended system/error, applied run.failed (status error while the native transcript advanced), and dropped the message. The queue never drained because it only drains from idle, until thread stop released the runtime.

The pi bridge amplified a refusal: a rejected prompt raised a session error (onDone(error) → provider.error {settlesTurn}) and resolved a failed prompt settlement (→ a failed turn.boundary with claimIfIdle). Either closed the open turn from under pi, after which every later send resolved to start and was refused identically; those are the repeated error blocks in #2370. There is no bb retry loop: each block was one new send hitting the same state.

The most common trigger in practice is two sends a few seconds apart from the UI or CLI on an idle thread: send 1 starts a turn, send 2 arrives while turn/started is still pending, and the daemon waited only 5 s (#2242) before refusing with "Refusing to start a competing turn while … is still starting". Measured on a Claude Code thread on 2026-08-25, client/turn/requested → turn/started took 7–15 s, so the refusal fired routinely.

On the reporter's nightly (7e10ea4, before #2379) the refusal text came from Agent.prompt in the in-process pi SDK session. On main, pi runs as an RPC child whose prompt answers an error only for refusals that precede its preflight (compaction); the post-preflight guard is swallowed. The pattern is kept as a defensive match only.

What changed

Two commits.

Commit 1 — park input the provider is too busy to take instead of failing the run

  • packages/provider-bridge-protocol: BRIDGE_JSON_RPC_ERRORS.TURN_BUSY (-32004) for a turn/start or turn/steer the provider refuses because it is mid-run (or compacting) and will not queue the input. Documented in docs/provider-bridge-protocol.md.
  • plugins/provider-pi: a rejected prompt/steer dispatch settles nothing (no session error, no prompt settlement) and keeps isProcessing as it was. Pi's compaction refusal, the bridge's own compaction-active steer refusal, and (defensively) the Agent.prompt guard answer TURN_BUSY. The fake pi's /busy knob models the compaction refusal pi really sends over RPC.
  • packages/agent-runtime: AgentRuntimeTurnBusyError (code thread_turn_busy) for the competing-start refusal and for TURN_BUSY rejections; turn state is left untouched; a refused start re-marks the session idle so the idle reaper can still release it.
  • packages/host-daemon-contract: THREAD_TURN_BUSY_ERROR_CODE, the one wire spelling. HOST_DAEMON_PROTOCOL_VERSION 170 → 171 (new turn.submit failure code on the wire).
  • apps/host-daemon: the pending-start refusal is an ExpectedCommandDispatchError with that code; thread_turn_busy is an expected RPC failure, checked against the runtime error's literal type at compile time.
  • apps/server (policy): a thread_turn_busy turn.submit failure records client/turn/rejected but appends no system/error and applies no run.failed; the live turn owns the status. The input is parked, never lost: a direct send goes to the thread's queue (raw payload, arrival order); a consumed queued group is restored at the head of the queue with its ids and grouping (restoreConsumedQueuedThreadMessagesInTransaction) on both drain paths, with fresh sort keys ahead of the current head; a parent system message (child-completed notice) is held in deferred_thread_messages with its taxonomy, stamped with the turn that refused it, and skipped while that turn is live (one attempt per turn); rows behind it still get their attempt. The re-queue hook is scoped to turn.submit dispatches.
  • CLI/skill/guide: --mode auto and the busy fallback are described on bb thread tell --help, the bb-cli skill, and the threads guide.

Commit 2 — wait out a starting turn and steer into it instead of refusing

  • packages/agent-runtime: RuntimeTurnState.releaseWaiters(threadId) resolves every waitForActiveTurn waiter with null when a pending start ends without a turn (bridge refused the start, a thread-scoped non-retrying provider/error, thread stop, process detach, shutdown) via dropPendingTurnStartWithoutTurn. turn/started still resolves waiters with the id first. WaitForActiveTurnArgs.signal (AbortSignal) lets a caller cancel the wait. DEFAULT_TURN_START_WATCHDOG_THRESHOLD_MS (120 s) is exported.
  • apps/host-daemon: the pending-start wait is now DEFAULT_TURN_START_WATCHDOG_THRESHOLD_MS instead of 5 s, so "still starting" has one meaning (the watchdog's); because the runtime releases waiters early, the bound is only reached for a start the watchdog also reports as stuck. thread.stop shares the per-thread lane with turn.submit, so the router keeps an AbortController per admitted turn.submit and an interrupt stop aborts them synchronously on arrival (abortQueuedTurnSubmits); an aborted wait, or a steer whose stop signal is already aborted, falls to the typed thread_turn_busy refusal, the server parks the input, and the stop runs next. A release stop does not abort (it leaves lifecycle state alone and skips a busy runtime, so a parked input would have nothing left to settle the thread); the submit keeps its wait and starts its turn if the release ends the pending start. No wire change (threadStopRequested is a daemon-internal dispatch option).
  • tests/scripted-echo-provider: thread_scoped_fail:<text> directive (accept input, emit a thread-scoped non-retrying provider/error, no turn), matching codex's real shape.
  • Contract comment, bb-cli skill, and threads guide updated: a message sent while the turn is starting waits for the start and steers into it; only a start the runtime reports as stuck, or a stop that arrives first, parks the message in the queue.

Known follow-ups (documented, not in this PR): the timeline still renders a busy-parked request as a rejected user row before the queued copy is delivered (thread-view projection change); a start refused busy on an idle thread waits on the daemon's turn events with no server-side watchdog; a later parent-system notice can overtake a held one when the provider accepts a steer mid-turn; thread.archive / interactive.resolve / thread.plan.cancel / thread.goal.clear queued behind a waiting submit still wait up to the bound (benign today, untested).

How you verified

Regression tests fail on the previous source and pass after (file-swap proofs logged per package):

  • pi bridge bridge.round2.test.ts: busy steer/start answer TURN_BUSY with no turn.boundary and no session error, including a turn/start refused during a held run.
  • agent-runtime runtime.recovery.test.ts / runtime.lifecycle.test.ts: typed busy on refused start/steer, live turn kept, refused start still reapable; a waitForActiveTurn waiter is released as soon as the bridge refuses the pending start, when an accepted start fails before its turn opens, and when the thread is stopped while its start is pending; runtime-turn-state.test.ts: releaseWaiters releases one thread's waiters only; abort signal resolves the wait.
  • host-daemon command-dispatch.test.ts / thread-stop-races.test.ts: typed expected code; pending start → id → appliedAs: steer with the 120 s bound; a start that ends without a turn runs the input as a new turn; an interrupt thread.stop aborts a waiting submit, which parks its input, and the stop runs next; a release stop waits behind the submit instead; a steer whose stop is already queued is parked.
  • db queued-thread-messages.test.ts: restore keeps ids and grouping, clears claims, lands ahead of a row queued into the emptied queue, and is what the next drain claims.
  • server thread-send-dispatch.test.ts: busy send keeps the thread active and queues the raw input; busy queued auto-send restores the group at the head; busy queued send into an active thread restores the group with its grouping ahead of the trailing row; busy parent system message is held with its taxonomy, not retried while the turn is live, steered into the next turn, and does not block a send deferred behind it.
  • contract test: protocol version expectation.

Commands (all through turbo, --force, on the rebased tip): typecheck for @bb/db, @bb/provider-bridge-protocol, @bb/agent-runtime, @bb/host-daemon, @bb/host-daemon-contract, bb-plugin-provider-pi, @bb/server, @bb/cli, @bb/templates, bb-plugin-scripted-echo-provider; the matching test tasks plus @bb/agent-runtime#test:integration and @bb/server#test:provider-corpus: all green. Four independent adversarial review rounds (the stop-lane finding came from one of them). EAP codename scan of origin/main..HEAD: clean.

Not done: no live reproduction against a real pi --mode rpc session during manual compaction (proven from pi's source and the fake's RPC shape instead).

Fixes #2370

AGENT GENERATED

…he run

Root cause: a turn submission the thread could not take was a generic
failure at every layer. `bb thread tell --mode auto` into a thread whose
turn the daemon still holds (a start whose turn/started is in flight, the
5s pending-start wait, #2379's admission assert) or whose provider refuses
input mid-run (pi while it compacts) came back as `command_failed`; the
server appended system/error, applied `run.failed` (status `error` while
the native transcript advanced), and dropped the message. The queue never
drained because it only drains from `idle` -- until `thread stop` released
the runtime. The pi bridge amplified a refusal: a rejected prompt raised a
session error (`onDone(error)` -> provider.error {settlesTurn}) and
resolved a failed prompt settlement (-> a failed `turn.boundary` with
claimIfIdle), either of which closed the OPEN turn from under pi, after
which every later send resolved to `start` and was refused identically
(the repeated error blocks). On the reporter's nightly (7e10ea4, before
#2379) the refusal was `Agent.prompt`'s "Agent is already processing a
prompt" from the in-process pi SDK session; on main pi runs as an RPC
child whose `prompt` answers an error only for refusals that precede its
preflight (compaction), and the post-preflight guard is swallowed. There
is no bb retry loop: each block was one new send hitting the same state.

What changed:
- provider-bridge-protocol: `BRIDGE_JSON_RPC_ERRORS.TURN_BUSY` (-32004)
  for a turn/start or turn/steer the provider refuses because it is
  mid-run (or compacting) and will not queue the input; documented in the
  protocol hygiene rules.
- provider-pi bridge: a rejected prompt/steer dispatch settles nothing --
  no session error, no prompt settlement (the rejection is the whole
  report; the live run settles itself) -- and keeps `isProcessing` as it
  was. Pi's compaction refusal, the bridge's own compaction-active steer
  refusal, and (defensively, for a pi that surfaces it) the `Agent.prompt`
  guard answer `TURN_BUSY`. The fake pi's `/busy` knob models the
  compaction refusal pi actually sends over RPC.
- agent-runtime: `AgentRuntimeTurnBusyError` (code `thread_turn_busy`) for
  the competing-start refusal and for `TURN_BUSY` rejections of turn/start
  and turn/steer; turn state is left untouched. A refused start re-marks
  the session idle like any other refusal (the runtime holds no turn for
  it), so the idle reaper can still release it; a provider that is in fact
  mid-run re-marks it busy with the turn events it emits.
- host-daemon-contract: `THREAD_TURN_BUSY_ERROR_CODE`, the one wire
  spelling, and protocol version 166 -> 167 (new turn.submit failure code
  on the wire).
- host-daemon: the pending-start refusal is an `ExpectedCommandDispatchError`
  with that code; `thread_turn_busy` is an expected RPC failure, checked
  against the runtime error's literal type at compile time.
- server: a `thread_turn_busy` turn.submit failure records
  client/turn/rejected but appends no system/error and applies no
  run.failed -- the live turn owns the status. The input is parked, never
  lost: a direct send goes to the thread's queue (raw payload, no envelope,
  no resolved mention context, arrival order); a consumed queued group is
  restored at the head of the queue with its ids and grouping
  (`restoreConsumedQueuedThreadMessagesInTransaction`) on both drain paths
  -- the idle fast path and a queued send into an active thread, which
  hands its consumed rows to `sendThreadMessage` -- so "do X" then "stop,
  do Y" keep their order. The restore assigns fresh sort keys ahead of the
  current head: the consume usually empties the queue, and a row queued
  during the round trip takes the initial key the consumed head had, so
  re-inserting the stored keys tied on `sortKey` and let the random id put
  the newcomer first or inside the group. A parent system message
  (child-completed notice) is held in `deferred_thread_messages` with its
  taxonomy, stamped with the turn that refused it; the flush skips it
  while that is still the live turn -- one attempt per turn, not one per
  sweep tick -- and moves on to the rows behind it, so a steer deferred
  behind the notice (#1650) is not parked for the rest of a long turn. The
  re-queue hook is scoped to turn.submit dispatches, matching the
  settlement exemption, and a failure handler that throws is logged rather
  than left as an unhandled rejection.
- CLI/skill/guide: `--mode auto` and the busy fallback are described on
  the discoverable surfaces.

Verification: regression tests fail on the previous source and pass after
-- pi bridge (busy steer/start answer TURN_BUSY with no turn.boundary and
no session error, including a turn/start refused during a held run),
agent-runtime (typed busy on refused start/steer, live turn kept, refused
start still reapable), host-daemon (typed expected code), db (restore
keeps ids and grouping, clears claims, lands ahead of a row queued into
the emptied queue and is what the next drain claims), server (busy send
keeps the thread active and queues the raw input; busy queued auto-send
restores the group at the head; busy queued send into an active thread
restores the group with its grouping ahead of the trailing row; busy
parent system message is held with its taxonomy, not retried while the
turn is live, steered into the next turn, and does not block a send
deferred behind it), contract (version 167). Typecheck and the full test
suites of every touched package pass via turbo.

Fixes #2370

Co-Authored-By: Claude <[email protected]>
@SawyerHood

Copy link
Copy Markdown
Collaborator Author

Closing. Superseded or out of date; will be redone on current main if still needed.

@SawyerHood SawyerHood closed this Aug 25, 2026
ymichael added a commit that referenced this pull request Sep 1, 2026
## Human comments

## What was wrong

The server marks a thread active when its first turn is accepted, before
the provider's root `turn/started` event records the active turn id. An
immediate `steer`, `steer-if-active`, or active-thread `auto` send
therefore tried to submit while startup was still in flight. The daemon
could reject it as a competing turn, and the follow-up was not reliably
delivered. The existing `thread-busy` wait cannot represent this state
because it intentionally waits for the current turn to finish and
dispatches the message as a later turn.

## What changed

- Added the distinct persisted queue wait `waitingOn.kind:
"turn-starting"` for join-turn sends against an active thread that has
no recorded root turn id yet.
- Root `turn/started` events wake those rows in queue order and
re-attempt them as steers into the newly identified turn. Ordinary
`thread-busy` rows remain untouched and continue waiting for the turn to
finish.
- Parent system notices use the same startup wait while preserving their
execution settings and system-message taxonomy.
- Added the queue label, icon, Send-now restriction, CLI description,
built-in bb-cli skill guidance, and thread guide documentation.
- Added regressions for multiple ordered startup steers, the real event
wakeup, separation from `thread-busy`, and parent-system-message
delivery. Updated older fixtures that previously modeled a live steer
without recording `turn/started`.
- Bumped the Plugin SDK to `0.4.34` and refreshed its public API
inventory because the queued-message DTO exposes the new wait kind.
- No host-daemon wire contract changed, so
`HOST_DAEMON_PROTOCOL_VERSION` is unchanged. The solution is
provider-agnostic and adds no Pi-specific behavior or held daemon
command.

This covers the startup-race portion investigated in closed PR #2417
with a server-owned persistent queue. It does not port #2417's separate
provider-busy/compaction refusal handling.

## How you verified

On the final rebase against `origin/main` (`026572964`):

- `pnpm exec turbo run test typecheck --filter=@get-bb/plugin-sdk
--filter=@bb/plugin-api-map --filter=@bb/app
--filter=bb-plugin-plugin-api-docs` — 11/11 tasks passed; the app suite
passed 3,688 tests and the Plugin Guide suite passed 74 tests.
- `pnpm exec turbo run test --filter=@bb/server --force --
test/threads/thread-send-dispatch.test.ts
test/threads/dispatch-hooks.test.ts
test/public/public-thread-fork.test.ts` — 43/43 tests passed.
- `pnpm exec turbo run typecheck --filter=@bb/server --filter=@bb/domain
--filter=@bb/db --filter=@bb/cli --filter=@bb/templates` — 8/8 tasks
passed.
- `bb plugin build plugins/plugin-api-docs` — backend and app artifacts
built successfully.
- Plugin SDK version guard and `git diff --check` passed.
- Manual QA with `sawyerhood/dev-browser` rendered a real queued row
showing `Waiting for turn to start`, with the thread still working and
Send now unavailable.

Related to #2370

> AGENT GENERATED
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.

tell --mode auto injects into busy turn instead of queueing: provider error retry loop, status flips to error while turn continues

1 participant