Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

perf(shared): replace lossless-json parser with native JSON.parse source reviver (#15104)

Steffen Schmitz650eaf7abab2
diff --git a/packages/shared/src/server/ingestion/extractToolsBackend.ts b/packages/shared/src/server/ingestion/extractToolsBackend.ts
index 763d8eb2c8..4fd57791db 100644
--- a/packages/shared/src/server/ingestion/extractToolsBackend.ts
+++ b/packages/shared/src/server/ingestion/extractToolsBackend.ts
@@ -7,8 +7,9 @@ type IngestionJsonValue = string | object | number | boolean | null | undefined;
*
* Deliberately native JSON.parse, not the shared parseJsonIfString: this runs
* over full observation input/output for every ingested span, and the shared
- * helper's lossless-json slow path triggers on any digit followed by e/E
- * (most UUIDs) or 13+ consecutive digits (ms timestamps).
+ * helper's precision-preserving path (triggered by any digit followed by e/E
+ * — most UUIDs — or 13+ consecutive digits — ms timestamps) pays a per-value
+ * reviver callback that ingestion does not need.
*/
function parseIfString(data: unknown): unknown {
if (typeof data === "string") {
diff --git a/packages/shared/src/utils/json.test.ts b/packages/shared/src/utils/json.test.ts
new file mode 100644
index 0000000000..bd152f3180
--- /dev/null
+++ b/packages/shared/src/utils/json.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from "vitest";
+
+import { parseJsonPrioritised } from "./json";
+
+// Focused on the precision path (UNSAFE_NUMBER_PATTERN hit -> source-access
+// reviver). Complementary coverage elsewhere: basic parseJsonPrioritised
+// semantics incl. invalid JSON and a bare unsafe integer live in
+// web/src/__tests__/server/zod.servertest.ts; unsafe integers in nested
+// objects/arrays via deepParseJson live in the "Number precision (issue
+// #6628)" block of web/src/__tests__/json-utils.clienttest.ts.
+//
+// All JSON documents are built as literal strings so big integers stay exact
+// digit text: a JS numeric literal in this file would itself be rounded to a
+// double before the parser under test ever sees it.
+describe("parseJsonPrioritised precision path", () => {
+ it("keeps a 13+ digit but double-safe integer as a number", () => {
+ // Trips the UNSAFE_NUMBER_PATTERN heuristic (13 digits), but round-trips
+ // losslessly — must stay numeric, not become a string.
+ expect(parseJsonPrioritised('{"ts": 1721001600000}')).toEqual({
+ ts: 1721001600000,
+ });
+ });
+
+ it("resolves safe scientific notation to a number and keeps overflow exact", () => {
+ expect(parseJsonPrioritised('{"a": 1e3}')).toEqual({ a: 1000 });
+ expect(parseJsonPrioritised('{"a": 1e500}')).toEqual({ a: "1e500" });
+ });
+
+ it("preserves decimals with more significant digits than a double", () => {
+ const result = parseJsonPrioritised(
+ '{"pi": 3.14159265358979323846}',
+ ) as any;
+ expect(result.pi).toBe("3.14159265358979323846");
+ });
+
+ it("parses docs that only trip the heuristic via string content", () => {
+ // Base64 payloads and ISO timestamps contain digit-e sequences and long
+ // digit runs inside strings; numbers elsewhere must stay untouched.
+ const result = parseJsonPrioritised(
+ '{"blob": "aGVsbG8e9wORLD3e", "at": "2026-07-15T12:00:00.123456Z", "n": 5}',
+ ) as any;
+ expect(result.blob).toBe("aGVsbG8e9wORLD3e");
+ expect(result.at).toBe("2026-07-15T12:00:00.123456Z");
+ expect(result.n).toBe(5);
+ });
+
+ it("keeps last duplicate key like native JSON.parse", () => {
+ // lossless-json threw on duplicate keys, so docs with an unsafe number
+ // stayed raw strings while docs without one parsed (fast path). Native
+ // parsing makes both paths consistently last-wins.
+ expect(parseJsonPrioritised('{"a": 1, "a": 9223372036854775807}')).toEqual({
+ a: "9223372036854775807",
+ });
+ });
+});
diff --git a/packages/shared/src/utils/json.ts b/packages/shared/src/utils/json.ts
index d231f5356c..f6c12aa574 100644
--- a/packages/shared/src/utils/json.ts
+++ b/packages/shared/src/utils/json.ts
@@ -1,5 +1,5 @@
import { JsonNested } from "./zod";
-import { parse, isSafeNumber, isNumber } from "lossless-json";
+import { isSafeNumber } from "lossless-json";
// Dangerous keys that could lead to prototype pollution
const DANGEROUS_KEYS = new Set(["__proto__", "constructor", "prototype"]);
@@ -399,7 +399,7 @@ export function deepParseJsonIterative(
*
* Catches:
* 1. [\d.]{13,} - 13+ characters of digits/dots (conservative threshold for ~12+ significant digits)
- * 2. \d[eE] - scientific notation (always use lossless-json for safety)
+ * 2. \d[eE] - scientific notation (always take the precision-preserving path for safety)
*/
const UNSAFE_NUMBER_PATTERN = /[\d.]{13,}|\d[eE]/;
const JSON_NUMBER_LITERAL_PATTERN =
@@ -408,6 +408,31 @@ const JSON_NUMBER_LITERAL_PATTERN =
export const isJsonNumberLiteral = (value: string): boolean =>
JSON_NUMBER_LITERAL_PATTERN.test(value.trim());
+/**
+ * JSON.parse reviver with source-text access (TC39 json-parse-with-source,
+ * V8 in Node >= 21 and evergreen browsers). The `context` parameter is not
+ * yet part of the es2023 lib types, hence the local signature. `context` is
+ * optional so the function stays assignable to the classic reviver type.
+ */
+type ReviverWithSource = (
+ this: unknown,
+ key: string,
+ value: unknown,
+ context?: { source?: string },
+) => unknown;
+
+/**
+ * Keeps numbers that cannot round-trip through a JS double as their exact
+ * source token (a string) instead of the rounded double. `context.source` is
+ * only provided for primitive values, so objects/arrays pass through.
+ */
+const preserveUnsafeNumbers: ReviverWithSource = (_key, value, context) =>
+ typeof value === "number" &&
+ context?.source !== undefined &&
+ !isSafeNumber(context.source)
+ ? context.source
+ : value;
+
/**
* 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
@@ -420,15 +445,15 @@ const parsePreservingPrecision = (json: string): unknown => {
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,
- );
+ // Precision path: native JSON.parse with a source-access reviver. Safe
+ // numbers stay real numbers, unsafe ones keep their exact source token as
+ // a string. Native parsing here replaced lossless-json's pure-JS parser,
+ // which dominated heap allocation on large payloads (any 13+ digit run or
+ // digit-followed-by-e — e.g. ms timestamps or base64 — lands on this path).
+ // On runtimes without source access (Safari < 18.4, Firefox < 135) the
+ // reviver receives no context and unsafe numbers round like plain
+ // JSON.parse; the server (Node >= 21) always preserves them.
+ return JSON.parse(json, preserveUnsafeNumbers);
};
export const parseJsonPrioritised = (