Repository navigation
Type-erase source-provider dispatch and move bake's providers out of bun_sourcemap - #32077
Conversation
|
Updated 10:46 AM PT - Jun 11th, 2026
❌ @robobun, your commit 6cd0221 has 2 failures in
🧪 To try this PR locally: bunx bun-pr 32077That installs a local version of the PR into your bun-32077 --bun |
|
@robobun adopt |
|
Adopted and ready for review. Rebased on main after part 1 merged (mergeable, same 22-file scope), review feedback addressed (boxed provider entries replacing the slot-table panic, churn test, inspector exactly-once fix), and all affected suites pass locally. CI status: the diff is green. Across the last three runs, 285+ of 287 jobs pass; the only failures are (1) the darwin-14-aarch64 lane dying in vendor-fixture tooling (missing tsup in the elysia checkout), which is currently hitting many unrelated branches, and (2) one debian snapshot flake that passed on the byte-identical tree in the previous build (the retrigger commit was empty). Needs a maintainer call on merging past those lanes. |
|
@robobun can you fix my comment? |
WalkthroughThis PR mechanically renames ChangesServerComponentsSsr rename, provider type-erasure, and source-provider consolidation
Possibly related PRs
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/runtime/bake/DevServer.rs (1)
4727-4735:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winConsume the inspector handle on the first failure response.
encode_serialized_failures()already emits the bundle-failed notification. This branch passesinspector_agent_ptr.map(...)without clearing it, so if the same failed bundle also has queued HTTP requests, the first request response will callnotify_bundle_failed()again via the latertake(). That produces duplicate inspector events for one bundle failure.Suggested fix
dev.send_serialized_failures( DevResponse::Promise(PromiseResponse { promise: current_bundle!().promise.strong.take(), global, }), failures, ErrorPageKind::Bundler, - inspector_agent_ptr.map(|p| unsafe { &*p }), + inspector_agent_ptr.take().map(|p| unsafe { &*p }), )?;🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/runtime/bake/DevServer.rs` around lines 4727 - 4735, The branch passes inspector_agent_ptr.map(...) into send_serialized_failures causing duplicate notify_bundle_failed() events; change to consume the inspector handle so it’s only used once: replace inspector_agent_ptr.map(|p| unsafe { &*p }) with inspector_agent_ptr.take().map(|p| unsafe { &*p }) (or otherwise take() the Option before mapping) when constructing the DevResponse::Promise so the inspector pointer is cleared after the first failure response; keep the SAFETY comment intact and ensure this happens in the same place where send_serialized_failures is called.src/jsc/SavedSourceMap.rs (1)
397-414:⚠️ Potential issue | 🟠 Major | ⚡ Quick winRe-check the slot identity before overwriting or removing it.
This branch parses with the mutex unlocked, then blindly
put_value()s orremove()s whatever is currently stored underh. If a reload installs new mappings or a replacement provider for the same path in between, the stale parse result will either overwrite the fresh entry or delete it on the failure path.Please compare the relocked slot against the copied provider from Line 390 and only replace/remove when it still refers to that same provider.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/jsc/SavedSourceMap.rs` around lines 397 - 414, The code parses a source map while unlocked and then blindly calls put_value/remove under the lock, risking overwriting/removing a newer entry; after reacquiring the mutex (after self.lock()) fetch the current slot value from self.map_mut().get(&h) and compare its identity to the original provider/slot that was present when you parsed (the same provider variable/box used to produce parse and parsed_map). Only call put_value or remove (and only release the parsed_map on removal) if the stored slot still refers to that same provider; otherwise drop/release the parsed_map without mutating the table. Use pointer/box identity (raw pointer or Arc::ptr_eq) to perform the comparison and guard both the put_value and the removal branch accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/sourcemap/ParsedSourceMap.rs`:
- Around line 140-144: ParsedSourceMap currently stores only a borrowed raw
provider pointer (via SourceContentPtr::from_source_provider) which
AnySourceProvider::get_source_map later dereferences, risking UAF when
SavedSourceMap::remove_source_provider unregisters the provider; fix by changing
ParsedSourceMap to own a refcounted provider handle (e.g., store an Arc<dyn
AnySourceProvider> or an owned FFI handle) or eagerly copy the source/sourcemap
bytes into ParsedSourceMap instead of keeping the raw pointer so lookups via
get_source_map remain valid even after unregister; update constructors that
create ParsedSourceMap (the path using SourceContentPtr::from_source_provider)
and ensure remove_source_provider drops only table-owned state while Arc clones
keep provider alive.
In `@test/bake/dev/server-sourcemap.test.ts`:
- Around line 154-193: The test currently rewrites the same file content but
always asserts the mapped position `pages/churn.tsx:6:1`, so a stale sourcemap
would still pass; modify churnPage and the loop so each revision moves the
mapped throw site (e.g., change the throw line number by inserting a variable
number of blank lines or adjust column) and compute the expected remapped
coordinate per iteration, then update the regexp assertion to use that per-round
line/column instead of the fixed `:6:1`; reference churnPage(name),
dev.write("pages/churn.tsx", ...), and the expect(...).toMatch(...) assertion to
implement the dynamic expected location.
---
Outside diff comments:
In `@src/jsc/SavedSourceMap.rs`:
- Around line 397-414: The code parses a source map while unlocked and then
blindly calls put_value/remove under the lock, risking overwriting/removing a
newer entry; after reacquiring the mutex (after self.lock()) fetch the current
slot value from self.map_mut().get(&h) and compare its identity to the original
provider/slot that was present when you parsed (the same provider variable/box
used to produce parse and parsed_map). Only call put_value or remove (and only
release the parsed_map on removal) if the stored slot still refers to that same
provider; otherwise drop/release the parsed_map without mutating the table. Use
pointer/box identity (raw pointer or Arc::ptr_eq) to perform the comparison and
guard both the put_value and the removal branch accordingly.
In `@src/runtime/bake/DevServer.rs`:
- Around line 4727-4735: The branch passes inspector_agent_ptr.map(...) into
send_serialized_failures causing duplicate notify_bundle_failed() events; change
to consume the inspector handle so it’s only used once: replace
inspector_agent_ptr.map(|p| unsafe { &*p }) with
inspector_agent_ptr.take().map(|p| unsafe { &*p }) (or otherwise take() the
Option before mapping) when constructing the DevResponse::Promise so the
inspector pointer is cleared after the first failure response; keep the SAFETY
comment intact and ensure this happens in the same place where
send_serialized_failures is called.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 32fa060a-38d8-4ad7-8f8c-35e523271942
📒 Files selected for processing (29)
src/ast/target.rssrc/bundler/ParseTask.rssrc/bundler/bundle_v2.rssrc/bundler/linker_context/computeChunks.rssrc/bundler/options.rssrc/bundler/transpiler.rssrc/codegen/generate-host-exports.tssrc/css/targets.rssrc/jsc/Debugger.rssrc/jsc/SavedSourceMap.rssrc/jsc/VirtualMachine.rssrc/jsc/virtual_machine_exports.rssrc/options_types/bundle_enums.rssrc/resolver/options.rssrc/runtime/bake/DevServer.rssrc/runtime/bake/DevServer/HmrSocket.rssrc/runtime/bake/dev_server/inspector_agent.rssrc/runtime/bake/dev_server/mod.rssrc/runtime/bake/mod.rssrc/runtime/bake/source_provider_exports.rssrc/runtime/jsc_hooks.rssrc/runtime/server/InspectorBunFrontendDevServerAgent.rssrc/runtime/server/mod.rssrc/sourcemap/ParsedSourceMap.rssrc/sourcemap/lib.rssrc/sourcemap_jsc/lib.rssrc/sourcemap_jsc/source_provider.rssrc/standalone_graph/StandaloneModuleGraph.rstest/bake/dev/server-sourcemap.test.ts
💤 Files with no reviewable changes (6)
- src/runtime/server/InspectorBunFrontendDevServerAgent.rs
- src/sourcemap_jsc/source_provider.rs
- src/sourcemap_jsc/lib.rs
- src/runtime/server/mod.rs
- src/jsc/VirtualMachine.rs
- src/runtime/jsc_hooks.rs
|
On the two review findings posted outside the diff range:
|
|
conflicts @robobun |
Replace the 3-slot dispatch intern table (and its capacity panic) with heap-boxed AnySourceProvider entries stored under a single tag: the (handle, dispatch) pair travels together, so a provider entry without its dispatch fn, or more dispatch fns than slots, cannot be represented. The box is table-owned and released on replace, remove, and drop via a shared release_value helper; the provider FFI handle inside stays borrowed as before.
Each round replaces the file's registered source provider and re-materializes the parsed map from it, so server stack remapping is pinned across repeated reloads rather than only the first install. Exercises the SavedSourceMap provider entry replace and release paths.
A stale first-installed sourcemap could satisfy a fixed expected position; filler lines now move the throwing function down one line per round so each round's assertion only passes with the freshly registered map.
The queued-request loop and the no-consumer fallback already take() the agent pointer for exactly-once notification; the promise response branch did not, so a failed bundle with a pending promise notified notify_bundle_failed twice (once more via the first queued request or the fallback).
3e804c9 to
55ca678
Compare
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/jsc/SavedSourceMap.rs (1)
385-415:⚠️ Potential issue | 🟠 Major | ⚡ Quick winRevalidate the table slot before applying the parse result.
After Line 391 unlocks, another thread can replace or remove
path. The success path at Line 403 then blindly overwrites that newer entry with a staleParsedSourceMap, and the failure path at Lines 411-414 blindly removes whatever is there now. Save the original raw slot value before unlocking and onlyput_value/removeif the slot still matches it after relocking.Suggested direction
- let tagged = Value::from(Some(*mapping)); + let original = *mapping; + let tagged = Value::from(Some(original)); let tag = tagged.tag(); ... } else if let Some(provider) = tagged.get::<AnySourceProvider>() { let provider = unsafe { *provider }; self.unlock(); if let Some(parse) = provider.get_source_map(path, Default::default(), hint) { if let Some(ref parsed_map) = parse.map { - let _ = - self.put_value(path, Value::init(Arc::into_raw(Arc::clone(parsed_map)))); + self.lock(); + let still_same = self.map_mut().get(&h).copied() == Some(original); + self.unlock(); + if still_same { + let _ = self.put_value( + path, + Value::init(Arc::into_raw(Arc::clone(parsed_map))), + ); + } return parse; } } self.lock(); - if let Some(removed) = self.map_mut().remove(&h) { - unsafe { Self::release_value(Value::from(Some(removed))) }; + if self.map_mut().get(&h).copied() == Some(original) { + if let Some(removed) = self.map_mut().remove(&h) { + unsafe { Self::release_value(Value::from(Some(removed))) }; + } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/jsc/SavedSourceMap.rs` around lines 385 - 415, Before unlocking the mutex, capture the current raw slot value for `path` (the value stored in the hash table, e.g. the `removed`/raw entry) and after you reacquire the lock compare that saved raw pointer/value to the current slot; only call `self.put_value(path, Value::init(Arc::into_raw(Arc::clone(parsed_map))))` when the slot still equals the saved raw value, and only call `self.map_mut().remove(&h)` / `Self::release_value(...)` when the slot still equals the saved raw value — otherwise skip the overwrite/remove to avoid replacing a newer entry. Ensure comparisons use the same `Value`/raw pointer representation you saved before the `self.unlock()` so ownership/release semantics remain correct for `Value::from(Some(...))`.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@src/jsc/SavedSourceMap.rs`:
- Around line 385-415: Before unlocking the mutex, capture the current raw slot
value for `path` (the value stored in the hash table, e.g. the `removed`/raw
entry) and after you reacquire the lock compare that saved raw pointer/value to
the current slot; only call `self.put_value(path,
Value::init(Arc::into_raw(Arc::clone(parsed_map))))` when the slot still equals
the saved raw value, and only call `self.map_mut().remove(&h)` /
`Self::release_value(...)` when the slot still equals the saved raw value —
otherwise skip the overwrite/remove to avoid replacing a newer entry. Ensure
comparisons use the same `Value`/raw pointer representation you saved before the
`self.unlock()` so ownership/release semantics remain correct for
`Value::from(Some(...))`.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: b98ce4c4-1fae-4e72-9a8a-a235fecce8f1
📒 Files selected for processing (22)
src/ast/target.rssrc/bundler/ParseTask.rssrc/bundler/bundle_v2.rssrc/bundler/linker_context/computeChunks.rssrc/bundler/options.rssrc/bundler/transpiler.rssrc/css/targets.rssrc/jsc/SavedSourceMap.rssrc/jsc/VirtualMachine.rssrc/jsc/virtual_machine_exports.rssrc/options_types/bundle_enums.rssrc/resolver/options.rssrc/runtime/bake/DevServer.rssrc/runtime/bake/mod.rssrc/runtime/bake/source_provider_exports.rssrc/runtime/jsc_hooks.rssrc/sourcemap/ParsedSourceMap.rssrc/sourcemap/lib.rssrc/sourcemap_jsc/lib.rssrc/sourcemap_jsc/source_provider.rssrc/standalone_graph/StandaloneModuleGraph.rstest/bake/dev/server-sourcemap.test.ts
💤 Files with no reviewable changes (4)
- src/sourcemap_jsc/source_provider.rs
- src/jsc/VirtualMachine.rs
- src/runtime/jsc_hooks.rs
- src/sourcemap_jsc/lib.rs
Part 2/3 of the bake dev-server decoupling series (based on part 1).
bun_sourcemap(a generic low-tier crate) defined bake's concrete source-provider types, declared FFI externs to bake's C++, knew the dev-server lookup policy and warning text, andSourceContentPtrbit-packed a closed provider-kind discriminant that forced the generic crate to name bake types to reconstitute dispatch.SourceContentPtrnow stores a type-erasedfnpointer captured at pack time via a genericfrom_source_provider::<P: SourceProvider>(), soParsedSourceMapreferences only the pre-existingSourceProvidertrait.SavedSourceMapstores registered providers as heap-boxedAnySourceProviderentries under a single tag, so the (handle, dispatch) pair always travels together. The box is table-owned and released on replace/remove/drop through a sharedrelease_valuehelper; the provider FFI handle inside stays borrowed as before.bake/source_provider_exports.rs.The sourcemap dispatch has no behavior change: it goes through the same monomorphized functions, now reached via an erased pointer instead of a nominal type switch. One small behavior fix rides along on lines this PR already touches (flagged by review): the promise response branch in
finalize_bundlenowtake()s the inspector agent pointer like the sibling paths, sonotify_bundle_failedfires once per failed bundle instead of twice when a promise consumer exists.Verification as in part 1, plus a new provider-replacement churn case in
test/bake/dev/server-sourcemap.test.ts: repeated reloads of the same file re-register the provider and re-materialize the parsed map each round, with the throw site shifted one line per round so only the freshly registered map satisfies each assertion. Exercises theSavedSourceMapreplace and release paths (ASAN-visible if the box ownership were wrong).