Skip to content

diagnostics_channel: add opt-in subscriber suppression via bypassBy and bypassed() - #63651

Open
DivyanshuX9 wants to merge 61 commits into
nodejs:mainfrom
DivyanshuX9:diag/suppression-als
Open

DivyanshuX9 wants to merge 61 commits into
nodejs:mainfrom
DivyanshuX9:diag/suppression-als

Conversation

@DivyanshuX9

@DivyanshuX9 DivyanshuX9 commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds an opt-in way for a subscriber to skip itself while a key is active in
the current async context. APM agents need this to stop their own internal
calls (for example exporting traces over HTTP) from triggering their own
instrumentation again. Each vendor currently builds this with a private
AsyncLocalStorage marker, and this moves the pattern into core.

Refs: #63623

API

  • diagnostics_channel.bypass(key, fn[, thisArg[, ...args]])
  • { bypassId } option on channel.subscribe(), channel.bindStore(),
    tracingChannel.subscribe() and boundedChannel.subscribe()

key and bypassId must be an object or a symbol. Subscribers and stores
registered with bypassId are skipped while bypass() is active with the
same key, including across promises and timers. They run after regular
subscribers and stores, regardless of registration order (documented).

Implementation

  • Regular subscribers and stores use the same structures as before.
    Bypass entries live in separate, lazily allocated structures, and the
    AsyncLocalStorage lookup only happens when such entries exist.
  • The AsyncLocalStorage is created lazily. Creating it eagerly fails during
    snapshot generation ("Should not query options before bootstrapping is
    done").
  • Rebinding a store with or without bypassId moves it between the two
    groups. An invalid bypassId is rejected before a channel is activated.

Tests and benchmark

  • test/parallel/test-diagnostics-channel-bypass.js: 18 test blocks (sync,
    async, promises, timers, stores, nesting, TracingChannel, validation,
    rebinding).
  • benchmark/diagnostics_channel/publish-bypass.js: regular, bypass idle
    and bypass active.

Performance

Measured on Windows with benchmark/compare.js, 30 runs per configuration,
Welch t-test. Baseline is upstream commit bc6dd40.

publish.js against main: no significant change with 0 subscribers
(-2.2% to +2.8%). With 1 subscriber about 70% to 77% more ops/s, and with
10 subscribers about 238% to 248% more. I have not isolated why the regular
path is faster.

Cost for subscribers that opt in (ns per publish):

Subscribers Regular bypassId, bypass not active Inside bypass()
1 3.6 6.3 23
10 12 25 110

Windows timing is noisy, so results from other platforms are welcome.

Open questions

  • Allowed key types (object or symbol today).
  • Whether the top-level subscribe() should take options.
  • I have not benchmarked a variant that keeps bypass entries in the
    regular structures too.

DivyanshuX9 and others added 2 commits May 24, 2026 21:33
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 <Divyanshu88999@gmail.com>
Copilot AI review requested due to automatic review settings May 29, 2026 21:31
@nodejs-github-bot nodejs-github-bot added c++ Issues and PRs that require attention from people who are familiar with C++. diagnostics_channel Issues and PRs related to the diagnostics_channel module. needs-ci PRs that need a full CI run. labels May 29, 2026
@DivyanshuX9
DivyanshuX9 force-pushed the diag/suppression-als branch from 5b4110a to 8b122c2 Compare May 29, 2026 21:49

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

@DivyanshuX9

DivyanshuX9 commented May 29, 2026 •

Copy link
Copy Markdown
Contributor Author

@BridgeAR @bengl @Qard , I am opening this as a implementation
of #63623. Test file is included. Happy to adjust the API shape
or implementation based on your feedback before CI runs.

Refs: nodejs#63623

Refs: nodejs#63651
Signed-off-by: Divyanshu Sharma <divyanshu88999@gmail.com>
Refs: nodejs#63623

Refs: nodejs#63651
Signed-off-by: Divyanshu Sharma <divyanshu88999@gmail.com>
@DivyanshuX9
DivyanshuX9 force-pushed the diag/suppression-als branch from 8b122c2 to e4aea85 Compare May 29, 2026 22:37
@codecov

codecov Bot commented May 30, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.58454% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.60%. Comparing base (4f6a561) to head (dd80cab).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
lib/diagnostics_channel.js 97.58% 5 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #63651      +/-   ##
==========================================
- Coverage   90.61%   90.60%   -0.01%     
==========================================
  Files         801      801              
  Lines      281134   281305     +171     
  Branches    54275    54323      +48     
==========================================
+ Hits       254737   254867     +130     
- Misses      16578    16592      +14     
- Partials     9819     9846      +27     
Files with missing lines Coverage Δ
lib/diagnostics_channel.js 98.35% <97.58%> (+0.10%) ⬆️

... and 30 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@Qard Qard left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Tests are missing a lot of necessary common.mustCall(fn) wrappers.

Also, it seems like this was just vibe-coded without reviewing the output before submitting the PR. Please ensure it is in a good state and that the test suite and lint passes before submitting.

Comment thread lib/diagnostics_channel.js Resolved
Comment thread src/node_errors.cc Resolved
Signed-off-by: Divyanshu Sharma <divyanshu88999@gmail.com>
Signed-off-by: Divyanshu Sharma <divyanshu88999@gmail.com>
Signed-off-by: Divyanshu Sharma <divyanshu88999@gmail.com>
Comment thread lib/diagnostics_channel.js Resolved
Signed-off-by: Divyanshu Sharma <divyanshu88999@gmail.com>
@DivyanshuX9

DivyanshuX9 commented May 30, 2026 •

Copy link
Copy Markdown
Contributor Author

@Qard , thanks for the detailed review. So far the checklist of what i have fixed in the latest push:

[] Removed the impossible ALS try/catch fallback
[] Removed node_errors.cc changes as you suggested
[] Replaced all IIFE wrappers with plain blocks in tests
[] Added common.mustCall() / common.mustNotCall() to all handlers
[] Ran lint and tests locally , both passing

Ready for re-review and any changes if you want, when you have time please review it.

@DivyanshuX9
DivyanshuX9 force-pushed the diag/suppression-als branch from 0f6e780 to 8fa6fd8 Compare May 30, 2026 12:27
Signed-off-by: Divyanshu Sharma <divyanshu88999@gmail.com>
@DivyanshuX9
DivyanshuX9 force-pushed the diag/suppression-als branch from 8fa6fd8 to b8194af Compare May 30, 2026 12:38
@Qard

Qard commented May 30, 2026

Copy link
Copy Markdown
Member

The node_errors.cc change still seems to be present.

…ove SetImmediate deferral)

Signed-off-by: Divyanshu Sharma <divyanshu88999@gmail.com>
Signed-off-by: Divyanshu Sharma <divyanshu88999@gmail.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated no new comments.

Suppressed comments (7)

doc/api/diagnostics_channel.md:685

  • The changes: entry for channel.bindStore() uses version: REPLACEME. This should be replaced with the actual semver release(s) that will include options.bypassId.
 - v18.19.0
changes:
  - version: REPLACEME
    pr-url: https://github.com/nodejs/node/pull/63651
    description: Added `options.bypassId` parameter.

test/parallel/test-diagnostics-channel-bypass.js:182

  • channel.runStores() does not publish to the channel, so the subscribed handler is never invoked and these assertions will never run. To test bypassed stores, move the assertions into the function passed to runStores() and remove the unnecessary subscribe()/unsubscribe().
  const handler = common.mustCall(() => {
    assert.strictEqual(normalAls.getStore()?.value, 42);
    assert.strictEqual(als.getStore(), undefined);
  });
  ch.subscribe(handler);

test/parallel/test-diagnostics-channel-bypass.js:197

  • These type-validation tests only assert name: 'TypeError'. Most diagnostics_channel tests assert the error code (e.g. ERR_INVALID_ARG_TYPE) to avoid passing on unrelated TypeErrors.
  assert.throws(() => ch.subscribe(() => {}, { bypassId: bad }), {
    name: 'TypeError'
  });

lib/diagnostics_channel.js:317

  • This implementation splits normal subscribers and bypassId subscribers into separate lists and publishes them in two passes, which changes invocation order: all non-bypass subscribers always run before any bypass-enabled subscriber, regardless of subscription order. If subscriber ordering is expected to follow registration order, consider preserving a single ordered list when any bypass subscribers exist (at the cost of an extra per-subscriber branch in the bypass-enabled case).
    // Bypass path, only entered if bypass subscribers exist.
    if (this._bypassSubscribers !== null) {
      const activeKeys = getBypassStorage().getStore();
      const bypassSubscribers = this._bypassSubscribers;
      for (let i = 0; i < bypassSubscribers.length; i++) {

lib/diagnostics_channel.js:793

  • PR description mentions APIs like suppressed() / { subscriberId }, but the code/docs introduce bypass() / { bypassId }. If the final API is bypass, please update the PR description to match so reviewers/users aren't misled.
function bypass(key, fn, thisArg, ...args) {
  validateFunction(fn, 'fn');

  validateBypassKey(key, 'key');

doc/api/diagnostics_channel.md:238

  • The doc YAML front-matter still contains added: REPLACEME. This placeholder should be replaced with the actual version(s) before landing so the docs site and release tooling remain accurate.
<!-- YAML
added: REPLACEME
-->

doc/api/diagnostics_channel.md:570

  • The changes: entry for channel.subscribe() uses version: REPLACEME. This should be replaced with the actual semver release(s) that will include options.bypassId.

This issue also appears on line 681 of the same file.

changes:
  - version: REPLACEME
    pr-url: https://github.com/nodejs/node/pull/63651
    description: Added `options.bypassId` parameter.

@DivyanshuX9
DivyanshuX9 requested a balanced review from Copilot August 12, 2026 15:07

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@DivyanshuX9
DivyanshuX9 requested a balanced review from Copilot September 6, 2026 11:31

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

DivyanshuX9 and others added 2 commits September 6, 2026 17:05
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 <divyanshu88999@gmail.com>
@DivyanshuX9
DivyanshuX9 requested a balanced review from Copilot November 1, 2026 11:40

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Two moderate issues remain unresolved: bindStore() can register the same store in both maps, which double-enters it and leaves it bound after one unbind, and bypass subscribers run after regular ones regardless of subscription order without that ordering being documented.

3 open issues

Review effort: Lite

Comment thread lib/diagnostics_channel.js Resolved
Comment on lines +349 to +364
// Bypass path, only entered if bypass subscribers exist.
if (this._bypassSubscribers != null) {
const activeKeys = getBypassStorage().getStore();
const bypassSubscribers = this._bypassSubscribers;
for (let i = 0; i < bypassSubscribers.length; i++) {
try {
const { handler, bypassId } = bypassSubscribers[i];
if (activeKeys?.has(bypassId)) continue;
handler(data, this.name);
} catch (err) {
process.nextTick(() => {
triggerUncaughtException(err, false);
});
}
}
}
return linkedChannel;
});

function bypass(key, fn, thisArg, ...args) {
DivyanshuX9 and others added 6 commits November 17, 2026 13:16
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: nodejs#63623
Signed-off-by: DivyanshuX9 <divyanshu88999@gmail.com>
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: nodejs#63623
Signed-off-by: DivyanshuX9 <divyanshu88999@gmail.com>
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: nodejs#63623
Signed-off-by: DivyanshuX9 <divyanshu88999@gmail.com>
Signed-off-by: DivyanshuX9 <divyanshu88999@gmail.com>
Add a test that subscribers and stores registered with `bypassId` run
after the regular ones on the same channel, whatever the registration
order, and that bypass entries keep their relative order. This is the
ordering documented for `diagnostics_channel`.

Refs: nodejs#63623
Signed-off-by: DivyanshuX9 <divyanshu88999@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

c++ Issues and PRs that require attention from people who are familiar with C++. diagnostics_channel Issues and PRs related to the diagnostics_channel module. needs-ci PRs that need a full CI run. semver-minor PRs that contain new features and should be released in the next minor version.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants