From 74cc97ca09816fac1c50e28254f23d666a843725 Mon Sep 17 00:00:00 2001 From: Aldrin Joseph Date: Mon, 16 Nov 2026 22:03:54 +0530 Subject: [PATCH 1/2] test: cover toJSON loss on the serialize worker path Payloads with a string >= 64 KiB are serialized on a worker thread, and postMessage's structured clone drops prototypes, so toJSON() never runs there. These tests pin the worker output to the inline JSON.stringify output for LangChain messages and for any other toJSON-bearing object. --- src/lib/tests/serialize_body.test.ts | 70 ++++++++++++++++++++++++++ src/lib/tests/serialize_worker.test.ts | 31 ++++++++++++ 2 files changed, 101 insertions(+) create mode 100644 src/lib/tests/serialize_body.test.ts diff --git a/src/lib/tests/serialize_body.test.ts b/src/lib/tests/serialize_body.test.ts new file mode 100644 index 0000000..a50ead8 --- /dev/null +++ b/src/lib/tests/serialize_body.test.ts @@ -0,0 +1,70 @@ +import { Client } from "../client.js"; +import { HumanMessage } from "@langchain/core/messages"; + +/** + * Regression tests for the shape-aware serialize gate in + * `Client._serializeBody`: payloads that contain a large string are serialized + * on a worker thread, and the worker path must produce the same JSON as the + * inline path. + * + * The bug these cover: `postMessage` uses the structured clone algorithm, + * which drops class prototypes, so `toJSON()` was never called on LangChain + * messages that crossed the thread boundary. + */ +describe("Client._serializeBody worker/inline parity", () => { + const client = new Client({ + apiKey: "test", + apiUrl: "http://127.0.0.1:1", + }); + + // The serialize worker is unref'd so it never keeps the process alive; hold + // the event loop open for the duration of the suite so a pending worker + // reply can't be dropped when the test is idle. + const keepAlive = setInterval(() => {}, 1000); + + afterAll(() => { + clearInterval(keepAlive); + }); + + type SerializeBody = ( + payload: unknown, + errorContext: string, + ) => Promise>; + + async function serializeBody(payload: unknown): Promise { + const bytes = await ( + client as unknown as { _serializeBody: SerializeBody } + )._serializeBody(payload, "test"); + return Buffer.from(bytes).toString("utf8"); + } + + async function serializeMessage(content: string) { + const payload = { inputs: { messages: [new HumanMessage(content)] } }; + const text = await serializeBody(payload); + return { text, message: JSON.parse(text).inputs.messages[0] }; + } + + it("uses the compact toJSON form on both sides of the worker threshold", async () => { + // 60k stays under the 64 KiB large-string threshold and is serialized + // inline; 70k crosses it and is serialized on the worker thread. + const inline = await serializeMessage("a".repeat(60_000)); + const worker = await serializeMessage("a".repeat(70_000)); + + expect(Object.keys(worker.message)).toEqual(Object.keys(inline.message)); + // Raw serialization leaks the class internals and stores the content twice. + expect(worker.message).not.toHaveProperty("lc_serializable"); + expect(worker.message).not.toHaveProperty("lc_kwargs"); + expect(worker.message.kwargs.content).toHaveLength(70_000); + expect(worker.message.content).toBeUndefined(); + }); + + it("does not duplicate the message content above the threshold", async () => { + const inline = await serializeMessage("a".repeat(60_000)); + const worker = await serializeMessage("a".repeat(70_000)); + + // Sizes should track the input length, not double it. + const inlineRatio = inline.text.length / 60_000; + const workerRatio = worker.text.length / 70_000; + expect(workerRatio).toBeLessThan(inlineRatio * 1.1); + }); +}); diff --git a/src/lib/tests/serialize_worker.test.ts b/src/lib/tests/serialize_worker.test.ts index 7cbfce8..3990583 100644 --- a/src/lib/tests/serialize_worker.test.ts +++ b/src/lib/tests/serialize_worker.test.ts @@ -1,6 +1,7 @@ /* eslint-disable no-process-env */ import { SerializeWorker } from "../utils/serialize_worker.js"; import { serialize } from "../utils/fast-safe-stringify/index.js"; +import { HumanMessage } from "@langchain/core/messages"; describe("SerializeWorker", () => { let worker: SerializeWorker; @@ -77,6 +78,36 @@ describe("SerializeWorker", () => { expect(await serializeToText(payload)).toContain("[Circular]"); }); + test("honours toJSON on objects that define it", async () => { + // structuredClone (used by postMessage) drops prototypes, taking + // toJSON() with them. The worker must still produce the same JSON as the + // inline path, which calls toJSON() via JSON.stringify. + class Money { + constructor(private readonly cents: number) {} + toJSON() { + return { amount: this.cents / 100, currency: "USD" }; + } + } + const payload = { price: new Money(4200), note: "x".repeat(70_000) }; + const workerStr = await serializeToText(payload); + expect(JSON.parse(workerStr).price).toEqual({ + amount: 42, + currency: "USD", + }); + expect(workerStr).toBe(Buffer.from(serialize(payload)).toString("utf8")); + }); + + test("honours toJSON on LangChain messages that trigger the worker path", async () => { + const payload = { + inputs: { messages: [new HumanMessage("a".repeat(70_000))] }, + }; + const workerStr = await serializeToText(payload); + const message = JSON.parse(workerStr).inputs.messages[0]; + expect(message.lc_serializable).toBeUndefined(); + expect(message.lc_kwargs).toBeUndefined(); + expect(workerStr).toBe(Buffer.from(serialize(payload)).toString("utf8")); + }); + test("produces byte-identical output to main-thread serialize for well-known types", async () => { // This test ensures the worker's inlined serialize logic stays in sync // with the main-thread implementation. If this fails, the worker source From 901e7a58b55d16f6ddb848061878cba937e66f50 Mon Sep 17 00:00:00 2001 From: Aldrin Joseph Date: Mon, 16 Nov 2026 22:04:08 +0530 Subject: [PATCH 2/2] fix: apply toJSON before handing payloads to the serialize worker postMessage uses the structured clone algorithm, which copies own enumerable properties and drops prototypes. A class-defined toJSON() -- LangChain messages, Decimal, Moment, Mongoose documents -- therefore never ran on the worker path, while the inline path honoured it through JSON.stringify. The uploaded shape and size depended on whether the payload contained a string of 64 KiB or more. applyToJSON() walks the payload once, returns it untouched when nothing defines toJSON(), and otherwise copies the graph with each toJSON() result substituted, the way JSON.stringify would. Binary views are left alone so large Buffers are never expanded into numeric arrays on the main thread. --- src/lib/tests/serialize.test.ts | 86 +++++++++++++++++- src/lib/utils/serialize_worker.ts | 145 +++++++++++++++++++++++++++++- 2 files changed, 229 insertions(+), 2 deletions(-) diff --git a/src/lib/tests/serialize.test.ts b/src/lib/tests/serialize.test.ts index c88b65f..f588dd0 100644 --- a/src/lib/tests/serialize.test.ts +++ b/src/lib/tests/serialize.test.ts @@ -5,7 +5,7 @@ import { serialize, estimateSerializedSize, } from "../utils/fast-safe-stringify/index.js"; -import { hasLargeString } from "../utils/serialize_worker.js"; +import { hasLargeString, applyToJSON } from "../utils/serialize_worker.js"; import { HumanMessage, SystemMessage, @@ -583,3 +583,87 @@ describe("hasLargeString", () => { expect(hasLargeString(new Error("boom"), 10)).toBe(false); }); }); + +describe("applyToJSON", () => { + class Money { + constructor(private readonly cents: number) {} + toJSON() { + return { amount: this.cents / 100, currency: "USD" }; + } + } + + it("returns the payload untouched when nothing defines toJSON", () => { + const payload = { messages: [{ role: "user", content: "hi" }] }; + expect(applyToJSON(payload)).toBe(payload); + expect(applyToJSON("plain string")).toBe("plain string"); + expect(applyToJSON(null)).toBe(null); + }); + + it("applies toJSON to nested objects, array elements, Maps and Sets", () => { + const payload = { + nested: { price: new Money(4200) }, + list: [new Money(100)], + map: new Map([["k", new Money(200)]]), + set: new Set([new Money(300)]), + }; + const prepared = applyToJSON(payload) as Record; + expect(prepared.nested).toEqual({ price: { amount: 42, currency: "USD" } }); + expect(prepared.list).toEqual([{ amount: 1, currency: "USD" }]); + expect((prepared.map as Map).get("k")).toEqual({ + amount: 2, + currency: "USD", + }); + expect(Array.from(prepared.set as Set)).toEqual([ + { amount: 3, currency: "USD" }, + ]); + }); + + it("passes the property key to toJSON, matching JSON.stringify", () => { + const withKeys = { + toJSON(key: string) { + return { key }; + }, + }; + const payload = { a: withKeys, list: [withKeys] }; + expect(JSON.stringify(applyToJSON(payload))).toBe(JSON.stringify(payload)); + }); + + it("preserves cycles so the serializer still emits [Circular]", () => { + const payload: Record = { price: new Money(500) }; + payload.self = payload; + const prepared = applyToJSON(payload) as Record; + expect(prepared.self).toBe(prepared); + expect(serialize(payload)).toEqual(serialize(prepared)); + }); + + it("does not mutate the input payload", () => { + const message = new HumanMessage("hello"); + const payload = { messages: [message] }; + applyToJSON(payload); + expect(payload.messages[0]).toBe(message); + expect(message).toBeInstanceOf(HumanMessage); + }); + + it("produces the same JSON as JSON.stringify for mixed well-known types", () => { + const payload = { + message: new HumanMessage({ content: "x".repeat(2000) }), + date: new Date("2024-01-01T00:00:00.000Z"), + regex: /foo/gi, + map: new Map([["k", new Money(100)]]), + set: new Set(["a"]), + big: BigInt(9007199254740999), + error: new Error("boom"), + buffer: Buffer.from([1, 2, 3]), + }; + expect(Buffer.from(serialize(applyToJSON(payload))).toString("utf8")).toBe( + Buffer.from(serialize(payload)).toString("utf8"), + ); + }); + + it("leaves binary views for structured clone", () => { + const buffer = Buffer.from([1, 2, 3]); + expect(applyToJSON(buffer)).toBe(buffer); + const view = new Uint8Array([1, 2, 3]); + expect(applyToJSON(view)).toBe(view); + }); +}); diff --git a/src/lib/utils/serialize_worker.ts b/src/lib/utils/serialize_worker.ts index e040fd7..7525612 100644 --- a/src/lib/utils/serialize_worker.ts +++ b/src/lib/utils/serialize_worker.ts @@ -14,6 +14,10 @@ * op = "serialize" -> worker returns bytes as a transferable ArrayBuffer * worker -> main: { id, bytes?: ArrayBuffer, error?: string } * + * Payloads are passed through applyToJSON() first: structured clone copies own + * properties but drops prototypes, so a class-defined toJSON() would never run + * on the worker and the bytes would differ from the inline JSON.stringify path. + * * The worker source is inlined as a string so the library bundles cleanly * under webpack/esbuild/ncc without requiring a separate asset file. */ @@ -125,6 +129,136 @@ type Pending = { reject: (err: Error) => void; }; +/** + * True for values whose JSON form is already produced correctly on the worker + * side by `serializeWellKnownTypes()` (or by the structured clone itself): + * Dates are stringified as ISO timestamps by both paths, and binary data is + * left to the clone so a large Buffer or typed array is never expanded into a + * numeric JSON array on the main thread. + */ +function isHandledWithoutToJSON(val: object): boolean { + return ( + val instanceof Date || + val instanceof RegExp || + val instanceof Error || + val instanceof ArrayBuffer || + ArrayBuffer.isView(val) + ); +} + +/** + * Cheap, short-circuiting walk that returns true iff any object in the payload + * graph defines a `toJSON()` method that the main thread would have to run. + * + * Mirrors the traversal in `hasLargeString`: iterative, cycle-safe and + * allocation-free apart from the `seen` set. + */ +export function hasToJSON(value: unknown): boolean { + if (value === null || typeof value !== "object") return false; + const stack: unknown[] = [value]; + const seen = new Set(); + while (stack.length > 0) { + const cur = stack.pop(); + if (cur === null || typeof cur !== "object") continue; + const obj = cur as { toJSON?: unknown }; + if (seen.has(obj)) continue; + seen.add(obj); + if (isHandledWithoutToJSON(obj)) continue; + if (typeof obj.toJSON === "function") return true; + if (Array.isArray(obj)) { + for (let i = 0; i < obj.length; i++) stack.push(obj[i]); + continue; + } + if (obj instanceof Map) { + for (const [, v] of obj) stack.push(v); + continue; + } + if (obj instanceof Set) { + for (const v of obj) stack.push(v); + continue; + } + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + stack.push((obj as Record)[keys[i]]); + } + } + return false; +} + +/** + * Deep-copy `value`, replacing every object that defines `toJSON()` with the + * value that method returns -- the same substitution `JSON.stringify` makes + * before our replacer sees a value. + * + * `key` is the property name the value was reached through, which is what + * `JSON.stringify` passes to `toJSON()`. Anything already visited is reused, so + * shared references and cycles survive the copy unchanged. + */ +function cloneWithToJSON( + value: unknown, + key: string, + seen: Map, +): unknown { + if (value === null || typeof value !== "object") return value; + const obj = value as Record & { toJSON?: unknown }; + const cached = seen.get(obj); + if (cached !== undefined) return cached; + if (isHandledWithoutToJSON(obj)) return obj; + if (typeof obj.toJSON === "function") { + const projected = (obj.toJSON as (key: string) => unknown).call(obj, key); + return cloneWithToJSON(projected, key, seen); + } + if (Array.isArray(obj)) { + const out: unknown[] = new Array(obj.length); + seen.set(obj, out); + for (let i = 0; i < obj.length; i++) { + out[i] = cloneWithToJSON(obj[i], String(i), seen); + } + return out; + } + if (obj instanceof Map) { + const out = new Map(); + seen.set(obj, out); + for (const [k, v] of obj) { + out.set( + k, + cloneWithToJSON(v, typeof k === "string" ? k : String(k), seen), + ); + } + return out; + } + if (obj instanceof Set) { + const out = new Set(); + seen.set(obj, out); + for (const v of obj) out.add(cloneWithToJSON(v, "", seen)); + return out; + } + const out: Record = {}; + seen.set(obj, out); + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + out[keys[i]] = cloneWithToJSON(obj[keys[i]], keys[i], seen); + } + return out; +} + +/** + * Apply `toJSON()` to a payload before it crosses a thread boundary. + * + * `postMessage` uses the structured clone algorithm, which copies own + * enumerable properties and drops prototypes -- so a `toJSON()` defined on a + * class (LangChain's `BaseMessage`, Decimal, Moment, Mongoose documents, ...) + * is silently lost on the worker path while the inline path honours it through + * `JSON.stringify`. That made the uploaded shape depend on the payload size. + * + * Returns the payload unchanged when nothing in the graph defines `toJSON()`, + * so plain JSON payloads are handed to the worker without being copied. + */ +export function applyToJSON(value: unknown): unknown { + if (!hasToJSON(value)) return value; + return cloneWithToJSON(value, "", new Map()); +} + export class SerializeWorker { private worker: WorkerLike | null = null; private nextId = 1; @@ -225,12 +359,21 @@ export class SerializeWorker { async serialize(payload: unknown): Promise | null> { const ok = await this.ensureStarted(); if (!ok) return null; + // postMessage clones the payload with the structured clone algorithm, + // which keeps own properties but drops prototypes -- taking any toJSON() + // with them. Run it here, where the objects still have their prototypes, + // so the worker emits exactly what inline JSON.stringify would emit. + const snapshot = applyToJSON(payload); const id = this.nextId++; return new Promise>((resolve, reject) => { this.pending.set(id, { resolve, reject }); try { // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this.worker as any).postMessage({ id, op: "serialize", payload }); + (this.worker as any).postMessage({ + id, + op: "serialize", + payload: snapshot, + }); } catch (e) { // postMessage throws synchronously for DataCloneError, unclonable // values, detached buffers, etc.