Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(trace): stop re-serializing multi-MB I/O in parsed-I/O cache keys (LFE-10992) (#15161)

Nikita Kabardin32224bc5f168
diff --git a/web/src/hooks/parsedIoCacheKey.clienttest.ts b/web/src/hooks/parsedIoCacheKey.clienttest.ts
new file mode 100644
index 0000000000..9b11b7803d
--- /dev/null
+++ b/web/src/hooks/parsedIoCacheKey.clienttest.ts
@@ -0,0 +1,78 @@
+import { cheapHash } from "@/src/hooks/parsedIoCacheKey";
+
+/**
+ * The React Query cache key for parsed trace/observation I/O must identify a
+ * field by a cheap, content-sensitive signature β€” never by embedding (and thus
+ * re-serializing) the raw payload. These tests pin that accounting: the
+ * signature never contains the payload text, is stable for identical content
+ * (cache hit), and changes on ANY content change β€” including a same-length swap
+ * (cache miss / re-parse), which a length-only key would have wrongly collided.
+ */
+describe("cheapHash", () => {
+ it("returns a fixed marker for null / undefined", () => {
+ expect(cheapHash(null)).toBe("βˆ…");
+ expect(cheapHash(undefined)).toBe("βˆ…");
+ });
+
+ it("keys a string by length + hash, never by its content", () => {
+ const big = "x".repeat(5_000_000);
+ const sig = cheapHash(big);
+ expect(sig).toMatch(/^s5000000:/);
+ // The whole point of the fix: the multi-MB payload is NOT in the key.
+ expect(sig.length).toBeLessThan(30);
+ expect(sig).not.toContain("xxxx");
+ });
+
+ it("keys arrays and objects by size + content hash", () => {
+ expect(cheapHash([1, 2, 3])).toMatch(/^a3:/);
+ expect(cheapHash([])).toMatch(/^a0:/);
+ expect(cheapHash({ a: 1, b: 2 })).toMatch(/^o2:/);
+ expect(cheapHash({})).toMatch(/^o0:/);
+ });
+
+ it("keeps a large object's signature tiny β€” no payload text in the key", () => {
+ const wide: Record<string, string> = {};
+ for (let i = 0; i < 1000; i++) wide[`k${i}`] = "y".repeat(10_000);
+ const sig = cheapHash(wide);
+ expect(sig).toMatch(/^o1000:/);
+ expect(sig.length).toBeLessThan(40);
+ expect(sig).not.toContain("yyyy");
+ });
+
+ it("keys primitives by their literal value", () => {
+ expect(cheapHash(42)).toBe("p42");
+ expect(cheapHash(true)).toBe("ptrue");
+ });
+
+ it("is stable for identical content (cache hit)", () => {
+ expect(cheapHash("the same payload")).toBe(cheapHash("the same payload"));
+ expect(cheapHash("z".repeat(4096))).toBe(cheapHash("z".repeat(4096)));
+ });
+
+ it("changes on ANY content change, including same length (cache miss / re-parse)", () => {
+ // The regression this guards against: a refetch that swaps a field for
+ // same-length different content (e.g. an SDK status update) must produce a
+ // different signature, or the parse query would serve the stale cached
+ // parse under staleTime: Infinity.
+ expect(cheapHash("pending")).not.toBe(cheapHash("running")); // both len 7
+ expect(cheapHash("hello")).not.toBe(cheapHash("world")); // both len 5
+ // A length change also differs.
+ expect(cheapHash("hello")).not.toBe(cheapHash("hi"));
+ // Type namespaces never collide: a 5-char string vs a 5-element array.
+ expect(cheapHash("abcde")).not.toBe(cheapHash([1, 2, 3, 4, 5]));
+ });
+
+ it("changes when an object/array value changes at the same shape", () => {
+ // A Prisma JSON metadata field whose value changes but whose key-count
+ // stays the same (e.g. {"status":"pending"} -> {"status":"running"}) must
+ // still invalidate the parse β€” same class of collision as the string case.
+ expect(cheapHash({ a: 1 })).not.toBe(cheapHash({ a: 2 }));
+ expect(cheapHash({ status: "pending" })).not.toBe(
+ cheapHash({ status: "running" }),
+ );
+ // Arrays too: same length, different element.
+ expect(cheapHash([1, 2, 3])).not.toBe(cheapHash([1, 2, 4]));
+ // ...and stable for identical object content (cache hit).
+ expect(cheapHash({ a: 1, b: 2 })).toBe(cheapHash({ a: 1, b: 2 }));
+ });
+});
diff --git a/web/src/hooks/parsedIoCacheKey.ts b/web/src/hooks/parsedIoCacheKey.ts
new file mode 100644
index 0000000000..70e98b91df
--- /dev/null
+++ b/web/src/hooks/parsedIoCacheKey.ts
@@ -0,0 +1,83 @@
+/**
+ * Cheap, stable React Query cache signatures for parsed-I/O hooks
+ * (`useParsedTrace`, `useParsedObservation`) β€” LFE-10992, part of the
+ * LFE-10152 large-traces epic.
+ *
+ * Both hooks previously embedded the raw `input`/`output`/`metadata` values
+ * directly in the queryKey, which forces React Query's `hashKey` to
+ * `JSON.stringify` the whole β€” potentially multi-MB β€” payload into the query
+ * hash on EVERY render (`defaultQueryOptions` recomputes the hash on each
+ * `useQuery` call, and its replacer even sorts object keys). That is an
+ * O(payload) main-thread serialization done purely for cache bookkeeping β€”
+ * precisely the kind of whole-payload stringify the large-traces work exists
+ * to remove.
+ *
+ * The replacement keys by the (unique) trace/observation id plus a per-field
+ * signature from `cheapHash`, which is content-sensitive (so a same-length
+ * refetch such as `"pending"` β†’ `"running"` still invalidates the parse) but
+ * never `JSON.stringify`s the payload. Callers memoize the hash on the raw
+ * reference, so the O(n) pass runs only when a field actually changes β€” the
+ * exact moment a re-parse is wanted β€” and is O(1) amortized per render.
+ */
+
+/**
+ * cyrb53 β€” a fast, well-distributed non-cryptographic 53-bit string hash
+ * (public-domain, by bryc). Used only to detect content changes for cache
+ * keying, never for security. A single O(n) pass over char codes with
+ * `Math.imul`, no allocation.
+ */
+function cyrb53(str: string, seed = 0): number {
+ let h1 = 0xdeadbeef ^ seed;
+ let h2 = 0x41c6ce57 ^ seed;
+ for (let i = 0; i < str.length; i++) {
+ const ch = str.charCodeAt(i);
+ h1 = Math.imul(h1 ^ ch, 2654435761);
+ h2 = Math.imul(h2 ^ ch, 1597334677);
+ }
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);
+ h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);
+ h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);
+ return 4294967296 * (2097151 & h2) + (h1 >>> 0);
+}
+
+/**
+ * Content hash of an object/array, from its serialization. Guarded: a circular
+ * or otherwise unserializable value falls back to `x` (shape-only), which only
+ * loses content-sensitivity for that rare payload β€” the unique id in the
+ * queryKey still scopes it. This DOES serialize to hash, but callers memoize
+ * `cheapHash` on the raw reference, so it runs only when the field actually
+ * changes (a real change = when a re-parse is wanted), never per render.
+ */
+function contentHash(value: object): number | string {
+ try {
+ return cyrb53(JSON.stringify(value));
+ } catch {
+ return "x";
+ }
+}
+
+/**
+ * Content-sensitive cache signature for one parse-input field.
+ *
+ * Returns a compact descriptor that changes whenever the field's content
+ * changes β€” never the payload itself: `s<len>:<hash>` for strings (length +
+ * cyrb53, so same-length-different-content still differs), `a<len>:<hash>` for
+ * arrays and `o<keys>:<hash>` for objects (size + content hash, so a
+ * same-shape value change such as `{"status":"pending"}` β†’ `{"status":
+ * "running"}` still differs β€” no cache collision), the literal for primitives,
+ * `βˆ…` for null/undefined. The type-tag prefix keeps namespaces distinct (a
+ * 5-char string never collides with a 5-element array).
+ *
+ * The trace/observation I/O fields that flow through here are `string | null`
+ * in practice, so the string branch is the operative one; the object/array
+ * branches exist for defensive correctness and consistency.
+ */
+export function cheapHash(value: unknown): string {
+ if (value === null || value === undefined) return "βˆ…";
+ if (typeof value === "string") return `s${value.length}:${cyrb53(value)}`;
+ if (Array.isArray(value)) return `a${value.length}:${contentHash(value)}`;
+ if (typeof value === "object")
+ return `o${Object.keys(value).length}:${contentHash(value)}`;
+ return `p${String(value)}`;
+}
diff --git a/web/src/hooks/useParsedObservation.ts b/web/src/hooks/useParsedObservation.ts
index d090db1b52..e9d72d9682 100644
--- a/web/src/hooks/useParsedObservation.ts
+++ b/web/src/hooks/useParsedObservation.ts
@@ -25,6 +25,7 @@ import type {
ParseRequest,
ParseResponse,
} from "@/src/workers/json-parser.worker";
+import { cheapHash } from "@/src/hooks/parsedIoCacheKey";
type ObservationWithStringifiedIO = ObservationReturnTypeWithMetadata & {
input: string | null;
@@ -272,15 +273,33 @@ export function useParsedObservation({
? eventsQuery.isLoading
: observationQuery.isLoading;
+ // Per-field cache signatures: content-sensitive but never a whole-payload
+ // stringify. Memoized on the raw reference (react-query structural sharing
+ // keeps it referentially stable between renders), so each O(n) hash runs
+ // only when that field actually changes β€” the exact moment a re-parse is
+ // wanted β€” instead of the multi-MB re-serialization the old raw-value key
+ // forced on every render.
+ const inputSig = useMemo(
+ () => cheapHash(mergedObservation?.input),
+ [mergedObservation?.input],
+ );
+ const outputSig = useMemo(
+ () => cheapHash(mergedObservation?.output),
+ [mergedObservation?.output],
+ );
+ const metadataSig = useMemo(
+ () => cheapHash(mergedObservation?.metadata),
+ [mergedObservation?.metadata],
+ );
+
// Step 2: Parse the data in Web Worker (React Query caches THIS too!)
const parseQuery = useQuery({
queryKey: [
"parsed-observation",
observationId,
- // Include data hash to detect changes
- mergedObservation?.input,
- mergedObservation?.output,
- mergedObservation?.metadata,
+ inputSig,
+ outputSig,
+ metadataSig,
],
queryFn: async () => {
if (!mergedObservation) {
diff --git a/web/src/hooks/useParsedTrace.ts b/web/src/hooks/useParsedTrace.ts
index ea98d2f2ca..8750c529e4 100644
--- a/web/src/hooks/useParsedTrace.ts
+++ b/web/src/hooks/useParsedTrace.ts
@@ -16,11 +16,13 @@
* - Graceful fallback: Uses sync parsing if Web Workers unavailable
*/
+import { useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import type {
ParseRequest,
ParseResponse,
} from "@/src/workers/json-parser.worker";
+import { cheapHash } from "@/src/hooks/parsedIoCacheKey";
/**
* Threshold for using Web Worker vs sync parsing (in characters).
@@ -188,16 +190,19 @@ export function useParsedTrace({
output,
metadata,
}: UseParsedTraceParams) {
+ // Per-field cache signatures: content-sensitive but never a whole-payload
+ // stringify. Memoized on the raw reference (react-query structural sharing
+ // keeps it referentially stable between renders), so each O(n) hash runs
+ // only when that field actually changes β€” the exact moment a re-parse is
+ // wanted β€” instead of the multi-MB re-serialization the old raw-value key
+ // forced on every render.
+ const inputSig = useMemo(() => cheapHash(input), [input]);
+ const outputSig = useMemo(() => cheapHash(output), [output]);
+ const metadataSig = useMemo(() => cheapHash(metadata), [metadata]);
+
// Parse the data in Web Worker (React Query caches this)
const parseQuery = useQuery({
- queryKey: [
- "parsed-trace",
- traceId,
- // Include data hash to detect changes
- input,
- output,
- metadata,
- ],
+ queryKey: ["parsed-trace", traceId, inputSig, outputSig, metadataSig],
queryFn: async () => {
return parseTraceData(input, output, metadata);
},