Repository navigation
fix: preserve compacted history during OpenAI tool continuations - #160895
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. Reviewed September 29, 2026, 12:28 AM ET / 04:28 UTC (Revision 3). ClawSweeper reviewWhat this changesThe branch preserves an OpenAI Responses compaction checkpoint when tool-call repair changes only assistant content after the checkpoint, and adds replay regression tests. Merge readiness✅ Ready for maintainer review Current main still drops the checkpoint in the reported tool continuation, and this PR addresses that behavior. The changed path has focused regression coverage, live OpenAI continuation evidence, and an isolated CLI comparison. No actionable patch defect was found. Priority: P2 Review scores
Verification
How this fits togetherThe embedded agent runner repairs transcript tool calls before the OpenAI Responses transport builds its next request. The transport uses a valid compaction checkpoint to replace covered conversation history while retaining subsequent tool calls and results. flowchart LR
A[Saved conversation] --> B[Tool-call repair]
B --> C[Checkpoint prefix check]
C --> D[Replay eligibility check]
D --> E[Responses request]
E --> F[OpenAI response]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +8, Tests +128. Total +136 across 3 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Technical reviewBest possible solution: Land the narrow checkpoint-owner repair with its replay regression coverage, preserving request-time route and identity validation. Do we have a high-confidence way to reproduce the issue? Yes. The captured before-fix sanitizer cases lose Is this the best way to solve the issue? Yes. The change repairs the shared checkpoint owner's covered-prefix invariant while leaving replay identity selection and tool/result repair with their existing owners. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 743c2ceb72e7. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
History |
|
Addressed the requested after-fix behavior proof on head
Redacted request sequence (generated IDs omitted; opaque checkpoint content redacted): The isolated live test passed in 6.565 s (7.54 s Vitest / 8.71 s runner). This proves the requested accepted continuation, not a guaranteed cache hit or billing reduction: provider input usage was 8142 then 8272 tokens, and cached tokens were zero in this deliberately small test. The earlier deterministic regression remains the before-fix proof. Production Gateway configuration and saved conversations were not changed. Reproduce the live proof on this PR headConfigure pnpm test src/agents/embedded-agent-runner/run/compaction-live-proof.test.ts --maxWorkers=1 --testNamePattern 'real api.openai.com'The harness uses synthetic text and a synthetic tool result, executes no tool action, and prints only statuses, request IDs, usage counters, and request-shape assertions. It does not print or persist credentials or opaque checkpoint bytes. It is one-off proof, not a new per-PR CI test. import type { Context, Model } from "@openclaw/llm-core";
import { expect, it } from "vitest";
import { createOpenAIResponsesTransportStreamFn } from "../../../../packages/ai/src/transports/openai-responses-client.js";
import { sanitizeOpenAIResponsesReplayForStream } from "./attempt-tool-call-replay-sanitization.js";
import { wrapStreamFnWithMessageTransform } from "./message-transform-stream-wrapper.js";
it.skipIf(!process.env.OPENAI_API_KEY)("real api.openai.com continuation keeps a streamed checkpoint after tool ID repair", async () => {
const requests: Array<Record<string, unknown>> = [];
const responses: Array<{ status: number; requestId: string | undefined }> = [];
const model = {
id: "gpt-5.2", name: "GPT-5.2", api: "openai-responses", provider: "openai",
baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 400_000, maxTokens: 256,
} satisfies Model<"openai-responses">;
const streamFn = wrapStreamFnWithMessageTransform(createOpenAIResponsesTransportStreamFn(), sanitizeOpenAIResponsesReplayForStream);
const run = async (messages: Context["messages"], first: boolean) => {
const stream = await streamFn(model, {
systemPrompt: "This is an isolated regression test. Call lookup once when requested. Once the result is ready, reply exactly ready.",
messages, tools: [{ name: "lookup", description: "Return a synthetic test value", parameters: { type: "object", properties: {}, additionalProperties: false } }],
}, {
apiKey: process.env.OPENAI_API_KEY, sessionId: "public-compaction-proof", authProfileId: "proof-profile", transport: "sse",
signal: AbortSignal.timeout(90_000),
onResponse: (response) => { responses.push({ status: response.status, requestId: response.headers["x-request-id"] }); },
onPayload: (payload) => {
const next = { ...(payload as Record<string, unknown>), store: false, max_output_tokens: 512, reasoning: { effort: "none" },
context_management: [{ type: "compaction", compact_threshold: 2048 }],
tool_choice: first ? { type: "function", name: "lookup" } : "none" };
requests.push(next);
return next;
},
});
return stream.result();
};
const user = { role: "user" as const, content: "Synthetic padding for a compaction regression. No customer information. The lookup tool returns ready. ".repeat(450) + "Call lookup now.", timestamp: 1 };
const first = await run([user], true);
expect(first.stopReason, first.errorMessage).toBe("toolUse");
expect(first.providerReplay).toBeDefined();
const toolCall = first.content.find((block) => block.type === "toolCall");
if (!toolCall) throw new Error("Live response did not contain the expected tool call");
expect(toolCall.id).toContain("|fc_");
expect(first.content.some((block) => block.type === "thinking")).toBe(false);
const persisted = JSON.parse(JSON.stringify(first)) as typeof first;
const second = await run([user, persisted, { role: "toolResult", toolCallId: toolCall.id, toolName: toolCall.name, content: [{ type: "text", text: "ready" }], isError: false, timestamp: 2 }], false);
expect(second.stopReason, second.errorMessage).toBe("stop");
const input = requests[1].input as Array<Record<string, unknown>>;
expect(input.map((item) => item.type)).toEqual(["compaction", "function_call", "function_call_output"]);
expect(input[0].encrypted_content).toBe((first.providerReplay as { data: string }).data);
expect(input[1].call_id).toBe(input[2].call_id);
expect(input[1]).not.toHaveProperty("id");
expect(JSON.stringify(requests[1])).not.toContain(user.content);
expect(second.content.filter((block) => block.type === "text").map((block) => block.text).join("")).toBe("ready");
console.log(JSON.stringify({ proof: "real api.openai.com -> production parser -> persisted transcript -> production stream wrapper -> real api.openai.com", head: "e6091958b13de3aace448d25ebc7acdbfc21e344", model: model.id, responses,
firstResponse: { savedCheckpoint: true, toolIdRepairTriggered: true, separateReasoning: false, usage: first.usage },
secondRequest: { inputTypes: input.map((item) => item.type), retainedCheckpointBytesIdentical: true, pairedToolResult: true, orphanItemIdIncluded: false, coveredHistoryIncluded: false, bytes: Buffer.byteLength(JSON.stringify(requests[1])) },
nextResponse: { stopReason: second.stopReason, text: "ready", usage: second.usage }, requests: requests.length }));
}, 200_000); |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Landing with pre-existing CI reds on exact head Review. The ClawSweeper review is ready on this SHA, with no findings and no security issues. Inherited failures. Fresh run 36521172103 finished with no cancelled jobs. All three failing jobs are subagent tests, outside this Responses/compaction diff:
Proof. A real isolated |
|
Landed in 7d8fe30. Thanks @brandon-julio-t for the report and the fix! OpenAI Responses tool continuations now keep the compaction checkpoint after tool-call ID repair instead of resending the covered history. A checkpoint is still only replayed for the model, base URL, session and auth profile it was captured for. |
…nclaw#160895) Co-authored-by: Ayaan Zaidi <[email protected]>
Closes #160889
What Problem This Solves
Fixes OpenAI tool continuations resending the full covered conversation when replay ID repair deletes an inline compaction checkpoint.
User Impact
OpenAI Responses sessions keep the compaction checkpoint on their next tool-loop request, avoiding unnecessary resubmission of covered history. Tool/result repair stays active. No configuration change or migration is required.
Why This Change Was Made
downgradeOpenAIFunctionCallReasoningPairsremoves orphanedfc_*item IDs when no separate replayable reasoning block precedes a tool call. Its replacement block previously causedreplaceCompactionReplayOwnerContentto invalidate the checkpoint, even when the edit was entirely after the checkpoint boundary. Responses ID normalization has the same interaction.The shared checkpoint owner now preserves checkpoints for same-length replacements when every covered prefix block remains the same object in the same position. Prefix changes still invalidate them; existing removal reindexing and empty-owner handling remain intact. The Workshop budget proposal in #159687 addresses a separate problem.
Evidence
e6091958b13de3aace448d25ebc7acdbfc21e344, two real requests tohttps://api.openai.com/v1/responsesreturned HTTP 200. The first streamed a real checkpoint followed by a tool call with no separate thinking block. After JSON transcript serialization/restoration, the production stream wrapper and sanitizer repaired its ID while retaining the byte-identical checkpoint. The next request contained onlycompaction -> function_call -> function_call_output, omitted covered source history and the orphaned function item ID, and received exactlyready. No injected checkpoint, local server, repair bypass, or fallback was used. Redacted request sequence, provider request IDs, assertions, and runnable one-off harness.80864601bf9e6fba4d1cf34a9f1bfabe3516b6adbecause the embedded stream sanitizer removesproviderReplay; 63/63 focused tests pass after the fix. The five new cases check serialized checkpoint/tool/result order, exclusion of covered history, matching repaired IDs, omitted orphan item IDs, and missing-result synthesis. Existing coverage retains prefix-edit invalidation, removal reindexing, compaction-only checkpoints, route/identity barriers, and retained-user handling.autoreviewreviewed the runtime patch and corrected regression fixture through P2. Its staged-only fixture typing finding was resolved with the reviewed role-narrowing fix; no other actionable findings were reported. The reviewed runtime head is unchanged for the fresh proof.git diff --check, core production typechecking, both affected test typecheck graphs (agents-other,packages), type-aware lint on all three changed files, and the focused changed-test gate pass, including repository guards and graph boundaries.Focused tests (8.59 s wall, one worker):
pnpm test src/agents/embedded-agent-runner/run/attempt-tool-call-replay-sanitization.compaction.test.ts packages/ai/src/transports/provider-compaction-replay.test.ts src/agents/embedded-agent-helpers/openai.test.ts src/agents/embedded-agent-runner/run/attempt-tool-call-replay-sanitization.test.ts --maxWorkers=1Measured standalone cost: new regression 4.16 s wall / 1.32 s Vitest; checkpoint-owner suite 4.12 s wall / 2.15 s Vitest. The committed tests use no timers, network calls, or Gateway boots. Fresh one-off live proof: 6.565 s test / 7.54 s Vitest / 8.71 s runner; synthetic input,
gpt-5.2,store:false, compaction threshold 2048, reasoning none. No production Gateway state or customer conversations were changed. Local environment: Amazon Linux 2023 ARM64, Node 26.10.0, pnpm 12.5.1, Vitest 5.0.1.CI follow-up
The original cron shard failure exceeded the 10-second completion watchdog in
src/cron/service.wake-now-real-heartbeat.test.ts, “drains coalesced cron and exec work without recurrence while retaining late arrivals” (10.221 s). The file is unchanged by this PR, injects synthetic replies, and does not execute the changed Responses/checkpoint path.The unchanged PR head passed the exact 50-file manifest with the same CI runner and three workers: 393/393 tests, 50/50 files, 206.94 s Vitest / 208.84 s runner. That case took 7.603 s. This passing reproduction does not prove a fix or establish the timeout's cause. Nearby PRs #160892, #160888, #160887, and #160878 had no matching red when inspected; the latest full main run had different plugin failures. We are not classifying this cron timeout as an inherited failure. No unrelated fix, timeout increase, workflow rerun, or extra push was made.
Limits: the fresh live test proves OpenAI accepts the retained-checkpoint tool continuation, not guaranteed cache hits or reduced billing: provider input usage was 8142 then 8272 tokens, with zero cached tokens in this small case. Historical raw provider bodies remain unavailable, so individual historical misses cannot be certified. This isolated proof does not boot the full Gateway/Workshop loop. Full local build and repository-wide tests were not run. Hosted CI and maintainer review remain authoritative for merge readiness; the original cron CI timeout remains unresolved.
Maintainer verification
Thanks @brandon-julio-t for the report and fix. Refreshed on current main (merge head 17b7322).
Owner check: the change only stops
replaceCompactionReplayOwnerContentfrom dropping a checkpoint when a same-length rewrite leaves every covered prefix block untouched. Whether a stored checkpoint may be replayed is still decided at request time byresolveNewestOpenAIResponsesCompactionReplayagainst the model, base URL, session and auth profile it was captured for, so a stale checkpoint stays unreplayable.Real CLI run: isolated
pnpm openclaw --profile … agent --localsessions (own home, state dir and config) on anopenai-responsesprovider pointed at a local mock Responses server that records request bodies. After two plain turns, the mock answers with an inlinecompactionitem followed by areadcallcall_lookup/fc_lookupwith no reasoning item, so the tool ID needs repair. The checkpoint is captured by the real stream path (the mock returns it inline because the client does not sendcontext_managementto a non-native URL).compactionitemcompaction -> function_call(call_lookup) -> function_call_output, covered turns omitted,fc_*ID still stripped127.0.0.1tolocalhost)All five new sanitizer regression rows fail with the fix reverted and pass with it; the 63 focused tests pass on the merged head.
No overlap with Pash/Sarah changes (no commits by either on the changed files).