Repository navigation
Fix BunString ref leaks in Bun.JSON5.stringify - #32331
Conversation
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.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (1)
Walkthrough
ChangesJSON5 OwnedString Refactor and Memory Regression Test
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
|
Updated 1:59 PM PT - Jun 15th, 2026
❌ @robobun, your commit f6b25db has some failures in 🧪 To try this PR locally: bunx bun-pr 32331That installs a local version of the PR into your bun-32331 --bun |
There was a problem hiding this comment.
Additional findings (outside current diff — PR may have been updated during review):
-
🟡
test/js/bun/json5/json5.test.ts:1698— Pertest/CLAUDE.md("CRITICAL: Do not set a timeout on tests. Bun already has timeouts.") and the rootCLAUDE.md("Don't raise per-test timeouts to make a slow test pass; shrink the workload"), this explicit60_000timeout 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 memorytest passes60_000as the third argument totest(), 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
test("does not leak with a string space argument", async () => {...}, 60_000)— the third positional arg is the timeout in ms.- Project guidelines say not to pass this argument at all.
- If the test body (500 warmup + 20,000 iterations of
Bun.JSON5.stringifywith 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_000argument:test("does not leak with a string space argument", async () => { ... });
If it then times out under the default, reduce
20000iterations and/or the8000-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.
There was a problem hiding this comment.
Additional findings (outside current diff — PR may have been updated during review):
-
🟡
test/js/bun/json5/json5.test.ts:1695— nit:test/CLAUDE.mdsays "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_000here.Extended reasoning...
What
The new
does not leak with a string space argumenttest in thestringify memorydescribe block passes60_000as the second argument totest():}, 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
- The new test at
test/js/bun/json5/json5.test.ts:1695ends with}, 60_000);, whichbun:testinterprets as a 60-second per-test timeout. - 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. test/CLAUDE.mdflags 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); + }); }); - The new test at
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.
There was a problem hiding this comment.
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=0toASAN_OPTIONSfor the child process (matchingarchive.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
BunStringderefs viaDrop), so removing them is correct.
|
CI status: the diff is green on all completed lanes (Linux x64/aarch64, musl, Windows, x64-asan). Remaining red is darwin infra, unrelated to this change:
The only test-failure annotation on both builds is Ready for a maintainer to merge. |
There was a problem hiding this comment.
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/ directCopypasses, and removal of two stale comments that incorrectly claimedBunStringderefs viaDrop.test/js/bun/json5/json5.test.ts(+40 lines): a child-process RSS-delta regression test withASAN_OPTIONS=quarantine_size_mb=0appended 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=0rather 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.rsortest/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.
What
Bun.JSON5.stringifyleakedWTF::StringImplrefs on every call with a stringspaceargument, and on every identifier key written.Repro
Cause
bun_core::Stringis#[derive(Copy)]with noDropimpl; sites that receive a +1 ref must wrap it inOwnedStringto get scope-exitderef().JSON5Object.rsstored a rawBunStringinSpace::Strand called.clone()(which on a WTF-backed string isdupe_ref(), and on a ZigString-backed one allocates a fresh impl) when passing toStringBuilder::append_string, assumingDropwould balance the refs. It doesn't:Space::init:to_bun_string()+1 stored inSpace::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 freshStringImplper indent level, all leaked.append_key():name.clone()+1 per identifier key.YAMLObject.rsalready handles this correctly withStr(OwnedString)and passing theCopyvalue directly.Fix
Space::Str(BunString)→Space::Str(OwnedString); wrap theto_bun_string()result immediately so the early-return path also releases it.append_key:append_string(*name)instead ofname.clone().newline: borrow theCopyvalue via**space_strand passclampeddirectly.BunStringderefs viaDrop.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.