Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 85 additions & 1 deletion src/lib/tests/serialize.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<string, unknown>;
expect(prepared.nested).toEqual({ price: { amount: 42, currency: "USD" } });
expect(prepared.list).toEqual([{ amount: 1, currency: "USD" }]);
expect((prepared.map as Map<string, unknown>).get("k")).toEqual({
amount: 2,
currency: "USD",
});
expect(Array.from(prepared.set as Set<unknown>)).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<string, unknown> = { price: new Money(500) };
payload.self = payload;
const prepared = applyToJSON(payload) as Record<string, unknown>;
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);
});
});
70 changes: 70 additions & 0 deletions src/lib/tests/serialize_body.test.ts
Original file line number Diff line number Diff line change
@@ -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<Uint8Array<ArrayBuffer>>;

async function serializeBody(payload: unknown): Promise<string> {
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);
});
});
31 changes: 31 additions & 0 deletions src/lib/tests/serialize_worker.test.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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
Expand Down
145 changes: 144 additions & 1 deletion src/lib/utils/serialize_worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down Expand Up @@ -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<object>();
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<string, unknown>)[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<object, unknown>,
): unknown {
if (value === null || typeof value !== "object") return value;
const obj = value as Record<string, unknown> & { 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<unknown, unknown>();
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<unknown>();
seen.set(obj, out);
for (const v of obj) out.add(cloneWithToJSON(v, "", seen));
return out;
}
const out: Record<string, unknown> = {};
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;
Expand Down Expand Up @@ -225,12 +359,21 @@ export class SerializeWorker {
async serialize(payload: unknown): Promise<Uint8Array<ArrayBuffer> | 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<Uint8Array<ArrayBuffer>>((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.
Expand Down
Loading