Skip to content

Commit 9c4e49a

Browse files
hartmarkclaude
andcommitted
fix(ai): remove the unsafe-integer comparison tag -- it broke every large-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
1 parent f4fb84f commit 9c4e49a

4 files changed

Lines changed: 240 additions & 27 deletions

File tree

‎packages/ai/src/transports/json-unsafe-integers.ts‎

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -78,17 +78,8 @@ function isUnsafeIntegerLiteral(token: string): boolean {
7878

7979
/**
8080
* Quotes integer literals above Number.MAX_SAFE_INTEGER before JSON.parse.
81-
*
82-
* The optional `tag` is prefixed inside the quotes around each converted
83-
* literal. Every real caller of this function wants the plain digit string
84-
* back and leaves `tag` at its default `""`. A caller that instead compares
85-
* two independently-serialized payloads needs `tag` non-empty: without it, a
86-
* quoted unsafe integer is byte-identical to a genuine JSON string holding
87-
* the same digits, so a real number-to-string argument change would compare
88-
* equal to the unchanged number. A control character a caller can't type
89-
* makes that collision impossible.
9081
*/
91-
export function quoteUnsafeIntegerLiterals(input: string, tag = ""): string {
82+
export function quoteUnsafeIntegerLiterals(input: string): string {
9283
let out = "";
9384
let inString = false;
9485
let escaped = false;
@@ -120,7 +111,7 @@ export function quoteUnsafeIntegerLiterals(input: string, tag = ""): string {
120111
const parsed = parseJsonNumberToken(input, idx);
121112
if (parsed) {
122113
if (parsed.isInteger && isUnsafeIntegerLiteral(parsed.token)) {
123-
out += `"${tag}${parsed.token}"`;
114+
out += `"${parsed.token}"`;
124115
} else {
125116
out += parsed.token;
126117
}
Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
import type { AssistantMessage, Context, Model } from "@openclaw/llm-core";
2+
import { afterEach, describe, expect, it } from "vitest";
3+
import { cleanupSessionResources } from "../session-resources.js";
4+
import { createOpenAIResponsesTransportStreamFn } from "./openai-responses-client.js";
5+
6+
// Live coverage, against the real native api.openai.com endpoint, for the
7+
// argument-canonicalization half of this PR: HTTP continuation must still
8+
// hold across a real multi-round tool-calling turn whose argument contains
9+
// an integer value ABOVE Number.MAX_SAFE_INTEGER. This isolates the
10+
// native-only path this PR's own code (claimOpenAIResponsesHttpContinuation)
11+
// actually gates on, rather than the stack this PR's prior live evidence
12+
// used, which also carried #128633's separate compat-endpoint opt-in.
13+
//
14+
// This test caught a real regression on first run: an earlier revision of
15+
// this fix tagged the cached side's unsafe integer to distinguish it from a
16+
// genuine same-digits string, but AssistantMessage.arguments already stores
17+
// every unsafe integer as a string (parseJsonObjectPreservingUnsafeIntegers,
18+
// precision-preserving), so an *unmodified* replay of this exact call always
19+
// re-serializes it as a same-digits string -- tagging only the cached side
20+
// made every real large-integer tool call permanently ineligible for
21+
// continuation on its very next round. Confirmed live: this test failed
22+
// (fell through to a full-history resend) before that tag was removed, and
23+
// passes now. See the unit regression test with the same shape
24+
// (`treats a cached number-typed unsafe integer as equal to its own
25+
// replayed string-typed round-trip`) for the deterministic version of this
26+
// proof.
27+
//
28+
// (The call_id-reshaping half of this PR is not exercisable here: a real
29+
// native OpenAI tool-call id already arrives in the call_*/fc_*-paired shape
30+
// normalizeOpenAIResponsesToolCallIds produces, so its idempotent
31+
// short-circuit correctly leaves it unchanged -- an earlier version of this
32+
// test asserted the id WOULD change and failed for exactly that reason.
33+
// That half stays covered by the existing unit tests using the real
34+
// transform function directly.)
35+
const LIVE = process.env.OPENCLAW_LIVE_TEST === "1";
36+
const OPENAI_KEY = process.env.OPENAI_API_KEY ?? "";
37+
const describeLive = LIVE && OPENAI_KEY ? describe : describe.skip;
38+
const LIVE_MODEL_ID = process.env.OPENCLAW_LIVE_RESPONSES_MODEL || "gpt-5.6-luna";
39+
const LIVE_TIMEOUT_MS = 120_000;
40+
41+
class GlobalFetchRequestCapture {
42+
readonly requests: Array<Record<string, unknown>> = [];
43+
private readonly realFetch = globalThis.fetch;
44+
45+
install(): void {
46+
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
47+
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
48+
const body = init?.body;
49+
if (url.includes("api.openai.com") && typeof body === "string") {
50+
try {
51+
this.requests.push(JSON.parse(body) as Record<string, unknown>);
52+
} catch {
53+
// Non-JSON body on this host is unexpected for a Responses call.
54+
}
55+
}
56+
return this.realFetch(input, init);
57+
}) as typeof fetch;
58+
}
59+
60+
restore(): void {
61+
globalThis.fetch = this.realFetch;
62+
}
63+
}
64+
65+
function userMessage(text: string, timestamp: number) {
66+
return { role: "user" as const, content: text, timestamp };
67+
}
68+
69+
const recordValueTool = {
70+
name: "record_value",
71+
description: "Record an integer value for the test harness.",
72+
parameters: { type: "object", properties: { n: { type: "integer" } }, required: ["n"] },
73+
};
74+
75+
function model(): Model<"openai-responses"> {
76+
return {
77+
id: LIVE_MODEL_ID,
78+
name: LIVE_MODEL_ID,
79+
api: "openai-responses",
80+
provider: "openai",
81+
baseUrl: "https://api.openai.com/v1",
82+
reasoning: true,
83+
input: ["text"],
84+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
85+
contextWindow: 200_000,
86+
maxTokens: 8192,
87+
} satisfies Model<"openai-responses">;
88+
}
89+
90+
async function run(context: Context, sessionId: string): Promise<AssistantMessage> {
91+
const stream = await createOpenAIResponsesTransportStreamFn()(model(), context, {
92+
apiKey: OPENAI_KEY,
93+
sessionId,
94+
transport: "sse",
95+
reasoningEffort: "low",
96+
maxTokens: 256,
97+
onPayload: (payload: Record<string, unknown>) => ({ ...payload, store: true }),
98+
} as never);
99+
return stream.result();
100+
}
101+
102+
describeLive(
103+
"HTTP continuation across a real unsafe-integer tool-call argument (real api.openai.com)",
104+
() => {
105+
afterEach(() => {
106+
cleanupSessionResources();
107+
});
108+
109+
it(
110+
"continues a real tool-calling round whose argument is above Number.MAX_SAFE_INTEGER",
111+
async () => {
112+
const capture = new GlobalFetchRequestCapture();
113+
capture.install();
114+
try {
115+
const sessionId = "live-toolcall-arg-canonicalization";
116+
const unsafeInt = "9007199254740993"; // > Number.MAX_SAFE_INTEGER
117+
const firstUser = userMessage(
118+
`This is an automated test. Call the record_value tool with exactly n=${unsafeInt}. ` +
119+
"Do not round or alter the number.",
120+
1,
121+
);
122+
const callTurn = await run(
123+
{ messages: [firstUser], tools: [recordValueTool] },
124+
sessionId,
125+
);
126+
const toolCall = callTurn.content.find((block) => block.type === "toolCall") as
127+
| { type: "toolCall"; id: string; name: string; arguments: Record<string, unknown> }
128+
| undefined;
129+
expect(toolCall).toBeDefined();
130+
expect(String(toolCall?.arguments.n)).toBe(unsafeInt);
131+
132+
const toolResultMsg = {
133+
role: "toolResult" as const,
134+
toolCallId: toolCall?.id ?? "",
135+
content: [{ type: "text" as const, text: "recorded" }],
136+
timestamp: 2,
137+
};
138+
const round1Messages: Context["messages"] = [firstUser, callTurn, toolResultMsg];
139+
const afterToolResult = await run(
140+
{ messages: round1Messages, tools: [recordValueTool] },
141+
sessionId,
142+
);
143+
expect(afterToolResult.stopReason).toBe("stop");
144+
145+
// Exactly two requests reached the real API -- a rejected
146+
// previous_response_id (the recovery path is a silent
147+
// full-history resend) would show up as a third.
148+
expect(capture.requests).toHaveLength(2);
149+
const secondRequest = capture.requests[1];
150+
expect(secondRequest).toHaveProperty("previous_response_id");
151+
expect(typeof secondRequest?.previous_response_id).toBe("string");
152+
expect((secondRequest?.previous_response_id as string).length).toBeGreaterThan(0);
153+
// toolCall.id is OpenClaw's own internal call_id|fc_id pairing;
154+
// the wire delta's call_id must be restored to the bare provider
155+
// call_id (the part before the pairing separator), not the
156+
// compound internal id.
157+
const rawCallId = toolCall?.id.split("|")[0];
158+
expect(secondRequest?.input).toEqual([
159+
{
160+
type: "function_call_output",
161+
call_id: rawCallId,
162+
output: "recorded",
163+
},
164+
]);
165+
} finally {
166+
capture.restore();
167+
}
168+
},
169+
LIVE_TIMEOUT_MS,
170+
);
171+
},
172+
);

‎packages/ai/src/transports/openai-responses-continuation.test.ts‎

Lines changed: 45 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -284,12 +284,19 @@ describe("OpenAI Responses continuation", () => {
284284
);
285285
});
286286

287-
it("does not treat an unsafe-integer argument as equal to a same-digits string (type collision)", () => {
288-
// quoteUnsafeIntegerLiterals converts an unsafe integer literal into a
289-
// quoted string before JSON.parse; without a distinguishing tag that
290-
// output is byte-identical to a genuine JSON string holding the same
291-
// digits, so a real number-to-string argument change would otherwise
292-
// compare equal and wrongly reuse the stale continuation state.
287+
it("treats a cached number-typed unsafe integer as equal to its own replayed string-typed round-trip", () => {
288+
// Real shape, confirmed live against a real tool-calling round: the
289+
// cached side is the raw provider text (a bare, unsafe-integer number),
290+
// but AssistantMessage.arguments already stores every unsafe integer as
291+
// a string (parseJsonObjectPreservingUnsafeIntegers,
292+
// transport-stream-shared.ts, precision-preserving), so the *unmodified*
293+
// replay of this exact same historical tool call always re-serializes it
294+
// back as a same-digits JSON string. This is the client's own necessary
295+
// representation of the same value, not a real argument change -- an
296+
// earlier revision of this fix (a distinguishing tag on the cached side
297+
// only) treated this as a genuine change, permanently breaking
298+
// continuation for the very next round of any real tool call carrying an
299+
// out-of-range integer.
293300
const toolCall = {
294301
type: "function_call",
295302
id: "fc_1",
@@ -316,7 +323,38 @@ describe("OpenAI Responses continuation", () => {
316323
};
317324

318325
expect(resolveResponsesContinuationRequest(state, nextRoundRequest).continuationStatus).toBe(
319-
"history_changed",
326+
"continued",
327+
);
328+
});
329+
330+
it("treats a whitespace-only re-serialization of the same unsafe integer as equal", () => {
331+
const toolCall = {
332+
type: "function_call",
333+
id: "fc_1",
334+
status: "completed",
335+
call_id: "call_original_abc",
336+
name: "exec",
337+
arguments: '{"n":9007199254740993}',
338+
};
339+
const state: ResponsesContinuationState = {
340+
lastRequest: { model: "gpt-5.6-luna", store: true, input: [firstUser] as never },
341+
lastResponseId: "resp_1",
342+
lastResponseItems: [toolCall] as never,
343+
};
344+
const replayedToolCall = { ...toolCall, arguments: '{"n": 9007199254740993}' };
345+
const toolResult = {
346+
type: "function_call_output",
347+
call_id: "call_original_abc",
348+
output: "hi\n",
349+
};
350+
const nextRoundRequest: ResponsesContinuationRequest = {
351+
model: "gpt-5.6-luna",
352+
store: true,
353+
input: [firstUser, replayedToolCall, toolResult] as never,
354+
};
355+
356+
expect(resolveResponsesContinuationRequest(state, nextRoundRequest).continuationStatus).toBe(
357+
"continued",
320358
);
321359
});
322360

‎packages/ai/src/transports/openai-responses-continuation.ts‎

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -75,20 +75,32 @@ function requestWithoutInput(request: ResponsesContinuationRequest): ResponsesCo
7575
// integer literal past Number.MAX_SAFE_INTEGER, so two genuinely DIFFERENT
7676
// unsafe integers could otherwise parse to the same JS number and wrongly
7777
// compare equal, sending a stale delta instead of the real changed argument.
78-
// The tag distinguishes a stringified unsafe integer from a genuine JSON
79-
// string holding the same digits -- without it `{"n":9007199254740993}` and
80-
// `{"n":"9007199254740993"}` both parse to the identical JS string and wrongly
81-
// compare equal, hiding a real number-to-string argument change.
82-
const UNSAFE_INTEGER_COMPARISON_TAG = "\u0000openclaw-unsafe-integer\u0000";
83-
78+
//
79+
// No distinguishing tag: an earlier revision quoted unsafe integers with a
80+
// tag to also catch a stringified unsafe integer colliding with a genuine
81+
// same-digits JSON string -- but on the *cached* side this compares against,
82+
// `arguments` is the raw provider text (a bare number), while the *replayed*
83+
// side is rebuilt from AssistantMessage.arguments, which
84+
// parseJsonObjectPreservingUnsafeIntegers (transport-stream-shared.ts)
85+
// already stores as a string for every unsafe integer, precision-preserving.
86+
// So a real, unmodified tool-calling round *always* replays an unsafe
87+
// integer as a same-digits string against a cached bare number -- tagging
88+
// only the cached side made every real large-integer tool call permanently
89+
// ineligible for continuation on its very next round (confirmed live: an
90+
// actual tool call with a real out-of-range integer, replayed unmodified,
91+
// still landed as history_changed). Plain (untagged) quoting can't tell a
92+
// converted integer apart from a genuine same-digit string either, but that
93+
// is not the risk here: both sides of this comparison replay the *same*
94+
// historical tool call, and the client-side "unsafe integers become
95+
// strings" convention already applies uniformly to how that call is cached
96+
// and replayed -- there is no independent second call in this comparison
97+
// for a same-digit string to collide with.
8498
function normalizeFunctionCallArguments(value: unknown): unknown {
8599
if (typeof value !== "string") {
86100
return value;
87101
}
88102
try {
89-
return JSON.stringify(
90-
JSON.parse(quoteUnsafeIntegerLiterals(value, UNSAFE_INTEGER_COMPARISON_TAG)),
91-
);
103+
return JSON.stringify(JSON.parse(quoteUnsafeIntegerLiterals(value)));
92104
} catch {
93105
return value;
94106
}

0 commit comments

Comments
 (0)