Skip to content

inspector: isolate Debugger/Runtime state between concurrent CDP clients - #35752

Closed
robobun wants to merge 10 commits into
mainfrom
farm/7d81f41e/inspector-multi-session
Closed

robobun wants to merge 10 commits into
mainfrom
farm/7d81f41e/inspector-multi-session

Conversation

@robobun

@robobun robobun commented Jul 25, 2026 •

Copy link
Copy Markdown
Collaborator

With two clients attached to one inspector.open() server, client B can silently hijack or blind client A: B's Debugger.setBreakpointsActive{active:false} or Debugger.disable stops A's breakpoints, B's Runtime.disable silences A's console stream, B receives A's Debugger.paused / Runtime.consoleAPICalled without ever enabling those domains, and B can read or releaseObject A's Runtime.RemoteObject handles by id. Node gives each WebSocket its own V8InspectorSession and is per-session on every cell of that matrix.

Repro

A: Debugger.enable + setBreakpointByUrl; interval hits it (A.paused = 1)
B: Debugger.setBreakpointsActive{active:false}   // B never enabled Debugger
A: paused count after = 0  (node: still 1)

A: Runtime.evaluate 'globalThis.secretStore' -> objectId {"injectedScriptId":1,"id":34}
B: Runtime.getProperties(objectId) -> alpha = "objA-secret"  (node: "Could not find object with given id")
B: Runtime.releaseObject(objectId)
A: Runtime.getProperties(objectId) -> "Internal error"       (node: still valid)

Cause

Every WebSocket client is a FrontendChannel on the one per-process JSGlobalObjectInspectorController, which owns a single InspectorDebuggerAgent / InspectorRuntimeAgent / InjectedScript. FrontendRouter::sendResponse / sendEvent broadcast to every channel (the // FIXME: send responses to the appropriate frontend in InspectorFrontendRouter.cpp), and dispatchMessageFromRemote carries no sender identity, so every agent's enable flags, breakpoints, breakpointsActive, pauseOnExceptions and RemoteObject id table are process-global across clients.

Fix

The CDP adapter already sits between each WebSocket and the shared JSC backend, so do the per-session scoping there (no WebKit changes):

  • Shared backend command-id counter across adapters, so a broadcast response only matches the sender's #pending map and ids stay within BackendDispatcher's 32-bit int. (Same approach as node:inspector: route CDP responses to the right client when multiple are attached #35701, which this PR subsumes.)
  • Per-adapter debuggerEnabled / runtimeEnabled gating of broadcast events and of inbound Debugger commands (pause/resume/step*/evaluateOnCallFrame reply Debugger agent is not enabled), and refcounted Debugger/Runtime/Console enable so one client's disable does not tear the shared agent down under another. The deprecated Console.enable/disable are acknowledged locally.
  • Per-adapter breakpointsActive / pauseOnExceptions with an aggregate written to the backend only on change; per-adapter breakpoint ownership so removeBreakpoint cannot delete another client's, and breakpointResolved / Debugger.paused.hitBreakpoints are filtered to the owner.
  • Session-tagged objectIds: every outbound RemoteObject.objectId gets a bunSessionId field (skipping RemoteObject.value, which is user JSON under returnByValue); inbound ids without this adapter's tag are rejected with V8's Could not find object with given id, including callFunctionOn arguments[].objectId. objectGroup names are likewise prefixed per session so releaseObjectGroup cannot free another client's handles.
  • dispose() on connection close removes the session's breakpoints and contribution to the aggregates.

Verification

New test two inspector.open() clients have isolated Debugger/Runtime session state drives A's breakpoint before and after B's setBreakpointsActive(false) / removeBreakpoint / Debugger.disable, checks B can't read or release A's objectId via getProperties / callFunctionOn (target or arguments[]) / releaseObject / releaseObjectGroup, checks B's Runtime.disable / Console.disable doesn't silence A, checks B's evaluateOnCallFrame is rejected, and checks returnByValue user JSON with an objectId property round-trips unchanged. Fails on main at the second pause count (Expected: 2, Received: 1), passes with the fix. Full test/js/node/inspector/inspector.test.ts 24/24.


[review] gate passed · iteration 2 · 3 files touched

fails on main (without fix)
ASAN without fix: 1 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/node/inspector/inspector.test.ts
bun test v1.4.0 (72a2623a3)

test/js/node/inspector/inspector.test.ts:
(pass) inspector.url() [9.78ms]
(pass) inspector.console [10.52ms]
(pass) inspector.close() is a no-op when the inspector is not open [5.34ms]
(pass) inspector.waitForDebugger() throws ERR_INSPECTOR_NOT_ACTIVE when the inspector is not active [6.12ms]
(pass) inspector.open() serves the DevTools protocol and /json discovery endpoints [5007.48ms]
(pass) inspector.close() followed by inspector.open() starts a new server [1926.46ms]
(pass) inspector.open() can be retried after a failed start [2128.59ms]
(pass) inspector.open() with wait=true does not hang the process after a bind failure [2067.17ms]
(pass) inspector.waitForDebugger() blocks until a client resumes the process [2551.42ms]
(pass) inspector.waitForDebugger() blocks again on the second call after a frontend disconnects [2396.46ms]
hello 42
after disable
(pass) Runtime.consoleAPICalled is emitted while the Runtime domain is enabled [72.54ms]
-0 NaN Infinity -Infinity 1
... (truncated)

release without fix: all passed
bun test v1.4.0-canary.1 (08b25a85a)

test/js/node/inspector/inspector.test.ts:
(pass) inspector.url() [3.99ms]
(pass) inspector.console [0.17ms]
(pass) inspector.close() is a no-op when the inspector is not open [1.93ms]
(pass) inspector.waitForDebugger() throws ERR_INSPECTOR_NOT_ACTIVE when the inspector is not active [0.23ms]
(pass) inspector.open() serves the DevTools protocol and /json discovery endpoints [900.36ms]
(pass) inspector.close() followed by inspector.open() starts a new server [89.07ms]
(pass) inspector.open() can be retried after a failed start [49.89ms]
(pass) inspector.open() with wait=true does not hang the process after a bind failure [49.48ms]
(pass) inspector.waitForDebugger() blocks until a client resumes the process [69.20ms]
(pass) inspector.waitForDebugger() blocks again on the second call after a frontend disconnects [138.34ms]
hello 42
after disable
(pass) Runtime.consoleAPICalled is emitted while the Runtime domain is enabled [2.78ms]
-0 NaN Infinity -Infinity 1n
(pass) Runtime.consoleAPICalled encodes -0/NaN/Infinity/bigint as unserializableValue like Node [0.18ms]
(pass) Session errors carry Node's ERR_INSPECTOR_* codes and post() va
... (truncated)
passes on PR (with fix)
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/node/inspector/inspector.test.ts
bun test v1.4.0 (72a2623a3)

test/js/node/inspector/inspector.test.ts:
(pass) inspector.url() [9.53ms]
(pass) inspector.console [9.70ms]
(pass) inspector.close() is a no-op when the inspector is not open [5.41ms]
(pass) inspector.waitForDebugger() throws ERR_INSPECTOR_NOT_ACTIVE when the inspector is not active [5.87ms]
(pass) inspector.open() serves the DevTools protocol and /json discovery endpoints [5015.69ms]
(pass) inspector.close() followed by inspector.open() starts a new server [1981.41ms]
(pass) inspector.open() can be retried after a failed start [1932.95ms]
(pass) inspector.open() with wait=true does not hang the process after a bind failure [2041.66ms]
(pass) inspector.waitForDebugger() blocks until a client resumes the process [2826.94ms]
(pass) inspector.waitForDebugger() blocks again on the second call after a frontend disconnects [2227.95ms]
hello 42
after disable
(pass) Runtime.consoleAPICalled is emitted while the Runtime domain is enabled [126.46ms]
-0 NaN Infinity -Infinity 1
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 904ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/21] gen JS modules (bundle-modules)
Preprocess modules (16614ms)
Bundle modules (1111ms)
Postprocesss modules (403ms)
Bundle Functions (2349ms)
Generate Code (715ms)

[21.22s] Bundled "src/js" for production
  2582 kb
  193 internal modules
  13 native modules
  90 internal functions across 19 files
[1/8] cargo bun_bin → libbun_rust.a (--target x86_64-unknown-linux-gnu)

  nightly-2026-07-20-x86_64-unknown-linux-gnu unchanged - rustc 1.99.0-nightly (9f36de775 2026-07-19)

�[1m�[92m   Compiling�[0m bun_core v0.0.0 (/workspace/bun/src/bun_core)
�[1m�[92m   Compiling�[0m bun_errno v0.0.0 (/workspace/bun/src/errno)
�[1m�[92m   Compiling�[0m bun_ptr v0.0.0 (/workspace/bun/src/ptr)
�[1m�[92m   Compiling�[0m bun_boringssl_sys v0.0.0 (/workspace/bun/src/boringssl_sys)
�[1m�[92m   Compiling�[0m bun_safety v0.0.0 (/workspace/bun/src/safety)
�[1m�[92m   Compiling�[0m bun_zlib_sys v0.0.0 (/workspace/bun/src/zlib_sys)
�[1m�[92m   Compiling�[0m bun_cares_sys v0.0.0 (/workspace/bun/src/cares_sys)
�[1m�[92m   Compili
... (truncated)
diff hotspot
src/js/internal/debugger.ts              |  12 +-
 src/js/internal/inspector/cdp.ts         | 439 ++++++++++++++++++++++++++++---
 test/js/node/inspector/inspector.test.ts | 287 +++++++++++++++++++-
 3 files changed, 697 insertions(+), 41 deletions(-)

gate history · 4 passed · 1 rejected · iteration 2

evidence per changed file
file                                      reads  edits  tests
src/js/internal/debugger.ts                   3      7      0
src/js/internal/inspector/cdp.ts             23     54      0
test/js/node/inspector/inspector.test.ts      5     27      0

JSC's JSGlobalObjectInspectorController has a single DebuggerAgent,
RuntimeAgent and InjectedScript, and FrontendRouter broadcasts every
response and event to every attached FrontendChannel. With two clients
attached to one inspector.open() server, client B could flip client A's
breakpointsActive / pauseOnExceptions, Debugger.disable A, delete A's
breakpoints, receive A's Debugger.paused / consoleAPICalled events
without ever enabling those domains, and read or release A's
RemoteObject handles by id. Node gives each WebSocket its own
V8InspectorSession and is per-session on all of these.

The CDP adapter already sits between each WebSocket and the shared
backend, so do the per-session scoping there:

- Per-adapter backend command-id ranges so a broadcast response only
  matches the sender's pending map.
- Per-adapter debuggerEnabled / runtimeEnabled gating of broadcast
  events, and refcounted Debugger/Runtime/Console enable so one
  client's disable does not tear the shared agent down under another.
- Per-adapter breakpointsActive / pauseOnExceptions with an aggregate
  written to the backend only on change, and per-adapter breakpoint
  ownership so removeBreakpoint cannot delete another client's.
- Every outbound RemoteObject.objectId is tagged with the adapter's
  session id; inbound ids without this adapter's tag are rejected with
  V8's 'Could not find object with given id'.
- dispose() on connection close removes the session's breakpoints and
  contribution to the aggregates.
@coderabbitai

coderabbitai Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The CDP adapter now isolates debugger and runtime state across inspector clients, remaps object handles, filters session-specific events, aggregates shared backend settings, and disposes adapters during connection teardown. A two-client integration test covers these behaviors.

Changes

Inspector session isolation

Layer / File(s) Summary
Shared session state and aggregation
src/js/internal/inspector/cdp.ts
Adds shared command identifiers, session tracking, aggregate debugger/runtime state, object-id tagging, and disposal cleanup.
Runtime object and command isolation
src/js/internal/inspector/cdp.ts
Scopes runtime object groups, rejects foreign object ids, remaps handles, and prevents console state changes from affecting other sessions.
Debugger ownership and event filtering
src/js/internal/inspector/cdp.ts
Gates debugger commands, tracks breakpoint ownership, synchronizes shared settings, and filters translated events by session state.
Adapter teardown and isolation validation
src/js/internal/debugger.ts, test/js/node/inspector/inspector.test.ts
Disposes adapters on close, disconnect, and error paths, with an integration test covering two-client isolation.

Possibly related PRs

  • oven-sh/bun#31823: Adds the optional adapter pipeline used by the updated node:inspector teardown paths.
  • oven-sh/bun#34719: Covers related adapter cleanup and CDP session isolation behavior.
  • oven-sh/bun#35717: Refactors the node:inspector session disconnect paths changed here.

Suggested reviewers: cirospaciari, jarred-sumner

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is concise and accurately summarizes the main change: isolating Debugger/Runtime state for concurrent CDP clients.
Description check ✅ Passed The description clearly explains the problem, fix, and verification, covering the required what/how despite using different headings.

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

@github-actions

Copy link
Copy Markdown
Contributor

Found 1 issue this PR may fix:

  1. Debugger randomly pauses at import statements and class declarations showing as "paused at breakpoint" even if there are no breakpoints #20339 - Reporter uses a compound VS Code launch config that starts multiple Bun services simultaneously, causing multiple CDP clients to connect concurrently. The random pauses at non-breakpoint locations (imports, class declarations) are consistent with shared breakpointsActive/pauseOnExceptions state leaking across sessions — exactly the cross-session state pollution this PR fixes.

If this is helpful, copy the block below into the PR description to auto-close this issue on merge.

Fixes #20339

🤖 Generated with Claude Code

@robobun

robobun commented Jul 25, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 11:05 PM PT - Jul 25th, 2026

❌ @robobun, your commit 72a2623 has 1 failures in Build #81669 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 35752

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

bun-35752 --bun

@github-actions

Copy link
Copy Markdown
Contributor

This PR may be a duplicate of:

  1. node:inspector: route CDP responses to the right client when multiple are attached #35701 - Solves the same multi-client CDP response routing problem (shared backend command-id collision). inspector: isolate Debugger/Runtime state between concurrent CDP clients #35752 explicitly subsumes node:inspector: route CDP responses to the right client when multiple are attached #35701, applying the same fix (unique backend command ids) plus additional per-session isolation (breakpoint ownership, objectId tagging, refcounted enable/disable).

🤖 Generated with Claude Code

Comment thread src/js/internal/inspector/cdp.ts Resolved
Comment thread src/js/internal/inspector/cdp.ts Resolved
Comment thread src/js/internal/inspector/cdp.ts Resolved
Comment thread src/js/internal/inspector/cdp.ts Resolved
Comment thread src/js/internal/inspector/cdp.ts Resolved
Comment thread src/js/internal/inspector/cdp.ts Resolved
Comment thread src/js/internal/inspector/cdp.ts Resolved
Comment thread src/js/internal/inspector/cdp.ts Resolved
Comment thread src/js/internal/inspector/cdp.ts Resolved
Comment thread src/js/internal/inspector/cdp.ts Resolved
A foreign-session or untagged objectId in Runtime.callFunctionOn
arguments[] was forwarded to JSC unchanged (InjectedScriptSource.js
ignores extra JSON fields), so client B could still read client A's
RemoteObject via that path. Reject the whole request the same way the
target objectId / getProperties / releaseObject paths already do, and
cover it in the test.

Also drain the debuggee's stderr in the test and include it in the
waitForStdout failure message, matching the sibling tests in this file.
Comment thread src/js/internal/inspector/cdp.ts Resolved
Comment thread src/js/internal/inspector/cdp.ts Resolved
Comment thread src/js/internal/inspector/cdp.ts Resolved

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Additional findings (outside current diff — PR may have been updated during review):

  • 🟡 src/js/internal/inspector/cdp.ts:384-390 — The raw pass-through at cdp.ts:719-724 still forwards Console.disable straight to the shared backend with no anyRuntimeEnabled() guard, so B sending {method:"Console.disable"} stops Console.messageAdded for every FrontendChannel — silencing A's Runtime.consoleAPICalled stream, the exact failure this PR fixes for Runtime.disable. The V8 Console domain is deprecated so real DevTools/vscode-js-debug won't send it, but the PR's threat model is explicitly a buggy/adversarial second client; the same if (anyRuntimeEnabled()) { reply {}; return; } guard belongs on the Console.disable case (or drop the deprecated Console.* pass-through entirely).

    Extended reasoning...

    What the bug is

    The PR adds a refcount guard on Runtime.disable (cdp.ts:384-390) so that when client B disables Runtime, the adapter checks anyRuntimeEnabled() and — if client A still has Runtime enabled — replies {} locally instead of sending Runtime.disable/Console.disable to the single shared JSC backend. But the pre-existing raw pass-through further down in the same switch is left untouched:

    case "Console.enable":
    case "Console.disable":
    case "Console.clearMessages":
    case "Inspector.enable":
      this.#sendToBackend(method, undefined, id, method);
      return;

    So client B can send {method:"Console.disable"} directly and it goes straight to JSC's InspectorConsoleAgent::disable with no per-session gate.

    The specific code path

    JSC's JSGlobalObjectInspectorController owns exactly one InspectorConsoleAgent (the PR description itself states this: "a single InspectorDebuggerAgent / InspectorRuntimeAgent"), and its enable state is a boolean, not a refcount. One Console.disable from any FrontendChannel flips it off, and the agent stops emitting Console.messageAdded to every channel. In #translateBackendEvent, Console.messageAdded is the sole producer of Runtime.consoleAPICalled — there is no other source. So once the backend Console agent is disabled, A stops receiving Runtime.consoleAPICalled even though A.#flags.runtimeEnabled is still true.

    Why existing code doesn't prevent it

    The new adapter-side event gate in #translateBackendEvent (if (!this.#flags.runtimeEnabled) return) filters events arriving from the backend per session; it can't help when the backend has stopped emitting them entirely. The anyRuntimeEnabled() refcount was added precisely to keep the backend Console agent alive while any session wants it — but only on the Runtime.disable path, not on the direct Console.disable sibling that reaches the same backend agent.

    Step-by-step proof

    1. Client A connects → adapter A, sessionId=1, #flags.runtimeEnabled=false.
    2. Client B connects → adapter B, sessionId=2, #flags.runtimeEnabled=false.
    3. A sends Runtime.enable → A's adapter sets A.#flags.runtimeEnabled=true and sends Runtime.enable + Console.enable to the backend. JSC's ConsoleAgent is now enabled.
    4. Debuggee runs console.log("x") → backend emits Console.messageAdded to both FrontendChannels → A's #translateBackendEvent sees runtimeEnabled=true, translates to Runtime.consoleAPICalled, A receives it. ✅
    5. B sends {id:1, method:"Console.disable"} → B's adapter hits case "Console.disable": at line 720 → this.#sendToBackend("Console.disable", undefined, 1, "Console.disable") — no anyRuntimeEnabled() check. JSC's ConsoleAgent flips to disabled.
    6. Debuggee runs console.log("y") → ConsoleAgent is disabled → no Console.messageAdded is emitted to any channel.
    7. A's #translateBackendEvent never runs; A never receives Runtime.consoleAPICalled for "y". A's #flags.runtimeEnabled is still true, so the adapter-side filter is irrelevant — the events simply stopped arriving.

    This is exactly the failure the PR description lists ("B's Runtime.disable silences A's console stream") reachable via a sibling entry point the fix left unguarded.

    Impact

    The V8 CDP Console domain is deprecated and Chrome DevTools / vscode-js-debug do not send Console.disable, so this won't fire in normal multi-client use. But the PR's stated threat model is per-session isolation regardless of what B sends — it already defends against B guessing raw backend objectIds (FOREIGN_OBJECT_ID_ERROR) and B calling Debugger.disable/removeBreakpoint without ever having enabled Debugger. A one-message bypass of the console-stream isolation via a documented (if deprecated) method leaves the class incompletely fixed. REVIEW.md: "Fix the whole class in the same PR — grep for every sibling site sharing the pattern."

    How to fix

    Either add the same guard the Runtime.disable case has:

    case "Console.disable":
      if (anyRuntimeEnabled()) {
        this.#replyToClient(id, {});
        return;
      }
      this.#sendToBackend(method, undefined, id, method);
      return;

    or, since Runtime.enable/Runtime.disable already manage the backend Console agent's lifecycle and no CDP client relies on the deprecated Console domain, drop the Console.enable/Console.disable pass-through cases entirely and reply {} locally (leaving Console.clearMessages as the only one that still needs to reach the backend, if at all).

Comment thread src/js/internal/inspector/cdp.ts Resolved
Comment thread src/js/internal/inspector/cdp.ts Resolved
Comment thread src/js/internal/inspector/cdp.ts Resolved
Comment thread src/js/internal/inspector/cdp.ts Resolved
…isolation gaps

- Backend command ids: replace per-session 1e9 stride with a single shared
  counter. JSC's BackendDispatcher reads the request id via
  JSON::Value::asInteger() into a 32-bit int, so session 3 at id 3e9
  overflowed and every command from the third+ connection hung with no
  reply.
- tagObjectIds: skip RemoteObject.value (arbitrary user JSON under
  returnByValue:true) and only rewrite strings with JSC's fixed
  {"injectedScriptId": prefix, so a user property named objectId is
  not mutated.
- objectGroup names are prefixed per session so one client's
  Runtime.releaseObjectGroup cannot free another's handles.
- The deprecated Console.enable/disable are acknowledged locally instead
  of reaching the shared ConsoleAgent.
- Debugger.pause/resume/step*/continueToLocation/getScriptSource and
  evaluateOnCallFrame are rejected with 'Debugger agent is not enabled'
  when this session has not enabled Debugger.
- Debugger.breakpointResolved and Debugger.paused.hitBreakpoints are
  filtered to the breakpoint's owning session.
- Test: wire ws close/error and proc.exited to reject pending sends;
  add coverage for callFunctionOn arguments, releaseObjectGroup,
  Console.disable, evaluateOnCallFrame gating, and returnByValue
  round-trip of user objectId properties.
Comment thread src/js/internal/inspector/cdp.ts Resolved
Comment thread src/js/internal/inspector/cdp.ts Resolved
Comment thread src/js/internal/inspector/cdp.ts Resolved
Comment thread src/js/internal/inspector/cdp.ts Resolved
@robobun

robobun commented Jul 25, 2026

Copy link
Copy Markdown
Collaborator Author

On the bot suggestions:

CI on 1330ddd failed only on test-fastutf8stream-reopen.js (alpine aarch64, marked flaky), which is unrelated to this diff.

Comment thread src/js/internal/inspector/cdp.ts Resolved
Comment thread src/js/internal/inspector/cdp.ts Resolved
…per-session enable; preserve omitted objectGroup

A never-enabled session could still set a breakpoint on the shared
agent (enabled by another session), have it recorded as owner, then
never see the pause and leave it orphaned on disconnect since
teardownDebuggerState early-returns when debuggerEnabled is false.
Reject these with V8's 'Debugger agent is not enabled' like the
already-gated sibling commands.

sessionObjectGroup now returns undefined for a non-string name so
JSON.stringify omits the key and JSC keeps its 'not in any group'
semantics for evaluations that omit objectGroup.
Comment thread src/js/internal/inspector/cdp.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 7

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/js/internal/debugger.ts`:
- Around line 609-615: Update `#error` to fully tear down the connection state
after logging the error: dispose the adapter, close or terminate the
websocket/backend, and clear data.adapter and data.backend so later frames
cannot reach handleClientMessage on the disposed session.

In `@src/js/internal/inspector/cdp.ts`:
- Around line 618-630: Gate the `Debugger.setBreakpointsActive` and
`Debugger.setPauseOnExceptions` cases on `debuggerEnabled` before mutating flags
or syncing the backend aggregate. When the domain is disabled, reject with the
existing “Debugger agent is not enabled” response path; otherwise preserve the
current state updates and successful replies.
- Around line 632-643: Update the Debugger.removeBreakpoint handling to forward
removal requests to the backend only when breakpointOwner.$get(breakpointId)
equals this.#sessionId. Treat both undefined owners and foreign owners as no-ops
by replying with an empty result and returning, while preserving deletion and
forwarding for breakpoints owned by the current session.

In `@test/js/node/inspector/inspector.test.ts`:
- Around line 1171-1188: Capture the responses from B.send calls for
Debugger.setBreakpointsActive, Debugger.setPauseOnExceptions,
Debugger.removeBreakpoint, and Debugger.disable, then assert each response
reports the adapter’s “Debugger agent is not enabled” error semantics, matching
the existing bEval assertion. Keep the existing pause-count and event assertions
unchanged.
- Around line 1258-1264: Update the test cleanup around proc.exited and
stderrDrained so stderr is always drained before evaluating the child’s exit
result. Await stderrDrained first, then assert the exit code together with the
collected stderr using the test’s combined failure output, preserving the
existing timeout and shutdown flow.
- Around line 1092-1093: Update the inspector startup wait in the URL extraction
flow to wait for the complete URL line, including its terminating newline,
before matching with the existing URL regex. Keep the wsUrl extraction unchanged
after waitForStdout has confirmed the full line is available.
- Around line 1137-1139: Update the WebSocket handlers in the attach flow to
track whether the socket has opened; when onclose fires before onopen,
explicitly reject the attach promise with a diagnostic error before abandoning
the client, while preserving the existing post-open abandon behavior and error
handling.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: f3996111-ffb5-474f-89bc-cae74dacf6d5

📥 Commits

Reviewing files that changed from the base of the PR and between df6c7ee and af874e0.

📒 Files selected for processing (3)
  • src/js/internal/debugger.ts
  • src/js/internal/inspector/cdp.ts
  • test/js/node/inspector/inspector.test.ts

Comment thread src/js/internal/debugger.ts Resolved
Comment thread src/js/internal/inspector/cdp.ts Resolved
Comment thread src/js/internal/inspector/cdp.ts Resolved
…removeBreakpoint owner check, clear connection data on error/close; test diagnostics

- setBreakpointsActive / setPauseOnExceptions / removeBreakpoint now reject
  with 'Debugger agent is not enabled' when the session has not enabled
  Debugger, matching the already-gated sibling commands. removeBreakpoint
  only forwards ids this session owns.
- debugger.ts #close / #error clear data.adapter / data.backend after
  disposing so a later frame on the same socket cannot dispatch to a
  disposed session.
- Test: wait for the full URL line before matching; reject the attach
  promise if the socket closes before open; assert B's Debugger config
  commands are rejected; await stderr drain before asserting the exit
  code and include stderr in the failure diff.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Additional findings (outside current diff — PR may have been updated during review):

  • 🟡 src/js/internal/inspector/cdp.ts:924-928 — The new owner filter at line 926 hides A's breakpoint id from B's hitBreakpoints, but three lines above cdpParams is built with data passed through — and for reason: "Breakpoint" JSC's data is exactly {breakpointId: <id>}, so B still receives A's id via params.data.breakpointId. V8 doesn't populate data for breakpoint pauses at all, so setting cdpParams.data = undefined in the "Breakpoint" arm both closes the leak and improves CDP fidelity. Impact is minimal (B can't act on the id — removeBreakpoint is owner-gated), so nit.

    Extended reasoning...

    What the gap is

    Commit 1e1f3d9 added per-session ownership filtering to Debugger.paused in response to the earlier review comment ("gate breakpoint events on breakpointOwner.$get(id) === this.#sessionId"):

    case "Breakpoint": {
      const hitId = data?.breakpointId;
      if (hitId && breakpointOwner.$get(hitId) === this.#sessionId) cdpParams.hitBreakpoints = [hitId];
      break;
    }

    but three lines above this, cdpParams is initialized as:

    const { data, asyncStackTrace } = params;
    const cdpParams: AnyObject = { callFrames, reason: "other", data };

    For reason: "Breakpoint", JSC's raw pause payload data is exactly {breakpointId: <id>} (that's why line 925 reads data?.breakpointId). The owner check only governs whether the hitBreakpoints key is added; it never strips the data field. So the same datum the filter was added to hide is still emitted one property over.

    Step-by-step proof

    1. Client A: Debugger.enable, setBreakpointByUrl → breakpointOwner.$set(bpId, A.#sessionId).
    2. Client B: Debugger.enable → B.#flags.debuggerEnabled = true.
    3. Debuggee hits A's breakpoint. JSC broadcasts Debugger.paused with {reason: "Breakpoint", data: {breakpointId: bpId}, callFrames: [...]} to every FrontendChannel.
    4. B's adapter enters #translateBackendEvent. Line 869 gate passes (B.#flags.debuggerEnabled === true).
    5. Line 916: cdpParams = { callFrames, reason: "other", data: {breakpointId: bpId} }.
    6. Line 924–927: hitId = bpId; breakpointOwner.$get(bpId) === A.#sessionId ≠ B.#sessionId → hitBreakpoints is not added. ✓
    7. Line 931: B receives {method: "Debugger.paused", params: {callFrames, reason: "other", data: {breakpointId: bpId}}} — A's id is in params.data.breakpointId.

    Why existing code doesn't prevent it

    The data passthrough at line 916 is pre-existing and untouched by the diff; the ownership check at line 926 only adds/omits a sibling key; tagObjectIds (line 901) doesn't touch breakpointId (only keys named objectId). Nothing else in the "Breakpoint" arm reads or clears cdpParams.data.

    Impact — why nit

    B cannot act on the leaked id: Debugger.removeBreakpoint is owner-gated at cdp.ts:632–636, and real CDP clients (Chrome DevTools, vscode-js-debug) correlate on hitBreakpoints[], not the non-standard data field. The scenario also requires B to have Debugger enabled, in which case B legitimately shares the pause and receives the full callFrames anyway. So this is an opaque-string information leak with no functional consequence — but it is the same class as the hitBreakpoints/breakpointResolved filtering this PR added in this exact switch arm (REVIEW.md: "Fix the whole class in the same PR … parallel switch arms"), and V8 does not populate data for plain breakpoint pauses, so it's also a minor Node-compat divergence.

    Fix

    In the "Breakpoint" arm, drop data (matches V8):

    case "Breakpoint": {
      const hitId = data?.breakpointId;
      if (hitId && breakpointOwner.$get(hitId) === this.#sessionId) cdpParams.hitBreakpoints = [hitId];
      cdpParams.data = undefined;
      break;
    }

    or, minimally, only when the owner check fails.

Comment thread src/js/internal/inspector/cdp.ts Resolved
Comment thread src/js/internal/inspector/cdp.ts Resolved
…se, drop paused.data for breakpoint pauses

- setAsyncCallStackDepth is stored per session and the max across
  debugger-enabled sessions is written to the backend, matching the
  breakpointsActive / pauseOnExceptions aggregates and V8's per-agent
  max.
- dispose() releases every session-prefixed objectGroup the adapter
  issued so a closed client's wrapped values are not pinned in the
  shared InjectedScript while another client remains attached.
- Debugger.paused for reason Breakpoint drops the JSC data:{breakpointId}
  field; V8 does not populate data for breakpoint pauses and the
  owner-filtered hitBreakpoints already carries the id for the owning
  session.
Comment thread src/js/internal/inspector/cdp.ts Resolved

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Additional findings (outside current diff — PR may have been updated during review):

  • 🟡 src/js/internal/inspector/cdp.ts:776-781 — Console.clearMessages is still forwarded verbatim to the shared backend, unlike the sibling Console.enable/Console.disable arms this PR just converted to local no-ops ("forwarding disable here would let one client tear the shared ConsoleAgent down under another"). JSC's InspectorConsoleAgent::clearMessages() calls m_injectedScriptManager.releaseObjectGroup("console"), which frees the raw backend ids that were session-tagged and delivered to A via Runtime.consoleAPICalled — so B (never enabled Runtime) can invalidate A's console-argument RemoteObjects, bypassing the releaseObject/releaseObjectGroup isolation. The CDP equivalent Runtime.discardConsoleEntries is already a local no-op below; move Console.clearMessages into the same local-ack block two lines up.

    Extended reasoning...

    What the gap is

    This PR split the fall-through group at cdp.ts:776-783: before, Console.enable / Console.disable / Console.clearMessages / Inspector.enable all forwarded to the backend together. The PR moved Console.enable/Console.disable into a local-ack block with the comment "forwarding disable here would let one client tear the shared ConsoleAgent down under another", but left Console.clearMessages in the forwarding arm with no per-session gate:

    case "Console.enable":
    case "Console.disable":
      this.#replyToClient(id, {});
      return;
    
    case "Console.clearMessages":       // ← still forwarded ungated
    case "Inspector.enable":
      this.#sendToBackend(method, undefined, id, method);
      return;

    WebKit's InspectorConsoleAgent::clearMessages() clears m_consoleMessages and calls m_injectedScriptManager.releaseObjectGroup("console"_s). Every object argument to console.log is wrapped by ConsoleMessage::addToFrontend via injectedScript.wrapObject(arg, "console"_s, ...) — the raw, unprefixed group name — before the resulting Console.messageAdded is broadcast to every FrontendChannel. So clearMessages releases exactly the backend ids that A received (session-tagged) in Runtime.consoleAPICalled.args[].objectId.

    Why existing code doesn't prevent it

    The PR's releaseObject guard checks the bunSessionId tag on inbound objectIds, and releaseObjectGroup prefixes the client-supplied group name with bun-session-<N>:. Neither touches this route: Console.clearMessages takes no objectId and no objectGroup parameter — the "console" group name is hard-coded on the JSC side, and #sessionObjectGroup() only rewrites client-supplied group names on inbound evaluate/callFunctionOn/releaseObjectGroup; it cannot rewrite what JSC uses internally when wrapping console-message arguments. There is no runtimeEnabled gate on this arm either, so B need never have enabled anything.

    Step-by-step proof

    1. A sends Runtime.enable. Debuggee runs console.log({secret:1}). JSC's ConsoleMessage::addToFrontend wraps the argument in objectGroup "console", minting raw id {"injectedScriptId":1,"id":N}, and broadcasts Console.messageAdded to every FrontendChannel.
    2. A's adapter (#translateBackendEvent → Console.messageAdded arm) calls tagObjectIds(params, A.#sessionId) and emits Runtime.consoleAPICalled with args[0].objectId = '{"bunSessionId":<A>,"injectedScriptId":1,"id":N}'. A now holds a valid session-tagged handle whose backing entry lives in the process-global InjectedScript under group "console".
    3. B (never enabled Runtime, never enabled Debugger) sends {"method":"Console.clearMessages"}. The Console.clearMessages arm at cdp.ts:781 forwards it verbatim to the shared backend. InspectorConsoleAgent::clearMessages() runs releaseObjectGroup("console"), freeing raw id N.
    4. A sends Runtime.getProperties({objectId}). untagObjectId strips A's bunSessionId tag → {"injectedScriptId":1,"id":N}, which is forwarded to JSC. JSC replies with an error (object not found). B has invalidated A's RemoteObject via a route the PR's releaseObject/releaseObjectGroup isolation doesn't cover.

    Impact and severity

    This is exactly the "one client tears down another's shared-agent state" class the adjacent Console.disable change and the releaseObject/releaseObjectGroup rewriting exist to prevent, and REVIEW.md explicitly names "parallel switch arms" as same-class sites to fix in the same PR. That said, exposure is narrow: the CDP Console domain is deprecated (V8 documents Console.clearMessages as "Does nothing"), and real clients (Chrome DevTools, vscode-js-debug) send Runtime.discardConsoleEntries instead — which is already stubbed as a local no-op at cdp.ts:796. Impact is limited to console-argument handles, and comparable same-class gaps in this PR (setAsyncCallStackDepth, dispose-time object groups) are already tracked at nit.

    Fix

    Move the case up two lines into the local-ack block:

    case "Console.enable":
    case "Console.disable":
    case "Console.clearMessages":
      this.#replyToClient(id, {});
      return;
    
    case "Inspector.enable":
      this.#sendToBackend(method, undefined, id, method);
      return;

    This matches the treatment of Runtime.discardConsoleEntries (its non-deprecated CDP equivalent) 15 lines below.

  • 🟡 src/js/internal/inspector/cdp.ts:825-833 — #forwardBreakpointResult records breakpointOwner.$set(breakpointId, this.#sessionId) unconditionally, so a setBreakpoint* response that arrives after this session has already run #teardownDebuggerState() (pipelined Debugger.disable or WS close mid-flight, while another client keeps Debugger enabled) records ownership for a dead session — the later dispose() early-returns on !debuggerEnabled and never sweeps it, leaving the surviving client paused on a breakpoint it can neither remove (owner check fails) nor re-set (JSC's "already exists"). Guard here on !this.#flags.debuggerEnabled || !liveAdapters.$has(this.#sessionId) and send Debugger.removeBreakpoint({breakpointId}) to the backend instead of recording ownership.

    Extended reasoning...

    What the bug is

    #forwardBreakpointResult (cdp.ts:825–833) is the onResult callback for Debugger.setBreakpointByUrl / Debugger.setBreakpoint. On a successful backend response it does:

    if (typeof breakpointId === "string") breakpointOwner.$set(breakpointId, this.#sessionId);

    with no check that the session is still debugger-enabled or still in liveAdapters. Backend dispatch is cross-thread async (BunDebugger.cpp: sendMessageToInspectorFromDebuggerThread queues to the inspected thread via postTaskConcurrently; the response returns via a posted task on the debugger thread), so a client that pipelines two frames — setBreakpointByUrl followed immediately by Debugger.disable — or whose socket closes between send and response, will have #teardownDebuggerState() run before the setBreakpoint response lands. When it later lands, ownership is recorded for a session whose teardown has already run and will never run again for this breakpoint.

    Step-by-step trace

    Two sessions A and B both Debugger.enable. A sends setBreakpointByUrl and, without awaiting, immediately sends Debugger.disable (or A's WebSocket closes right after the send). On the debugger thread:

    1. setBreakpointByUrl handler runs → #sendToBackend(..., onResult=#forwardBreakpointResult); entry queued in A's #pending. The command is posted to the inspected thread.
    2. Debugger.disable handler (or #close → dispose()) runs → #teardownDebuggerState(). It iterates breakpointOwner — X is not there yet (response still pending) — removes nothing, sets A.#flags.debuggerEnabled = false. anyDebuggerEnabled() is still true (B is enabled), so Debugger.disable is NOT sent to the backend (cdp.ts:337).
    3. The backend response for setBreakpointByUrl arrives → handleBackendMessage finds A's #pending entry → #forwardBreakpointResult → breakpointOwner[X] = A.#sessionId. (In the WS-close variant, data.adapter is now undefined so no more client frames reach A, but the receive closure in debugger.ts #open captured adapter by local — the callback still fires.)
    4. A's WebSocket closes → dispose() → #teardownDebuggerState() early-returns at cdp.ts:324 because !this.#flags.debuggerEnabled. Then sessionFlags.$delete(A), liveAdapters.$delete(A) — breakpointOwner[X] survives, keyed to a monotonic session id no future adapter can ever match.

    Why nothing catches it

    • #teardownDebuggerState() sweeps breakpointOwner only for entries that already exist and only when debuggerEnabled is still true — neither holds after step 2.
    • dispose() does no unconditional breakpointOwner sweep and does not clear #pending, so late onResult callbacks still run.
    • Debugger.removeBreakpoint (cdp.ts:643) now requires breakpointOwner.$get(breakpointId) === this.#sessionId, so B's remove is a silent no-op.
    • B's own setBreakpointByUrl at that location fails with JSC's "Breakpoint at specified location already exists".
    • Debugger.paused on X reaches B (B is debugger-enabled) with hitBreakpoints omitted (owner ≠ B at cdp.ts:937), so B doesn't even know which breakpoint is stopping it.

    Impact

    The debuggee pauses on an unremovable breakpoint every time X's location is hit until every debugger-enabled client disconnects (only then does the last #teardownDebuggerState() send Debugger.disable to the backend, which JSC clears). This is a regression window opened by the ownership map: pre-PR, Debugger.disable forwarded straight to JSC (clearing all breakpoints) and removeBreakpoint had no owner gate, so either path would have reclaimed X. Node avoids this because V8DebuggerAgentImpl::disable() clears that session's breakpoints synchronously per-session.

    The trigger is narrow — well-behaved DevTools/vscode-js-debug await responses, so it takes a client that pipelines set+disable or crashes/closes mid-flight while another debugger-enabled client is attached — hence nit rather than blocking. But it's a genuine gap in the new state machine and directly in scope for this PR's isolation contract (REVIEW.md: every error/abort path actively completes the operation).

    Fix

    At the top of #forwardBreakpointResult's success branch:

    const { breakpointId } = result;
    if (typeof breakpointId === "string") {
      if (!this.#flags.debuggerEnabled || !liveAdapters.$has(this.#sessionId)) {
        // Session tore down while this setBreakpoint was in flight; the shared
        // backend was not disabled (another session holds it), so remove the
        // breakpoint we just armed instead of orphaning it under a dead owner.
        this.#sendToBackend("Debugger.removeBreakpoint", { breakpointId });
        return;
      }
      breakpointOwner.$set(breakpointId, this.#sessionId);
    }

    Alternatively (or additionally), have dispose() unconditionally sweep breakpointOwner for owner === this.#sessionId regardless of debuggerEnabled, and clear #pending so late onResult callbacks don't run.

…give child-spawning tests ASAN headroom

- Console.clearMessages releases JSC's internal "console" objectGroup
  (the raw backend ids A received as console-argument handles), so
  acknowledge it locally alongside Console.enable/disable instead of
  forwarding to the shared agent. Matches Runtime.discardConsoleEntries.
- A setBreakpoint* response that arrives after this session already tore
  down Debugger (pipelined disable or socket close while another session
  keeps the backend enabled) would record a dead owner the teardown path
  can no longer sweep; remove the breakpoint from the backend instead.
- The existing child-spawning tests in this file run 3-5s on an ASAN
  build and flake at the 5s default under load; give them the same
  20s headroom as the first test's 30s.
Comment thread src/js/internal/inspector/cdp.ts Resolved
Comment thread src/js/internal/inspector/cdp.ts Resolved
Comment thread src/js/internal/inspector/cdp.ts Resolved
@robobun

robobun commented Jul 25, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI status across the four builds on this branch: test/js/node/inspector/inspector.test.ts is green on every lane in every run. The only red lanes have been unrelated tests marked [flaky], a different one each build:

  • #81139: test-fastutf8stream-reopen.js (alpine aarch64)
  • #81439: test-http-server-connections-checking-leak.js (alpine x64)
  • #81669: test/cli/run/no-orphans.test.ts (darwin x64)

All three reported to main-break triage. The diff is green on everything it touches; needs a maintainer to merge.

Comment thread src/js/internal/inspector/cdp.ts Resolved
…xceptions states

A 1e400 maxDepth parses to Infinity and would poison the max-aggregate
(JSON.stringify emits depth:null, JSC rejects it silently, and the
cached backendAggregate.asyncCallStackDepth stays at Infinity so no
later depth ever re-syncs). Number.isFinite + |0 matches V8's integer
parameter. An off-enum pauseOnExceptions state now replies -32602 as
JSC/V8 did before the value moved into adapter storage.
Comment thread src/js/internal/inspector/cdp.ts Resolved
…th-enabled aggregate/ownership

The torn-down guard returned without settling the client's setBreakpoint
request id. Reply with the translated result before returning.

Test: after the never-enabled block, B enables Debugger and sends
setBreakpointsActive(false) and removeBreakpoint on A's id, then A's
breakpoint still fires. This exercises aggregateBreakpointsActive with
two enabled sessions and the removeBreakpoint owner-mismatch branch.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

No further issues found after 72a2623 — all six earlier findings (asyncCallStackDepth aggregation, dispose() object-group release, late setBreakpoint result guard + reply, maxDepth/state validation, both-enabled test coverage) are addressed. Deferring to a human because this adds ~440 lines of new stateful per-session emulation to cdp.ts (module-level sessionFlags/breakpointOwner/backendAggregate, refcounted enable/disable, recursive tagObjectIds with a RemoteObject heuristic) and that design choice — scoping sessions at the JS adapter layer rather than in the backend — is worth a maintainer's sign-off.

What was reviewed:

  • tagObjectIds skipping RemoteObject.value so returnByValue user JSON round-trips — covered by test; the typeof obj.type === "string" heuristic matches JSC's RemoteObject shape.
  • dispose() ordering vs backend.close() in debugger.ts #close/#error — dispose runs first while #writeToBackend is still live, so the removeBreakpoint/releaseObjectGroup sends land.
  • Debugger.enable unconditionally forcing backendAggregate.breakpointsActive = true — correct, since the enabling session's default is true and the aggregate is OR.
  • Runtime.disable from a never-enabled session — flag was already false, anyRuntimeEnabled() sees the other session, backend Console stays up.
Extended reasoning...

Overview

Three files: src/js/internal/inspector/cdp.ts (+~440 lines: module-level session registry, per-adapter SessionFlags, three aggregate functions, tagObjectIds/untagObjectId, #sessionObjectGroup, dispose()/#teardownDebuggerState()/#syncBackendAggregate(), #forwardBreakpointResult, and per-command debuggerEnabled gates), src/js/internal/debugger.ts (+12: call adapter.dispose() before backend.close() on WS close/error and on the in-process Session control-channel close/disconnect), and test/js/node/inspector/inspector.test.ts (+276: one large multi-client end-to-end test plus timeout bumps on existing subprocess tests).

Security risks

The PR closes a cross-session information leak (client B reading client A's RemoteObject handles / paused frames). The objectId session tag is not a security boundary in the cryptographic sense — a client can still forge {"bunSessionId":N,...} for any N — but that matches Node/V8, where objectIds are opaque per-session but not authenticated across sessions on the same process; the isolation here is against accidental cross-talk from well-behaved DevTools clients, not adversarial ones on the same debug port. No new network-facing surface; the WS server, Host/Origin checks, and upgrade path are unchanged.

Level of scrutiny

Medium-high. This is developer-tooling (node:inspector), not a production hot path, and the failure mode is a degraded debugging experience rather than data corruption. But the change is large, introduces module-level mutable state whose correctness rests on the "all adapters run on the one debugger thread" invariant, and the tagObjectIds recursive walker mutates backend payloads in place using typeof obj.type === "string" as the RemoteObject heuristic to avoid descending into user returnByValue JSON. Both are well-commented and tested, but they're the kind of thing a maintainer familiar with the JSC inspector plumbing should confirm.

Other factors

The PR has been through five fix commits addressing every prior automated finding, all threads are resolved, CI on the previous commit was green except an unrelated flaky, and the mechgate evidence shows the new test fails on main and passes on the branch under both debug/ASAN and release. The remaining reason to defer is scope/design, not any known defect.

@github-actions

Copy link
Copy Markdown
Contributor

Closing this PR because it has been inactive for more than 90 days.

@github-actions github-actions Bot closed this Oct 25, 2026
@robobun

robobun commented Oct 25, 2026

Copy link
Copy Markdown
Collaborator Author

The stale sweep closed this PR. No maintainer reviewed it. I do not plan to reopen it. A design review of the alternatives found that this PR puts the fix in the wrong layer. The PR also leaves a common case broken.

What this PR does not fix

  • A second client that attaches and closes, and sends no command, disables the Debugger of the first client. In a probe on main, client A gets 7 breakpoint pauses in 1.5 s before client B attaches. After B closes, A gets 0. This happens in 3 of 3 runs. Node v26.3.0 gets 7 and 7.
  • The cause is in JSC. JSGlobalObjectInspectorController::disconnectFrontend calls m_agents.willDestroyFrontendAndBackend() on each disconnect, before it removes the channel (line 153). This PR changed only JS files (cdp.ts, debugger.ts), so it does not change that teardown. Its adapter state still says that the survivor is enabled. Its test closes the two clients only at the end, so the test does not show the problem.
  • Raw bun --inspect clients do not pass through cdp.ts. They attach to the same controller. In a second probe, a raw client that sent nothing received the reply to the other client's Runtime.evaluate in 10 of 10 rounds.
  • Each lone CDP client pays for a walk of each backend reply, to tag object ids.

The two probes ran on the release build at 367d939. The inspector sources on main (179664e) differ from that build only in type annotations. I did not run this PR's branch against the first probe. That statement comes from the code path above.

Probe
// bun probe.mjs  (or: node probe.mjs)
import { spawn } from "node:child_process";
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
const src = ['// debuggee','import inspector from "node:inspector";','inspector.open(0, "127.0.0.1");',
  'process.stdout.write("URL " + inspector.url() + "\\n");','globalThis.secretStore = { alpha: "objA-secret" };',
  'globalThis.hitme = function hitme(x) {','  const local = "frame-local-" + x;','  return local;','};',
  'let n = 0;','setInterval(() => { globalThis.hitme(++n); }, 200);'].join("\n");
const dir = mkdtempSync(join(tmpdir(), "cdpidle-"));
writeFileSync(join(dir, "debuggee3350.mjs"), src);
const child = spawn(process.execPath, [join(dir, "debuggee3350.mjs")], { stdio: ["ignore", "pipe", "ignore"] });
let out = ""; child.stdout.on("data", d => (out += d));
const url = await new Promise(r => { const iv = setInterval(() => { const m = /URL (\S+)/.exec(out); if (m) { clearInterval(iv); r(m[1]); } }, 20); });
const sleep = ms => new Promise(r => setTimeout(r, ms));
let pauses = 0;
const attach = () => new Promise(res => { const ws = new WebSocket(url); const c = { ws, byId: new Map() };
  ws.onmessage = e => { const m = JSON.parse(String(e.data));
    if (m.id !== undefined) c.byId.set(m.id, m);
    else if (m.method === "Debugger.paused") { pauses++; ws.send(JSON.stringify({ id: 100000 + pauses, method: "Debugger.resume" })); } };
  ws.onopen = () => res(c); });
const cmd = async (c, id, method, params = {}) => { c.ws.send(JSON.stringify({ id, method, params }));
  for (let i = 0; i < 300; i++) { if (c.byId.has(id)) return c.byId.get(id); await sleep(10); } return { timeout: true }; };
const A = await attach();
await cmd(A, 1, "Debugger.enable");
await cmd(A, 2, "Debugger.setBreakpointByUrl", { lineNumber: 6, urlRegex: "debuggee3350\\.mjs$" });
pauses = 0; await sleep(1500); const before = pauses;
const B = await attach(); B.ws.close(); await sleep(300);
pauses = 0; await sleep(1500); const after = pauses;
console.log(`A's breakpoint pauses in 1.5s before B: ${before}; after B attached and closed without sending anything: ${after}`);
child.kill("SIGKILL");
process.exit(0);
bun:  A's breakpoint pauses in 1.5s before B: 7; after B attached and closed without sending anything: 0
node: A's breakpoint pauses in 1.5s before B: 7; after B attached and closed without sending anything: 7

Where the fix can live

The sizes are estimates from the review. No option is built yet.

Option Layer What it covers Size
1. One inspector session for each frontend channel JSC in oven-sh/WebKit. BunDebugger.cpp passes the sender. CDP clients, raw --inspect clients, the in-process inspector.Session, and the inspector domains that Bun adds about 40 files in two repos
2. A sender token through dispatch JSC in oven-sh/WebKit Addressed replies, teardown only on the last disconnect, and handles and breakpoints per channel, for all clients. Each agent method must check the sender. about 600 JSC lines
3. Session mux for each connection BunDebugger.cpp only Routing, event fan-out and teardown. It mirrors JSC state by hand, and it fixes the problem only in part. 1,500 to 2,000 lines
4. Session emulation in the CDP adapter (this PR) cdp.ts CDP clients, while both stay attached 738 lines

The review picked option 1. Node works this way: one V8InspectorSession for each client, over one shared V8Debugger. By code reading, option 1 adds no allocation per command for a lone client. That is not measured yet.

Decision needed from a maintainer

Will the oven-sh/WebKit fork take a per-frontend inspector session? The change adds session files. It edits the controller, InspectorDebuggerAgent and Debugger.cpp. Bun then needs a WEBKIT_VERSION bump.

  • If yes, I build option 1. The fork PR comes first, then the Bun half.
  • If the fork can take only a small change, I build option 2.
  • If the fork must not change, I build option 3.

Notes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants