claude-code-hub icon indicating copy to clipboard operation
claude-code-hub copied to clipboard

fix: false 499 on completed Codex Responses streams

Open miraserver opened this issue 5 months ago • 2 comments

Summary

Fixes false `499 CLIENT_ABORTED` accounting for Codex Responses SSE streams. Codex CLI closes the HTTP connection immediately after receiving the terminal `response.completed` event, which CCH previously logged as a client abort — making successful requests look aborted in logs and provider-chain / circuit-breaker accounting.

Closes #1083. Related: #1242, #985.

Problem

For a streaming response CCH `tee()`s the upstream body into two branches: one forwarded to the client, one read internally to accumulate `allContent` (used for usage/cost, fake-200 detection, session binding). The internal reader breaks early when `clientAbortSignal` fires (`response-handler.ts`, stream loop). Codex CLI disconnects right after the terminal SSE event, so:

  1. the internal reader stops before consuming the terminal chunk → `allContent` is truncated,
  2. deferred finalization sees no terminal evidence and falls through to the client-abort branch,
  3. the request is recorded as `499` even though the upstream completed successfully.

Solution

Capture the Codex terminal signal independently of the internal reader, on the client-forwarding path before `tee()`, so timing of the client disconnect no longer matters.

  • A `TransformStream` placed before `tee()` feeds an incremental terminal-state tracker (`createCodexResponsesTerminalStateTracker`) that records terminal state, usage, service tier and `prompt_cache_key` as events flow to the client (last-event-wins).
  • `finalize()` handles a trailing terminal event that arrives without a closing blank line.
  • The tracker is the primary source of truth for Codex deferred streams; `allContent` remains the fallback. Non-Codex streams are entirely unaffected (guarded by `providerType === "codex"` from the deferred-finalization meta, which is correct under provider failover).

Terminal-state matrix

Terminal event Outcome
`response.completed`, `response.incomplete` `200` success (even if client aborted right after)
`response.failed`, `response.error`, `error` `502` + circuit-breaker `recordFailure`
No terminal event observed unchanged (`499` / `502`)
Non-Codex stream entirely unchanged

Changes

  • `src/app/v1/_lib/proxy/response-handler.ts` — `createCodexResponsesTerminalStateTracker` with incremental SSE parser and `finalize()` for trailing data without boundary newline; tracker-first priority for usage / service_tier / prompt_cache_key in `finalizeStream`; `shouldTrackForwardedCodexTerminalState` guard uses deferred meta `providerType` (correct under failover).
  • `src/app/v1/_lib/proxy/stream-finalization.ts` — optional `providerType` field on `DeferredStreamingFinalization`, normalized at set-time from meta or current session provider.
  • `tests/unit/proxy/response-handler-abort-listener-cleanup.test.ts` — 30 cases covering the full matrix: completed / failed / incomplete / error / response.error terminal states; abort timing; provider mismatch; multiline SSE data; trailing-newline-less terminal event; non-Codex unaffected; prompt_cache_key preservation.

Testing

ALLOW_NON_TEST_DB=true bunx vitest run tests/unit/proxy/response-handler-abort-listener-cleanup.test.ts
# → 30/30 pass

bun run typecheck
# → exit 0

bunx @biomejs/biome check src/app/v1/_lib/proxy/response-handler.ts \
  src/app/v1/_lib/proxy/stream-finalization.ts \
  tests/unit/proxy/response-handler-abort-listener-cleanup.test.ts
# → clean

Checklist

  • [x] Base branch is `dev`
  • [x] Single squashed commit, Conventional Commits format
  • [x] Linked related issues (#1083, #1242, #985)
  • [x] Unit tests added and passing (30/30)
  • [x] `bun run typecheck` exit 0
  • [ ] Docker Build Test green (CI)

Greptile Summary

This PR fixes false 499 CLIENT_ABORTED accounting for Codex Responses SSE streams. When Codex CLI closes the HTTP connection immediately after receiving the terminal response.completed event, CCH was previously logging successful requests as client aborts because the internal reader broke early before consuming the terminal chunk. The fix inserts a TransformStream before tee() that feeds an incremental terminal-state tracker (createCodexResponsesTerminalStateTracker), making the terminal verdict available independently of whether the internal reader consumed all content.

  • response-handler.ts: Adds createCodexResponsesTerminalStateTracker with incremental SSE parsing, finalize() for trailing events without boundary newlines, and uses tracker-first priority for usage/service_tier/prompt_cache_key in finalizeStream; shouldTrackForwardedCodexTerminalState guards use deferred meta providerType (correct under failover).
  • stream-finalization.ts: Adds optional providerType field to DeferredStreamingFinalization, normalized at set-time from meta or current session provider.
  • tests/: 30 new test cases covering all terminal states, abort timing, provider mismatch, multiline SSE data, trailing-newline-less terminal events, and non-Codex isolation.

Confidence Score: 4/5

Safe to merge; the fix is well-scoped, non-Codex streams are entirely unaffected, and the 30-case test suite covers the full terminal-state matrix including abort timing and provider failover.

The core mechanism is sound. The one gap is in finalize(): trailing plain-text error events that arrive without a closing blank line after a prior response.completed are silently ignored, recording the request as 200 instead of 502. This is an edge-case but a real correctness gap on the changed path.

The finalize() method in src/app/v1/_lib/proxy/response-handler.ts (lines 629-676) warrants a second look for its handling of plain-text error events without a trailing blank-line boundary.

Important Files Changed

Filename Overview
src/app/v1/_lib/proxy/response-handler.ts Core fix: adds createCodexResponsesTerminalStateTracker and wires it into the stream forwarding path before tee(); finalize() has a minor correctness gap for trailing plain-text error events without a closing blank line that follow a prior response.completed.
src/app/v1/_lib/proxy/stream-finalization.ts Minimal, correct change: adds optional providerType to DeferredStreamingFinalization and normalizes it at set-time from the meta or current session provider.
tests/unit/proxy/response-handler-abort-listener-cleanup.test.ts Comprehensive 30-case test suite covering the full terminal-state matrix, abort timing, provider failover, multiline SSE, trailing-newline-less events, and non-Codex isolation; no issues found.

Sequence Diagram

sequenceDiagram
    participant US as Upstream
    participant TS as TransformStream<br/>(+ terminal tracker)
    participant CS as clientStream<br/>(→ Codex CLI)
    participant IS as internalStream<br/>(internal reader)
    participant FS as finalizeStream()
    participant FD as finalizeDeferredStreaming...()

    US->>TS: SSE chunk (response.completed\n\n)
    TS->>TS: tracker.push(chunk)
    Note over TS: tracker state → "completed"
    TS->>CS: forward chunk
    TS->>IS: tee branch

    CS-->>CS: Codex CLI receives response.completed
    CS-->>CS: Codex CLI closes connection (abort signal fires)

    Note over IS: abortController.abort()<br/>internal reader breaks early<br/>allContent may be truncated

    IS->>FS: "streamEndedNormally=false, clientAborted=true"
    FS->>FS: "forwardedCodexTerminalDecoder.decode()<br/>tracker.finalize()"
    FS->>FD: getTerminalState() → "completed"
    FD->>FD: "codexTerminalFinished=true<br/>streamCompletedForFinalization=true<br/>effectiveStatusCode=200"
    FD-->>FS: "{effectiveStatusCode: 200, ...}"
    Note over FS: Request recorded as 200 (not 499)
Prompt To Fix All With AI
Fix the following 1 code review issue. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 1
src/app/v1/_lib/proxy/response-handler.ts:629-676
**`finalize()` silently ignores trailing plain-text `error` events when a prior `response.completed` was already processed**

`finalize()` only extracts `data:` lines and requires a successfully-parsed JSON object with a `type` field. When a plain-text `event: error\ndata: upstream connection closed` arrives in the buffer without a closing `\n\n` (e.g. the connection drops between the data line and the blank line), `JSON.parse` throws, `parsedObject` is `null`, `resolvedType` is `null`, and the state update is skipped entirely.

If `push()` already processed a prior `response.completed\n\n` (state → `"completed"`), the residual `error` event goes through `finalize()` unclassified, leaving `terminalState = "completed"` and causing the request to be recorded as a `200` success when the upstream actually signaled an error. The test suite covers the normal-close path ("lets a normally closed plain-text error event override response.completed") but not the truncated-boundary path.

Extending `finalize()` to also scan for an `event:` line (similar to how `push()` uses `event.event` as fallback) would close this gap. The conservative guard for truncated JSON events could still be applied via a `resolvedType ?? eventLine` pattern so that a truncated `event: response.completed\ndata: {"type":"respon` does not yield a false positive.

Reviews (2): Last reviewed commit: "fix: address review comments on codex te..." | Re-trigger Greptile

miraserver avatar Jun 05 '26 06:06 miraserver

Review Change Stack

📝 Walkthrough

Walkthrough

该 PR 为 Codex "Responses" SSE 流添加了终态追踪与最终化决策:实现按 SSE 边界解析终态/usage/service_tier/prompt_cache_key 的 tracker,forward-side 实时捕获并把终态注入 deferred finalization,收紧假200检测并调整失败早返回与 session 清理,附带大量单元测试覆盖终态与 abort 时序。

Changes

Codex 终态追踪与流最终化

Layer / File(s) Summary
终态追踪基础合约与类型
src/app/v1/_lib/proxy/response-handler.ts
定义 Codex Responses SSE 终态类型、事件解析与 tracker 实现,支持按 SSE 边界增量缓冲,提取终态、usage metrics、service tier 与 prompt cache key,并导出给测试使用的工厂。
Deferred Finalization 元信息扩展
src/app/v1/_lib/proxy/stream-finalization.ts
在 DeferredStreamingFinalization 中新增可选 providerType 字段;setDeferredStreamingFinalization 在写入时补齐缺失的 providerType(从 session.provider 推导)。
最终结算决策与终态判断
src/app/v1/_lib/proxy/response-handler.ts
在 finalizeDeferredStreamingFinalizationIfNeeded 中引入 forwardedCodexTerminalState 参数;当上游 2xx 且 providerType 为 codex 时使用该终态判定结算完成/成功,收紧“假 200”检测并调整 effectiveStatusCode 的映射(codex 终态非成功 → 内部 502)。
Codex 终态失败早返回与 Session 清理
src/app/v1/_lib/proxy/response-handler.ts
将 codex 终态非成功纳入 shouldClearSessionBindingOnFailure 条件,增加早返回分支:清理 session 绑定、记录专用日志、按需触发 circuit-breaker、向 provider 链追加 retry_failed 原因并直接返回。
流处理链路的实时终态捕获与结果提取
src/app/v1/_lib/proxy/response-handler.ts
在 handleStream 的 forward 流装载 tracker,逐块解码并 push SSE 文本,flush 时补齐并 finalize;finalizeStream 使用 forward tracker 的终态结果影响 deferred finalization,并优先从 tracker 获取 usageForCost/actualServiceTier 与 prompt_cache_key,回退为对 allContent 的解析结果。
测试基础设施与会话工厂参数化
tests/unit/proxy/response-handler-abort-listener-cleanup.test.ts
扩展测试导入与 mock(Codex tracker、session cache key),将 makeSession 重构为支持按 pathname/originalFormat/providerType/provider 参数化的工厂,新增 setDeferredMeta、Codex session 构造与流测试工具。
Codex 终态与 Abort 时序综合测试覆盖
tests/unit/proxy/response-handler-abort-listener-cleanup.test.ts
新增大量用例覆盖 response.completed/failed/error/incomplete、terminal usage/last-terminal-event 语义、客户端/上游 abort 时序与状态码、terminal 失败对 prompt_cache_key 的影响以及非 Codex 路径的互斥断言。

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • ding113
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.25% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed PR标题准确概括了核心变更:修复Codex完成流上的假499错误。标题简洁具体,清晰传达了主要问题。
Linked Issues check ✅ Passed PR完整解决了#1083的核心目标:通过独立捕获Codex终态信号,解决内部读取器与客户端断连时序导致的假499问题,确保成功上游响应被正确记录。
Out of Scope Changes check ✅ Passed 所有变更均在范围内:新增终态跟踪器、deferred meta字段、30个单元测试,全部聚焦于修复Codex响应的499误判,无无关改动。
Description check ✅ Passed 拉取请求描述详细阐述了修复的问题、解决方案、改动范围和测试覆盖,与变更集高度相关。

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • [ ] Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar Jun 05 '26 06:06 coderabbitai[bot]

The fix requires some work. User-generated response.failed errors can cause issues with provider shutdown. I'm not sure I can provide a reliable solution.

miraserver avatar Jun 06 '26 08:06 miraserver