Repository navigation
fix: honour toJSON() when payloads are serialized on the worker thread - #98
Aldrin Joseph (ALDRIN121) wants to merge 2 commits into
Conversation
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.
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.
|
Thibaut Lehmann (@thibautlehmann) — the four workflows on this PR are sitting |
|
Hi Aldrin Joseph (@ALDRIN121) , thank you for opening a PR, I will take a look! |
|
Thanks Thibaut Lehmann (@thibautlehmann). A quick status on the reds so they don't mislead while you look:
Everything deterministic is green: The change is self-contained in |
|
Hello Aldrin Joseph (@ALDRIN121), the fix has been released in 0.13.1 in this commit :) |
fix: honour
toJSON()when a payload is serialized on the worker threadWhat
Payloads with a string of 64 KiB or more are serialized off-thread by
SerializeWorker.postMessageuses the structured clone algorithm, whichcopies own enumerable properties but drops prototypes — so a class-defined
toJSON()never ran on that path. LangChain messages were uploaded as theirraw own properties (
lc_serializable,lc_kwargs, duplicatedcontent)instead of the compact
{ lc, type, id, kwargs }form the inline pathproduces, so the stored run shape and size depended on the length of the input.
This applies
toJSON()on the thread that still owns the objects, before thepayload crosses the thread boundary, so both paths emit the same JSON.
Why
Reproduction from the issue (
@langchain/core1.2.16 / langsmith 0.12.0), asingle
HumanMessageininputs, serialized throughClient._serializeBody:After this change:
The clone succeeds, so the
DataCloneErrorfallback to inline serializationnever runs and the divergence is silent.
RunTree.postRun()and the batchingest path both go through
_serializeBody, so ordinary LLM traces with along prompt were doubly affected (duplicated content, ~2x uploaded bytes).
Change
src/lib/utils/serialize_worker.ts(only production file touched):applyToJSON(payload)— new internal helper. Walks the payload once(
hasToJSON, iterative, cycle-safe, short-circuiting), returns the payloadby reference when nothing defines
toJSON()so plain JSON andbinary-heavy payloads are not copied, and otherwise deep-copies the graph
with each
toJSON()result substituted, exactly asJSON.stringifydoes(the property key is passed through, cycles and shared references are
preserved).
SerializeWorker.serialize()— callsapplyToJSON()after the worker isknown to be available and posts the prepared snapshot.
form is already produced identically by the worker's
serializeWellKnownTypes(),and materializing a large
Bufferinto a numeric array on the main threadwould undo the point of offloading. (Binary payloads therefore keep their
previous behaviour; that divergence predates this issue and is not addressed
here.)
No public API change:
serialize_workeris not re-exported from the packageentry point.
Tests
Red — the two regression suites against unmodified
main(test-only commit74cc97c):Green — after the fix:
All serialization suites (adds the
applyToJSONunit tests and the existingestimateSerializedSize/hasLargeStringsuites):Full hand-written SDK project:
Repo lint pipeline (prettier --check, eslint, build,
tscfor the CJS and ESMconfigs, attw, publint):
eslintreports 0 errors (284 pre-existing warnings, none from this change).Test coverage added
src/lib/tests/serialize_body.test.ts— end-to-end throughClient._serializeBody: a 60k message (inline path) and a 70k message(worker path) must produce the same keys, no
lc_serializable/lc_kwargs,a single copy of the content, and a size that tracks the input length.
src/lib/tests/serialize_worker.test.ts— worker output must bebyte-identical to main-thread
serialize()for a payload containing atoJSON()object, and for a LangChain message above the threshold.src/lib/tests/serialize.test.ts— unit tests forapplyToJSON: returns thesame reference when nothing defines
toJSON(), handles nested objects,arrays, Maps and Sets, passes the property key like
JSON.stringify, keepscycles, does not mutate the input, and leaves binary views alone.
Notes
payloads that actually define
toJSON(). Payloads withouttoJSON()(thebase64-heavy case the worker exists for) are posted by reference as before.