Skip to content

Reconcile daemon turns the server lost track of on explicit stop - #3502

Merged
SawyerHood merged 8 commits into
mainfrom
bb/3462-fix-stop-leaving-threads-stuck-thr_vdv2rx6c7w
Sep 16, 2026
Merged

SawyerHood merged 8 commits into
mainfrom
bb/3462-fix-stop-leaving-threads-stuck-thr_vdv2rx6c7w

Conversation

@SawyerHood

@SawyerHood SawyerHood commented Sep 11, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

When the server considered a thread idle or failed while its daemon still held a root turn, Stop sent a release that deliberately retained the turn. The daemon returned the same result as a completed release, so Stop did nothing and subsequent sends kept failing as competing turns (#3462). A competing-turn refusal could also fail the server run despite a stored root turn still running.

What changed

The daemon reports activeTurnRetained on a declined release and identifies competing-turn refusals with competing_turn. Explicit Stop reconciles the retained turn into the normal interrupt path. Concurrent awaited stops share the complete operation, including an escalated interrupt; machine-preservation callers requiring a stopped thread receive any failure. Context clear cannot proceed while the thread remains stopping. An explicit Stop also interrupts a turn that starts while its release is pending.

A declined release no longer marks background commands stopped. A regression covers an interrupt failure followed by a successful Stop retry. Competing-turn refusals with a stored running root turn retain the active run; negative controls still fail ordinary refusals and refusals without a running root turn. Automatic release protection remains intact.

Rebased onto main c663ff1911496870026c779911ff874fb2a43f24, preserving the shared daemon Stop/storage-deletion helper, lifecycle ownership, and writable queues during Stop. Protocol 211 → 212 and plugin SDK 0.4.98 → 0.4.99 cover the contract/declaration changes. SDK, thread guide, and CLI skill document the behavior. The scripted Codex test server also accepts main's new configuration arguments so this layer passes independently.

Existing failure policy remains: an unsuccessful interrupt leaves the thread stopping; the public Stop request can still return success, so callers must inspect thread status before treating interruption as confirmed. This is explicitly documented. requireStopped callers reject on the command failure.

This is the bottom layer of #3502 → #3503 → #3512. #3503 repairs the Codex response/notification correlation race; #3512 protects provider-session ownership.

How you verified

  • Fresh Turbo tests/typechecks for server, daemon, runtime, daemon contract, SDK, and templates. Runtime 331, contract 59, SDK 113, and templates 55 passed. Server broad run passed 2,893 tests; three timeout suites passed a focused rerun, and both inherited Codex fixture failures passed after the argument parser fix. Stop/checkpoint suites passed 23 tests; the timeout/Stop rerun passed 108. Daemon passed 717 tests; its two repository-discovery failures came from the filesystem sandbox's synthetic /tmp/.git marker, and all 26 discovery tests passed outside that sandbox.
  • New retained-background-work regression fails before the settlement guard and passes after it, including successful retry. Existing coverage exercises idle/error retained turns, concurrent stops, turn-start/release races, context clear, and escalated interrupt failure for requireStopped callers.
  • Real Codex through the configured account pool, fresh isolated BB store and session home: with sleep 90 running, injected the server's erroneous error status, then invoked CLI Stop. The thread became idle in under a second with an interrupted completion, and the next turn answered STOP_RECOVERY_CONFIRMED. In a separate turn, injected idle during a foreground wait: the competing send recorded competing_turn without system/error, the original turn completed to idle, and a follow-up answered COMPETING_RECOVERY_CONFIRMED. Test server and daemon were shut down; no production store or process was changed. This verifies provider behavior through normal pool routing, not a separate scratch login.

Fixes #3462

AGENT GENERATED

@SawyerHood
SawyerHood added this pull request to stack #3504 September 11, 2026 17:30
@SawyerHood
SawyerHood force-pushed the bb/3462-fix-stop-leaving-threads-stuck-thr_vdv2rx6c7w branch from 7b1bae0 to 9bb6c72 Compare September 11, 2026 17:40
@SawyerHood
SawyerHood force-pushed the bb/3462-fix-stop-leaving-threads-stuck-thr_vdv2rx6c7w branch from a84cf29 to 5a30d7d Compare September 11, 2026 21:41
SawyerHood and others added 8 commits September 16, 2026 19:54
A thread could wedge with every send refused as a competing turn while
the app showed it idle or errored, and `bb thread stop` reported success
without changing anything (#3462).

Root cause, traced on four production Codex threads from 2026-09-01: the
Codex bridge settled the spawn turn as a synthetic zero-work completion
250 ms after `turn/start` responded, before the real turn opened. The
server went idle, a follow-up send was dispatched, and the real turn then
started as an unrequested root turn. The daemon correctly refused the
follow-up `turn.submit` as a competing turn, but the server settled that
refusal as `run.failed`, moving the thread to `error` while a root turn
it had already stored was still running. From `error` or `idle` an
explicit stop sends `intent: "release"`, which the daemon deliberately
skips when a turn is active, and the release result was indistinguishable
from a completed release, so the stop was a silent no-op until the daemon
turn ended. When it did, `run.succeeded` is illegal from `error`, so the
thread stayed errored.

The Codex zero-work settlement race that started the sequence is tracked
separately in #2580 (candidate fix #2639); this change does not touch the
bridge. It repairs the server and daemon sides so any provider turn the
server lost track of can no longer wedge a thread or be reported as a
successful stop.

Changes:
- Daemon: `thread.stop` with `intent: "release"` now reports
  `activeTurnRetained: true` when it keeps an active turn. Runtime and
  dispatcher refusals carry the `competing_turn` error code
  (`CompetingTurnError`, `COMPETING_TURN_ERROR_CODE`).
- Server: explicit stops (stop route, context clear) that get a retained
  release re-activate the thread from the daemon's report, mark it
  stopping, and interrupt it through the normal stop path, so the stored
  turn is completed as interrupted and the thread settles idle. Automatic
  release paths and the daemon's release race guard are unchanged.
- Server: a `turn.submit` refused with `competing_turn` while the thread
  has an uncompleted stored root turn records the rejection but keeps the
  thread active instead of failing the run; the running turn's completion
  settles it.
- Protocol version 199 -> 200 for the new optional result field and error
  code.

Verification: new server tests for idle/error retained-turn stops,
context clear, concurrent stops, a failed escalated interrupt, and the
competing-turn settlement with negative controls; all six behavioral
tests fail on the previous lifecycle implementation. Daemon dispatch and
error-code tests updated. Full @bb/server (2426), @bb/host-daemon (591),
@bb/agent-runtime (318) and @bb/host-daemon-contract (51) suites pass.
Live dev-app check with Codex: a running turn whose thread was flipped
to error/idle is interrupted by `bb thread stop` and the next send
succeeds; a send refused as competing keeps the thread active and it
settles idle when the daemon turn completes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The test helper returned the queued command as the RPC union, so the
caller's requestId read failed typecheck in CI.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
An explicit stop (the stop route, context clear, and machine preservation)
is now one single-flight operation per thread that re-reads the thread row
each round: it interrupts a live turn, releases an idle runtime, and after a
release the daemon declined it re-activates the thread and interrupts the
retained turn. A concurrent stop joins the whole operation, so it no longer
returns when a pending release resolves while the escalated interrupt is
still outstanding. Command failures are returned to each caller, and callers
that require the thread stopped get the failure of the escalated interrupt.

An explicit stop wins over work that is still running: a turn that starts
while the stop's release is in flight is interrupted too. This is documented
in the thread guide and the SDK declaration and covered by a regression.

The stop guard now counts holders and tracks releases separately, so a
pending awaited release no longer suppresses an interrupt requested through
the non-awaited path, and concurrent awaited stops no longer drop each
other's claim.

Co-Authored-By: Claude Code <[email protected]>
main published 0.4.84, and this layer changes the SDK's bundled type
declarations (the thread.stop result's activeTurnRetained field and the
threads.stop declaration), so the npm version guard requires a new version.

Co-Authored-By: Claude Code <[email protected]>
@SawyerHood
SawyerHood force-pushed the bb/3462-fix-stop-leaving-threads-stuck-thr_vdv2rx6c7w branch from cab00a5 to 8e083db Compare September 16, 2026 20:20
@SawyerHood
SawyerHood merged commit 4ae86ed into main Sep 16, 2026
16 checks passed
@SawyerHood
SawyerHood deleted the bb/3462-fix-stop-leaving-threads-stuck-thr_vdv2rx6c7w branch September 16, 2026 21:44
SawyerHood added a commit that referenced this pull request Sep 16, 2026
… names (#3503)

## Human comments

## What was wrong

Stacked on #3502. Codex can return `turn/start` before emitting
`turn/started`. The bridge discarded the response and fabricated a
completed turn after 250 ms, attaching accepted input to that synthetic
turn while the real work ran in a second, unaccepted turn (#2580 and
consolidated #2634). Compaction's empty response has the same
delayed-notification problem.

## What changed

Preserves Ratul Sarna's original #2639 implementation and authorship,
with lifecycle and failure-path fixes:

- Open and correlate the turn named by `turn/start`; deduplicate its
later native lifecycle notifications. Dedupe is scoped by provider
thread, cleared on exit, and bounded to 256 pending lifecycle records
per thread.
- Await compaction's actual turn. An idle/system-error report or process
exit can settle an unopened dispatch. Register it before sending the
request, buffer early status until RPC acceptance, and remove it as soon
as its input is accepted. A rejected request cannot fabricate an
accepted/completed turn.
- Retry an interrupt once only for the exact `-32600` / `no active turn
to interrupt` rejection when that same response-opened turn lacked
native activation at the initial attempt. Wait for activation, return
the original error on timeout, and avoid retrying a turn that already
settled.
- Preserve the legacy zero-work fallback only for a `turn/start` result
that names no turn.
- Bump `HOST_DAEMON_PROTOCOL_VERSION` from #3502's 212 to 213. Update
lifecycle regressions to use the current test harness after rebasing
onto main.

## How you verified

- Nine new failure-path regressions fail against the previous #3503
implementation and pass with these fixes: unrelated interrupt errors,
interrupt after native activation, completion-before-error, activation
timeout, compact idle/error before response, cross-thread dedupe, and
exit cleanup. Additional cases exercise a single retry,
activation-before-rejection, delayed terminal notifications, compaction
exit, and consecutive requests' tool attribution.
- `pnpm exec turbo run test typecheck --filter=bb-plugin-provider-codex
--filter=@bb/provider-bridge-protocol --filter=@bb/provider-parity
--filter=@bb/host-daemon-contract` passes on the rebased layer. Codex:
317 tests; protocol: 279; parity: 56; contract: 59.
- Real Codex 0.154.0 via the configured account pool, with fresh empty
`CODEX_HOME` directories and workspaces: a relay delays native start
notifications 400 ms. Reverting this layer to #3502 reproduces two
lifecycles for both an ordinary turn and compaction; the final layer
produces one accepted lifecycle. Delaying completion notifications also
proves the review fix: the prior bridge sends two interrupts after
native activation/real completion; the fixed bridge sends one and
preserves the real `-32600` rejection. No BB core or imported store was
started, and no credentials were copied.

Fixes #2580
Closes #2639

> AGENT GENERATED

---------

Co-authored-by: Ratul Sarna <[email protected]>
Co-authored-by: Claude Code <[email protected]>
SawyerHood added a commit that referenced this pull request Sep 16, 2026
## Human comments

## What was wrong

After the runtime identity mix-up in #3461, the server could resume a
thread into whichever provider session its newest event named. Ordinary
completion events and contaminated identity history could therefore
redirect messages into another conversation. Current main still has this
selector.

The independent safety review also reproduced a second path: editing a
message can delete the original owner's identity event, making a
contaminated later claimant appear to own that session.

## What changed

Third layer of #3502 → #3503 → #3512. Review this layer against #3503;
it retains the lower layers' Stop and Codex correlation behavior.

- Resolve sessions only from identity events after the last completed
context clear. Compare claims within the provider and host; unknown
hosts are treated conservatively. An earlier foreign identity is skipped
in favor of an owned identity. Earliest claims tied in the same
millisecond are ambiguous, regardless of insertion order.
- Refuse foreign-only, ambiguous, and invalid (null or empty
authoritative handle) resume attempts with 409
`provider_session_unavailable`. No turn is dispatched or history
appended. Queued sends record the refusal. `/clear` or `bb thread clear`
starts a fresh session on the next send while retaining history.
- Check ownership on edit checkpoints and anchored/tip fork sources.
Refuse an edit that would erase the earliest shared ownership evidence,
both before provider rewind preparation and atomically before suffix
deletion. If another claimant arrives while a rewind is being staged,
discard that staged session and retain the original history.
- Record identities for empty-input starts. Require start/fork identity
announcements in the public conformance kit and document unique, durable
provider session handles. Scripted multi-process fixtures mint unique
handles.
- Regenerate the identity index migration after current main as
`0125_silent_guardian`. Preserve idempotent index creation for migration
replay. Update pruning tests to keep their retention assertions while no
longer treating ordinary event stamps as authoritative identities.
- Resolve the real-provider integration manifest after test TMPDIR
isolation so setup and workers use the same manifest.

No daemon wire fields change in this layer. Existing stored history is
not rewritten on upgrade.

## How you verified

Independent review covered the complete layer, #3461 and original
investigation history, current-main changes, ownership queries/index
plans, context clear, provider/host isolation, tied claims, legacy
checkpoint lineage, and fork/rewind paths.

A new migrated-SQLite regression failed before the edit guard: removing
the owner's identity changed the other thread from `foreign` to `owned`.
Additional regressions fail before and pass after for null/empty
identity handles; these cannot silently replace the conversation. Guard
tests cover tied/strictly ordered claims, provider/host/unknown-host
scoping, retained duplicate claims, clear-context retention, pre-rewind
refusal, and a competing claim arriving before the atomic edit commit.
Server tests assert no history mutation or replacement start after
refusal, and successful staged-session discard.

Final head: `55097953348f0d583e34317375ed693d4d130716`, based on #3503
`cd67ddbb5735e4153e506bceec1a8c6a665dc2ef`. Its tree exactly matches the
reviewed local tree. Fresh forced Turbo checks ran on integrated
implementation head `e23319817a80042971fcf1e40036dda9b11ae5e6`; the
final follow-up changes only fixtures and formatting:

- DB: 573 tests and typecheck passed, including the generated migration,
replay, query plans, new edit guard and invalid-history regressions.
- Codex: 317 tests and typecheck passed. The unit run excludes inherited
account-pool environment variables because one missing-variable test
assumes they are absent.
- Server: typecheck passed. The full run passed 2,909 tests with one
skipped; two failed. One new-main fork metadata fixture lacked an
identity announcement and was corrected. The other, an unchanged
machine-environment test, exceeded its five-second limit under
full-suite load. All nine affected fixture tests then passed with
default timeouts; the 57-test migration suite also passed after
formatting. The final follow-up changes tests and formatting only.
- Other unchanged surfaces were freshly verified before final
lower-layer integration: protocol 282, SDK 291, Claude Code 364, ACP
319, Pi 167 (one skipped), echo 15, scripted echo 1, bb-guide 5, and
server/bridge integration 82. Corresponding typechecks passed.
- Real `codex-cli 0.154.0`: isolated session/workspace tests through the
configured account pool. All 12 tests passed again with the final
integrated implementation, serially: eight basic lifecycle and four
cross-process resume tests. The final fixture-only commit does not
change provider code. These are live provider calls, with no production
BB process or imported store started.
- The SDK npm version guard passes for unpublished 0.4.99. Changed-file
formatting passes under repository configuration; generated snapshots
were not manually edited.

Commands:

```sh
pnpm exec turbo run test typecheck --filter=@bb/db --filter=@bb/server --filter=bb-plugin-provider-codex --force --continue=always
pnpm exec turbo run test --filter=@bb/integration-tests --force
pnpm exec turbo run test:integration --filter=@bb/agent-runtime --force -- integration.provider-basic.test.ts integration.resume.test.ts -t '^codex' --maxConcurrency 1
```

Local runs used a writable npm cache. Tests were forced rather than
relying on prior CI or cache results. The full server run is not
represented as wholly green; the two failures and focused confirmations
are reported above. Final-head CI remains the landing gate.

## Limits

- Ownership is inferred from retained records, not an independent
durable ownership ledger. Purging all original-owner records still
removes that protection.
- Existing legacy fork/rewind checkpoints whose session was never
announced remain usable when no conflicting claim exists. Missing
announcement history is not proof of cross-thread ownership.
- Falling back to an older owned session cannot recover context written
into another rollout.
- A late edit refusal leaves the source session and stored history
intact. Discarding an unused staged rewind is best-effort; a provider
cleanup failure can leave an unused staged session.
- Third-party bridges must provide handles unique across that provider's
sessions on a host.

Fixes #3461

> AGENT GENERATED

---------

Co-authored-by: Claude Code <[email protected]>
ymichael added a commit that referenced this pull request Nov 14, 2026
… live commands

Output an ACP agent sends with no prompt in flight is recorded on the last
turn (attach currentOrLast on text, item.open and item.close) instead of
opening a turn, so agents without an idle signal never leave a thread
Working. Stop answers a pending turn/start at once. Built-in /compact is
offered when the provider declares it or the thread's live commands list
compact; ACP no longer declares it. Launch-flag agents only receive model
ids their list contains. Restores coverage for #3502 at the daemon and
server.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 14, 2026
… live commands

Output an ACP agent sends with no prompt in flight is recorded on the last
turn (attach currentOrLast on text, item.open and item.close) instead of
opening a turn, so agents without an idle signal never leave a thread
Working. Stop answers a pending turn/start at once. Built-in /compact is
offered when the provider declares it or the thread's live commands list
compact; ACP no longer declares it. Launch-flag agents only receive model
ids their list contains. Restores coverage for #3502 at the daemon and
server.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 17, 2026
… live commands

Output an ACP agent sends with no prompt in flight is recorded on the last
turn (attach currentOrLast on text, item.open and item.close) instead of
opening a turn, so agents without an idle signal never leave a thread
Working. Stop answers a pending turn/start at once. Built-in /compact is
offered when the provider declares it or the thread's live commands list
compact; ACP no longer declares it. Launch-flag agents only receive model
ids their list contains. Restores coverage for #3502 at the daemon and
server.

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.

bb thread stop reports success but leaves a stray daemon turn, so every send is refused ("Refusing to start a competing turn")

1 participant