Repository navigation
Conversation
|
Status: reproduced on release builds of main (92e819d), 1.4.4, 1.4.0 and 1.3.14. A The PR has a new mechanism (c6219a9). The plugin object of a The two lifetime tests ask the heap snapshot what keeps the object alive (019da83). The Notes of the PR body say why a collection alone cannot tell. CI on 019da83 (build 133891): 180 of 181 jobs passed, and the 6 new tests pass on every lane, Windows included. One job failed: It needs a maintainer to confirm two choices, listed first in the Notes of the PR body: hooks read the stores of the |
|
No actionable comments were generated in the recent review.
|
| Layer / File(s) | Summary |
|---|---|
Define and route plugin async-context modes src/jsc/bindings/JSBundlerPlugin.h, src/runtime/api/JSBundler.rs, src/runtime/bake/config/bundler.rs, src/runtime/server/server_body.rs |
The Rust and C++ interfaces define None and Caller modes. Bun.build() passes Caller; bake and server plugin creation pass None. |
Capture and restore context for hooks src/jsc/bindings/JSBundlerPlugin.cpp |
The plugin stores caller context without module-graph frames. Hook dispatch and on-end callbacks enter that context with the active module graph. Tombstoning clears the stored context. |
Validate build async-context propagation test/bundler/bundler_plugin.test.ts |
Tests check the async store observed by hooks, deferred work, result accessors, setup callbacks, and overlapping builds. |
Validate context and module-graph lifetime test/bundler/bundler_plugin.test.ts |
Tests check collection of completed-build stores, hook execution in the build’s module graph, host state isolation, and behavior while a hook remains pending. |
Possibly related PRs
- oven-sh/bun#34112: Stores and restores the
ModuleGraphfor deferred virtual-module plugin results. - oven-sh/bun#46967: Captures and restores async context for HTMLRewriter transform handlers.
- oven-sh/bun#41561: Covers async context in direct stream pull, cancel, and close callbacks.
Suggested reviewers: dylan-conway, alii
Priority:
Merge Risk: 
Minimal · up to c6219
-
The change is mergeable after normal checks; no actionable issue remains identified.
Pre-merge checks: 
4
-
Full details: Description check
-
Explanation
The description follows the required template with both sections present. "### What does this PR do?" is covered by the Problem, Fix, Background, Downsides, and Notes content, which explain the bug, the chosen fix, the contract, lifetime handling, and measured costs. "### How did you verify your code works?" is covered by the test count, the tests that fail on main, the test suites run on release builds, and the heap-based lifetime checks. The description is very long, and parts of it are detailed. Some items need attention. The evidence banner states "no test proof" for test/bundler/bundler_plugin.test.ts and defers to CI for platform-specific tests. The Notes block also contains two open questions for a maintainer to confirm, which are unresolved in the description itself.
-
Finishing Touches: 💡 1
-
🛠️ Fix failing CI checks: 💡
-
- Commit to this branch
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands.
|
Updated 2:17 PM PT - Oct 27th, 2026
❌ @robobun, your commit 019da83 has 1 failures in
The baseline build crashed or failed tests under 🧪 To try this PR locally: bunx bun-pr 41562That installs a local version of the PR into your bun-41562 --bun |
There was a problem hiding this comment.
LGTM — straightforward application of the existing internal/async_context_frame.run pattern to bundler plugin hooks.
What was reviewed:
run(frame, fn, thisArg?, ...args)signature matches all three call sites;thisArg: undefinedpreserves the original bare-call receiver, and.runuses.$applyinternally so tamper-proofing holds.- Tuple shape change: other readers (
for (var [filter] of callbacks)at addFilter, the merge loops) destructure by leading position only, andonBeforeParsekeeps its 4-tuple — no consumer breaks. onStartintentionally not touched: it invokes the callback synchronously insiderunSetupFunction, so it already inherits the caller's frame (test asserts this).- Test follows conventions:
tempDir,test.concurrent, single combined.toEqual; theBun.sleep(0)exercises context propagation across an await, not a timing wait.
Extended reasoning...
Overview
The PR captures the active async-context frame ($getInternalField($asyncContext, 0)) alongside each onLoad/onResolve/onEnd callback at registration time in src/js/builtins/BundlerPlugin.ts, and dispatches through require("internal/async_context_frame").run so AsyncLocalStorage.getStore() works inside those hooks. The stored tuples grow from [filter, callback] to [filter, callback, asyncContext] (and onEndCallbacks becomes an array of [callback, asyncContext]). JSBundlerPlugin.cpp only drops a now-resolved TODO comment. A new concurrent test in test/bundler/bundler_plugin.test.ts verifies each hook — including after an await inside onLoad — sees the store from its registration frame.
Security risks
None. The change routes user callbacks through an internal helper that already uses tamper-proof .$apply, and the captured frame is an opaque internal-field value the user cannot forge. No new user-controlled input parsing, no auth/crypto/path handling.
Level of scrutiny
Low-to-moderate. This is a small, mechanical fix that mirrors the exact pattern already shipping in src/js/node/_http_client.ts and src/js/node/http2.ts (module-level const runInFrame = require("internal/async_context_frame").run; here it's per-builtin-function since builtins/ files are compiled as standalone functions with no shared module scope). I checked every other reader of the tuples in BundlerPlugin.ts — they either destructure only the leading [filter] or iterate the Map's [namespace, callbacks] entries — so the added third element is invisible to them. onBeforeParse keeps its [filter, napiModule, symbol, external] shape, which is correct since it's a native callback with no JS async context. onStart is correctly excluded because it calls the callback synchronously during setup (line 262).
Other factors
No CODEOWNERS cover these paths. The bug hunt exited on dry_streak with no findings and no ruled-out candidates. The PR timeline has no prior reviews or objections. The test uses harness tempDir, test.concurrent, a single combined-object .toEqual, and asserts a nested als.run("registration", ...) around onEnd to prove the capture point is registration rather than the outer Bun.build call — a meaningful distinction the fix's design implies. The one added source comment explains why the capture happens at registration (bundle thread dispatches later outside any JS frame), which is load-bearing rather than narration.
6b20d21 to
c348ee7
Compare
…f the Bun.build() call The bundle thread hands each onResolve / onLoad request and the onEnd callbacks to the JS thread as event-loop tasks. The two native calls that dispatch them (dispatchRequest and JSBundlerPlugin__runOnEndCallbacks) called the builtin in whatever async context the event loop had. A plugin registered inside AsyncLocalStorage.run() never saw its store in a hook. The plugin object of a Bun.build() call now keeps the stores that are current when it is made, before the first setup() runs, and both dispatches enter them for the call. The kept context has no Bun.ModuleGraph frames, so a build does not keep the graph that started it alive: the dispatch enters the graph the event loop called it for again on top. The context is released at the tombstone, because script can keep the plugin object after the build. JSBundlerPlugin__create takes which stores the hooks run in, so each of its three callers states it. The plugin object of Bun.serve is made from the event loop at the first request, and nothing tombstones a dev server's plugin object, so their hooks stay as they are.
567f4ab to
c6219a9
Compare
…tores alive The two lifetime tests waited for a collection. JavaScriptCore also marks what a word on the native stack points at, and a frame that the loop enters again on each turn can keep such a word. The graph was then never collected on Windows. Both tests now use Lifetimes from the module graph tests. It asks the heap snapshot if a root reaches the object. The graph test holds the graph until the first hook has run, because a collection before that gives the build up.
|
Closing as stale: this PR conflicts with main, and its last commit is from 2026-10-27. The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR. |
Problem
Bun.build()plugin registered insideAsyncLocalStorage.run()loses the caller's store in its hooks:als.getStore()inonResolve,onLoadandonEndisundefined.setup()andonStartread the store. It never worked.dispatchRequest(JSBundlerPlugin.cpp:598) andJSBundlerPlugin__runOnEndCallbacks(:773) call it in the event loop's async context.Fix
Bun.build()call keeps the stores current at its creation, before the firstsetup(). Both dispatches enter them with anAsyncContextScope.Bun.ModuleGraphframes.test/bundler/bundler_plugin.test.ts, all fail on main. Also the other plugin,Bun.build,Bun.serveHTML and Bake suites.Background
AsyncLocalStorageis one slot per global. Native code that calls script later must restore it.JSBundlerPlugin) is the native cell behindsetup(build). After its tombstone it answers no request.Downsides
.text+1024 bytes.Bun.serveHTML routes and of Bake still see no store.Bun.build()caller's store while that caller waits for an asyncsetup().Notes
An audit of
AsyncLocalStoragepropagation found this. No issue reports it. On released versionsAsyncLocalStorage.bind()around each hook is the way to keep a store.Repro
Two things for a maintainer to confirm
Bun.build()call, read before the firstsetup()runs. It does not read the stores of itsonLoad()/onResolve()/onEnd()registration call. This is the reverse of what this PR carried in September.Bun.ModuleGraphframes. The dispatch enters the graph that the event loop called the hook for again on top of the kept stores, asWebSocketdoes since WebSocket: real closing handshake, one failure path,wsrewritten on native transports (consolidates the open WebSocket PRs) #45223 (Bun::asyncContextWithoutModuleGraphs,Bun::ModuleGraphContextScope).The contract
setup()registers insideals.run("registration"), or after anawait, reads the store of theBun.build()call.als.enterWith()insidesetup()does not change what hooks read.AsyncLocalStorage.bind(callback)is the opt-in for one hook: a bound hook keeps the store it was bound in, as on main.toJSONofexports,toStringof a thrown value, code after anawaitorawait args.defer(), anonEndthat a hook registers late, andonEndof a failed build.rollup()call, not the store the plugin object was made in. esbuild 0.21.5 runs them in the store of the call that started its service. Neither runs a hook in the store of its registration.Reading another caller's store
Bun.build()runs the event loop inside the call while an asyncsetup()is pending. A hook of another build that is dispatched during that wait runs in the waiting caller's store on main.first build, notsecond build.fscallbacks andBun.servehandlers do the same on main. That belongs to the wait: event loop: never re-enter from inside a dispatch callback (de-block expect().resolves and HTMLRewriter.transform, then assert) #33261 item 3, Stop running the event loop inside JavaScript calls #46545, Bun.build: return the promise before a pending plugin setup() settles #42680, Suspend the caller's AsyncLocalStorage context while a blocking wait runs the event loop #37932.Why the plugin object and the two native calls
onResolveandonLoadrequest passesdispatchRequest, and everyonEndpassesJSBundlerPlugin__runOnEndCallbacks. No other place sees all hooks.JSBundlerPlugin__runOnEndCallbackshad// TODO: use AsyncContextFrame?since Bundler changes to bring us closer to esbuild's api #22076.Bun.build()lives for one build, so what it keeps is released with the build.JSBundlerPlugin__createtakes a required argument that says which stores the hooks run in. Each of its three callers states its choice:Bun.build(): the caller's.Bun.serveHTML routes (server_body.rs): none. The plugin object is made from the event loop at the first request. The store of theBun.serve()call is not current there, and a capture would take whatever the event loop has at that moment.bake/config/bundler.rs): none. Nothing tombstones a dev server's plugin object when the server stops (bake: consolidate the open robobun dev-server, HMR runtime, production build and router fixes #39488), so a kept context would never be released.BundlerPlugin.tsand ran each callback throughinternal/async_context_frame. None of it is kept. It gave hooks the registration store, added one rest array and one JS call per hook call for every plugin build, put the contexts into tuples that script can reach, and left getters,toJSONand the thrown-value path in the event loop's context.Bun.ModuleGraph
Bun.ModuleGraphidentity. On main the event loop already enters the caller's graph for both tasks, so a graph's build runs its hooks as the graph. That does not change: the test readsthe graphandthe hoston both builds.Lifetime
onLoadargsobject orargs.defer. The tombstone clears the kept context, so a kept plugin object does not keep the store. Test: 5 finished builds with the builder kept, and no root reaches any of the 5 stores. Without the clear, the kept builder reaches all 5.Bun.ModuleGraphis disposed during the build, the requests that the plugins hold are cancelled and noonEndruns, as on main.Measurements
Release builds of main 92e819d and of this PR on it.
AsyncLocalStorage: +51 instructions by disassembly (28 inline, 8 in theAsyncContextScopeconstructor, 15 in its destructor), 2 direct calls, 0 allocations, 0 slot writes. One scope per dispatch: 203 of 203 and 403 of 403 dispatches (gdb). The whole-process count per virtual import (oneonResolveand oneonLoad) is 832,326 on main and 832,293 here, spread 577 and 848: the change is inside the noise.AsyncLocalStorage: +0 rest arrays, +0 internal modules, +0 heap objects (gdbhit counts at N=100 and N=200,heapStatsover 20,000 registrations).Bun.ModuleGraphin the process: +0AsyncContextFramewrappers, +0 rest arrays, +0 heap cells, at most 2 slot writes. One moreStronghandle is freed per build.Bun.ModuleGraph: a host build allocates and frees 1Stronghandle per dispatch (main 0). A graph's own build does that on main already (263 and 263 at N=100), and allocates 1 more heap cell per dispatch here: the graph frame that is entered on top.Bun.build()with plugins: one capture inJSBundlerPlugin__create, 0 new FFI calls, 0 new exported functions (15JSBundlerPlugin__symbols on both).Bun.build()without plugins: +0 (JSBundlerPlugin__createis not called).JSBundlerPlugin:sizeof360 to 368 bytes (lldb, debug builds). Allocated per cell: 362 and 362 bytes (estimateShallowMemoryUsageOf)..text+1024 bytes.matchOnLoad+239,matchOnResolve+283,runOnEndCallbacks+247,create+76,tombstone+30, GC visitor +192 and +32 bytes (llvm-size -Aandnm -S).AsyncLocalStorage: main 53.8 us, this PR 51.7 us, noise floor 32 us (20 interleaved runs each, 40,002 hook calls). The delta is below the noise floor.Tests
Six subprocess fixtures in
test/bundler/bundler_plugin.test.ts. All six fail on main.onEndof a failed build under boththrowstates.setup()registers inside another store, or after anawait.Bun.build()call, and that the second call reads its own store after the wait.Bun.build()call.Bun.ModuleGraph. A host timer that ticks between the hooks reads no store and no graph.Bun.ModuleGraphthat started it: no root reaches the graph.Each part of the change removed alone fails a test: no restore at the end of the scope fails 3 and 5, no GC visit of the kept context fails 4, no tombstone clear fails 4, graph frames left in the kept context fail 6.
Tests 4 and 6 ask the heap what keeps the object alive. The section below says why.
Equal results on release builds of main and of this PR:
bundler_plugin_chain,plugin-error-nested-throw,plugin-sync-exception-fallback,native-plugin,bun-build-api,test/js/bun/plugin/plugins.test.ts,bun-serve-html,test/bake/dev/plugins.test.ts,test/bake/serve-plugins-dev-server.test.ts,module-graph,module-graph-isolation,module-graph-callbacks,AsyncLocalStorage.test.ts. The new tests and theonEnd, resolve and load groups pass withBUN_JSC_validateExceptionChecks=1.Why tests 4 and 6 read the heap
Bun.gc(true)in a loop until the graph was collected. In CI that loop did not collect the graph in any attempt on Windows 2019 x64 and Windows 11 aarch64. On alpine 3.23 x64, alpine 3.23 aarch64 and ubuntu 25.04 aarch64 it failed on the first attempt and passed on the second.setImmediateturns shows it. The graph is not collected after 200 collections in 31 of 40 runs on main 92e819d, and in 33 of 40 runs with this PR.generateHeapSnapshotForDebugging()gives the cells that reach it (five on main, six with this PR), and none of them is a root. The top one is aPromisewith no incoming edge and no root entry. It is the result of theasyncarrow inrunOnLoadPluginsfor the hook that waits. Its.then()reaction keeps the async context of the dispatch, and that context names the graph.Promise.gdbon main, stopped inJSC__VM__runGCin that state, with the frames from the frame pointer chain (abridged):fp-72ofJSC::JSModuleRecord::evaluate. The loop is the top-levelawaitof the fixture, so each turn enters these two frames again at the same stack address. A hardware watchpoint on those words saw 0 writes over the next 3 turns, on main and with this PR.Lifetimesfromtest/js/bun/module-graph/module-graph-lifetimes.ts, as theBun.ModuleGraphcollection tests do. It collects from a timer callback. For an object that is still not finalized it reads the heap snapshot, and reports the path from a root or nothing.Lifetimesreported no root in 60 of 60. With graph frames left in the kept context it reportedroot(ProtectedValues) BundlerPlugin -Internal:0-> Frame -Property:prev-> Object -Property:storage-> ModuleGraphin 60 of 60.Not changed here
bunfig.toml[serve.static]on static HTML routes and the dev server, andbake.config.tsplugins. They need a capture where the server is made. Before that the server must release its plugin object: Bun.serve: release the [serve.static] plugin cell when the server is freed #37805 forBun.serve, bake: consolidate the open robobun dev-server, HMR runtime, production build and router fixes #39488 for Bake.JSBundlerPlugin__loadAndResolvePluginsForServestays unscoped. It has no context to enter until a serve capture exists.Bun.plugin()hooks read the caller's store for theimport()specifier and no store for its static dependencies, on 1.3.14 too. That loss is in the module loader.onBeforeParsenative plugins run on parser threads and call no script.Related
Plugin::createlines: RemoveBunPluginTarget, the plugin target value that nothing reads #46089 (removesBunPluginTarget), Bun.serve: release the [serve.static] plugin cell when the server is freed #37805, Bun.build: return the promise before a pending plugin setup() settles #42680 (replacesPlugin::createwithcreate_unrooted), feat(bake): await plugin preparation and track load dependencies #46706, Stop running the event loop inside JavaScript calls #46545. The one that lands second carries thePluginAsyncContextargument over.no test proof · iteration 2 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/bundler/bundler_plugin.test.ts