Repository navigation
Conversation
|
Warning Review limit reached
Next review available in: 17 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (9)
WalkthroughThis PR adds callback-based async completion handling for NodeFS, rewires JS ChangesCallback-based fs completion pipeline
Possibly related PRs
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Updated 3:56 AM PT - Jul 7th, 2026
❌ @robobun, your commit 3d3c8ce has 1 failures in
🧪 To try this PR locally: bunx bun-pr 33366That installs a local version of the PR into your bun-33366 --bun |
|
CI on 291ea01: the two red lanes are not from this diff.
The 3f502db pushed since then addresses the |
There was a problem hiding this comment.
Thanks for addressing the fs.rm options-validation issue (3f502db) with a regression test. I didn't find any further issues, but this reworks GC-rooting and completion dispatch across all four async fs task types plus ~40 callback entry points, so it's worth a human pass over the FsCompletionRef detach/ensure_still_alive lifetime pattern and the Windows UVFSRequest path.
Extended reasoning...
Overview
This PR changes how node:fs callback APIs deliver their results: instead of .then(cb, cb) on an internal promise (which runs the callback as a microtask and inverts process.nextTick ordering), each async op gains a native *Cb sibling that stores the callback in a Strong, threads it through the async task as a new FsCompletion enum (Promise | Callback | Detached), and invokes it via EventLoop::run_callback from the completion task. Touches node_fs.rs (all four async task structs — AsyncFSTask, UVFSRequest, NewAsyncCpTask, AsyncReaddirRecursiveTask), node_fs_binding.rs (macro expansion for ~40 new *Cb host functions plus a CallShape argument splitter), node.classes.ts (codegen entries), src/js/node/fs.ts (rewrites every callback wrapper), trace_events.ts (span closure moved to the wrapped callback), and mechanical updates to the shell cp builtin and Blob store to pass FsCompletion::Detached/::init(_, None).
Prior feedback addressed
My earlier inline comment flagged that in the non-recursive fs.rm path, a native option-validation throw inside the lstatCb completion callback would surface as an uncaught exception. Commit 3f502db wraps that inner fs.rmCb in try/catch → callback(e), and adds a spawned-fixture test (hands invalid fs.rm options to the callback instead of throwing uncaught) covering { force: "yes" }, { retryDelay: "nope" }, null, and the recursive fast-path's synchronous throw. That resolves the concern.
Security risks
None identified. No auth/crypto/permission surface; the change is confined to how already-computed fs results are handed back to JS. Path validation and argument parsing are unchanged (the *Cb variant strips only the trailing callback and feeds the same args::*::from_js parsers).
Level of scrutiny
High. This is production-critical Node compat code with several patterns CLAUDE.md calls out for careful review: (1) the FsCompletionRef type is a Copy handle holding a raw *mut JSPromise / JSValue that must outlive a destroy() which drops the owning Strong, kept alive only by core::hint::black_box on the stack for JSC's conservative scan — the same shape as the pre-existing promise pattern, but now generalized across an enum; (2) the async-context snapshot via with_async_context_if_needed replaces what .then() did implicitly; (3) the IS_VOID trait constant + value.is_undefined() heuristic decides callback arity for every op; (4) the Windows-only UVFSRequest completion path is modified in parallel and only checked via rust:check-all, not run. None of these look wrong on read-through, and test coverage (ordering, ALS propagation, cb arity, error path, rm options) is solid — but the blast radius and memory-safety sensitivity put this well beyond what I'd auto-approve.
Other factors
The PR description documents verification against the full test/js/node/fs/ suite, all test-fs-* parallel tests, trace-events tests, and async_hooks/ALS tests with no new failures. The bug-hunting pass on the current revision found nothing. The one design question a maintainer might weigh in on is whether adding ~40 sibling binding methods (vs. a single flag argument) is the preferred shape long-term — the PR justifies it (positional-function-argument validation), but it's an API-surface decision on the internal binding.
3f502db to
4c01cad
Compare
|
Rebased onto On the two points raised for a human pass: ~40 sibling
Windows |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 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/runtime/node/node_fs.rs`:
- Around line 1925-1929: The early-return paths in
AsyncReaddirRecursiveTask::run_from_js_thread skip cleanup, so the task state
can leak when fs_result_to_js, error_to_js, or to_js fails. Update both
conversion-error branches to invoke Self::destroy before calling
completion.settle, matching the destroy-before-settle pattern already used by
AsyncFSTask/UVFSRequest. Re-audit the ownership in this method to ensure every
acquired task resource is released on all error exits.
In `@test/js/node/fs/fs.test.ts`:
- Around line 5123-5127: The callback-success matrix in fs tests includes
fs.symlink, which can fail for platform-specific permission reasons instead of
exercising callback behavior. Update the starters array in fs.test.ts to use a
cross-platform value-less fs callback such as fs.copyFile, or conditionally
include the symlink case only when the platform supports it. Keep the change
localized to the matrix setup so the test remains about callback semantics, not
symlink permissions.
- Around line 5101-5103: The test currently loads AsyncLocalStorage with a
dynamic require inside the AsyncLocalStorage context test, which should be moved
to a module-scope import instead. Update the fs.test.ts setup so
AsyncLocalStorage is imported once at the top of the file, then remove the
inline require from the test while keeping the rest of the test logic unchanged
in restores the AsyncLocalStorage context of the call site.
🪄 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: 2692a74c-a8a6-47c8-9927-55169e8c0195
📒 Files selected for processing (9)
src/js/internal/trace_events.tssrc/js/node/fs.tssrc/runtime/node/node.classes.tssrc/runtime/node/node_fs.rssrc/runtime/node/node_fs_binding.rssrc/runtime/shell/builtin/cp.rssrc/runtime/webcore/Blob.rssrc/runtime/webcore/blob/Store.rstest/js/node/fs/fs.test.ts
There was a problem hiding this comment.
The fs.rm options-validation fix and its test look right — no further issues found. This rewires every node:fs callback API through new native entry points and refactors GC rooting across four async task types, so it's worth a human pass before merge.
Extended reasoning...
Overview
This PR changes how node:fs callback APIs invoke their completion callbacks: instead of .then(cb, cb) on an internal promise (making the callback a microtask), each of ~41 fs operations gains a native *Cb binding that stores the callback in a new FsCompletion enum and invokes it from the event-loop task via EventLoop::run_callback. This restores Node's process.nextTick-before-microtasks ordering inside fs callbacks. It touches src/js/node/fs.ts (every callback wrapper), src/runtime/node/node_fs.rs (new FsCompletion/FsCompletionRef/FsOutcome types threaded through AsyncFSTask, UVFSRequest, NewAsyncCpTask, AsyncReaddirRecursiveTask), node_fs_binding.rs (CallShape + macro expansion for 41 *_cb entry points), node.classes.ts (41 new proto entries), trace_events.ts (span-close hook for the new callback shape), and three call sites in Blob.rs/Store.rs/shell/builtin/cp.rs that now pass FsCompletion explicitly.
Since my last review
I flagged one bug on the previous revision (invalid fs.rm options in the non-recursive path became an uncaught exception instead of reaching the callback). The author wrapped the inner fs.rmCb in try/catch and routes the error to the callback (commit 4c01cad), with a subprocess test in fs.test.ts covering {force: "yes"}, {retryDelay: "nope"}, null, and the recursive-path synchronous throw. That fix is correct and matches pre-PR delivery semantics. Two other small fixup commits landed (a SAFETY comment placement and caching args.length in wrapFsAsyncMethod). The bug hunter found nothing new on the current head.
Security risks
None identified. No auth/crypto/permissions surface; input validation paths are unchanged (the same args::*::from_js parsers run, just with the trailing callback split off first).
Level of scrutiny
High. This is production-critical Node compat surface — every node:fs callback API flows through the new code. The Rust side refactors GC-lifetime handling in four separate task types: JSPromiseStrong becomes FsCompletion with a new detach()/ensure_still_alive() pattern that relies on conservative stack scanning to keep the JS cell alive across destroy(). The FsCompletionRef::Promise arm still dereferences a raw *mut JSPromise under a SAFETY comment. The NewAsyncCpTask and AsyncReaddirRecursiveTask paths in particular run Self::destroy() before completion.settle(), so the GC-rooting argument needs to hold. There are also user-visible behavioral changes (callback arity, null vs undefined first arg, mkdir recursive now passing the created path, fstat throwing on missing callback) that could affect ecosystem code.
Other factors
Test coverage is solid: a subprocess fixture asserts nextTick-before-microtask ordering across 10 operations including the recursive-readdir and cp task types, plus AsyncLocalStorage propagation and callback arity. The author ran the full test/js/node/fs/ suite, all test-fs-* parallel tests, trace-events tests, async_hooks tests, and rust:check-all across 10 targets including the Windows UVFSRequest path. CI on the previous sha had only unrelated/infra failures. The PR description is unusually thorough about design trade-offs (why separate *Cb methods rather than trailing-function sniffing, why async stack traces are unaffected, why fs.cp stays on the promise path). Still, the combination of scope, GC-sensitive unsafe Rust, and observable behavior changes puts this well past the threshold for auto-approval.
|
CI triage for
The other two annotations are the runner's own Pushing one |
|
The re-roll settles the napi question: build 68535 ran The one remaining red check is So the diff is green and I'm done pushing. Summary for whoever picks this up:
|
node drains the process.nextTick queue before the microtask queue, so a
process.nextTick() scheduled inside an fs completion callback has to run
before any promise microtask scheduled next to it. node:fs's callback APIs
were implemented as `binding.op(...).then(callback, callback)`, which makes
the callback a microtask: the tick it schedules then waits for the rest of
the microtask queue, inverting the order.
Give the binding's async operations a `*Cb` entry point that takes the
completion callback as its last argument. The task settles through a new
FsCompletion (promise | callback | detached): the callback form invokes the
callback from the event-loop task via EventLoop::run_callback, so the tick
queue drains first, as in node.
The promise entry points are unchanged, so node:fs/promises keeps the
promise whose await chain to_js_with_async_stack walks for async frames.
The callback form has no await chain to walk (and node's callback-form fs
errors carry no stack either).
The callback is identified by position, not by sniffing for a trailing
function: fs operations accept functions in positional slots, which must
still be rejected (`fh.read(buf, 0, 4, fn)` throws ERR_INVALID_ARG_TYPE).
It is snapshotted with AsyncContextFrame so AsyncLocalStorage still
propagates the way `.then(callback)` propagated it.
Along the way, matching node:
- `fs.access`/`fs.symlink`/`fs.utimes`/... call back with `null`, not
`undefined`, and with one argument instead of two.
- `fs.mkdir(path, { recursive: true }, cb)` passes the created path.
- `fs.fstat` throws ERR_INVALID_ARG_TYPE when the callback is missing.
fs.cp's callback still settles from a promise: its non-fast path
(internal/fs/cp) is a JS promise chain, so it hops through the tick queue
instead, like fs.glob already does.
fs.rm's non-recursive path starts the native rm from inside the lstat
completion callback, so the native option parser's throw (`{ force: "yes" }`,
`{ retryDelay: "nope" }`, `options === null`) escaped into run_callback and
surfaced as an uncaught exception: the user callback never fired and the error
was unrecoverable.
Catch it and hand it to the callback, which is where the promise chain this
replaced delivered it. Node throws these synchronously from the fs.rm frame;
the recursive fast path reaches the native rm in the caller frame and now
matches that.
NewAsyncCpTask and AsyncReaddirRecursiveTask settle from a raw completion handle and destroy the task themselves, but the conversion-error branches returned early and skipped destroy(): the Box, the protected args and the KeepAlive ref leaked, and a KeepAlive that never unrefs holds the event loop open. Carry the thrown exception into the outcome instead of returning, so every path runs the single destroy. Also in the tests: import AsyncLocalStorage at module scope, and keep the value-less-callback matrix cross-platform (fs.copyFile always, fs.symlink only where creating one does not need a privilege).
fffc342 to
3d3c8ce
Compare
|
Rebased onto main (
Dropped the stale |
|
CI on so the runner never downloaded the binary to test. Same infra timeout this PR hit on build 68502 and 68516. The only annotation is the The rest of the matrix is still running (56 passed, ~224 pending at the time of this comment). The diff itself was green end-to-end on build 68535 (284/284), and the rebase only resolved two trivial append conflicts with #33561/#33355. I'm not pushing another |
|
Build 69682 finished: 280 jobs passed, zero |
…askTick nextTick hook Node.js evaluates a CommonJS entry synchronously from Module.runMain and then runs processTicksAndRejections, so nextTick callbacks scheduled at top level run before microtasks. An ESM entry runs from inside the microtask queue, so its top level sees the reverse. Bun ran every entry through the ESM loader's promise chain and relied on a one-shot onEachMicrotaskTick hook to drain the nextTick queue after the entry body's microtask. The one-shot fired once and never re-armed, so whichever preload (explicit or the implicit node:worker_threads preload every worker_threads Worker gets since #31216) touched process.nextTick first consumed it, and the entry's own nextTicks ran after its microtasks. F1: gate the bun:main load on the entry kind. A known-ESM entry (.mjs/.mts, or .js/.ts/.jsx/.tsx under "type": "module") keeps the async loader path so its top level sees microtasks first (Node's ESM ordering). Every other entry drains JSC's SynchronousModuleQueue before returning, so the CommonJS body runs before the first microtask checkpoint and nextTick drains first. Preloads apply the same gate (Node's --require is synchronous, --import is async). One tick() after a synchronously-loaded body drains its nextTick queue then its microtasks, matching processTicksAndRejections after Module.runMain. F2: drop the onEachMicrotaskTick nextTick hook. The hook interleaved nextTick between individual microtasks, so a process.nextTick queued from inside a microtask jumped ahead of that microtask's siblings (Node drains the whole FIFO first, then the tick queue). With F1 it is no longer needed for entry ordering. resetOnEachMicrotaskTick / cleanupAsyncHooksData now only serve AsyncLocalStorage.enterWith. GlobalObject::drainMicrotasks re-checks the queue after vm.drainMicrotasks so ticks scheduled by the lazy-first process.nextTick access still run in the same checkpoint, and processTicksAndRejections clears the "has work" field so JSNextTickQueue::isEmpty reflects the drained state. The fs-callback ordering (fs.readFile(...).then(cb) runs cb from a promise reaction) needs the same treatment as F1 applied to completion dispatch; that is #33366. Fixes #34115
|
Closing as part of a cleanup of stale pull requests. This PR has had no new commits since 2026-07-07, it conflicts with main, and its last CI run failed. This is not a judgment on the fix itself. If the problem still reproduces on a current build, reopen this PR after a rebase or open a new one against main. |
…ction (#43728) ### Problem - Inside an async `node:fs` callback, a microtask the callback queues runs before a `process.nextTick()` it queues. Node runs the nextTick first: it prints `cb0 tick0 mt0 cb1 tick1 mt1`, and bun prints `cb0 tick0 mt0 cb1 mt1 tick1`. - The binding only returns promises, so `src/js/node/fs.ts` ran each callback from a promise reaction. A reaction is a microtask, so the callback's microtasks ran before the tick queue. ### Fix - The binding gets a third arm, `xCb(callback, ...args)`. The task keeps the callback in a `Strong` and calls it from the completion with `EventLoop::run_callback`, as `node:crypto` does. - `run_callback` then runs the tick queue and the microtasks, which is node's order. A callback API creates no promise, reaction or microtask. - `node:fs/promises` stays on the promise arm. Callback arguments do not change. - Verified: `test/js/node/fs/fs.test.ts` (49 new tests), node's `test-fs-*` files, Windows x64. ### Background - A checkpoint runs the tick queue (`process.nextTick`), then the microtask queue (promise reactions, `queueMicrotask`). Node calls an fs callback from the event loop, outside both. - `fs.promises` forwards every user argument, so a trailing function cannot select the callback arm. The arm needs its own entry points. ### Downsides - Seven callback APIs are JS promise chains with no binding operation (`cp`, `rm`, recursive `rmdir`, `Dir.read`, `Dir.close`, `glob`, `opendir`). They still use `process.nextTick`, so they report a `TickObject` to `async_hooks` and wait on a replaced `process.nextTick`. - Binary size: stripped Linux x64 release `bun` +53,248 bytes (+0.066%), `.text` +49,152, for 41 new host functions. - `fs.access` allocates one more closure per call (1 → 2), for a JS adapter that keeps its callback arguments identical. Others allocate fewer (Notes). <details><summary>Notes</summary> **Repro** ```js import fs from "node:fs"; const seq = []; let n = 0; function cb() { const i = n++; seq.push("cb" + i); process.nextTick(() => seq.push("tick" + i)); queueMicrotask(() => seq.push("mt" + i)); } for (let k = 0; k < 2; k++) fs.stat(".", cb); setTimeout(() => console.log(seq.join(" ")), 200); ``` The first callback of a process looks correct without the fix. The tick queue does not exist until the first `process.nextTick()` call. While it does not exist, the `onEachMicrotaskTick` hook (`ZigGlobalObject.cpp`, `checkIfNextTickWasCalledDuringMicrotask`) drains it right after the microtask that created it. **History of this PR** The first version kept the promise and passed the callback to `process.nextTick` from the reaction. A maintainer asked for a native callback arm instead ([review](#43728 (review))). The hop kept the whole promise path and added a tick. It also had two costs that the native arm removes for the operations of the binding, both measured on one `fs.stat` callback: | | released bun | hop | native arm | node v26.3.0 | |---|---|---|---|---| | `async_hooks` `init` events | `{}` | `{"TickObject":1}` | `{}` | `{"FSREQCALLBACK":1}` | | `process.nextTick` replaced before `node:fs` loads | callback runs | callback held | callback runs | callback runs | Bun reports no `FSREQCALLBACK` resource, before or after this PR. #33366 was an earlier native attempt, closed as stale without a review. **Shape of the callback arm** - `FsCompletion { Promise(JSPromiseStrong), Callback(Strong) }` replaces the promise in `AsyncFSTask`, the recursive readdir task and the Windows `UVFSRequest`. `NewAsyncCpTask` keeps its promise, because `fs.cp` is a JS promise chain. - The callback is stored with `with_async_context_if_needed` and called with `ContextId::NONE`, the pairing `run_callback` documents for a callback that carries its own `AsyncLocalStorage` frame. - An error found before the operation is scheduled (an aborted signal, a path that is too long) goes to the callback on the next tick. The callback goes in bare, because `Process::queueNextTick` asserts against an `AsyncContextFrame`. - The task releases its arguments before it calls back. They pin their buffers, and the callback now runs inside the completion, so a transfer of the buffer from the callback would copy it. Main and node detach it. The Windows `UVFSRequest` takes the completion out, frees the task, and then calls back. It takes `*mut Self` for that reason. - `FsCompletion::reject` builds the error value as `JSPromise::reject` does: it creates an out-of-memory error and does not take one, it returns a termination, and it unwraps a thrown `Exception` cell to its `Error`. - The entry points are named `xCb`, not `xCallback`. The class generator names the C++ host wrapper of a method `x` `Prototype__xCallback`, so a method named `xCallback` collides with it. - Ten operations keep a small JS adapter so that their argument lists stay identical: `access`, `close`, `exists`, `read`, `write` (both overloads), `readv`, `writev`, `symlink`. `fs.symlink` with a callback that is not callable stays on the promise arm, as before. - `internal/trace_events.ts` wraps `binding[method + "Cb"]` for each operation in its existing table, so `node.fs.async` spans still close. Without this, `test-trace-events-fs-async.js` gets no traces. **Size and performance** Two release builds from one tree and toolchain, each in its own build directory: main `bf80d21` and this PR. Linux x64. | | main | PR | delta | |---|---|---|---| | `bun` (stripped) | 80,770,592 | 80,823,840 | +53,248 (+0.066%) | | `bun-profile` | 169,212,560 | 169,315,968 | +103,408 (+0.061%) | | `.text` | 58,086,812 | 58,135,964 | +49,152 | | `.rodata` | 19,821,204 | 19,825,364 | +4,160 | | `.data`, `.data.rel.ro`, `.bss` | | | 0 | JS heap objects allocated per operation. This count is exact and has no timing in it: the script starts 1000 operations in one synchronous turn and reads `heapStats()` in the same turn. No operation can complete before control returns to the event loop, so each one is pending and roots what it allocated. Three runs of each binary give identical numbers. | per operation | `Promise` | `Function` | |---|---|---| | callback `fs.stat` | 2 → 0 | 2 → 1 | | callback `fs.readFile` | 2 → 0 | 2 → 1 | | callback `fs.read` | 2 → 0 | 3 → 2 | | callback `fs.access` | 2 → 0 | 1 → 2 | | `fs.promises.stat` | 3 → 3 | 0 → 0 | | `fs.promises.readFile` | 3 → 3 | 0 → 0 | On main each callback operation allocates two promises: the one the binding returns, and the one `.then()` derives. Eight operations keep a JS adapter so that their callback arguments stay identical. For `fs.access` the adapter is one more closure than main, which passed the callback to `.then()` directly. For `fs.read` it replaces two closures that main created. I measured only these two of the eight. Process CPU time per operation (user + system, µs), 200,000 operations, 256 in flight, 10 alternating runs per binary. This is statistical, not exact. The spread between runs of one binary is 2 to 4 µs, which is larger than the differences, and the distributions overlap. Read it as a direction. | | main median | PR median | main min | PR min | |---|---|---|---|---| | callback `fs.stat` | 12.36 | 10.41 | 10.27 | 8.46 | | callback `fs.read` | 10.47 | 9.50 | 8.67 | 8.64 | | `fs.promises.stat` | 11.51 | 11.88 | 8.57 | 9.79 | `fs.stat` is about 16% cheaper by the median and by the minimum. `fs.read` is not conclusive: 9% by the median, no difference by the minimum. `fs.promises.stat` is the control, because its code path and its allocations did not change. Its 3% difference shows the noise of the method, and it gives no evidence of a regression. I could not count CPU instructions on this machine. `valgrind` has no install candidate, and `perf_event_open` returns `EPERM`. **Not in this PR** - `dns.lookup` has the same order problem (`cb mt tick`). - Void operations call back with `(null, undefined)` where node passes `(null)`. Same on main, #38085 changes it. - `fs.symlink` calls back with `(undefined)` on success. Same on main, #40916 changes it. - `fs.fstat`, `fs.read` and the 4-argument `fs.symlink` do not check the callback synchronously as node does. Same on main. - `fs.readFile` with a signal that is already aborted calls back synchronously in node and asynchronously in bun. **Verification** - `test/js/node/fs/fs.test.ts`: the 45 order tests give 0 pass with main's `src/` and 45 pass with this PR. The 4 transfer tests guard a bug that an earlier commit of this PR had (6174ba5 fails them with `source: 8`). They pass on main. Whole file: 614 pass, 0 fail. - The same cases as a plain script pass on node v26.3.0. - 15 other files in `test/js/node/fs/`: 240 pass, 0 fail. `abort-signal-leak-read-write-file.test.ts` is a 300 s timeout under the ASAN debug build and uses only `fs.promises`. - Node's `test/parallel` files for fs, trace events, `util.promisify`, `util.callbackify`, http2 `respondWithFile`, `Utf8Stream`, `stream.pipeline`, readline and `FileHandle`: 413 files, all pass. `test-fs-cp-async-file-url.mjs` needs the working directory `test/js/node`. - `AsyncLocalStorage` stores reach the callback on 10 paths (native, adapter, error, recursive readdir, the early abort path, and the JS chains), the same as node. - `bun run rust:check-all`: 12 of 12 targets. - Windows x64 debug build: the order tests are 42 pass, 0 fail and the transfer tests 4 pass, on the final commit. An earlier run of the whole file was 598 pass, 2 fail. Both fail the same way on main without this PR on the same machine: `keeps a non-throwing callback in the same place in the event loop` (`setImmediate` runs before the `fs.stat` callback) and `readSync > works on large files` (5 s timeout). </details> <!-- robobun:evidence:begin --> --- **no test proof** · iteration 0 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/node/fs/fs.test.ts <!-- robobun:evidence:end --> --------- Co-authored-by: Alistair Smith <hi@alistair.sh>
…on has no result FsCompletion::resolve passed (null, value) to every callback, so the operations with no result called back with (null, undefined). Node's FSReqCallback::Resolve passes one argument when the value is undefined. The Callback arm now does the same. A const on FsReturn, UNDEFINED_RESULT, lets StatOrNotFound keep (null, undefined) for fs.stat with throwIfNoEntry: false, which is what node passes there. A const assert pins it. The access, close and symlink adapters in fs.ts only reshaped the arguments, so they are removed. symlink now calls back with (null). rm and the recursive rmdir use settleCallbackWithNull. The const on FsReturn follows the design of #33366.
Repro
Cause
node:fs's callback APIs werebinding.op(...).then(callback, callback), so theuser callback runs as a promise microtask. A
process.nextTick()scheduledfrom inside a microtask only runs once the whole microtask queue drains, so the
tick loses to any sibling microtask. Node invokes the callback from the poll
phase, where the tick queue drains first.
(Only the first completed operation in a process looked right:
m_nextTickQueuedoes not exist until
process.nextTickis first touched, and theonEachMicrotaskTickhook that lazily installs it happens to drain the queueright after that first callback.)
Fix
Each async operation on the
node:fsbinding gains a*Cbentry point whoselast argument is the completion callback. A new
FsCompletion(
Promise | Callback | Detached) is threaded through the four async task types;the callback variant invokes the callback from the event-loop task through
EventLoop::run_callback, so the tick queue drains before microtasks, as innode.
node:fs/promisescalls the unchanged promise entry points.Details worth calling out:
to_js_with_async_stackonly yieldsframes when a generator awaits the native promise (
getAwaitingGeneratorinAsyncStackTrace.cpp)..then(cb, cb)has no generator, so the callback formnever produced frames — and node's callback-form fs errors have no frames
either (
err.stackis justError: ENOENT: ...).node:fs/promiseskeeps itspromise and its frames.
function. fs operations legitimately receive functions in positional slots
and must reject them:
fh.read(buf, 0, 4, () => {})has to throwERR_INVALID_ARG_TYPEforposition(
test-fs-read-promises-position-validation.mjs). Hence separate*Cbmethods rather than a heuristic on the shared ones.
AsyncLocalStoragestill propagates: the callback is snapshotted withAsyncContextFrame::withAsyncContextIfNeeded, the way.then(callback)captured the context at registration.
JSPromiseplus two reaction closuresper call.
Node-compat fixes that fall out of the native callback convention
(
cb(err)/cb(null)/cb(null, value)):fs.access,fs.symlink,fs.utimes, … now call back withnullratherthan
undefined, and with one argument instead of two.fs.mkdir(path, { recursive: true }, cb)now passes the created path.fs.fstatthrowsERR_INVALID_ARG_TYPEwhen the callback is missing.fs.rm'sERR_FS_EISDIRprobe runs on the callback path instead of routingthrough
fs.promises.rm.fs.cpis deliberately excluded from the native path: its non-fast path(
internal/fs/cp) is a JS promise chain, so its callback hops through the tickqueue instead (the same shape
fs.globandfs.opendiralready used). Orderingis still node-correct; the callback is just one tick later.
internal/trace_events.tskeyed the end of anode.fs.asyncspan off thereturned promise, so it learned about the
*Cbsiblings and closes the spanfrom the callback.
Verification
test/js/node/fs/fs.test.tsgets acallback orderingblock: one fixture runsreadFile,stat,access,readdir, recursivereaddir,open,close,rm,cpand an error callback, and asserts every callback observesnextTickbeforemicrotask. Plus theAsyncLocalStoragepropagation and thecb(null)arity.Fails on the released binary (8 of the 10 callbacks inverted), passes with the
fix.
Suites run (debug build)
test/js/node/fs/— 548 pass, 1 fail (abort-signal-leak-read-write-file: its100k-iteration fixture takes ~5 min under ASAN against a 5s test timeout, and
it fails identically on the released binary)
test/js/node/test/parallel/test-fs-*— same 9 failures as on thereleased binary, no new ones;
test-fs-read-promises-position-validation.mjspasses
test-trace-events-fs-async.js,test-trace-events-fs-sync.jstest/js/node/async_hooks/,test-async-local-storage-*bun run rust:check-all— 10/10 targets (the WindowsUVFSRequestpath)