Skip to content

Preserve terminal stream disconnect classification - #1563

Closed
brsbl wants to merge 1 commit into
mainfrom
bb/retry-terminal-stream-disconnect-thr_957f3xid9y
Closed

brsbl wants to merge 1 commit into
mainfrom
bb/retry-terminal-stream-disconnect-thr_957f3xid9y

Conversation

@brsbl

@brsbl brsbl commented Aug 13, 2026 •

Copy link
Copy Markdown
Collaborator

What changed

  • Preserve stream-disconnected classification when Codex exhausts reconnect attempts and reports the terminal failure as codexErrorInfo: "other".
  • Keep the workaround narrow to the exact stream disconnected before completion message prefix; retry semantics and unrelated generic errors are unchanged.

Local reproduction

The deterministic replay below uses the exact terminal Codex event from the incident. It does not require intentionally breaking your network.

1. Reproduce on main

From a fresh clone:

git clone https://github.com/get-bb/bb.git bb-pr-1563
cd bb-pr-1563
pnpm install --frozen-lockfile
git switch main

node --conditions=source --import tsx --input-type=module <<'NODE'
import { createCodexProviderAdapter } from "./packages/agent-runtime/src/codex/adapter.ts";

const [event] = createCodexProviderAdapter().translateEvent({
  jsonrpc: "2.0",
  method: "error",
  params: {
    threadId: "repro-thread",
    turnId: "repro-turn",
    error: {
      message:
        "stream disconnected before completion: error sending request for url (https://chatgpt.com/backend-api/codex/responses)",
      codexErrorInfo: "other",
      additionalDetails: null,
    },
    willRetry: false,
  },
});

if (event?.type !== "provider/error") throw new Error("Expected provider/error");
console.log(event.errorInfo);
NODE

Observed on main (e1ec66e8c when this PR was opened):

{ category: 'unknown', providerCode: 'other', httpStatusCode: null }

This is the bug: the terminal event loses the structured disconnect category, so BB renders the final timeline row as Provider error.

2. Verify this PR

In the same clone:

git fetch origin pull/1563/head:pr-1563
git switch pr-1563

Rerun the same node ... <<'NODE' block above. Expected output:

{
  category: 'stream-disconnected',
  providerCode: 'responseStreamDisconnected',
  httpStatusCode: null
}

BB can now render the terminal row consistently as Provider stream disconnected.

Optional real-network reproduction

  1. Start a Codex turn that runs long enough to keep the response stream open.
  2. After the turn is accepted, temporarily disable the machine's network or DNS until Codex exhausts its reconnect attempts.
  3. Restore connectivity and inspect the thread events:
bb thread log <thread-id> --format json --limit 5000 \
  | jq '[.[] | select(.type == "provider/error") | {
      seq,
      willRetry: .data.willRetry,
      errorInfo: .data.errorInfo,
      detail: .data.detail
    }] | .[-10:]'

Before this fix, reconnect attempts carry responseStreamDisconnected, but the final willRetry: false event can carry providerCode: "other" and category: "unknown" even though its detail still starts with stream disconnected before completion:. Network behavior and retry timing make this path less deterministic than the event replay above.

Root cause

Codex preserves responseStreamDisconnected during reconnect attempts, then can downgrade the same terminal failure to codexErrorInfo: "other" after its retry budget is exhausted. BB trusted that degraded terminal value and discarded the more specific classification encoded in the unchanged message.

Verification

  • Deterministic replay on main: reproduced category: "unknown".
  • The same replay on this PR: returns category: "stream-disconnected".
  • Regression test failed before the production change and passed afterward.
  • pnpm exec turbo run test --filter=@bb/agent-runtime: 46 files, 943 tests passed.
  • pnpm exec turbo run typecheck --filter=@bb/agent-runtime: passed.
  • Review loop: CORRECT, no P0–P2 findings.
  • GitHub CI: green.

Fixes #1840

BB-Thread-ID: thr_957f3xid9y

AGENT GENERATED: by GPT-5.6 Sol

@bb-slop-cop

bb-slop-cop Bot commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

🚨 SLOP COP 🚨 · review

I am SlopCop. I am reviewing this pull request for security, code quality, performance, architecture, and practical behavior.

I will post the complete review after the parallel checks finish.

error: {
message:
"stream disconnected before completion: error sending request for url (https://chatgpt.com/backend-api/codex/responses)",
codexErrorInfo: "other",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 slopcop/review — Please add one negative case for an unrelated other error.

The PR states that unrelated generic errors stay unchanged. This test proves only the positive match.

Add a second case with message: "request failed". Assert category: "unknown" and providerCode: "other". This case will protect the narrow guard.

@bb-slop-cop bb-slop-cop Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 SLOP COP 🚨 · review

ELI5: Codex sometimes puts the wrong name on a lost connection. This change adds the correct label, like a label on a toy box.

Review result

I found no security, correctness, performance, or architecture defect. The Codex adapter is the correct layer, and no duplicate classifier exists.

One minor test gap remains. The new test covers the matching other error, but it does not protect unrelated other errors. I left an inline suggestion for a negative case.

The anchored regular expression has a bounded cost. The category change does not affect retries, process restarts, credentials, or rate-limit recovery.

I ran these checks:

  • pnpm exec turbo run test --filter=@bb/agent-runtime --force: 46 files and 943 tests passed.
  • pnpm exec turbo run typecheck --filter=@bb/agent-runtime: passed.
  • A direct adapter replay returned stream-disconnected with responseStreamDisconnected.
  • All required GitHub CI checks pass.

I did not run a browser test because this change has no web route. The direct adapter replay tested the complete changed path.

This is a comment-only review. I did not approve the PR or request changes.

Carry structured retry error context through Codex's terminal downgrade instead of inferring the category from English message text.

Co-authored-by: Bersabel Tadesse <[email protected]>
@ymichael
ymichael force-pushed the bb/retry-terminal-stream-disconnect-thr_957f3xid9y branch from 064c93e to 9b15e33 Compare August 18, 2026 06:15
SawyerHood added a commit that referenced this pull request Aug 21, 2026
Codex labels each reconnect attempt with a structured codexErrorInfo such
as responseStreamDisconnected, then reports the terminal failure for the
same stream error as "other" once its retry budget is exhausted
(codex-rs maps CodexErrorDetails::Stream to CodexErrorInfo::Other). The
bridge trusted the degraded terminal value, so the final timeline row
rendered as a generic "Provider error" instead of "Provider stream
disconnected".

Remember the retry-time classification per codex thread and turn, and
reuse it when the terminal "other" error carries the same failure text.
Unrelated terminal errors, other turns, completed turns, and closed
threads keep the provider-reported value. Ports the design of #1563 onto
the narrow-grammar delta translator that replaced event-translation.ts.

Co-Authored-By: Claude <[email protected]>
SawyerHood added a commit that referenced this pull request Aug 21, 2026
)

## What was wrong

Codex labels each reconnect attempt with a structured `codexErrorInfo`
(for example `{ responseStreamDisconnected: { httpStatusCode } }`,
`willRetry: true`, failure text in `additionalDetails`), then reports
the terminal failure for the same stream error with `codexErrorInfo:
"other"` and the failure text moved to `message`. That downgrade is
upstream: codex-rs `notify_stream_error` always labels retries
`ResponseStreamDisconnected`, while `CodexErr::to_codex_protocol_error`
maps `CodexErrorDetails::Stream` to `CodexErrorInfo::Other`. The bridge
trusted the terminal value, so the final timeline row lost the
`stream-disconnected` category and rendered as a generic **Provider
error** (the detail text is longer than the 80-char title budget, so the
disconnect cause was only visible after expanding the row).

Issue: #1840. The independent report URL
(https://get-bb.github.io/reports/issues/1840.html) returns 404; the
issue body and #1563 carry the repro.

## What changed

- `plugins/provider-codex/src/delta-translation.ts`: the translation
state remembers the retry-time `codexErrorInfo` and failure text per
codex `threadId\0turnId`. A terminal (`willRetry: false`) error whose
`codexErrorInfo` is `other` and whose failure text equals the remembered
retry text reuses the retry classification. The context is consumed by
the terminal error, dropped on `turn/completed`, and never crosses
turns. Unrelated terminal errors and every non-`other` terminal value
keep the provider-reported classification. No provider prose is parsed.
- `plugins/provider-codex/src/translator.ts`: `thread/closed` also
clears the retry context for that codex thread (exported
`clearCodexEventTranslationThreadState`).
- No wire change between server and host daemon: the `provider/error`
event shape is unchanged, only the value of `errorInfo` on this one
path. No CLI or doc surface changes.

Relation to #1563: that PR (same design, by @ymichael and @brsbl)
targets `plugins/provider-codex/src/event-translation.ts`, which #1834
deleted when it moved Codex onto the narrow-grammar delta translator. It
no longer merges (`git merge-tree` reports a content conflict in
`delta-translation.ts`). This PR ports that design onto
`delta-translation.ts`, with a flat `Map` keyed by thread+turn instead
of nested maps.

## How you verified

Tests added in `plugins/provider-codex/src/translator.test.ts` (`codex
terminal retry-error classification`):

- carries the retry classification into the degraded terminal error (and
the context is consumed, so a repeat stays `other`)
- does not relabel an unrelated terminal error after a reconnect
- scopes the retry context to the turn and drops it on `turn/completed`
- drops the retry context when the codex thread closes

Fail-before: with `delta-translation.ts` and `translator.ts` restored
from `origin/main`, `pnpm exec turbo run test
--filter=bb-plugin-provider-codex --force -- --run
src/translator.test.ts` fails the first test:

```
× carries the retry classification into the degraded terminal error
AssertionError: expected [ { type: 'provider/error', …(7) } ] to deep equally contain ObjectContaining{…}
  expected "category": "stream-disconnected", "providerCode": "responseStreamDisconnected"
  received "category": "unknown", "providerCode": "other"
```

The three negative tests pass on `origin/main` as expected (they pin
that the guard does not over-apply).

Pass-after, from the committed tree (`git status --porcelain` empty):

- `pnpm exec turbo run typecheck test --filter=bb-plugin-provider-codex`
→ `Tasks: 7 successful, 7 total` (16 test files, 176 tests passed)
- `pnpm exec turbo run build` → `Tasks: 18 successful, 18 total`

Manual replay of the incident's two events (reconnect with
`responseStreamDisconnected`, then terminal `other` with the same
`stream disconnected before completion: ...` text) through
`createCodexEventTranslator` via `node --conditions=source --import
tsx`: the terminal delta now carries `errorInfo: { category:
"stream-disconnected", providerCode: "responseStreamDisconnected",
httpStatusCode: null }`.


## Rebase

Rebased onto `origin/main` after the grammar-v3 bridge stack landed
(#2124, #2136, #2153, #2148, #2164). That stack rewrote
`delta-translation.ts` (presentation on every item,
`injectedToolsByName` on the translation state, delegation items) and
`translator.ts` (`clearClosedThreadState` now returns the closes for
open delegations), but it did not touch the `error` case,
`toProviderErrorInfo`, or `turn/completed`, so the fix maps onto the new
code unchanged:

- The only textual conflict was in `CodexEventTranslationState` /
`createCodexEventTranslationState`, where main added
`injectedToolsByName` next to where this PR adds `retryErrorsByTurnKey`.
Resolved by keeping both fields.
- `clearCodexEventTranslationThreadState` is still called from
`clearClosedThreadState` in `translator.ts`, before it returns the
delegation closes that main added.
- The tests merged cleanly into `translator.test.ts`; they run through
the grammar-v3 `createDeltaAssembler` harness on main, and the
`provider/error` event shape they assert is unchanged.

Re-verified on the new base (`798b720ef`, one commit on top of
`origin/main`):

- Fail-before: with `delta-translation.ts` and `translator.ts` restored
from `origin/main`, `pnpm exec turbo run test
--filter=bb-plugin-provider-codex --force -- --run
src/translator.test.ts -t "codex terminal retry-error classification"` →
`1 failed | 3 passed`; `carries the retry classification into the
degraded terminal error` fails with expected `"category":
"stream-disconnected", "providerCode": "responseStreamDisconnected"`,
received `"category": "unknown", "providerCode": "other"`. The bug is
still present on current main.
- Pass-after, from the committed tree (`git status --porcelain` empty):
`pnpm exec turbo run typecheck test --filter=bb-plugin-provider-codex
--force` → `Tasks: 7 successful, 7 total`, `Test Files 18 passed (18)`,
`Tests 197 passed (197)`. `pnpm exec turbo run build` → `Tasks: 18
successful, 18 total`.

Fixes #1840

> AGENT GENERATED: by Claude Opus 5


## Independent verification

Verified on a fresh checkout of `bb/fix-1840-codex-stream-disconnect`
(282f32e, one commit on top of `origin/main`; `git merge-base
--is-ancestor origin/main HEAD` true, GitHub reports MERGEABLE).

Root cause checked against current upstream sources (not from the PR
description): `codex-rs/core/src/session/mod.rs` `notify_stream_error`
hard-codes `CodexErrorInfo::ResponseStreamDisconnected` for every retry
notification, `codex-rs/core/src/responses_retry.rs` returns the raw
`CodexErr` once retries are exhausted, and
`codex-rs/protocol/src/error.rs` `to_codex_protocol_error` has no arm
for `CodexErrorDetails::Stream` so it hits `_ => CodexErrorInfo::Other`.
The app-server maps `EventMsg::StreamError` to `error` with `willRetry:
true` plus `additionalDetails`, and `EventMsg::Error` to `willRetry:
false` with `additional_details: None`. The PR's correlation (retry
`additionalDetails` vs terminal `message`, same thread+turn, `other`
only) matches that wire shape exactly.

Commands:

- `pnpm install --frozen-lockfile --prefer-offline` and `pnpm exec turbo
run build` (18/18).
- Fail-before: `git checkout origin/main --
plugins/provider-codex/src/delta-translation.ts
plugins/provider-codex/src/translator.ts`, then `pnpm exec turbo run
test --filter=bb-plugin-provider-codex --force -- --run
src/translator.test.ts -t "codex terminal retry-error classification"`:
1 failed, 3 passed. Failing assertion: `carries the retry classification
into the degraded terminal error` -> `AssertionError: expected [ { type:
'provider/error', ...(7) } ] to deep equally contain
ObjectContaining{...}`, expected `"category": "stream-disconnected",
"providerCode": "responseStreamDisconnected", "httpStatusCode": 502`,
received `"category": "unknown", "providerCode": "other",
"httpStatusCode": null`.
- Pass-after: restored the PR sources (`git status --porcelain` empty),
`pnpm exec turbo run typecheck test --filter=bb-plugin-provider-codex
--force` -> `Tasks: 7 successful, 7 total`, `Test Files 16 passed (16)`,
`Tests 176 passed (176)`.
- Only `packages/thread-view/src/error-display.ts` consumes the
`stream-disconnected` category (title text); no runtime recovery keys on
it, so the blast radius is the timeline row title.

Repro on the fixed branch: a real Codex stream outage cannot be
triggered deterministically here, so I replayed upstream-shaped events
through `createCodexEventTranslator` directly (`node --conditions=source
--import tsx`): four `Reconnecting... n/5` retries labelled
`responseStreamDisconnected` with the failure text in
`additionalDetails`, then a terminal `other` with that text as `message`
and `additionalDetails: null`. Fixed branch:
`{"category":"stream-disconnected","providerCode":"responseStreamDisconnected","httpStatusCode":null}`.
Same script with `origin/main` sources:
`{"category":"unknown","providerCode":"other"}`. Extra negative replays
on the fixed branch all stayed correct: unrelated terminal text after a
retry stays `unknown`; a structured terminal value
(`responseTooManyFailedAttempts`, 503) is never overridden by the
remembered retry; a thread-scoped retry (no `turnId`) does not relabel a
turn-scoped terminal; a retry on a different codex thread does not leak
across threads.

CI: all checks pass (Checks, Package Smoke ubuntu+macos, Tests
app-1/2/3, integration, server, packages, version check).

Residual risks (minor, not blocking): the correlation needs the terminal
`message` to equal the last notified retry's `additionalDetails`; the
terminal `CodexErr` is the attempt after the last notified retry, so if
the inner reqwest text differs between attempts the row falls back to
today's generic label (never to a wrong one). Retry context for a turn
whose child dies without `thread/closed` or `turn/completed` lives in
the per-session translator until the session is released (a few bytes).
The upstream mapping gap in codex-rs remains.

> AGENT GENERATED: by Claude Opus 5




## Independent verification (post-rebase)

Re-verified after the rebase onto the grammar-v3 bridge. Checked out
`798b720ef` (one commit on top of `cf00cfe06`); `origin/main` had since
gained #2120 (provider-literal ratchet), which merges cleanly and
excludes `plugins/provider-*`, so it cannot affect this PR (`node
scripts/check-provider-literal-ratchet.mjs --base origin/main` ->
`ratchet OK: 148 references across 40 core files`).

Fix still targets the right code path in the rewritten translator: the
v3 stack left the `error` case, `toProviderErrorInfo`, and
`turn/completed` unchanged; `clearCodexEventTranslationThreadState` runs
inside `clearClosedThreadState` before the delegation closes it now
returns; `translateEvent` still routes `error` events through
`translateCodexEventToDeltas(event, eventTranslationState)` with the
single per-session state. Nothing downstream reclassifies:
`@bb/agent-runtime` `shouldRestartCodexThreadAfterEvent` keys only on
`rate-limit`/`unauthorized` categories (a retry-time label is always
`stream-disconnected`, so restart policy is unchanged) and
`packages/thread-view/src/error-display.ts` is the only consumer of the
category.

Commands (all from the committed tree):

- Fail-before on current main source: `git checkout origin/main --
plugins/provider-codex/src/delta-translation.ts
plugins/provider-codex/src/translator.ts`, then `pnpm exec vitest run
src/translator.test.ts -t "codex terminal retry-error classification"`
in `plugins/provider-codex` -> `1 failed | 3 passed`; `carries the retry
classification into the degraded terminal error` fails with expected
`"category": "stream-disconnected", "providerCode":
"responseStreamDisconnected", "httpStatusCode": 502`, received
`"category": "unknown", "providerCode": "other", "httpStatusCode": null`
(`src/translator.test.ts:1272`).
- Pass-after (sources restored, `git status --porcelain` empty): same
vitest command -> `4 passed`. `pnpm exec turbo run typecheck test
--filter=bb-plugin-provider-codex --force` -> `Tasks: 7 successful, 7
total`, `Test Files 18 passed (18)`, `Tests 197 passed (197)`.
- Dependents: `pnpm exec turbo run typecheck test
--filter=@bb/provider-parity --filter=@bb/agent-runtime
--filter=@bb/provider-bridge-protocol --force` -> `Tasks: 10 successful,
10 total` (parity 43 passed, agent-runtime 439 passed, bridge-protocol
217 passed). The parity suite replays every committed recording,
including `recordings/codex/auth-failure`, through the current bridge
with zero diffs.
- `pnpm exec prettier --check` and `pnpm exec eslint` on the three
touched files: clean.

Repro on the fixed branch: replayed the issue's event sequence (four
`Reconnecting... n/5` retries labelled `responseStreamDisconnected` with
the failure text in `additionalDetails`, then terminal `other` with that
text as `message`) through `createCodexEventTranslator` via `node
--conditions=source --import tsx`: terminal delta is
`{"category":"stream-disconnected","providerCode":"responseStreamDisconnected","httpStatusCode":null}`.
A terminal-only event with no preceding retry stays `unknown`/`other`
(by design). Cross-checked against upstream
`codex-rs/protocol/src/error.rs` (`Stream(..)` still falls to `_ =>
CodexErrorInfo::Other`; terminal `message` is `self.to_string()`, the
same text `notify_stream_error` puts in `additional_details`).

CI: all 11 check-runs on `798b720ef` succeed (Checks, Package Smoke
ubuntu+macos, Tests app-1/2/3, integration, server, packages, version
check x2); 2 skipped (node-compat smoke, iOS flows).

Residual risk (minor, not blocking): the real recorded `auth-failure`
cell shows Codex's failure text can carry per-request `cf-ray`/`request
id` values that differ between the last retry and the terminal attempt;
there the exact-text guard does not fire and the terminal row stays the
generic label exactly as on main (for that 401 case a
`stream-disconnected` label would arguably be wrong anyway, and the
runtime's 401 restart text pattern still matches). Retry context for
errors without a `turnId` is only dropped on `thread/closed`.

> AGENT GENERATED: by Claude Opus 5

Co-authored-by: Claude <[email protected]>
@ymichael

Copy link
Copy Markdown
Collaborator

Superseded by #2147

@ymichael ymichael closed this Aug 21, 2026
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.

Terminal Codex stream disconnects are misclassified as generic provider errors

2 participants