Skip to content

fix: recover saved Responses state and completion delivery after restart - #200020

Merged
steipete merged 8 commits into
mainfrom
steipete/fix-restart-announce-item-conflict
Nov 16, 2026
Merged

steipete merged 8 commits into
mainfrom
steipete/fix-restart-announce-item-conflict

Conversation

@steipete

@steipete steipete commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Related: #199896, #199757

What Problem This Solves

Fixes: saved OpenAI Responses state can fail on the first turn after restart and leave a completed sub-agent result waiting for the requester's next message.

User Impact

Pre-output state conflicts recover within the turn, and a deferred requester-settle repair gets an automatic bounded delivery retry. Newly completed tool calls retain their original argument bytes across restart. Existing transcripts remain supported through the existing one-shot repair; no configuration, database schema migration, or user action is required.

Why This Change Was Made

A failed response can contain a text/reasoning snapshot that the stream parser never emits. Counting that snapshot as emitted output incorrectly selects deferred recovery. Real items, deltas, and possible tool effects still prevent unsafe replay.

Cold reconstruction also reserialized completed function arguments while retaining the provider's immutable item ID. The transcript now carries the original arguments when serialization changes them, and reuses them only for an unchanged call with matching provider, API, and model. Warm continuation retains the legacy normalized comparison. Terminal results also retain the provider error code: a failed announce can return meta.error instead of throwing. Requester-settle recognizes both forms of typed saved-state conflict and keeps its existing three-attempt wake budget (30-second and two-minute retry delays), rather than completing the obligation after a retryable failure.

Evidence

Team reported build 25c97908 (includes #199896): after the November 15 restart at 22:41:52 PST, a 22:43:05 requester-settle request logged item_conflict_recovery outcome=deferred, and a completed child became delivery-failed/retryable. The output flag is request-local and announce uses the normal Responses transport. The precise sanitized wire event sequence remains unavailable: the failed-snapshot case is a reproduced matching failure route, not a claimed exact trace of that Team request. No Team state was changed or copied.

  • Exact parent c3413be17dd0c7f3007c52d34d036daeb8fc6b70: four transport regressions fail (SSE/WebSocket failed snapshots; whitespace/unsafe-integer argument replay), and two requester-settle regressions fail because the wake is completed after the first retryable conflict.

  • A real Gateway upgrade from official stable 2026.11.4 preserves existing SQLite tool history and recovers a pre-output failed snapshot in-turn. A stricter real-text-output announce experiment exposed the returned-error gap: it deferred but did not retry within 90 seconds. The terminal-code regression and both returned-result dispatch cases fail on 4520fa6; the repair passes all 242 focused terminal/delivery tests. The repaired real Gateway proof passes: the first announce emits text and logs deferred at 02:04:03.607 PST; a distinct :retry-1 run logs recovered at 02:05:02.966 and delivers the child result without another user message. The product test passes in 114.7 seconds (build/worker preparation excluded). This is a real Gateway, SQLite state, agent tools, and scheduler against a synthetic loopback model, not an external-provider live test.

  • Candidate: 33 item-conflict integration, 56 continuation unit, 16 continuation integration, seven real SQLite cold-reopen (including old transcripts without argument metadata), 22 wake, 23 requester-settle dispatch, and 14 prefix-stability tests pass. Deferred repair survives a new internal session-effects run. A persistent delivery conflict exhausts at three attempts without a fourth turn.

  • ClawSweeper found that the early returned-conflict branch could bypass intentional message-hook suppression. The combined cancellation/conflict regression fails before the correction; conflict handling now stays inside the existing missing-reply decision, preserving suppression, ambiguous sends, and permanent outcomes. This removes the early branch. All 159 delivery tests, production/test types, targeted lint, and full-context Codex review pass. The real upgrade/delivery proof above was repeated successfully after this correction.

  • Browser import gate: 46 affected browser tests and 10 messaging UI E2E tests pass.

  • Codex P0–P2 autoreview is clean after fixing the accepted stale-terminal-snapshot finding. Full owner context was supplied. ClawSweeper’s source-identity finding is fixed: raw arguments require matching provider, API, and model; provider/API regressions fail before the fix. The follow-up independent Codex review is also clean.

  • pnpm check:changed: the full staged run against the original parent passes all gates except the inherited dead export, including production, script, core-test and root-test types, lint and format. An unused EXEC_RETENTION_CAP_NOTE export reproduces on the exact parent, introduced by 202514ee61a09f929f587f43820eb125cc51aed8 (feat(exec): write background exec output to a file named in the exit wake #199992). This is an inherited main regression, not a passing check.

  • Prior-head CI exposed a loopback-fixture host dependency: inherited Gateway guarded fetch rejected the redirected local URL before output. Reproduced with the production host installed (7 failures); explicit library-host setup/restoration gives 33 passing cases. No production network policy changed.

  • CI found a steering fixture race: the execute case released a held tool on RPC acknowledgment before asynchronous runtime admission. It now uses the sibling's existing admission receipt. All six FIFO cases pass; targeted lint and independent Codex P0–P2 review are clean. The overlapping fix(agents): mid-turn messages no longer drop message-tool replies #176084 changes a different scenario.

  • The repeated 120-second plugin-reload timeout was reproduced through the exact two-file Bun CI wrapper. The guarded child selected its owned temp root only after capability preloads; the nested runner's short-path temp relocation therefore sent the real SQLite-close probe outside the guard. Its rejection disabled native-close support and caused 593 transcript-worker starts/rotations across three scenarios. Moving the existing temp-root assignment into the guard preload makes the real probe succeed and reduces starts/rotations to 15. All database-path rejection checks remain intact; no timeout, runtime policy, scheduling, or production code changed. The new regression fails before the fix, then all 12 isolation tests pass. Node passes the continuation and revocation product tests (continuation 38.2 seconds); the observed Bun continuation passes in 41.6 seconds at the unchanged 120-second limit. The exact two-file/two-worker Bun CI wrapper passes all 16 tests (continuation 39.3 seconds, full Vitest 59.8 seconds); CI run 43868215781 attempt 1 on ee0cfc5e956ffdcb615becf27fb42abf08f21659 passed every job that reached tests; 35 jobs failed during runner setup because Boat exhausted its sandbox-start quota. The large-4 setup log independently confirms this happened before Bun launched. A single failed-job-only infrastructure retry used the existing GitHub-hosted fallback, preserving successful jobs and the emitted plan. Attempt 2 completed: the actual agentic-control-plane-http-plugin-ws group passed all 17 tests in job 133319653459, with the continuation at 66.358 seconds. Added fixture selection repacked shard names; the green large-4 job itself is not the reload proof. No billing or runner settings changed.

  • The fixture interaction comes from the late temp reset in fix(plugins): continue self-held session sends after reload #187095 and nested-runner temp shortening in fix(test): prevent Chromium crashes under deep temporary roots #196509. Earlier passing parent controls did not establish inheritance; the capability rejection and worker churn establish the cause. This is a main test-infrastructure regression corrected here, not ignored as CI noise. Codex P0–P2 review of the three-file correction is clean. Final-head ClawSweeper review (ee0cfc5e956ff, worker 43868311976) has zero findings and zero open items. Native preparation is complete. Exact-head CI remains failed only on the two qualified main regressions below; landing uses the explicitly authorized inherited-failure exception.

  • Remaining CI failure checks-node-changed-compact-large-1: settled-turn-finalization.transport.test.ts expects terminated but receives native Bun ECONNRESET. The exact CI main parent cf74e641eb9c reproduces it in the same 26-file Bun group (477 pass, one fail). Replacing only the two transport-host owners with their versions before chore(release): close out 2026.11.4 on main #199956 / ea69fcb makes all 478 pass. That change made host state and base installation process-global across test module resets; preceding host replacement can survive into the socket test. This is a main regression already owned by peer fix: isolate transport policy between shared-worker test files #200101, not ignored noise. Standalone passing tests were not used as inheritance proof.

  • Remaining CI failure checks-ui-e2e (1/3): the cached reader shifts 22.390625 pixels. Exact cf74e641eb9c reproduces that drift (11 pass, one fail); reused causal owner controls attribute fix(ui): keep the chat reader's text still while scrolling and while content renders late #199080 / 97dd78c, with its predecessor passing all 12. All test/owner/lock inputs match the tested merge. This is a main UI regression. Both root failures and their aggregate are recorded for pinned-head native admin landing; overall CI is not green.

Owner measurements and synthetic scale

Correctness repair, not a speedup claim. Five interleaved A1/A2/B arms per flow, 5,000 distinct histories × 40 messages, 8 KiB tool arguments/results, 10,000 timing iterations and separate 5,000-iteration sampled-allocation passes. Measured request conversion only, not Gateway/provider latency or database scans. The changed converter does no database or workspace I/O.

Measured conversion shape (9ba044c; converter bytes unchanged by later test and terminal-error repairs):

Flow Arm Wall median/p95 µs CPU median µs Main-thread CPU µs Sampled bytes/request
Uncached A1 39.22 / 40.37 49.23 39.17 117405
Uncached A2 39.82 / 40.25 50.06 39.74 117630
Uncached B 40.53 / 41.30 50.68 40.45 117725
Frozen warm A1 50.62 / 51.52 61.97 50.37 76796
Frozen warm A2 46.86 / 50.89 57.73 46.67 76816
Frozen warm B 47.34 / 48.88 57.81 47.23 76805

Uncached wall cost is about +2.6% and CPU +2.1% against the A/A midpoint, with unchanged allocation within sampling variation. Warm results lie within the A/A range. Healthy wire hashes match; noncanonical-argument hashes intentionally differ because baseline reserializes provider bytes. An earlier unmerged JSON-envelope representation doubled uncached conversion cost and was replaced by the structured field.

Verified synthetic btrfs inventory: 37,798,600,704-byte canonical agent database (35.2 GiB), 5,000 sessions, 197,221 active transcript events; 62,000 workspace files / 1,116,000,000 bytes. All generated locally; no Team data. The btrfs loop image is backed by the external task volume. A first internal-backed attempt filled the local disk and was removed; its failed proof is not used.

Production LOC net +85; the CI correction adds zero production lines (test infrastructure: 34 additions, three deletions). Growth covers durable exact-argument metadata/edit checks, source identity, continuation compatibility, typed settle retry classification, and preserving returned terminal error codes. No new cache, scheduler, configuration, or schema. Existing stored calls without metadata continue through normalized replay and one-shot recovery.

@clawsweeper

clawsweeper Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation scripts Repository scripts agents Agent runtime and tooling size: M labels Nov 16, 2026
@steipete
steipete marked this pull request as ready for review November 16, 2026 07:32
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 16, 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-16T12:39:55.077307Z ee0cfc5 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.

@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. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. 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 16, 2026
@clawsweeper

clawsweeper Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Preserves original Responses tool arguments across restart and automatically retries completion delivery after saved-state conflicts.

Example: A saved tool call contains {"n":9007199254740993} and the Gateway restarts.

  • Before: Replay changes the argument to {"n":"9007199254740993"}, potentially conflicting with the saved provider item.
  • After: An unchanged call from the same provider, API, and model replays the original argument bytes.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused owner-level repair with production-entry-point and stable-upgrade evidence, resolved prior findings, and no new actionable defect.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): The supplied real Gateway trace exercises stable-state reopening, agent tools, SQLite, and the wake scheduler against a synthetic loopback model: cold conflicts recover in-turn, and a text-emitting deferred announce delivers through a distinct retry without user input; final-head changes affect only test isolation.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: After restart, a conversation can reject its saved Responses history and leave a completed child result undelivered.
Reason: The maintainer-authored direction repairs demonstrated recovery failures while retaining existing delivery limits and suppression policy.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR fixes current restart and completion-delivery failures, and prior findings are resolved; current-head validation remains unfinished after runner-setup failures.

Priority: P1
Reviewed head: ee0cfc5e956ffdcb615becf27fb42abf08f21659

Before merge

None.

Findings

None.

Agent review details

How this fits together

The Responses transport converts persisted conversation history into provider requests; the existing completion owner consumes terminal results and schedules bounded requester delivery retries.

flowchart TD
  A[SQLite transcript] --> B[Responses replay converter]
  B --> C[Responses transport]
  C --> D[Provider response]
  D --> E[Terminal result]
  E --> F[Completion delivery owner]
  F --> G[Requester reply or bounded retry]
Loading

Technical review

Best possible solution:

Land the existing shared-owner repair once current-head validation completes.

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

Current main still reserializes saved arguments and excludes saved-state conflicts from public settle retries; supplied failing-base regressions and the Gateway trace demonstrate both failure routes.

Is this the best way to solve the issue?

The patch repairs argument preservation at terminal admission and replay, then carries typed failures into the existing bounded delivery policy without adding another scheduler or recovery owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Failed-response output classification changes intended behavior with a stated reason (e1f84d9: Permit recovery before real assistant output while avoiding replay after tool activity; failed text/reasoning snapshots were still counted despite never being emitted.)
  • Continuation argument comparison keeps the original intent (b9ffdc9: Normalize admitted provider output to preserve continuation across unsafe integers while keeping sent input and real edits strict; the patch retains that legacy comparison alongside exact-byte replay.)
  • Streamed tool-argument precedence keeps the original intent (d72281e: Reliable complete streamed arguments must win over stale done snapshots; the selected raw bytes now accompany the selected parsed value.)
  • Requester retry eligibility changes intended behavior with a stated reason (67a560e: Retain completion obligations for specific retryable failures under existing authority and attempt limits; this PR explicitly extends eligibility to repaired provider state.)
  • Intentional delivery suppression keeps the original intent (976c5bf: Preserve intentional suppression, committed and ambiguous sends, permanent failures, and explicit stops during requester recovery.)
  • Guarded plugin-reload fixture keeps the original intent (bca8823: Keep product-test SQLite work inside the owned fixture; moving temporary-root selection before capability probes preserves that boundary after runner path relocation.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

Source +85, Tests +252, Docs +7, Other +15. Total +359 across 27 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 14 133 48 +85
Tests 10 280 28 +252
Docs 2 10 3 +7
Config 0 0 0 0
Generated 0 0 0 0
Other 1 17 2 +15
Total 27 440 81 +359

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
Production versus test growth Production +133/-48; tests and fixtures +280/-28 The production growth supplies exact replay metadata and typed recovery through existing owners; regressions cover transport, persistence, delivery suppression, retry exhaustion, and fixture isolation.
Benchmark option One new benchmark flag: --provider-arguments This generates noncanonical argument fixtures for conversion measurements; it adds no Gateway configuration setting.

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster. Replaced prior rating: 🐚 platinum hermit.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P1: Saved Responses conflicts can strand active conversations and completed subagent results until another user message arrives.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster. Replaced prior rating: 🐚 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 (4 earlier review cycles)
  • reviewed 2026-11-16T07:48:30.041Z sha 0327a2e :: blocked before merge. :: [P2] Fence argument signatures to the complete source model identity
  • reviewed 2026-11-16T08:38:13.142Z sha e4aef0a :: blocked before merge. :: none
  • reviewed 2026-11-16T09:48:26.803Z sha 8d8d250 :: needs changes before merge. :: [P2] [P2] Preserve intentional suppression before retrying saved-state conflicts
  • reviewed 2026-11-16T10:13:28.467Z sha 336ae68 :: needs maintainer review before merge. :: none

Reviewed November 16, 2026, 7:43 AM ET / 12:43 UTC (Revision 5).

@steipete

Copy link
Copy Markdown
Contributor Author

Addressed both items from the review of 0327a2e0 in 9ba044cdcde27ea7e417356c8e7d743fdf33e0e3:

  1. Complete source identity: exact argument replay now requires provider, API, and model equality at openai-responses-replay-messages-internal.ts:563–567. Existing item-ID policy is unchanged. The integration cases at lines 207–285 exercise provider/API/model changes and argument edits. Provider and API cases failed before this correction; all pass afterward.
  2. Stored-data compatibility: argumentsSignature is optional. The real SQLite cold-runner test now includes the legacy no-signature shape, closes/reopens the database and runtime state, and successfully continues with normalized arguments: fixture modes and cold reopen. All seven cold-reopen cases pass. The transport regression also explicitly removes the field before serialized reload (lines 163–201) and proves bounded repair plus stable subsequent replay. No database schema changed.

The PR body now separates deterministic proof from the unavailable exact Team wire trace and records the remaining CI uncertainty. Codex autoreview is clean after these corrections.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot removed merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 16, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

Addressed every open item against 8d8d2509ffb3b064ae4be05ca67668920da39253:

  1. Current compatibility-proof item: the official stable 2026.11.4 npm tarball was integrity-verified and run in an isolated test instance. A real Gateway created a conversation containing a completed session_status tool call and no argumentsSignature. After stopping that Gateway, candidate Doctor and Gateway reopened the same SQLite state. Existing history remained visible; a synthetic pre-output response.failed conflict recovered inside the same turn with exactly one retry. The committed legacy/cold-reopen regression remains at embedded-agent-runner.responses-cold-prefix.test.ts:29.

    The same real Gateway then used sessions_spawn and sessions_yield. Its first requester-settle response emitted actual text before item_conflict. The trace recorded outcome=deferred at 01:38:57.447 PST, then a distinct :retry-1 announce run recorded outcome=recovered at 01:39:56.674 and delivered DELIVERY_RECOVERED_PROOF, without another user message. There were exactly two announce attempts. The one-off product test passed in 148.3 seconds, excluding build/worker preparation. This uses the real Gateway, agent tools, SQLite and wake scheduler with a synthetic loopback model; it is not an external-provider live test. Candidate build was the pinned CI merge 4f391cb plus the final returned-error repair; affected source blobs match the current head.

    That stronger product proof caught an additional defect missed by the earlier thrown-error fixture: returned Gateway failures lost their error code and became non-retryable missing replies. terminal-resolution.ts:462 now preserves the code; subagent-announce-direct-response.ts:166 preserves the retry reason while respecting delivery evidence. The real pre-fix test stranded delivery for its full 90-second observation; the terminal-code and returned-response regressions also fail before the repair. All 241 focused terminal/delivery tests and full-context Codex P0–P2 review pass. Persistent conflicts remain capped at three attempts.

  2. Earlier source-identity finding: openai-responses-replay-messages-internal.ts:563 requires matching provider, API and model before replaying raw argument bytes. The provider/API regression cases are red before that fix and green on this head, alongside changed-model and edited-argument cases. This correction remains intact.

The PR body now records the complete proof and the still-pending exact-head CI. No schema, scheduler or configuration was added. No Team data was copied or changed.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8d8d2509ff

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 16, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

Addressed both open items on 336ae68528ccb28debbf3ab6926a7ad13455cb04:

  1. P2 — preserve intentional suppression: removed the early returned-conflict branch. Conflict classification now lives in the existing missing-reply decision, after the caller's normal delivery decisions. Intentional suppression and ambiguous/committed sends retain priority. The combined suppression/conflict regression fails on 8d8d2509 and passes after this correction. All 159 delivery tests, production/test type checks, targeted lint and full-context Codex P0–P2 review pass.

  2. Restore original intent of intentional delivery suppression: the contract from 976c5bfa46df46e86434d0e618df31251b68b743 (fix(agents): reconcile late requester recovery receipts #155357) remains authoritative. A recorded message-hook cancellation remains delivery_suppressed / intentional_non_delivery / terminal; saved-state repair no longer overrides it. Existing permanent and ambiguous outcomes also retain their classifier paths. This correction reduces production code by seven lines; total PR production delta is now +85.

The real stable 2026.11.4 → candidate Gateway upgrade and automatic-delivery proof was repeated after this correction and passes (114.7 seconds, excluding preparation). The cold pre-output request logs recovered; the text-emitting announce logs deferred at 02:04:03.607 PST, and a distinct :retry-1 logs recovered at 02:05:02.966 and delivers the completed child result with no new user message. Exactly two announce attempts. All 14 changed production modules match the tested candidate. This uses real Gateway/tools/SQLite/scheduler execution with a synthetic loopback model, not an external-provider live claim.

The PR body and proof are current. Exact-head CI remains in progress; no merge submitted.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 16, 2026
Nested Vitest temp-path relocation could send the native-close capability probe outside the fixture guard. Its rejection disabled explicit close and caused hundreds of transcript-worker replacements during reload continuations. Select the owned temp root in the preload guard and remove the late reset.

Regression fails before the fix; 12 isolation tests, Node continuation/revocation product tests, and the exact Bun CI group pass at the unchanged timeout. check:changed passes except the exact-parent dead export introduced by #199992. Codex review is clean.
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime and removed size: M labels Nov 16, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

The repeated Bun CI timeout is now reproduced and corrected at the fixture owner. Nested Vitest temp-path shortening ran before the SQLite capability preload, while the private handoff guard still selected its owned temp directory later during scenario setup. The real close probe was rejected, disabling native close and causing 593 transcript-worker starts/rotations. Selecting the owned temp root in the preload guard makes the genuine probe pass and reduces this to 15. Database-path rejection remains unchanged; no runtime policy, timeout, or shard placement changed.

The new startup-probe regression fails before the correction; all 12 isolation cases pass afterward. Uninstrumented Node continuation and revocation product tests pass. The exact two-file Bun CI wrapper passes all 16 tests, with the formerly failing continuation at 39.3 seconds against the unchanged 120-second limit. Independent Codex P0–P2 review is clean. Exact-head hosted CI is pending.

Rechecked every item from the previous review against ee0cfc5e956ffdcb615becf27fb42abf08f21659:

  1. Intentional suppression still precedes saved-state conflict handling in src/agents/subagents/announce/subagent-announce-direct-response.ts:127; the combined cancellation/conflict regression at src/agents/subagents/announce/subagent-announce-direct-delivery.test.ts:468 remains unchanged and passing.
  2. The same ordering preserves the original intentional non-delivery contract, including committed and ambiguous sends. This test-infrastructure correction changes no delivery production code.

The prior review reported zero open items; the PR body now includes the causal timeout fix and final local proof.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete
steipete merged commit 5962eee into main Nov 16, 2026
204 of 248 checks passed
@steipete
steipete deleted the steipete/fix-restart-announce-item-conflict branch November 16, 2026 13:45
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

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]>
RomneyDa added a commit that referenced this pull request Nov 17, 2026
Use the repository loader for checklist subprocesses and preserve the SQLite
fixture-owned temp root. Adapt the canonical repairs from
da3ac01 (#200313) and
5962eee (#200020).

Preload the real lazy model-picker module for retained-settings assertions,
import the Google request transport through its existing narrow SDK owner,
and synchronize the cron fixture with callback rather than mock-payload
settlement. No test deadlines, production cancellation semantics, or
assertions are weakened.

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: RomneyDa <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 17, 2026
…art (openclaw#200020)

* fix: recover saved Responses state and retry completion delivery after restart

* fix: preserve streamed replay bytes without repeated metadata parsing

* fix: scope saved argument replay to its source provider

* test: satisfy conditional braces in replay regression

* test(gateway): await steering admission before releasing tool

* fix(agents): retry returned saved-state delivery failures

* fix(agents): preserve delivery suppression before state repair

* fix(test): initialize guarded temp root before SQLite probes

Nested Vitest temp-path relocation could send the native-close capability probe outside the fixture guard. Its rejection disabled explicit close and caused hundreds of transcript-worker replacements during reload continuations. Select the owned temp root in the preload guard and remove the late reset.

Regression fails before the fix; 12 isolation tests, Node continuation/revocation product tests, and the exact Bun CI group pass at the unchanged timeout. check:changed passes except the exact-parent dead export introduced by openclaw#199992. Codex review is clean.
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 docs Improvements or additions to documentation gateway Gateway runtime P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: L 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