Skip to content

Fix BunString ref leaks in Bun.JSON5.stringify - #32331

Merged
Jarred-Sumner merged 5 commits into
mainfrom
farm/a4e33778/json5-stringify-string-leak
Jun 15, 2026
Merged

Jarred-Sumner merged 5 commits into
mainfrom
farm/a4e33778/json5-stringify-string-leak

Conversation

@robobun

@robobun robobun commented Jun 15, 2026 •

Copy link
Copy Markdown
Collaborator

What

Bun.JSON5.stringify leaked WTF::StringImpl refs on every call with a string space argument, and on every identifier key written.

Repro

const obj = { a: [1, 2, 3], b: { c: 4 }, d: 5 };
const pad = Buffer.alloc(1024 * 1024, " ").toString();
for (let i = 0; i < 20; i++) Bun.JSON5.stringify(obj, null, pad + i);
Bun.gc(true);
const before = process.memoryUsage.rss();
for (let i = 0; i < 200; i++) Bun.JSON5.stringify(obj, null, pad + i);
Bun.gc(true);
console.log(((process.memoryUsage.rss() - before) / 1024 / 1024).toFixed(1), "MB");
// before: ~200 MB
// after:  ~2 MB

Cause

bun_core::String is #[derive(Copy)] with no Drop impl; sites that receive a +1 ref must wrap it in OwnedString to get scope-exit deref(). JSON5Object.rs stored a raw BunString in Space::Str and called .clone() (which on a WTF-backed string is dupe_ref(), and on a ZigString-backed one allocates a fresh impl) when passing to StringBuilder::append_string, assuming Drop would balance the refs. It doesn't:

  • Space::init: to_bun_string() +1 stored in Space::Str(BunString), never released.
  • newline(): space_str.clone() / clamped.clone() in the indent loop; for a >10 char space the clamped value is ZigString-backed so .clone() allocates a fresh StringImpl per indent level, all leaked.
  • append_key(): name.clone() +1 per identifier key.

YAMLObject.rs already handles this correctly with Str(OwnedString) and passing the Copy value directly.

Fix

  • Space::Str(BunString) → Space::Str(OwnedString); wrap the to_bun_string() result immediately so the early-return path also releases it.
  • append_key: append_string(*name) instead of name.clone().
  • newline: borrow the Copy value via **space_str and pass clamped directly.
  • Removed the two comments that incorrectly claimed BunString derefs via Drop.

Verification

New RSS-delta regression test in test/js/bun/json5/json5.test.ts. Fails on the unfixed build (leaked ~200MB), passes with the fix. All 320 existing json5 tests and 113 json5-test-suite tests continue to pass.

bun_core::String is Copy with no Drop impl, so the BunString stored in
Space::Str and the .clone() calls in append_key() and newline() never
released their WTF::StringImpl refs. With a string space argument this
pinned every space string's backing storage plus a fresh StringImpl per
indent level on each newline.

Switch Space::Str to OwnedString (which derefs on Drop) and pass the
Copy value to append_string() directly instead of .clone()ing. This
matches the pattern already used in YAMLObject.rs.
@coderabbitai

coderabbitai Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: f9b10860-1c60-473f-ad8c-89558d8897c3

📥 Commits

Reviewing files that changed from the base of the PR and between d0fc18b and 6659976.

📒 Files selected for processing (1)
  • test/js/bun/json5/json5.test.ts

Walkthrough

Space::Str in JSON5Object.rs switches from storing a BunString to an OwnedString, with all downstream call sites (Space::init, stringify_value, append_key, newline, expr_to_js_with_check) updated to construct or dereference OwnedString without cloning. Stale deinit comments are removed. A new memory regression test spawns a child process and asserts RSS growth stays within bounds after repeated Bun.JSON5.stringify calls with a string space argument.

Changes

JSON5 OwnedString Refactor and Memory Regression Test

Layer / File(s) Summary
Space::Str and stringify call sites switched to OwnedString
src/runtime/api/JSON5Object.rs
OwnedString added to imports; Space::Str variant switches its stored type from BunString to OwnedString; Space::init wraps parsed JS strings into OwnedString; stringify_value, append_key, newline, and expr_to_js_with_check all construct or deref OwnedString instead of cloning; stale deinit comments removed.
RSS memory regression test for string-space stringify
test/js/bun/json5/json5.test.ts
New stringify memory describe block spawns a child Bun process that runs repeated Bun.JSON5.stringify calls with a changing string space, forces GC, computes RSS delta in MB, and asserts the delta stays within an ASAN-adjusted threshold.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Fix BunString ref leaks in Bun.JSON5.stringify' clearly and specifically describes the main change—fixing reference leaks in JSON5 stringify caused by improper BunString handling.
Description check ✅ Passed The PR description comprehensively covers both required sections: 'What' explains the issue and fix in detail, and verification is provided through both a reproduction case and new tests.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

@robobun

robobun commented Jun 15, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 1:59 PM PT - Jun 15th, 2026

❌ @robobun, your commit f6b25db has some failures in Build #62611 (All Failures)


🧪   To try this PR locally:

bunx bun-pr 32331

That installs a local version of the PR into your bun-32331 executable, so you can run:

bun-32331 --bun

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

Additional findings (outside current diff — PR may have been updated during review):

  • 🟡 test/js/bun/json5/json5.test.ts:1698 — Per test/CLAUDE.md ("CRITICAL: Do not set a timeout on tests. Bun already has timeouts.") and the root CLAUDE.md ("Don't raise per-test timeouts to make a slow test pass; shrink the workload"), this explicit 60_000 timeout should be dropped — the other subprocess test in this file (deeply nested parse results) doesn't set one either. If the default timeout isn't enough, shrink the workload (fewer iterations or a smaller pad) instead.

    Extended reasoning...

    What

    The new stringify memory test passes 60_000 as the third argument to test(), setting an explicit per-test timeout of 60 seconds.

    Why this violates project convention

    test/CLAUDE.md (line 120) states:

    CRITICAL: Do not set a timeout on tests. Bun already has timeouts.

    And the root CLAUDE.md (line 193) reinforces it:

    Don't raise per-test timeouts to make a slow test pass; shrink the workload.

    The repo-wide default test timeout is configured by the harness; per-test overrides are explicitly disallowed by the contribution guidelines. The other subprocess-spawning test in this same file — deeply nested parse results — follows the convention and does not pass a timeout argument, so this is inconsistent even within the file.

    Step-by-step

    1. test("does not leak with a string space argument", async () => {...}, 60_000) — the third positional arg is the timeout in ms.
    2. Project guidelines say not to pass this argument at all.
    3. If the test body (500 warmup + 20,000 iterations of Bun.JSON5.stringify with an 8 KB pad) is slow enough to need 60 s, the guideline says to reduce the iteration count and/or pad size rather than raise the timeout. Since the regression being guarded against leaked ~199 MB while the threshold is 30 MB (80 MB under ASAN), there's plenty of headroom to cut the workload by 2-4× and still reliably detect the leak.

    Impact

    This is a style/convention issue, not a functional bug — the test will still pass or fail correctly. But it diverges from an explicitly CRITICAL-tagged repo rule and from the precedent set by the neighboring test.

    Fix

    Remove the 60_000 argument:

    test("does not leak with a string space argument", async () => {
      ...
    });

    If it then times out under the default, reduce 20000 iterations and/or the 8000-byte pad until it fits.

Use a 1MB unique space string over 200 iterations instead of 8KB over
20k. Same ~200MB leak on the unfixed build, under 2s on debug+ASAN, so
the explicit per-test timeout is no longer needed.

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

Additional findings (outside current diff — PR may have been updated during review):

  • 🟡 test/js/bun/json5/json5.test.ts:1695 — nit: test/CLAUDE.md says "CRITICAL: Do not set a timeout on tests. Bun already has timeouts." The sibling subprocess test in this file (deeply nested parse results) follows that convention and omits a timeout — drop the , 60_000 here.

    Extended reasoning...

    What

    The new does not leak with a string space argument test in the stringify memory describe block passes 60_000 as the second argument to test():

      }, 60_000);

    This sets an explicit per-test timeout, which the repo's test guidelines forbid.

    Why this violates the convention

    test/CLAUDE.md (line ~120) states:

    CRITICAL: Do not set a timeout on tests. Bun already has timeouts.

    The harness manages timeouts globally; explicit per-test timeouts override that and create inconsistency across the suite.

    Step-by-step

    1. The new test at test/js/bun/json5/json5.test.ts:1695 ends with }, 60_000);, which bun:test interprets as a 60-second per-test timeout.
    2. The directly preceding test in the same file — deeply nested parse results → JSON5.parse and JSONC.parse near the nesting depth limit… — also spawns a subprocess and runs a heavy iteration sweep, yet it does not pass a timeout argument. So the file already follows the convention; this new test is the only one diverging.
    3. test/CLAUDE.md flags this rule as CRITICAL, so even though the test functions correctly with the timeout, it should be removed for consistency with the documented project policy.

    Impact

    No functional impact — the test still works. This is purely a repo-convention/style violation. It is worth fixing because (a) the rule is explicitly marked CRITICAL in the repo docs, and (b) the adjacent equivalent test already omits it, so leaving it in is inconsistent within the same file.

    Fix

    Remove the explicit timeout:

         expect({ stdout, stderr, exitCode }).toEqual({ stdout: "", stderr: "", exitCode: 0 });
    -  }, 60_000);
    +  });
     });

Comment thread test/js/bun/json5/json5.test.ts Resolved
Matches archive.test.ts / readdirSync-recursive-error-leak.test.ts so the
64MB threshold holds regardless of allocator config. Widening the ASAN
threshold instead would let the unfixed ~200MB leak slip under it.

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

LGTM — the OwnedString wrap matches the established YAMLObject.rs pattern line-for-line, and the ASAN quarantine fix in 6659976 is the right call.

Extended reasoning...

Overview

This PR fixes WTF::StringImpl ref leaks in Bun.JSON5.stringify by switching Space::Str from holding a raw BunString (which is #[derive(Copy)] with no Drop) to OwnedString (which calls .deref() on drop), and replacing .clone() calls with by-value Copy passes. Touches src/runtime/api/JSON5Object.rs (~15 lines of logic) and adds an RSS-delta regression test in test/js/bun/json5/json5.test.ts.

Security risks

None. This is a ref-counting/memory-leak fix in a JSON5 stringifier; no auth, crypto, permissions, or untrusted-input parsing changes.

Level of scrutiny

Low-to-medium. The change is mechanical and mirrors src/runtime/api/YAMLObject.rs exactly — same Str(OwnedString) variant, same **space_str deref to get the Copy BunString, same clamped: BunString borrow from substring_with_len (which returns a ZigString-backed view with no ref taken, so the original owning self.space outlives it). I verified OwnedString::Drop calls self.0.deref() and StringBuilder::append_string takes String by value, so passing *name / clamped directly is correct and balances refs.

Other factors

  • I previously flagged the hardcoded 64MB threshold as ASAN-unsafe; the author addressed it in 6659976 by appending quarantine_size_mb=0 to ASAN_OPTIONS for the child process (matching archive.test.ts), with sound reasoning that a widened threshold would let the ~200MB regression pass under ASAN and defeat the fail-before check. That comment thread is resolved.
  • The bug-hunting system found no issues on the current revision.
  • 320 existing json5 tests + 113 json5-test-suite tests pass per the PR description; the new regression test fails-before/passes-after.
  • No CODEOWNERS entry for these paths.
  • The two removed comments were factually wrong (claimed BunString derefs via Drop), so removing them is correct.

@robobun

robobun commented Jun 15, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI status: the diff is green on all completed lanes (Linux x64/aarch64, musl, Windows, x64-asan). test/js/bun/json5/json5.test.ts passed on every lane that ran it.

Remaining red is darwin infra, unrelated to this change:

  • Build #62564: all six darwin test jobs expired waiting for agents and never ran.
  • Build #62611 (retrigger): darwin 14 aarch64 failed at guest boot attempt 1 failed / global command hook exited with status 1 before any tests ran; other darwin jobs still scheduled.

The only test-failure annotation on both builds is test/cli/install/migration/complex-workspace.test.ts on debian x64-asan, tagged flaky by the runner (package install migration, unrelated to JSON5 stringify).

Ready for a maintainer to merge.

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

LGTM — straightforward application of the documented OwnedString RAII pattern to plug the Space::Str ref leak, with a verified fail-before/pass-after regression test; the ASAN-quarantine fix in 6659976 resolves my earlier concern.

Extended reasoning...

Overview

Two files touched:

  • src/runtime/api/JSON5Object.rs (~30 lines net): Space::Str(BunString) → Space::Str(OwnedString), plus replacing .clone() calls with *name / **space_str / direct Copy passes, and removal of two stale comments that incorrectly claimed BunString derefs via Drop.
  • test/js/bun/json5/json5.test.ts (+40 lines): a child-process RSS-delta regression test with ASAN_OPTIONS=quarantine_size_mb=0 appended for the measurement process.

I verified against src/bun_core/string/mod.rs: String is #[derive(Clone, Copy)] with an explicit comment (line ~1249) that this precludes impl Drop, and OwnedString is the documented wrapper ("Prefer this over ad-hoc scopeguard…") whose Drop calls .deref(). to_bun_string() returns +1, so storing it raw in Space::Str and dropping the Stringifier leaked exactly that ref — wrapping in OwnedString::new(...) immediately is the canonical fix and also covers the length()==0 early-return path. substring_with_len on a WTF-backed string returns a ZigString-tagged view into the impl's byte storage (no new ref), so clamped is safely borrowed for the duration of newline() while the backing OwnedString lives in self.space. append_string takes String by value (Copy), so passing clamped / *name directly is correct and equivalent to the prior .clone() (derived Clone on a Copy type is bitwise). The match self.space sites in stringify_array/stringify_object only use _ bindings, so the loss of Copy on Space doesn't introduce a move.

Security risks

None. This is a memory-leak fix in a serializer; no auth, crypto, permissions, or untrusted-input parsing surface is touched. The only refcount change is releasing a previously-leaked +1 — there is no path that could double-deref (the inner String is never .deref()'d elsewhere) or use-after-free (clamped never outlives self.space).

Level of scrutiny

Medium-low. Refcounting across the Rust↔C++ FFI boundary normally warrants care, but this change is a textbook application of the repo's own OwnedString abstraction (which exists precisely for this case and is already used identically in YAMLObject.rs). The diff is small, mechanical, and self-contained to one non-core API (Bun.JSON5.stringify).

Other factors

  • My earlier inline comment about ASAN flakiness was addressed in 6659976 with quarantine_size_mb=0 rather than threshold widening; the author's reasoning (a 384MB ASAN threshold would mask the ~200MB regression) is sound, and they reported 9MB-fixed vs 200MB-unfixed on debug+ASAN. Comment thread is resolved.
  • CI is green on all completed lanes including x64-asan; the one failing test (complex-workspace.test.ts) is tagged flaky and unrelated.
  • No CODEOWNERS entry covers src/runtime/api/JSON5Object.rs or test/js/bun/json5/.
  • 320 existing json5 tests + 113 suite tests continue to pass per the PR description, and the new test is fail-before/pass-after.

@Jarred-Sumner
Jarred-Sumner merged commit 88d09d5 into main Jun 15, 2026
77 of 78 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the farm/a4e33778/json5-stringify-string-leak branch June 15, 2026 22:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants