🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(trace): preserve big integer precision in IO JSON viewer (#14449)
Nikita Kabardinc7133c1abc2a
diff --git a/.agents/skills/seed-test-data/SKILL.md b/.agents/skills/seed-test-data/SKILL.mdindex a9ee832e8a..b5dc65464f 100644--- a/.agents/skills/seed-test-data/SKILL.md+++ b/.agents/skills/seed-test-data/SKILL.md@@ -36,7 +36,8 @@ this.| A super tough session (v3 legacy session view) | `pnpm run seed -- long-session --traces 300 --observations-per-trace 8` || Many traces for list/filter performance | `pnpm run seed -- many-traces --count 100000 --days 14` || Scores with spaces in the name (filter/grammar testing) | `pnpm run seed -- scored-traces --traces 24 --v4` |-| Huge/malformed/unicode payloads | `pnpm run seed -- trace-tree --payload-bytes 1000000 --payload-style malformed` (styles: json, text, malformed, unicode) |+| Huge/malformed/unicode payloads | `pnpm run seed -- trace-tree --payload-bytes 1000000 --payload-style malformed` (styles: json, text, malformed, unicode, bignum) |+| Big integers beyond 2^53-1 (number-precision testing) | `pnpm run seed -- trace-tree --observations 1 --payload-style bignum` || See all scenarios and flags | `pnpm run seed -- list --json` || Predict without writing | add `--dry-run` |diff --git a/packages/shared/scripts/seeder/scenarios/payload.ts b/packages/shared/scripts/seeder/scenarios/payload.tsindex c2f95335c5..7476b0103d 100644--- a/packages/shared/scripts/seeder/scenarios/payload.ts+++ b/packages/shared/scripts/seeder/scenarios/payload.ts@@ -1,12 +1,13 @@import { Rng } from "./rng";-export type PayloadStyle = "json" | "text" | "malformed" | "unicode";+export type PayloadStyle = "json" | "text" | "malformed" | "unicode" | "bignum";export const PAYLOAD_STYLES: PayloadStyle[] = ["json","text","malformed","unicode",+ "bignum",];const WORDS = [@@ -104,9 +105,44 @@ const buildUnicodePayload = (rng: Rng, targetBytes: number): string => {return parts.join("\n");};+/**+ * Builds a JSON payload containing integers that exceed JavaScript's+ * Number.MAX_SAFE_INTEGER (2^53-1), to reproduce precision loss in the+ * JSON/IO viewer (issue #6628). `as_number` is the exact value from that+ * report; native JSON.parse rounds it to 107505301260286110.+ *+ * CRITICAL: every large integer is emitted as literal digit text, never as a+ * JS number literal. A literal like `107505301260286111` in this source would+ * be rounded to a double by V8 before it could be stringified, so the seeded+ * payload would already be wrong on disk. Hand-build the string instead.+ */+const buildBignumPayload = (targetBytes: number): string => {+ const entries: string[] = [+ `"as_number": 107505301260286111`, // exact value from #6628 (unsafe int64)+ `"as_string": "107505301260286111"`, // control: must always render verbatim+ `"int64_max": 9223372036854775807`, // int64 max, far beyond 2^53-1+ `"safe_number": 42`, // safe integer, must be unaffected+ `"nested": {"big": 1234567890123456789, "ok": 7}`, // recursive parse path+ `"array": [100000000000000001, 100000000000000002, "100000000000000003"]`,+ ];+ // Pad deterministically toward targetBytes with more unsafe integers. Each+ // filler is a 17-digit number (> 2^53), derived purely from its index so the+ // payload is reproducible and never touches the rng stream.+ let index = 0;+ let size = entries.reduce((n, e) => n + e.length + 1, 2);+ while (size < targetBytes) {+ const entry = `"filler_${index}": 90071992547${String(index).padStart(6, "0")}`;+ entries.push(entry);+ size += entry.length + 1;+ index++;+ }+ return `{${entries.join(",")}}`;+};+/*** Builds a payload string of approximately targetBytes. "malformed" returns* intentionally invalid JSON (truncated, unclosed) for JSON-viewer edge cases.+ * "bignum" returns integers beyond 2^53-1 for number-precision edge cases.*/export const buildPayload = (style: PayloadStyle,@@ -120,6 +156,8 @@ export const buildPayload = (return buildTextPayload(rng, targetBytes);case "unicode":return buildUnicodePayload(rng, targetBytes);+ case "bignum":+ return buildBignumPayload(targetBytes);case "malformed": {const valid = buildJsonPayload(rng, targetBytes);return `${valid.slice(0, Math.floor(valid.length * 0.9))},"unclosed":"tr`;diff --git a/packages/shared/scripts/seeder/scenarios/trace-tree.ts b/packages/shared/scripts/seeder/scenarios/trace-tree.tsindex a9c2b42eee..5cf977dd01 100644--- a/packages/shared/scripts/seeder/scenarios/trace-tree.ts+++ b/packages/shared/scripts/seeder/scenarios/trace-tree.ts@@ -600,7 +600,7 @@ export const traceTreeScenario: ScenarioDefinition = {flag: "payload-style",type: "string",default: "json",- description: "json | text | malformed | unicode",+ description: "json | text | malformed | unicode | bignum",},{flag: "v4",diff --git a/packages/shared/src/utils/json.ts b/packages/shared/src/utils/json.tsindex 76a95d9c04..24f98cd247 100644--- a/packages/shared/src/utils/json.ts+++ b/packages/shared/src/utils/json.ts@@ -34,7 +34,9 @@ function tryParsePythonDict(str: string): unknown {// therefore, the failure case is the default already..replace(/'/g, '"');- return JSON.parse(jsonStr);+ // parsePreservingPrecision (not JSON.parse) so big integers in Python-dict+ // payloads (e.g. LangChain/LangGraph run IDs) keep their precision too.+ return parsePreservingPrecision(jsonStr);} catch {return str;}@@ -92,9 +94,12 @@ function deepParseJsonRecursive(}if (typeof json === "string") {+ // A bare JSON number literal stays a string: this preserves user-provided+ // numeric strings and, critically, big integers that would lose precision+ // if coerced to a JS number (issue #6628).+ if (isJsonNumberLiteral(json)) return json;try {- const parsed = JSON.parse(json);- if (typeof parsed === "number") return json; // numbers that were strings in the input should remain as strings+ const parsed = parsePreservingPrecision(json);return deepParseJsonRecursive(parsed, currentDepth + 1, maxDepth); // Recursively parse parsed value} catch {const pythonParsed = tryParsePythonDict(json);@@ -208,15 +213,21 @@ export function deepParseJsonIterative(// Process strings - try to parse as JSONif (typeof input === "string") {+ // A bare JSON number literal stays a string (see deepParseJsonRecursive):+ // preserves numeric strings and big integers that would otherwise lose+ // precision when coerced to a JS number (issue #6628).+ if (isJsonNumberLiteral(input)) {+ entry.output = input;+ processed.add(entry);+ continue;+ }+let parsed: unknown;let wasParsed = false;try {- parsed = JSON.parse(input);- // Numbers that were strings in the input should remain as strings- if (typeof parsed !== "number") {- wasParsed = true;- }+ parsed = parsePreservingPrecision(input);+ wasParsed = true;} catch {// Try Python dict parsingconst pythonParsed = tryParsePythonDict(input);@@ -264,7 +275,9 @@ export function deepParseJsonIterative(}}} else {- // Not JSON or parsed to number, use as-is+ // Not valid JSON (and the Python-dict fallback also failed), keep as-is.+ // Bare numeric literals never reach here — isJsonNumberLiteral above+ // already short-circuits them to preserve big-int precision (#6628).entry.output = input;processed.add(entry);continue;@@ -395,28 +408,34 @@ const JSON_NUMBER_LITERAL_PATTERN =export const isJsonNumberLiteral = (value: string): boolean =>JSON_NUMBER_LITERAL_PATTERN.test(value.trim());+/**+ * Parses a JSON string like JSON.parse, but preserves integers beyond+ * Number.MAX_SAFE_INTEGER (2^53-1) by emitting them as strings instead of+ * rounding them to a JS double (issue #6628). Throws on invalid JSON, exactly+ * like JSON.parse, so callers can fall back to other parsing strategies.+ */+const parsePreservingPrecision = (json: string): unknown => {+ // Fast path: native JSON.parse when no number could lose precision.+ if (!UNSAFE_NUMBER_PATTERN.test(json)) {+ return JSON.parse(json);+ }++ // Slow path: lossless-json keeps the exact token. Safe numbers become real+ // numbers, unsafe ones are preserved as their string representation.+ return parse(json, null, (value) =>+ isNumber(value)+ ? isSafeNumber(value)+ ? Number(value.valueOf())+ : value.toString()+ : value,+ );+};+export const parseJsonPrioritised = (json: string,): JsonNested | string | undefined => {try {- // Fast path: use native JSON.parse if no potentially unsafe numbers detected- if (!UNSAFE_NUMBER_PATTERN.test(json)) {- return JSON.parse(json) as JsonNested;- }-- // Slow path: use lossless-json to preserve precision- return parse(json, null, (value) => {- if (isNumber(value)) {- if (isSafeNumber(value)) {- // Safe numbers (integers and decimals) can be converted to Number- return Number(value.valueOf());- } else {- // For large integers beyond safe limits, preserve string representation- return value.toString();- }- }- return value;- }) as JsonNested;+ return parsePreservingPrecision(json) as JsonNested;} catch {return json;}diff --git a/web/src/__tests__/json-utils.clienttest.ts b/web/src/__tests__/json-utils.clienttest.tsindex a238b3c9cd..44ecc6f0e3 100644--- a/web/src/__tests__/json-utils.clienttest.ts+++ b/web/src/__tests__/json-utils.clienttest.ts@@ -1081,3 +1081,55 @@ describe("Performance Comparison", () => {expect(recursiveResult).toEqual(iterativeResult);});});++describe("Number precision (issue #6628)", () => {+ // Build the JSON by hand so the big integers stay literal digit text. A JS+ // numeric literal like 107505301260286111 would be rounded to a double by+ // this test file itself, before the parser ever sees it.+ const flatJson =+ '{"as_number": 107505301260286111, "as_string": "107505301260286111", "safe_number": 42}';+ const nestedJson =+ '{"nested": {"big": 9223372036854775807}, "arr": [100000000000000001, 7, "100000000000000003"]}';++ describe.each([+ ["deepParseJson", deepParseJson],+ ["deepParseJsonIterative", deepParseJsonIterative],+ ])("%s", (_name, parse) => {+ it("preserves integers beyond Number.MAX_SAFE_INTEGER as strings", () => {+ const result = parse(flatJson) as any;+ // The unsafe integer is preserved verbatim instead of being rounded to+ // 107505301260286110 by native JSON.parse.+ expect(result.as_number).toBe("107505301260286111");+ // A safe integer stays a real number.+ expect(result.safe_number).toBe(42);+ // A value already provided as a string is untouched.+ expect(result.as_string).toBe("107505301260286111");+ });++ it("preserves big integers nested in objects and arrays", () => {+ const result = parse(nestedJson) as any;+ expect(result.nested.big).toBe("9223372036854775807");+ expect(result.arr[0]).toBe("100000000000000001");+ expect(result.arr[1]).toBe(7);+ expect(result.arr[2]).toBe("100000000000000003");+ });++ it("preserves a big integer passed as an already-parsed nested string", () => {+ // Mirrors the real path: the API ships input as a JSON string nested+ // inside an object, and the client deep-parses it.+ const result = parse({ output: flatJson }) as any;+ expect(result.output.as_number).toBe("107505301260286111");+ });++ it("preserves a big integer inside a Python-dict-formatted string", () => {+ // LangChain/LangGraph tool calls are logged as Python dicts, which often+ // carry big integer run/correlation IDs. These reach the Python-dict+ // fallback parser, not the JSON parser.+ const result = parse(+ "{'request_id': 107505301260286111, 'ok': True}",+ ) as any;+ expect(result.request_id).toBe("107505301260286111");+ expect(result.ok).toBe(true);+ });+ });+});