Repository navigation
fix(ai): preserve long Responses sessions after server compaction - #120457
Conversation
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. |
|
Codex review: needs maintainer review before merge. Reviewed August 8, 2026, 2:50 PM ET / 18:50 UTC. ClawSweeper reviewWhat this changesThis PR persists opaque OpenAI Responses compaction state across compatible turns, worker transcripts, and Gateway restarts while removing it from public display and diagnostic payloads. Merge readinessKeep this maintainer-owned PR open. The prior worker-replay omission blocker is repaired, but merge readiness still needs a maintainer decision on exact-head external-provider proof and the required direct Codex source audit. Priority: P1 Review scores
Verification
How this fits togetherResponses transports convert session transcripts into provider requests, then Gateway and worker paths persist the resulting messages. The PR carries provider-owned compaction state through that flow so compatible future requests can resume server-compressed history without exposing ciphertext to users. flowchart LR
A[Session transcript] --> B[Responses transport]
B --> C[Compaction replay state]
C --> D[Gateway and worker transcript]
D --> E[Compatibility and redaction checks]
E --> F[Next OpenAI Responses request]
Decision needed
Why: The patch is source-coherent, but repository policy requires direct Codex inspection for this Codex-backed behavior and the available live proof predates the final head. Before merge
Agent review detailsSecurityNone. PR surfaceSource +906, Tests +5219, Docs +152, Other +3. Total +6280 across 62 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Retain the transport-owned replay design, rebase onto current main, and merge only after direct Codex contract inspection plus exact-head authenticated compaction/restart evidence confirm the documented behavior. Do we have a high-confidence way to reproduce the issue? No live current-head reproduction was independently run in this read-only review; the added Gateway E2E and focused worker tests provide a clear source-level reproduction path. Is this the best way to solve the issue? Unclear for merge readiness: the owner boundary and prior-finding repair are sound in source, but direct Codex-contract inspection and exact-head external-provider proof remain required. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 82f6280fa86a. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (7 earlier review cycles)
|
|
@clawsweeper re-review |
|
🦞👀 Command router queued. I will update this comment with the next step. |
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
Persist opaque Responses compaction items as fenced provider replay state so long stateless sessions can resume authoritative compressed history without exposing it in display or diagnostics. Carry state through worker transcripts and prune replay prefixes without splitting tool pairs. Release note: Preserve long OpenAI Responses sessions across server-side compaction and worker restarts. Related: #95788
Make tool-result fixtures type-complete, use the canonical model selector helper, remove unused test-helper exports, and route the paid long-context live probe through the dedicated Gateway profile shard.
Give the mock SSE event collection an explicit open event shape so terminal response events coexist with output-item events under the root test typecheck.
Persist a route-fenced suppression tombstone when encrypted-content recovery rejects a compaction item, so later turns do not retry the same opaque state. Preserve the tombstone through transcript redaction and cover successful fallback followed by the next turn.
Keep the suppression contract local to its sole Responses transport owner and make the regression fixture satisfy root type and lint checks without widening the Plugin SDK surface.
|
@clawsweeper re-review |
|
🦞👀 Command router queued. I will update this comment with the next step. |
Use the shared encrypted-content retry owner for Azure Responses so compaction suppression and prompt-observer variants stay coherent across transports.
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
Fence Azure replay by the resolved request endpoint, drop invalid replay during transcript sanitization, and surface worker-launch replay omissions through the existing redacted diagnostic path.
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
ClawSweeper rank-up disposition for
No actionable ClawSweeper finding remains. The maintainer accepts the explicitly documented live-proof timing gap for this landing. |
|
Merged via squash.
|
…0807 * origin/main: fix(qa): honor Crabbox SSH fallback ports (openclaw#120539) refactor(core): adopt normalization-core leaf helpers across production (openclaw#120350) fix(release): scope upgrade plugin credentials (openclaw#120666) fix(ai): preserve long Responses sessions after server compaction (openclaw#120457) fix(test): keep fork E2E setup builds observable (openclaw#120653) fix(cloud-workers): retain provider operation ownership (openclaw#120661) docs: runners plan — one placement model for sessions, devices, and cloud (openclaw#120657) refactor(cli): inline state migration policy (openclaw#120641) feat(update): scheduled update campaigns with countdown, dev-channel auto-update, and Updates settings page (openclaw#120506) chore(i18n): refresh native locales (openclaw#120614) fix(ci): retry transient artifact API reads (openclaw#120654) fix(clawrouter): honor advertised reasoning efforts (openclaw#120631) fix(infra): unify env-truthiness, missing-path, realpath, and abort-sleep semantics (openclaw#120359) fix(maintainers): parse merge comment URL structurally (openclaw#120649) fix(ui): label only operator-pinned runtimes in model picker rows (openclaw#120646) docs(agents): replace exact-head re-review gate with 12-hour review window # Conflicts: # src/agents/payload-redaction.ts
…enclaw#120457) * fix(ai): preserve Responses server compaction state Persist opaque Responses compaction items as fenced provider replay state so long stateless sessions can resume authoritative compressed history without exposing it in display or diagnostics. Carry state through worker transcripts and prune replay prefixes without splitting tool pairs. Release note: Preserve long OpenAI Responses sessions across server-side compaction and worker restarts. Related: openclaw#95788 * test(ai): align long-context fixtures with CI contracts Make tool-result fixtures type-complete, use the canonical model selector helper, remove unused test-helper exports, and route the paid long-context live probe through the dedicated Gateway profile shard. * test(ai): type mocked Responses terminal events Give the mock SSE event collection an explicit open event shape so terminal response events coexist with output-item events under the root test typecheck. * fix(ai): suppress rejected compaction replay Persist a route-fenced suppression tombstone when encrypted-content recovery rejects a compaction item, so later turns do not retry the same opaque state. Preserve the tombstone through transcript redaction and cover successful fallback followed by the next turn. * fix(ai): keep compaction suppression transport-private Keep the suppression contract local to its sole Responses transport owner and make the regression fixture satisfy root type and lint checks without widening the Plugin SDK surface. * refactor(ai): remove compaction suppression re-export * fix(ai): scope compaction suppression to replay route Keep foreign-route rejection tombstones from hiding the newest compatible Responses compaction while preserving same-route suppression. * fix(ai): harden Responses replay recovery Stage encrypted replay recovery so compaction is only suppressed after an attributable rejection. Preserve terminal ordering and keep provider replay within worker frame budgets without truncating opaque state. * refactor(ai): centralize Responses output indexes Keep normalized output identity tracking in the stream-slot owner, move response failure state to its diagnostic owner, and remove the obsolete replay clone export so exact-head static gates remain shrink-only. * fix(ai): retain idless terminal tool identity Use the canonical empty identity only when a provider supplies neither call nor item id, preventing terminal recovery from duplicating a done-only tool call while preserving stronger identities when available. * fix(sessions): hide provider replay from public events * fix(ai): stage encrypted replay recovery * fix(ai): keep replay attempt kind internal * fix(ai): route Azure through replay recovery Use the shared encrypted-content retry owner for Azure Responses so compaction suppression and prompt-observer variants stay coherent across transports. * fix(ai): harden replay persistence boundaries Fence Azure replay by the resolved request endpoint, drop invalid replay during transcript sanitization, and surface worker-launch replay omissions through the existing redacted diagnostic path.
## Problem Long OpenAI Responses sessions lost their server compaction checkpoint and fell back to client summarization, even though the provider had compacted the session. The replay identity fence for compaction and encrypted reasoning items included the auth profile hash. One OpenAI key can reach a session two ways: through an auth profile (`openai:*`) or through `models.providers.openai.apiKey`. When runs alternate between those two sources, the fence rejects the session's own checkpoints. The next request then resends the full raw history (about 1M tokens on the affected host) and client summarization runs. In the reported incident, that summarization was refused, which left the session with no summary. This was observed in production on one host where both sources hold the same key; four sessions were affected. The fence was added in #120457 and moved in #135727. ## Fix - The replay identity is now session plus model route only. `authProfileHash` and `authProfileId` are removed from the replay context, the compaction and reasoning replay builders, the context-usage meter, and every provider, transport and agent call site. - A checkpoint from a different org is still rejected by the server (`invalid_encrypted_content` / `item_conflict`). The existing recovery in `openai-responses-replay-internal.ts` already handles that. - Checkpoints saved with a legacy `authProfileHash` still replay. No migration is needed. Net change: 32 files, +42 −77 (tests that asserted the credential-source fence are removed). ## Evidence **Regression test:** `provider-compaction-replay.test.ts` › "counts the returned prefix once after restart, including checkpoints with a legacy auth hash". It fails on base and passes with the fix. **Real-model E2E** (isolated state, `openai/gpt-5.4-mini`, server compaction threshold 12k): - Setup: three seed turns run through an auth profile only. The final turn runs with the config `apiKey` present, which takes precedence. It is the same key, so only the credential source changes. - Request shapes come from `OPENCLAW_DEBUG_MODEL_PAYLOAD=summary`. | arm | final-turn request | items | text chars | answer | | --- | --- | --- | --- | --- | | base `7f234bd` | `message×N, reasoning…`; `compactionItems=0` | 12 | 113,498 | correct | | fix | `compaction, message:user, message:developer`; `compactionItems=1` | 3 | 758 | correct | Base drops the checkpoint and the encrypted reasoning items and resends the full transcript. With the fix, the same checkpoint replays across the credential switch. At production scale, the same flip on a copy of a real session measured 331k tokens with a matching identity versus 900k with only the auth profile changed. **Checks:** - `pnpm check:changed` is green. - Every replay test file that used the credential-source fence is updated. The changed test files pass (153/154; the remaining case needs `--expose-gc`). - The full `packages/ai/src/transports` run shows 7 failures. The same 7 fail on base under the same invocation. They are the GC retention fixtures that need `--expose-gc`, plus two order-dependent tests that pass when run alone. ## Follow-up The meter still estimates from the full transcript when a checkpoint is present. That fix is a separate PR. <!-- openclaw-publication:4ab5fa4d-c2cc-4079-99d9-55f7c6a888a9 --> Co-authored-by: Ayaan Zaidi <[email protected]>
…w#200063) ## Problem Long OpenAI Responses sessions lost their server compaction checkpoint and fell back to client summarization, even though the provider had compacted the session. The replay identity fence for compaction and encrypted reasoning items included the auth profile hash. One OpenAI key can reach a session two ways: through an auth profile (`openai:*`) or through `models.providers.openai.apiKey`. When runs alternate between those two sources, the fence rejects the session's own checkpoints. The next request then resends the full raw history (about 1M tokens on the affected host) and client summarization runs. In the reported incident, that summarization was refused, which left the session with no summary. This was observed in production on one host where both sources hold the same key; four sessions were affected. The fence was added in openclaw#120457 and moved in openclaw#135727. ## Fix - The replay identity is now session plus model route only. `authProfileHash` and `authProfileId` are removed from the replay context, the compaction and reasoning replay builders, the context-usage meter, and every provider, transport and agent call site. - A checkpoint from a different org is still rejected by the server (`invalid_encrypted_content` / `item_conflict`). The existing recovery in `openai-responses-replay-internal.ts` already handles that. - Checkpoints saved with a legacy `authProfileHash` still replay. No migration is needed. Net change: 32 files, +42 −77 (tests that asserted the credential-source fence are removed). ## Evidence **Regression test:** `provider-compaction-replay.test.ts` › "counts the returned prefix once after restart, including checkpoints with a legacy auth hash". It fails on base and passes with the fix. **Real-model E2E** (isolated state, `openai/gpt-5.4-mini`, server compaction threshold 12k): - Setup: three seed turns run through an auth profile only. The final turn runs with the config `apiKey` present, which takes precedence. It is the same key, so only the credential source changes. - Request shapes come from `OPENCLAW_DEBUG_MODEL_PAYLOAD=summary`. | arm | final-turn request | items | text chars | answer | | --- | --- | --- | --- | --- | | base `e263be2` | `message×N, reasoning…`; `compactionItems=0` | 12 | 113,498 | correct | | fix | `compaction, message:user, message:developer`; `compactionItems=1` | 3 | 758 | correct | Base drops the checkpoint and the encrypted reasoning items and resends the full transcript. With the fix, the same checkpoint replays across the credential switch. At production scale, the same flip on a copy of a real session measured 331k tokens with a matching identity versus 900k with only the auth profile changed. **Checks:** - `pnpm check:changed` is green. - Every replay test file that used the credential-source fence is updated. The changed test files pass (153/154; the remaining case needs `--expose-gc`). - The full `packages/ai/src/transports` run shows 7 failures. The same 7 fail on base under the same invocation. They are the GC retention fixtures that need `--expose-gc`, plus two order-dependent tests that pass when run alone. ## Follow-up The meter still estimates from the full transcript when a checkpoint is present. That fix is a separate PR. <!-- openclaw-publication:4ab5fa4d-c2cc-4079-99d9-55f7c6a888a9 --> Co-authored-by: Ayaan Zaidi <[email protected]>
Related: #95788
What Problem This Solves
Fixes an issue where long stateless OpenAI Responses sessions could lose the provider's authoritative compressed history after automatic server compaction. OpenAI emitted an opaque encrypted
compactionoutput item, but OpenClaw neither persisted nor replayed it on the next request, so continuation after compaction or a worker/Gateway restart could silently fall back to an incomplete transcript.Issue #95788 is related but narrower: it asks whether the ChatGPT/Codex no-store route should emit
context_managementor diagnose that it cannot. This PR does not expand that OAuth/store contract and therefore does not close the issue.Why This Change Was Made
The Responses transport is the architectural owner of provider replay state. It now captures the newest first-class compaction item from stream and terminal events, fences reuse by provider, API, model, base URL, session, and auth identity, and replays only a compatible newest item while pruning the prefix it replaces without separating tool calls from their outputs.
The typed replay state crosses the existing LLM, Gateway, SQLite transcript, and worker transcript-frame boundaries. Display, session-history, diagnostics, cache traces, and debug payloads remove the opaque encrypted content; request correlation remains redacted. Native Codex retains its own compaction policy and receives the same long-context budget through its catalog/app-server contract rather than through embedded Responses parameters.
Encrypted-content recovery is deliberately attributable and bounded through one transport-owned three-state plan shared by the SDK (including the canonical Azure Responses transport), native SSE, and native WebSocket paths. A mixed request first retries without encrypted reasoning while preserving compaction. Compaction is removed only after that compaction-preserving request receives the recognized rejection. SDK recovery records the route-fenced tombstone only after successful response acquisition; native SSE waits for a non-aborted 2xx response with a body, and native WebSocket waits for the first yielded response event. Fetch, observer, unrelated provider, abort, final-recovery, and post-stream-start failures cannot advance the semantic retry plan. The terminal stream owner also records provider output identities at their normalized content indexes so terminal-only compaction is replayed at the exact observed boundary.
Worker replay data is capped at 48 KiB without truncating ciphertext. Representative complete commit-frame overhead was 1,021-1,068 bytes, leaving about 15.3 KiB at the cap. A conservative identifier/signature envelope measured 3,829-3,831 bytes, leaving about 12.5 KiB; at 60 KiB only about 267 bytes remained. Projection checks both raw UTF-8 replay bytes and the exact JSON-encoded complete commit frame, omitting only unpersistable replay and emitting a redacted
payload.largediagnostic.No config/default surface or protocol version changes. Production growth is +1,146/-272 (net +874) across 29 files; that growth is justified by the external provider replay contract, its typed persistence and invalidation owner boundary, native retry attribution, exact worker-frame safety, and the privacy invariant around opaque provider state. Tests are +5,168/-101 across 26 files. Docs are +221/-69 across 3 files.
AI-assisted: yes. Codex assisted with the repair and fresh structured reviews. The final Azure recovery review reported no accepted/actionable findings at 0.98 confidence; the staged-recovery review was clean at 0.97 and earlier full-branch/focused reviews were clean at 0.98/0.99. TruffleHog was clean.
User Impact
Operators can run long embedded OpenAI Responses sessions through server-side compaction and continue across later turns, worker transcript commits, and Gateway restarts without losing the server's compressed history. The state remains internal and opaque rather than appearing in chat history or diagnostics.
If a provider rejects a replayed compaction item, encrypted-content recovery now persists a route-fenced suppression tombstone only after attributable successful recovery. A reasoning-only rejection cannot suppress valid compaction, a foreign-route tombstone cannot hide compatible replay, and an oversized opaque replay cannot turn otherwise successful worker inference into a terminal error.
Both explicit runtime recipes now share this policy:
Pricing warning: OpenAI's current pricing states that GPT-5.5/GPT-5.6 requests above 272,000 input tokens bill the whole request at 2x input/cache and 1.5x output rates, while Fast/Priority is another 2x tier. Combined long-context Priority traffic is therefore 4x short-context Standard input-side pricing and 3x short-context Standard output pricing. The live suites are deliberately opt-in and expensive.
Upstream contracts checked:
c2bcb9a26b5b:ResponseItem::Compactionowns the opaque encrypted item;ModelInfodefaults usable context to 95% and clamps automatic compaction to 90%;TurnContext::model_context_windowapplies the effective window;run_pre_sampling_compactinvokes automatic compaction before sampling andrun_auto_compactselects the supported compaction route;compact_conversation_historyowns the/responses/compactrequest; and remote v2 both installs compacted history and requires exactly one compaction output.Evidence
Full embedded OpenAI Responses proof
compactionitem, persisted it, replayed the exact opaque item, and structurally pruned the replaced prefixFull native Codex proof
Deterministic and static proof
providerReplay; internal listeners and persisted ordinary/worker messages retain it, with source and nested object identity preserved and no source mutationinitial->compaction-stripped->initial. The Azure follow-up matrix passed 143 tests across two shardspnpm buildpassed in 3m39s before publicationgit diff --checkpassedProof gaps: the paid live suites ran before the conflict-free rebase and were intentionally not repeated. The standalone packed-package consumer E2E was attempted twice locally: one run timed out its isolated consumer typecheck at 180 seconds and the second reached the suite's 300-second ceiling, with no assertion or code failure. Exact-head hosted CI remains the package-boundary and broad check/lint/build/type authority for the final head.