From 6a9412f2f0643766a019b77586ab4bf2f32b619b Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Sun, 24 May 2026 15:11:15 +0530 Subject: [PATCH 01/39] errors: handle V8 warnings in DisallowJavascriptExecutionScope Defer non-critical warnings to the next event loop iteration when can_call_into_js() returns false. This prevents crashes when V8 emits warnings during REPL preview evaluation or other contexts where JavaScript execution is temporarily forbidden. When a warning is emitted inside DisallowJavascriptExecutionScope, ProcessEmitWarningGeneric cannot be called immediately. Instead, use env->SetImmediate() to queue the warning emission for after the scope exits. This preserves full warning formatting, deprecation codes, and --redirect-warnings routing. Signed-off-by: Divyanshu Sharma --- src/node_errors.cc | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/node_errors.cc b/src/node_errors.cc index 743264961327..63db97f6a56d 100644 --- a/src/node_errors.cc +++ b/src/node_errors.cc @@ -1064,7 +1064,12 @@ void PerIsolateMessageListener(Local message, Local error) { filename, message->GetLineNumber(env->context()).FromMaybe(-1), msg); - USE(ProcessEmitWarningGeneric(env, warning, "V8")); + // Defer the warning to the next event loop iteration. This prevents + // crashes when V8 emits warnings during code evaluation with + // throwOnSideEffect. + env->SetImmediate([warning](Environment* env) { + ProcessEmitWarningGeneric(env, warning, "V8"); + }); break; } case Isolate::MessageErrorLevel::kMessageError: From a786501288a70db3c65e8965e2e7e66c30a7c5a0 Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Sat, 30 May 2026 04:07:04 +0530 Subject: [PATCH 02/39] lib: diagnostics_channel use AsyncLocalStorage for suppression context Refs: #63623 Refs: #63651 Signed-off-by: Divyanshu Sharma --- lib/diagnostics_channel.js | 120 +++++++++++++++++++++++++++++++------ 1 file changed, 101 insertions(+), 19 deletions(-) diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index 8d2d374dc8e6..18f2005ff231 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -2,7 +2,6 @@ const { ArrayPrototypeAt, - ArrayPrototypeIndexOf, ArrayPrototypePush, ArrayPrototypePushApply, ArrayPrototypeSlice, @@ -15,6 +14,7 @@ const { ReflectApply, SafeFinalizationRegistry, SafeMap, + SafeSet, SymbolDispose, SymbolHasInstance, } = primordials; @@ -36,6 +36,32 @@ const { subscribers: subscriberCounts } = dc_binding; const { WeakReference } = require('internal/util'); const { isPromise } = require('internal/util/types'); +// Internal only: tracks a Set of active suppression keys for the current async +// context. Uses a simple stack-based approach to avoid bootstrap issues with +// async_hooks. This is a simplified implementation that works for typical usage. +let suppressionStorage = null; + +function getSuppressionsStorage() { + if (suppressionStorage === null) { + try { + const { AsyncLocalStorage } = require('async_hooks'); + suppressionStorage = new AsyncLocalStorage(); + } catch { + // If AsyncLocalStorage fails to initialize (rare), use a fallback + // that won't provide async context isolation but at least works + suppressionStorage = false; // Marker for "tried and failed" + } + } + return suppressionStorage || undefined; +} + +function withSuppressionsContext(set, fn, thisArg, args) { + const storage = getSuppressionsStorage(); + if (storage) { + return storage.run(set, () => ReflectApply(fn, thisArg, args)); + } + return ReflectApply(fn, thisArg, args); +} // Can't delete when weakref count reaches 0 as it could increment again. // Only GC can be used as a valid time to clean up the channels map. class WeakRefMap extends SafeMap { @@ -93,9 +119,17 @@ class RunStoresScope { // Enter stores using withScope if (activeChannel._stores) { + const storage = getSuppressionsStorage(); + const activeKeys = storage ? storage.getStore() : undefined; for (const entry of activeChannel._stores.entries()) { const store = entry[0]; - const transform = entry[1]; + const { transform, suppressedBy = null } = entry[1]; + + // Skip this bound store if it opted into suppression and its key + // is active in the current async context. + if (suppressedBy !== null && activeKeys?.has(suppressedBy)) { + continue; + } let newContext = data; if (transform) { @@ -127,16 +161,32 @@ class RunStoresScope { // TODO(qard): should there be a C++ channel interface? class ActiveChannel { - subscribe(subscription) { + subscribe(subscription, options = {}) { validateFunction(subscription, 'subscription'); + const suppressedBy = options && options.suppressedBy !== undefined ? options.suppressedBy : null; + if (suppressedBy !== null) { + const t = typeof suppressedBy; + if (t === 'string' || t === 'number' || t === 'bigint' || t === 'boolean') { + throw new ERR_INVALID_ARG_TYPE('suppressedBy', ['object', 'symbol', 'function'], suppressedBy); + } + } + + const handler = subscription; this._subscribers = ArrayPrototypeSlice(this._subscribers); - ArrayPrototypePush(this._subscribers, subscription); + ArrayPrototypePush(this._subscribers, { handler, suppressedBy }); channels.incRef(this.name); if (this._index !== undefined) subscriberCounts[this._index]++; } unsubscribe(subscription) { - const index = ArrayPrototypeIndexOf(this._subscribers, subscription); + // Find subscriber entry by handler identity. + let index = -1; + for (let i = 0; i < (this._subscribers?.length || 0); i++) { + if (this._subscribers[i].handler === subscription) { + index = i; + break; + } + } if (index === -1) return false; const before = ArrayPrototypeSlice(this._subscribers, 0, index); @@ -151,13 +201,21 @@ class ActiveChannel { return true; } - bindStore(store, transform) { + bindStore(store, transform, options = {}) { + const suppressedBy = options && options.suppressedBy !== undefined ? options.suppressedBy : null; + if (suppressedBy !== null) { + const t = typeof suppressedBy; + if (t === 'string' || t === 'number' || t === 'bigint' || t === 'boolean') { + throw new ERR_INVALID_ARG_TYPE('suppressedBy', ['object', 'symbol', 'function'], suppressedBy); + } + } + const replacing = this._stores.has(store); if (!replacing) { channels.incRef(this.name); if (this._index !== undefined) subscriberCounts[this._index]++; } - this._stores.set(store, transform); + this._stores.set(store, { transform, suppressedBy }); } unbindStore(store) { @@ -180,10 +238,15 @@ class ActiveChannel { publish(data) { const subscribers = this._subscribers; + const storage = getSuppressionsStorage(); + const activeKeys = storage ? storage.getStore() : undefined; for (let i = 0; i < (subscribers?.length || 0); i++) { try { - const onMessage = subscribers[i]; - onMessage(data, this.name); + const { handler, suppressedBy = null } = subscribers[i]; + if (suppressedBy !== null && activeKeys?.has(suppressedBy)) { + continue; + } + handler(data, this.name); } catch (err) { process.nextTick(() => { triggerUncaughtException(err, false); @@ -221,18 +284,18 @@ class Channel { prototype === ActiveChannel.prototype; } - subscribe(subscription) { + subscribe(subscription, options) { markActive(this); - this.subscribe(subscription); + this.subscribe(subscription, options); } unsubscribe() { return false; } - bindStore(store, transform) { + bindStore(store, transform, options) { markActive(this); - this.bindStore(store, transform); + this.bindStore(store, transform, options); } unbindStore() { @@ -366,12 +429,12 @@ class BoundedChannel { this.end?.hasSubscribers; } - subscribe(handlers) { + subscribe(handlers, options) { for (let i = 0; i < boundedEvents.length; ++i) { const name = boundedEvents[i]; if (!handlers[name]) continue; - this[name]?.subscribe(handlers[name]); + this[name]?.subscribe(handlers[name], options); } } @@ -458,13 +521,13 @@ class TracingChannel { this.error?.hasSubscribers; } - subscribe(handlers) { + subscribe(handlers, options) { // Subscribe to call window (start/end) if (handlers.start || handlers.end) { this.#callWindow.subscribe({ start: handlers.start, end: handlers.end, - }); + }, options); } // Subscribe to continuation window (asyncStart/asyncEnd) @@ -472,12 +535,12 @@ class TracingChannel { this.#continuationWindow.subscribe({ start: handlers.asyncStart, end: handlers.asyncEnd, - }); + }, options); } // Subscribe to error channel if (handlers.error) { - this.error.subscribe(handlers.error); + this.error.subscribe(handlers.error, options); } } @@ -633,10 +696,29 @@ function tracingChannel(nameOrChannels) { dc_binding.linkNativeChannel((name) => channel(name)); +function suppressed(key, fn, thisArg, ...args) { + validateFunction(fn, 'fn'); + + if (key === null || key === undefined) { + throw new ERR_INVALID_ARG_TYPE('key', ['object', 'symbol', 'function'], key); + } + const t = typeof key; + if (t === 'string' || t === 'number' || t === 'bigint' || t === 'boolean') { + throw new ERR_INVALID_ARG_TYPE('key', ['object', 'symbol', 'function'], key); + } + + const storage = getSuppressionsStorage(); + const currentSet = storage ? storage.getStore() : undefined; + const next = currentSet ? new SafeSet(currentSet) : new SafeSet(); + next.add(key); + return withSuppressionsContext(next, fn, thisArg, args); +} + module.exports = { channel, hasSubscribers, subscribe, + suppressed, tracingChannel, unsubscribe, boundedChannel, From e4aea85312a5f045c49136c1f1b88c84b9cd2d9b Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Sat, 30 May 2026 04:07:05 +0530 Subject: [PATCH 03/39] test: add diagnostics_channel suppression coverage Refs: #63623 Refs: #63651 Signed-off-by: Divyanshu Sharma --- .../test-diagnostics-channel-suppression.js | 255 ++++++++++++++++++ 1 file changed, 255 insertions(+) create mode 100644 test/parallel/test-diagnostics-channel-suppression.js diff --git a/test/parallel/test-diagnostics-channel-suppression.js b/test/parallel/test-diagnostics-channel-suppression.js new file mode 100644 index 000000000000..a0143b9d2faf --- /dev/null +++ b/test/parallel/test-diagnostics-channel-suppression.js @@ -0,0 +1,255 @@ +'use strict'; + +const common = require('../common'); +const assert = require('assert'); +const { channel, suppressed } = require('node:diagnostics_channel'); +const { AsyncLocalStorage } = require('async_hooks'); + +// Helper to run a function and capture whether a handler was called +function makeHandler() { + let called = false; + const handler = (msg) => { called = true; }; + return { + handler, + called: () => called, + reset: () => { called = false; } + }; +} + +// Test 1: Basic suppression - subscriber with suppressedBy is skipped inside suppressed() +(function testBasicSuppression() { + const key = Symbol('tracer'); + const ch = channel('test-suppression-basic'); + const h = makeHandler(); + ch.subscribe(h.handler, { suppressedBy: key }); + + suppressed(key, () => { + ch.publish({}); + }); + + assert.strictEqual(h.called(), false, 'suppressed subscriber should not be called'); + // cleanup + ch.unsubscribe(h.handler); +})(); + +// Test 2: Non-opted subscriber fires even inside suppressed() scope +(function testNonOptedFires() { + const key = Symbol('tracer2'); + const ch = channel('test-suppression-nonopted'); + const h1 = makeHandler(); + const h2 = makeHandler(); + ch.subscribe(h1.handler, { suppressedBy: key }); + ch.subscribe(h2.handler); // no suppression + + suppressed(key, () => { + ch.publish({}); + }); + + assert.strictEqual(h1.called(), false, 'opted subscriber should be skipped'); + assert.strictEqual(h2.called(), true, 'non-opted subscriber should be called'); + + ch.unsubscribe(h1.handler); + ch.unsubscribe(h2.handler); +})(); + +// Test 3: Two APMs with different keys don't suppress each other +(function testTwoKeysIndependent() { + const k1 = Symbol('k1'); + const k2 = Symbol('k2'); + const ch = channel('test-suppression-two-keys'); + const h1 = makeHandler(); + const h2 = makeHandler(); + ch.subscribe(h1.handler, { suppressedBy: k1 }); + ch.subscribe(h2.handler, { suppressedBy: k2 }); + + suppressed(k1, () => { + ch.publish({}); + }); + + assert.strictEqual(h1.called(), false); + assert.strictEqual(h2.called(), true); + + h1.reset(); h2.reset(); + + suppressed(k2, () => { + ch.publish({}); + }); + + assert.strictEqual(h1.called(), true); + assert.strictEqual(h2.called(), false); + + ch.unsubscribe(h1.handler); + ch.unsubscribe(h2.handler); +})(); + +// Test 4: Nested suppressed() calls (same key, different keys) +(function testNestedSuppressed() { + const k1 = Symbol('nested1'); + const k2 = Symbol('nested2'); + const ch = channel('test-suppression-nested'); + const h1 = makeHandler(); + const h2 = makeHandler(); + ch.subscribe(h1.handler, { suppressedBy: k1 }); + ch.subscribe(h2.handler, { suppressedBy: k2 }); + + suppressed(k1, () => { + // inside k1, h1 skipped, h2 runs + ch.publish({}); + assert.strictEqual(h1.called(), false); + assert.strictEqual(h2.called(), true); + h2.reset(); + + suppressed(k2, () => { + // inside both, both skipped + ch.publish({}); + assert.strictEqual(h1.called(), false); + assert.strictEqual(h2.called(), false); + }); + + // back to only k1 + ch.publish({}); + assert.strictEqual(h1.called(), false); + assert.strictEqual(h2.called(), true); + }); + + ch.unsubscribe(h1.handler); + ch.unsubscribe(h2.handler); +})(); + +// Test 5: suppressed() across a Promise boundary (async/await) +(async function testSuppressedAcrossPromise() { + const key = Symbol('promise'); + const ch = channel('test-suppression-promise'); + const h = makeHandler(); + ch.subscribe(h.handler, { suppressedBy: key }); + + await suppressed(key, async () => { + await Promise.resolve(); + ch.publish({}); + }); + + assert.strictEqual(h.called(), false); + ch.unsubscribe(h.handler); +})(); + +// Test 6: suppressed() across setImmediate and queueMicrotask +(async function testSuppressedAcrossTimers() { + const key = Symbol('timers'); + const ch = channel('test-suppression-timers'); + const h = makeHandler(); + ch.subscribe(h.handler, { suppressedBy: key }); + + await suppressed(key, async () => { + await new Promise((resolve) => { + setImmediate(() => { + ch.publish({}); + assert.strictEqual(h.called(), false); + h.reset(); + + queueMicrotask(() => { + ch.publish({}); + assert.strictEqual(h.called(), false); + + ch.unsubscribe(h.handler); + resolve(); + }); + }); + }); + }); +})(); + +// Test 7: unsubscribe() works correctly after using suppressedBy +(function testUnsubscribeCleansUp() { + const key = Symbol('unsub'); + const ch = channel('test-suppression-unsubscribe'); + const h = makeHandler(); + ch.subscribe(h.handler, { suppressedBy: key }); + ch.unsubscribe(h.handler); + + // Should not throw and should not be called + suppressed(key, () => { + ch.publish({}); + }); + + assert.strictEqual(h.called(), false); +})(); + +// Test 8: bindStore with suppressedBy is skipped inside suppressed() +(function testBindStoreSuppression() { + const key = Symbol('store'); + const ch = channel('test-suppression-store'); + const als = new AsyncLocalStorage(); + + let transformCalls = 0; + const handler = common.mustCall(() => { + assert.strictEqual(als.getStore(), undefined); + }); + + ch.subscribe(handler); + ch.bindStore(als, (d) => { + transformCalls++; + return { foo: d }; + }, { suppressedBy: key }); + + suppressed(key, () => { + ch.publish({}); + }); + + assert.strictEqual(transformCalls, 0); + ch.unsubscribe(handler); + ch.unbindStore(als); +})(); + +// Test 9: Wrong type for suppressedBy throws ERR_INVALID_ARG_TYPE +(function testWrongTypeThrows() { + const ch = channel('test-suppression-wrong-type'); + const bad = 'not-allowed'; + assert.throws(() => ch.subscribe(() => {}, { suppressedBy: bad }), { + name: 'TypeError' + }); + const als = new AsyncLocalStorage(); + assert.throws(() => ch.bindStore(als, (d) => d, { suppressedBy: bad }), { + name: 'TypeError' + }); +})(); + +// Test 10: suppressed() return value passes through fn's return value +(function testSuppressedReturnValueAndContext() { + const key = Symbol('return'); + const receiver = { value: 41 }; + const result = suppressed(key, function(a, b) { + assert.strictEqual(this, receiver); + assert.strictEqual(a, 'a'); + assert.strictEqual(b, 'b'); + return this.value + 1; + }, receiver, 'a', 'b'); + assert.strictEqual(result, 42); +})(); + +// Test 11: null suppressedBy behaves like no suppression opt-in +(function testNullSuppressedByIsIgnored() { + const key = Symbol('null-suppressed-by'); + const ch = channel('test-suppression-null-suppressed-by'); + const h = makeHandler(); + + ch.subscribe(h.handler, { suppressedBy: null }); + + suppressed(key, () => { + ch.publish({}); + }); + + assert.strictEqual(h.called(), true); + ch.unsubscribe(h.handler); +})(); + +// Test 12: suppressed() rejects null/undefined keys consistently +(function testKeyValidation() { + assert.throws(() => suppressed(null, () => {}), { + name: 'TypeError' + }); + assert.throws(() => suppressed(undefined, () => {}), { + name: 'TypeError' + }); +})(); + +console.log('ok - diagnostics_channel suppression tests loaded'); From a5c4940295ffd4dcfcb026834e579f990f5197b3 Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Sat, 30 May 2026 13:54:10 +0530 Subject: [PATCH 04/39] lib: rename diagnostics_channel suppression option to subscriberId Signed-off-by: Divyanshu Sharma --- lib/diagnostics_channel.js | 62 ++++++++++++++------------------------ 1 file changed, 23 insertions(+), 39 deletions(-) diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index 18f2005ff231..ccabaade8498 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -36,31 +36,18 @@ const { subscribers: subscriberCounts } = dc_binding; const { WeakReference } = require('internal/util'); const { isPromise } = require('internal/util/types'); -// Internal only: tracks a Set of active suppression keys for the current async -// context. Uses a simple stack-based approach to avoid bootstrap issues with -// async_hooks. This is a simplified implementation that works for typical usage. -let suppressionStorage = null; +let suppressionStorage; function getSuppressionsStorage() { - if (suppressionStorage === null) { - try { - const { AsyncLocalStorage } = require('async_hooks'); - suppressionStorage = new AsyncLocalStorage(); - } catch { - // If AsyncLocalStorage fails to initialize (rare), use a fallback - // that won't provide async context isolation but at least works - suppressionStorage = false; // Marker for "tried and failed" - } + if (suppressionStorage === undefined) { + const { AsyncLocalStorage } = require('async_hooks'); + suppressionStorage = new AsyncLocalStorage(); } - return suppressionStorage || undefined; + return suppressionStorage; } function withSuppressionsContext(set, fn, thisArg, args) { - const storage = getSuppressionsStorage(); - if (storage) { - return storage.run(set, () => ReflectApply(fn, thisArg, args)); - } - return ReflectApply(fn, thisArg, args); + return getSuppressionsStorage().run(set, () => ReflectApply(fn, thisArg, args)); } // Can't delete when weakref count reaches 0 as it could increment again. // Only GC can be used as a valid time to clean up the channels map. @@ -119,15 +106,14 @@ class RunStoresScope { // Enter stores using withScope if (activeChannel._stores) { - const storage = getSuppressionsStorage(); - const activeKeys = storage ? storage.getStore() : undefined; + const activeKeys = getSuppressionsStorage().getStore(); for (const entry of activeChannel._stores.entries()) { const store = entry[0]; - const { transform, suppressedBy = null } = entry[1]; + const { transform, subscriberId = null } = entry[1]; // Skip this bound store if it opted into suppression and its key // is active in the current async context. - if (suppressedBy !== null && activeKeys?.has(suppressedBy)) { + if (subscriberId !== null && activeKeys?.has(subscriberId)) { continue; } @@ -163,17 +149,17 @@ class RunStoresScope { class ActiveChannel { subscribe(subscription, options = {}) { validateFunction(subscription, 'subscription'); - const suppressedBy = options && options.suppressedBy !== undefined ? options.suppressedBy : null; - if (suppressedBy !== null) { - const t = typeof suppressedBy; + const subscriberId = options && options.subscriberId !== undefined ? options.subscriberId : null; + if (subscriberId !== null) { + const t = typeof subscriberId; if (t === 'string' || t === 'number' || t === 'bigint' || t === 'boolean') { - throw new ERR_INVALID_ARG_TYPE('suppressedBy', ['object', 'symbol', 'function'], suppressedBy); + throw new ERR_INVALID_ARG_TYPE('subscriberId', ['object', 'symbol', 'function'], subscriberId); } } const handler = subscription; this._subscribers = ArrayPrototypeSlice(this._subscribers); - ArrayPrototypePush(this._subscribers, { handler, suppressedBy }); + ArrayPrototypePush(this._subscribers, { handler, subscriberId }); channels.incRef(this.name); if (this._index !== undefined) subscriberCounts[this._index]++; } @@ -202,11 +188,11 @@ class ActiveChannel { } bindStore(store, transform, options = {}) { - const suppressedBy = options && options.suppressedBy !== undefined ? options.suppressedBy : null; - if (suppressedBy !== null) { - const t = typeof suppressedBy; + const subscriberId = options && options.subscriberId !== undefined ? options.subscriberId : null; + if (subscriberId !== null) { + const t = typeof subscriberId; if (t === 'string' || t === 'number' || t === 'bigint' || t === 'boolean') { - throw new ERR_INVALID_ARG_TYPE('suppressedBy', ['object', 'symbol', 'function'], suppressedBy); + throw new ERR_INVALID_ARG_TYPE('subscriberId', ['object', 'symbol', 'function'], subscriberId); } } @@ -215,7 +201,7 @@ class ActiveChannel { channels.incRef(this.name); if (this._index !== undefined) subscriberCounts[this._index]++; } - this._stores.set(store, { transform, suppressedBy }); + this._stores.set(store, { transform, subscriberId }); } unbindStore(store) { @@ -238,12 +224,11 @@ class ActiveChannel { publish(data) { const subscribers = this._subscribers; - const storage = getSuppressionsStorage(); - const activeKeys = storage ? storage.getStore() : undefined; + const activeKeys = getSuppressionsStorage().getStore(); for (let i = 0; i < (subscribers?.length || 0); i++) { try { - const { handler, suppressedBy = null } = subscribers[i]; - if (suppressedBy !== null && activeKeys?.has(suppressedBy)) { + const { handler, subscriberId = null } = subscribers[i]; + if (subscriberId !== null && activeKeys?.has(subscriberId)) { continue; } handler(data, this.name); @@ -707,8 +692,7 @@ function suppressed(key, fn, thisArg, ...args) { throw new ERR_INVALID_ARG_TYPE('key', ['object', 'symbol', 'function'], key); } - const storage = getSuppressionsStorage(); - const currentSet = storage ? storage.getStore() : undefined; + const currentSet = getSuppressionsStorage().getStore(); const next = currentSet ? new SafeSet(currentSet) : new SafeSet(); next.add(key); return withSuppressionsContext(next, fn, thisArg, args); From 7e415c058968d650cb5ca3be796ae6b73ecc1074 Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Sat, 30 May 2026 13:54:15 +0530 Subject: [PATCH 05/39] test: clean up diagnostics_channel suppression coverage Signed-off-by: Divyanshu Sharma --- .../test-diagnostics-channel-suppression.js | 203 +++++++----------- 1 file changed, 74 insertions(+), 129 deletions(-) diff --git a/test/parallel/test-diagnostics-channel-suppression.js b/test/parallel/test-diagnostics-channel-suppression.js index a0143b9d2faf..0f9e4cae3c6a 100644 --- a/test/parallel/test-diagnostics-channel-suppression.js +++ b/test/parallel/test-diagnostics-channel-suppression.js @@ -5,216 +5,187 @@ const assert = require('assert'); const { channel, suppressed } = require('node:diagnostics_channel'); const { AsyncLocalStorage } = require('async_hooks'); -// Helper to run a function and capture whether a handler was called -function makeHandler() { - let called = false; - const handler = (msg) => { called = true; }; - return { - handler, - called: () => called, - reset: () => { called = false; } - }; -} - -// Test 1: Basic suppression - subscriber with suppressedBy is skipped inside suppressed() -(function testBasicSuppression() { +// Test 1: Basic suppression - subscriber with subscriberId is skipped inside suppressed() +{ const key = Symbol('tracer'); const ch = channel('test-suppression-basic'); - const h = makeHandler(); - ch.subscribe(h.handler, { suppressedBy: key }); + const handler = common.mustNotCall(); + ch.subscribe(handler, { subscriberId: key }); suppressed(key, () => { ch.publish({}); }); - assert.strictEqual(h.called(), false, 'suppressed subscriber should not be called'); - // cleanup - ch.unsubscribe(h.handler); -})(); + ch.unsubscribe(handler); +} // Test 2: Non-opted subscriber fires even inside suppressed() scope -(function testNonOptedFires() { +{ const key = Symbol('tracer2'); const ch = channel('test-suppression-nonopted'); - const h1 = makeHandler(); - const h2 = makeHandler(); - ch.subscribe(h1.handler, { suppressedBy: key }); - ch.subscribe(h2.handler); // no suppression + const optedHandler = common.mustNotCall(); + const regularHandler = common.mustCall(() => {}, 1); + ch.subscribe(optedHandler, { subscriberId: key }); + ch.subscribe(regularHandler); // no suppression suppressed(key, () => { ch.publish({}); }); - assert.strictEqual(h1.called(), false, 'opted subscriber should be skipped'); - assert.strictEqual(h2.called(), true, 'non-opted subscriber should be called'); - - ch.unsubscribe(h1.handler); - ch.unsubscribe(h2.handler); -})(); + ch.unsubscribe(optedHandler); + ch.unsubscribe(regularHandler); +} // Test 3: Two APMs with different keys don't suppress each other -(function testTwoKeysIndependent() { +{ const k1 = Symbol('k1'); const k2 = Symbol('k2'); const ch = channel('test-suppression-two-keys'); - const h1 = makeHandler(); - const h2 = makeHandler(); - ch.subscribe(h1.handler, { suppressedBy: k1 }); - ch.subscribe(h2.handler, { suppressedBy: k2 }); + let h1Calls = 0; + let h2Calls = 0; + const h1 = common.mustCall(() => { h1Calls++; }, 1); + const h2 = common.mustCall(() => { h2Calls++; }, 1); + ch.subscribe(h1, { subscriberId: k1 }); + ch.subscribe(h2, { subscriberId: k2 }); suppressed(k1, () => { ch.publish({}); }); - assert.strictEqual(h1.called(), false); - assert.strictEqual(h2.called(), true); - - h1.reset(); h2.reset(); + assert.strictEqual(h1Calls, 0); + assert.strictEqual(h2Calls, 1); suppressed(k2, () => { ch.publish({}); }); - assert.strictEqual(h1.called(), true); - assert.strictEqual(h2.called(), false); + assert.strictEqual(h1Calls, 1); + assert.strictEqual(h2Calls, 1); - ch.unsubscribe(h1.handler); - ch.unsubscribe(h2.handler); -})(); + ch.unsubscribe(h1); + ch.unsubscribe(h2); +} // Test 4: Nested suppressed() calls (same key, different keys) -(function testNestedSuppressed() { +{ const k1 = Symbol('nested1'); const k2 = Symbol('nested2'); const ch = channel('test-suppression-nested'); - const h1 = makeHandler(); - const h2 = makeHandler(); - ch.subscribe(h1.handler, { suppressedBy: k1 }); - ch.subscribe(h2.handler, { suppressedBy: k2 }); + const h1 = common.mustNotCall(); + let h2Calls = 0; + const h2 = common.mustCall(() => { h2Calls++; }, 2); + ch.subscribe(h1, { subscriberId: k1 }); + ch.subscribe(h2, { subscriberId: k2 }); suppressed(k1, () => { // inside k1, h1 skipped, h2 runs ch.publish({}); - assert.strictEqual(h1.called(), false); - assert.strictEqual(h2.called(), true); - h2.reset(); + assert.strictEqual(h2Calls, 1); suppressed(k2, () => { // inside both, both skipped ch.publish({}); - assert.strictEqual(h1.called(), false); - assert.strictEqual(h2.called(), false); + assert.strictEqual(h2Calls, 1); }); // back to only k1 ch.publish({}); - assert.strictEqual(h1.called(), false); - assert.strictEqual(h2.called(), true); + assert.strictEqual(h2Calls, 2); }); - ch.unsubscribe(h1.handler); - ch.unsubscribe(h2.handler); -})(); + ch.unsubscribe(h1); + ch.unsubscribe(h2); +} -// Test 5: suppressed() across a Promise boundary (async/await) -(async function testSuppressedAcrossPromise() { +// Test 5: suppressed() across a Promise boundary +{ const key = Symbol('promise'); const ch = channel('test-suppression-promise'); - const h = makeHandler(); - ch.subscribe(h.handler, { suppressedBy: key }); + const handler = common.mustNotCall(); + ch.subscribe(handler, { subscriberId: key }); - await suppressed(key, async () => { + suppressed(key, async () => { await Promise.resolve(); ch.publish({}); - }); - - assert.strictEqual(h.called(), false); - ch.unsubscribe(h.handler); -})(); + }).then(common.mustCall(() => { + ch.unsubscribe(handler); + })); +} // Test 6: suppressed() across setImmediate and queueMicrotask -(async function testSuppressedAcrossTimers() { +{ const key = Symbol('timers'); const ch = channel('test-suppression-timers'); - const h = makeHandler(); - ch.subscribe(h.handler, { suppressedBy: key }); + const handler = common.mustNotCall(); + ch.subscribe(handler, { subscriberId: key }); - await suppressed(key, async () => { + suppressed(key, async () => { await new Promise((resolve) => { setImmediate(() => { ch.publish({}); - assert.strictEqual(h.called(), false); - h.reset(); queueMicrotask(() => { ch.publish({}); - assert.strictEqual(h.called(), false); - - ch.unsubscribe(h.handler); resolve(); }); }); }); - }); -})(); + }).then(common.mustCall(() => { + ch.unsubscribe(handler); + })); +} -// Test 7: unsubscribe() works correctly after using suppressedBy -(function testUnsubscribeCleansUp() { +// Test 7: unsubscribe() works correctly after using subscriberId +{ const key = Symbol('unsub'); const ch = channel('test-suppression-unsubscribe'); - const h = makeHandler(); - ch.subscribe(h.handler, { suppressedBy: key }); - ch.unsubscribe(h.handler); + const handler = common.mustNotCall(); + ch.subscribe(handler, { subscriberId: key }); + ch.unsubscribe(handler); // Should not throw and should not be called suppressed(key, () => { ch.publish({}); }); - assert.strictEqual(h.called(), false); -})(); +} -// Test 8: bindStore with suppressedBy is skipped inside suppressed() -(function testBindStoreSuppression() { +// Test 8: bindStore with subscriberId is skipped inside suppressed() +{ const key = Symbol('store'); const ch = channel('test-suppression-store'); const als = new AsyncLocalStorage(); - let transformCalls = 0; const handler = common.mustCall(() => { assert.strictEqual(als.getStore(), undefined); }); ch.subscribe(handler); - ch.bindStore(als, (d) => { - transformCalls++; - return { foo: d }; - }, { suppressedBy: key }); + ch.bindStore(als, common.mustNotCall(), { subscriberId: key }); suppressed(key, () => { ch.publish({}); }); - assert.strictEqual(transformCalls, 0); ch.unsubscribe(handler); ch.unbindStore(als); -})(); +} -// Test 9: Wrong type for suppressedBy throws ERR_INVALID_ARG_TYPE -(function testWrongTypeThrows() { +// Test 9: Wrong type for subscriberId throws ERR_INVALID_ARG_TYPE +{ const ch = channel('test-suppression-wrong-type'); const bad = 'not-allowed'; - assert.throws(() => ch.subscribe(() => {}, { suppressedBy: bad }), { + assert.throws(() => ch.subscribe(() => {}, { subscriberId: bad }), { name: 'TypeError' }); const als = new AsyncLocalStorage(); - assert.throws(() => ch.bindStore(als, (d) => d, { suppressedBy: bad }), { + assert.throws(() => ch.bindStore(als, (d) => d, { subscriberId: bad }), { name: 'TypeError' }); -})(); +} // Test 10: suppressed() return value passes through fn's return value -(function testSuppressedReturnValueAndContext() { +{ const key = Symbol('return'); const receiver = { value: 41 }; const result = suppressed(key, function(a, b) { @@ -224,32 +195,6 @@ function makeHandler() { return this.value + 1; }, receiver, 'a', 'b'); assert.strictEqual(result, 42); -})(); - -// Test 11: null suppressedBy behaves like no suppression opt-in -(function testNullSuppressedByIsIgnored() { - const key = Symbol('null-suppressed-by'); - const ch = channel('test-suppression-null-suppressed-by'); - const h = makeHandler(); - - ch.subscribe(h.handler, { suppressedBy: null }); - - suppressed(key, () => { - ch.publish({}); - }); - - assert.strictEqual(h.called(), true); - ch.unsubscribe(h.handler); -})(); - -// Test 12: suppressed() rejects null/undefined keys consistently -(function testKeyValidation() { - assert.throws(() => suppressed(null, () => {}), { - name: 'TypeError' - }); - assert.throws(() => suppressed(undefined, () => {}), { - name: 'TypeError' - }); -})(); +} console.log('ok - diagnostics_channel suppression tests loaded'); From 8e6d7cb8d55f902474f4334968bfaf543e125356 Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Sat, 30 May 2026 14:11:02 +0530 Subject: [PATCH 06/39] test: simplify diagnostics_channel suppression handler Signed-off-by: Divyanshu Sharma --- test/parallel/test-diagnostics-channel-suppression.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/parallel/test-diagnostics-channel-suppression.js b/test/parallel/test-diagnostics-channel-suppression.js index 0f9e4cae3c6a..cb396c011bed 100644 --- a/test/parallel/test-diagnostics-channel-suppression.js +++ b/test/parallel/test-diagnostics-channel-suppression.js @@ -24,7 +24,7 @@ const { AsyncLocalStorage } = require('async_hooks'); const key = Symbol('tracer2'); const ch = channel('test-suppression-nonopted'); const optedHandler = common.mustNotCall(); - const regularHandler = common.mustCall(() => {}, 1); + const regularHandler = common.mustCall(); ch.subscribe(optedHandler, { subscriberId: key }); ch.subscribe(regularHandler); // no suppression From 07e7e9768edc835009b31b4df5175598f4a70fd3 Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Sat, 30 May 2026 14:54:40 +0530 Subject: [PATCH 07/39] test: finalize diagnostics_channel suppression test Signed-off-by: Divyanshu Sharma --- .../test-diagnostics-channel-suppression.js | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/test/parallel/test-diagnostics-channel-suppression.js b/test/parallel/test-diagnostics-channel-suppression.js index cb396c011bed..ed75dd864d64 100644 --- a/test/parallel/test-diagnostics-channel-suppression.js +++ b/test/parallel/test-diagnostics-channel-suppression.js @@ -77,21 +77,21 @@ const { AsyncLocalStorage } = require('async_hooks'); ch.subscribe(h1, { subscriberId: k1 }); ch.subscribe(h2, { subscriberId: k2 }); - suppressed(k1, () => { - // inside k1, h1 skipped, h2 runs + suppressed(k1, common.mustSucceed(() => { + // Inside k1, h1 skipped, h2 runs ch.publish({}); assert.strictEqual(h2Calls, 1); - suppressed(k2, () => { - // inside both, both skipped + suppressed(k2, common.mustSucceed(() => { + // Inside both, both skipped ch.publish({}); assert.strictEqual(h2Calls, 1); - }); + })); - // back to only k1 + // Back to only k1 ch.publish({}); assert.strictEqual(h2Calls, 2); - }); + })); ch.unsubscribe(h1); ch.unsubscribe(h2); @@ -188,12 +188,12 @@ const { AsyncLocalStorage } = require('async_hooks'); { const key = Symbol('return'); const receiver = { value: 41 }; - const result = suppressed(key, function(a, b) { + const result = suppressed(key, common.mustSucceed(function(a, b) { assert.strictEqual(this, receiver); assert.strictEqual(a, 'a'); assert.strictEqual(b, 'b'); return this.value + 1; - }, receiver, 'a', 'b'); + }), receiver, 'a', 'b'); assert.strictEqual(result, 42); } From 94687951f36707b335dd9e94b85f2cfa0bfc09d6 Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Sat, 30 May 2026 15:08:35 +0530 Subject: [PATCH 08/39] diag(suppression-als): use ALS.run bound fn for suppression context; update tests to use common.mustCall --- lib/diagnostics_channel.js | 2 +- test/parallel/test-diagnostics-channel-suppression.js | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index ccabaade8498..cfcbb2ea1f32 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -47,7 +47,7 @@ function getSuppressionsStorage() { } function withSuppressionsContext(set, fn, thisArg, args) { - return getSuppressionsStorage().run(set, () => ReflectApply(fn, thisArg, args)); + return getSuppressionsStorage().run(set, fn.bind(thisArg), ...args); } // Can't delete when weakref count reaches 0 as it could increment again. // Only GC can be used as a valid time to clean up the channels map. diff --git a/test/parallel/test-diagnostics-channel-suppression.js b/test/parallel/test-diagnostics-channel-suppression.js index ed75dd864d64..f826db8ded52 100644 --- a/test/parallel/test-diagnostics-channel-suppression.js +++ b/test/parallel/test-diagnostics-channel-suppression.js @@ -77,12 +77,12 @@ const { AsyncLocalStorage } = require('async_hooks'); ch.subscribe(h1, { subscriberId: k1 }); ch.subscribe(h2, { subscriberId: k2 }); - suppressed(k1, common.mustSucceed(() => { + suppressed(k1, common.mustCall(() => { // Inside k1, h1 skipped, h2 runs ch.publish({}); assert.strictEqual(h2Calls, 1); - suppressed(k2, common.mustSucceed(() => { + suppressed(k2, common.mustCall(() => { // Inside both, both skipped ch.publish({}); assert.strictEqual(h2Calls, 1); @@ -188,7 +188,7 @@ const { AsyncLocalStorage } = require('async_hooks'); { const key = Symbol('return'); const receiver = { value: 41 }; - const result = suppressed(key, common.mustSucceed(function(a, b) { + const result = suppressed(key, common.mustCall(function(a, b) { assert.strictEqual(this, receiver); assert.strictEqual(a, 'a'); assert.strictEqual(b, 'b'); From b8194afe6a730666b64f07e046662c5d00a93da4 Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Sat, 30 May 2026 15:38:54 +0530 Subject: [PATCH 09/39] test: wrap suppressed callbacks with common.mustCall Signed-off-by: Divyanshu Sharma --- .../test-diagnostics-channel-suppression.js | 46 ++++++++++--------- 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/test/parallel/test-diagnostics-channel-suppression.js b/test/parallel/test-diagnostics-channel-suppression.js index f826db8ded52..cd3523848a81 100644 --- a/test/parallel/test-diagnostics-channel-suppression.js +++ b/test/parallel/test-diagnostics-channel-suppression.js @@ -12,9 +12,9 @@ const { AsyncLocalStorage } = require('async_hooks'); const handler = common.mustNotCall(); ch.subscribe(handler, { subscriberId: key }); - suppressed(key, () => { + suppressed(key, common.mustCall(() => { ch.publish({}); - }); + })); ch.unsubscribe(handler); } @@ -28,9 +28,9 @@ const { AsyncLocalStorage } = require('async_hooks'); ch.subscribe(optedHandler, { subscriberId: key }); ch.subscribe(regularHandler); // no suppression - suppressed(key, () => { + suppressed(key, common.mustCall(() => { ch.publish({}); - }); + })); ch.unsubscribe(optedHandler); ch.unsubscribe(regularHandler); @@ -48,16 +48,16 @@ const { AsyncLocalStorage } = require('async_hooks'); ch.subscribe(h1, { subscriberId: k1 }); ch.subscribe(h2, { subscriberId: k2 }); - suppressed(k1, () => { + suppressed(k1, common.mustCall(() => { ch.publish({}); - }); + })); assert.strictEqual(h1Calls, 0); assert.strictEqual(h2Calls, 1); - suppressed(k2, () => { + suppressed(k2, common.mustCall(() => { ch.publish({}); - }); + })); assert.strictEqual(h1Calls, 1); assert.strictEqual(h2Calls, 1); @@ -103,12 +103,14 @@ const { AsyncLocalStorage } = require('async_hooks'); const ch = channel('test-suppression-promise'); const handler = common.mustNotCall(); ch.subscribe(handler, { subscriberId: key }); + const done = common.mustCall(); - suppressed(key, async () => { + suppressed(key, common.mustCall(async () => { await Promise.resolve(); ch.publish({}); - }).then(common.mustCall(() => { + })).then(common.mustCall(() => { ch.unsubscribe(handler); + done(); })); } @@ -118,20 +120,22 @@ const { AsyncLocalStorage } = require('async_hooks'); const ch = channel('test-suppression-timers'); const handler = common.mustNotCall(); ch.subscribe(handler, { subscriberId: key }); + const done = common.mustCall(); - suppressed(key, async () => { + suppressed(key, common.mustCall(async () => { await new Promise((resolve) => { - setImmediate(() => { + setImmediate(common.mustCall(() => { ch.publish({}); - queueMicrotask(() => { + queueMicrotask(common.mustCall(() => { ch.publish({}); resolve(); - }); - }); + })); + })); }); - }).then(common.mustCall(() => { + })).then(common.mustCall(() => { ch.unsubscribe(handler); + done(); })); } @@ -144,9 +148,9 @@ const { AsyncLocalStorage } = require('async_hooks'); ch.unsubscribe(handler); // Should not throw and should not be called - suppressed(key, () => { + suppressed(key, common.mustCall(() => { ch.publish({}); - }); + })); } @@ -163,9 +167,9 @@ const { AsyncLocalStorage } = require('async_hooks'); ch.subscribe(handler); ch.bindStore(als, common.mustNotCall(), { subscriberId: key }); - suppressed(key, () => { + suppressed(key, common.mustCall(() => { ch.publish({}); - }); + })); ch.unsubscribe(handler); ch.unbindStore(als); @@ -196,5 +200,3 @@ const { AsyncLocalStorage } = require('async_hooks'); }), receiver, 'a', 'b'); assert.strictEqual(result, 42); } - -console.log('ok - diagnostics_channel suppression tests loaded'); From 66e0cc9bf06d25f706f186eaf5bd57fd0dbe88b5 Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Sat, 30 May 2026 20:27:10 +0530 Subject: [PATCH 10/39] src: emit V8 warnings synchronously in PerIsolateMessageListener (remove SetImmediate deferral) Signed-off-by: Divyanshu Sharma --- src/node_errors.cc | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/node_errors.cc b/src/node_errors.cc index 63db97f6a56d..9b7adae8806a 100644 --- a/src/node_errors.cc +++ b/src/node_errors.cc @@ -1064,12 +1064,8 @@ void PerIsolateMessageListener(Local message, Local error) { filename, message->GetLineNumber(env->context()).FromMaybe(-1), msg); - // Defer the warning to the next event loop iteration. This prevents - // crashes when V8 emits warnings during code evaluation with - // throwOnSideEffect. - env->SetImmediate([warning](Environment* env) { - ProcessEmitWarningGeneric(env, warning, "V8"); - }); + // Emit the warning immediately. + ProcessEmitWarningGeneric(env, warning, "V8"); break; } case Isolate::MessageErrorLevel::kMessageError: From 01d9cc054e2166f6a38b485c925f379abd1b0e2e Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Sat, 30 May 2026 20:31:07 +0530 Subject: [PATCH 11/39] src: reintroduce synchronous V8 warning emission (USE wrapper) Signed-off-by: Divyanshu Sharma --- src/node_errors.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/node_errors.cc b/src/node_errors.cc index 9b7adae8806a..2c0fc0c33c02 100644 --- a/src/node_errors.cc +++ b/src/node_errors.cc @@ -1065,7 +1065,7 @@ void PerIsolateMessageListener(Local message, Local error) { message->GetLineNumber(env->context()).FromMaybe(-1), msg); // Emit the warning immediately. - ProcessEmitWarningGeneric(env, warning, "V8"); + USE(ProcessEmitWarningGeneric(env, warning, "V8")); break; } case Isolate::MessageErrorLevel::kMessageError: From ddf8179804d6513b6ab709462a4df4b0a1ca656a Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Sun, 31 May 2026 14:31:06 +0530 Subject: [PATCH 12/39] lib: initialize suppression storage eagerly --- lib/diagnostics_channel.js | 22 ++++++---------------- 1 file changed, 6 insertions(+), 16 deletions(-) diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index cfcbb2ea1f32..5f567717192c 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -35,20 +35,10 @@ const { subscribers: subscriberCounts } = dc_binding; const { WeakReference } = require('internal/util'); const { isPromise } = require('internal/util/types'); +const { AsyncLocalStorage } = require('async_hooks'); -let suppressionStorage; +const suppressionStorage = new AsyncLocalStorage(); -function getSuppressionsStorage() { - if (suppressionStorage === undefined) { - const { AsyncLocalStorage } = require('async_hooks'); - suppressionStorage = new AsyncLocalStorage(); - } - return suppressionStorage; -} - -function withSuppressionsContext(set, fn, thisArg, args) { - return getSuppressionsStorage().run(set, fn.bind(thisArg), ...args); -} // Can't delete when weakref count reaches 0 as it could increment again. // Only GC can be used as a valid time to clean up the channels map. class WeakRefMap extends SafeMap { @@ -106,7 +96,7 @@ class RunStoresScope { // Enter stores using withScope if (activeChannel._stores) { - const activeKeys = getSuppressionsStorage().getStore(); + const activeKeys = suppressionStorage.getStore(); for (const entry of activeChannel._stores.entries()) { const store = entry[0]; const { transform, subscriberId = null } = entry[1]; @@ -224,7 +214,7 @@ class ActiveChannel { publish(data) { const subscribers = this._subscribers; - const activeKeys = getSuppressionsStorage().getStore(); + const activeKeys = suppressionStorage.getStore(); for (let i = 0; i < (subscribers?.length || 0); i++) { try { const { handler, subscriberId = null } = subscribers[i]; @@ -692,10 +682,10 @@ function suppressed(key, fn, thisArg, ...args) { throw new ERR_INVALID_ARG_TYPE('key', ['object', 'symbol', 'function'], key); } - const currentSet = getSuppressionsStorage().getStore(); + const currentSet = suppressionStorage.getStore(); const next = currentSet ? new SafeSet(currentSet) : new SafeSet(); next.add(key); - return withSuppressionsContext(next, fn, thisArg, args); + return suppressionStorage.run(next, () => ReflectApply(fn, thisArg, args)); } module.exports = { From 909f0fc56169a9a70af5cef347cf575b2f6920b4 Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Sun, 31 May 2026 14:48:51 +0530 Subject: [PATCH 13/39] Revert "lib: initialize suppression storage eagerly" This reverts commit ddf8179804d6513b6ab709462a4df4b0a1ca656a. --- lib/diagnostics_channel.js | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index 5f567717192c..cfcbb2ea1f32 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -35,10 +35,20 @@ const { subscribers: subscriberCounts } = dc_binding; const { WeakReference } = require('internal/util'); const { isPromise } = require('internal/util/types'); -const { AsyncLocalStorage } = require('async_hooks'); -const suppressionStorage = new AsyncLocalStorage(); +let suppressionStorage; +function getSuppressionsStorage() { + if (suppressionStorage === undefined) { + const { AsyncLocalStorage } = require('async_hooks'); + suppressionStorage = new AsyncLocalStorage(); + } + return suppressionStorage; +} + +function withSuppressionsContext(set, fn, thisArg, args) { + return getSuppressionsStorage().run(set, fn.bind(thisArg), ...args); +} // Can't delete when weakref count reaches 0 as it could increment again. // Only GC can be used as a valid time to clean up the channels map. class WeakRefMap extends SafeMap { @@ -96,7 +106,7 @@ class RunStoresScope { // Enter stores using withScope if (activeChannel._stores) { - const activeKeys = suppressionStorage.getStore(); + const activeKeys = getSuppressionsStorage().getStore(); for (const entry of activeChannel._stores.entries()) { const store = entry[0]; const { transform, subscriberId = null } = entry[1]; @@ -214,7 +224,7 @@ class ActiveChannel { publish(data) { const subscribers = this._subscribers; - const activeKeys = suppressionStorage.getStore(); + const activeKeys = getSuppressionsStorage().getStore(); for (let i = 0; i < (subscribers?.length || 0); i++) { try { const { handler, subscriberId = null } = subscribers[i]; @@ -682,10 +692,10 @@ function suppressed(key, fn, thisArg, ...args) { throw new ERR_INVALID_ARG_TYPE('key', ['object', 'symbol', 'function'], key); } - const currentSet = suppressionStorage.getStore(); + const currentSet = getSuppressionsStorage().getStore(); const next = currentSet ? new SafeSet(currentSet) : new SafeSet(); next.add(key); - return suppressionStorage.run(next, () => ReflectApply(fn, thisArg, args)); + return withSuppressionsContext(next, fn, thisArg, args); } module.exports = { From e630f722439b238daf4f5380dc48eb017f983871 Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Sun, 31 May 2026 21:46:24 +0530 Subject: [PATCH 14/39] src: defer V8 warning emission to next tick --- src/node_errors.cc | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/node_errors.cc b/src/node_errors.cc index 2c0fc0c33c02..63db97f6a56d 100644 --- a/src/node_errors.cc +++ b/src/node_errors.cc @@ -1064,8 +1064,12 @@ void PerIsolateMessageListener(Local message, Local error) { filename, message->GetLineNumber(env->context()).FromMaybe(-1), msg); - // Emit the warning immediately. - USE(ProcessEmitWarningGeneric(env, warning, "V8")); + // Defer the warning to the next event loop iteration. This prevents + // crashes when V8 emits warnings during code evaluation with + // throwOnSideEffect. + env->SetImmediate([warning](Environment* env) { + ProcessEmitWarningGeneric(env, warning, "V8"); + }); break; } case Isolate::MessageErrorLevel::kMessageError: From cd5c009858253344ffddfd5b40ee35e3555805d1 Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Thu, 4 Jun 2026 03:29:29 +0530 Subject: [PATCH 15/39] lib: unify bypass key validation in diagnostics_channel Signed-off-by: Divyanshu Sharma --- lib/diagnostics_channel.js | 219 ++++++++++++++++++++++++++----------- 1 file changed, 154 insertions(+), 65 deletions(-) diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index cfcbb2ea1f32..d0911148bcab 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -47,8 +47,22 @@ function getSuppressionsStorage() { } function withSuppressionsContext(set, fn, thisArg, args) { - return getSuppressionsStorage().run(set, fn.bind(thisArg), ...args); + return getSuppressionsStorage().run( + set, + () => ReflectApply(fn, thisArg, args), + ); } + +function validateBypassKey(value, name) { + if (value == null) { + throw new ERR_INVALID_ARG_TYPE(name, ['object', 'symbol'], value); + } + const type = typeof value; + if (type !== 'object' && type !== 'symbol') { + throw new ERR_INVALID_ARG_TYPE(name, ['object', 'symbol'], value); + } +} + // Can't delete when weakref count reaches 0 as it could increment again. // Only GC can be used as a valid time to clean up the channels map. class WeakRefMap extends SafeMap { @@ -84,16 +98,23 @@ function markActive(channel) { // eslint-disable-next-line no-use-before-define ObjectSetPrototypeOf(channel, ActiveChannel.prototype); channel._subscribers = []; + channel._bypassSubscribers = null; channel._stores = new SafeMap(); + channel._bypassStores = null; } function maybeMarkInactive(channel) { // When there are no more active subscribers or bound, restore to fast prototype. - if (!channel._subscribers.length && !channel._stores.size) { + if (!channel._subscribers.length && + !channel._stores.size && + !channel._bypassSubscribers?.length && + !channel._bypassStores?.size) { // eslint-disable-next-line no-use-before-define ObjectSetPrototypeOf(channel, Channel.prototype); channel._subscribers = undefined; channel._stores = undefined; + channel._bypassSubscribers = undefined; + channel._bypassStores = undefined; } } @@ -104,19 +125,33 @@ class RunStoresScope { // eslint-disable-next-line no-restricted-globals using stack = new DisposableStack(); - // Enter stores using withScope + // Normal stores - exactly as before, zero extra cost if (activeChannel._stores) { - const activeKeys = getSuppressionsStorage().getStore(); for (const entry of activeChannel._stores.entries()) { const store = entry[0]; - const { transform, subscriberId = null } = entry[1]; - - // Skip this bound store if it opted into suppression and its key - // is active in the current async context. - if (subscriberId !== null && activeKeys?.has(subscriberId)) { - continue; + const transform = entry[1]; + let newContext = data; + if (transform) { + try { + newContext = transform(data); + } catch (err) { + process.nextTick(() => { + triggerUncaughtException(err, false); + }); + continue; + } } + stack.use(store.withScope(newContext)); + } + } + // Bypass stores - only entered if bypass stores exist + if (activeChannel._bypassStores) { + const activeKeys = getSuppressionsStorage().getStore(); + for (const entry of activeChannel._bypassStores.entries()) { + const store = entry[0]; + const { transform, subscriberId } = entry[1]; + if (activeKeys?.has(subscriberId)) continue; let newContext = data; if (transform) { try { @@ -128,7 +163,6 @@ class RunStoresScope { continue; } } - stack.use(store.withScope(newContext)); } } @@ -149,73 +183,121 @@ class RunStoresScope { class ActiveChannel { subscribe(subscription, options = {}) { validateFunction(subscription, 'subscription'); - const subscriberId = options && options.subscriberId !== undefined ? options.subscriberId : null; - if (subscriberId !== null) { - const t = typeof subscriberId; - if (t === 'string' || t === 'number' || t === 'bigint' || t === 'boolean') { - throw new ERR_INVALID_ARG_TYPE('subscriberId', ['object', 'symbol', 'function'], subscriberId); + const subscriberId = options?.subscriberId; + + if (subscriberId !== undefined) { + validateBypassKey(subscriberId, 'subscriberId'); + // Bypass path - lazy separate array + if (this._bypassSubscribers === null) { + this._bypassSubscribers = []; } + this._bypassSubscribers = ArrayPrototypeSlice(this._bypassSubscribers); + ArrayPrototypePush(this._bypassSubscribers, { handler: subscription, subscriberId }); + } else { + // Normal path - plain function, zero extra cost + this._subscribers = ArrayPrototypeSlice(this._subscribers); + ArrayPrototypePush(this._subscribers, subscription); } - const handler = subscription; - this._subscribers = ArrayPrototypeSlice(this._subscribers); - ArrayPrototypePush(this._subscribers, { handler, subscriberId }); channels.incRef(this.name); if (this._index !== undefined) subscriberCounts[this._index]++; } unsubscribe(subscription) { - // Find subscriber entry by handler identity. + // Check normal subscribers first let index = -1; - for (let i = 0; i < (this._subscribers?.length || 0); i++) { - if (this._subscribers[i].handler === subscription) { + for (let i = 0; i < this._subscribers.length; i++) { + if (this._subscribers[i] === subscription) { index = i; break; } } - if (index === -1) return false; - const before = ArrayPrototypeSlice(this._subscribers, 0, index); - const after = ArrayPrototypeSlice(this._subscribers, index + 1); - this._subscribers = before; - ArrayPrototypePushApply(this._subscribers, after); + if (index !== -1) { + const before = ArrayPrototypeSlice(this._subscribers, 0, index); + const after = ArrayPrototypeSlice(this._subscribers, index + 1); + this._subscribers = before; + ArrayPrototypePushApply(this._subscribers, after); + channels.decRef(this.name); + if (this._index !== undefined) subscriberCounts[this._index]--; + maybeMarkInactive(this); + return true; + } - channels.decRef(this.name); - if (this._index !== undefined) subscriberCounts[this._index]--; - maybeMarkInactive(this); + // Check bypass subscribers + if (this._bypassSubscribers !== null) { + let bypassIndex = -1; + for (let i = 0; i < this._bypassSubscribers.length; i++) { + if (this._bypassSubscribers[i].handler === subscription) { + bypassIndex = i; + break; + } + } + if (bypassIndex !== -1) { + const before = ArrayPrototypeSlice(this._bypassSubscribers, 0, bypassIndex); + const after = ArrayPrototypeSlice(this._bypassSubscribers, bypassIndex + 1); + this._bypassSubscribers = before; + ArrayPrototypePushApply(this._bypassSubscribers, after); + if (this._bypassSubscribers.length === 0) { + this._bypassSubscribers = null; + } + channels.decRef(this.name); + if (this._index !== undefined) subscriberCounts[this._index]--; + maybeMarkInactive(this); + return true; + } + } - return true; + return false; } bindStore(store, transform, options = {}) { - const subscriberId = options && options.subscriberId !== undefined ? options.subscriberId : null; - if (subscriberId !== null) { - const t = typeof subscriberId; - if (t === 'string' || t === 'number' || t === 'bigint' || t === 'boolean') { - throw new ERR_INVALID_ARG_TYPE('subscriberId', ['object', 'symbol', 'function'], subscriberId); - } - } + const subscriberId = options?.subscriberId; - const replacing = this._stores.has(store); - if (!replacing) { - channels.incRef(this.name); - if (this._index !== undefined) subscriberCounts[this._index]++; + if (subscriberId !== undefined) { + validateBypassKey(subscriberId, 'subscriberId'); + // Bypass path - lazy separate SafeMap + if (this._bypassStores === null) { + this._bypassStores = new SafeMap(); + } + const replacing = this._bypassStores.has(store); + if (!replacing) { + channels.incRef(this.name); + if (this._index !== undefined) subscriberCounts[this._index]++; + } + this._bypassStores.set(store, { transform, subscriberId }); + } else { + // Normal path - plain transform, zero extra cost + const replacing = this._stores.has(store); + if (!replacing) { + channels.incRef(this.name); + if (this._index !== undefined) subscriberCounts[this._index]++; + } + this._stores.set(store, transform); } - this._stores.set(store, { transform, subscriberId }); } unbindStore(store) { - if (!this._stores.has(store)) { - return false; + if (this._stores.has(store)) { + this._stores.delete(store); + channels.decRef(this.name); + if (this._index !== undefined) subscriberCounts[this._index]--; + maybeMarkInactive(this); + return true; } - this._stores.delete(store); - - channels.decRef(this.name); - if (this._index !== undefined) subscriberCounts[this._index]--; - maybeMarkInactive(this); + if (this._bypassStores?.has(store)) { + this._bypassStores.delete(store); + if (this._bypassStores.size === 0) { + this._bypassStores = null; + } + channels.decRef(this.name); + if (this._index !== undefined) subscriberCounts[this._index]--; + maybeMarkInactive(this); + return true; + } - return true; + return false; } get hasSubscribers() { @@ -223,21 +305,34 @@ class ActiveChannel { } publish(data) { + // Normal path - no ALS lookup, plain function call, zero overhead const subscribers = this._subscribers; - const activeKeys = getSuppressionsStorage().getStore(); - for (let i = 0; i < (subscribers?.length || 0); i++) { + for (let i = 0; i < subscribers.length; i++) { try { - const { handler, subscriberId = null } = subscribers[i]; - if (subscriberId !== null && activeKeys?.has(subscriberId)) { - continue; - } - handler(data, this.name); + subscribers[i](data, this.name); } catch (err) { process.nextTick(() => { triggerUncaughtException(err, false); }); } } + + // Bypass path - only entered if bypass subscribers exist + if (this._bypassSubscribers !== null) { + const activeKeys = getSuppressionsStorage().getStore(); + const bypassSubscribers = this._bypassSubscribers; + for (let i = 0; i < bypassSubscribers.length; i++) { + try { + const { handler, subscriberId } = bypassSubscribers[i]; + if (activeKeys?.has(subscriberId)) continue; + handler(data, this.name); + } catch (err) { + process.nextTick(() => { + triggerUncaughtException(err, false); + }); + } + } + } } withStoreScope(data) { @@ -684,13 +779,7 @@ dc_binding.linkNativeChannel((name) => channel(name)); function suppressed(key, fn, thisArg, ...args) { validateFunction(fn, 'fn'); - if (key === null || key === undefined) { - throw new ERR_INVALID_ARG_TYPE('key', ['object', 'symbol', 'function'], key); - } - const t = typeof key; - if (t === 'string' || t === 'number' || t === 'bigint' || t === 'boolean') { - throw new ERR_INVALID_ARG_TYPE('key', ['object', 'symbol', 'function'], key); - } + validateBypassKey(key, 'key'); const currentSet = getSuppressionsStorage().getStore(); const next = currentSet ? new SafeSet(currentSet) : new SafeSet(); From 3fdcd8e3fd63643c64a4d0185130c11d3d48e0e7 Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Thu, 4 Jun 2026 03:29:29 +0530 Subject: [PATCH 16/39] test: update diagnostics_channel suppression tests for lazy storage Signed-off-by: Divyanshu Sharma --- .../test-diagnostics-channel-suppression.js | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/test/parallel/test-diagnostics-channel-suppression.js b/test/parallel/test-diagnostics-channel-suppression.js index cd3523848a81..04cfc42e3e43 100644 --- a/test/parallel/test-diagnostics-channel-suppression.js +++ b/test/parallel/test-diagnostics-channel-suppression.js @@ -160,17 +160,25 @@ const { AsyncLocalStorage } = require('async_hooks'); const ch = channel('test-suppression-store'); const als = new AsyncLocalStorage(); + // Bypass store transform - must NOT be called inside suppressed() + ch.bindStore(als, common.mustNotCall(), { subscriberId: key }); + + // Handler counts how many times it's called + let handlerCalls = 0; const handler = common.mustCall(() => { + handlerCalls++; assert.strictEqual(als.getStore(), undefined); }); - ch.subscribe(handler); - ch.bindStore(als, common.mustNotCall(), { subscriberId: key }); + // Use runStores so stores are actually entered suppressed(key, common.mustCall(() => { - ch.publish({}); + ch.runStores({}, () => { + // runStores already calls ch.publish() internally + }, null); })); + assert.strictEqual(handlerCalls, 1); ch.unsubscribe(handler); ch.unbindStore(als); } From 716a4eb0dabd3b35d620211b3755fe31968b1f65 Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Thu, 4 Jun 2026 14:24:11 +0530 Subject: [PATCH 17/39] test: fix lint errors in diagnostics_channel suppression tests Signed-off-by: Divyanshu Sharma --- .../test-diagnostics-channel-suppression.js | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/test/parallel/test-diagnostics-channel-suppression.js b/test/parallel/test-diagnostics-channel-suppression.js index 04cfc42e3e43..2724ded79700 100644 --- a/test/parallel/test-diagnostics-channel-suppression.js +++ b/test/parallel/test-diagnostics-channel-suppression.js @@ -159,28 +159,30 @@ const { AsyncLocalStorage } = require('async_hooks'); const key = Symbol('store'); const ch = channel('test-suppression-store'); const als = new AsyncLocalStorage(); + const normalAls = new AsyncLocalStorage(); - // Bypass store transform - must NOT be called inside suppressed() + // Normal store - no subscriberId, must always be entered + ch.bindStore(normalAls, common.mustCall((data) => ({ value: data.value }))); + + // Bypass store - must NOT be entered inside suppressed() ch.bindStore(als, common.mustNotCall(), { subscriberId: key }); - // Handler counts how many times it's called - let handlerCalls = 0; + // Handler verifies: + // - normal store WAS entered (normalAls has value) + // - bypass store was NOT entered (als is undefined) const handler = common.mustCall(() => { - handlerCalls++; + assert.strictEqual(normalAls.getStore()?.value, 42); assert.strictEqual(als.getStore(), undefined); }); ch.subscribe(handler); - // Use runStores so stores are actually entered suppressed(key, common.mustCall(() => { - ch.runStores({}, () => { - // runStores already calls ch.publish() internally - }, null); + ch.runStores({ value: 42 }, common.mustCall()); })); - assert.strictEqual(handlerCalls, 1); ch.unsubscribe(handler); ch.unbindStore(als); + ch.unbindStore(normalAls); } // Test 9: Wrong type for subscriberId throws ERR_INVALID_ARG_TYPE From 993bc0dd92a16e01bd5a929648b0372dcd7dbffc Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Tue, 9 Jun 2026 03:52:15 +0530 Subject: [PATCH 18/39] lib,test: rename suppressed/subscriberId to bypass/bypassId in diagnostics_channel Signed-off-by: Divyanshu Sharma --- lib/diagnostics_channel.js | 62 ++++++------- ....js => test-diagnostics-channel-bypass.js} | 93 +++++++++---------- 2 files changed, 77 insertions(+), 78 deletions(-) rename test/parallel/{test-diagnostics-channel-suppression.js => test-diagnostics-channel-bypass.js} (58%) diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index d0911148bcab..9067e6164b12 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -36,18 +36,18 @@ const { subscribers: subscriberCounts } = dc_binding; const { WeakReference } = require('internal/util'); const { isPromise } = require('internal/util/types'); -let suppressionStorage; +let bypassStorage; -function getSuppressionsStorage() { - if (suppressionStorage === undefined) { +function getBypassStorage() { + if (bypassStorage === undefined) { const { AsyncLocalStorage } = require('async_hooks'); - suppressionStorage = new AsyncLocalStorage(); + bypassStorage = new AsyncLocalStorage(); } - return suppressionStorage; + return bypassStorage; } function withSuppressionsContext(set, fn, thisArg, args) { - return getSuppressionsStorage().run( + return getBypassStorage().run( set, () => ReflectApply(fn, thisArg, args), ); @@ -125,7 +125,7 @@ class RunStoresScope { // eslint-disable-next-line no-restricted-globals using stack = new DisposableStack(); - // Normal stores - exactly as before, zero extra cost + // Normal stores, unchanged from before. if (activeChannel._stores) { for (const entry of activeChannel._stores.entries()) { const store = entry[0]; @@ -145,13 +145,13 @@ class RunStoresScope { } } - // Bypass stores - only entered if bypass stores exist + // Bypass stores, only checked when bypass stores exist. if (activeChannel._bypassStores) { - const activeKeys = getSuppressionsStorage().getStore(); + const activeKeys = getBypassStorage().getStore(); for (const entry of activeChannel._bypassStores.entries()) { const store = entry[0]; - const { transform, subscriberId } = entry[1]; - if (activeKeys?.has(subscriberId)) continue; + const { transform, bypassId } = entry[1]; + if (activeKeys?.has(bypassId)) continue; let newContext = data; if (transform) { try { @@ -183,18 +183,18 @@ class RunStoresScope { class ActiveChannel { subscribe(subscription, options = {}) { validateFunction(subscription, 'subscription'); - const subscriberId = options?.subscriberId; + const bypassId = options?.bypassId; - if (subscriberId !== undefined) { - validateBypassKey(subscriberId, 'subscriberId'); - // Bypass path - lazy separate array + if (bypassId !== undefined) { + validateBypassKey(bypassId, 'bypassId'); + // Bypass path, lazy separate array only allocated when needed. if (this._bypassSubscribers === null) { this._bypassSubscribers = []; } this._bypassSubscribers = ArrayPrototypeSlice(this._bypassSubscribers); - ArrayPrototypePush(this._bypassSubscribers, { handler: subscription, subscriberId }); + ArrayPrototypePush(this._bypassSubscribers, { handler: subscription, bypassId }); } else { - // Normal path - plain function, zero extra cost + // Normal path, plain function call with no extra overhead. this._subscribers = ArrayPrototypeSlice(this._subscribers); ArrayPrototypePush(this._subscribers, subscription); } @@ -252,11 +252,11 @@ class ActiveChannel { } bindStore(store, transform, options = {}) { - const subscriberId = options?.subscriberId; + const bypassId = options?.bypassId; - if (subscriberId !== undefined) { - validateBypassKey(subscriberId, 'subscriberId'); - // Bypass path - lazy separate SafeMap + if (bypassId !== undefined) { + validateBypassKey(bypassId, 'bypassId'); + // Bypass path, lazy separate SafeMap only allocated when needed. if (this._bypassStores === null) { this._bypassStores = new SafeMap(); } @@ -265,9 +265,9 @@ class ActiveChannel { channels.incRef(this.name); if (this._index !== undefined) subscriberCounts[this._index]++; } - this._bypassStores.set(store, { transform, subscriberId }); + this._bypassStores.set(store, { transform, bypassId }); } else { - // Normal path - plain transform, zero extra cost + // Normal path, plain transform with no extra overhead. const replacing = this._stores.has(store); if (!replacing) { channels.incRef(this.name); @@ -305,7 +305,7 @@ class ActiveChannel { } publish(data) { - // Normal path - no ALS lookup, plain function call, zero overhead + // Normal path, no ALS lookup, plain function call, zero overhead. const subscribers = this._subscribers; for (let i = 0; i < subscribers.length; i++) { try { @@ -317,14 +317,14 @@ class ActiveChannel { } } - // Bypass path - only entered if bypass subscribers exist + // Bypass path, only entered if bypass subscribers exist. if (this._bypassSubscribers !== null) { - const activeKeys = getSuppressionsStorage().getStore(); + const activeKeys = getBypassStorage().getStore(); const bypassSubscribers = this._bypassSubscribers; for (let i = 0; i < bypassSubscribers.length; i++) { try { - const { handler, subscriberId } = bypassSubscribers[i]; - if (activeKeys?.has(subscriberId)) continue; + const { handler, bypassId } = bypassSubscribers[i]; + if (activeKeys?.has(bypassId)) continue; handler(data, this.name); } catch (err) { process.nextTick(() => { @@ -776,12 +776,12 @@ function tracingChannel(nameOrChannels) { dc_binding.linkNativeChannel((name) => channel(name)); -function suppressed(key, fn, thisArg, ...args) { +function bypass(key, fn, thisArg, ...args) { validateFunction(fn, 'fn'); validateBypassKey(key, 'key'); - const currentSet = getSuppressionsStorage().getStore(); + const currentSet = getBypassStorage().getStore(); const next = currentSet ? new SafeSet(currentSet) : new SafeSet(); next.add(key); return withSuppressionsContext(next, fn, thisArg, args); @@ -791,7 +791,7 @@ module.exports = { channel, hasSubscribers, subscribe, - suppressed, + bypass, tracingChannel, unsubscribe, boundedChannel, diff --git a/test/parallel/test-diagnostics-channel-suppression.js b/test/parallel/test-diagnostics-channel-bypass.js similarity index 58% rename from test/parallel/test-diagnostics-channel-suppression.js rename to test/parallel/test-diagnostics-channel-bypass.js index 2724ded79700..1f05c9f419e1 100644 --- a/test/parallel/test-diagnostics-channel-suppression.js +++ b/test/parallel/test-diagnostics-channel-bypass.js @@ -2,33 +2,33 @@ const common = require('../common'); const assert = require('assert'); -const { channel, suppressed } = require('node:diagnostics_channel'); +const { channel, bypass } = require('node:diagnostics_channel'); const { AsyncLocalStorage } = require('async_hooks'); -// Test 1: Basic suppression - subscriber with subscriberId is skipped inside suppressed() +// Test 1: Basic bypass - subscriber with bypassId is skipped inside bypass() { const key = Symbol('tracer'); - const ch = channel('test-suppression-basic'); + const ch = channel('test-bypass-basic'); const handler = common.mustNotCall(); - ch.subscribe(handler, { subscriberId: key }); + ch.subscribe(handler, { bypassId: key }); - suppressed(key, common.mustCall(() => { + bypass(key, common.mustCall(() => { ch.publish({}); })); ch.unsubscribe(handler); } -// Test 2: Non-opted subscriber fires even inside suppressed() scope +// Test 2: Non-opted subscriber fires even inside bypass() scope { const key = Symbol('tracer2'); - const ch = channel('test-suppression-nonopted'); + const ch = channel('test-bypass-nonopted'); const optedHandler = common.mustNotCall(); const regularHandler = common.mustCall(); - ch.subscribe(optedHandler, { subscriberId: key }); - ch.subscribe(regularHandler); // no suppression + ch.subscribe(optedHandler, { bypassId: key }); + ch.subscribe(regularHandler); // no bypass - suppressed(key, common.mustCall(() => { + bypass(key, common.mustCall(() => { ch.publish({}); })); @@ -36,26 +36,26 @@ const { AsyncLocalStorage } = require('async_hooks'); ch.unsubscribe(regularHandler); } -// Test 3: Two APMs with different keys don't suppress each other +// Test 3: Two APMs with different keys don't bypass each other { const k1 = Symbol('k1'); const k2 = Symbol('k2'); - const ch = channel('test-suppression-two-keys'); + const ch = channel('test-bypass-two-keys'); let h1Calls = 0; let h2Calls = 0; const h1 = common.mustCall(() => { h1Calls++; }, 1); const h2 = common.mustCall(() => { h2Calls++; }, 1); - ch.subscribe(h1, { subscriberId: k1 }); - ch.subscribe(h2, { subscriberId: k2 }); + ch.subscribe(h1, { bypassId: k1 }); + ch.subscribe(h2, { bypassId: k2 }); - suppressed(k1, common.mustCall(() => { + bypass(k1, common.mustCall(() => { ch.publish({}); })); assert.strictEqual(h1Calls, 0); assert.strictEqual(h2Calls, 1); - suppressed(k2, common.mustCall(() => { + bypass(k2, common.mustCall(() => { ch.publish({}); })); @@ -66,23 +66,23 @@ const { AsyncLocalStorage } = require('async_hooks'); ch.unsubscribe(h2); } -// Test 4: Nested suppressed() calls (same key, different keys) +// Test 4: Nested bypass() calls (same key, different keys) { const k1 = Symbol('nested1'); const k2 = Symbol('nested2'); - const ch = channel('test-suppression-nested'); + const ch = channel('test-bypass-nested'); const h1 = common.mustNotCall(); let h2Calls = 0; const h2 = common.mustCall(() => { h2Calls++; }, 2); - ch.subscribe(h1, { subscriberId: k1 }); - ch.subscribe(h2, { subscriberId: k2 }); + ch.subscribe(h1, { bypassId: k1 }); + ch.subscribe(h2, { bypassId: k2 }); - suppressed(k1, common.mustCall(() => { + bypass(k1, common.mustCall(() => { // Inside k1, h1 skipped, h2 runs ch.publish({}); assert.strictEqual(h2Calls, 1); - suppressed(k2, common.mustCall(() => { + bypass(k2, common.mustCall(() => { // Inside both, both skipped ch.publish({}); assert.strictEqual(h2Calls, 1); @@ -97,15 +97,15 @@ const { AsyncLocalStorage } = require('async_hooks'); ch.unsubscribe(h2); } -// Test 5: suppressed() across a Promise boundary +// Test 5: bypass() across a Promise boundary { const key = Symbol('promise'); - const ch = channel('test-suppression-promise'); + const ch = channel('test-bypass-promise'); const handler = common.mustNotCall(); - ch.subscribe(handler, { subscriberId: key }); + ch.subscribe(handler, { bypassId: key }); const done = common.mustCall(); - suppressed(key, common.mustCall(async () => { + bypass(key, common.mustCall(async () => { await Promise.resolve(); ch.publish({}); })).then(common.mustCall(() => { @@ -114,15 +114,15 @@ const { AsyncLocalStorage } = require('async_hooks'); })); } -// Test 6: suppressed() across setImmediate and queueMicrotask +// Test 6: bypass() across setImmediate and queueMicrotask { const key = Symbol('timers'); - const ch = channel('test-suppression-timers'); + const ch = channel('test-bypass-timers'); const handler = common.mustNotCall(); - ch.subscribe(handler, { subscriberId: key }); + ch.subscribe(handler, { bypassId: key }); const done = common.mustCall(); - suppressed(key, common.mustCall(async () => { + bypass(key, common.mustCall(async () => { await new Promise((resolve) => { setImmediate(common.mustCall(() => { ch.publish({}); @@ -139,33 +139,32 @@ const { AsyncLocalStorage } = require('async_hooks'); })); } -// Test 7: unsubscribe() works correctly after using subscriberId +// Test 7: unsubscribe() works correctly after using bypassId { const key = Symbol('unsub'); - const ch = channel('test-suppression-unsubscribe'); + const ch = channel('test-bypass-unsubscribe'); const handler = common.mustNotCall(); - ch.subscribe(handler, { subscriberId: key }); + ch.subscribe(handler, { bypassId: key }); ch.unsubscribe(handler); // Should not throw and should not be called - suppressed(key, common.mustCall(() => { + bypass(key, common.mustCall(() => { ch.publish({}); })); - } -// Test 8: bindStore with subscriberId is skipped inside suppressed() +// Test 8: bindStore with bypassId is skipped inside bypass() { const key = Symbol('store'); - const ch = channel('test-suppression-store'); + const ch = channel('test-bypass-store'); const als = new AsyncLocalStorage(); const normalAls = new AsyncLocalStorage(); - // Normal store - no subscriberId, must always be entered + // Normal store, no bypassId, must always be entered. ch.bindStore(normalAls, common.mustCall((data) => ({ value: data.value }))); - // Bypass store - must NOT be entered inside suppressed() - ch.bindStore(als, common.mustNotCall(), { subscriberId: key }); + // Bypass store, must NOT be entered inside bypass(). + ch.bindStore(als, common.mustNotCall(), { bypassId: key }); // Handler verifies: // - normal store WAS entered (normalAls has value) @@ -176,7 +175,7 @@ const { AsyncLocalStorage } = require('async_hooks'); }); ch.subscribe(handler); - suppressed(key, common.mustCall(() => { + bypass(key, common.mustCall(() => { ch.runStores({ value: 42 }, common.mustCall()); })); @@ -185,24 +184,24 @@ const { AsyncLocalStorage } = require('async_hooks'); ch.unbindStore(normalAls); } -// Test 9: Wrong type for subscriberId throws ERR_INVALID_ARG_TYPE +// Test 9: Wrong type for bypassId throws ERR_INVALID_ARG_TYPE { - const ch = channel('test-suppression-wrong-type'); + const ch = channel('test-bypass-wrong-type'); const bad = 'not-allowed'; - assert.throws(() => ch.subscribe(() => {}, { subscriberId: bad }), { + assert.throws(() => ch.subscribe(() => {}, { bypassId: bad }), { name: 'TypeError' }); const als = new AsyncLocalStorage(); - assert.throws(() => ch.bindStore(als, (d) => d, { subscriberId: bad }), { + assert.throws(() => ch.bindStore(als, (d) => d, { bypassId: bad }), { name: 'TypeError' }); } -// Test 10: suppressed() return value passes through fn's return value +// Test 10: bypass() return value passes through fn's return value { const key = Symbol('return'); const receiver = { value: 41 }; - const result = suppressed(key, common.mustCall(function(a, b) { + const result = bypass(key, common.mustCall(function(a, b) { assert.strictEqual(this, receiver); assert.strictEqual(a, 'a'); assert.strictEqual(b, 'b'); From 24a87f4c862125bcb280594325087c572442b91b Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Tue, 9 Jun 2026 04:21:28 +0530 Subject: [PATCH 19/39] lib: rename withSuppressionsContext to withBypassContext in diagnostics_channel Signed-off-by: Divyanshu Sharma --- lib/diagnostics_channel.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index 9067e6164b12..41598d5b1767 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -46,7 +46,7 @@ function getBypassStorage() { return bypassStorage; } -function withSuppressionsContext(set, fn, thisArg, args) { +function withBypassContext(set, fn, thisArg, args) { return getBypassStorage().run( set, () => ReflectApply(fn, thisArg, args), @@ -784,7 +784,7 @@ function bypass(key, fn, thisArg, ...args) { const currentSet = getBypassStorage().getStore(); const next = currentSet ? new SafeSet(currentSet) : new SafeSet(); next.add(key); - return withSuppressionsContext(next, fn, thisArg, args); + return withBypassContext(next, fn, thisArg, args); } module.exports = { From 614bc7e86cd3c18a5463e98c78b71bb4cffe28a3 Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Sun, 14 Jun 2026 13:19:11 +0530 Subject: [PATCH 20/39] lib,test: propagate bypass context through TracingChannel trace methods Signed-off-by: Divyanshu Sharma --- lib/diagnostics_channel.js | 23 ++++- .../test-diagnostics-channel-bypass.js | 96 +++++++++++++++++++ 2 files changed, 116 insertions(+), 3 deletions(-) diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index 41598d5b1767..20ad0e5c26fe 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -552,6 +552,7 @@ function boundedChannel(nameOrChannels) { class TracingChannel { #callWindow; #continuationWindow; + #bypassIds = null; constructor(nameOrChannels) { // Create a BoundedChannel for start/end (call window) @@ -601,7 +602,23 @@ class TracingChannel { this.error?.hasSubscribers; } + #allBypassed() { + const activeKeys = bypassStorage?.getStore(); + if (!activeKeys) return false; + const ids = this.#bypassIds; + if (ids === null) return false; + for (const id of ids) { + if (activeKeys.has(id)) return true; + } + return false; + } + subscribe(handlers, options) { + if (options?.bypassId !== undefined) { + if (this.#bypassIds === null) this.#bypassIds = new SafeSet(); + this.#bypassIds.add(options.bypassId); + } + // Subscribe to call window (start/end) if (handlers.start || handlers.end) { this.#callWindow.subscribe({ @@ -658,7 +675,7 @@ class TracingChannel { } traceSync(fn, context = {}, thisArg, ...args) { - if (!this.hasSubscribers) { + if (!this.hasSubscribers || this.#allBypassed()) { return ReflectApply(fn, thisArg, args); } @@ -678,7 +695,7 @@ class TracingChannel { } tracePromise(fn, context = {}, thisArg, ...args) { - if (!this.hasSubscribers) { + if (!this.hasSubscribers || this.#allBypassed()) { const result = ReflectApply(fn, thisArg, args); if (typeof result?.then !== 'function') { emitNonThenableWarning(fn); @@ -733,7 +750,7 @@ class TracingChannel { } traceCallback(fn, position = -1, context = {}, thisArg, ...args) { - if (!this.hasSubscribers) { + if (!this.hasSubscribers || this.#allBypassed()) { return ReflectApply(fn, thisArg, args); } diff --git a/test/parallel/test-diagnostics-channel-bypass.js b/test/parallel/test-diagnostics-channel-bypass.js index 1f05c9f419e1..d3ddd3d4def2 100644 --- a/test/parallel/test-diagnostics-channel-bypass.js +++ b/test/parallel/test-diagnostics-channel-bypass.js @@ -209,3 +209,99 @@ const { AsyncLocalStorage } = require('async_hooks'); }), receiver, 'a', 'b'); assert.strictEqual(result, 42); } + +// Test 11: TracingChannel traceSync respects bypass +{ + const { tracingChannel } = require('node:diagnostics_channel'); + const key = Symbol('tracing-sync'); + const tc = tracingChannel('test-bypass-tracing-sync'); + const startHandler = common.mustNotCall(); + const endHandler = common.mustNotCall(); + const errorHandler = common.mustNotCall(); + + tc.subscribe({ + start: startHandler, + end: endHandler, + error: errorHandler, + }, { bypassId: key }); + + bypass(key, common.mustCall(() => { + tc.traceSync(common.mustCall(), {}); + })); + + tc.unsubscribe({ + start: startHandler, + end: endHandler, + error: errorHandler, + }); +} + +// Test 12: TracingChannel tracePromise respects bypass +{ + const { tracingChannel } = require('node:diagnostics_channel'); + const key = Symbol('tracing-promise'); + const tc = tracingChannel('test-bypass-tracing-promise'); + const startHandler = common.mustNotCall(); + const endHandler = common.mustNotCall(); + const asyncStartHandler = common.mustNotCall(); + const asyncEndHandler = common.mustNotCall(); + const done = common.mustCall(); + + tc.subscribe({ + start: startHandler, + end: endHandler, + asyncStart: asyncStartHandler, + asyncEnd: asyncEndHandler, + }, { bypassId: key }); + + bypass(key, common.mustCall(() => { + return tc.tracePromise(common.mustCall(() => Promise.resolve(42)), {}); + })).then(common.mustCall(() => { + tc.unsubscribe({ + start: startHandler, + end: endHandler, + asyncStart: asyncStartHandler, + asyncEnd: asyncEndHandler, + }); + done(); + })); +} + +// Test 13: TracingChannel traceCallback respects bypass +{ + const { tracingChannel } = require('node:diagnostics_channel'); + const key = Symbol('tracing-callback'); + const tc = tracingChannel('test-bypass-tracing-callback'); + const startHandler = common.mustNotCall(); + const endHandler = common.mustNotCall(); + const asyncStartHandler = common.mustNotCall(); + const asyncEndHandler = common.mustNotCall(); + const done = common.mustCall(); + + tc.subscribe({ + start: startHandler, + end: endHandler, + asyncStart: asyncStartHandler, + asyncEnd: asyncEndHandler, + }, { bypassId: key }); + + bypass(key, common.mustCall(() => { + tc.traceCallback( + common.mustCall((cb) => setImmediate(cb, null, 'result')), + -1, + {}, + null, + common.mustCall((err, res) => { + assert.strictEqual(err, null); + assert.strictEqual(res, 'result'); + tc.unsubscribe({ + start: startHandler, + end: endHandler, + asyncStart: asyncStartHandler, + asyncEnd: asyncEndHandler, + }); + done(); + }) + ); + })); +} From fcef8705a0f5431f80b99aff120bf562c796cc57 Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Sun, 14 Jun 2026 13:25:44 +0530 Subject: [PATCH 21/39] lib: remove unnecessary TracingChannel bypass tracking Signed-off-by: Divyanshu Sharma --- lib/diagnostics_channel.js | 23 +++-------------------- 1 file changed, 3 insertions(+), 20 deletions(-) diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index 20ad0e5c26fe..41598d5b1767 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -552,7 +552,6 @@ function boundedChannel(nameOrChannels) { class TracingChannel { #callWindow; #continuationWindow; - #bypassIds = null; constructor(nameOrChannels) { // Create a BoundedChannel for start/end (call window) @@ -602,23 +601,7 @@ class TracingChannel { this.error?.hasSubscribers; } - #allBypassed() { - const activeKeys = bypassStorage?.getStore(); - if (!activeKeys) return false; - const ids = this.#bypassIds; - if (ids === null) return false; - for (const id of ids) { - if (activeKeys.has(id)) return true; - } - return false; - } - subscribe(handlers, options) { - if (options?.bypassId !== undefined) { - if (this.#bypassIds === null) this.#bypassIds = new SafeSet(); - this.#bypassIds.add(options.bypassId); - } - // Subscribe to call window (start/end) if (handlers.start || handlers.end) { this.#callWindow.subscribe({ @@ -675,7 +658,7 @@ class TracingChannel { } traceSync(fn, context = {}, thisArg, ...args) { - if (!this.hasSubscribers || this.#allBypassed()) { + if (!this.hasSubscribers) { return ReflectApply(fn, thisArg, args); } @@ -695,7 +678,7 @@ class TracingChannel { } tracePromise(fn, context = {}, thisArg, ...args) { - if (!this.hasSubscribers || this.#allBypassed()) { + if (!this.hasSubscribers) { const result = ReflectApply(fn, thisArg, args); if (typeof result?.then !== 'function') { emitNonThenableWarning(fn); @@ -750,7 +733,7 @@ class TracingChannel { } traceCallback(fn, position = -1, context = {}, thisArg, ...args) { - if (!this.hasSubscribers || this.#allBypassed()) { + if (!this.hasSubscribers) { return ReflectApply(fn, thisArg, args); } From ec9316b25afe3866ce70127efacd2e9f25fbf3f1 Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Sun, 14 Jun 2026 13:46:06 +0530 Subject: [PATCH 22/39] lib: use kEmptyObject for options defaults in diagnostics_channel Signed-off-by: Divyanshu Sharma --- lib/diagnostics_channel.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index 41598d5b1767..2f1adf8c6109 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -33,7 +33,7 @@ const { triggerUncaughtException } = internalBinding('errors'); const dc_binding = internalBinding('diagnostics_channel'); const { subscribers: subscriberCounts } = dc_binding; -const { WeakReference } = require('internal/util'); +const { WeakReference, kEmptyObject } = require('internal/util'); const { isPromise } = require('internal/util/types'); let bypassStorage; @@ -181,7 +181,7 @@ class RunStoresScope { // TODO(qard): should there be a C++ channel interface? class ActiveChannel { - subscribe(subscription, options = {}) { + subscribe(subscription, options = kEmptyObject) { validateFunction(subscription, 'subscription'); const bypassId = options?.bypassId; @@ -251,7 +251,7 @@ class ActiveChannel { return false; } - bindStore(store, transform, options = {}) { + bindStore(store, transform, options = kEmptyObject) { const bypassId = options?.bypassId; if (bypassId !== undefined) { From 365ab7b5d6ad82940ab6557594e710f38f14a25d Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Thu, 2 Jul 2026 23:50:20 +0530 Subject: [PATCH 23/39] diagnostics_channel: add bypass subscriber/store support --- lib/diagnostics_channel.js | 56 ++++++++++++++++---------------------- 1 file changed, 24 insertions(+), 32 deletions(-) diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index e383287f46fc..49d0dbfb69c6 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -2,6 +2,7 @@ const { ArrayPrototypeAt, + ArrayPrototypeIndexOf, ArrayPrototypePush, ArrayPrototypePushApply, ArrayPrototypeSlice, @@ -103,6 +104,19 @@ function markActive(channel) { channel._bypassStores = null; } +function incRefIfNew(channel, isNew) { + if (isNew) { + channels.incRef(channel.name); + subscriberCounts[channel._index]++; + } +} + +function decRefAndMaybeInactive(channel) { + channels.decRef(channel.name); + subscriberCounts[channel._index]--; + maybeMarkInactive(channel); +} + function maybeMarkInactive(channel) { // When there are no more active subscribers or bound, restore to fast prototype. if (!channel._subscribers.length && @@ -199,28 +213,17 @@ class ActiveChannel { ArrayPrototypePush(this._subscribers, subscription); } - channels.incRef(this.name); - if (this._index !== undefined) subscriberCounts[this._index]++; + incRefIfNew(this, true); } unsubscribe(subscription) { - // Check normal subscribers first - let index = -1; - for (let i = 0; i < this._subscribers.length; i++) { - if (this._subscribers[i] === subscription) { - index = i; - break; - } - } - + const index = ArrayPrototypeIndexOf(this._subscribers, subscription); if (index !== -1) { const before = ArrayPrototypeSlice(this._subscribers, 0, index); const after = ArrayPrototypeSlice(this._subscribers, index + 1); this._subscribers = before; ArrayPrototypePushApply(this._subscribers, after); - channels.decRef(this.name); - if (this._index !== undefined) subscriberCounts[this._index]--; - maybeMarkInactive(this); + decRefAndMaybeInactive(this); return true; } @@ -241,9 +244,7 @@ class ActiveChannel { if (this._bypassSubscribers.length === 0) { this._bypassSubscribers = null; } - channels.decRef(this.name); - if (this._index !== undefined) subscriberCounts[this._index]--; - maybeMarkInactive(this); + decRefAndMaybeInactive(this); return true; } } @@ -261,18 +262,13 @@ class ActiveChannel { this._bypassStores = new SafeMap(); } const replacing = this._bypassStores.has(store); - if (!replacing) { - channels.incRef(this.name); - if (this._index !== undefined) subscriberCounts[this._index]++; - } + incRefIfNew(this, !replacing); this._bypassStores.set(store, { transform, bypassId }); } else { - // Normal path, plain transform with no extra overhead. + // No bypassId provided: store as a plain transform function, + // matching the pre-bypass-feature behavior exactly. const replacing = this._stores.has(store); - if (!replacing) { - channels.incRef(this.name); - if (this._index !== undefined) subscriberCounts[this._index]++; - } + incRefIfNew(this, !replacing); this._stores.set(store, transform); } } @@ -280,9 +276,7 @@ class ActiveChannel { unbindStore(store) { if (this._stores.has(store)) { this._stores.delete(store); - channels.decRef(this.name); - if (this._index !== undefined) subscriberCounts[this._index]--; - maybeMarkInactive(this); + decRefAndMaybeInactive(this); return true; } @@ -291,9 +285,7 @@ class ActiveChannel { if (this._bypassStores.size === 0) { this._bypassStores = null; } - channels.decRef(this.name); - if (this._index !== undefined) subscriberCounts[this._index]--; - maybeMarkInactive(this); + decRefAndMaybeInactive(this); return true; } From 149f073884206b7691f719fd9d0d83e7e7ac1c89 Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Mon, 6 Jul 2026 21:09:03 +0530 Subject: [PATCH 24/39] doc: add diagnostics_channel bypass API documentation Signed-off-by: Divyanshu Sharma --- doc/api/diagnostics_channel.md | 311 +++++++++++++++++++++++++++++++-- 1 file changed, 299 insertions(+), 12 deletions(-) diff --git a/doc/api/diagnostics_channel.md b/doc/api/diagnostics_channel.md index c21e83e11457..741c2b42321b 100644 --- a/doc/api/diagnostics_channel.md +++ b/doc/api/diagnostics_channel.md @@ -72,6 +72,13 @@ if (channel.hasSubscribers) { // Unsubscribe from the channel diagnostics_channel.unsubscribe('my-channel', onMessage); + +// Use bypass() to skip opted-in subscribers during internal calls +const kMyTool = Symbol('my-tool'); +diagnostics_channel.channel('my-channel').subscribe(onMessage, { bypassId: kMyTool }); +diagnostics_channel.bypass(kMyTool, () => { + // onMessage will NOT be called for publishes inside here +}); ``` ```cjs @@ -97,6 +104,13 @@ if (channel.hasSubscribers) { // Unsubscribe from the channel diagnostics_channel.unsubscribe('my-channel', onMessage); + +// Use bypass() to skip opted-in subscribers during internal calls +const kMyTool = Symbol('my-tool'); +diagnostics_channel.channel('my-channel').subscribe(onMessage, { bypassId: kMyTool }); +diagnostics_channel.bypass(kMyTool, () => { + // onMessage will NOT be called for publishes inside here +}); ``` #### `diagnostics_channel.hasSubscribers(name)` @@ -231,6 +245,151 @@ diagnostics_channel.subscribe('my-channel', onMessage); diagnostics_channel.unsubscribe('my-channel', onMessage); ``` +#### `diagnostics_channel.bypass(key, fn[, thisArg[, ...args]])` + + + +* `key` {symbol|Object} The bypass identity token. Must match the + `bypassId` used when subscribing. +* `fn` {Function} The function to run with bypass active. +* `thisArg` {any} The receiver to use for the function call. +* `...args` {any} Optional arguments to pass to the function. +* Returns: {any} The return value of `fn`. + +Runs `fn` with the given `key` active in the current async context. +Any channel subscribers or bound stores that were registered with +`{ bypassId: key }` will be skipped for the duration of `fn` and +any async continuations (Promises, timers, microtasks) within it. + +This is designed for observability tooling (APM agents, tracers) +that need to prevent recursive instrumentation when their own +internal code calls into an instrumented library. + +```mjs +import diagnostics_channel from 'node:diagnostics_channel'; +import { request } from 'node:http'; + +const { channel, bypass } = diagnostics_channel; + +// A unique token identifying this APM tool +const kMyTracer = Symbol('my-tracer'); + +// Subscribe to HTTP requests, but opt into bypass +channel('http.client.request').subscribe((message) => { + console.log('HTTP request:', message.url); +}, { bypassId: kMyTracer }); + +// When exporting traces internally, use bypass() so the +// above subscriber is NOT triggered for this internal request +function exportTraces(data) { + bypass(kMyTracer, () => { + // This HTTP request will NOT trigger the subscriber above + const req = request('https://my-apm-backend.example.com/traces', { + method: 'POST', + }); + req.end(); + }); +} +``` + +```cjs +const diagnostics_channel = require('node:diagnostics_channel'); +const { request } = require('node:http'); + +const { channel, bypass } = diagnostics_channel; + +// A unique token identifying this APM tool +const kMyTracer = Symbol('my-tracer'); + +// Subscribe to HTTP requests, but opt into bypass +channel('http.client.request').subscribe((message) => { + console.log('HTTP request:', message.url); +}, { bypassId: kMyTracer }); + +// When exporting traces internally, use bypass() so the +// above subscriber is NOT triggered for this internal request +function exportTraces(data) { + bypass(kMyTracer, () => { + // This HTTP request will NOT trigger the subscriber above + const req = request('https://my-apm-backend.example.com/traces', { + method: 'POST', + }); + req.end(); + }); +} +``` + +Without `bypass()`, the internal `exportTraces()` HTTP request +would trigger the subscriber, which would try to export a trace +of the export, causing infinite recursion. + +The bypass context propagates across async boundaries: + +```mjs +// bypass() works across Promise boundaries +await bypass(kMyTracer, async () => { + await someAsyncOperation(); // still bypassed + channel('http.client.request').publish({}); // subscriber skipped +}); + +// And across timers +bypass(kMyTracer, () => { + setImmediate(() => { + // Still bypassed here + channel('http.client.request').publish({}); + }); +}); +``` + +```cjs +(async () => { + await bypass(kMyTracer, async () => { + await someAsyncOperation(); + channel('http.client.request').publish({}); + }); + bypass(kMyTracer, () => { + setImmediate(() => { + channel('http.client.request').publish({}); + }); + }); +})(); +``` + +Multiple tools can each use their own `bypassId` without +interfering with each other: + +```mjs +const kToolA = Symbol('tool-a'); +const kToolB = Symbol('tool-b'); + +channel('http.client.request').subscribe(handlerA, { bypassId: kToolA }); +channel('http.client.request').subscribe(handlerB, { bypassId: kToolB }); + +// Only handlerA is skipped, handlerB still fires +bypass(kToolA, () => { + channel('http.client.request').publish({}); +}); +``` + +```cjs +const diagnostics_channel = require('node:diagnostics_channel'); + +const { channel, bypass } = diagnostics_channel; + +const kToolA = Symbol('tool-a'); +const kToolB = Symbol('tool-b'); + +channel('http.client.request').subscribe(handlerA, { bypassId: kToolA }); +channel('http.client.request').subscribe(handlerB, { bypassId: kToolB }); + +// Only handlerA is skipped, handlerB still fires +bypass(kToolA, () => { + channel('http.client.request').publish({}); +}); +``` + #### `diagnostics_channel.tracingChannel(nameOrChannels)` > Stability: 1 - Experimental * `store` {AsyncLocalStorage} The store to which to bind the context data * `transform` {Function} Transform context data before setting the store context +* `options` {Object} + * `bypassId` {symbol|Object} An optional identity token. When + provided, this bound store will be skipped while + [`diagnostics_channel.bypass()`][] is active with the same key. When [`channel.runStores(context, ...)`][] is called, the given context data will be applied to any store bound to the channel. If the store has already been @@ -565,6 +767,38 @@ channel.bindStore(store, (data) => { }); ``` +To opt this bound store into bypass behavior: + +```mjs +import diagnostics_channel from 'node:diagnostics_channel'; +import { AsyncLocalStorage } from 'node:async_hooks'; + +const { channel, bypass } = diagnostics_channel; +const kMyTool = Symbol('my-tool'); +const ch = channel('http.client.request'); +const store = new AsyncLocalStorage(); + +// This store will NOT be entered when bypass(kMyTool, fn) is active +ch.bindStore(store, (data) => ({ requestId: data.id }), { + bypassId: kMyTool, +}); +``` + +```cjs +const diagnostics_channel = require('node:diagnostics_channel'); +const { AsyncLocalStorage } = require('node:async_hooks'); + +const { channel, bypass } = diagnostics_channel; +const kMyTool = Symbol('my-tool'); +const ch = channel('http.client.request'); +const store = new AsyncLocalStorage(); + +// This store will NOT be entered when bypass(kMyTool, fn) is active +ch.bindStore(store, (data) => ({ requestId: data.id }), { + bypassId: kMyTool, +}); +``` + #### `channel.unbindStore(store)` * `subscribers` {Object} Set of [TracingChannel Channels][] subscribers @@ -770,6 +1008,11 @@ added: * `asyncStart` {Function} The [`asyncStart` event][] subscriber * `asyncEnd` {Function} The [`asyncEnd` event][] subscriber * `error` {Function} The [`error` event][] subscriber +* `options` {Object} + * `bypassId` {symbol|Object} An optional identity token. When + provided, ALL handlers (start, end, asyncStart, asyncEnd, error) + will be skipped while [`diagnostics_channel.bypass()`][] is + active with the same key. Helper to subscribe a collection of functions to the corresponding channels. This is the same as calling [`channel.subscribe(onMessage)`][] on each channel @@ -823,6 +1066,52 @@ channels.subscribe({ }); ``` +To opt all TracingChannel handlers into bypass behavior: + +```mjs +import diagnostics_channel from 'node:diagnostics_channel'; + +const { tracingChannel, bypass } = diagnostics_channel; +const kMyTool = Symbol('my-tool'); +const tc = tracingChannel('my-operation'); + +// All TracingChannel events skipped when bypass(kMyTool) is active +tc.subscribe({ + start(message) { /* ... */ }, + end(message) { /* ... */ }, + asyncStart(message) { /* ... */ }, + asyncEnd(message) { /* ... */ }, +}, { bypassId: kMyTool }); + +bypass(kMyTool, () => { + tc.traceSync(() => { + // Start and end handlers are NOT called + }); +}); +``` + +```cjs +const diagnostics_channel = require('node:diagnostics_channel'); + +const { tracingChannel, bypass } = diagnostics_channel; +const kMyTool = Symbol('my-tool'); +const tc = tracingChannel('my-operation'); + +// All TracingChannel events skipped when bypass(kMyTool) is active +tc.subscribe({ + start(message) { /* ... */ }, + end(message) { /* ... */ }, + asyncStart(message) { /* ... */ }, + asyncEnd(message) { /* ... */ }, +}, { bypassId: kMyTool }); + +bypass(kMyTool, () => { + tc.traceSync(() => { + // Start and end handlers are NOT called + }); +}); +``` + #### `tracingChannel.unsubscribe(subscribers)` * `fn` {Function} Function to wrap a trace around * `context` {Object} Shared object to correlate trace events through * `thisArg` {any} The receiver to be used for the function call * `...args` {any} Optional arguments to pass to the function -* Returns: {any} The return value of the given function. If the return value - is a Promise or thenable, tracing events will be published when it settles. - If the return value is not a Promise or thenable, it is returned as-is and - a warning is emitted. +* Returns: {any} The return value of the given function, or the result of + calling `.then(...)` on the return value if the tracing channel has active + subscribers. If the return value is not a Promise or thenable, then + it is returned as-is and a warning is emitted. Trace an asynchronous function call which returns a {Promise} or [thenable object][]. This will always produce a [`start` event][] and @@ -1930,6 +2216,7 @@ Emitted when a new thread is created. [`channel.unsubscribe(onMessage)`]: #channelunsubscribeonmessage [`channel.withStoreScope(data)`]: #channelwithstorescopedata [`child_process.spawn()`]: child_process.md#child_processspawncommand-args-options +[`diagnostics_channel.bypass()`]: #diagnostics_channelbypasskey-fn-thisarg-args [`diagnostics_channel.channel(name)`]: #diagnostics_channelchannelname [`diagnostics_channel.subscribe(name, onMessage)`]: #diagnostics_channelsubscribename-onmessage [`diagnostics_channel.tracingChannel()`]: #diagnostics_channeltracingchannelnameorchannels From f7f593edadc8147585eed5986ef3b71949330fdd Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Wed, 8 Jul 2026 19:12:56 +0530 Subject: [PATCH 25/39] doc: address Flarna review feedback on bypass documentation Signed-off-by: Divyanshu Sharma --- doc/api/diagnostics_channel.md | 121 +++++++-------------------------- 1 file changed, 23 insertions(+), 98 deletions(-) diff --git a/doc/api/diagnostics_channel.md b/doc/api/diagnostics_channel.md index 741c2b42321b..8a6b21f91c12 100644 --- a/doc/api/diagnostics_channel.md +++ b/doc/api/diagnostics_channel.md @@ -72,13 +72,6 @@ if (channel.hasSubscribers) { // Unsubscribe from the channel diagnostics_channel.unsubscribe('my-channel', onMessage); - -// Use bypass() to skip opted-in subscribers during internal calls -const kMyTool = Symbol('my-tool'); -diagnostics_channel.channel('my-channel').subscribe(onMessage, { bypassId: kMyTool }); -diagnostics_channel.bypass(kMyTool, () => { - // onMessage will NOT be called for publishes inside here -}); ``` ```cjs @@ -104,13 +97,6 @@ if (channel.hasSubscribers) { // Unsubscribe from the channel diagnostics_channel.unsubscribe('my-channel', onMessage); - -// Use bypass() to skip opted-in subscribers during internal calls -const kMyTool = Symbol('my-tool'); -diagnostics_channel.channel('my-channel').subscribe(onMessage, { bypassId: kMyTool }); -diagnostics_channel.bypass(kMyTool, () => { - // onMessage will NOT be called for publishes inside here -}); ``` #### `diagnostics_channel.hasSubscribers(name)` @@ -251,21 +237,20 @@ diagnostics_channel.unsubscribe('my-channel', onMessage); added: REPLACEME --> -* `key` {symbol|Object} The bypass identity token. Must match the - `bypassId` used when subscribing. +> Stability: 1.1 - Active development + +* `key` {symbol|Object} The bypass identity token. Subscribers and + stores registered with the same `bypassId` value will be skipped + while this function executes. * `fn` {Function} The function to run with bypass active. * `thisArg` {any} The receiver to use for the function call. * `...args` {any} Optional arguments to pass to the function. * Returns: {any} The return value of `fn`. -Runs `fn` with the given `key` active in the current async context. -Any channel subscribers or bound stores that were registered with -`{ bypassId: key }` will be skipped for the duration of `fn` and -any async continuations (Promises, timers, microtasks) within it. - -This is designed for observability tooling (APM agents, tracers) -that need to prevent recursive instrumentation when their own -internal code calls into an instrumented library. +Calls `fn` and skips any channel subscribers or bound stores that +were registered with a matching `bypassId` key. The skip behavior +also applies to any async continuations (Promises, timers, +microtasks) within `fn`. ```mjs import diagnostics_channel from 'node:diagnostics_channel'; @@ -277,7 +262,7 @@ const { channel, bypass } = diagnostics_channel; const kMyTracer = Symbol('my-tracer'); // Subscribe to HTTP requests, but opt into bypass -channel('http.client.request').subscribe((message) => { +channel('http.client.request.start').subscribe((message) => { console.log('HTTP request:', message.url); }, { bypassId: kMyTracer }); @@ -304,7 +289,7 @@ const { channel, bypass } = diagnostics_channel; const kMyTracer = Symbol('my-tracer'); // Subscribe to HTTP requests, but opt into bypass -channel('http.client.request').subscribe((message) => { +channel('http.client.request.start').subscribe((message) => { console.log('HTTP request:', message.url); }, { bypassId: kMyTracer }); @@ -331,14 +316,14 @@ The bypass context propagates across async boundaries: // bypass() works across Promise boundaries await bypass(kMyTracer, async () => { await someAsyncOperation(); // still bypassed - channel('http.client.request').publish({}); // subscriber skipped + channel('http.client.request.start').publish({}); // subscriber skipped }); // And across timers bypass(kMyTracer, () => { setImmediate(() => { // Still bypassed here - channel('http.client.request').publish({}); + channel('http.client.request.start').publish({}); }); }); ``` @@ -347,11 +332,11 @@ bypass(kMyTracer, () => { (async () => { await bypass(kMyTracer, async () => { await someAsyncOperation(); - channel('http.client.request').publish({}); + channel('http.client.request.start').publish({}); }); bypass(kMyTracer, () => { setImmediate(() => { - channel('http.client.request').publish({}); + channel('http.client.request.start').publish({}); }); }); })(); @@ -364,12 +349,12 @@ interfering with each other: const kToolA = Symbol('tool-a'); const kToolB = Symbol('tool-b'); -channel('http.client.request').subscribe(handlerA, { bypassId: kToolA }); -channel('http.client.request').subscribe(handlerB, { bypassId: kToolB }); +channel('http.client.request.start').subscribe(handlerA, { bypassId: kToolA }); +channel('http.client.request.start').subscribe(handlerB, { bypassId: kToolB }); // Only handlerA is skipped, handlerB still fires bypass(kToolA, () => { - channel('http.client.request').publish({}); + channel('http.client.request.start').publish({}); }); ``` @@ -381,12 +366,12 @@ const { channel, bypass } = diagnostics_channel; const kToolA = Symbol('tool-a'); const kToolB = Symbol('tool-b'); -channel('http.client.request').subscribe(handlerA, { bypassId: kToolA }); -channel('http.client.request').subscribe(handlerB, { bypassId: kToolB }); +channel('http.client.request.start').subscribe(handlerA, { bypassId: kToolA }); +channel('http.client.request.start').subscribe(handlerB, { bypassId: kToolB }); // Only handlerA is skipped, handlerB still fires bypass(kToolA, () => { - channel('http.client.request').publish({}); + channel('http.client.request.start').publish({}); }); ``` @@ -627,33 +612,7 @@ channel.subscribe((message, name) => { }); ``` -To opt this subscriber into bypass behavior: - -```mjs -import diagnostics_channel from 'node:diagnostics_channel'; - -const { channel, bypass } = diagnostics_channel; -const kMyTool = Symbol('my-tool'); -const ch = channel('http.client.request'); - -// This handler will be skipped when bypass(kMyTool, fn) is active -ch.subscribe((message) => { - // handle message -}, { bypassId: kMyTool }); -``` - -```cjs -const diagnostics_channel = require('node:diagnostics_channel'); - -const { channel, bypass } = diagnostics_channel; -const kMyTool = Symbol('my-tool'); -const ch = channel('http.client.request'); - -// This handler will be skipped when bypass(kMyTool, fn) is active -ch.subscribe((message) => { - // handle message -}, { bypassId: kMyTool }); -``` +See [`diagnostics_channel.bypass()`][] for usage with `bypassId`. #### `channel.unsubscribe(onMessage)` @@ -767,37 +726,7 @@ channel.bindStore(store, (data) => { }); ``` -To opt this bound store into bypass behavior: - -```mjs -import diagnostics_channel from 'node:diagnostics_channel'; -import { AsyncLocalStorage } from 'node:async_hooks'; - -const { channel, bypass } = diagnostics_channel; -const kMyTool = Symbol('my-tool'); -const ch = channel('http.client.request'); -const store = new AsyncLocalStorage(); - -// This store will NOT be entered when bypass(kMyTool, fn) is active -ch.bindStore(store, (data) => ({ requestId: data.id }), { - bypassId: kMyTool, -}); -``` - -```cjs -const diagnostics_channel = require('node:diagnostics_channel'); -const { AsyncLocalStorage } = require('node:async_hooks'); - -const { channel, bypass } = diagnostics_channel; -const kMyTool = Symbol('my-tool'); -const ch = channel('http.client.request'); -const store = new AsyncLocalStorage(); - -// This store will NOT be entered when bypass(kMyTool, fn) is active -ch.bindStore(store, (data) => ({ requestId: data.id }), { - bypassId: kMyTool, -}); -``` +See [`diagnostics_channel.bypass()`][] for usage with `bypassId`. #### `channel.unbindStore(store)` @@ -996,10 +925,6 @@ dynamically. added: - v19.9.0 - v18.19.0 -changes: - - version: REPLACEME - pr-url: https://github.com/nodejs/node/pull/63651 - description: Added `options.bypassId` parameter. --> * `subscribers` {Object} Set of [TracingChannel Channels][] subscribers From 58785bb51ad46c4d08f50d21f6ba30ee40a69fd8 Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Mon, 13 Jul 2026 19:01:12 +0530 Subject: [PATCH 26/39] doc: revert unrelated tracePromise description changes Signed-off-by: Divyanshu Sharma --- doc/api/diagnostics_channel.md | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/doc/api/diagnostics_channel.md b/doc/api/diagnostics_channel.md index 8a6b21f91c12..4ca30bf0e219 100644 --- a/doc/api/diagnostics_channel.md +++ b/doc/api/diagnostics_channel.md @@ -1162,20 +1162,23 @@ added: - v19.9.0 - v18.19.0 changes: + - version: v26.5.0 + pr-url: https://github.com/nodejs/node/pull/62407 + description: Non-native-Promise thenables are now returned as-is, + preserving their original type and methods. - version: v26.0.0 pr-url: https://github.com/nodejs/node/pull/61766 - description: Custom thenables will no longer be wrapped in native Promises. - Non-thenables will be returned with a warning. + description: Non-thenables will be returned with a warning. --> * `fn` {Function} Function to wrap a trace around * `context` {Object} Shared object to correlate trace events through * `thisArg` {any} The receiver to be used for the function call * `...args` {any} Optional arguments to pass to the function -* Returns: {any} The return value of the given function, or the result of - calling `.then(...)` on the return value if the tracing channel has active - subscribers. If the return value is not a Promise or thenable, then - it is returned as-is and a warning is emitted. +* Returns: {any} The return value of the given function. If the return value + is a Promise or thenable, tracing events will be published when it settles. + If the return value is not a Promise or thenable, it is returned as-is and + a warning is emitted. Trace an asynchronous function call which returns a {Promise} or [thenable object][]. This will always produce a [`start` event][] and From aa285c86ec68cc099256dc31ae6e2855e84420b7 Mon Sep 17 00:00:00 2001 From: DivyanshuX9 Date: Fri, 24 Jul 2026 21:51:42 +0530 Subject: [PATCH 27/39] lib: resolve merge conflicts in diagnostics_channel bypass feature Signed-off-by: DivyanshuX9 --- lib/diagnostics_channel.js | 43 +++++++++++++++++++------------------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index 49d0dbfb69c6..805ca81a8084 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -32,7 +32,6 @@ const { const { triggerUncaughtException } = internalBinding('errors'); const dc_binding = internalBinding('diagnostics_channel'); -const { subscribers: subscriberCounts } = dc_binding; const { WeakReference, kEmptyObject } = require('internal/util'); const { isPromise } = require('internal/util/types'); @@ -104,19 +103,6 @@ function markActive(channel) { channel._bypassStores = null; } -function incRefIfNew(channel, isNew) { - if (isNew) { - channels.incRef(channel.name); - subscriberCounts[channel._index]++; - } -} - -function decRefAndMaybeInactive(channel) { - channels.decRef(channel.name); - subscriberCounts[channel._index]--; - maybeMarkInactive(channel); -} - function maybeMarkInactive(channel) { // When there are no more active subscribers or bound, restore to fast prototype. if (!channel._subscribers.length && @@ -213,7 +199,8 @@ class ActiveChannel { ArrayPrototypePush(this._subscribers, subscription); } - incRefIfNew(this, true); + channels.incRef(this.name); + if (this._index !== undefined) dc_binding.subscribers[this._index]++; } unsubscribe(subscription) { @@ -223,7 +210,9 @@ class ActiveChannel { const after = ArrayPrototypeSlice(this._subscribers, index + 1); this._subscribers = before; ArrayPrototypePushApply(this._subscribers, after); - decRefAndMaybeInactive(this); + channels.decRef(this.name); + if (this._index !== undefined) dc_binding.subscribers[this._index]--; + maybeMarkInactive(this); return true; } @@ -244,7 +233,9 @@ class ActiveChannel { if (this._bypassSubscribers.length === 0) { this._bypassSubscribers = null; } - decRefAndMaybeInactive(this); + channels.decRef(this.name); + if (this._index !== undefined) dc_binding.subscribers[this._index]--; + maybeMarkInactive(this); return true; } } @@ -262,13 +253,19 @@ class ActiveChannel { this._bypassStores = new SafeMap(); } const replacing = this._bypassStores.has(store); - incRefIfNew(this, !replacing); + if (!replacing) { + channels.incRef(this.name); + if (this._index !== undefined) dc_binding.subscribers[this._index]++; + } this._bypassStores.set(store, { transform, bypassId }); } else { // No bypassId provided: store as a plain transform function, // matching the pre-bypass-feature behavior exactly. const replacing = this._stores.has(store); - incRefIfNew(this, !replacing); + if (!replacing) { + channels.incRef(this.name); + if (this._index !== undefined) dc_binding.subscribers[this._index]++; + } this._stores.set(store, transform); } } @@ -276,7 +273,9 @@ class ActiveChannel { unbindStore(store) { if (this._stores.has(store)) { this._stores.delete(store); - decRefAndMaybeInactive(this); + channels.decRef(this.name); + if (this._index !== undefined) dc_binding.subscribers[this._index]--; + maybeMarkInactive(this); return true; } @@ -285,7 +284,9 @@ class ActiveChannel { if (this._bypassStores.size === 0) { this._bypassStores = null; } - decRefAndMaybeInactive(this); + channels.decRef(this.name); + if (this._index !== undefined) dc_binding.subscribers[this._index]--; + maybeMarkInactive(this); return true; } From 8dd3c97eeaf15d5de9938007de1a577573b2df6f Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Fri, 24 Jul 2026 23:29:04 +0530 Subject: [PATCH 28/39] lib: fix merge conflict residue in diagnostics_channel.js Signed-off-by: Divyanshu Sharma --- lib/diagnostics_channel.js | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index d79778950277..9c2952576fce 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -34,6 +34,7 @@ const { triggerUncaughtException } = internalBinding('errors'); // The subscriber buffer is replaced when native channel storage grows, so it // must always be accessed through the binding instead of cached. const dc_binding = internalBinding('diagnostics_channel'); +const { subscribers: subscriberCounts } = dc_binding; const { WeakReference, kEmptyObject } = require('internal/util'); const { isPromise } = require('internal/util/types'); @@ -202,7 +203,7 @@ class ActiveChannel { } channels.incRef(this.name); - if (this._index !== undefined) dc_binding.subscribers[this._index]++; + if (this._index !== undefined) subscriberCounts[this._index]++; } unsubscribe(subscription) { @@ -213,7 +214,7 @@ class ActiveChannel { this._subscribers = before; ArrayPrototypePushApply(this._subscribers, after); channels.decRef(this.name); - if (this._index !== undefined) dc_binding.subscribers[this._index]--; + if (this._index !== undefined) subscriberCounts[this._index]--; maybeMarkInactive(this); return true; } @@ -236,7 +237,7 @@ class ActiveChannel { this._bypassSubscribers = null; } channels.decRef(this.name); - if (this._index !== undefined) dc_binding.subscribers[this._index]--; + if (this._index !== undefined) subscriberCounts[this._index]--; maybeMarkInactive(this); return true; } @@ -260,7 +261,7 @@ class ActiveChannel { const replacing = this._bypassStores.has(store); if (!replacing) { channels.incRef(this.name); - if (this._index !== undefined) dc_binding.subscribers[this._index]++; + if (this._index !== undefined) subscriberCounts[this._index]++; } this._bypassStores.set(store, { transform, bypassId }); } else { @@ -269,7 +270,7 @@ class ActiveChannel { const replacing = this._stores.has(store); if (!replacing) { channels.incRef(this.name); - if (this._index !== undefined) dc_binding.subscribers[this._index]++; + if (this._index !== undefined) subscriberCounts[this._index]++; } this._stores.set(store, transform); bindStore(store, transform) { @@ -284,7 +285,7 @@ class ActiveChannel { if (this._stores.has(store)) { this._stores.delete(store); channels.decRef(this.name); - if (this._index !== undefined) dc_binding.subscribers[this._index]--; + if (this._index !== undefined) subscriberCounts[this._index]--; maybeMarkInactive(this); return true; } @@ -295,7 +296,7 @@ class ActiveChannel { this._bypassStores = null; } channels.decRef(this.name); - if (this._index !== undefined) dc_binding.subscribers[this._index]--; + if (this._index !== undefined) subscriberCounts[this._index]--; maybeMarkInactive(this); return true; } @@ -315,7 +316,7 @@ class ActiveChannel { publish(data) { // Normal path, no ALS lookup, plain function call, zero overhead. const subscribers = this._subscribers; - for (let i = 0; i < subscribers.length; i++) { + for (let i = 0; i < (subscribers?.length || 0); i++) { try { subscribers[i](data, this.name); } catch (err) { From cc7604f81f11e0c86dd16d107d2f44c9b6d15aea Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Sat, 25 Jul 2026 00:45:12 +0530 Subject: [PATCH 29/39] lib: remove stale merge remnants in diagnostics_channel ActiveChannel Three bad-merge fragments were committed without conflict markers: - unsubscribe: spurious decRef/maybeMarkInactive before return false - bindStore: stale bindStore(store, transform) fragment injected inside the else block of bindStore(store, transform, options), with missing closing braces for the else block and the method - unbindStore: spurious delete/decRef/maybeMarkInactive before return false All three were remnants of the pre-bypass single-path implementation that were not removed during the bypass-feature merge. Signed-off-by: Divyanshu Sharma --- lib/diagnostics_channel.js | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index 9c2952576fce..99645cf5966e 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -242,10 +242,6 @@ class ActiveChannel { return true; } } - channels.decRef(this.name); - if (this._index !== undefined) dc_binding.subscribers[this._index]--; - maybeMarkInactive(this); - return false; } @@ -273,11 +269,6 @@ class ActiveChannel { if (this._index !== undefined) subscriberCounts[this._index]++; } this._stores.set(store, transform); - bindStore(store, transform) { - const replacing = this._stores.has(store); - if (!replacing) { - channels.incRef(this.name); - if (this._index !== undefined) dc_binding.subscribers[this._index]++; } } @@ -300,12 +291,6 @@ class ActiveChannel { maybeMarkInactive(this); return true; } - this._stores.delete(store); - - channels.decRef(this.name); - if (this._index !== undefined) dc_binding.subscribers[this._index]--; - maybeMarkInactive(this); - return false; } From 67b93333c815ed06c0ec1cd450bd5bd3be67400e Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Sat, 25 Jul 2026 01:02:41 +0530 Subject: [PATCH 30/39] lib: fix diagnostics_channel native subscriber count to include bypass entries Signed-off-by: Divyanshu Sharma --- lib/diagnostics_channel.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index 99645cf5966e..d5554bc2557c 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -781,7 +781,9 @@ dc_binding.linkNativeChannel((name, index) => { linkedChannel._index = index; dc_binding.subscribers[index] = (linkedChannel._subscribers?.length || 0) + - (linkedChannel._stores?.size || 0); + (linkedChannel._stores?.size || 0) + + (linkedChannel._bypassSubscribers?.length || 0) + + (linkedChannel._bypassStores?.size || 0); return linkedChannel; }); From 6d23c3bb08721069fa5b815257917cc949aec39f Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Sun, 26 Jul 2026 13:41:10 +0530 Subject: [PATCH 31/39] lib: fix diagnostics_channel subscriber count after native buffer growth The subscriber buffer (dc_binding.subscribers) is replaced with a new larger TypedArray when native channel storage grows past its initial capacity. The old code destructured it once at module load: const { subscribers: subscriberCounts } = dc_binding; After growth, dc_binding.subscribers points to the new array but subscriberCounts still holds a reference to the old one. Any subscribe/unsubscribe/bindStore/unbindStore call after growth would increment/decrement the stale array, leaving the live array at zero. Channel::HasSubscribers() reads from the live array and would return false even with active subscribers, breaking the C++ test NativeChannelsGrowSubscriberStorage. Fix: remove the cached destructuring and access dc_binding.subscribers directly at every call site. The comment above the binding already stated this requirement; the code just did not follow it. Signed-off-by: Divyanshu Sharma --- lib/diagnostics_channel.js | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index d5554bc2557c..31f0d036474c 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -34,7 +34,6 @@ const { triggerUncaughtException } = internalBinding('errors'); // The subscriber buffer is replaced when native channel storage grows, so it // must always be accessed through the binding instead of cached. const dc_binding = internalBinding('diagnostics_channel'); -const { subscribers: subscriberCounts } = dc_binding; const { WeakReference, kEmptyObject } = require('internal/util'); const { isPromise } = require('internal/util/types'); @@ -203,7 +202,7 @@ class ActiveChannel { } channels.incRef(this.name); - if (this._index !== undefined) subscriberCounts[this._index]++; + if (this._index !== undefined) dc_binding.subscribers[this._index]++; } unsubscribe(subscription) { @@ -214,7 +213,7 @@ class ActiveChannel { this._subscribers = before; ArrayPrototypePushApply(this._subscribers, after); channels.decRef(this.name); - if (this._index !== undefined) subscriberCounts[this._index]--; + if (this._index !== undefined) dc_binding.subscribers[this._index]--; maybeMarkInactive(this); return true; } @@ -237,7 +236,7 @@ class ActiveChannel { this._bypassSubscribers = null; } channels.decRef(this.name); - if (this._index !== undefined) subscriberCounts[this._index]--; + if (this._index !== undefined) dc_binding.subscribers[this._index]--; maybeMarkInactive(this); return true; } @@ -257,7 +256,7 @@ class ActiveChannel { const replacing = this._bypassStores.has(store); if (!replacing) { channels.incRef(this.name); - if (this._index !== undefined) subscriberCounts[this._index]++; + if (this._index !== undefined) dc_binding.subscribers[this._index]++; } this._bypassStores.set(store, { transform, bypassId }); } else { @@ -266,7 +265,7 @@ class ActiveChannel { const replacing = this._stores.has(store); if (!replacing) { channels.incRef(this.name); - if (this._index !== undefined) subscriberCounts[this._index]++; + if (this._index !== undefined) dc_binding.subscribers[this._index]++; } this._stores.set(store, transform); } @@ -276,7 +275,7 @@ class ActiveChannel { if (this._stores.has(store)) { this._stores.delete(store); channels.decRef(this.name); - if (this._index !== undefined) subscriberCounts[this._index]--; + if (this._index !== undefined) dc_binding.subscribers[this._index]--; maybeMarkInactive(this); return true; } @@ -287,7 +286,7 @@ class ActiveChannel { this._bypassStores = null; } channels.decRef(this.name); - if (this._index !== undefined) subscriberCounts[this._index]--; + if (this._index !== undefined) dc_binding.subscribers[this._index]--; maybeMarkInactive(this); return true; } From b552f97fc26dc2db43a05e7f2dfdaa8ba557bbee Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Sun, 26 Jul 2026 17:39:18 +0530 Subject: [PATCH 32/39] lib: remove unnecessary optional chain in diagnostics_channel publish() ActiveChannel.publish() accessed this._subscribers with optional chaining (subscribers?.length || 0). This is unnecessary because: - _subscribers is always initialized to [] by markActive() before any ActiveChannel method can be called - maybeMarkInactive() sets _subscribers back to undefined only after switching the prototype back to Channel.prototype, so ActiveChannel methods are never reachable with a nullish _subscribers Use subscribers.length directly. Signed-off-by: Divyanshu Sharma --- lib/diagnostics_channel.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index 31f0d036474c..45c68340d2cd 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -300,7 +300,7 @@ class ActiveChannel { publish(data) { // Normal path, no ALS lookup, plain function call, zero overhead. const subscribers = this._subscribers; - for (let i = 0; i < (subscribers?.length || 0); i++) { + for (let i = 0; i < subscribers.length; i++) { try { subscribers[i](data, this.name); } catch (err) { From 748f6bccd416a1000b827e2a3e01d1ec6aa9ed12 Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Wed, 12 Aug 2026 00:14:23 +0530 Subject: [PATCH 33/39] test: fix bypass store test assertions and error code checks Signed-off-by: Divyanshu Sharma --- .../test-diagnostics-channel-bypass.js | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/test/parallel/test-diagnostics-channel-bypass.js b/test/parallel/test-diagnostics-channel-bypass.js index d3ddd3d4def2..ecec5c064c31 100644 --- a/test/parallel/test-diagnostics-channel-bypass.js +++ b/test/parallel/test-diagnostics-channel-bypass.js @@ -166,20 +166,14 @@ const { AsyncLocalStorage } = require('async_hooks'); // Bypass store, must NOT be entered inside bypass(). ch.bindStore(als, common.mustNotCall(), { bypassId: key }); - // Handler verifies: - // - normal store WAS entered (normalAls has value) - // - bypass store was NOT entered (als is undefined) - const handler = common.mustCall(() => { - assert.strictEqual(normalAls.getStore()?.value, 42); - assert.strictEqual(als.getStore(), undefined); - }); - ch.subscribe(handler); - bypass(key, common.mustCall(() => { - ch.runStores({ value: 42 }, common.mustCall()); + ch.runStores({ value: 42 }, common.mustCall(() => { + // Assertions inside runStores where store context exists + assert.strictEqual(normalAls.getStore()?.value, 42); + assert.strictEqual(als.getStore(), undefined); + })); })); - ch.unsubscribe(handler); ch.unbindStore(als); ch.unbindStore(normalAls); } @@ -189,11 +183,17 @@ const { AsyncLocalStorage } = require('async_hooks'); const ch = channel('test-bypass-wrong-type'); const bad = 'not-allowed'; assert.throws(() => ch.subscribe(() => {}, { bypassId: bad }), { - name: 'TypeError' + code: 'ERR_INVALID_ARG_TYPE', + name: 'TypeError', }); const als = new AsyncLocalStorage(); assert.throws(() => ch.bindStore(als, (d) => d, { bypassId: bad }), { - name: 'TypeError' + code: 'ERR_INVALID_ARG_TYPE', + name: 'TypeError', + }); + assert.throws(() => bypass(bad, () => {}), { + code: 'ERR_INVALID_ARG_TYPE', + name: 'TypeError', }); } From 33f12a54e53c4e996662af1441d0e6d0b9fb2fee Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Mon, 24 Aug 2026 18:57:43 +0530 Subject: [PATCH 34/39] doc: fix link order in diagnostics_channel.md --- doc/api/diagnostics_channel.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/api/diagnostics_channel.md b/doc/api/diagnostics_channel.md index 3ed560f95b3a..a59168ee1e3c 100644 --- a/doc/api/diagnostics_channel.md +++ b/doc/api/diagnostics_channel.md @@ -2189,8 +2189,8 @@ statement, since both are still in use while the event is being delivered; see [`channel.unsubscribe(onMessage)`]: #channelunsubscribeonmessage [`channel.withStoreScope(data)`]: #channelwithstorescopedata [`child_process.spawn()`]: child_process.md#child_processspawncommand-args-options -[`diagnostics_channel.bypass()`]: #diagnostics_channelbypasskey-fn-thisarg-args [`database.close()`]: sqlite.md#databaseclose +[`diagnostics_channel.bypass()`]: #diagnostics_channelbypasskey-fn-thisarg-args [`diagnostics_channel.channel(name)`]: #diagnostics_channelchannelname [`diagnostics_channel.subscribe(name, onMessage)`]: #diagnostics_channelsubscribename-onmessage [`diagnostics_channel.tracingChannel()`]: #diagnostics_channeltracingchannelnameorchannels From 16325a36fb5ea754d47bff3726319bac3f66d6d2 Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Tue, 15 Sep 2026 23:38:01 +0530 Subject: [PATCH 35/39] lib: fix diagnostics_channel crash when _bypassSubscribers is undefined Channels activated via the native linkNativeChannel path do not go through markActive(), so _bypassSubscribers is never initialized and remains undefined rather than null. The strict null checks in unsubscribe() and publish(): if (this._bypassSubscribers !== null) pass for undefined, causing the subsequent .length access to throw: TypeError: Cannot read properties of undefined (reading 'length') Use loose inequality (!= null) which guards against both null and undefined, matching the intent of "only enter bypass path when bypass subscribers exist". Fixes: test-crypto-fips-indicator-strict Fixes: test-diagnostics-channel-crypto-fips-indicator Signed-off-by: Divyanshu Sharma --- lib/diagnostics_channel.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index 095ac1cb9f33..c36b1cc8e163 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -227,7 +227,7 @@ class ActiveChannel { } // Check bypass subscribers - if (this._bypassSubscribers !== null) { + if (this._bypassSubscribers != null) { let bypassIndex = -1; for (let i = 0; i < this._bypassSubscribers.length; i++) { if (this._bypassSubscribers[i].handler === subscription) { @@ -319,7 +319,7 @@ class ActiveChannel { } // Bypass path, only entered if bypass subscribers exist. - if (this._bypassSubscribers !== null) { + if (this._bypassSubscribers != null) { const activeKeys = getBypassStorage().getStore(); const bypassSubscribers = this._bypassSubscribers; for (let i = 0; i < bypassSubscribers.length; i++) { From f4c8bb7bd46e4b3f3dfda76be60700c49e0cb239 Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma Date: Thu, 8 Oct 2026 16:35:20 +0530 Subject: [PATCH 36/39] lib: refactor RunStoresScope to use manual stack instead of DisposableStack --- lib/diagnostics_channel.js | 40 ++++++++++++++++++++++++++++++++------ 1 file changed, 34 insertions(+), 6 deletions(-) diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index c36b1cc8e163..fe2177faf434 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -21,6 +21,7 @@ const { } = primordials; const { + aggregateTwoErrors, codes: { ERR_INVALID_ARG_TYPE, }, @@ -128,12 +129,25 @@ function maybeMarkInactive(channel) { } } +function disposeStoreScopes(stack, error, hasError = false) { + for (let i = stack.length - 1; i >= 0; i--) { + try { + stack[i][SymbolDispose](); + } catch (err) { + error = hasError ? aggregateTwoErrors(err, error) : err; + hasError = true; + } + } + + if (hasError) throw error; +} + class RunStoresScope { #stack; constructor(activeChannel, data) { - // eslint-disable-next-line no-restricted-globals - using stack = new DisposableStack(); + // TODO: use native DisposableStack once supported in core + const stack = []; // Normal stores, unchanged from before. if (activeChannel._stores) { @@ -151,7 +165,11 @@ class RunStoresScope { continue; } } - stack.use(store.withScope(newContext)); + try { + ArrayPrototypePush(stack, store.withScope(newContext)); + } catch (err) { + disposeStoreScopes(stack, err, true); + } } } @@ -173,7 +191,11 @@ class RunStoresScope { continue; } } - stack.use(store.withScope(newContext)); + try { + ArrayPrototypePush(stack, store.withScope(newContext)); + } catch (err) { + disposeStoreScopes(stack, err, true); + } } } @@ -181,11 +203,17 @@ class RunStoresScope { activeChannel.publish(data); // Transfer ownership of the stack - this.#stack = stack.move(); + // TODO: Restore stack.move() when DisposableStack is restored in core + this.#stack = stack; } [SymbolDispose]() { - this.#stack[SymbolDispose](); + if (this.#stack !== undefined) { + const stack = this.#stack; + this.#stack = undefined; + + disposeStoreScopes(stack); + } } } From 9429cc3226906efe0f0984e1c24de1e6cbc0b42a Mon Sep 17 00:00:00 2001 From: DivyanshuX9 Date: Sat, 21 Nov 2026 22:13:06 +0530 Subject: [PATCH 37/39] diagnostics_channel: fix bypass store rebinding and validation Binding the same store once normally and once with `bypassId` left it registered in both the regular and the bypass map. `runStores()` then entered it twice and a single `unbindStore()` did not unbind it. Check both maps when binding and move the store from one to the other. Validate `bypassId` before activating an inactive channel, so an invalid value can no longer leave a channel active without subscribers. Document that subscribers and stores registered with `bypassId` run after the regular ones, and document `options.bypassId` for `tracingChannel.subscribe()` and `boundedChannel.subscribe()`. Declare the two bypass properties in the `Channel` constructor. Refs: https://github.com/nodejs/node/issues/63623 Signed-off-by: DivyanshuX9 --- doc/api/diagnostics_channel.md | 26 +- lib/diagnostics_channel.js | 34 ++- .../test-diagnostics-channel-bypass.js | 258 ++++++++++++++++++ 3 files changed, 308 insertions(+), 10 deletions(-) diff --git a/doc/api/diagnostics_channel.md b/doc/api/diagnostics_channel.md index 0b6983006db0..78d0547c9782 100644 --- a/doc/api/diagnostics_channel.md +++ b/doc/api/diagnostics_channel.md @@ -252,6 +252,10 @@ were registered with a matching `bypassId` key. The skip behavior also applies to any async continuations (Promises, timers, microtasks) within `fn`. +Subscribers and stores registered with `bypassId` run after all +regular subscribers and stores on the same channel, regardless of +registration order. This applies to both `publish()` and `runStores()`. + ```mjs import diagnostics_channel from 'node:diagnostics_channel'; import { request } from 'node:http'; @@ -591,6 +595,8 @@ changes: * `bypassId` {symbol|Object} An optional identity token. When provided, this subscriber will be skipped while [`diagnostics_channel.bypass()`][] is active with the same key. + Subscribers registered with `bypassId` run after all regular + subscribers on the same channel, regardless of registration order. Register a message handler to subscribe to this channel. This message handler will be run synchronously whenever a message is published to the channel. Any @@ -697,10 +703,14 @@ changes: * `bypassId` {symbol|Object} An optional identity token. When provided, this bound store will be skipped while [`diagnostics_channel.bypass()`][] is active with the same key. + Stores registered with `bypassId` run after all regular stores + on the same channel, regardless of registration order. When [`channel.runStores(context, ...)`][] is called, the given context data will be applied to any store bound to the channel. If the store has already been bound the previous `transform` function will be replaced with the new one. +Rebinding a store with or without `bypassId` moves it between the regular and +bypass groups. The `transform` function may be omitted to set the given context data as the context directly. @@ -933,6 +943,10 @@ dynamically. added: - v19.9.0 - v18.19.0 +changes: + - version: REPLACEME + pr-url: https://github.com/nodejs/node/pull/63651 + description: Added `options.bypassId` parameter. --> * `subscribers` {Object} Set of [TracingChannel Channels][] subscribers @@ -1418,15 +1432,25 @@ if (wc.hasSubscribers) { } ``` -#### `boundedChannel.subscribe(handlers)` +#### `boundedChannel.subscribe(handlers[, options])` * `handlers` {Object} Set of channel subscribers * `start` {Function} The start event subscriber * `end` {Function} The end event subscriber +* `options` {Object} + * `bypassId` {symbol|Object} An optional identity token. When + provided, this subscriber will be skipped while + [`diagnostics_channel.bypass()`][] is active with the same key. + Subscribers registered with `bypassId` run after all regular + subscribers on the same channel, regardless of registration order. Subscribe to the bounded channel events. This is equivalent to calling [`channel.subscribe(onMessage)`][] on each channel individually. diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index f7434ed02e51..ffff8574044c 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -285,23 +285,29 @@ class ActiveChannel { if (bypassId !== undefined) { validateBypassKey(bypassId, 'bypassId'); + } + + const replacing = this._stores.has(store) || this._bypassStores?.has(store); + if (!replacing) { + channels.incRef(this.name); + if (this._index !== undefined) dc_binding.subscribers[this._index]++; + } + + if (bypassId !== undefined) { + this._stores.delete(store); // Bypass path, lazy separate SafeMap only allocated when needed. if (this._bypassStores === null) { this._bypassStores = new SafeMap(); } - const replacing = this._bypassStores.has(store); - if (!replacing) { - channels.incRef(this.name); - if (this._index !== undefined) dc_binding.subscribers[this._index]++; - } this._bypassStores.set(store, { transform, bypassId }); } else { // No bypassId provided: store as a plain transform function, // matching the pre-bypass-feature behavior exactly. - const replacing = this._stores.has(store); - if (!replacing) { - channels.incRef(this.name); - if (this._index !== undefined) dc_binding.subscribers[this._index]++; + if (this._bypassStores?.has(store)) { + this._bypassStores.delete(store); + if (this._bypassStores.size === 0) { + this._bypassStores = null; + } } this._stores.set(store, transform); } @@ -382,6 +388,8 @@ class Channel { constructor(name) { this._subscribers = undefined; this._stores = undefined; + this._bypassSubscribers = undefined; + this._bypassStores = undefined; this.name = name; this._index = undefined; @@ -396,6 +404,10 @@ class Channel { subscribe(subscription, options) { validateFunction(subscription, 'subscription'); + const bypassId = options?.bypassId; + if (bypassId !== undefined) { + validateBypassKey(bypassId, 'bypassId'); + } markActive(this); this.subscribe(subscription, options); } @@ -405,6 +417,10 @@ class Channel { } bindStore(store, transform, options) { + const bypassId = options?.bypassId; + if (bypassId !== undefined) { + validateBypassKey(bypassId, 'bypassId'); + } markActive(this); this.bindStore(store, transform, options); } diff --git a/test/parallel/test-diagnostics-channel-bypass.js b/test/parallel/test-diagnostics-channel-bypass.js index ecec5c064c31..de5af39d3979 100644 --- a/test/parallel/test-diagnostics-channel-bypass.js +++ b/test/parallel/test-diagnostics-channel-bypass.js @@ -305,3 +305,261 @@ const { AsyncLocalStorage } = require('async_hooks'); ); })); } + +// Test 14: Bind normally, rebind with bypassId, unbindStore once marks channel inactive +{ + const key = Symbol('rebind-normal-to-bypass'); + const ch = channel('test-bypass-rebind-normal-to-bypass'); + const als = new AsyncLocalStorage(); + + ch.bindStore(als, (data) => data); + assert.strictEqual(ch.hasSubscribers, true); + + // Rebind with bypassId + ch.bindStore(als, (data) => data, { bypassId: key }); + assert.strictEqual(ch.hasSubscribers, true); + + // Outside bypass(key), the store is entered + ch.runStores({ value: 1 }, common.mustCall(() => { + assert.deepStrictEqual(als.getStore(), { value: 1 }); + })); + + // Inside bypass(key), the store is skipped + bypass(key, common.mustCall(() => { + ch.runStores({ value: 1 }, common.mustCall(() => { + assert.strictEqual(als.getStore(), undefined); + })); + })); + + // Unbind once: must completely remove store and make channel inactive + const unbound = ch.unbindStore(als); + assert.strictEqual(unbound, true); + assert.strictEqual(ch.hasSubscribers, false); + + // Store is no longer entered + ch.runStores({ value: 1 }, common.mustCall(() => { + assert.strictEqual(als.getStore(), undefined); + })); + + // Unbinding again returns false + assert.strictEqual(ch.unbindStore(als), false); +} + +// Test 15: Bind with bypassId, rebind normally, unbindStore once marks channel inactive +{ + const key = Symbol('rebind-bypass-to-normal'); + const ch = channel('test-bypass-rebind-bypass-to-normal'); + const als = new AsyncLocalStorage(); + + ch.bindStore(als, (data) => data, { bypassId: key }); + assert.strictEqual(ch.hasSubscribers, true); + + // Rebind without bypassId (normal) + ch.bindStore(als, (data) => data); + assert.strictEqual(ch.hasSubscribers, true); + + // Inside bypass(key), normal store should now fire (it was rebound to normal) + bypass(key, common.mustCall(() => { + ch.runStores({ value: 2 }, common.mustCall(() => { + assert.deepStrictEqual(als.getStore(), { value: 2 }); + })); + })); + + // Outside bypass(key), normal store fires + ch.runStores({ value: 2 }, common.mustCall(() => { + assert.deepStrictEqual(als.getStore(), { value: 2 }); + })); + + // Unbind once: must completely remove store and make channel inactive + const unbound = ch.unbindStore(als); + assert.strictEqual(unbound, true); + assert.strictEqual(ch.hasSubscribers, false); + + // Store is no longer entered + ch.runStores({ value: 3 }, common.mustCall(() => { + assert.strictEqual(als.getStore(), undefined); + })); + + // Unbinding again returns false + assert.strictEqual(ch.unbindStore(als), false); +} + +// Test 16: Store is entered exactly once per runStores() after rebind and transform calls verified +{ + const key = Symbol('rebind-single-entry'); + const ch = channel('test-bypass-rebind-single-entry'); + const als = new AsyncLocalStorage(); + + let transformCalls = 0; + ch.bindStore(als, (data) => { + transformCalls++; + return data; + }); + + // Rebind with bypassId + let transformCallsRebound = 0; + ch.bindStore(als, (data) => { + transformCallsRebound++; + return data; + }, { bypassId: key }); + + ch.runStores({ value: 42 }, common.mustCall(() => { + assert.deepStrictEqual(als.getStore(), { value: 42 }); + })); + + // The original transform must not be called; the rebound transform called exactly once + assert.strictEqual(transformCalls, 0); + assert.strictEqual(transformCallsRebound, 1); + + // Rebind back to normal + let transformCallsRebound2 = 0; + ch.bindStore(als, (data) => { + transformCallsRebound2++; + return data; + }); + + ch.runStores({ value: 43 }, common.mustCall(() => { + assert.deepStrictEqual(als.getStore(), { value: 43 }); + })); + + assert.strictEqual(transformCalls, 0); + assert.strictEqual(transformCallsRebound, 1); + assert.strictEqual(transformCallsRebound2, 1); + + ch.unbindStore(als); + assert.strictEqual(ch.hasSubscribers, false); +} + +// Test 17: Invalid bypassId on rebind throws ERR_INVALID_ARG_TYPE and preserves earlier binding and refcount +{ + const bad = 'invalid-string-key'; + + // 1. Earlier binding is normal + { + const ch = channel('test-bypass-rebind-invalid-normal'); + const als = new AsyncLocalStorage(); + + ch.bindStore(als, (data) => data); + assert.strictEqual(ch.hasSubscribers, true); + + assert.throws( + () => ch.bindStore(als, (data) => ({ modified: data }), { bypassId: bad }), + { + code: 'ERR_INVALID_ARG_TYPE', + name: 'TypeError', + } + ); + + // Channel still active, earlier binding intact and entered + assert.strictEqual(ch.hasSubscribers, true); + ch.runStores({ value: 100 }, common.mustCall(() => { + assert.deepStrictEqual(als.getStore(), { value: 100 }); + })); + + // Unbinding once still properly decrements refcount and marks inactive + assert.strictEqual(ch.unbindStore(als), true); + assert.strictEqual(ch.hasSubscribers, false); + } + + // 2. Earlier binding is bypass + { + const ch = channel('test-bypass-rebind-invalid-bypass'); + const als = new AsyncLocalStorage(); + const key = Symbol('valid-key'); + + ch.bindStore(als, (data) => data, { bypassId: key }); + assert.strictEqual(ch.hasSubscribers, true); + + assert.throws( + () => ch.bindStore(als, (data) => ({ modified: data }), { bypassId: bad }), + { + code: 'ERR_INVALID_ARG_TYPE', + name: 'TypeError', + } + ); + + // Channel still active, earlier bypass binding intact + assert.strictEqual(ch.hasSubscribers, true); + + // Outside bypass, store is entered + ch.runStores({ value: 200 }, common.mustCall(() => { + assert.deepStrictEqual(als.getStore(), { value: 200 }); + })); + + // Inside bypass with valid key, store is skipped + bypass(key, common.mustCall(() => { + ch.runStores({ value: 200 }, common.mustCall(() => { + assert.strictEqual(als.getStore(), undefined); + })); + })); + + // Unbinding once still properly decrements refcount and marks inactive + assert.strictEqual(ch.unbindStore(als), true); + assert.strictEqual(ch.hasSubscribers, false); + } +} + +// Test 18: Invalid bypassId on fresh inactive channel leaves channel inactive +{ + const bad = 'invalid-string-key'; + + // 1. Invalid bypassId passed to subscribe() on fresh inactive channel + { + const ch = channel('test-bypass-fresh-invalid-subscribe'); + assert.strictEqual(ch.hasSubscribers, false); + + assert.throws( + () => ch.subscribe(() => {}, { bypassId: bad }), + { + code: 'ERR_INVALID_ARG_TYPE', + name: 'TypeError', + } + ); + assert.strictEqual(ch.hasSubscribers, false); + + const key = Symbol('valid-subscribe'); + const handler = common.mustCall(); + ch.subscribe(handler, { bypassId: key }); + assert.strictEqual(ch.hasSubscribers, true); + + ch.publish({}); + + assert.strictEqual(ch.unsubscribe(handler), true); + assert.strictEqual(ch.hasSubscribers, false); + + const plainHandler = common.mustCall(); + ch.subscribe(plainHandler); + assert.strictEqual(ch.hasSubscribers, true); + + ch.publish({}); + + assert.strictEqual(ch.unsubscribe(plainHandler), true); + assert.strictEqual(ch.hasSubscribers, false); + } + + // 2. Invalid bypassId passed to bindStore() on fresh inactive channel + { + const ch = channel('test-bypass-fresh-invalid-bind-store'); + const als = new AsyncLocalStorage(); + assert.strictEqual(ch.hasSubscribers, false); + + assert.throws( + () => ch.bindStore(als, (data) => data, { bypassId: bad }), + { + code: 'ERR_INVALID_ARG_TYPE', + name: 'TypeError', + } + ); + assert.strictEqual(ch.hasSubscribers, false); + + const key = Symbol('valid-bind-store'); + const handler = common.mustCall(); + ch.subscribe(handler, { bypassId: key }); + assert.strictEqual(ch.hasSubscribers, true); + + ch.publish({}); + + assert.strictEqual(ch.unsubscribe(handler), true); + assert.strictEqual(ch.hasSubscribers, false); + } +} From d1a6ea1a0e770f5b199cbb4444620251abb08ce5 Mon Sep 17 00:00:00 2001 From: DivyanshuX9 Date: Sat, 21 Nov 2026 22:13:24 +0530 Subject: [PATCH 38/39] benchmark: add diagnostics_channel publish-bypass benchmark Measure `Channel.prototype.publish()` with regular subscribers, with subscribers registered with `bypassId` while no bypass is active, and with the same subscribers while `diagnostics_channel.bypass()` is active. This needs a binary that supports `bypassId`. Refs: https://github.com/nodejs/node/issues/63623 Signed-off-by: DivyanshuX9 --- .../diagnostics_channel/publish-bypass.js | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 benchmark/diagnostics_channel/publish-bypass.js diff --git a/benchmark/diagnostics_channel/publish-bypass.js b/benchmark/diagnostics_channel/publish-bypass.js new file mode 100644 index 000000000000..1ed1cdfec9e8 --- /dev/null +++ b/benchmark/diagnostics_channel/publish-bypass.js @@ -0,0 +1,47 @@ +'use strict'; +const common = require('../common.js'); +const dc = require('node:diagnostics_channel'); + +// This benchmark requires a binary supporting bypassId and cannot run on main. + +const bench = common.createBenchmark(main, { + mode: ['normal', 'bypass-idle', 'bypass-active'], + n: [1e7], + subscribers: [1, 10], +}); + +function noop() {} + +function main({ mode, n, subscribers }) { + const channel = dc.channel('test'); + const key = Symbol('key'); + const data = {}; + + for (let i = 0; i < subscribers; i++) { + if (mode === 'normal') { + channel.subscribe(noop); + } else { + channel.subscribe(noop, { bypassId: key }); + } + } + + const publish = () => { + bench.start(); + for (let i = 0; i < n; i++) { + channel.publish(data); + } + bench.end(n); + }; + + switch (mode) { + case 'normal': + case 'bypass-idle': + publish(); + break; + case 'bypass-active': + dc.bypass(key, publish); + break; + default: + throw new Error(`Unsupported mode: ${mode}`); + } +} From ddf51e6686bc7d1096fa62cbc8b1d0bd895a1fd5 Mon Sep 17 00:00:00 2001 From: DivyanshuX9 Date: Sat, 21 Nov 2026 23:10:50 +0530 Subject: [PATCH 39/39] =?UTF-8?q?=EF=BB=BFdiagnostics=5Fchannel:=20adopt?= =?UTF-8?q?=20DisposableStack=20for=20store=20scoping?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Upstream Node.js adopted native DisposableStack in diagnostics_channel, replacing manual array scope tracking. Update RunStoresScope to use DisposableStackPrototypeUse for both regular and bypass stores, transfer stack ownership with DisposableStackPrototypeMove, and remove the obsolete disposeStoreScopes helper and aggregateTwoErrors import. Refs: https://github.com/nodejs/node/issues/63623 Signed-off-by: DivyanshuX9 --- lib/diagnostics_channel.js | 42 ++++++++------------------------------ 1 file changed, 8 insertions(+), 34 deletions(-) diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index ffff8574044c..4c6d3ef20b7e 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -7,6 +7,9 @@ const { ArrayPrototypePushApply, ArrayPrototypeSlice, ArrayPrototypeSplice, + DisposableStack, + DisposableStackPrototypeMove, + DisposableStackPrototypeUse, ObjectDefineProperty, ObjectGetPrototypeOf, ObjectSetPrototypeOf, @@ -21,7 +24,6 @@ const { } = primordials; const { - aggregateTwoErrors, codes: { ERR_INVALID_ARG_TYPE, }, @@ -129,25 +131,11 @@ function maybeMarkInactive(channel) { } } -function disposeStoreScopes(stack, error, hasError = false) { - for (let i = stack.length - 1; i >= 0; i--) { - try { - stack[i][SymbolDispose](); - } catch (err) { - error = hasError ? aggregateTwoErrors(err, error) : err; - hasError = true; - } - } - - if (hasError) throw error; -} - class RunStoresScope { #stack; constructor(activeChannel, data) { - // TODO: use native DisposableStack once supported in core - const stack = []; + using stack = new DisposableStack(); // Normal stores, unchanged from before. if (activeChannel._stores) { @@ -165,11 +153,7 @@ class RunStoresScope { continue; } } - try { - ArrayPrototypePush(stack, store.withScope(newContext)); - } catch (err) { - disposeStoreScopes(stack, err, true); - } + DisposableStackPrototypeUse(stack, store.withScope(newContext)); } } @@ -191,11 +175,7 @@ class RunStoresScope { continue; } } - try { - ArrayPrototypePush(stack, store.withScope(newContext)); - } catch (err) { - disposeStoreScopes(stack, err, true); - } + DisposableStackPrototypeUse(stack, store.withScope(newContext)); } } @@ -203,17 +183,11 @@ class RunStoresScope { activeChannel.publish(data); // Transfer ownership of the stack - // TODO: Restore stack.move() when DisposableStack is restored in core to avoid broken behavior. - this.#stack = stack; + this.#stack = DisposableStackPrototypeMove(stack); } [SymbolDispose]() { - if (this.#stack !== undefined) { - const stack = this.#stack; - this.#stack = undefined; - - disposeStoreScopes(stack); - } + this.#stack[SymbolDispose](); } }