Skip to content

fix: honour toJSON() when payloads are serialized on the worker thread - #98

Closed
Aldrin Joseph (ALDRIN121) wants to merge 2 commits into
langchain-ai:mainfrom
ALDRIN121:fix/serialize-worker-tojson
Closed

Aldrin Joseph (ALDRIN121) wants to merge 2 commits into
langchain-ai:mainfrom
ALDRIN121:fix/serialize-worker-tojson

Conversation

@ALDRIN121

Copy link
Copy Markdown
Contributor

fix: honour toJSON() when a payload is serialized on the worker thread

What

Payloads with a string of 64 KiB or more are serialized off-thread by
SerializeWorker. postMessage uses the structured clone algorithm, which
copies own enumerable properties but drops prototypes — so a class-defined
toJSON() never ran on that path. LangChain messages were uploaded as their
raw own properties (lc_serializable, lc_kwargs, duplicated content)
instead of the compact { lc, type, id, kwargs } form the inline path
produces, 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 the
payload crosses the thread boundary, so both paths emit the same JSON.

Why

Reproduction from the issue (@langchain/core 1.2.16 / langsmith 0.12.0), a
single HumanMessage in inputs, serialized through Client._serializeBody:

60000 lc,type,id,kwargs 60175 bytes
70000 lc_serializable,lc_kwargs,lc_namespace,content,additional_kwargs,response_metadata 140242 bytes

After this change:

60000 lc,type,id,kwargs 60175 bytes
70000 lc,type,id,kwargs 70175 bytes

The clone succeeds, so the DataCloneError fallback to inline serialization
never runs and the divergence is silent. RunTree.postRun() and the batch
ingest path both go through _serializeBody, so ordinary LLM traces with a
long 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 payload
    by reference when nothing defines toJSON() so plain JSON and
    binary-heavy payloads are not copied, and otherwise deep-copies the graph
    with each toJSON() result substituted, exactly as JSON.stringify does
    (the property key is passed through, cycles and shared references are
    preserved).
  • SerializeWorker.serialize() — calls applyToJSON() after the worker is
    known to be available and posts the prepared snapshot.
  • Date / RegExp / Error / ArrayBuffer / typed arrays are left alone: their JSON
    form is already produced identically by the worker's serializeWellKnownTypes(),
    and materializing a large Buffer into a numeric array on the main thread
    would 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_worker is not re-exported from the package
entry point.

Tests

Red — the two regression suites against unmodified main (test-only commit
74cc97c):

$ NODE_OPTIONS="--experimental-vm-modules" ./node_modules/.bin/jest \
    --selectProjects lib \
    --testPathPattern='src/lib/tests/(serialize_worker|serialize_body)\.test\.ts$'
● Client._serializeBody worker/inline parity › uses the compact toJSON form on both sides of the worker threshold

    expect(received).toEqual(expected) // deep equality

    - Expected  - 4
    + Received  + 6

      Array [
    -   "lc",
    -   "type",
    -   "id",
    -   "kwargs",
    +   "lc_serializable",
    +   "lc_kwargs",
    +   "lc_namespace",
    +   "content",
    +   "additional_kwargs",
    +   "response_metadata",
      ]

    > 53 |     expect(Object.keys(worker.message)).toEqual(Object.keys(inline.message));

● Client._serializeBody worker/inline parity › does not duplicate the message content above the threshold

    expect(received).toBeLessThan(expected)

    Expected: < 1.1032083333333333
    Received:   2.0032428571428573

    > 68 |     expect(workerRatio).toBeLessThan(inlineRatio * 1.1);

● SerializeWorker › honours toJSON on objects that define it

    - Expected  - 2
    + Received  + 1

      Object {
    -   "amount": 42,
    -   "currency": "USD",
    +   "cents": 4200,
      }

● SerializeWorker › honours toJSON on LangChain messages that trigger the worker path

    Received: true   (message.lc_serializable)

Test Suites: 2 failed, 2 total
Tests:       4 failed, 6 passed, 10 total

Green — after the fix:

$ NODE_OPTIONS="--experimental-vm-modules" ./node_modules/.bin/jest \
    --selectProjects lib \
    --testPathPattern='src/lib/tests/(serialize_worker|serialize_body)\.test\.ts$'
PASS lib src/lib/tests/serialize_worker.test.ts
PASS lib src/lib/tests/serialize_body.test.ts
Test Suites: 2 passed, 2 total
Tests:       10 passed, 10 total

All serialization suites (adds the applyToJSON unit tests and the existing
estimateSerializedSize / hasLargeString suites):

$ NODE_OPTIONS="--experimental-vm-modules" ./node_modules/.bin/jest \
    --selectProjects lib --testPathPattern='src/lib/tests/serialize'
Test Suites: 3 passed, 3 total
Tests:       61 passed, 61 total

Full hand-written SDK project:

$ NODE_OPTIONS="--experimental-vm-modules" ./node_modules/.bin/jest --selectProjects lib
Test Suites: 55 passed, 55 total
Tests:       2 skipped, 1414 passed, 1416 total

Repo lint pipeline (prettier --check, eslint, build, tsc for the CJS and ESM
configs, attw, publint):

$ ./scripts/lint
LINT_EXIT=0

eslint reports 0 errors (284 pre-existing warnings, none from this change).

Test coverage added

  • src/lib/tests/serialize_body.test.ts — end-to-end through
    Client._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 be
    byte-identical to main-thread serialize() for a payload containing a
    toJSON() object, and for a LangChain message above the threshold.
  • src/lib/tests/serialize.test.ts — unit tests for applyToJSON: returns the
    same reference when nothing defines toJSON(), handles nested objects,
    arrays, Maps and Sets, passes the property key like JSON.stringify, keeps
    cycles, does not mutate the input, and leaves binary views alone.

Notes

  • Cost: one short-circuiting walk per worker request, plus a copy only for
    payloads that actually define toJSON(). Payloads without toJSON() (the
    base64-heavy case the worker exists for) are posted by reference as before.
  • Verified locally only; nothing has been pushed.

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.
@ALDRIN121

Copy link
Copy Markdown
Contributor Author

Thibaut Lehmann (@thibautlehmann) — the four workflows on this PR are sitting action_required (first run from a fork). Could you approve the runs so CI can verify the change? The bug and the red-to-green numbers are in the description: on the worker path postMessage structured-clones the payload, so a class-defined toJSON() never runs and 70 KB of input uploads as 140 KB.

@thibautlehmann

Copy link
Copy Markdown
Contributor

Hi Aldrin Joseph (@ALDRIN121) , thank you for opening a PR, I will take a look!

@ALDRIN121

Copy link
Copy Markdown
Contributor Author

Thanks Thibaut Lehmann (@thibautlehmann). A quick status on the reds so they don't mislead while you look:

  • PR comes from staging — this is the export policy, not the diff: main only takes copybara/export-javascript / release-please. Happy to have this ported into sdks/javascript in langchainplus if that is the right home; I can also paste the diff as a patch wherever it is easier to apply.
  • benchmark — the benchmark itself ran on both main and this branch. The job only failed on its last step, posting the comparison comment (403 Resource not accessible by integration — fork PRs get a read-only token).
  • CI Success — it fails only because cancelled counts as a failure. The four test (…, node …) legs were cancelled ~85 s into run attempt 2 (the one you approved) after every suite they had reached passed; no test failed in any of the four logs. A re-run of the matrix should finish.

Everything deterministic is green: lint, build, and all eight exports (*) targets (esm, cjs, cf, vite, webpack, esbuild, metro, deepagent-compat), plus both Socket checks. Locally the hand-written SDK project is 55 suites / 1414 tests passing and ./scripts/lint is clean.

The change is self-contained in src/lib/utils/serialize_worker.ts plus three test files, so it should apply cleanly to whatever branch or repo you want it to land in.

@thibautlehmann

Copy link
Copy Markdown
Contributor

Hello Aldrin Joseph (@ALDRIN121), the fix has been released in 0.13.1 in this commit :)
Thank you for your help!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants