Skip to content

fix(ai): restore raw call_id on continuation wire delta, canonicalize for eligibility - #128910

Closed
hartmark wants to merge 4 commits into
openclaw:mainfrom
hartmark:fix/http-continuation-toolcall-id-resanitization
Closed

hartmark wants to merge 4 commits into
openclaw:mainfrom
hartmark:fix/http-continuation-toolcall-id-resanitization

Conversation

@hartmark

@hartmark hartmark commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

HTTP continuation (previous_response_id reuse) never engaged for a multi-round tool-calling turn — confirmed live against a real gateway: every attempt within a single turn resolved to history_changed and fell back to full history, even though the continuation cache held a valid ready baseline and eligibility was satisfied on every call. This defeats the whole point of continuation for exactly the case it should help most (a tool-calling loop, where turns are seconds apart).

Why This Change Was Made

Root-caused via live diagnostic instrumentation against a real gateway. Replaying history for the next round in a tool-calling loop re-sanitizes tool-call ids for provider compatibility (normalizeOpenAIResponsesToolCallIds in embedded-agent-helpers), so a function_call's call_id the client echoes back on round N+1 never matches the raw call_id resolveResponsesContinuationRequest cached straight from the provider's own streamed response on round N (e.g. chatcmpl-tool-20cf1f2f... cached vs call_chatcmpl-tool-20cf1f2f..._d7218567a7 replayed). Separately, the arguments JSON string can pick up different whitespace on a re-JSON.stringify along the same replay path, and the comparison treated that as changed content too since arguments is compared as a raw string, not a parsed value.

Neither is a real change to what the model said — both are expected, necessary reshaping for provider-format compatibility. normalizeAssistantReplayInput already strips id/status from function_call/assistant-message items for exactly this kind of volatility; this extends the same treatment to call_id and arguments — but not with a blanket drop.

Revised from the original patch per review feedback: blanket-dropping call_id from the comparison would have made any changed function-call id look like the known replay reshape, masking a genuinely different tool call. Instead, canonicalizeReplayedCallId reshapes both sides through the exact same transform the replay path applies (normalizeOpenAIResponsesFunctionCallId) and only treats them as equal when they canonicalize to the same value — fail-closed for an unrelated id change (covered by a new regression test). The wire-bound delta then gets the raw provider call_id restored (restoreRawCallIdsInDelta) before it's sent, so a server that reconstructs continuation history from its own cached copy of the raw response still sees a function_call_output whose call_id matches the function_call it cached — instead of an orphaned id it silently drops. The arguments comparison also now runs quoteUnsafeIntegerLiterals before parsing, since plain JSON.parse rounds integers past Number.MAX_SAFE_INTEGER and could otherwise treat two genuinely different large-integer arguments as equal.

Second revision, per ClawSweeper P1 finding (paired call_id|item_id): the previous revision only canonicalized the cached response's bare call_id, but replay pairs the provider's call_id and item id into one call_id|fc_id string before reshaping (normalizeOpenAIResponsesToolCallIds → normalizeOpenAIResponsesFunctionCallId), and the request builder later splits that reshaped pair back into separate wire fields (openai-responses-replay-messages-internal.ts). So a cached raw item like call_id: "functions.gateway:0", id: "fc_tmp" needed to canonicalize via the paired string "functions.gateway:0|fc_tmp", not call_id alone — otherwise the eligibility comparison hashed a different input than replay actually produced and permanently stayed history_changed for any turn whose provider ids needed reshaping (i.e., almost always, since most providers don't return call_*/fc_*-shaped ids natively).

Fixed by reconstructing the same pairing from the cached item's call_id + id before canonicalizing (canonicalizeCachedCallId), mirroring the exact idempotent short-circuit the real replay resolver uses (shouldNormalizeOpenAIResponsesToolCallId) so already provider-shaped ids are left unchanged rather than needlessly re-hashed — the naive "always pair" version broke 8 existing tests in openai-responses-retained-compaction-replay.test.ts where ids were already validly shaped, since pairing two independently-valid ids together and hashing the combined string produces a value replay never generates. restoreRawCallIdsInDelta had the identical bug (built its reshaped→raw lookup from the bare cached call_id only) and got the same fix.

User Impact

A native OpenAI Responses endpoint now actually gets the continuation savings it was designed for during multi-round tool-calling turns, not just across separate inbound messages. Before this fix, continuation only ever worked in the narrow case of zero tool calls in between (a plain text reply), which is not the common case for an agentic run.

(HTTP continuation eligibility on main today is native-endpoint-only — supportsNativeOpenAIResponsesEndpoint. A separate, still-open PR, #128633, proposes extending eligibility to compat-endpoint connections via compat.supportsResponsesContinuation; that opt-in is not part of this PR's scope and needs more investigation before landing, so it's marked draft. This fix is endpoint-agnostic — it repairs the same comparison logic regardless of which eligibility gate lets a request reach it.)

Evidence

  • New regression tests reproduce the exact real-world shapes and assert the correct outcome in three cases: (1) continues a tool-calling round despite replay re-sanitizing call_id and re-serializing arguments, and restores the raw call_id on the wire delta — bare vs re-sanitized, paired call_id|fc_id (verified against the real normalizeOpenAIResponsesFunctionCallId transform on the paired string, not hand-approximated) plus differently-whitespaced arguments, asserting continuationStatus: "continued" and that the wire delta carries the raw call_id, not the reshaped one; (2) does not tolerate an unrelated function-call id change as the known replay reshape — an unrelated call_id change still correctly falls back to history_changed; (3) does not treat two different unsafe-integer arguments as equal (lossless comparison) — two different integers above Number.MAX_SAFE_INTEGER are not conflated.
  • Confirmed test (1)'s current, paired-id fixture fails on the code from the first revision (bare-call_id-only canonicalization) for the exact right reason (history_changed), and passes with the paired-canonicalization fix.
  • Full packages/ai/src/transports/ suite green: 737/737 tests, 49 files (includes openai-responses-retained-compaction-replay.test.ts, which exercises the real end-to-end AgentMessage → wire conversion pipeline with already-valid call_*/fc_* ids and caught the "naive always-pair" bug in an earlier iteration of this fix before landing the idempotent-short-circuit version above).
  • src/agents/embedded-agent-helpers/openai.test.ts (the real normalizeOpenAIResponsesToolCallIds unit suite this fix mirrors): 10/10 passing.
  • oxfmt --check and oxlint clean on both changed files.
  • Autoreview (Codex, gpt-5.6-sol, high): clean, no accepted/actionable findings, "patch is correct (0.98)".
  • Live-verified end-to-end on a deployment carrying this fix stacked with feat(ai): opt compatible Responses endpoints into stored HTTP continuation #128633's compat opt-in (against a self-hosted OpenAI-Responses-compatible connection, since a native OpenAI endpoint wasn't available for live testing): a multi-round tool-calling turn's later model call carried previous_response_id with a small input delta instead of the full accumulated history, confirmed via the upstream proxy's own request logs.

Update: fixed the P1 type-collision finding (unsafe integer vs. same-digits string)

quoteUnsafeIntegerLiterals converts an unsafe integer literal into a bare quoted string before JSON.parse, so the argument comparator's normalized output for {"n":9007199254740993} (a number) and {"n":"9007199254740993"} (a string) was byte-identical — a real number-to-string argument change wrongly compared equal, letting continuation reuse stale server-side state against a genuinely different tool call.

Fixed by adding an optional tag parameter to the shared quoteUnsafeIntegerLiterals (default "", so every other caller — including the other real callers in transport-stream-shared.ts and anthropic-transport-stream.ts via the wrapper functions — is unaffected), and passing a control-character-prefixed tag from normalizeFunctionCallArguments so a stringified unsafe integer can never collide with a genuine string holding the same digits.

New regression test: "does not treat an unsafe-integer argument as equal to a same-digits string (type collision)". Confirmed it fails pre-fix (expected 'continued' to be 'history_changed') and passes post-fix.

Proof: openai-responses-continuation.test.ts 10/10 (was 9/9, +1 new); full packages/ai/src/transports suite 738/738 (confirms the backward-compatible default doesn't change any other caller's behavior); oxfmt clean; autoreview (gpt-5.6-sol, high) clean, no accepted findings, patch correct 0.96.

Update: the type-collision tag was itself wrong -- reverted, with a real live-endpoint regression it caught

Addresses ClawSweeper's P2 finding on the previous head (native-endpoint real behavior proof missing for the type-collision fix). Two bugs found:

1. Mechanical: UNSAFE_INTEGER_COMPARISON_TAG was defined as "openclaw-unsafe-integer" -- a literal control character once evaluated at runtime, not its JSON-escaped form. quoteUnsafeIntegerLiterals interpolates the tag directly between the JSON quote characters it emits, so the produced text was invalid JSON; JSON.parse threw and the catch silently fell back to the untagged comparison the tag exists to replace. New regression test (treats a whitespace-only re-serialization of the same unsafe integer as equal) failed pre-fix for exactly this reason.

2. Deeper, found live while proving fix (1): even once the tag was valid JSON, testing it against a real multi-round tool call over api.openai.com showed continuation still breaking on the very next round. Root cause: AssistantMessage.arguments already stores every unsafe integer as a string (parseJsonObjectPreservingUnsafeIntegers, transport-stream-shared.ts -- precision-preserving, since a JS number can't hold it losslessly). So an unmodified replay of a real tool call's argument always re-serializes as a same-digits string, compared against the cached side's raw provider text (a bare number). Tagging only the cached side made this look like a real type change on every single out-of-range-integer tool call, permanently breaking continuation for the very next round -- not a rare edge case, but the common case for timestamps, snowflake IDs, and similar large-integer arguments.

The type-collision concern the tag was solving doesn't actually apply to this comparison: both sides replay the same historical tool call (not two independent model outputs), so there's no second, unrelated call for a same-digit string to collide with -- the risk the tag guarded against can't occur here.

Fix: reverted normalizeFunctionCallArguments to plain (untagged) quoteUnsafeIntegerLiterals, which still correctly distinguishes two genuinely different unsafe integers (the original lossless-comparison fix, unaffected). Removed the now-unused tag parameter from quoteUnsafeIntegerLiterals itself (no other caller used it). Deleted the now-incorrect "type collision" unit test and replaced it with treats a cached number-typed unsafe integer as equal to its own replayed string-typed round-trip, proving the realistic case.

Proof:

  • New live test openai-responses-client.continuation-unsafe-integer.live.test.ts, gated on OPENCLAW_LIVE_TEST=1 + OPENAI_API_KEY, against real https://api.openai.com/v1: a real tool call with n=9007199254740993 (> Number.MAX_SAFE_INTEGER), replayed unmodified. Failed before this fix (fell through to a full-history resend, no previous_response_id); passes after (continues correctly, and the wire delta's call_id is correctly restored to the bare provider id).
  • openai-responses-continuation.test.ts: 11/11.
  • Full packages/ai/src/transports/ suite: 739/739 (49 files) -- confirms removing the tag parameter doesn't change any other caller.
  • src/agents/embedded-agent-helpers/openai.test.ts: 10/10.
  • oxfmt clean.
  • Net effect on production LOC: the tag mechanism is removed entirely (fewer lines than the previous head), addressing the earlier P1 finding about production growth for this change.

@clawsweeper re-review

Update: attaching the actual raw trace + production LOC justification

Addresses ClawSweeper's remaining P1/P2 findings: the prior update only narrated the live test's pass/fail rather than including the checkable raw output, and the production LOC growth needed an explicit justification rather than a bare summary.

Raw trace, exact head, real api.openai.com (paths sanitized to repo-relative):

$ OPENCLAW_LIVE_TEST=1 OPENAI_API_KEY=*** pnpm test:live \
    packages/ai/src/transports/openai-responses-client.continuation-unsafe-integer.live.test.ts

 RUN  v4.1.11 <repo>

 ✓ openai-responses-client.continuation-unsafe-integer.live.test.ts > HTTP continuation across a real unsafe-integer tool-call argument (real api.openai.com) > continues a real tool-calling round whose argument is above Number.MAX_SAFE_INTEGER 4418ms

 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  16:18:05
   Duration  8.10s (transform 1.66s, setup 1.86s, import 1.03s, tests 4.42s, environment 0ms)

This is the second-request recovery the finding asks about: a real tool call with n=9007199254740993 (> Number.MAX_SAFE_INTEGER), replayed unmodified on round 2, correctly carries previous_response_id and the restored raw call_id -- proven against the real endpoint, not a mock.

Production LOC (net +154, openai-responses-continuation.ts +144/-5, openai-responses-tool-call-id-shape.ts +88 new, embedded-agent-helpers/openai.ts +6/-82):

The embedded-agent-helpers/openai.ts delta is a real net reduction there (-76) -- its own id-shaping logic moved into the new shared file. That extraction is necessary, not optional: packages/ai cannot import from src/agents (core-boundary rule -- packages/ai is the lower-level package src/agents builds on, not the reverse), so the continuation resolver needs its own copy of the exact id-shaping transform to canonicalize a cached raw id against what replay will produce, or the comparison silently uses a different transform than what's actually applied on the wire. openai-responses-tool-call-id-shape.ts is that necessary mirror, sized to the transform it mirrors.

The remaining growth in openai-responses-continuation.ts (+144/-5) is the actual fix: canonicalizeReplayedCallId/canonicalizeCachedCallId (comparison-side canonicalization, fail-closed on an unrelated id change -- covered by its own regression test) and restoreRawCallIdsInDelta (restoring the provider's raw id on the wire delta, so a server reconstructing history from its own cached raw response can still pair a function_call_output against the function_call it cached). Both are the specific mechanism this PR exists to add; there isn't a smaller shape that preserves fail-closed behavior on a genuinely different id while forgiving only the known replay reshape.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@hartmark
hartmark marked this pull request as ready for review August 25, 2026 00:03
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 25, 2026
@clawsweeper

clawsweeper Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed August 31, 2026, 2:54 PM ET / 18:54 UTC.

ClawSweeper review

What this changes

The PR canonicalizes replayed OpenAI Responses tool-call IDs and equivalent JSON arguments for continuation eligibility, then restores the provider’s original call ID in the trimmed follow-up request.

Regression provenance

Possible regression — probable (reviewed change; failure trace). No predecessor PR is attributed.

Merge readiness

⛔ Blocked until stronger real behavior proof is added - 4 items remain

Keep open: the source repair is coherent and unit-covered, but the supplied native-endpoint trace explicitly bypasses the new call-ID canonicalization and raw-ID restoration branch, so real behavior proof remains incomplete.

Priority: P2
Reviewed head: 9c4e49af161208d20f189834345ffecbed3c93f4

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch has credible focused coverage and a partial real-endpoint trace, but its central wire-ID compatibility behavior lacks real boundary proof.
Proof confidence 🦐 gold shrimp (3/6) Needs stronger real behavior proof before merge: The changed production owner is the HTTP continuation resolver. The supplied exact-head terminal trace shows a real native OpenAI unsafe-integer tool round continuing with two requests, but the test itself says native IDs short-circuit normalization, so it does not exercise or observe the introduced raw-ID restoration path. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: The changed production owner is the HTTP continuation resolver. The supplied exact-head terminal trace shows a real native OpenAI unsafe-integer tool round continuing with two requests, but the test itself says native IDs short-circuit normalization, so it does not exercise or observe the introduced raw-ID restoration path. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 6 items Current-main behavior: Current main strips volatile item IDs but retains raw function-call IDs and raw argument strings during continuation-prefix comparison, so replay normalization can produce history drift.
Replay producer: The agent replay boundary normalizes paired tool-call identifiers before serializing Responses history, which is the owner-side transformation the continuation comparator must recognize.
Proposed repair and regression coverage: The branch compares cached paired IDs through the shared shaping helper and rewrites only the trimmed delta back to the cached raw ID; focused tests cover the reshaped pair, unrelated-ID rejection, and unsafe-integer preservation.
Findings None None.
Security None None.

How this fits together

OpenAI Responses continuation caches a provider response so a following tool-result round can send only a delta using previous_response_id. Agent replay normalizes tool-call IDs, while the transport must compare that replay safely and preserve the provider-compatible ID on the outgoing delta.

flowchart LR
A[Provider response] --> B[Continuation cache]
C[Agent replay history] --> D[ID and argument normalization]
B --> E[Continuation eligibility comparison]
D --> E
E --> F[Trimmed follow-up request]
F --> G[OpenAI Responses endpoint]
Loading

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: The changed production owner is the HTTP continuation resolver. The supplied exact-head terminal trace shows a real native OpenAI unsafe-integer tool round continuing with two requests, but the test itself says native IDs short-circuit normalization, so it does not exercise or observe the introduced raw-ID restoration path. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Resolve merge risk (P1) - The supplied live trace does not exercise the new transformed-ID-to-raw-ID delta restoration, leaving compatibility with a server that pairs against its cached raw function call unproven.
  • Resolve merge risk (P1) - Production code is net +154 lines; the shared helper removes the prior agent-side duplicate, but the additional comparison and restoration logic should earn that complexity with production-boundary proof.
  • Complete next step (P2) - The remaining blocker is contributor-supplied real behavior proof rather than a bounded automated repair.
Agent review details

Security

None.

PR surface

Source +154, Tests +383. Total +537 across 7 files.

View PR surface stats
Area Files Added Removed Net
Source 5 242 88 +154
Tests 2 383 0 +383
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 625 88 +537

Review metrics

Metric Value Why it matters
Production versus test delta production +242/-88 (net +154); tests +383/-0 The shared ID-shaping extraction offsets part of the new continuation logic, but the remaining production growth needs the missing boundary proof to justify landing.

Merge-risk options

Maintainer options:

  1. Prove the transformed-ID delta (recommended)
    Capture a redacted production-boundary run with a real transport client and injected raw provider ID that shows the replayed ID and the emitted delta’s restored raw ID.
  2. Keep the draft paused
    Leave this PR in draft until that trace is available, preserving the unit-covered repair without asserting endpoint compatibility prematurely.

Technical review

Best possible solution:

Retain the strict history-change fallback until a production-boundary trace proves that a replay-normalized tool-call ID is converted back to the cached provider ID in the emitted continuation delta.

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

Yes, source-reproducible: current main compares cached raw function-call IDs against replayed normalized IDs, and the focused branch test models the resulting history_changed path. The supplied real-endpoint trace additionally proves the unsafe-integer half, but not the transformed-ID branch.

Is this the best way to solve the issue?

Unclear: sharing the ID-shaping transform is the right ownership direction and focused tests cover the intended invariant, but the best end-to-end solution is not proven until the changed wire-restoration branch is observed through the transport boundary.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This repairs a bounded provider-continuation path, with no evidence of data loss, security bypass, or core-runtime outage.
  • merge-risk: 🚨 compatibility: The patch changes when existing sessions reuse server-side Responses state and changes the tool-call ID emitted in the continuation delta.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: The changed production owner is the HTTP continuation resolver. The supplied exact-head terminal trace shows a real native OpenAI unsafe-integer tool round continuing with two requests, but the test itself says native IDs short-circuit normalization, so it does not exercise or observe the introduced raw-ID restoration path. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

Likely related people:

  • hartmark: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Add a redacted production-boundary trace that exercises a normalized replay ID and shows the emitted delta restores the cached raw provider ID.

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.

History

Review history (8 earlier review cycles)
  • reviewed 2026-08-25T00:09:25.394Z sha c07a9be09780ffb623e1573411ad999ac0d89564 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-25T00:52:29.375Z sha c07a9be09780ffb623e1573411ad999ac0d89564 :: needs real behavior proof before merge. :: [P1] Keep argument comparison lossless before reusing the response | [P1] Do not ignore arbitrary function-call IDs
  • reviewed 2026-08-26T13:26:09.643Z sha 75664a5 :: needs real behavior proof before merge. :: [P1] Canonicalize call IDs with their paired item IDs
  • reviewed 2026-08-26T13:53:52.881Z sha 75664a5 :: needs real behavior proof before merge. :: [P1] Canonicalize call IDs with their paired item IDs
  • reviewed 2026-08-28T11:35:34.711Z sha f9508ca :: needs changes before merge. :: [P1] Preserve JSON type when canonicalizing unsafe integers
  • reviewed 2026-08-29T19:22:48.260Z sha f4fb84f :: needs real behavior proof before merge. :: [P2] Keep the unsafe-integer marker valid JSON
  • reviewed 2026-08-31T14:31:18.304Z sha 9c4e49a :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-31T17:31:41.117Z sha 9c4e49a :: needs real behavior proof before merge. :: none

@hartmark hartmark changed the title fix(ai): tolerate call-id resanitization and arg re-serialization in continuation replay fix(ai): restore raw call_id on continuation wire delta, canonicalize for eligibility Aug 26, 2026
@hartmark
hartmark force-pushed the fix/http-continuation-toolcall-id-resanitization branch from c07a9be to 75664a5 Compare August 26, 2026 13:21
@hartmark

Copy link
Copy Markdown
Contributor Author

Addressed both P1 findings:

  1. Lossless argument comparison — normalizeFunctionCallArguments now runs quoteUnsafeIntegerLiterals before JSON.parse, so two different integers above Number.MAX_SAFE_INTEGER no longer compare equal. New regression test covers it.
  2. Don't ignore arbitrary function-call IDs — replaced the blanket call_id drop with canonicalizeReplayedCallId, which reshapes both sides through the exact replay transform and only treats them as equal when they canonicalize to the same value (fail-closed for an unrelated change — new regression test covers it). The wire-bound delta now gets the raw provider call_id restored before sending (restoreRawCallIdsInDelta), since a server that reconstructs continuation history from its own cached raw response needs the id to match what it cached, not the client's local reshape.

Also corrected the PR body: HTTP continuation eligibility on main is native-endpoint-only today (the compat-endpoint opt-in is #128633, separately still under review) — the body previously implied that opt-in already existed here.

Rebased onto latest main, full transports suite green (828/828), autoreview clean.

Converting to draft — this sits in the same continuation-eligibility area as #128848 and #128633, and the whole area needs more investigation (there's a separate, still-unresolved rendering-mismatch mechanism that independently causes history_changed on some heartbeat/orphan-repair turns) before any of these land. Will re-request review once that's sorted.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 26, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

@hartmark
hartmark marked this pull request as draft August 26, 2026 13:21
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M and removed size: S labels Aug 26, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 26, 2026
@hartmark

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 26, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

… for eligibility

normalizeOpenAIResponsesToolCallIds re-sanitizes call_id for provider-format
compatibility on replay, which previously made the eligibility check either
reject every multi-round tool-calling turn (blanket compare) or, after a
prior loosening, blanket-drop call_id from the comparison entirely -- letting
an unrelated changed function-call id through as if it were the known reshape,
and shipping the client's reshaped call_id instead of the raw provider id on
the wire delta. A server that reconstructs continuation history server-side
from its own cached raw response (e.g. a proxy virtualizing previous_response_id)
pairs function_call_output against the function_call it cached verbatim, so
the reshaped call_id reads as orphaned and the tool result gets dropped.

Canonicalize call_id/fc_id through the same reshape for the eligibility
comparison (fail-closed: only forgives ids that reshape TO the cached raw
id, never an arbitrary difference), and restore the raw provider id on the
wire-bound delta before it's sent. Also fixes a lossless-integer gap in the
arguments comparison (distinct unsafe integers could round to the same JS
number under plain JSON.parse and wrongly compare equal).
…inuation eligibility

Replay reshapes a function_call's id by pairing call_id and item id into
one call_id|fc_id string before hashing (normalizeOpenAIResponsesToolCallIds).
The continuation eligibility comparison and the raw-id restore path only
canonicalized the cached response's bare call_id, ignoring its paired item
id, so they hashed a different input than replay actually produced and
permanently returned history_changed for any turn whose provider ids needed
reshaping.

Reconstruct the same call_id|item_id pairing from the cached raw response
before canonicalizing, mirroring the exact idempotent short-circuit replay's
own resolver uses so already provider-shaped ids are left unchanged.
@hartmark
hartmark force-pushed the fix/http-continuation-toolcall-id-resanitization branch from 75664a5 to f9508ca Compare August 28, 2026 11:25
@hartmark

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 28, 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 exact_review_queue).
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 proof: sufficient ClawSweeper judged the real behavior proof convincing. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 28, 2026
@clawsweeper clawsweeper Bot added the status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. label Aug 28, 2026
…ontinuation comparisons

quoteUnsafeIntegerLiterals converted an unsafe integer literal into a bare
quoted string before JSON.parse, so a genuine JSON string holding the same
digits normalized identically. A real number-to-string argument change
(e.g. {"n":9007199254740993} -> {"n":"9007199254740993"}) wrongly compared
equal, letting continuation reuse stale server-side state for a changed
tool call. Adds an optional tag parameter to the shared helper (default
unchanged, so every other caller is unaffected) and uses it to keep the
two cases distinguishable in the continuation argument comparator.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6
@hartmark

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 29, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 29, 2026
…arge-integer tool call

Two bugs found while chasing ClawSweeper's P2 real-behavior-proof
request for the unsafe-integer type-collision fix (previous head):

1. Mechanical: UNSAFE_INTEGER_COMPARISON_TAG embedded literal control
   characters into JSON text, so JSON.parse threw and normalizeFunctionCallArguments's
   catch silently fell back to the untagged comparison the tag exists to
   replace -- confirmed via a new regression test (fails pre-fix with
   `expected 'history_changed' to be 'continued'`, a whitespace-only
   re-serialization of the same value wrongly compared as changed).

2. Deeper, found by testing the fix for (1) live against a real
   multi-round tool call: the tag's whole premise -- distinguishing a
   converted unsafe integer from a genuine same-digits string -- doesn't
   hold for this comparison. AssistantMessage.arguments already stores
   every unsafe integer as a string (parseJsonObjectPreservingUnsafeIntegers,
   transport-stream-shared.ts, precision-preserving), so an *unmodified*
   replay of a real tool call's argument always re-serializes it as a
   same-digits string against the cached raw provider number. Tagging
   only the cached side made every real out-of-range-integer tool call
   permanently ineligible for continuation on its very next round --
   confirmed live: a real tool call with n=9007199254740993, replayed
   unmodified, fell through to a full-history resend before this fix and
   continues correctly after it.

Both sides of this comparison replay the *same* historical tool call
(not two independent model outputs), so the type-collision risk the tag
was guarding against doesn't apply here: there's no second, unrelated
call for a same-digit string to collide with. Reverted
normalizeFunctionCallArguments to plain (untagged) quoteUnsafeIntegerLiterals,
which still correctly distinguishes two genuinely DIFFERENT unsafe
integers (the original lossless-comparison fix this PR keeps), and
removed the now-unused tag parameter from quoteUnsafeIntegerLiterals
itself (no other caller used it).

Net effect: removes the tag mechanism entirely (fewer production lines
than before), deletes the now-incorrect "type collision" unit test,
and replaces it with a test proving the realistic round-trip case
continues correctly, backed by a new live test against the real native
api.openai.com endpoint (the sibling live test this PR's evidence was
missing per ClawSweeper's prior review).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6
@hartmark

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Found and fixed two real bugs while chasing the P2 native-endpoint proof request:

  1. The comparison tag contained literal control characters (not JSON-escaped), so JSON.parse threw on it and the whole mechanism silently no-op'd.
  2. Deeper: even fixed, tagging only the cached side broke continuation for every real out-of-range-integer tool call, since AssistantMessage.arguments always stores unsafe integers as strings — an unmodified replay of any such call always looked like a type change. Reverted to untagged comparison (both sides replay the same historical call, so the type-collision risk the tag guarded against doesn't apply here).

New live test against real api.openai.com proves the fix (fails pre-fix, passes post-fix). Net production LOC is now a reduction versus the previous head.

@clawsweeper

clawsweeper Bot commented Aug 31, 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 exact_review_queue).
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 the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Aug 31, 2026
@hartmark

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Added the actual raw terminal output for the live api.openai.com trace (was previously narrated only), and an explicit justification for the production LOC growth: the new shared file is a necessary mirror (packages/ai can't import from src/agents), and the remaining growth is the fail-closed comparison/restoration logic itself, with no smaller shape available that preserves correctness on a genuinely different id.

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 31, 2026
@clawsweeper

clawsweeper Bot commented Aug 31, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

@clawsweeper

clawsweeper Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@hartmark

Copy link
Copy Markdown
Contributor Author

Splitting per ClawSweeper's own suggested alternative on this PR ("split the proven unsafe-integer repair from the deferred raw-ID compatibility work").

Investigated the raw-ID branch's proof gap directly: this PR's httpContinuationEligible gate only recognizes a genuine native api.openai.com connection, and native OpenAI's own tool-call ids are always already call_*/fc_*-shaped -- so the reshape/restore code is a provable no-op on this PR's own scope. Confirmed by adding temporary debug logging and re-running a scripted-server test against a custom-endpoint model: the continuation resolver is never even called for that connection here. There's no live request, real or scripted, that can exercise this branch until eligibility widens to custom/proxy endpoints (#128633's scope, not this PR's).

Replaced by two PRs:

Closing this one in favor of those.

@hartmark hartmark closed this Aug 31, 2026
hartmark added a commit to hartmark/openclaw that referenced this pull request Aug 31, 2026
… in live test

Real CI failure (check-test-types-core-1), not caught earlier because
.live.test.ts files aren't in the broad tsgo:core lane I'd checked --
they are covered by the sharded tsgo:core:test lane CI actually runs.
Pre-existing since this file's creation on openclaw#128910, unrelated to this
PR's own changes; fixed here since it's now blocking this PR's CI and
I'm already touching the file.

toolResultMsg was missing toolName and isError, both required on
ToolResultMessage<unknown>. Added toolName: "record_value" (matching
the tool actually called) and isError: false (the recorded result is
a success).
steipete added a commit that referenced this pull request Sep 1, 2026
…ts (#134423)

* fix(ai): lossless unsafe-integer comparison for tool-call argument replay in HTTP continuation

Split from #128910 per ClawSweeper's own suggested alternative: this is
the proven half (the raw-ID reshape/restore half is deferred, blocked on
custom-endpoint eligibility -- see the follow-up PR).

A real, multi-round tool-calling turn on a native api.openai.com
connection loses HTTP continuation whenever the tool call's argument
contains an integer literal above Number.MAX_SAFE_INTEGER (timestamps,
snowflake IDs, etc). AssistantMessage.arguments already stores every
unsafe integer as a string (parseJsonObjectPreservingUnsafeIntegers,
precision-preserving), so an unmodified replay of the same historical
tool call always re-serializes it as a same-digits string against the
cached side's raw provider number -- without normalization this reads
as a real content change and falls back to a full-history resend.

quoteUnsafeIntegerLiterals (existing helper) run before the
parse/stringify comparison round-trip fixes both directions: two
genuinely different large integers stay distinguishable (lossless), and
a same-digits number-vs-string round-trip of the same historical call
compares equal. No distinguishing tag needed: both sides of this
comparison replay the *same* historical tool call, not two independent
model outputs, so there's no second call for a same-digit string to
collide with.

* test(ai): prove the raw wire arguments were a bare unsafe integer, not a quoted string

ClawSweeper P2 on this PR: the live test only asserted on
AssistantMessage.arguments after OpenClaw's own terminal parser
(parseJsonObjectPreservingUnsafeIntegers) had already converted the
unsafe integer into a string -- identical whether the provider sent a
real bare 9007199254740993 (the regression this fix repairs) or the
model quoted it as a string itself (already handled correctly
pre-fix). The test couldn't distinguish those two cases, so it didn't
actually prove the claimed regression path.

GlobalFetchRequestCapture now tees each captured response's SSE body
(ReadableStream.tee(), so the real SDK consumer is never disturbed)
and extractRawFunctionCallArguments pulls the raw arguments string out
of the response.function_call_arguments.done event -- the exact bytes
the provider sent, before any parsing. The test asserts that raw text
matches a bare, unquoted integer literal and explicitly asserts it
does NOT match a quoted-string shape.

Verified live: raw wire text for the tool call was exactly
{"n":9007199254740993} -- a genuine bare literal, confirming this
proves the real regression path, not an inferred one.

Also fixed a pre-existing (unrelated) oxlint no-unsafe-optional-chaining
finding a few lines below in the same file, found while already here.

* fix(ai): satisfy ToolResultMessage's required toolName/isError fields in live test

Real CI failure (check-test-types-core-1), not caught earlier because
.live.test.ts files aren't in the broad tsgo:core lane I'd checked --
they are covered by the sharded tsgo:core:test lane CI actually runs.
Pre-existing since this file's creation on #128910, unrelated to this
PR's own changes; fixed here since it's now blocking this PR's CI and
I'm already touching the file.

toolResultMsg was missing toolName and isError, both required on
ToolResultMessage<unknown>. Added toolName: "record_value" (matching
the tool actually called) and isError: false (the recorded result is
a success).

* fix(ai): await the raw SSE capture before reading it in the live test

ClawSweeper P2: the response.body.tee() capture branch was read in a
fire-and-forget async IIFE, populating rawResponseTexts[i] in the
background while fetch() itself already resolved. The test read
rawResponseTexts[0] immediately after the request completed, racing
the background reader -- a pass didn't reliably prove the raw-wire
assertion actually saw the real captured text, only that it got lucky
on scheduling.

GlobalFetchRequestCapture now exposes captureCompletions (one promise
per captured response, parallel to rawResponseTexts), and the test
explicitly awaits captureCompletions[0] before reading
rawResponseTexts[0]. The real SDK consumer is still never blocked --
only the test's own inspection of the capture branch waits.

Verified live, 3 consecutive runs: deterministic pass each time.

* fix(ai): normalize only admitted Responses output

Match cached provider function-call output to the existing lossless terminal admission and replay serialization, while keeping previously sent and newly edited argument text strict. Prove unsafe-integer continuation and value/type edits through the actual SDK over HTTP SSE and cached WebSocket transports.

Co-authored-by: Markus Hartung <[email protected]>

---------

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: Markus Hartung <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 2, 2026
…ts (openclaw#134423)

* fix(ai): lossless unsafe-integer comparison for tool-call argument replay in HTTP continuation

Split from openclaw#128910 per ClawSweeper's own suggested alternative: this is
the proven half (the raw-ID reshape/restore half is deferred, blocked on
custom-endpoint eligibility -- see the follow-up PR).

A real, multi-round tool-calling turn on a native api.openai.com
connection loses HTTP continuation whenever the tool call's argument
contains an integer literal above Number.MAX_SAFE_INTEGER (timestamps,
snowflake IDs, etc). AssistantMessage.arguments already stores every
unsafe integer as a string (parseJsonObjectPreservingUnsafeIntegers,
precision-preserving), so an unmodified replay of the same historical
tool call always re-serializes it as a same-digits string against the
cached side's raw provider number -- without normalization this reads
as a real content change and falls back to a full-history resend.

quoteUnsafeIntegerLiterals (existing helper) run before the
parse/stringify comparison round-trip fixes both directions: two
genuinely different large integers stay distinguishable (lossless), and
a same-digits number-vs-string round-trip of the same historical call
compares equal. No distinguishing tag needed: both sides of this
comparison replay the *same* historical tool call, not two independent
model outputs, so there's no second call for a same-digit string to
collide with.

* test(ai): prove the raw wire arguments were a bare unsafe integer, not a quoted string

ClawSweeper P2 on this PR: the live test only asserted on
AssistantMessage.arguments after OpenClaw's own terminal parser
(parseJsonObjectPreservingUnsafeIntegers) had already converted the
unsafe integer into a string -- identical whether the provider sent a
real bare 9007199254740993 (the regression this fix repairs) or the
model quoted it as a string itself (already handled correctly
pre-fix). The test couldn't distinguish those two cases, so it didn't
actually prove the claimed regression path.

GlobalFetchRequestCapture now tees each captured response's SSE body
(ReadableStream.tee(), so the real SDK consumer is never disturbed)
and extractRawFunctionCallArguments pulls the raw arguments string out
of the response.function_call_arguments.done event -- the exact bytes
the provider sent, before any parsing. The test asserts that raw text
matches a bare, unquoted integer literal and explicitly asserts it
does NOT match a quoted-string shape.

Verified live: raw wire text for the tool call was exactly
{"n":9007199254740993} -- a genuine bare literal, confirming this
proves the real regression path, not an inferred one.

Also fixed a pre-existing (unrelated) oxlint no-unsafe-optional-chaining
finding a few lines below in the same file, found while already here.

* fix(ai): satisfy ToolResultMessage's required toolName/isError fields in live test

Real CI failure (check-test-types-core-1), not caught earlier because
.live.test.ts files aren't in the broad tsgo:core lane I'd checked --
they are covered by the sharded tsgo:core:test lane CI actually runs.
Pre-existing since this file's creation on openclaw#128910, unrelated to this
PR's own changes; fixed here since it's now blocking this PR's CI and
I'm already touching the file.

toolResultMsg was missing toolName and isError, both required on
ToolResultMessage<unknown>. Added toolName: "record_value" (matching
the tool actually called) and isError: false (the recorded result is
a success).

* fix(ai): await the raw SSE capture before reading it in the live test

ClawSweeper P2: the response.body.tee() capture branch was read in a
fire-and-forget async IIFE, populating rawResponseTexts[i] in the
background while fetch() itself already resolved. The test read
rawResponseTexts[0] immediately after the request completed, racing
the background reader -- a pass didn't reliably prove the raw-wire
assertion actually saw the real captured text, only that it got lucky
on scheduling.

GlobalFetchRequestCapture now exposes captureCompletions (one promise
per captured response, parallel to rawResponseTexts), and the test
explicitly awaits captureCompletions[0] before reading
rawResponseTexts[0]. The real SDK consumer is still never blocked --
only the test's own inspection of the capture branch waits.

Verified live, 3 consecutive runs: deterministic pass each time.

* fix(ai): normalize only admitted Responses output

Match cached provider function-call output to the existing lossless terminal admission and replay serialization, while keeping previously sent and newly edited argument text strict. Prove unsafe-integer continuation and value/type edits through the actual SDK over HTTP SSE and cached WebSocket transports.

Co-authored-by: Markus Hartung <[email protected]>

---------

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: Markus Hartung <[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 merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: L status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant