Skip to content

Type-erase source-provider dispatch and move bake's providers out of bun_sourcemap - #32077

Merged
alii merged 13 commits into
mainfrom
ali/decouple-bake-2-sourcemaps
Jun 11, 2026
Merged

alii merged 13 commits into
mainfrom
ali/decouple-bake-2-sourcemaps

Conversation

@alii

@alii alii commented Jun 10, 2026 •

Copy link
Copy Markdown
Member

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, and SourceContentPtr bit-packed a closed provider-kind discriminant that forced the generic crate to name bake types to reconstitute dispatch.

  • SourceContentPtr now stores a type-erased fn pointer captured at pack time via a generic from_source_provider::<P: SourceProvider>(), so ParsedSourceMap references only the pre-existing SourceProvider trait.
  • SavedSourceMap stores registered providers as heap-boxed AnySourceProvider entries 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 shared release_value helper; the provider FFI handle inside stays borrowed as before.
  • Bake's concrete providers and their host exports move to 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_bundle now take()s the inspector agent pointer like the sibling paths, so notify_bundle_failed fires 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 the SavedSourceMap replace and release paths (ASAN-visible if the box ownership were wrong).

@robobun

robobun commented Jun 10, 2026 •

Copy link
Copy Markdown
Collaborator
Updated 10:46 AM PT - Jun 11th, 2026

❌ @robobun, your commit 6cd0221 has 2 failures in Build #61863 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 32077

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

bun-32077 --bun

@alii

alii commented Jun 10, 2026

Copy link
Copy Markdown
Member Author

@robobun adopt

@robobun

robobun commented Jun 10, 2026 •

Copy link
Copy Markdown
Collaborator

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.

Comment thread src/jsc/SavedSourceMap.rs Resolved
@alii

alii commented Jun 10, 2026

Copy link
Copy Markdown
Member Author

@robobun can you fix my comment?

Base automatically changed from ali/decouple-bake-1-inspector to main June 10, 2026 23:07
@coderabbitai

coderabbitai Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

This PR mechanically renames Target::BakeServerComponentsSsr to Target::ServerComponentsSsr across bundler, resolver, and transpiler logic while refactoring source-provider storage from enum-based dispatch to type-erased function pointers. SavedSourceMap consolidates to three tagged variants and introduces unified provider-registration APIs. Bake and DevServer provider implementations move to a new runtime FFI module, removing legacy bake plumbing from jsc_hooks.

Changes

ServerComponentsSsr rename, provider type-erasure, and source-provider consolidation

Layer / File(s) Summary
Target enum rename to ServerComponentsSsr
src/ast/target.rs, src/bundler/ParseTask.rs, src/bundler/bundle_v2.rs, src/bundler/linker_context/computeChunks.rs, src/bundler/options.rs, src/bundler/transpiler.rs, src/css/targets.rs, src/options_types/bundle_enums.rs, src/resolver/options.rs
BakeServerComponentsSsr renamed to ServerComponentsSsr in all predicate logic, bundler dispatch points, transpiler target mapping, and resolver main-fields selection.
Source-provider type-erasure in ParsedSourceMap
src/sourcemap/ParsedSourceMap.rs
AnySourceProvider changed from enum-based variant dispatch to type-erased struct holding raw pointer and function-pointer dispatch; SourceContentPtr changed from bit-packed u64 to multi-field struct carrying data, load_hint, and optional erased dispatch; introduce erased_get_source_map<P> shim for generic dispatch forwarding.
SourceProvider trait evolution and sourcemap module cleanup
src/sourcemap/lib.rs, src/sourcemap_jsc/lib.rs
Replace IS_DEV_SERVER and HAS_EXTERNAL_DATA constants with HAS_SOURCE_MAP_JSON capability flag and warn_invalid_source_map_json() method for provider-controlled error handling; remove BakeSourceProvider and DevServerSourceProvider opaque types from sourcemap crate; generalize external-lookup flow to gate on capability and use provider-supplied JSON.
SavedSourceMap consolidation and provider APIs
src/jsc/SavedSourceMap.rs
Consolidate table to three variants (ParsedSourceMap, AnySourceProvider, InternalSourceMap); add release_value() helper for centralized ownership teardown; introduce put_source_provider() and remove_source_provider() generic APIs replacing provider-specific methods; refactor get_with_content() to unified provider handling with erased dispatch and consistent cleanup via release_value().
RuntimeHooks and virtual-machine exports
src/jsc/VirtualMachine.rs, src/jsc/virtual_machine_exports.rs
Replace bake_per_thread_source_map hook with load_standalone_sourcemap returning Arc<ParsedSourceMap>; update Bun__addSourceProviderSourceMap to register via put_source_provider(AnySourceProvider::new(...)) and Bun__removeSourceProviderSourceMap to call remove_source_provider().
Runtime source-provider FFI exports and implementations
src/runtime/bake/mod.rs, src/runtime/bake/source_provider_exports.rs
Create source_provider_exports module with opaque FFI handles for C++ Bake and DevServer providers; implement SourceProvider trait for both with bake-global per-thread external-data return and dev-server JSON sourcemap capability; export add_bake_source_provider_source_map, add_dev_server_source_provider, remove_dev_server_source_provider host functions.
Cleanup: remove legacy bake plumbing
src/runtime/jsc_hooks.rs
Remove bake_per_thread_source_map implementation, bake_external_sourcemap helper, and __BUN_BAKE_EXTERNAL_SOURCEMAP export symbol; remove bake hook from __BUN_RUNTIME_HOOKS vtable initialization.
Inspector agent and test additions
src/runtime/bake/DevServer.rs, src/standalone_graph/StandaloneModuleGraph.rs, test/bake/dev/server-sourcemap.test.ts
Add inspector_agent_ptr.take() consumption safeguard in finalize_bundle to prevent reuse; update standalone-graph comment to clarify type-erased provider behavior; add integration test verifying server-side stack-frame remapping stays correct across repeated hot reloads.

Possibly related PRs

  • oven-sh/bun#32076: Concurrent changes to src/runtime/bake/DevServer.rs inspector agent handling around bundle lifecycle and failure notification paths.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main changes: type-erasing source-provider dispatch and moving bake's providers out of bun_sourcemap crate.
Description check ✅ Passed The PR description provides detailed context about the refactoring, rationale, and verification approach, but lacks explicit sections matching the template structure.
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.

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

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 win

Consume the inspector handle on the first failure response.

encode_serialized_failures() already emits the bundle-failed notification. This branch passes inspector_agent_ptr.map(...) without clearing it, so if the same failed bundle also has queued HTTP requests, the first request response will call notify_bundle_failed() again via the later take(). 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 win

Re-check the slot identity before overwriting or removing it.

This branch parses with the mutex unlocked, then blindly put_value()s or remove()s whatever is currently stored under h. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 1c90e5a and 5be7ddf.

📒 Files selected for processing (29)
  • src/ast/target.rs
  • src/bundler/ParseTask.rs
  • src/bundler/bundle_v2.rs
  • src/bundler/linker_context/computeChunks.rs
  • src/bundler/options.rs
  • src/bundler/transpiler.rs
  • src/codegen/generate-host-exports.ts
  • src/css/targets.rs
  • src/jsc/Debugger.rs
  • src/jsc/SavedSourceMap.rs
  • src/jsc/VirtualMachine.rs
  • src/jsc/virtual_machine_exports.rs
  • src/options_types/bundle_enums.rs
  • src/resolver/options.rs
  • src/runtime/bake/DevServer.rs
  • src/runtime/bake/DevServer/HmrSocket.rs
  • src/runtime/bake/dev_server/inspector_agent.rs
  • src/runtime/bake/dev_server/mod.rs
  • src/runtime/bake/mod.rs
  • src/runtime/bake/source_provider_exports.rs
  • src/runtime/jsc_hooks.rs
  • src/runtime/server/InspectorBunFrontendDevServerAgent.rs
  • src/runtime/server/mod.rs
  • src/sourcemap/ParsedSourceMap.rs
  • src/sourcemap/lib.rs
  • src/sourcemap_jsc/lib.rs
  • src/sourcemap_jsc/source_provider.rs
  • src/standalone_graph/StandaloneModuleGraph.rs
  • test/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

Comment thread src/sourcemap/ParsedSourceMap.rs Resolved
Comment thread test/bake/dev/server-sourcemap.test.ts Resolved
@robobun

robobun commented Jun 10, 2026

Copy link
Copy Markdown
Collaborator

On the two review findings posted outside the diff range:

  • DevServer.rs (inspector notified twice per failed bundle): fixed in 3e804c9. The queued-request loop and the no-consumer fallback already take() the agent pointer for exactly-once notification; the promise branch now does too. The flow predates this PR, but the PR already rewrites those lines for the shared-borrow change, so the one-token fix rides along (called out in the PR body).
  • SavedSourceMap.rs (parse with the mutex unlocked, then put/remove): this is the same flow main has, down to the comments; the refactor preserves it, and the new release_value on the removal path only corrects the ownership of whatever entry is removed. Re-validating slot identity after relocking would change longstanding semantics and belongs in a separate change if wanted.

@alii

alii commented Jun 11, 2026

Copy link
Copy Markdown
Member Author

conflicts @robobun

alii and others added 12 commits June 11, 2026 01:45
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).
@robobun
robobun force-pushed the ali/decouple-bake-2-sourcemaps branch from 3e804c9 to 55ca678 Compare June 11, 2026 01:49

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

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 win

Revalidate 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 stale ParsedSourceMap, and the failure path at Lines 411-414 blindly removes whatever is there now. Save the original raw slot value before unlocking and only put_value / remove if 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3e804c9 and 55ca678.

📒 Files selected for processing (22)
  • src/ast/target.rs
  • src/bundler/ParseTask.rs
  • src/bundler/bundle_v2.rs
  • src/bundler/linker_context/computeChunks.rs
  • src/bundler/options.rs
  • src/bundler/transpiler.rs
  • src/css/targets.rs
  • src/jsc/SavedSourceMap.rs
  • src/jsc/VirtualMachine.rs
  • src/jsc/virtual_machine_exports.rs
  • src/options_types/bundle_enums.rs
  • src/resolver/options.rs
  • src/runtime/bake/DevServer.rs
  • src/runtime/bake/mod.rs
  • src/runtime/bake/source_provider_exports.rs
  • src/runtime/jsc_hooks.rs
  • src/sourcemap/ParsedSourceMap.rs
  • src/sourcemap/lib.rs
  • src/sourcemap_jsc/lib.rs
  • src/sourcemap_jsc/source_provider.rs
  • src/standalone_graph/StandaloneModuleGraph.rs
  • test/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

@alii
alii merged commit 6e91d24 into main Jun 11, 2026
5 checks passed
@alii
alii deleted the ali/decouple-bake-2-sourcemaps branch June 11, 2026 21:37
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.

2 participants