Repository navigation
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Essentials Run ID: 📒 Files selected for processing (3)
💤 Files with no reviewable changes (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review. WalkthroughChangesEmpty JSON handling
Suggested reviewers: Merge Risk: ⚪ Minimal · up to Empty and BOM-only JSON bodies now reject with parser diagnostics rather than resolving to null, with coverage across the affected JSON body APIs. No current merge-blocking risk is identified. 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Updated 12:57 PM PT - Sep 5th, 2026
✅ @robobun, your commit de493a15d0bc0f6248e60a80033e4e8d5ac3b831 passed in 🧪 To try this PR locally: bunx bun-pr 33658That installs a local version of the PR into your bun-33658 --bun |
|
Found 3 issues this PR may fix:
🤖 Generated with Claude Code |
|
Of the three suggested issues, linking only #24955: express #8702 reports a behavioural difference between bun and tsx on a request body; this PR only improves the rejection message and does not address whatever causes the parse failure there. #8524 is about importing a JSON file via the module loader, which already reports the parser diagnostic and is not touched here. |
There was a problem hiding this comment.
No bugs found; the change looks correct and well-tested, but it removes the #5859 JSONParseWithException workaround and flips empty-body .json() from resolving null to rejecting — worth a quick human sanity check on that behavior change.
Extended reasoning...
Overview
Two C++ bindings (BunString__toJSON, ZigString__toJSONObject) switch from JSONParse to JSONParseWithException so the parser's own SyntaxError (with token/position) propagates instead of a generic "Failed to parse JSON". Null input strings are normalised to emptyString() so the parser throws its own EOF diagnostic. In Blob.rs, three empty-body shortcuts are removed: the hardcoded "Unexpected end of JSON input" in to_json_with_bytes, and two return Ok(JSValue::NULL) early-returns in Any::to_json for the InternalBlob/WTFStringImpl arms. Four test files are updated with new coverage that pins .json() rejection to exactly what JSON.parse throws for the same bytes.
I traced the memory-safety side of the removed empty-buffer branch in to_json_with_bytes: the _free = ... TemporaryBytes(raw_bytes) guard further down still reclaims the leaked Box<[u8]> on the Temporary path, so removing the early return doesn't leak. I also confirmed via JSC__AnyPromise__wrap that a returned ErrorInstance value (which ZigString__toJSONObject produces after clearing the exception) is converted to a promise rejection, so the fetch-response path rejects rather than resolving with the error object.
Security risks
None. This is error-message plumbing on the JSON body-consumer path; no new input surface, auth, or crypto.
Level of scrutiny
Moderate. The code change is small and mechanical, but two things push it past auto-approval:
- User-visible behavior change:
await new Response("").json()(and the emptyInternalBlob/WTFStringImplfetch-body paths) previously resolved tonull; now they reject with aSyntaxError. That's the spec- and Node-correct behavior, and the PR tests it explicitly, but it's still a breaking change for anyone relying on the oldnull. - Reverting a documented workaround: the
JSONParsefallback carried a// JSONParseWithException does not propagate exceptions as expected. See #5859comment. The PR argues (plausibly) that #5859's real cause was a scope-nesting bug, notJSONParseWithExceptionitself, and the #5859 regression test inserve.test.tsstill passes with the updated assertion. A maintainer who remembers that history should confirm.
Other factors
Test coverage is thorough — the new body.test.ts block exercises Response, Request, Blob, ReadableStream body, Bun.file(), and a live fetch() against the exact JSON.parse message across five malformed inputs including empty, plus a dedicated "empty body rejects (does not resolve null)" case. The exception-scope handling in BunString__toJSON looks correct (RETURN_IF_EXCEPTION after the parse, fallback throw only when no exception is set).
|
CI status on build 69875 (finished): 284 jobs passed, including every test lane that ran. No error-style annotations. The only failures are both |
…41387) ### Problem - `test/js/bun/spawn/readablestream-helpers.test.ts` fails at random. On PR builds 110091 (debian 13 aarch64) and 110186 (windows 11 aarch64), a case got `Failed to parse JSON` where it expected `JSON Parse error: Expected '}'`, or the reverse. - `json()` on a stream that holds the whole body parses it in `BunString__toJSON` (`src/jsc/bindings/BunString.cpp:522`) or `EncodedSlice__toJSONObject` (`src/jsc/bindings/bindings.cpp:2748`). These call `JSC::JSONParse` and throw the generic message. A streamed body gets the `JSON.parse` message. - For `proc.stdout`, timing selects the path. #20694 pinned one message per case. Since #41204, one failure is final. ### Fix - Both helpers call `JSONParseWithException`, and parse `""` for an empty input. For the same text, they throw the SyntaxError that `JSON.parse` throws. The removed "See #5859" comment is stale (see Notes). - `Response.json()`, `Request.json()`, `Blob.json()` and `Bun.file().json()` change the same way. The fetch spec rethrows the `JSON.parse` exception. Node does too. - `scripts/verify-baseline-static/allowlist-x64.txt` gets `llint_op_jmp_wide32`, a documented LLInt decode false positive that moved with the code layout (see Notes). - Verified on the ASAN build with `BUN_JSC_validateExceptionChecks=1`: `readablestream-helpers.test.ts` (new cases), `body.test.ts`, `serve.test.ts`. Self-reviewed: 5 concerns raised, 4 addressed. ### Background - A stream that Bun creates has a native source. A Blob source returns the whole body at once, so `json()` tries it first. - `JSC::JSONParse` returns an empty value on a syntax error and throws nothing. - Bun creates `proc.stdout` when JS first reads it. If the pipe is at EOF then, it is a Blob stream. `Bun.spawn()` reads the pipe once before it returns, and on Windows `exited` can resolve before EOF. <details><summary>Notes</summary> - Reproduction on the released build (1.4.1): - `new Blob([s]).stream().json()` rejects with `Failed to parse JSON`. A stream with a JavaScript source rejects with `JSON Parse error: Expected '}'`. - `proc.stdout.json()` with no await after `Bun.spawn()`: 11 of 50 runs took the buffered path when the parent and a fast child (`/bin/echo`) share one CPU. This is the debian case. - After `await proc.exited`, a grandchild that keeps the pipe open makes the streamed path run. This is the Windows case. - Empty input: `JSONParseWithException` throws nothing for a null string, and an empty input converts to one. A child that printed only a byte order mark got `JSON Parse error: Unexpected EOF` on the streamed path and `Failed to parse JSON` on the buffered path. Both paths now give the first. A zero-byte stdout was already the same on both paths. - #5859: in 2023 the helper caught the exception and returned it as a value. Today both helpers use a throw scope. The #5859 tests pass with `BUN_JSC_validateExceptionChecks=1`. - Baseline scan: the `:linux: x64-musl - verify-baseline` step flagged one `RDPMC` in `llint_op_jmp_wide32`. Each LLInt opcode handler starts with an embedded 4-byte opcode id, and the linear-sweep decoder desyncs on it. The allowlist already covers two sibling handlers for this reason. The same scan lists those two entries as stale, so the desync moved to this handler. The emulator phase of the same job passes, and the step passed on main at the same base commit. The three LLInt entries are blanket passes, as the triage guide in `scripts/verify-baseline-static/CLAUDE.md` says for a data-in-.text misdecode. - The helpers keep `Failed to parse JSON` for a string that failed to convert (a dead string, or a failed allocation). - The empty-body checks in `Blob.rs` run before the helpers. They resolve `null` or throw `Unexpected end of JSON input`. That is #24955, and this PR does not change them. - #33658 (open since July) makes the same change to the two helpers, and also removes the empty-body checks for #24955. This PR supersedes the helper half of #33658. After it lands, #33658 only needs its `Blob.rs` change. - Self-review, 5 concerns. Addressed: the narrowed claim, the empty-input case, the note that the failures were on PR builds, and the relation to #33658. Not addressed: `Blob::to_json_with_bytes` decodes a body that starts with FF FE as UTF-16LE, and the streamed path decodes it as UTF-8. That difference is separate from this change. - Tests on the debug ASAN build. The first three also ran with `BUN_JSC_validateExceptionChecks=1`. - `test/js/bun/spawn/readablestream-helpers.test.ts`: 32 pass. The released build fails 3 (the two new cases and `(after exited)`). - `test/js/web/fetch/body.test.ts`: 476 pass. The released build fails 34 (17 inputs, for `Request` and `Response`). - `test/js/bun/http/serve.test.ts`: 295 pass, 2 fail. The 2 failures (`root range port(#7187)` and `/bun:info to loopback clients`) also fail on the released build in this environment, which runs as root. - Also pass: `bun-file.test.ts`, `regression/issue/02367.test.ts`, `express.json.test.ts`, `spawn.ipc.test.ts`, `spawn.ipc.bun-node.test.ts`, and the json cases of `fetch.test.ts`. The one failure there, `bad permissions throws`, also fails as root on the released build. </details> <!-- robobun:evidence:begin --> --- **no test proof** · iteration 1 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/web/fetch/body.test.ts, test/js/bun/http/serve.test.ts <!-- robobun:evidence:end -->
Remove the three empty-body checks in Blob.rs that ran before the JSON
helpers. They resolved null for a fetch() or Bun.serve() body and threw
a hardcoded message for a Blob body. The helpers now parse the empty
text and throw the SyntaxError that JSON.parse("") throws.
eecc9a6 to
de493a1
Compare
|
Rebased onto main and trimmed. #41387 landed the helper change in |
There was a problem hiding this comment.
LGTM — small, well-tested spec-compliance fix.
Checked that the deleted Temporary-lifetime heap::take in to_json_with_bytes is not a leak: the fall-through path already arms TemporaryBytes(raw_bytes) (Blob.rs:2762) before the parse call, so the leaked Box<[u8]> is still reclaimed on empty and BOM-only input.
Verified all three storage arms (Blob / InternalBlob / WTFStringImpl) now uniformly reach the real parser, matching the fetch spec's "reject with what %JSON.parse% throws".
Grepped for other assertions on the old "Unexpected end of JSON input" string — only the one updated in bun-file.test.ts.
New tests follow harness conventions (port: 0, tempDir, await using, test.each, added to existing files) and cover the full .json() entry-point matrix.
Extended reasoning...
Overview
This PR removes three empty-body short-circuits from src/runtime/webcore/Blob.rs so that .json() on an empty body always goes through the real JSON parser and rejects with JSC's native SyntaxError: JSON Parse error: Unexpected EOF — the same error JSON.parse("") throws — instead of the previous divergent behavior where a fetch() Response resolved to null (InternalBlob/WTFStringImpl arms) or threw a hand-rolled V8-style message (Blob arm). One existing test assertion is updated for the new message, and a comprehensive describe.concurrent suite is added covering every body-holding path (fetch Response, Bun.serve incoming Request, constructed Response/Request/Blob, ReadableStream, Bun.file with empty and BOM-only files).
Security risks
None. This is a pure error-path behavioral change in JSON parsing of empty input; no auth, crypto, permissions, or untrusted-input parsing surface is affected. The change actually reduces hand-rolled code by deferring to the engine's own parser.
Level of scrutiny
Moderate, focused on memory safety. The one non-trivial deletion was the early return that explicitly reclaimed a leaked Box<[u8]> when LIFETIME == Temporary. I read the surrounding function and confirmed the fall-through path arms a TemporaryBytes(raw_bytes) RAII guard at line 2762 before any parse call, so the allocation is still freed on empty/BOM-only input — the deleted manual reclaim was only needed because the old early return happened before that guard was armed. The UTF-16LE branch (which has its own manual reclaim) is unreachable for empty input since no BOM is detected. The other two deletions (InternalBlob and WTFStringImpl returning JSValue::NULL) have no resource-ownership implications.
Other factors
The fix satisfies REVIEW.md's "fix the whole class" rule: all three body-storage variants are corrected together, and the test matrix exercises every .json() entry point rather than just the reported repro. Tests follow all harness conventions from CLAUDE.md/test/CLAUDE.md. The user-visible error-message change is the intended fix (aligning with the WHATWG spec and JSON.parse), and a grep confirmed only one existing test asserted the old string. A new commit landed since the prior review on this PR, so posting a fresh verdict is warranted.
|
Closing as stale: this PR conflicts with main, and its last commit is from 2026-09-05. The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR. |
Problem
fetch()of a response with an empty body:response.json()resolvesnull. Node rejects with theJSON.parseSyntaxError. Fixes Response.json behavior is different between bun and node #24955. ARequestbody inBun.serve()resolvesnullthe same way.Blob,Response("")orBun.file()body rejects with a hardcodedUnexpected end of JSON input. A streamed empty body rejects withJSON Parse error: Unexpected EOF, theJSON.parse("")message.src/runtime/webcore/Blob.rsthat run before the JSON helpers:to_json_with_bytes(line 2726) throws the hardcoded message,Any::to_json(lines 6336 and 6348) returnsnullfor anInternalBlobor aWTFStringImplbody.Fix
EncodedSlice__toJSONObjectorBunString__toJSONas any other text does. Since Reject json() with the JSON.parse SyntaxError on the buffered path #41387, both helpers parse an empty input as""and throw theJSON.parseSyntaxError.JSON.parse("")SyntaxError. This is what the fetch spec says (json()runsJSON.parseon the text and rethrows) and what Node does.test/js/web/fetch/body.test.ts(newdescribeblock, 11 of its 13 cases fail on bun 1.4.1, and the<empty>cases of thejson()table now check the message). Alsotest/js/bun/util/bun-file.test.ts,test/js/bun/spawn/readablestream-helpers.test.tsandtest/js/bun/http/serve.test.tson the debug build.Background
Bodyholds its bytes in one of several forms: aBlob(a store with bytes or a file), anInternalBlob(an owned byte vector, what afetch()orBun.serve()body arrives as), or aWTFStringImpl(a JS string body).Any::to_jsondispatches on the form.EncodedSlice__toJSONObject(src/jsc/bindings/bindings.cpp) andBunString__toJSON(src/jsc/bindings/BunString.cpp) are the two C++ helpers that runJSONParseWithExceptionon the text.Blob.rschange.Notes
await (await fetch(url)).json()where the server answersnew Response(""): resolvesnull. With a204: rejectsUnexpected end of JSON input.new Response("").json(),new Blob([]).json(),Bun.file(empty).json():Unexpected end of JSON input.new Blob([]).stream().json()and aResponseover an emptyReadableStream:JSON Parse error: Unexpected EOF.new Response("").json()rejects withSyntaxError: Unexpected end of JSON input, the V8 message ofJSON.parse(""). JSC's message for the same input isJSON Parse error: Unexpected EOF. The tests compare againstJSON.parse("")of the running engine, not against a literal.Blob(["\uFEFF"]), a file that holds only a byte order mark) ran through the removed check too.BOM::detect_and_splitstrips the mark, the helpers see an empty slice and throw the same error.Temporarylifetime branch into_json_with_bytesis still freed: the_freeguard below the removed check covers the empty slice.Blobnow reachesset_is_ascii_flag(true)fromjson(), as a BOM-prefixedBlobwith ASCII content already does fromtext()andjson(). The flag is wrong for the store in both cases, and a laterslice(1).text()decodes the BOM bytes as Latin-1. That is the helper bug Blob: keep the caller's Blob intact after a slice read, an array body, and a rejected bytes() #38503 fixes inset_is_ascii_flag. This PR does not add a guard at the call site.set_is_ascii_flagstamp above (owned by Blob: keep the caller's Blob intact after a slice read, an array body, and a rejected bytes() #38503).bun-file.test.tspins the message for a BOM-only file. It changes from the hardcoded text to theJSON.parse("")message.BUN_JSC_validateExceptionChecks=1on thejson()tests ofbody.test.ts: 81 pass.serve.test.ts: 295 pass, 2 fail (root range port(#7187),/bun:info to loopback clients). Both fail the same way on the released build in this environment, which runs as root.no test proof · iteration 5 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/web/fetch/body.test.ts