Skip to content

fix(internal): avoid calling toJSON twice in safeStringify - #1480

Open
yunyv wants to merge 3 commits into
VoltAgent:mainfrom
yunyv:fix/safe-stringify-tojson-once
Open

yunyv wants to merge 3 commits into
VoltAgent:mainfrom
yunyv:fix/safe-stringify-tojson-once

Conversation

@yunyv

@yunyv yunyv commented Oct 26, 2026 •

Copy link
Copy Markdown

PR Checklist

  • The proposed commit message follows the contribution guidelines: fix(internal): avoid calling toJSON twice in safeStringify

Bugs / Features

  • Related issue(s) linked — found directly while inspecting the serializer; no existing open issue identified.
  • Tests for the changes have been added.
  • Docs have been added / updated — an implementation comment explains why conversion is left to JSON.stringify; there is no public API change.
  • Changesets have been added.

What is the current behavior?

JSON.stringify calls an object's toJSON(key) before passing its result to the replacer. safeStringify then invokes toJSON again when that result is an object with a toJSON method.

For example, a self-returning toJSON runs twice for one property. If its second invocation throws, safeStringify returns SAFE_STRINGIFY_ERROR rather than valid JSON. The extra invocation also lacks the property-key argument. An object returned by toJSON can likewise have its own method unexpectedly invoked.

What is the new behavior?

Leave toJSON conversion to JSON.stringify, then apply the existing circular-reference checks to its result. The traversal stack and WeakSet handling are preserved.

Regression tests cover a self-returning method being called once with its property key, an object returned by toJSON, and errors genuinely thrown by the initial conversion. Existing circular-reference, shared-reference, Date, and custom-serialization tests remain unchanged.

Notes for reviewers

Validation used Node 24.22.1 and Vitest 3.2.4 against the actual source modules:

  • Before the fix: the serializer suite had 2 failing regression tests and 28 passing tests.
  • After the fix: the complete internal package suite had 131 passing tests and 1 existing skipped test across 6 files. An independent second AI review and test run reproduced that result.
  • Biome 1.9.4 checks passed for both changed TypeScript files.
  • Strict TypeScript 5.8.3 checking passed for those two files.
  • Full internal-package tsc reports a pre-existing Map inference error in src/utils/objects.spec.ts:171. Running the same check with the original HEAD source and tests produced identical output.
  • git diff --check passed.

The full monorepo build, full-repository lint, core integration/e2e tests, and Node 20/22 matrix were not run locally. Tools were installed in an isolated lightweight environment rather than installing the entire monorepo.

Historical PR #961 replaced recursive reconstruction with stack-based traversal for performance. This patch keeps that approach; its existing custom-serialization tests compare against native JSON.stringify. The behavioral correction is specifically removal of the extra conversion, including for objects returned by toJSON.

This contribution was prepared and independently checked with AI assistance. The checks listed above were actually run; this does not claim human review.

Independent validation refresh (2026-11-03)

Exact PR head de8bb6eb2173790c1d736e19fd3ba052f5999e67 was rechecked against unchanged main 72a46c76b4507e1f98b41d5050a92bd30587eb70. A fresh Node 24 run of all six internal-package test files produced 129 passed, 2 failed and 1 skipped on the baseline, then 131 passed and 1 skipped on the PR. This repeats the package inventory above; it is not an additional 131 unique tests. Ten separate direct-TypeScript boundary probes produced 7 passed/3 failed on baseline and 10 passed on the PR. Changed-file strict TypeScript and Biome checks passed. Whole-package TypeScript still reports the identical pre-existing TS2769 Map inference diagnostic on baseline and PR; it did not pass.

This refresh did not run the full workspace build/tests/lint, core integration/E2E, or Node 20/22. It does not claim hosted CI success: the PR workflow currently awaits maintainer approval, and CodeRabbit skipped review while the PR was a draft. The independent verification was AI-assisted, not human or maintainer approval.

Summary by CodeRabbit

  • Bug Fixes
    • Safe serialization now respects toJSON behavior without invoking it twice, and handles circular references and serialization errors correctly.
  • Tests
    • Added coverage for toJSON call counts, returned values, and errors.

yunyv added 3 commits October 26, 2026 11:52
Let JSON.stringify perform toJSON conversion before the existing circular-reference checks.
Cover single invocation with property keys, returned objects, and genuine conversion errors.
Add a patch release note for the internal serializer correction.
@changeset-bot

changeset-bot Bot commented Oct 26, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: de8bb6e

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@voltagent/internal Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai

coderabbitai Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Walkthrough

safeStringifyReplacer now checks the value supplied by JSON.stringify after toJSON processing. Three tests cover a self-returning toJSON, an object returned by toJSON, and an exception thrown by toJSON.

Changes: Safe serialization

Layer / File(s) Summary
Replacer behavior and validation
packages/internal/src/utils/safe-stringify.ts, packages/internal/src/utils/safe-stringify.spec.ts, .changeset/quiet-tojson-calls.md
The replacer checks the value supplied by JSON.stringify for circular references instead of invoking toJSON itself. Tests cover invocation behavior and errors. A patch changeset records the update.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Suggested reviewers: zrosenbauer

Merge Risk: Minimal · up to de8bb

No merge-blocking issue is established for the serialization change.

Pre-merge checks: Passed 5
Check name Status Explanation
Title check Passed The title "fix(internal): avoid calling toJSON twice in safeStringify" matches the main change. The raw summary and objectives show that safeStringifyReplacer stops calling toJSON itself, so JSON.stri…
Description check Passed The description follows the repository template. It includes the PR checklist, the bugs/features checklist, current and new behavior sections, and notes for reviewers. It explains the root cause, the …
Docstring Coverage Passed No eligible functions found in the changed files. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title "fix(internal): avoid calling toJSON twice in safeStringify" matches the main change. The raw summary and objectives show that safeStringifyReplacer stops calling toJSON itself, so JSON.stringify performs the conversion once, and the title names that behavior and the affected module.

Full details: Description check

Explanation

The description follows the repository template. It includes the PR checklist, the bugs/features checklist, current and new behavior sections, and notes for reviewers. It explains the root cause, the fix, the regression tests, and the validation performed. Two gaps remain: no related issue is linked, and the 'fixes (issue)' line in the template is not filled in. The author states this openly, so the description is still mostly complete.

Full details: Docstring Coverage

Explanation

No eligible functions found in the changed files. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 0 functions across 2 files. (1 skipped: 1 unsupported.)

Finishing Touches
Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

CodeRabbit Verify

  • Run CodeRabbit Verify to test the changes in this pull request.
Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: c2185632-b3fc-4625-81f4-944821773662
Commits

Reviewing files that changed from the base of the PR and between 72a46c7 and de8bb6e.

Files selected for processing: 3
  • .changeset/quiet-tojson-calls.md
  • packages/internal/src/utils/safe-stringify.spec.ts
  • packages/internal/src/utils/safe-stringify.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@yunyv
yunyv marked this pull request as ready for review November 3, 2026 20:52

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 3 files

View guided diff | Re-trigger cubic

This branch has not been deployed

No deployments
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.

1 participant