Skip to content

Fix provider session identity mixups during concurrent thread starts - #3496

Merged
ymichael merged 1 commit into
mainfrom
fix/3281-checkpoint-identity-thr_wexzr2ic26
Sep 11, 2026
Merged

ymichael merged 1 commit into
mainfrom
fix/3281-checkpoint-identity-thr_wexzr2ic26

Conversation

@ymichael

@ymichael ymichael commented Sep 11, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

When Codex forks started concurrently, BB could save a completed turn from one conversation with another conversation's provider session ID. Editing a later message then failed with HTTP 502: turn not found. The shared runtime ignored an identity delta's explicit BB thread owner and assigned it using a FIFO whose entries survived construction-result identity resolution. It also applied all identities in a batch before stamping earlier events and overwrote explicit event session IDs. This is a core runtime bookkeeping defect; native Codex notifications in the live reproduction named the correct sessions. See #3281 and the original incident report.

What changed

  • Remove pending-identity FIFO assignment. Resolve identities through explicit thread ownership or an existing provider mapping; unknown and retired identities cannot claim another thread.
  • Process identity updates and event stamping in order, filling only missing session IDs so explicit checkpoint/session pairs remain intact. Preserve legitimate scoped session replacement and late/duplicate notifications.
  • Add runtime, actual Codex bridge, and server ingestion/edit regressions using real in-memory SQLite, including reverse-order native identity deltas and failed-rewind history preservation.
  • Bump HOST_DAEMON_PROTOCOL_VERSION from 199 to 200 because daemon-emitted identity/checkpoint semantics change. No new wire fields, CLI/UI surface, or data migration.

Existing corrupt history is intentionally not rewritten: previous sessions and forks may legitimately share checkpoints, so a generic reassignment could lose history or replay ambiguous work. This fixes identity ownership; it does not implement the separate native-rewind or child-correlation proposals.

How you verified

Real authenticated Codex 0.153.3, gpt-5.6-luna, low reasoning: launched an isolated worktree server with pnpm start:worktree, scratch BB data and CODEX_HOME, then drove it through the source CLI. Three concurrent forks plus one ordinary start produced a mismatched SQLite checkpoint on the original runtime. Native completion records and scratch rollout membership independently confirmed the correct owner. Send → Stop → edit returned native turn not found, preserving all prior events. After applying the patch, all four fresh concurrent conversations passed send → Stop → edit, and a separate resume after daemon restart passed. Retrying the already-corrupt scratch thread still failed without altering its history. The exact timing of the reporter's private incident remains unverified.

Browser follow-up: used dev-browser on the same isolated patched server to edit the latest message in a fork. Luna low returned the replacement response; it persisted after reload, the thread returned to idle, and the native completion/session pair matched SQLite. Before/after screenshots were retained locally.

Fail before / pass after: native bridge fork/sibling checkpoint pairing; runtime → authenticated server ingestion → SQLite → edit consumption; duplicate/late identity handling, explicit pair preservation, same-batch ordering, and reverse registration-order native deltas.

Passing checks: 1,545 tests across selected runtime, server edit/fork/stop, Codex/Claude/Pi/ACP provider, host contract, and scripted-provider suites. Turbo typecheck and server/daemon build, changed-file formatting, and git diff --check passed. Representative commands:

pnpm exec turbo run test --filter=@bb/agent-runtime
pnpm exec turbo run test --filter=@bb/server -- thread-checkpoint-identity.test.ts thread-edit-message.test.ts thread-fork thread-stop
pnpm exec turbo run typecheck --filter=@bb/agent-runtime --filter=@bb/server --filter=@bb/host-daemon --filter=@bb/host-daemon-contract --filter=bb-plugin-scripted-echo-provider
pnpm exec turbo run build --filter=@bb/host-daemon --filter=@bb/server

Fixes #3281

AGENT GENERATED

@ymichael
ymichael merged commit bc75f9d into main Sep 11, 2026
16 checks passed
@ymichael
ymichael deleted the fix/3281-checkpoint-identity-thr_wexzr2ic26 branch September 11, 2026 17:15
ymichael added a commit that referenced this pull request Sep 21, 2026
…ff (#3460)

## Human comments

<!-- Agents: Do not fill in this section. This is for human users to
fill in. -->

## What was wrong

Codex >= 0.146 guards each rollout with a per-process `flock` on
`~/.codex/thread-writer-locks/<thread-id>.lock`, and refuses
`thread/start|resume|fork` with `thread <id> already has an active
writer` while another process holds it. The bridge treated that refusal
as a terminal, untyped error, so a single refused attempt failed the
user's turn outright even when the lock was about to be released a few
hundred milliseconds later.

This PR originally also carried fixes for the two bb-internal races that
produced most of those refusals. **Both have since landed on `main` by
other routes**, so they are no longer part of this diff:

- Awaiting the previous app-server child's exit before spawning its
replacement landed in #3025.
- Binding one Codex thread id to two bb threads (the #2327
investigation's root cause) landed in #3496.

What remains is the foreign-writer case that neither addresses.
`~/.codex/thread-writer-locks/` is global to the user account — bb only
overrides it through `CODEX_HOME`, never per instance — so a second bb
instance on the same machine, or a `codex` CLI the user ran in a
terminal, can hold a rollout bb wants to resume.

## What changed

`plugins/provider-codex/src/bridge/bridge.ts` (+40/-4):
`requestThreadConstructionWithWriterRetry` wraps the
`thread/start|resume|fork` request used by `constructThreadSession` in a
bounded 100/400/1000 ms retry ladder, matching only `already has an
active writer` and rethrowing everything else unchanged. Each retry
writes its method, delay, and attempt number to the bridge's stderr.
After the ladder is exhausted the provider's own error surfaces
verbatim.

An earlier revision appended remediation prose to the exhausted error.
It was removed in `dcc795d1cb`: it named no session the user could
actually find, told them to wait after the ladder had already waited,
and asked them to identify one of several concurrent `codex app-server`
processes distinguishable only by a port buried in their arguments.
Human-facing remediation is also product policy the server owns, and
every other provider failure class carries a structured recovery hint
the runtime acts on rather than prose in a plugin bridge.

The remaining ~450 lines are test infrastructure, and cover more than
the retry:

- `bridge.writer-lock.test.ts` (new, 250): seven regressions. Three
cover the retry ladder. **The other four cover the writer-handoff
serialization that shipped in #3025 with no test coverage at all** —
`previousChildExit` and `releasePromise` currently appear only in
`bridge.ts` on `main`, in no test file.
- `bridge-process.test-support.ts` (new, 130): shared process-lifecycle
helpers, missing-log-safe, attempting every cleanup stage even if an
earlier one fails. It already pays for itself:
`bridge.archived-rebuild.test.ts` is net −31 lines after adopting it.
- `fake-codex-app-server.mjs` (+69): a `writer.lock` fixture mirroring
Codex's flock semantics, a process-lifecycle log, and a scripted SIGTERM
delay applied only to children that served `thread/start|resume|fork` —
a real maintenance child holds no writer and exits promptly, and
delaying every child let an in-flight rebuild finish before a concurrent
discard could mark the replacement closing.

No host-daemon wire contract changed, so `HOST_DAEMON_PROTOCOL_VERSION`
is unchanged.

## How you verified

`pnpm exec turbo run test typecheck lint
--filter=bb-plugin-provider-codex --filter=@bb/agent-runtime
--filter=@bb/host-daemon` — 13/13 tasks, 324 + 333 + 727 tests passing.
After the prose removal, `--filter=bb-plugin-provider-codex
--filter=@bb/agent-runtime` — 10/10 tasks, `bridge.writer-lock.test.ts`
7/7.

Live end-to-end against real `codex-cli 0.154.0` (the test fake cannot
be injected into a running app — `sanitizeInheritedChildProcessEnv`
strips every `BB_*` variable from bridge children). A Codex thread was
run to completion, its app-server child killed, and an exclusive `flock`
taken on its rollout lock by an outside process, reproducing exactly
what a leftover Codex session does. Measured from the persisted `events`
table:

| Scenario | Build | Result |
| --- | --- | --- |
| Persistent foreign writer | `origin/main` | rejected after **668 ms**
— one attempt |
| Persistent foreign writer | this branch | rejected after **2503 ms** —
four attempts over 100+400+1000 ms |
| Lock released 539 ms after the turn was issued | `origin/main` | hard
turn failure |
| Lock released 539 ms after the turn was issued | this branch |
`turn/started` 440 ms later, turn completed normally |

The recovery case is the one that matters: the resume was blocked when
issued, retried through the backoff, and succeeded once the lock freed,
with no error shown to the user.

## Scope

This does **not** close #2327. That issue contains two distinct bugs;
the identity mixup found during its investigation was fixed by #3496,
and the originally reported problem — `turn/completed` published before
the commands in that turn terminalize — is untouched here and still
open.

A persistent foreign writer is improved but not eliminated: if the other
owner does not release within ~1.5 s, the turn still fails with Codex's
error. A typed `writerBusy` recovery hint carrying the provider thread
id would let the runtime name the owning bb thread instead of surfacing
a raw UUID; that is deliberately left out of scope.

Supersedes #2578.
Relates to #2327.

> AGENT GENERATED

---------

Co-authored-by: Michael Yong <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[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.

Codex message edit fails with 502: stored checkpoint references another thread’s session

1 participant