Skip to content

fs: run node:fs callbacks from the event loop, not a promise reaction - #33366

Closed
robobun wants to merge 5 commits into
mainfrom
farm/9db5c407/fs-callback-next-tick-ordering
Closed

robobun wants to merge 5 commits into
mainfrom
farm/9db5c407/fs-callback-next-tick-ordering

Conversation

@robobun

@robobun robobun commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator

Repro

const fs = require("fs");
const order = [];
const probe = name => {
  Promise.resolve().then(() => order.push(name + ":microtask"));
  process.nextTick(() => order.push(name + ":nextTick"));
};

fs.stat(__filename, () => probe("stat1"));
fs.stat(__filename, () => probe("stat2"));
process.on("exit", () => console.log(order.join(" | ")));
node  stat1:nextTick | stat1:microtask | stat2:nextTick | stat2:microtask
bun   stat1:nextTick | stat1:microtask | stat2:microtask | stat2:nextTick

Cause

node:fs's callback APIs were binding.op(...).then(callback, callback), so the
user callback runs as a promise microtask. A process.nextTick() scheduled
from 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_nextTickQueue
does not exist until process.nextTick is first touched, and the
onEachMicrotaskTick hook that lazily installs it happens to drain the queue
right after that first callback.)

Fix

Each async operation on the node:fs binding gains a *Cb entry point whose
last 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 in
node. node:fs/promises calls the unchanged promise entry points.

Details worth calling out:

  • Async stack traces are unaffected. to_js_with_async_stack only yields
    frames when a generator awaits the native promise (getAwaitingGenerator in
    AsyncStackTrace.cpp). .then(cb, cb) has no generator, so the callback form
    never produced frames — and node's callback-form fs errors have no frames
    either (err.stack is just Error: ENOENT: ...). node:fs/promises keeps its
    promise and its frames.
  • The callback is identified by position, not by sniffing for a trailing
    function.
    fs operations legitimately receive functions in positional slots
    and must reject them: fh.read(buf, 0, 4, () => {}) has to throw
    ERR_INVALID_ARG_TYPE for position
    (test-fs-read-promises-position-validation.mjs). Hence separate *Cb
    methods rather than a heuristic on the shared ones.
  • AsyncLocalStorage still propagates: the callback is snapshotted with
    AsyncContextFrame::withAsyncContextIfNeeded, the way .then(callback)
    captured the context at registration.
  • The callback path no longer allocates a JSPromise plus two reaction closures
    per 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 with null rather
    than undefined, and with one argument instead of two.
  • fs.mkdir(path, { recursive: true }, cb) now passes the created path.
  • fs.fstat throws ERR_INVALID_ARG_TYPE when the callback is missing.
  • fs.rm's ERR_FS_EISDIR probe runs on the callback path instead of routing
    through fs.promises.rm.

fs.cp is deliberately excluded from the native path: its non-fast path
(internal/fs/cp) is a JS promise chain, so its callback hops through the tick
queue instead (the same shape fs.glob and fs.opendir already used). Ordering
is still node-correct; the callback is just one tick later.

internal/trace_events.ts keyed the end of a node.fs.async span off the
returned promise, so it learned about the *Cb siblings and closes the span
from the callback.

Verification

test/js/node/fs/fs.test.ts gets a callback ordering block: one fixture runs
readFile, stat, access, readdir, recursive readdir, open, close,
rm, cp and an error callback, and asserts every callback observes
nextTick before microtask. Plus the AsyncLocalStorage propagation and the
cb(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: its
    100k-iteration fixture takes ~5 min under ASAN against a 5s test timeout, and
    it fails identically on the released binary)
  • every test/js/node/test/parallel/test-fs-* — same 9 failures as on the
    released binary, no new ones; test-fs-read-promises-position-validation.mjs
    passes
  • test-trace-events-fs-async.js, test-trace-events-fs-sync.js
  • test/js/node/async_hooks/, test-async-local-storage-*
  • bun run rust:check-all — 10/10 targets (the Windows UVFSRequest path)

@coderabbitai

coderabbitai Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@robobun, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 17 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 9816cf36-60f9-40f2-afdc-191244e75ac6

📥 Commits

Reviewing files that changed from the base of the PR and between ce0b752 and 3d3c8ce.

📒 Files selected for processing (9)
  • src/js/internal/trace_events.ts
  • src/js/node/fs.ts
  • src/runtime/node/node.classes.ts
  • src/runtime/node/node_fs.rs
  • src/runtime/node/node_fs_binding.rs
  • src/runtime/shell/builtin/cp.rs
  • src/runtime/webcore/Blob.rs
  • src/runtime/webcore/blob/Store.rs
  • test/js/node/fs/fs.test.ts

Walkthrough

This PR adds callback-based async completion handling for NodeFS, rewires JS fs callback APIs to native *Cb bindings, updates trace span closure to occur from callbacks, adjusts a few internal callers to pass completion handles, and adds regression tests for ordering and callback semantics.

Changes

Callback-based fs completion pipeline

Layer / File(s) Summary
FsCompletion types
src/runtime/node/node_fs.rs
Adds FsCompletion, FsCompletionRef, FsOutcome, fs_result_to_js, and FsReturn::IS_VOID, and updates async task storage and settlement to use completion handles.
Binding layer callback dispatch
src/runtime/node/node_fs_binding.rs, src/runtime/node/node.classes.ts
Adds CallShape and split_callback, passes FsCompletion into async task creation, adds readdir_cb, and expands node_fs_bindings! and NodeJSFS mappings to generate *_cb methods.
fs.ts callback methods
src/js/node/fs.ts
Rewrites callback-style fs methods to call fs.*Cb(...) directly, updates rm recursive error handling, and adds nextTickWithNull and onOpendirStat helpers.
Internal consumers pass completion
src/runtime/shell/builtin/cp.rs, src/runtime/webcore/Blob.rs, src/runtime/webcore/blob/Store.rs
ShellCpTask, BlobExt::get_stat, and FileExt::unlink now pass FsCompletion values into async task creation.
Trace callbacks
src/js/internal/trace_events.ts
installFsInstrumentation() now wraps *Cb siblings, and wrapFsAsyncMethod() emits async end events from callback wrappers instead of promise chaining.
Filesystem callback regressions
test/js/node/fs/fs.test.ts
Adds tests for callback ordering, fs.rm callback error delivery, AsyncLocalStorage propagation, and null error arguments on success.

Possibly related PRs

  • oven-sh/bun#31824: Both PRs modify src/js/internal/trace_events.ts's FS async tracing instrumentation.
  • oven-sh/bun#32748: Both touch the recursive readdir async task implementation and its completion/error handling.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: fs callbacks now run from the event loop instead of a promise reaction.
Description check ✅ Passed The description covers the change and verification, though it uses custom headings instead of the template’s exact sections.
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.

Comment @coderabbitai help to get the list of available commands.

@github-actions github-actions Bot added the claude label Jul 5, 2026
@robobun

robobun commented Jul 5, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 3:56 AM PT - Jul 7th, 2026

❌ @robobun, your commit 3d3c8ce has 1 failures in Build #69682 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 33366

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

bun-33366 --bun

Comment thread src/js/node/fs.ts Resolved
@robobun

robobun commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI on 291ea01: the two red lanes are not from this diff.

  • test/js/node/test/parallel/test-worker-message-port-transfer-terminate.js — SIGABRT on 13 x64-asan with ASSERTION FAILED: !scope.exception() || !hasSlot in JSValue::get. The same assertion on the same lane hit unrelated PR readline: reject instead of throwing when question() gets an aborted signal #33343 (build 68435); the test spawns 10 workers and calls terminate() mid-postMessage, which races the termination exception against a property get. Nothing in this diff touches workers or message ports.
  • darwin 26 aarch64 - test-bun — buildkite-agent artifact download timed out after 120s, infra.

The flaky annotation (update_interactive_install, spawn-pipe-leak) passed on retry.

3f502db pushed since then addresses the fs.rm review finding, so CI is re-running on that sha.

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

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.

@robobun
robobun force-pushed the farm/9db5c407/fs-callback-next-tick-ordering branch from 3f502db to 4c01cad Compare July 5, 2026 09:46
@robobun

robobun commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto fb50cce (was branched off b8e7a95), which picks up #33348 — that explains the 13 x64-asan red on the previous two builds. tls-syscall-fault.test.ts asserted stderr.includes("Bun ran out of memory"), a line the crash handler suppresses whenever BUN_CRASH_REPORT_URL is set, which is exactly what the CI runner does when its remap server comes up. It passes 11/11 here now. The darwin 26 aarch64 job was buildkite-agent artifact download timed out after 120s, and the flaky annotation (bun-install, update_interactive_install) passed on retry.

On the two points raised for a human pass:

~40 sibling *Cb methods vs. one flag argument. I started with a flag — "if the last argument is callable, it's the callback" — and test-fs-read-promises-position-validation.mjs killed it: fh.read(buf, 0, 4, () => {}) must throw ERR_INVALID_ARG_TYPE for position, so a callable last argument genuinely carries no information about the caller's intent. args::Write::from_js already has current.is_function() guards for the same reason. The CallShape enum makes the split a property of the entry point rather than of the argument values, which is the only version I could convince myself was sound. It does cost ~40 host functions on an internal binding object; a maintainer may prefer a different shape and I'm happy to rework it.

FsCompletionRef lifetime. The invariant is unchanged from the promise code it generalizes: detach() copies the cell out of the owning Strong, ensure_still_alive() pins it on the stack for JSC's conservative scan, and only then may destroy() drop the Strong. AsyncFSTask/UVFSRequest destroy via a scopeguard after the settle, so the Strong is still live there; NewAsyncCpTask and AsyncReaddirRecursiveTask destroy before it, which is exactly where the old code already carried promise_value + a raw *mut JSPromise across the same gap.

Windows UVFSRequest. Checked with bun run rust:check-all (10/10 targets) but not executed — it is the same fs_result_to_js → completion.settle() shape as the POSIX task, differing only in where result is produced.

@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: 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

📥 Commits

Reviewing files that changed from the base of the PR and between fb50cce and 4c01cad.

📒 Files selected for processing (9)
  • src/js/internal/trace_events.ts
  • src/js/node/fs.ts
  • src/runtime/node/node.classes.ts
  • src/runtime/node/node_fs.rs
  • src/runtime/node/node_fs_binding.rs
  • src/runtime/shell/builtin/cp.rs
  • src/runtime/webcore/Blob.rs
  • src/runtime/webcore/blob/Store.rs
  • test/js/node/fs/fs.test.ts

Comment thread src/runtime/node/node_fs.rs Resolved
Comment thread test/js/node/fs/fs.test.ts Resolved
Comment thread test/js/node/fs/fs.test.ts Resolved

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

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.

@robobun

robobun commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI triage for ce0b752 (build 68527):

test/napi/napi.test.ts → napi_wrap > has the right lifetime on 2019 x64-baseline — Condition was not met after 100 GC attempts. This is gcUntil() (test/napi/napi-app/module.js:24) polling for a napi finalizer across 100 Bun.gc(true) rounds, on the slowest lane in the matrix. I don't believe it's this diff:

  • build 68521 ran 4c01cad, which has byte-identical node_fs.rs / fs.ts / node_fs_binding.rs to this sha apart from one control-flow fold in an fs result-conversion error path (unreachable without an exception while converting an already-completed result). It was 68/68 green across every baseline job, napi included. Build 68502 was likewise clean there.
  • test/napi/napi-app/ never requires node:fs, so no FsCompletion / Strong from this PR exists in the process whose heap gcUntil is collecting.
  • The job was not retried (retried: false), so this is a single sample of a GC-timing assertion, not a reproduced failure.

The other two annotations are the runner's own flaky classification (passed on retry): test/cli/update_interactive_install.test.ts and test/cli/install/bun-install.test.ts, both on Windows, both unrelated to fs.

Pushing one ci: retrigger to re-roll. If napi lands red again I'll stop pushing and leave it here for a maintainer rather than churning the queue.

@robobun

robobun commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

The re-roll settles the napi question: build 68535 ran test/napi/napi.test.ts on the same 2019 x64-baseline lane and it passed. 284 jobs green, zero test failures.

The one remaining red check is buildkite/bun/darwin-14-aarch64-test-bun, status Expired — no macOS 14 aarch64 agent ever picked the job up, so it never executed. The only annotation is the runner's own flaky classification for test/cli/update_interactive_install.test.ts (Windows, passed on retry).

So the diff is green and I'm done pushing. Summary for whoever picks this up:

  • Fixes node's process.nextTick-before-microtasks contract inside fs completion callbacks, which .then(cb, cb) was inverting.
  • node:fs/promises is untouched and keeps its await-chain async frames; the callback form never had any (nor does node's).
  • Two real bugs surfaced in review and are fixed with tests: an uncaught exception from invalid fs.rm options, and a pre-existing leak where NewAsyncCpTask/AsyncReaddirRecursiveTask skipped destroy() on the conversion-error path (a KeepAlive that never unrefs holds the event loop open).
  • The one thing worth a maintainer's opinion is in the PR body: whether ~40 sibling *Cb methods on the internal binding is the shape you want. A "trailing callable ⇒ callback" flag is unsound — test-fs-read-promises-position-validation.mjs requires fh.read(buf, 0, 4, fn) to reject fn as an invalid position — but there may be a shape I didn't consider.

robobun added 5 commits July 7, 2026 05:03
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).
@robobun
robobun force-pushed the farm/9db5c407/fs-callback-next-tick-ordering branch from fffc342 to 3d3c8ce Compare July 7, 2026 05:22
@robobun

robobun commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto main (3f67971) to resolve conflicts with #33561 and #33355. Both were trivial:

  • src/runtime/node/node_fs.rs: node:fs: close(0/1/2) must actually close the descriptor #33561 deleted the Windows UVFSRequest arm that skipped uv_fs_close for fd 1/2; this PR had renamed task.promise.value() to task.completion.value() inside it. Took upstream's deletion.
  • test/js/node/fs/fs.test.ts: both PRs appended a describe block at the end of the file. Kept both.

Dropped the stale ci: retrigger commit. rust:check-all 10/10, callback ordering 4/4, #33561's fs.close on stdio descriptors 2/2, lint + clippy clean.

@robobun

robobun commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI on 3d3c8ce (build 69682, the rebase): the two red jobs are both darwin 26 aarch64 - test-bun dying at scripts/runner.node.mjs:2182 with

Error: buildkite-agent artifact download timed out after 120s for step 'darwin-aarch64-build-bun'. Refusing to continue with a partial download

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 flaky tag on test/bake/dev-and-prod.test.ts (Windows HMR timing, passed on retry).

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 ci: retrigger — retrying the two darwin jobs in Buildkite directly would be cheaper than a full re-queue. Diff is ready for review.

@robobun

robobun commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

Build 69682 finished: 280 jobs passed, zero error annotations. The three red checks are all macOS lanes that never ran a test: darwin 26 aarch64 twice with buildkite-agent artifact download timed out after 120s (runner.node.mjs:2182), and darwin 14 aarch64/darwin 14 x64 both Expired (no agent picked them up). The only annotation is warning | flaky on a bake HMR test that passed on retry.

robobun added a commit that referenced this pull request Jul 29, 2026
…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
@robobun

robobun commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator Author

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.

@robobun robobun closed this Sep 13, 2026
alii added a commit that referenced this pull request Sep 22, 2026
…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>
robobun added a commit that referenced this pull request Sep 24, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant