Skip to content

fix(providers): recover conversations after encrypted reasoning stream rejection - #129886

Merged
steipete merged 2 commits into
mainfrom
codex/issue-124465
Aug 26, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/issue-124465

Conversation

@steipete

@steipete steipete commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #124465
Related: #95493, #95587, #97926

What Problem This Solves

Fixes an issue where users chatting with GitHub Copilot could permanently lose a conversation after replayed encrypted reasoning was rejected: the assistant repeatedly failed with LLM request failed until the session was reset. The same failure could affect another Responses-compatible provider when its rejection arrived after streaming had already started.

Why This Change Was Made

The OpenAI SDK can defer a provider error until the Responses stream is iterated, and those streamed SDK errors do not necessarily retain their HTTP status or structured error code. OpenClaw's existing encrypted-replay recovery wrapped only initial stream creation, so both the deferred SDK exception and normal response.failed / error stream events escaped recovery.

Move recovery ownership across the complete SDK create-and-drain lifecycle used by both Responses transport callers. Recognize narrowly bounded encrypted-content verification/decryption failures, retry only before thinking, text, or tool output has been committed, preserve the existing reasoning-then-compaction recovery stages, re-run the correct response hook for replacement HTTP responses, and keep one visible assistant lifecycle. Aborted requests and failed response hooks never retry.

The existing Copilot plugin remains responsible for proactively stripping connection-bound reasoning before dispatch. Its producer-side mitigation and this shared transport-side recovery are complementary; this change does not recursively remove valid encrypted compaction state or change provider configuration.

Production delta: +126/-49 (net +77). The additional production code is necessary to own deferred single-consumption stream failures, provider response/continuation lifecycles, and the pre-output/abort safety boundary; the existing creation-only retry cannot express that capability. Regression tests: +332/-0.

User Impact

Copilot and other Responses-compatible conversations recover automatically from a rejected stale reasoning item instead of repeatedly resending poisoned history. Valid compaction remains available, existing streamed output is never duplicated, and operators do not need to reset the conversation.

Evidence

  • Before the fix, the real shared lifecycle regression failed for iterator-thrown errors, response.failed, and error events: each sent only one poisoned request instead of the required sanitized recovery request.

  • Direct dependency proof: installed OpenAI SDK 7.5.0 node_modules/openai/src/core/streaming.ts:58-87 consumes SSE only during async iteration and constructs new APIError(undefined, data.error, undefined, response.headers) at lines 83-85. A real SDK Stream over a real Response containing an SSE error yielded APIError with absent status and code, confirming the deferred shape independently of mocks.

  • Additional independent review reproduced two real edge cases before repair: a nested status-only response.failed did not recover, and an encrypted-looking response-hook failure incorrectly attempted a second request.

  • After the fix, seven focused Responses transport and agent-side replay suites pass 261 tests, including immediate HTTP 400, deferred SDK errors without status/code, flat/nested error events, unrelated OAuth-sidecar/HTTP-500 negative cases, the existing xAI rejection contract, exactly one start/done lifecycle, no retry after thinking/text/tool output, aborted hooks, retained encrypted compaction, prompt observation, replacement-response headers, continuation state, and WebSocket siblings:

    node scripts/run-vitest.mjs \
      src/agents/openai-transport-stream.replay-and-tools.test.ts \
      packages/ai/src/providers/openai-responses-shared.test.ts \
      packages/ai/src/transports/openai-responses-prompt-observer.test.ts \
      packages/ai/src/transports/openai-responses-websocket-client.test.ts \
      packages/ai/src/transports/openai-responses-compaction-replay.test.ts \
      packages/ai/src/transports/openai-responses-transport.response-hook.test.ts \
      packages/ai/src/transports/openai-responses-client.continuation.test.ts
  • A genuine authenticated GitHub Copilot request from the patched checkout completed through the documented disposable CLI flow using github-copilot/gpt-5.4; the real /responses endpoint returned HTTP 200 and the requested assistant response.

  • A deliberate live 400-to-200 recovery cannot be safely forced through the normal disposable CLI: the shipped Copilot plugin removes stale reasoning ciphertext before dispatch, the disposable command supports only one turn, and inducing the original state would require bypassing the production sanitizer, altering an operator-owned session, or invalidating credentials. The maintainer accepts this concrete live-fault-proof limitation; genuine authenticated Copilot success, direct SDK source/real-SSE fault proof, and real exported production-boundary recovery regressions are the strongest safe evidence. No live fault recovery is claimed.

  • The separate handwritten ChatGPT SSE transport does not serve Copilot and remains a named sibling follow-up; its WebSocket path already owns complete-stream semantic recovery.

  • Structured Codex autoreview: no accepted/actionable findings. Independently source-reviewed across the SDK contract, both production caller paths, response hooks, continuation state, compaction, and cancellation.

Reported by @shanselman. AI-assisted implementation; no prior contributor code was copied.

@clawsweeper

clawsweeper Bot commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added size: M maintainer Maintainer-authored PR labels Aug 26, 2026
@steipete
steipete marked this pull request as ready for review August 26, 2026 05:14
@clawsweeper

clawsweeper Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed August 26, 2026, 2:50 AM ET / 06:50 UTC.

ClawSweeper review

What this changes

Extends Responses transport recovery so encrypted-reasoning rejections raised during stream iteration or failure events retry sanitized history before assistant output begins.

Regression provenance

Possible regression — probable (reproduction; reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 6 items remain

Keep open: the new in-stream recovery can bypass the replacement stream’s first-event deadline and can persist compaction suppression before that replacement stream succeeds.

Priority: P1
Reviewed head: a2aad98f4ed380eebd6e6deb42da85a597d65978

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch has strong targeted intent and evidence, but two P1 lifecycle regressions prevent merge readiness.
Proof confidence 🌊 off-meta tidepool Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; its body documents authenticated Copilot success but not a safely forced live recovery fault.
Patch quality 🦐 gold shrimp (3/6) 2 actionable review findings remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; its body documents authenticated Copilot success but not a safely forced live recovery fault.
Evidence reviewed 5 items Replacement retry bypasses the first-event deadline: The new recursive recovery consumes a replacement stream inside the already-started outer iterator; the outer first-event timer is cleared after the failed attempt’s first event.
Compaction suppression is committed before stream success: A compaction-stripped attempt commits its suppression immediately after HTTP headers, although the returned async stream can still fail before producing assistant output.
Existing tests leave both new failure modes uncovered: The added recovery test checks successful iterator and failure-event recovery, while the hook timeout test covers only the initial response; the established compaction test covers a second HTTP failure rather than a post-header iterator failure.
Findings 2 actionable findings [P1] Reset the first-event deadline for replacement streams
[P1] Defer compaction suppression until replacement drain succeeds
Security None None.

Live Verification

Command: node scripts/run-vitest.mjs packages/ai/src/transports/openai-responses-prompt-observer.test.ts

Result: PASS (completed)

[test] starting test/vitest/vitest.unit.config.ts

 RUN  v4.1.10 /tmp/clawsweeper-live-proof-129886-eyug54/target

 ✓  unit  packages/ai/src/transports/openai-responses-prompt-observer.test.ts (17 tests) 162ms

 Test Files  1 passed (1)
      Tests  17 passed (17)
   Start at  06:51:36
   Duration  2.37s (transform 1.62s, setup 971ms, import 884ms, tests 162ms, environment 0ms)

[test] passed 1 Vitest shard in 13.77s
[test] starting test/vitest/vitest.unit.config.ts

 RUN  v4.1.10 /tmp/clawsweeper-live-proof-129886-eyug54/target

 ✓  unit  packages/ai/src/transports/openai-responses-prompt-observer.test.ts (17 tests) 129ms

 Test Files  1 passed (1)
      Tests  17 passed (17)
   Start at  06:51:50
   Duration  1.28s (transform 527ms, setup 449ms, import 478ms, tests 129ms, environment 0ms)

[test] passed 1 Vitest shard in 12.56s

Assertions:

  • PASS expect_output: Test Files

How this fits together

Responses-compatible providers send conversation history to a shared transport, which consumes provider stream events into an assistant response. The recovery path can remove rejected encrypted replay state and issue one replacement request while preserving hooks and conversation state.

flowchart LR
A[Conversation history] --> B[Responses request]
B --> C[Provider stream]
C --> D{Encrypted replay rejection}
D -->|Before output| E[Sanitize replay state]
E --> F[Replacement stream]
F --> G[Assistant lifecycle]
D -->|Other result| G
Loading

Before merge

  • Reset the first-event deadline for replacement streams (P1) - The outer timeout is cleared by the failed attempt’s response.created, then this recursive retry reuses the same abort signal while its replacement response hook waits without a new deadline. A stalled replacement hook can therefore hang a request that configured firstEventTimeoutMs.
  • Defer compaction suppression until replacement drain succeeds (P1) - This new recursive path can enter a compaction-stripped attempt whose helper commits suppression immediately after headers. If its async stream then throws before output, later replay has already been suppressed despite the failed recovery; commit only after a successful terminal response.
  • Resolve merge risk (P1) - Merging before correction can leave a replacement provider response waiting indefinitely after the original stream has emitted its first event.
  • Resolve merge risk (P1) - Merging can suppress a rejected compaction after a replacement stream later fails, degrading the next conversation turn’s replay context.
  • Resolve merge risk (P1) - The installed OpenAI 7.5 stream contract and exact current-main merge result could not be independently inspected from this partial checkout.
  • Complete next step (P2) - The protected maintainer PR has two concrete lifecycle defects but should remain under maintainer handling rather than enter an automated repair lane.

Findings

  • [P1] Reset the first-event deadline for replacement streams — packages/ai/src/transports/openai-responses-replay-internal.ts:273-279
  • [P1] Defer compaction suppression until replacement drain succeeds — packages/ai/src/transports/openai-responses-replay-internal.ts:273-279
Agent review details

Security

None.

PR surface

Source +77, Tests +332. Total +409 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 3 126 49 +77
Tests 2 332 0 +332
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 458 49 +409

Review metrics

Metric Value Why it matters
Production versus test delta production +77 net, tests +332 The added shared retry lifecycle spans two transport callers, so the two uncovered failure boundaries are material despite substantial test growth.

Stored data model

Persistent data-model change detected: vector/embedding metadata: packages/ai/src/providers/openai-responses-shared.test.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #124465
Summary: This PR is the active candidate fix for the open issue’s remaining encrypted-reasoning stream recovery gap.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Repair the replacement-stream lifecycle (recommended)
    Move first-event timeout and successful-compaction commit handling to each retry attempt, then add failure-path regressions for both Responses callers.
  2. Pause this recovery expansion
    Hold the PR if the lifecycle repair or direct OpenAI SDK contract review cannot be completed on the current head.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Reset first-event timeout per replacement stream, defer compaction suppression until successful terminal recovery, and add regression tests for stalled replacement hooks and post-header drain failure.

Technical review

Best possible solution:

Make timeout and compaction-commit ownership attempt-scoped: reset the first-event boundary for every replacement response, and persist suppression only after the stripped recovery reaches a successful terminal response.

Do we have a high-confidence way to reproduce the issue?

Yes—source reproducible: emit a first stream event then an encrypted rejection, and make the replacement response hook never settle; separately, let a compaction-stripped replacement iterator fail after headers but before output.

Is this the best way to solve the issue?

No—the complete-stream retry needs attempt-scoped timeout and commit semantics so a failed replacement cannot bypass its timeout or durably suppress replay state.

Full review comments:

  • [P1] Reset the first-event deadline for replacement streams — packages/ai/src/transports/openai-responses-replay-internal.ts:273-279
    The outer timeout is cleared by the failed attempt’s response.created, then this recursive retry reuses the same abort signal while its replacement response hook waits without a new deadline. A stalled replacement hook can therefore hang a request that configured firstEventTimeoutMs.
    Confidence: 0.96
  • [P1] Defer compaction suppression until replacement drain succeeds — packages/ai/src/transports/openai-responses-replay-internal.ts:273-279
    This new recursive path can enter a compaction-stripped attempt whose helper commits suppression immediately after headers. If its async stream then throws before output, later replay has already been suppressed despite the failed recovery; commit only after a successful terminal response.
    Confidence: 0.94

Overall correctness: patch is incorrect
Overall confidence: 0.95

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against fc64c5704a77.

Labels

Label changes:

  • add merge-risk: 🚨 availability: A replacement response hook can wait past the configured first-event deadline after the failed stream already emitted an event.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; its body documents authenticated Copilot success but not a safely forced live recovery fault.
  • remove status: 👀 ready for maintainer look: Current PR status label is status: ⏳ waiting on author.

Label justifications:

  • P1: The patch can leave an active provider conversation stalled or with degraded next-turn replay after a failed automatic recovery.
  • merge-risk: 🚨 availability: A replacement response hook can wait past the configured first-event deadline after the failed stream already emitted an event.
  • merge-risk: 🚨 session-state: The patch can persist compaction suppression before the replacement stream succeeds, changing later replay context after a failed recovery.
  • merge-risk: 🚨 auth-provider: The change reissues provider requests based on streamed OpenAI Responses failure shapes whose installed SDK contract still needs direct confirmation.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; its body documents authenticated Copilot success but not a safely forced live recovery fault.

Evidence

What I checked:

Likely related people:

  • rvdlaar: The merged xAI replay-rejection work established the neighboring encrypted-content classifier boundary that this PR extends. (role: adjacent feature contributor; confidence: medium; commits: fc507c70c5e3; files: packages/ai/src/transports/openai-responses-replay-internal.ts)
  • steipete: Available local blame attributes the active retry implementation to the current PR head; deeper feature history was unavailable in this partial checkout. (role: current recovery-path contributor; confidence: medium; commits: a2aad98f4ed3, 423bee549e36; files: packages/ai/src/transports/openai-responses-replay-internal.ts, packages/ai/src/providers/openai-responses-shared.ts, packages/ai/src/transports/openai-responses-client.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Reset the first-event timeout boundary for every replacement stream and prove a stalled replacement hook aborts.
  • Delay compaction suppression until successful terminal recovery and prove a post-header drain failure leaves replay available.
  • Recheck the installed OpenAI 7.5 streaming contract on a current-main merge result.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (3 earlier review cycles)
  • reviewed 2026-08-26T05:13:40.980Z sha 423bee5 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-26T05:56:26.487Z sha 423bee5 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-26T06:18:56.302Z sha a2aad98 :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 26, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 26, 2026
@steipete
steipete merged commit 1ff98e5 into main Aug 26, 2026
133 checks passed
@steipete
steipete deleted the codex/issue-124465 branch August 26, 2026 07:20
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

maintainer Maintainer-authored PR merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: L status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Responses recovery misses code-less Copilot encrypted-content 400 and retries poisoned history

1 participant