Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 0 additions & 15 deletions test/expectations.txt
Original file line number Diff line number Diff line change
Expand Up @@ -26,21 +26,6 @@
# ships ClangCL. Runs everywhere else.
[ WINDOWS ] test/bundler/native-plugin.test.ts [ SKIP ] # node-gyp needs a ClangCL toolset the Windows agents do not have

# Verbatim node v26.3.0 test asserting a FinalizationRegistry callback fires
# within ONE globalThis.gc() + ONE setImmediate after the connect callback's
# closure is unreferenced. The FinalizationRegistry spec gives no timing
# guarantee for cleanup callbacks; JSC schedules them via DeferredWorkTimer
# with no defined ordering relative to the immediate queue. The connect
# listener IS removed (verified: listenerCount("secureConnect") === 0 in
# done()) and the object IS collected (test passes 70/70 on darwin and
# glibc Linux); on alpine x64 the FR callback delivery slips past the single
# setImmediate after this PR's added module loads at process startup shift
# the heap layout. The robust fix is gcUntil() rather than a single tick,
# but the file is a verbatim upstream port. Quarantined on the failing
# linux-x64-musl matrix only; still runs everywhere else (build 63145:
# alpine 3.23 x64 + x64-baseline only).
[ LINUX-X64-MUSL ] test/js/node/test/parallel/test-tls-connect-memleak.js [ FLAKY ] # JSC FinalizationRegistry callback delivery vs setImmediate timing on musl x64

# Vendored node v26.3.0 stream tests blocked on missing native subsystems (see PR #31826)
test/js/node/test/parallel/test-stream-pipeline.js [ SKIP ] # block at L271 hangs: pipeline(rs, req) writes 11x'hello' raw after a never-ended GET's \r\n\r\n; node's llhttp rejects lowercase 'h' as a method char (HPE_INVALID_METHOD -> clientError -> 400+close -> req 'close' -> pipeline callback fires), but bun's uWS HttpParser buffers any incomplete run of valid tchars waiting for the request-line, so the connection stays open and the callback never fires. Pre-existing server-parser leniency; needs uWS HttpParser to reject non-uppercase method bytes like llhttp.
test/js/node/test/parallel/test-stream-wrap.js [ FAIL ] # needs internal/test/binding + js_stream (net.Socket({handle}) libuv compat layer)
Expand Down
65 changes: 60 additions & 5 deletions test/js/node/test/common/gc.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,17 +120,72 @@ async function checkIfCollectableByCounting(fn, ctor, count, waitTime = 20) {
throw new Error(`${name} cannot be collected`);
}

var finalizationRegistry = new FinalizationRegistry(heldValue => {
heldValue.ongc();
})
// Upstream implements onGC() with an async_hooks destroy hook, which gives it

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@robobun what node.js do here?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Node's onGC() (test/common/gc.js @ v26.3.0) is built on async_hooks:

const gcTrackerMap = new WeakMap();
const gcTrackerTag = 'NODE_TEST_COMMON_GC_TRACKER';

function onGC(obj, gcListener) {
  const async_hooks = require('async_hooks');
  const onGcAsyncHook = async_hooks.createHook({
    init: common.mustCallAtLeast(function(id, type) {
      if (this.trackedId === undefined) {
        assert.strictEqual(type, gcTrackerTag);
        this.trackedId = id;
      }
    }),
    destroy(id) {
      if (id === this.trackedId) {
        this.gcListener.ongc();
        onGcAsyncHook.disable();
      }
    },
  }).enable();
  onGcAsyncHook.gcListener = gcListener;

  gcTrackerMap.set(obj, new async_hooks.AsyncResource(gcTrackerTag));
  obj = null;
}

It creates an AsyncResource held only by a WeakMap keyed on obj. When V8 collects obj the AsyncResource becomes unreachable, V8 collects it, and its native finalizer calls EmitDestroy, which Node drains through env->SetImmediate on the next loop iteration. That's where the documented guarantee in their JSDoc comes from: "A full setImmediate() invocation passes between a global.gc() call and the listener being invoked."

Bun can't use that path: async_hooks.createHook here only delivers init (for TickObject) and warns that destroy is never called (src/js/node/async_hooks.ts:362). So there's no destroy event to hook. The WeakRef sweep after an explicit gc() is the closest mechanism that gives the same "observable by the next setImmediate" ordering, and the FinalizationRegistry stays for the two callers that never call gc() at all.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@robobun check cirospaciari async hooks PR to see if it would solve this

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked #31825. It wouldn't solve this on its own.

That PR's src/js/node/async_hooks.ts diff covers AsyncLocalStorage (run/disable restore semantics, defaultValue, name, withScope) and AsyncResource.bind() parity, but it doesn't touch createHook at all. The destroy hook still never fires; the PR's own vendored test-eventemitter-asyncresource.js adds a comment saying exactly that ("Bun does not implement createHook event [delivery]").

Node's onGC() needs two things that remain missing after #31825:

  1. createHook({ destroy }) actually delivering destroy events.
  2. AsyncResource having a native finalizer that calls emitDestroy when GC collects it. In Node the AsyncResource is a native AsyncWrap; V8 runs its C++ destructor, which queues EmitDestroy. In Bun AsyncResource is a plain JS class with no JSC finalizer, so nothing fires on collection even if (1) were wired up.

So even with #31825 merged, common/gc.js still needs a non-async_hooks mechanism, and the WeakRef sweep here is that mechanism. If/when Bun grows a native-backed AsyncResource with GC-driven destroy, this file could switch to upstream's verbatim implementation and drop the WeakRef path.

// this documented contract: "A full setImmediate() invocation passes between a
// global.gc() call and the listener being invoked." Bun does not implement
// destroy hooks (async_hooks.createHook only emits init), so onGC() is built on
// FinalizationRegistry instead.
//
// FinalizationRegistry alone cannot honour that contract. JSC schedules cleanup
// callbacks through DeferredWorkTimer, which Bun drains via the event loop's
// concurrent task queue, while setImmediate() has its own separate queues. The
// two have no defined order relative to each other, so the callback can land
// after the setImmediate() a test uses to observe it.
//
// WeakRef has no such problem: gc() clears weak refs synchronously, so a sweep
// performed right after an explicit gc() observes collection with no queue in
// between. Listeners are therefore delivered by whichever comes first:
//
// - flushGCListeners(), for tests that call gc() explicitly, and
// - the FinalizationRegistry, for tests that rely on a natural GC and never
// call gc() at all.
//
// pendingListeners keeps each entry reachable until it fires and doubles as the
// guard that fires it exactly once, whichever path gets there first. An entry
// never references the tracked value, only a WeakRef to it.
const pendingListeners = new Set();

const finalizationRegistry = new FinalizationRegistry(fireGCListener);

function fireGCListener(entry) {
// Returns false if the other delivery path already fired this entry.
if (!pendingListeners.delete(entry)) {
return;
}
finalizationRegistry.unregister(entry);
entry.ongc();
}

// Fires the listeners whose tracked values are already collected. Values that
// are still alive stay registered.
function flushGCListeners() {
for (const entry of [...pendingListeners]) {
if (entry.ref.deref() === undefined) {
fireGCListener(entry);
}
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

function onGC(value, holder) {
if (holder?.ongc) {

finalizationRegistry.register(value, { ongc: holder.ongc });
const entry = { ref: new WeakRef(value), ongc: holder.ongc };
pendingListeners.add(entry);
finalizationRegistry.register(value, entry, entry);
}
}

// Deliver pending listeners synchronously on every explicit gc() so they are
// always observable by the time the next setImmediate() runs. Tests spell this
// both global.gc() and globalThis.gc(); those are the same property.
if (typeof globalThis.gc === 'function') {
const realGC = globalThis.gc;
globalThis.gc = function gc(...args) {
const result = realGC.apply(this, args);
flushGCListeners();
return result;
};
}

/**
* Repeatedly triggers garbage collection until a specified condition is met or a maximum number of attempts is reached.
* @param {string|Function} [name] - Optional name, used in the rejection message if the condition is not met.
Expand Down
Loading