Skip to content

fix(ai): preserve Responses history after compaction - #120729

Merged
steipete merged 1 commit into
mainfrom
steipete/fix-openai-compaction-tool-output
Aug 8, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/fix-openai-compaction-tool-output

Conversation

@steipete

@steipete steipete commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes two confirmed failures from #120457 in long embedded Responses sessions. First, a function_call_output arriving after compaction was dropped when its matching function_call lived inside the compacted prefix. Second, when a compaction checkpoint was rejected, the retry started from an already-pruned suffix, allowing a plausible but context-blind answer to be committed.

Why This Change Was Made

The replay plan now keeps the raw transcript immutable before any projection or pruning. The normal request sends the compaction checkpoint plus its chronological suffix; rejection lazily builds a fallback from the untouched full history instead of reusing the pruned request. Within the narrow compaction window, unframed function results are preserved even when their calls moved into the compacted prefix, while the existing pairing policy remains in place outside that window.

The same replay plan is carried through the SDK, SSE, WebSocket, and Azure success boundaries. This changes no configuration, protocol, or storage schema.

Related: #120457

User Impact

Long embedded Responses sessions retain chronological tool outputs and recover rejected checkpoints with full conversation history instead of silently losing context.

Evidence

  • node scripts/run-vitest.mjs packages/ai/src/transports/openai-responses-compaction-replay.test.ts packages/ai/src/transports/openai-responses-prompt-observer.test.ts src/agents/transport-message-transform.test.ts — 3 files passed across 2 shards, 78 tests passed (31 + 47).
  • node scripts/run-vitest.mjs packages/ai/src/providers/openai-chatgpt-responses.encrypted-retry.test.ts packages/ai/src/providers/openai-responses-shared.test.ts packages/ai/src/providers/azure-openai-responses.test.ts — 3 files passed in 1 shard, 95 tests passed.
  • git diff --check origin/main...HEAD — passed.
  • node_modules/.bin/oxfmt --check <all 20 touched files> — passed; all matched files use the correct format.
  • Autoreview was clean at 0.97 before the rebase. A fresh post-rebase review remains a pre-land gate.
  • Production LOC: +245/-197 (net +48) across 15 files. Tests: +261/-60 (net +201) across 5 files.
  • OpenAI compaction contract: https://developers.openai.com/api/docs/guides/compaction

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: L maintainer Maintainer-authored PR labels Aug 8, 2026
@steipete
steipete marked this pull request as ready for review August 8, 2026 22:17
@steipete

steipete commented Aug 8, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. 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. labels Aug 8, 2026
@clawsweeper

clawsweeper Bot commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 8, 2026, 6:45 PM ET / 22:45 UTC.

ClawSweeper review

What this changes

This PR preserves post-checkpoint tool results in OpenAI Responses requests and rebuilds a rejected compaction retry from the unmodified transcript.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep open for maintainer review: the patch appears to repair the two replay failures through the shared owner, but direct OpenAI SDK and required Codex-source contract audits were unavailable. Likely related people: steipete, the original compaction-replay and follow-up author (high confidence).

Priority: P1
Reviewed head: 779ae3df7e4010f0249950e982ac10ff663372c5

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The owner-boundary repair and focused regressions are coherent, but unavailable external dependency and Codex contract audits limit merge confidence.
Proof confidence 🌊 off-meta tidepool Not applicable: This maintainer-authored, maintainer-labeled PR is exempt from the external-contributor proof gate; its body still provides focused mocked transport coverage rather than live provider proof.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This maintainer-authored, maintainer-labeled PR is exempt from the external-contributor proof gate; its body still provides focused mocked transport coverage rather than live provider proof.
Evidence reviewed 5 items Shared replay owner: The exact PR head returns the untouched transcript for full-history mode, while checkpoint mode slices before transcript repair and retains post-checkpoint results chronologically.
Rejected-checkpoint recovery: The retry owner now lazily rebuilds full history before removing rejected compaction, rather than filtering the already-pruned request.
Provider conversion entry point: The shared Responses converter builds the replay plan before transforming messages and adds the checkpoint only from that plan.
Findings None None.
Security None None.

How this fits together

The Responses transport converts an agent transcript into OpenAI or Azure request input and carries the provider’s opaque compaction checkpoint across turns. Its retry path determines whether a rejected checkpoint falls back to the full conversation or an incomplete suffix.

flowchart LR
  A[Agent transcript] --> B[Replay planner]
  B --> C[Checkpoint request]
  B --> D[Full-history retry]
  C --> E[OpenAI and Azure transports]
  D --> E
  E --> F[Provider response]
  F --> G[Session transcript]
Loading

Before merge

  • Resolve merge risk (P1) - Direct OpenAI SDK types/docs and the required Codex source checkout were unavailable, so the external retry contract and Codex-specific behavior remain unverified before merge.
  • Complete next step (P2) - The maintainer label and unavailable direct dependency/Codex audits require human pre-land review rather than automated repair.
Agent review details

Security

None.

PR surface

Source +48, Tests +201. Total +249 across 20 files.

View PR surface stats
Area Files Added Removed Net
Source 15 245 197 +48
Tests 5 261 60 +201
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 20 506 257 +249

Review metrics

Metric Value Why it matters
Production versus test delta production +245/-197 (net +48); tests +261/-60 (net +201) The production growth centralizes replay ownership across provider paths, while the larger test delta covers retry and transcript-order regressions.

Stored data model

Persistent data-model change detected: serialized state: packages/ai/src/providers/openai-chatgpt-responses.encrypted-retry.test.ts, serialized state: packages/ai/src/transports/openai-responses-prompt-observer.test.ts, serialized state: src/agents/session-transcript-repair.ts, unknown-data-model-change: src/agents/session-transcript-repair.ts, vector/embedding metadata: packages/ai/src/transports/openai-responses-client.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Complete the contract audit (recommended)
    Inspect the direct OpenAI SDK request/error contract and the required Codex compaction source against this exact head before merge.
  2. Pause for broader confirmation
    Hold this transport change until a maintainer can establish the external replay contract with the unavailable source material.

Technical review

Best possible solution:

Retain the transport-owned replay plan, but complete direct OpenAI SDK and Codex contract review on the exact head before landing.

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

Yes — source inspection shows the prior retry stripped compaction from an already-pruned request; the exact-head regressions exercise the full-history fallback and post-checkpoint tool-result path, though they were not executed in this read-only review.

Is this the best way to solve the issue?

Yes — centralizing checkpoint versus full-history selection in the replay owner is the narrowest maintainable repair; final dependency-contract confirmation remains required before merge.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P1: The repaired path can silently commit context-blind answers in long embedded Responses sessions.
  • add merge-risk: 🚨 session-state: A retry projection error can omit or mis-associate conversation and tool-result history for an existing session.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This maintainer-authored, maintainer-labeled PR is exempt from the external-contributor proof gate; its body still provides focused mocked transport coverage rather than live provider proof.

Label justifications:

  • P1: The repaired path can silently commit context-blind answers in long embedded Responses sessions.
  • merge-risk: 🚨 session-state: A retry projection error can omit or mis-associate conversation and tool-result history for an existing session.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This maintainer-authored, maintainer-labeled PR is exempt from the external-contributor proof gate; its body still provides focused mocked transport coverage rather than live provider proof.

Evidence

What I checked:

Likely related people:

  • steipete: Peter Steinberger authored the merged compaction-replay feature and this focused corrective commit. (role: original feature and follow-up author; confidence: high; commits: 47f78a32eb9e, 779ae3df7e40; files: packages/ai/src/transports/openai-responses-compaction-replay.ts, packages/ai/src/transports/openai-responses-replay-internal.ts, packages/ai/src/providers/openai-responses-shared.ts)

Rank-up moves

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

  • Complete direct OpenAI SDK and Codex-source contract checks for the exact head before landing.

Rating scale

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

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

Workflow

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

@steipete

steipete commented Aug 8, 2026

Copy link
Copy Markdown
Contributor Author

ClawSweeper rank-up disposition for 779ae3df7e4010f0249950e982ac10ff663372c5:

  • Direct OpenAI SDK audit completed against installed [email protected]. ResponseCompactionItemParam treats encrypted content as opaque and permits the replay ID to be omitted; non-2xx requests throw before withResponse() can succeed, and ordinary SDK retries cover 408/409/429/5xx rather than the 400 invalid-encrypted-content contract. Sources: compaction types, non-2xx handling, and retry classification.
  • OpenAI's compaction guide defines the replay window chronologically: only items before the newest compaction may be dropped. The patch now retains every later item, including a tool output whose call was absorbed into the checkpoint.
  • Direct Codex source audit completed against the exact pinned @openai/[email protected] source commit be6e8eac029b. Codex models compaction as opaque encrypted state (item contract), requires exactly one completed compaction output before accepting it (validation), and replaces canonical history only after the compaction attempt succeeds (installation). Invalid requests remain distinct from stream retries (error category, retry owner).
  • Exact-head CI is green. Focused proof passed 173 tests across replay conversion, prompt observation, native SSE/WebSocket recovery, public/Azure providers, and transcript repair. Post-rebase autoreview is clean at 0.98 confidence.

No actionable ClawSweeper finding remains. The dependency-contract rank-up move is complete, and the maintainer considers this head ready for the guarded prepare/merge workflow.

@steipete

steipete commented Aug 8, 2026

Copy link
Copy Markdown
Contributor Author

Land-ready verification for exact head 779ae3df7e4010f0249950e982ac10ff663372c5:

  • node scripts/run-vitest.mjs packages/ai/src/transports/openai-responses-compaction-replay.test.ts packages/ai/src/transports/openai-responses-prompt-observer.test.ts src/agents/transport-message-transform.test.ts — passed, 78 tests (31 + 47 across two shards).
  • node scripts/run-vitest.mjs packages/ai/src/providers/openai-chatgpt-responses.encrypted-retry.test.ts packages/ai/src/providers/openai-responses-shared.test.ts packages/ai/src/providers/azure-openai-responses.test.ts — passed, 95 tests. git diff --check origin/main...HEAD and the 20-file format check also passed.
  • Exact-head hosted CI is green: https://github.com/openclaw/openclaw/actions/runs/31281353211 (openclaw/ci-gate, lint, production/test typechecks, formatting, tests, and security passed).
  • OPENCLAW_TESTBOX=1 scripts/pr prepare-run 120729 succeeded at 2026-08-08T22:57:42Z with GATES_MODE=hosted_exact_or_recent_parent; it reused the exact-head hosted CI/Testbox evidence above, so no separate remote lease or run ID was issued.
  • Direct [email protected] and pinned Codex be6e8eac029b contract audits are complete; the Codex checks covered codex-rs/protocol/src/models.rs:1020-1028, codex-rs/core/src/compact_remote_v2.rs:206-326,385-442, codex-rs/protocol/src/error.rs:117-122, and codex-rs/core/src/responses_retry.rs:20-73. Full disposition: fix(ai): preserve Responses history after compaction #120729 (comment)

Known proof gap: the expensive paid live suites were not repeated for this narrowly focused correction; deterministic owner-boundary regressions, direct dependency audits, clean post-rebase autoreview, and exact-head required CI cover the change.

@steipete
steipete merged commit 257ac20 into main Aug 8, 2026
190 checks passed
@steipete
steipete deleted the steipete/fix-openai-compaction-tool-output branch August 8, 2026 22:59
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling maintainer Maintainer-authored PR merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: L status: 👀 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