Skip to content

fix: recover OpenAI sessions after compaction item conflicts - #198357

Merged
steipete merged 3 commits into
mainfrom
steipete/perf-micro-responses-item-conflict-wedges-sessions-20260919
Nov 13, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/perf-micro-responses-item-conflict-wedges-sessions-20260919

Conversation

@steipete

@steipete steipete commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes OpenAI conversations that permanently reject every turn with item_conflict after replaying a compaction checkpoint.

User Impact

Affected conversations can resume on their next turn after upgrading, without editing or discarding their saved history. Any remaining item conflict gives recovery guidance instead of a generic failure.

Why This Change Was Made

The real Responses API accepts a compacted window with store:true once, then rejects replay of that checkpoint. Removing all item IDs still fails; replaying the unchanged checkpoint with store:false succeeds, including after it was stored. The shared payload policy now selects stateless replay for compaction input on the native public OpenAI endpoint.

Checkpoint contents remain intact. Ordinary requests keep stored HTTP continuation; compacted requests replay their bounded window instead of using stored previous_response_id. Azure and custom endpoint policies remain unchanged. No new configuration, cache, retry wrapper, database change, or migration is required.

Evidence

The policy regression fails on the original code. Live official API probes distinguish the conflict from ordinary message/reasoning/tool ID replay and confirm that stripping IDs cannot fix it. A live test deliberately wedges a synthetic checkpoint, then runs the real agent loop for four successful turns across two reloads of unchanged saved state. Each turn makes one HTTP request and correctly recalls a random marker retained only in compacted tool history.

Focused policy, failure-copy, compaction, continuation and prompt-prefix tests; Chromium failure-notice tests (5) and terminal-reload UI E2E tests (3). Codex autoreview: no actionable P0–P2 findings. The changed-file check completed; proof-harness type errors were corrected and both affected typechecks now pass. CI on the initial head exposed five stale admission/replay golden assertions; the only corrected fixture field is store:false, matching the live-proven contract. The affected suite now passes all 17 tests, and the follow-up independent review is clean. Exact-head CI 43466589308 passed on 15bee219b67f72fc4642dd3573eb8513d57d2a7a; ClawSweeper reviewed the same head with zero findings and zero open items.

CI run 43462361673 subsequently found a real-Gateway Home test incorrectly assigned to the ordinary parallel UI lane: Gateway startup took 157.7 seconds against the test’s 120-second limit. #196902 introduced the test without its canonical real-Gateway registration. This PR adds that inventory entry and a red/green routing regression proving serial local ownership, ordinary-lane exclusion, and exactly-once dedicated Gateway coverage. The unchanged behavior test passes in the corrected serial project (27.097 seconds); timeouts and behavior assertions remain intact. Independent Codex review of this repair is clean. No inherited-CI bypass is used.

pnpm check:changed exposed an unrelated script unused-export regression: #198274 removed the final importer of RELEASE_VALIDATION_WAIVERS in b9f1e62e00d8. The same unused-export failure reproduces on clean exact parent af10e5594d38; this is a main regression, not a passing check.

The committed policy benchmark uses a synthetic 2,000-item active history, five A/A controls and five interleaved A/B pairs. Median wall/CPU µs per request: compacted 0.0058/0.0188 → 0.1155/0.1325; ordinary 0.0058/0.0181 → 5.1141/5.1232. Added sampled allocation is approximately 56 bytes/request. A/A wall controls are 0.0056–0.0057 µs. The owner performs no database or workspace reads; this is a bounded request-input scan, not a session-inventory scan or an end-to-end speedup claim.

Runtime production delta: +34 lines for endpoint-scoped storage policy and shared recovery copy. The additional benchmark and live proof are separate tooling/tests; no state machinery was introduced.

Redacted execution evidence

Observed from synthetic requests to the real public OpenAI Responses API:

compact-first-replay          HTTP 200  completed
compact-exact-repeat         HTTP 200  SSE item_conflict / invalid_request_error / input
compact-without-message-ids   HTTP 200  SSE item_conflict / invalid_request_error / input
compact-without-checkpoint-id HTTP 200  SSE item_conflict / invalid_request_error / input
compact-all-idless            HTTP 200  SSE item_conflict / invalid_request_error / input

Terminal excerpts from the real agent/transport and shared failure-copy runs:

✓ src/agents/openai-responses-compaction.live.test.ts > recovers a stored compaction checkpoint on the next agent turn and after reload 15120ms
Test Files  1 passed (1)
Tests  1 passed (1)

✓ gives compacted-history recovery guidance for structured and terminal item conflicts
Test Files  1 passed (1)
Tests  27 passed (27)

The committed live test asserts the initial stored success, subsequent item_conflict, unchanged serialized checkpoint across reloads, four successful real agent turns, exactly one HTTP request per turn, store:false, no previous_response_id, and correct recall of compacted tool memory. Run it with pnpm test:live src/agents/openai-responses-compaction.live.test.ts --maxWorkers=1 using an approved OpenAI API key. Request IDs, checkpoint bytes and credentials are deliberately omitted from this public excerpt.

Replay native OpenAI compaction checkpoints without provider storage so existing sessions recover on their next turn without transcript edits. Preserve ordinary stored continuation and add shared actionable item_conflict guidance. Live proof covers poisoned checkpoint replay, consecutive agent turns, reload, and retained tool memory.
@clawsweeper

clawsweeper Bot commented Nov 13, 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 docs Improvements or additions to documentation scripts Repository scripts agents Agent runtime and tooling size: M labels Nov 13, 2026
@steipete
steipete marked this pull request as ready for review November 13, 2026 16:09
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-13T16:51:49.909101Z 15bee21 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper review

Please review head 804fe54. Focus on native Responses compaction replay, recovery of an already-stored checkpoint without transcript edits, preservation of ordinary HTTP continuation, and live/saved item_conflict guidance. The PR includes live API reproduction and agent reload proof; stripping item IDs does not repair this failure.

@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 13, 2026
@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR makes native OpenAI compaction replay stateless, adds item-conflict recovery guidance, and corrects Home E2E test routing.

Example: A conversation reuses the saved compaction checkpoint cmp_checkpoint on api.openai.com.

  • Before: The checkpoint is resent with store:true and subsequent requests fail with item_conflict.
  • After: The unchanged checkpoint is replayed with store:false, allowing the conversation to continue.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused, correct repair with recorded live-service coverage through an in-process agent composition; a shipped CLI or Gateway recovery run is not shown.
Proof confidence 🦐 gold shrimp (3/6) Sufficient (terminal): The supplied live API trace and inspected live-agent test exercise the production payload policy and real Responses client against an already-stored checkpoint, then recover across repeated turns and serialized-state reloads; the downloaded Daybreak screenshots are unrelated and were excluded.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: An OpenAI conversation can become unusable after its compaction checkpoint has been stored once.
Reason: Automatic recovery preserves the user's conversation, and the maintainer-authored direction keeps the change within existing policy and failure-rendering owners.

Merge readiness

✅ Ready for maintainer review

This PR addresses a concrete OpenAI session failure that remains on main. No actionable correctness or security findings were identified; exact-head CI is still pending.

Priority: P1
Reviewed head: 15bee219b67f72fc4642dd3573eb8513d57d2a7a

Before merge

None.

Findings

None.

Agent review details

How this fits together

The shared Responses payload policy transforms assembled conversation input into provider requests; the transport handles continuation, and shared failure rendering supplies live and saved-history guidance.

flowchart TD
  A[Saved conversation checkpoint] --> B[Agent request assembly]
  B --> C[Shared payload policy]
  C --> D[Responses transport]
  D --> E[OpenAI Responses API]
  E --> F[Assistant result or failure guidance]
Loading

Technical review

Best possible solution:

Keep the endpoint-scoped repair in the existing payload-policy owner so affected checkpoints recover without rewriting saved history.

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

The unchanged main policy sends stored compaction replay, and the supplied live API evidence records its repeatable item_conflict failure; this read-only review did not execute target code.

Is this the best way to solve the issue?

The repair changes the existing endpoint policy at request construction, preserves checkpoint bytes and custom-endpoint contracts, and avoids an unnecessary retry or migration layer.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 68542b21d0d2.

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 575467a adds packages/ai/src/transports/openai-responses-payload-policy.ts:387 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 575467aa5834; files: packages/ai/src/transports/openai-responses-payload-policy.ts)
  • Markus Hartung: Raw commit cc26392 adds packages/ai/src/transports/openai-responses-payload-policy.ts:323 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: cc2639283d95; files: packages/ai/src/transports/openai-responses-payload-policy.ts)
  • Vincent Koc: Raw commit cc1881a adds src/agents/openai-responses-payload-policy.ts:121 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: cc1881a83846; files: src/agents/openai-responses-payload-policy.ts)

PR surface

Source +34, Tests +235, Docs +8, Other +111. Total +388 across 10 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 2 36 2 +34
Tests 6 236 1 +235
Docs 1 11 3 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 1 111 0 +111
Total 10 394 6 +388

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Runtime versus regression coverage Runtime +36/-2 lines; tests and support +235/-1 lines The small runtime repair stays within existing owners; most test growth provides opt-in live checkpoint recovery and reload coverage.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.

Label justifications:

  • P1: Affected existing OpenAI conversations repeatedly reject turns, breaking an active agent workflow.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (2 earlier review cycles)
  • reviewed 2026-11-13T16:16:12.247Z sha 804fe54 :: needs maintainer review before merge. :: none
  • reviewed 2026-11-13T16:33:32.528Z sha cde67c8 :: needs maintainer review before merge. :: none

Reviewed November 13, 2026, 11:54 AM ET / 16:54 UTC (Revision 3).

@steipete

steipete commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Please review final head cde67c8. The previous review reported zero findings/open items. This follow-up changes only the shared wire fixture at src/agents/embedded-agent-runner/run/preemptive-compaction.replay.test.ts:204 from store:true to store:false, matching the live-proven compaction policy. Its five failing assertions reproduced locally; all 17 tests now pass without changing input-byte, pressure or conversion-count assertions. Independent Codex review of this correction is clean.

The PR body now includes sanitized execution excerpts for the stored-checkpoint conflict, failed ID-stripping variants, real-agent recovery after reload, and live/saved failure guidance, addressing the previous review's proof guidance.

@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 13, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 13, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

The reviewed Responses fix is unchanged. Follow-up head 15bee21 repairs the CI-exposed Home test lane assignment: test/vitest/vitest.ui-paths.mjs registers the real-Gateway test with its existing serial/prebuilt owner, and test/scripts/ci-ui-e2e-ownership.test-support.ts verifies serial ownership, exclusion from ordinary shards, and exactly-once dedicated coverage. The routing regression is red before / green after; the actual Home behavior test passes in the serial project (27.097s). No timeouts or behavior assertions changed. Independent Codex review is clean, and the PR body now records this CI repair.

The latest review had zero findings and zero open items. Please review the new final head.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 13, 2026
@steipete
steipete merged commit 58c1549 into main Nov 13, 2026
153 of 156 checks passed
@steipete
steipete deleted the steipete/perf-micro-responses-item-conflict-wedges-sessions-20260919 branch November 13, 2026 17:09
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 14, 2026
…w#198357)

* fix: recover OpenAI sessions after compaction item conflicts

Replay native OpenAI compaction checkpoints without provider storage so existing sessions recover on their next turn without transcript edits. Preserve ordinary stored continuation and add shared actionable item_conflict guidance. Live proof covers poisoned checkpoint replay, consecutive agent turns, reload, and retained tool memory.

* test: align compacted replay wire storage contract

* test: route read-only Home through the real Gateway lane
RomneyDa pushed a commit that referenced this pull request Nov 14, 2026
(cherry picked from commit 58c1549)

Release adaptation: preserve the older failure-copy signature and test helper names. Include the complete payload policy, actionable recovery copy, docs, and focused regressions. Existing continuation owner already sends the full request without previous_response_id when store is false. Omit absent future-main Home UI lane repair and golden fixture; omit optional performance and credentialed live harnesses. No storage or transcript changes.

Closure: later same-production-path commits and PR mentions are absent through 7bccde6. Later Home dedup #198391 and handoff/model/Telegram documentation edits are not applicable. Existing policy instruction tests and continuation owners retain their contracts.

Proof: four changed TypeScript files parse; git diff --check passes. Targeted Vitest cannot start because dependencies are unavailable. Native Node policy probe also cannot load a pre-existing parameter-property module in strip-only mode; no behavioral pass claimed. Runtime/live, typecheck, and formatter qualification remain with release lane.

Co-authored-by: RomneyDa <[email protected]>

Co-authored-by: vincentkoc <[email protected]>
(cherry picked from commit eb066410a973a7f2ea50a244d6ee6ba9bd3205aa)
obviyus added a commit that referenced this pull request Nov 16, 2026
…#200163)

## What Problem This Solves

Long OpenAI Responses chats fail with "The AI service could not recover saved conversation state (item_conflict)". Subagent completions sent to those chats fail with the same error.

On the shared team Gateway, 4 to 15 real conflicts happened each day. Every conflict on November 16 had the outcome `deferred`, so each one failed a visible turn or a completion delivery. The reported rate jump on November 16 (28, then 82 per hour) was not new conflicts. After a deferred repair, `outcome=recovered` is logged on every later request in that chat: one run logged it 26 times. That day there were 4 real conflicts.

## Root cause

OpenAI item IDs show if their response was stored. When a turn is sent with `store:false`, its reasoning item IDs name no stored record. For example, every turn that carries a compaction checkpoint is sent with `store:false` (#198357).

The replay converter sent those reasoning items again with both `id` and `encrypted_content` whenever the current request had `store:true` (`openai-responses-replay-messages-internal.ts`, reasoning branch of `convertMessage`). The first stored request records that ciphertext under its ID. The next stored request that sends it again fails with `item_conflict` ("An input item conflicts with an existing record."). The server returns this error only after the whole output has streamed. In-turn recovery then defers the repair to the next request, so the current turn fails.

Session history from the affected team chats agrees (only structural fields were read, no message content). Each chat that failed had reasoning from unstored responses, followed by stored full-history requests:
- One chat had 45 unstored reasoning items after a compact-endpoint checkpoint. Its next stored turn failed after 100 seconds of output.
- In two other chats, stored and unstored responses alternate.

The fix for function-call argument bytes (#200020) does not cover this. The real API accepts a changed `function_call` under the same ID.

## Fix

On the native OpenAI Responses endpoint, reasoning that has encrypted content is replayed without its ID. Ciphertext is self-contained. Message and function-call IDs need their reasoning ID, so they are omitted with it. This is the shape that stateless replay already used. Reasoning without ciphertext keeps its ID, as before. Microsoft Foundry and other routes that opt in to item IDs are unchanged: Foundry checks ciphertext against its original ID (#91033).

Production code: net -1 line. No config, schema or stored-data change. Existing transcripts are fixed when the next request is built.

## Evidence

Real OpenAI API probes (`gpt-6.1-sol`):

| Replayed input | Stored replay 1 | Stored replay 2 |
| --- | --- | --- |
| reasoning from a `store:true` response, with ID | ok | ok |
| reasoning from a `store:false` response, with ID | ok | `item_conflict` after output |
| same reasoning, ciphertext only (no ID) | ok | ok (also a third time) |
| message or function call from an unstored response, with ID | ok | ok |

`cached_tokens` is the same with and without the reasoning ID: 5327 of 5362 tokens in both cases.

Real OpenAI route through OpenClaw's Responses transport. One `store:false` turn is followed by two stored turns, cold replay each time, 3 trials per arm:
- base `fcf29c4`: the third turn fails 3 out of 3 times with `item_conflict` "An input item conflicts with an existing record.", and the log shows `item_conflict_recovery outcome=deferred`. This is the production failure.
- this PR: 3 out of 3 trials pass, with no conflict.

Real scratch Gateway with `gpt-6.1-sol` and `gpt-6-astra`. The journey: a turn, a compact-endpoint checkpoint, a `store:false` turn, a model switch with server compaction, then three stored turns. Both arms finish every turn. `cacheRead` for the last three turns is 22614/23293/23516 on base and 22620/23299/23522 on this PR. I did not find a Gateway-only path on current `main` that drops a checkpoint and also keeps the reasoning ciphertext. The transport run above is the reproduction of the failure.

Regression test: `replays reasoning from an unstored response without a conflicting ID`, over SSE and WebSocket. The loopback server follows the real store rule: it records ciphertext under its ID, and it requires a stored message ID to come with its reasoning ID. The test fails on base with `item_conflict` and passes here. It also fails if message IDs are kept without their reasoning ID. The conflict triggers of the existing item-conflict and cold-reopen recovery tests used function-call IDs, which are no longer sent. They now use the identity that their repair removes, so recovery stays covered. Focused transport, provider and agent replay suites pass, and so do `tsgo:core` and `check:test-types`.

Merge danger: two-way door. It only changes the request projection; no stored state is written, and a revert restores the old wire shape. Blast radius: native OpenAI Responses requests only. They no longer send reasoning, message or call IDs next to encrypted reasoning. Azure, Copilot, Foundry and custom routes keep their current wire shape.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 17, 2026
…openclaw#200163)

## What Problem This Solves

Long OpenAI Responses chats fail with "The AI service could not recover saved conversation state (item_conflict)". Subagent completions sent to those chats fail with the same error.

On the shared team Gateway, 4 to 15 real conflicts happened each day. Every conflict on November 16 had the outcome `deferred`, so each one failed a visible turn or a completion delivery. The reported rate jump on November 16 (28, then 82 per hour) was not new conflicts. After a deferred repair, `outcome=recovered` is logged on every later request in that chat: one run logged it 26 times. That day there were 4 real conflicts.

## Root cause

OpenAI item IDs show if their response was stored. When a turn is sent with `store:false`, its reasoning item IDs name no stored record. For example, every turn that carries a compaction checkpoint is sent with `store:false` (openclaw#198357).

The replay converter sent those reasoning items again with both `id` and `encrypted_content` whenever the current request had `store:true` (`openai-responses-replay-messages-internal.ts`, reasoning branch of `convertMessage`). The first stored request records that ciphertext under its ID. The next stored request that sends it again fails with `item_conflict` ("An input item conflicts with an existing record."). The server returns this error only after the whole output has streamed. In-turn recovery then defers the repair to the next request, so the current turn fails.

Session history from the affected team chats agrees (only structural fields were read, no message content). Each chat that failed had reasoning from unstored responses, followed by stored full-history requests:
- One chat had 45 unstored reasoning items after a compact-endpoint checkpoint. Its next stored turn failed after 100 seconds of output.
- In two other chats, stored and unstored responses alternate.

The fix for function-call argument bytes (openclaw#200020) does not cover this. The real API accepts a changed `function_call` under the same ID.

## Fix

On the native OpenAI Responses endpoint, reasoning that has encrypted content is replayed without its ID. Ciphertext is self-contained. Message and function-call IDs need their reasoning ID, so they are omitted with it. This is the shape that stateless replay already used. Reasoning without ciphertext keeps its ID, as before. Microsoft Foundry and other routes that opt in to item IDs are unchanged: Foundry checks ciphertext against its original ID (openclaw#91033).

Production code: net -1 line. No config, schema or stored-data change. Existing transcripts are fixed when the next request is built.

## Evidence

Real OpenAI API probes (`gpt-6.1-sol`):

| Replayed input | Stored replay 1 | Stored replay 2 |
| --- | --- | --- |
| reasoning from a `store:true` response, with ID | ok | ok |
| reasoning from a `store:false` response, with ID | ok | `item_conflict` after output |
| same reasoning, ciphertext only (no ID) | ok | ok (also a third time) |
| message or function call from an unstored response, with ID | ok | ok |

`cached_tokens` is the same with and without the reasoning ID: 5327 of 5362 tokens in both cases.

Real OpenAI route through OpenClaw's Responses transport. One `store:false` turn is followed by two stored turns, cold replay each time, 3 trials per arm:
- base `9977d5c`: the third turn fails 3 out of 3 times with `item_conflict` "An input item conflicts with an existing record.", and the log shows `item_conflict_recovery outcome=deferred`. This is the production failure.
- this PR: 3 out of 3 trials pass, with no conflict.

Real scratch Gateway with `gpt-6.1-sol` and `gpt-6-astra`. The journey: a turn, a compact-endpoint checkpoint, a `store:false` turn, a model switch with server compaction, then three stored turns. Both arms finish every turn. `cacheRead` for the last three turns is 22614/23293/23516 on base and 22620/23299/23522 on this PR. I did not find a Gateway-only path on current `main` that drops a checkpoint and also keeps the reasoning ciphertext. The transport run above is the reproduction of the failure.

Regression test: `replays reasoning from an unstored response without a conflicting ID`, over SSE and WebSocket. The loopback server follows the real store rule: it records ciphertext under its ID, and it requires a stored message ID to come with its reasoning ID. The test fails on base with `item_conflict` and passes here. It also fails if message IDs are kept without their reasoning ID. The conflict triggers of the existing item-conflict and cold-reopen recovery tests used function-call IDs, which are no longer sent. They now use the identity that their repair removes, so recovery stays covered. Focused transport, provider and agent replay suites pass, and so do `tsgo:core` and `check:test-types`.

Merge danger: two-way door. It only changes the request projection; no stored state is written, and a revert restores the old wire shape. Blast radius: native OpenAI Responses requests only. They no longer send reasoning, message or call IDs next to encrypted reasoning. Azure, Copilot, Foundry and custom routes keep their current wire shape.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. docs Improvements or additions to documentation P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant