From 4f188b5fad2bf634f833e8d68a04c4eee85f3d64 Mon Sep 17 00:00:00 2001 From: JF Date: Sun, 15 Nov 2026 20:36:52 -0500 Subject: [PATCH 01/24] chore(javascript): the function-breakpoint bridge's source holds no raw NUL byte The key that tells two function breakpoints apart joins a name and a condition with a NUL character, and the source had the character itself in a template literal. Git treated the file as binary (no diff, no blame), and text tools refused to edit it. The separator is now written as an escape. It is the same character at run time, so nothing about the keys changes; the existing keyed cases pin that, and a new case reads the source and fails on a raw NUL. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn69pXrYMWc1JUwv5v8 --- src/proxy/cdp-function-breakpoint-bridge.ts | Bin 31357 -> 31358 bytes .../cdp-function-breakpoint-bridge.test.ts | 12 ++++++++++++ 2 files changed, 12 insertions(+) diff --git a/src/proxy/cdp-function-breakpoint-bridge.ts b/src/proxy/cdp-function-breakpoint-bridge.ts index 9a2e3b624477d0aad4389e86664b664dd7e2d647..53fef4aa318b2f7773ed7cfd879eb49a57f38e0b 100644 GIT binary patch delta 17 YcmezSh4J4P#tmY^Ofd$V#f8(-0Zfwy_W%F@ delta 16 XcmezOh4Jqf#tmY^j0~G4gwxUiL@owv diff --git a/tests/proxy/cdp-function-breakpoint-bridge.test.ts b/tests/proxy/cdp-function-breakpoint-bridge.test.ts index 978be0e8e..7e8216be9 100644 --- a/tests/proxy/cdp-function-breakpoint-bridge.test.ts +++ b/tests/proxy/cdp-function-breakpoint-bridge.test.ts @@ -11,6 +11,8 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; import { EventEmitter } from 'events'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; import type { DebugProtocol } from '@vscode/debugprotocol'; import { CdpFunctionBreakpointBridge, MAX_SCRIPT_URLS } from '../../src/proxy/cdp-function-breakpoint-bridge.js'; import { JS_LOGPOINT_BINDING } from '@debugmcp/shared'; @@ -778,4 +780,14 @@ describe('CdpFunctionBreakpointBridge', () => { expect(urls.get(`s${MAX_SCRIPT_URLS + overshoot - 1}`)).toBe(`file:///f${MAX_SCRIPT_URLS + overshoot - 1}.js`); }); }); + + describe('the source file', () => { + it('holds no raw NUL byte: the key separator is written as an escape', () => { + // A literal NUL made git treat the file as binary (no diff, no blame) + // and made text tools refuse to edit it. The separator is the same + // character at run time; the keyed cases above pin that. + const source = readFileSync(fileURLToPath(new URL('../../src/proxy/cdp-function-breakpoint-bridge.ts', import.meta.url)), 'utf8'); + expect(source.includes(String.fromCharCode(0))).toBe(false); + }); + }); }); From aa178afdfde3e41f8a661fd95785d64b88503e61 Mon Sep 17 00:00:00 2001 From: JF Date: Sun, 15 Nov 2026 20:46:37 -0500 Subject: [PATCH 02/24] fix(javascript): the server steps through skipped code itself; js-debug's stepper is off (#1130, #1161) A step lands where the program's code next runs, in bounded time, and is never lost. One rule decides what a step skips, for step_into, step_over and step_out alike, and one component applies it. js-debug's smart stepper was that component. While a step landed in code the session skips it stepped again by itself: with `breakOnAsyncCall`, which moves the step to a later task and loses it (step_into on the first console.log of simple_test.js ended the session), and one V8 step per statement of the skipped code (131 for one console.log; ~6 s on a Linux host, where every engine step costs ~46 ms). #513, #678/#687 and #1130 are that stepper deciding where a step ends. So the adapter is always sent `smartStep: false`, and the start request's `smartStep` is read as the session's choice. A session that chose it has its stepIn / next / stepOut served by JsStepper, over the raw CDP socket js-debug hands out for the target: - one CDP command per engine step, never with breakOnAsyncCall; - the verdict on a landing is js-debug's own mark on frame 0 (stackTrace levels 1), asked at once: the session's one definition of skipped code (justMyCode, a caller's skipFiles, source maps); - skipped code on top: step_into repeats up to a budget of 24, which is how a call through Node's code reaches a callback of the program's, then steps out; step_over and step_out step out at once; with no program frame below the stack the step started on is gone, and the program is resumed; - js-debug's stopped / continued events are withheld by count (one stopped per pause it keeps, out of order), and one stopped goes out: reason `step` on a landing, js-debug's own on a real stop. V8 itself loses a step that leaves a function through `return` inside try...finally (#1161: V8 12.4, 13.6 and 14.6 with a bare CDP client; step_out answered "Step completed as session exited"). Node's Module.prototype.require has that shape. So a step never counts on V8 alone to come BACK to a frame: before it can leave one that way, the stepper arms a net, up to 24 temporary CDP breakpoints on the break positions of the program frame the step returns to (the nearest one below, or the async parent), kept with that activation's depth. Any position there is where V8's own step-out would stop, so a hit is a landing. No net goes on the frame being stepped in: V8 reports no statement boundaries, and a net there would stop a multi-line call half-way. Every ender removes every net. A step_into whose line called only skipped code says so in its answer. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn69pXrYMWc1JUwv5v8 --- .../src/interfaces/adapter-policy-js.ts | 3 + .../src/interfaces/dap-client-behavior.ts | 13 + src/proxy/child-session-manager.ts | 126 ++- src/proxy/js-stepper.ts | 870 ++++++++++++++++++ src/proxy/minimal-dap.ts | 18 + src/session/execution/execution-controller.ts | 5 +- src/utils/error-messages.ts | 27 + 7 files changed, 1032 insertions(+), 30 deletions(-) create mode 100644 src/proxy/js-stepper.ts diff --git a/packages/shared/src/interfaces/adapter-policy-js.ts b/packages/shared/src/interfaces/adapter-policy-js.ts index b6a57e3d3..a107514f7 100644 --- a/packages/shared/src/interfaces/adapter-policy-js.ts +++ b/packages/shared/src/interfaces/adapter-policy-js.ts @@ -1428,6 +1428,9 @@ export const JsDebugAdapterPolicy = { // JavaScript-specific child session behaviors mirrorBreakpointsToChild: true, pauseAfterChildAttach: true, + // js-debug's smart stepper stays off; the proxy's own stepper serves + // the steps of a session whose effective `smartStep` is on (issue #1130). + stepsThroughSkippedCode: true, // js-debug's only word on a condition (or compiled logpoint) that // does not parse is a stderr output line during setBreakpoints or // the child attach; the proxy correlates it (issue #853) diff --git a/packages/shared/src/interfaces/dap-client-behavior.ts b/packages/shared/src/interfaces/dap-client-behavior.ts index 679b89b51..4f580320d 100644 --- a/packages/shared/src/interfaces/dap-client-behavior.ts +++ b/packages/shared/src/interfaces/dap-client-behavior.ts @@ -122,6 +122,19 @@ export interface DapClientBehavior { * child session is available instead of falling back to the parent. */ childRequiredCommands?: Set; + + /** + * The proxy steps through skipped code itself, and the adapter's own + * stepper that would do it is kept off (issue #1130). js-debug's smart + * stepper re-steps with `breakOnAsyncCall`, which loses the step, and takes + * one engine step per statement of the skipped code. With this set, the + * `smartStep` of the start request is read as the session's choice (step + * through skipped code, or land where the engine lands), the adapter is + * always sent `smartStep: false`, and `stepIn` / `next` / `stepOut` for a + * session that chose it are served by the proxy's stepper over the + * adapter's raw CDP socket. + */ + stepsThroughSkippedCode?: boolean; } /** diff --git a/src/proxy/child-session-manager.ts b/src/proxy/child-session-manager.ts index 8c31425cc..d481e0c8a 100644 --- a/src/proxy/child-session-manager.ts +++ b/src/proxy/child-session-manager.ts @@ -16,6 +16,8 @@ import { createLogger } from '../utils/logger.js'; import { createChildSafePolicy } from './child-safe-policy.js'; import type { MinimalDapClient } from './minimal-dap.js'; import { CdpFunctionBreakpointBridge } from './cdp-function-breakpoint-bridge.js'; +import { CdpProxyClient } from './cdp-proxy-client.js'; +import { JsStepper } from './js-stepper.js'; import { sendSetBreakpointsStamping, watchConditionSyntaxErrors, matchStoredBreakpoint } from './breakpoint-condition-errors.js'; import path from 'path'; @@ -151,6 +153,12 @@ export class ChildSessionManager extends EventEmitter { // CDP-delivered function breakpoints (issue #295); present only when the // policy declares functionBreakpointsVia 'cdp' (js-debug) private cdpBridge: CdpFunctionBreakpointBridge | null = null; + /** + * The proxy's own stepper for the program's target (issue #1130); present + * when the policy keeps the adapter's stepper off. It shares the CDP socket + * the bridge opens, and every event of the target passes it first. + */ + private stepper: JsStepper | null = null; // Serializes child event forwarding so a stopped event held by the bridge // (correlation/bind window) cannot be overtaken by later events private childEventChain: Promise = Promise.resolve(); @@ -188,8 +196,29 @@ export class ChildSessionManager extends EventEmitter { this.port = options.port; this.getParentStart = options.getParentStart; this.instanceId = createInstanceId(); + if (this.dapBehavior.stepsThroughSkippedCode) { + this.stepper = new JsStepper({ + target: { + sendRequest: (command, args, timeoutMs) => { + const child = this.activeChild; + if (!child) { + return Promise.reject(new Error(`No active child session for '${command}'`)); + } + return child.sendRequest(command, args, timeoutMs) as Promise; + } + }, + deliver: (evt) => this.forwardChildEvent(evt) + }); + } if (options.policy.functionBreakpointsVia === 'cdp') { - this.cdpBridge = options.cdpBridgeFactory?.() ?? new CdpFunctionBreakpointBridge(); + // One CDP socket per target: the bridge opens it, the stepper listens on it too. + this.cdpBridge = options.cdpBridgeFactory?.() ?? new CdpFunctionBreakpointBridge({ + clientFactory: () => { + const client = new CdpProxyClient(); + this.stepper?.attachCdp(client); + return client; + } + }); this.cdpBridge.on('breakpointEvent', (evt: DebugProtocol.Event) => { this.emit('childEvent', evt); }); @@ -289,6 +318,30 @@ export class ChildSessionManager extends EventEmitter { return state; } + /** + * The session's choice, read from its start request's `smartStep`: step + * through skipped code (the proxy's stepper serves the steps), or land + * where the engine lands (issue #1130). + */ + setStepThroughSkippedCode(enabled: boolean): void { + this.stepper?.setEnabled(enabled); + logger.info(`[ChildSessionManager:${this.instanceId}] stepping through skipped code: ${enabled ? 'the proxy stepper' : 'off'}`); + } + + /** + * A step the proxy's stepper serves now, or null when it goes to the + * adapter as it is (the session chose plain steps, no CDP socket, a step + * into a named target). + */ + stepRequest(command: string, args?: unknown): Promise | null { + return this.stepper?.handles(command, args) ? this.stepper.request(command, args) : null; + } + + /** Any other request for the target: one that resumes or ends it ends a step still in flight. */ + async beforeChildRequest(command: string): Promise { + await this.stepper?.beforeRequest(command); + } + /** * Route a command to the appropriate child session if needed */ @@ -931,36 +984,12 @@ export class ChildSessionManager extends EventEmitter { if (evt.event === 'initialized') { this.childInitializedCount++; } - const bridge = this.cdpBridge; - if (!bridge) { - // Forward child events through parent - this.emit('childEvent', evt); + // The stepper's own pauses and resumes are its business (issue #1130): + // of a step's many `stopped` events one is forwarded, by the stepper. + if (this.stepper?.withholds(evt)) { return; } - // Serialize through the chain so a stopped event the bridge holds - // (bind/correlation window) keeps its place in the event order. Every - // event first waits for the adoption's bridge attach to settle (issue - // #850); not on adoptionInProgress, which flushEvents() below awaits - // through this very chain. - this.childEventChain = this.childEventChain.then(async () => { - await this.bridgeAttachSettled; - let out = evt; - if (evt.event === 'stopped') { - // An entry stop always goes through the bridge: with nothing armed - // it can still be a late entry inside a function (issue #858). - const reason = (evt.body as { reason?: string } | undefined)?.reason; - if (bridge.hasArmedOrPending() || reason === 'entry') { - try { - out = await bridge.processStoppedEvent(evt); - } catch (err) { - logger.warn(`[ChildSessionManager:${this.instanceId}] bridge stop processing failed, forwarding original: ${String(err)}`); - } - } else { - logger.info(`[ChildSessionManager:${this.instanceId}] stopped event bypassed the CDP bridge (no armed or pending function breakpoints)`); - } - } - this.emit('childEvent', out); - }); + this.forwardChildEvent(evt); }); child.on('error', (err: Error) => { @@ -970,6 +999,7 @@ export class ChildSessionManager extends EventEmitter { child.on('close', () => { logger.info(`[ChildSessionManager:${this.instanceId}] [child] DAP client connection closed (current count=${this.childSessions.size})`); + this.stepper?.detachCdp(); this.cdpBridge?.detach(); this.emit('childClosed'); this.childSessions.clear(); @@ -979,6 +1009,43 @@ export class ChildSessionManager extends EventEmitter { }); } + /** + * Forward one event of the program's target to the parent connection: the + * target's own events, and the one `stopped` the stepper reports for a step. + */ + private forwardChildEvent(evt: DebugProtocol.Event): void { + const bridge = this.cdpBridge; + if (!bridge) { + // Forward child events through parent + this.emit('childEvent', evt); + return; + } + // Serialize through the chain so a stopped event the bridge holds + // (bind/correlation window) keeps its place in the event order. Every + // event first waits for the adoption's bridge attach to settle (issue + // #850); not on adoptionInProgress, which flushEvents() below awaits + // through this very chain. + this.childEventChain = this.childEventChain.then(async () => { + await this.bridgeAttachSettled; + let out = evt; + if (evt.event === 'stopped') { + // An entry stop always goes through the bridge: with nothing armed + // it can still be a late entry inside a function (issue #858). + const reason = (evt.body as { reason?: string } | undefined)?.reason; + if (bridge.hasArmedOrPending() || reason === 'entry') { + try { + out = await bridge.processStoppedEvent(evt); + } catch (err) { + logger.warn(`[ChildSessionManager:${this.instanceId}] bridge stop processing failed, forwarding original: ${String(err)}`); + } + } else { + logger.info(`[ChildSessionManager:${this.instanceId}] stopped event bypassed the CDP bridge (no armed or pending function breakpoints)`); + } + } + this.emit('childEvent', out); + }); + } + /** * Wait until the child has emitted more 'initialized' events than * `baseline`. The count is latched in wireChildEvents from connect time, so @@ -1059,6 +1126,7 @@ export class ChildSessionManager extends EventEmitter { */ async shutdown(): Promise { logger.info(`[ChildSessionManager:${this.instanceId}] Shutting down child sessions`); + this.stepper?.detachCdp(); this.cdpBridge?.detach(); for (const [id, child] of this.childSessions) { diff --git a/src/proxy/js-stepper.ts b/src/proxy/js-stepper.ts new file mode 100644 index 000000000..230416ffe --- /dev/null +++ b/src/proxy/js-stepper.ts @@ -0,0 +1,870 @@ +/** + * The server's own JavaScript stepper (issue #1130). + * + * js-debug has a "smart stepper": while a step lands in code the session + * skips (Node internals, node_modules, an unmapped helper of a source-mapped + * file) it steps again by itself. It does so with `breakOnAsyncCall`, which + * moves the step to a later task and loses it, and it takes one V8 step per + * statement of the skipped code (131 for one `console.log`). Three issues + * (#513, #678/#687, #1130) were that stepper deciding where a step ends. + * + * So js-debug's stepper is off for every session, and this one decides. It + * sits on one js-debug target: that target's DAP connection, and the raw CDP + * socket js-debug hands out with `requestCDPProxy`. One `stepIn`, `next` or + * `stepOut` comes in, one `stopped` goes out. + * + * One CDP command per engine step. `Debugger.stepInto` never carries + * `breakOnAsyncCall`. + * + * The verdict on a landing is js-debug's own mark on frame 0 + * (`stackTrace { levels: 1 }`: `presentationHint: "deemphasize"`), asked at + * once after the CDP `paused`. It is the session's one definition of + * skipped code: it follows `justMyCode`, a caller's `skipFiles` and source + * maps. js-debug's `stopped` for the pause is never waited for: it is sent + * a timer tick later, which costs 12 ms a landing on Windows. + * + * NETS. V8 loses a step in two measured ways: when a frame is left through + * a `return` inside try...finally (issue #1161), and when js-debug resumes + * a pause of its own, a module-entry breakpoint, while the step is in + * flight (issue #1162). So a step never counts on V8 alone to come BACK to + * a frame. A net is a capped set of temporary CDP breakpoints on the break + * positions of a program frame the step returns to, kept with the stack + * depth of the activation it guards. Any position there is where V8's own + * step-out would stop, so a hit at that depth is a landing. + * + * No net is put on the frame being stepped IN. V8 says `ambiguous` for any + * breakpoint hit while a step is in flight, and it exposes no statement + * boundaries, so a hit on a later position of the same statement (the + * second argument of a multi-line call) cannot be told from the next + * statement. In-frame stepping stays V8's own. That is why a plain + * `step_over` across issue #1162's module load is not recovered here. + * + * Skipped code on top: `step_into` repeats up to a budget (that is how a + * call through Node's own code reaches a callback of the program's), then + * steps out; `step_over` and `step_out` step out at once. With no program + * frame below, the stack the step started on is gone: the program is + * resumed and nothing is reported (stepping out of the bottom frame would + * land in the next task's internals instead). + * + * A pause that is not the stepper's (another breakpoint, an exception, a + * `debugger;`) is js-debug's to decide. Resumed by js-debug, the chain + * waits on. Kept, the chain ends and that stop is forwarded as itself. + * + * js-debug's `stopped` and `continued` events are withheld by count: it + * sends one `stopped` per pause it keeps, out of order with the + * `continued` of the next resume. The last one is forwarded: as reason + * `step` on a landing (it arrives as `pause` or `breakpoint`), unchanged on + * a real stop. + * + * Every ender removes every net. + */ +import type { DebugProtocol } from '@vscode/debugprotocol'; +import { createLogger } from '../utils/logger.js'; +import { ErrorMessages } from '../utils/error-messages.js'; + +// redirectable: re-pointed into the per-session proxy log at worker init (#519) +const logger = createLogger('js-stepper', { redirectable: true }); + +/** The slice of the target's DAP connection the stepper needs. */ +export interface StepperTarget { + sendRequest(command: string, args?: unknown, timeoutMs?: number): Promise; +} + +/** The slice of the CDP proxy client the stepper needs. */ +export interface StepperCdp { + send(method: string, params?: object, timeoutMs?: number): Promise; + isConnected(): boolean; + on(event: 'cdp-event', listener: (method: string, params: unknown) => void): unknown; + off(event: 'cdp-event', listener: (method: string, params: unknown) => void): unknown; +} + +export interface JsStepperTunables { + /** Repeats of a step-in while the landing is skipped code, before stepping out. */ + budget: number; + /** CDP step commands in one chain, all told. */ + commandCap: number; + /** Break positions in one net. A breakpoint in a big function is slow to set (1000 took 2.4 s). */ + netSize: number; + /** Re-issued commands on a net position that is not a landing (recursion; the origin statement). */ + reissueCap: number; + /** How long a finished chain waits for js-debug's `stopped` events before it reports without them. */ + settleCeilingMs: number; + /** How long `stackTrace` may answer "not paused" for a pause js-debug keeps. */ + verdictCeilingMs: number; +} + +export const DEFAULT_JS_STEPPER_TUNABLES: JsStepperTunables = { + budget: 24, + commandCap: 128, + netSize: 24, + reissueCap: 24, + settleCeilingMs: 2000, + verdictCeilingMs: 2000 +}; + +export interface JsStepperOptions { + target: StepperTarget; + /** Hands an event to whoever forwards this target's events. */ + deliver: (event: DebugProtocol.Event) => void; + tunables?: Partial; + /** Test seam. */ + sleep?: (ms: number) => Promise; +} + +export type StepKind = 'in' | 'over' | 'out'; + +const STEP_OF_COMMAND: Record = { stepIn: 'in', next: 'over', stepOut: 'out' }; +const CDP_COMMAND: Record = { in: 'Debugger.stepInto', over: 'Debugger.stepOver', out: 'Debugger.stepOut' }; + +/** Requests that resume or end the target: a chain still waiting on a net must give it up first. */ +const CHAIN_ENDING_REQUESTS = new Set(['continue', 'disconnect', 'terminate', 'restart', 'goto', 'reverseContinue', 'restartFrame']); + +/** What ends a chain as a real stop when the pause carries no breakpoint of ours. */ +const STEP_REASONS = new Set(['step', 'ambiguous']); + +interface CdpLocation { + scriptId: string; + lineNumber: number; + columnNumber?: number; +} + +interface CdpBreakLocation extends CdpLocation { + type?: string; +} + +interface CdpCallFrame { + functionName?: string; + functionLocation?: CdpLocation; + location: CdpLocation; +} + +interface CdpAsyncFrame { + functionName?: string; + scriptId: string; + lineNumber: number; + columnNumber: number; +} + +interface CdpPaused { + callFrames: CdpCallFrame[]; + reason: string; + hitBreakpoints?: string[]; + asyncStackTrace?: { callFrames?: CdpAsyncFrame[] }; +} + +interface Net { + /** What it guards, for the log. */ + name: string; + /** Function identity, or the async parent's position. */ + fn: string; + /** The stack depth of the guarded activation; Infinity for an async parent, which resumes at any depth. */ + depth: number; + ids: Set; +} + +type Inbox = + | { type: 'paused'; pause: CdpPaused } + | { type: 'resumed'; ours: boolean }; + +interface Chain { + kind: StepKind; + threadId: number | undefined; + originDepth: number; + originLine: number; + originFn: string; + inbox: Inbox[]; + wake: (() => void) | null; + cancelled: string | null; + /** Pauses js-debug keeps, each of which it reports with one `stopped`. */ + kept: number; + /** `stopped` events of this chain seen so far. */ + stoppedSeen: number; + lastStopped: DebugProtocol.Event | null; + commands: string[]; + spent: number; + reissues: number; + /** A net fired in recursion and was dropped: V8's own step-outs finish, to the origin depth. */ + unwinding: boolean; + /** A step-in spent its budget in skipped code and stepped out: the line called nothing of the program's. */ + steppedOutOfSkipped: boolean; + /** Every command the chain may send is spent and skipped code is still on top. */ + capped: boolean; + startedAt: number; +} + +type Verdict = + | { kind: 'wait' } + | { kind: 'command'; command: string } + | { kind: 'landing'; by: string } + | { kind: 'real-stop' } + | { kind: 'left-stack' }; + +function fnKey(frame: CdpCallFrame): string { + const l = frame.functionLocation ?? frame.location; + return `${l.scriptId}:${l.lineNumber}:${l.columnNumber ?? 0}`; +} + +function sameOrAfter(a: CdpLocation, b: CdpLocation): boolean { + return a.lineNumber > b.lineNumber || (a.lineNumber === b.lineNumber && (a.columnNumber ?? 0) >= (b.columnNumber ?? 0)); +} + +function errorText(err: unknown): string { + return err instanceof Error ? err.message : String(err); +} + +/** + * js-debug's mark on a frame. `deemphasize` is its own value for a frame of + * skipped code (skipFiles, or an unmapped position of a source-mapped file); + * the DAP type does not list it. + */ +function markOf(frame: DebugProtocol.StackFrame): string | undefined { + return frame.presentationHint as string | undefined; +} + +export class JsStepper { + private readonly target: StepperTarget; + private readonly deliver: (event: DebugProtocol.Event) => void; + private readonly tunables: JsStepperTunables; + private readonly sleep: (ms: number) => Promise; + + private cdp: StepperCdp | null = null; + private readonly onCdpEvent = (method: string, params: unknown): void => this.handleCdpEvent(method, params); + + /** Whether this session steps through skipped code (the effective `smartStep`). */ + private enabled = false; + /** The pause V8 is in now, as CDP reported it; null while running. */ + private current: CdpPaused | null = null; + /** Whether the stepper sent a resuming command since the last pause: tells its resumes from js-debug's. */ + private sentSincePause = false; + private chain: Chain | null = null; + private nets: Net[] = []; + /** `stopped` events of a finished chain still on their way; dropped when they arrive, until the deadline. */ + private owed = 0; + private owedUntil = 0; + /** Scripts js-debug marked "Skipped by skipFiles": a script-level verdict, not asked again. */ + private readonly skippedScripts = new Set(); + private readonly finallyByFunction = new Map(); + private readonly sources = new Map(); + + constructor(options: JsStepperOptions) { + this.target = options.target; + this.deliver = options.deliver; + this.tunables = { ...DEFAULT_JS_STEPPER_TUNABLES, ...(options.tunables ?? {}) }; + this.sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))); + } + + /** The session's choice: step through skipped code (on), or land where V8 lands (off). */ + setEnabled(enabled: boolean): void { + this.enabled = enabled; + } + + isEnabled(): boolean { + return this.enabled; + } + + /** Listen on the target's CDP socket. Safe before it is connected. */ + attachCdp(cdp: StepperCdp): void { + this.detachCdp(); + this.cdp = cdp; + cdp.on('cdp-event', this.onCdpEvent); + } + + /** The socket is gone (the target ended): nothing can be removed any more. */ + detachCdp(): void { + this.cdp?.off('cdp-event', this.onCdpEvent); + this.cdp = null; + this.current = null; + this.nets = []; + this.owed = 0; + const chain = this.chain; + if (chain) { + chain.cancelled = 'the CDP connection closed'; + chain.wake?.(); + } + } + + /** Whether this request is one the stepper serves now. */ + handles(command: string, args?: unknown): boolean { + if (!this.enabled || !(command in STEP_OF_COMMAND)) { + return false; + } + // A step into a named target is js-debug's own feature. + if (command === 'stepIn' && (args as { targetId?: number } | undefined)?.targetId !== undefined) { + return false; + } + return this.cdp?.isConnected() === true && this.current !== null && this.current.callFrames.length > 0; + } + + /** + * Serve one step. Resolves when V8 has taken the first command; the one + * `stopped` of the chain is delivered later. + */ + async request(command: string, args?: unknown): Promise { + const kind = STEP_OF_COMMAND[command]; + const origin = this.current; + if (!kind || !origin || !this.cdp) { + throw new Error(`The JavaScript stepper cannot serve '${command}' now`); + } + await this.abandonChain('another step was requested'); + + const top = origin.callFrames[0]; + const chain: Chain = { + kind, + threadId: (args as { threadId?: number } | undefined)?.threadId, + originDepth: origin.callFrames.length, + originLine: top.location.lineNumber, + originFn: fnKey(top), + inbox: [], + wake: null, + cancelled: null, + kept: 0, + stoppedSeen: 0, + lastStopped: null, + commands: [], + spent: 0, + reissues: 0, + unwinding: false, + steppedOutOfSkipped: false, + capped: false, + startedAt: Date.now() + }; + this.chain = chain; + this.owed = 0; + + try { + // A net before the first command only where V8 can lose the step by + // LEAVING the origin frame (issue #1161): a step-out always, a step-over + // or step-in when the function's text has `finally`. Not when it returns + // to itself: that net would sit in the frame being stepped in. + if (kind === 'out' || await this.hasFinally(top)) { + await this.armReturnTarget(origin, kind === 'out' ? null : chain.originFn); + } + await this.sendStep(chain, CDP_COMMAND[kind]); + } catch (err) { + await this.disarmAll(); + this.chain = null; + throw err; + } + void this.run(chain); + return { type: 'response', seq: 0, request_seq: -1, command, success: true, body: {} } as DebugProtocol.Response; + } + + /** + * A request for the target that is not a step. One that resumes or ends + * the target ends a chain still waiting on a net, and removes the net first. + */ + async beforeRequest(command: string): Promise { + if (CHAIN_ENDING_REQUESTS.has(command)) { + await this.abandonChain(`a '${command}' request`); + } + } + + /** + * Every event of the target passes here first. True means the stepper + * keeps it: the caller must not forward it. + */ + withholds(event: DebugProtocol.Event): boolean { + const chain = this.chain; + if (event.event === 'stopped') { + if (chain) { + chain.stoppedSeen++; + chain.lastStopped = event; + chain.wake?.(); + return true; + } + if (this.owed > 0) { + if (Date.now() <= this.owedUntil) { + this.owed--; + return true; + } + this.owed = 0; + } + return false; + } + // One `continued` per resume: a chain's are its own business. The caller + // was told the program resumed when the step was answered. + return event.event === 'continued' && chain !== null; + } + + /** For the log and the tests. */ + describe(): { enabled: boolean; chain: boolean; nets: number; owed: number; paused: boolean } { + return { enabled: this.enabled, chain: this.chain !== null, nets: this.nets.length, owed: this.owed, paused: this.current !== null }; + } + + // ----- CDP events ----- + + private handleCdpEvent(method: string, params: unknown): void { + if (method === 'Debugger.paused') { + const pause = params as CdpPaused; + this.current = pause; + this.sentSincePause = false; + const chain = this.chain; + if (chain) { + chain.inbox.push({ type: 'paused', pause }); + chain.wake?.(); + } + } else if (method === 'Debugger.resumed') { + const ours = this.sentSincePause; + this.current = null; + const chain = this.chain; + if (chain) { + chain.inbox.push({ type: 'resumed', ours }); + chain.wake?.(); + } + } + } + + // ----- the chain ----- + + private async run(chain: Chain): Promise { + try { + for (;;) { + const pause = await this.nextPause(chain); + if (!pause) { + await this.finish(chain, 'cancelled'); + return; + } + const verdict = await this.judge(chain, pause); + if (verdict.kind === 'wait') { + continue; + } + if (verdict.kind === 'command') { + if (chain.commands.length >= this.tunables.commandCap) { + // Still in skipped code after every command the chain may send: + // stop here and say so rather than run on. + chain.capped = true; + await this.finish(chain, 'landing', 'the command cap, still in skipped code'); + return; + } + await this.sendStep(chain, verdict.command); + continue; + } + await this.finish(chain, verdict.kind, verdict.kind === 'landing' ? verdict.by : undefined); + return; + } + } catch (err) { + logger.warn(`[JsStepper] chain failed: ${errorText(err)}`); + await this.finish(chain, 'error'); + } + } + + private async sendStep(chain: Chain, command: string): Promise { + const cdp = this.cdp; + if (!cdp) { + throw new Error('the CDP connection closed'); + } + chain.commands.push(command); + this.sentSincePause = true; + await cdp.send(command, command === CDP_COMMAND.in ? { breakOnAsyncCall: false } : {}); + } + + private waitForInbox(chain: Chain): Promise { + return new Promise((resolve) => { + chain.wake = () => { + chain.wake = null; + resolve(); + }; + }); + } + + /** The next CDP pause of the chain, or null when the chain was given up. */ + private async nextPause(chain: Chain): Promise { + for (;;) { + if (chain.cancelled) { + return null; + } + const next = chain.inbox.shift(); + if (next?.type === 'paused') { + return next.pause; + } + if (!next) { + await this.waitForInbox(chain); + } + } + } + + private netOf(id: string): Net | undefined { + return this.nets.find((net) => net.ids.has(id)); + } + + private async judge(chain: Chain, pause: CdpPaused): Promise { + const hits = pause.hitBreakpoints ?? []; + const hitNets = [...new Set(hits.map((id) => this.netOf(id)).filter((net): net is Net => net !== undefined))]; + const foreignHit = hits.some((id) => !this.netOf(id)); + const ours = !foreignHit && (STEP_REASONS.has(pause.reason) || (pause.reason === 'other' && hitNets.length > 0)); + + if (!ours) { + // Another breakpoint, an exception, a `debugger;`: js-debug decides. + const decision = await this.jsDebugDecides(chain); + if (decision === 'resumed') { + return { kind: 'wait' }; + } + if (decision === 'cancelled') { + return { kind: 'wait' }; + } + chain.kept++; + return { kind: 'real-stop' }; + } + chain.kept++; + + const top = pause.callFrames[0]; + const depth = pause.callFrames.length; + const skipped = await this.isSkipped(chain, pause); + + if (skipped) { + // Before anything else, a net on the program frame this code returns to. + const guarded = this.nets.some((net) => net.depth < depth || net.depth === Infinity); + if (!guarded && !(await this.armReturnTarget(pause, null))) { + return { kind: 'left-stack' }; + } + if (chain.kind === 'in' && !chain.unwinding && chain.spent < this.tunables.budget) { + chain.spent++; + return { kind: 'command', command: CDP_COMMAND.in }; + } + if (chain.kind === 'in') { + chain.steppedOutOfSkipped = true; + } + return { kind: 'command', command: CDP_COMMAND.out }; + } + + // Program code on top. + if (chain.unwinding) { + return depth > chain.originDepth + ? { kind: 'command', command: CDP_COMMAND.out } + : { kind: 'landing', by: 'V8 step-outs after a net was dropped (recursion)' }; + } + const backOnOriginStatement = depth === chain.originDepth && fnKey(top) === chain.originFn && top.location.lineNumber === chain.originLine; + if (hits.length === 0) { + // V8's step landed. A step-in that is back on the line it left steps in + // again: that enters the line's next call, or moves on. + if (chain.kind === 'in' && backOnOriginStatement && chain.reissues < this.tunables.reissueCap) { + chain.reissues++; + return { kind: 'command', command: CDP_COMMAND.in }; + } + return { kind: 'landing', by: 'V8 step' }; + } + if (chain.kind === 'in' && depth > chain.originDepth) { + return { kind: 'landing', by: 'net, in a deeper frame of the program' }; + } + const guarding = hitNets.filter((net) => depth <= net.depth); + if (guarding.length === 0) { + if (chain.kind === 'out' && depth >= chain.originDepth && chain.reissues < this.tunables.reissueCap) { + // The frame being left is the same function as its caller (recursion) + // and is still running: step out again. + chain.reissues++; + return { kind: 'command', command: CDP_COMMAND.out }; + } + // The net fired in a deeper activation than the one it guards. Drop it; + // V8's own step-outs from here, until the depth is the origin's. + for (const net of hitNets) { + await this.disarm(net); + } + chain.unwinding = true; + if (depth <= chain.originDepth) { + return { kind: 'landing', by: 'net dropped (recursion)' }; + } + return { kind: 'command', command: CDP_COMMAND.out }; + } + // Control is back in a frame a net guards: where V8's own step-out would stop. + if (chain.kind === 'in' && backOnOriginStatement && chain.reissues < this.tunables.reissueCap) { + chain.reissues++; + return { kind: 'command', command: CDP_COMMAND.in }; + } + return { kind: 'landing', by: pause.reason === 'ambiguous' ? 'net, with a V8 step in flight' : 'net, V8 had lost the step' }; + } + + /** + * A pause that is not the stepper's: either js-debug resumes it itself (a + * `resumed` the stepper did not send), or it keeps it and sends one more + * `stopped` than the chain's kept pauses account for. + */ + private async jsDebugDecides(chain: Chain): Promise<'kept' | 'resumed' | 'cancelled'> { + for (;;) { + if (chain.cancelled) { + return 'cancelled'; + } + const next = chain.inbox[0]; + if (next?.type === 'resumed') { + chain.inbox.shift(); + if (!next.ours) { + return 'resumed'; + } + continue; + } + if (next?.type === 'paused') { + // A newer pause already: the one being judged was resumed. + return 'resumed'; + } + if (chain.stoppedSeen > chain.kept) { + return 'kept'; + } + await this.waitForInbox(chain); + } + } + + /** js-debug's mark on frame 0 of the current pause. */ + private async isSkipped(chain: Chain, pause: CdpPaused): Promise { + const scriptId = pause.callFrames[0].location.scriptId; + const plainLanding = pause.reason === 'step' && (pause.hitBreakpoints ?? []).length === 0; + if (plainLanding && this.skippedScripts.has(scriptId)) { + return true; + } + const deadline = Date.now() + this.tunables.verdictCeilingMs; + for (;;) { + let failure: string; + try { + const answer = await this.target.sendRequest( + 'stackTrace', + { threadId: chain.threadId ?? 0, startFrame: 0, levels: 1 }, + 5000 + ); + const frame = answer?.body?.stackFrames?.[0]; + if (answer?.success !== false && frame) { + const skipped = markOf(frame) === 'deemphasize'; + if (skipped && /skipFiles/i.test(frame.source?.origin ?? '')) { + this.skippedScripts.add(scriptId); + } + return skipped; + } + failure = answer?.message ?? 'no frame'; + } catch (err) { + failure = errorText(err); + } + // js-debug answers "not paused" until it has taken the pause in. + if (chain.cancelled || Date.now() >= deadline) { + logger.warn(`[JsStepper] no verdict for a landing (${failure}); treating it as program code`); + return false; + } + await this.sleep(1); + } + } + + private async finish(chain: Chain, ender: 'landing' | 'real-stop' | 'left-stack' | 'cancelled' | 'error', by?: string): Promise { + await this.disarmAll(); + if (ender === 'left-stack') { + // Nothing of the program is below: resume, and report nothing. + try { + chain.commands.push('Debugger.resume'); + this.sentSincePause = true; + await this.cdp?.send('Debugger.resume', {}); + } catch (err) { + logger.warn(`[JsStepper] resume after leaving the stack failed: ${errorText(err)}`); + } + } + const reports = ender === 'landing' || ender === 'real-stop'; + if (reports) { + // One `stopped` per kept pause; the last is this chain's. + const deadline = Date.now() + this.tunables.settleCeilingMs; + while (chain.stoppedSeen < chain.kept && !chain.cancelled && Date.now() < deadline) { + await Promise.race([this.waitForInbox(chain), this.sleep(5)]); + } + } + if (this.chain === chain) { + this.chain = null; + } + const missing = Math.max(0, chain.kept - chain.stoppedSeen); + if (missing > 0) { + this.owed = missing; + this.owedUntil = Date.now() + this.tunables.settleCeilingMs; + } + const count = (name: string): number => chain.commands.filter((c) => c === name).length; + logger.info( + `[JsStepper] step ${chain.kind} ended: ${ender}${by ? ` (${by})` : ''}${chain.cancelled ? ` [${chain.cancelled}]` : ''}; ` + + `${count(CDP_COMMAND.in)} in, ${count(CDP_COMMAND.over)} over, ${count(CDP_COMMAND.out)} out; ` + + `${chain.kept} pauses kept, ${chain.stoppedSeen} stopped seen; ${Date.now() - chain.startedAt} ms` + ); + if (ender === 'landing') { + const body = { ...((chain.lastStopped?.body ?? {}) as Record) }; + delete body.hitBreakpointIds; + delete body.text; + this.deliver({ + seq: 0, + type: 'event', + event: 'stopped', + body: { + allThreadsStopped: false, + ...body, + threadId: (body.threadId as number | undefined) ?? chain.threadId ?? 0, + reason: 'step', + description: 'Paused', + ...(chain.capped + ? { text: ErrorMessages.stepStillInSkippedCode(chain.commands.length) } + : chain.steppedOutOfSkipped ? { text: ErrorMessages.stepIntoFoundOnlySkippedCode() } : {}) + } + }); + } else if (ender === 'real-stop' && chain.lastStopped) { + this.deliver(chain.lastStopped); + } + } + + private async abandonChain(why: string): Promise { + const chain = this.chain; + if (!chain) { + return; + } + chain.cancelled = why; + chain.wake?.(); + // The run loop ends the chain; the nets must be gone before the caller goes on. + await this.disarmAll(); + if (this.chain === chain) { + this.chain = null; + } + } + + // ----- nets ----- + + private async possible(start: CdpLocation): Promise { + const answer = await this.cdp?.send<{ locations?: CdpBreakLocation[] }>('Debugger.getPossibleBreakpoints', { + start: { scriptId: start.scriptId, lineNumber: start.lineNumber, columnNumber: start.columnNumber ?? 0 }, + restrictToFunction: true + }); + return answer?.locations ?? []; + } + + /** The break positions of the frame's function. */ + private async locationsOf(frame: CdpCallFrame): Promise { + const here = frame.location; + let all = frame.functionLocation ? await this.possible(frame.functionLocation) : []; + // Top-level code whose first token is a function declaration: the function + // at that position is the nested one. Ask from the frame's own line. + const spans = all.length > 0 && sameOrAfter(here, all[0]) && sameOrAfter(all[all.length - 1], here); + if (!spans) { + all = await this.possible({ scriptId: here.scriptId, lineNumber: here.lineNumber, columnNumber: 0 }); + } + return all; + } + + /** At most `netSize` positions, from the frame's own position on. */ + private window(all: CdpBreakLocation[], here: CdpLocation): CdpBreakLocation[] { + const size = this.tunables.netSize; + if (all.length <= size) { + return all; + } + const at = all.findIndex((location) => sameOrAfter(location, here)); + const from = at === -1 ? 0 : at; + const part = all.slice(from, from + size); + return part.length === size ? part : [...part, ...all.slice(0, size - part.length)]; + } + + private async arm(all: CdpBreakLocation[], here: CdpLocation, net: Omit): Promise { + if (this.nets.some((existing) => existing.fn === net.fn && existing.depth === net.depth)) { + return true; + } + const cdp = this.cdp; + if (!cdp) { + return false; + } + const answers = await Promise.all( + this.window(all, here).map((location) => + cdp + .send<{ breakpointId?: string }>('Debugger.setBreakpoint', { + location: { scriptId: location.scriptId, lineNumber: location.lineNumber, columnNumber: location.columnNumber ?? 0 } + }) + .catch(() => undefined) + ) + ); + const ids = new Set(answers.map((answer) => answer?.breakpointId).filter((id): id is string => typeof id === 'string')); + if (ids.size === 0) { + return false; + } + this.nets.push({ ...net, ids }); + return true; + } + + private async disarm(net: Net): Promise { + this.nets = this.nets.filter((other) => other !== net); + const cdp = this.cdp; + if (!cdp) { + return; + } + await Promise.all([...net.ids].map((breakpointId) => cdp.send('Debugger.removeBreakpoint', { breakpointId }).catch(() => undefined))); + } + + private async disarmAll(): Promise { + for (const net of [...this.nets]) { + await this.disarm(net); + } + } + + /** Whether the function's text has `finally`: the one shape V8 loses a leaving step on (issue #1161). */ + private async hasFinally(frame: CdpCallFrame): Promise { + const key = fnKey(frame); + const known = this.finallyByFunction.get(key); + if (known !== undefined) { + return known; + } + let found = false; + try { + const scriptId = frame.location.scriptId; + let lines = this.sources.get(scriptId); + if (!lines) { + const answer = await this.cdp?.send<{ scriptSource?: string }>('Debugger.getScriptSource', { scriptId }); + lines = (answer?.scriptSource ?? '').split('\n'); + this.sources.set(scriptId, lines); + } + const all = await this.locationsOf(frame); + if (all.length > 0) { + const from = Math.min(frame.functionLocation?.lineNumber ?? all[0].lineNumber, all[0].lineNumber); + found = /\bfinally\b/.test(lines.slice(from, all[all.length - 1].lineNumber + 1).join('\n')); + } + } catch (err) { + logger.warn(`[JsStepper] could not read the function's text: ${errorText(err)}`); + } + this.finallyByFunction.set(key, found); + return found; + } + + /** + * Arm a net on what the top frame of `pause` returns to: the nearest + * program frame below, by js-debug's marks, or the async parent when the + * stack has none. False when nothing of the program is below. + */ + private async armReturnTarget(pause: CdpPaused, notFn: string | null): Promise { + const frames = pause.callFrames; + let marks: DebugProtocol.StackFrame[] = []; + try { + const answer = await this.target.sendRequest( + 'stackTrace', + { threadId: this.chain?.threadId ?? 0, startFrame: 0, levels: 80 }, + 5000 + ); + marks = answer?.body?.stackFrames ?? []; + } catch (err) { + logger.warn(`[JsStepper] could not read the stack's marks: ${errorText(err)}`); + return false; + } + // js-debug lists the sync frames, then a label frame per async segment. + const firstLabel = marks.findIndex((frame) => markOf(frame) === 'label'); + const sync = firstLabel === -1 ? marks : marks.slice(0, firstLabel); + for (let i = 1; i < Math.min(sync.length, frames.length); i++) { + if (markOf(sync[i]) === 'deemphasize') { + continue; + } + if (notFn && fnKey(frames[i]) === notFn) { + // It returns to itself (recursion): a net would sit in the frame being stepped in. + return true; + } + return this.arm(await this.locationsOf(frames[i]), frames[i].location, { + name: frames[i].functionName || '(anonymous)', + fn: fnKey(frames[i]), + depth: frames.length - i + }); + } + // No program frame below on this stack: an async function the event loop + // resumed returns to its awaiter, which is not on the stack. + const parent = pause.asyncStackTrace?.callFrames?.[0]; + const firstAsync = firstLabel === -1 ? undefined : marks[firstLabel + 1]; + if (parent && firstAsync && markOf(firstAsync) !== 'deemphasize' && markOf(firstAsync) !== 'label') { + const start: CdpLocation = { scriptId: parent.scriptId, lineNumber: parent.lineNumber, columnNumber: parent.columnNumber }; + const all = await this.possible(start); + if (all.length > 0) { + return this.arm(all, start, { + name: `${parent.functionName || '(anonymous)'} (async parent)`, + fn: `async:${parent.scriptId}:${parent.lineNumber}:${parent.columnNumber}`, + depth: Infinity + }); + } + } + return false; + } +} diff --git a/src/proxy/minimal-dap.ts b/src/proxy/minimal-dap.ts index 6d278f0de..bfd1ea5cc 100644 --- a/src/proxy/minimal-dap.ts +++ b/src/proxy/minimal-dap.ts @@ -561,6 +561,16 @@ export class MinimalDapClient extends EventEmitter implements IDapClient { this.parentStart = command === 'attach' ? { request: command, ...intent, attachArguments } : { request: command, ...intent }; + + // The start request's `smartStep` is the session's choice, not the + // adapter's setting (issue #1130): the proxy's stepper steps through + // skipped code, and the adapter's own stepper stays off whatever was + // asked, because it loses steps and re-steps a statement at a time. + if (this.dapBehavior.stepsThroughSkippedCode && this.childSessionManager && args !== null && typeof args === 'object') { + const start = args as Record; + this.childSessionManager.setStepThroughSkippedCode(start.smartStep === true); + args = { ...start, smartStep: false }; + } } // CDP-delivered function breakpoints (issue #295): the adapter has no @@ -683,6 +693,14 @@ export class MinimalDapClient extends EventEmitter implements IDapClient { if (this.activeChild) { try { + // A step of a session that steps through skipped code is the proxy + // stepper's (issue #1130); any other request may end a step in flight. + const stepped = manager?.stepRequest(command, args); + if (stepped) { + logger.info(`[MinimalDapClient] '${command}' served by the proxy stepper`); + return (await stepped) as T; + } + await manager?.beforeChildRequest(command); logger.info(`[MinimalDapClient] Dispatching '${command}' to child session`); return await this.activeChild.sendRequest(command, args as unknown, timeoutMs); } catch (err) { diff --git a/src/session/execution/execution-controller.ts b/src/session/execution/execution-controller.ts index 6facdd209..f4516ee42 100644 --- a/src/session/execution/execution-controller.ts +++ b/src/session/execution/execution-controller.ts @@ -396,7 +396,10 @@ export class ExecutionController { success(message, landing, stop); return; } - success(options.successMessage, landing); + // What the step itself has to say about how it landed (the JavaScript + // stepper: the line called only skipped code; issue #1130). + const stepNote = ownStop?.reason === 'step' ? ownStop.text : undefined; + success(stepNote ? `${options.successMessage}. ${stepNote}` : options.successMessage, landing); }; const onTerminated = () => success(terminatedMessage); diff --git a/src/utils/error-messages.ts b/src/utils/error-messages.ts index 5397eae8f..95bb0f75b 100644 --- a/src/utils/error-messages.ts +++ b/src/utils/error-messages.ts @@ -305,6 +305,33 @@ export const ErrorMessages = { 'step_over again to go on, or set a breakpoint on the next line.' : `${stepped} in ${steps} steps: this adapter stops once per expression on a line, so the step was repeated until the line changed.`, + /** + * The sentence on a step_into whose line called only skipped code (issue #1130) + * Occurs when: the proxy's JavaScript stepper walked into the call, found + * nothing of the program's within its budget and came back out. The line + * ran as a step over would have run it, and the caller should know that + * was not a refusal to step in. + * Used in: src/proxy/js-stepper.ts (the `text` of the step's stopped + * event), appended to the step's message by + * src/session/execution/execution-controller.ts + */ + stepIntoFoundOnlySkippedCode: () => + 'The call on that line ran only skipped code (Node internals, node_modules, or files on skipFiles), ' + + 'so there was nothing of your program to step into and the line ran as a step over. ' + + 'dapLaunchArgs.justMyCode: false steps into that code.', + + /** + * The sentence on a step that is still in skipped code after every engine + * step its chain may take (issue #1130) + * Occurs when: the proxy's JavaScript stepper reached its command cap. + * It stops where it is rather than run on. + * Used in: src/proxy/js-stepper.ts + * @param commands - How many engine steps the chain took + */ + stepStillInSkippedCode: (commands: number) => + `The step is still in skipped code after ${commands} engine steps, so it stopped here rather than run on. ` + + 'step_out or continue_execution goes on; a breakpoint in your own code is the reliable way back.', + /** * Informational message for pause requests not yet honored within the grace window * Occurs when: A pause request is acknowledged but no 'stopped' event arrives within the grace From 47fe60cbb15af05c6b12dd0c0a9e51302fcc406d Mon Sep 17 00:00:00 2001 From: JF Date: Sun, 15 Nov 2026 20:57:16 -0500 Subject: [PATCH 03/24] fix(javascript): a forked child steps through skipped code too; the stepper's unit cases (#1130) js-debug's own stepper is off for the whole session, so a child the program forks would have lost stepping through skipped code: its connection is not the program target's, and had no stepper. Each adopted child connection now gets one, on that child's own CDP socket (js-debug hands one out per target). The session's choice is the root's. Without a socket the child's steps stay the engine's plain ones. Measured through the server on the subprocess-tree fixture: step_into on the child's console.log line lands on the next line in 163 ms, with the sentence that the line called only skipped code. The stepper's 33 unit cases run it against a scripted V8 and a scripted js-debug that behave as measured: one stopped per kept pause a moment late, a continued per resume, the mark on frame 0. They cover each chain ender, the budget and the cap, the return to the origin line, the nets (armed before the first command, capped, on the async parent, not on a frame that returns to itself, dropped in recursion, removed before a real stop goes out), a pause js-debug resumes by itself, the relabel and the events kept back. The client's cases pin that the start request's smartStep is read as the session's choice and that the adapter is always sent smartStep: false. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn69pXrYMWc1JUwv5v8 --- src/proxy/child-connections.ts | 89 +++- src/proxy/dap-proxy-worker.ts | 10 +- tests/proxy/js-stepper.test.ts | 746 +++++++++++++++++++++++++++ tests/unit/proxy/minimal-dap.test.ts | 30 +- 4 files changed, 872 insertions(+), 3 deletions(-) create mode 100644 tests/proxy/js-stepper.test.ts diff --git a/src/proxy/child-connections.ts b/src/proxy/child-connections.ts index cd795c9e8..824a61d33 100644 --- a/src/proxy/child-connections.ts +++ b/src/proxy/child-connections.ts @@ -25,6 +25,8 @@ import { resolveExceptionFilters } from '@debugmcp/shared'; import type { AdapterPolicy, ChildAdoptionContract, ChildReport, LanguageSpecificLaunchConfig } from '@debugmcp/shared'; import type { DapConnectionManager } from './dap-proxy-connection-manager.js'; import { createChildSafePolicy } from './child-safe-policy.js'; +import { CdpProxyClient } from './cdp-proxy-client.js'; +import { JsStepper } from './js-stepper.js'; import { releaseByThrowawayAttach } from './throwaway-release.js'; import type { BreakpointSyncResult, @@ -66,6 +68,8 @@ export interface ChildConnectionsOptions { releaseTimeoutMs?: number; /** Absent for a worker whose policy reports no children: adopt() then refuses. */ adoption?: ChildAdoptionDeps; + /** DI seam for tests: the CDP socket of a child whose steps the proxy serves (issue #1130). */ + cdpClientFactory?: () => CdpProxyClient; } /** The worker's answer to CHILD_ADOPT_COMMAND. */ @@ -92,6 +96,10 @@ interface ChildConnection { closed: boolean; /** Cancel a handshake that is still opening this connection. */ cancelAdoption?: (reason: string) => void; + /** The proxy's own stepper for this child, when the adapter's is kept off (issue #1130). */ + stepper?: JsStepper; + /** That stepper's CDP socket: the child's own, from `requestCDPProxy`. */ + cdp?: CdpProxyClient; } /** Forwarded as-is under the child's session id; `terminated` and `close` have their own handling. */ @@ -248,6 +256,9 @@ export class ChildConnections extends EventEmitter { connection.cancelAdoption = undefined; this.answer(held, true); + // Not awaited: the child is adopted either way, and the socket's replay + // covers a pause that comes before it is open. + void this.openStepper(deps, connection); logger.info(`[ChildConnections] Child ${held.report.targetId} adopted as session ${childSessionId}`); return { sessionId: childSessionId, capabilities }; } catch (error) { @@ -300,6 +311,7 @@ export class ChildConnections extends EventEmitter { connection.closed = true; this.clients.delete(sessionId); connection.cancelAdoption?.('child session closed during adoption'); + this.closeStepper(connection); const deps = this.options.adoption; try { await deps?.connectionManager.disconnect(connection.client, options.terminateDebuggee); @@ -396,6 +408,72 @@ export class ChildConnections extends EventEmitter { } } + /** + * A step the child's proxy stepper serves now, or null when it goes to the + * adapter as it is (issue #1130). + */ + stepRequest(sessionId: string, command: string, args?: unknown): Promise | null { + const stepper = this.clients.get(sessionId)?.stepper; + return stepper?.handles(command, args) ? stepper.request(command, args) : null; + } + + /** Any other request for the child: one that resumes or ends it ends a step still in flight. */ + async beforeRequest(sessionId: string, command: string): Promise { + await this.clients.get(sessionId)?.stepper?.beforeRequest(command); + } + + /** + * A child of an adapter whose own stepper is kept off gets the proxy's + * (issue #1130), over that child's own CDP socket: the adapter hands one + * out per target. Not fatal: without it the child's steps are the engine's + * plain ones, and a landing in skipped code is shown as such. + */ + private async openStepper(deps: ChildAdoptionDeps, connection: ChildConnection): Promise { + if (!deps.policy.getDapClientBehavior().stepsThroughSkippedCode) { + return; + } + const { client, sessionId } = connection; + const { logger } = this.options; + const stepper = new JsStepper({ + target: { sendRequest: (command, args, timeoutMs) => client.sendRequest(command, args, timeoutMs) as Promise }, + deliver: (event) => this.sendEvent(sessionId, event.event, event.body) + }); + // The session's choice is the root's: the start request's `smartStep`. + stepper.setEnabled((deps.launchConfig as { smartStep?: unknown } | undefined)?.smartStep === true); + connection.stepper = stepper; + try { + const response = (await client.sendRequest('requestCDPProxy', {}, 5000)) as { body?: { host?: string; port?: number; path?: string } }; + const info = response?.body; + if (!info?.host || !info.port || !info.path) { + throw new Error(`requestCDPProxy returned no address: ${JSON.stringify(info)}`); + } + const cdp = this.options.cdpClientFactory?.() ?? new CdpProxyClient(); + stepper.attachCdp(cdp); + await cdp.connect(info.host, info.port, info.path); + if (connection.closed) { + cdp.dispose(); + return; + } + connection.cdp = cdp; + await cdp.send('JsDebug.subscribe', { events: ['Debugger.paused', 'Debugger.resumed'] }); + // Re-enabling the (already enabled) domain makes the proxy replay the + // pause the target is in, if any. + await cdp.send('Debugger.enable', {}); + logger.info(`[ChildConnections] Child session ${sessionId}: the proxy stepper is on its CDP socket`); + } catch (error) { + stepper.detachCdp(); + logger.warn( + `[ChildConnections] Child session ${sessionId}: no CDP socket for the proxy stepper, its steps stay the adapter's: ${error instanceof Error ? error.message : String(error)}` + ); + } + } + + private closeStepper(connection: ChildConnection): void { + connection.stepper?.detachCdp(); + connection.cdp?.dispose(); + connection.cdp = undefined; + } + /** The policy for a connection opened here: never an in-session adopter (issue #1082). */ private policyForConnections(deps: ChildAdoptionDeps): AdapterPolicy { this.connectionPolicy ??= createChildSafePolicy(deps.policy); @@ -447,7 +525,15 @@ export class ChildConnections extends EventEmitter { private wireChildEvents(connection: ChildConnection): void { const { client, sessionId } = connection; for (const event of FORWARDED_CHILD_EVENTS) { - client.on(event, (body: unknown) => this.sendEvent(sessionId, event, body)); + client.on(event, (body: unknown) => { + // A step's own pauses and resumes are the stepper's (issue #1130): of + // their `stopped` events it reports one itself. + if ((event === 'stopped' || event === 'continued') && + connection.stepper?.withholds({ seq: 0, type: 'event', event, body } as DebugProtocol.Event)) { + return; + } + this.sendEvent(sessionId, event, body); + }); } client.on('terminated', (body: unknown) => { connection.terminatedSeen = true; @@ -465,6 +551,7 @@ export class ChildConnections extends EventEmitter { } private onConnectionClosed(connection: ChildConnection): void { + this.closeStepper(connection); if (this.clients.get(connection.sessionId) !== connection) { // Closed by this worker already (close()/closeAll()), reported then. return; diff --git a/src/proxy/dap-proxy-worker.ts b/src/proxy/dap-proxy-worker.ts index 1bb818c3e..016a3375c 100644 --- a/src/proxy/dap-proxy-worker.ts +++ b/src/proxy/dap-proxy-worker.ts @@ -2038,7 +2038,15 @@ export class DapProxyWorker { /** A child session's DAP request, answered on the child's envelope (issue #1081). */ private async forwardToChild(childClient: IDapClient, payload: DapCommandPayload): Promise { try { - const response = await childClient.sendRequest(payload.dapCommand, payload.dapArgs, payload.timeoutMs); + // A step of a child that steps through skipped code is its proxy + // stepper's (issue #1130); any other request may end a step in flight. + const stepped = this.childConnections?.stepRequest(payload.sessionId, payload.dapCommand, payload.dapArgs); + if (!stepped) { + await this.childConnections?.beforeRequest(payload.sessionId, payload.dapCommand); + } + const response = stepped + ? await stepped + : await childClient.sendRequest(payload.dapCommand, payload.dapArgs, payload.timeoutMs); this.sendDapResponse(payload.requestId, true, response, undefined, payload.sessionId); } catch (error) { const message = error instanceof Error ? error.message : String(error); diff --git a/tests/proxy/js-stepper.test.ts b/tests/proxy/js-stepper.test.ts new file mode 100644 index 000000000..2b85b7acc --- /dev/null +++ b/tests/proxy/js-stepper.test.ts @@ -0,0 +1,746 @@ +/** + * The proxy's own JavaScript stepper (issue #1130), against a scripted V8 + * and a scripted js-debug. + * + * The engine below plays what was measured through the real pair (the spike + * notes of the issue): every step command is answered, then `Debugger.resumed` + * and the next scripted `Debugger.paused` arrive; js-debug marks frame 0 of a + * `stackTrace` answer `deemphasize` for skipped code; and for every pause it + * keeps it sends one DAP `stopped` (reason `pause` for a step it did not + * request, `breakpoint` for a breakpoint it does not know) a moment later, + * and one `continued` per resume. + */ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { EventEmitter } from 'events'; +import type { DebugProtocol } from '@vscode/debugprotocol'; +import { JsStepper } from '../../src/proxy/js-stepper.js'; +import { ErrorMessages } from '../../src/utils/error-messages.js'; + +interface Frame { + fn: string; + script?: string; + /** 0-based line of the frame's position. */ + line: number; + col?: number; + /** 0-based line the function starts on; defaults to a line per function name. */ + fnLine?: number; + /** js-debug marks it skipped code. */ + skipped?: boolean; + /** The mark's wording; "Skipped by skipFiles" is a script-level verdict. */ + origin?: string; +} + +interface ScriptedPause { + frames: Frame[]; + reason?: string; + /** Breakpoint ids V8 reports; a function picks from the nets armed at that moment. */ + hits?: string[] | ((armed: ArmedBreakpoint[]) => string[]); + /** js-debug resumes this pause itself (a module-entry breakpoint): no `stopped`, then a `resumed`. */ + resumedByJsDebug?: boolean; + /** What js-debug reports this pause as. */ + dapReason?: string; + asyncParent?: { fn: string; script?: string; line: number; col?: number; skipped?: boolean }; +} + +interface ArmedBreakpoint { + id: string; + scriptId: string; + lineNumber: number; + columnNumber: number; +} + +const FN_LINES: Record = {}; +function fnLineOf(frame: Frame): number { + if (frame.fnLine !== undefined) return frame.fnLine; + FN_LINES[frame.fn] ??= 1000 + Object.keys(FN_LINES).length * 100; + return FN_LINES[frame.fn]; +} + +/** A scripted V8 behind a CDP socket, and the js-debug that watches it. */ +class Engine extends EventEmitter { + calls: Array<{ method: string; params: Record }> = []; + /** What the next resuming command leads to: a pause, or nothing (the program runs). */ + script: Array = []; + armed: ArmedBreakpoint[] = []; + removed: string[] = []; + /** Break positions per function, keyed `script:fnLine`; default: ten lines from the function's start. */ + positions = new Map>(); + sources = new Map(); + connected = true; + current: ScriptedPause | null = null; + /** DAP events js-debug sent, in order: the test feeds them to the stepper. */ + onDap: (event: DebugProtocol.Event) => void = () => undefined; + stackTraceFailures = 0; + stackTraceCalls: number[] = []; + private nextId = 0; + + isConnected(): boolean { + return this.connected; + } + + async send(method: string, params: Record = {}): Promise { + this.calls.push({ method, params }); + switch (method) { + case 'Debugger.stepInto': + case 'Debugger.stepOver': + case 'Debugger.stepOut': + case 'Debugger.resume': + if (!this.current) throw new Error(`${method}: Can only perform operation while paused.`); + this.current = null; + setImmediate(() => this.advance(true)); + return {} as T; + case 'Debugger.getPossibleBreakpoints': { + const start = params.start as { scriptId: string; lineNumber: number; columnNumber: number }; + const own = [...this.positions.entries()].find(([key]) => key === `${start.scriptId}:${start.lineNumber}`)?.[1]; + const list = own ?? Array.from({ length: 10 }, (_, i) => ({ lineNumber: start.lineNumber + i })); + return { locations: list.map((l) => ({ scriptId: start.scriptId, columnNumber: 0, ...l })) } as T; + } + case 'Debugger.setBreakpoint': { + const location = params.location as { scriptId: string; lineNumber: number; columnNumber: number }; + const id = `net:${++this.nextId}`; + this.armed.push({ id, ...location }); + return { breakpointId: id } as T; + } + case 'Debugger.removeBreakpoint': + this.removed.push(params.breakpointId as string); + this.armed = this.armed.filter((bp) => bp.id !== params.breakpointId); + return {} as T; + case 'Debugger.getScriptSource': + return { scriptSource: this.sources.get(params.scriptId as string) ?? '' } as T; + default: + return {} as T; + } + } + + /** V8 pauses here now (the stop a step starts from). */ + pauseAt(pause: ScriptedPause): void { + this.current = pause; + this.emit('cdp-event', 'Debugger.paused', this.toCdp(pause)); + } + + private advance(resumedFirst: boolean): void { + if (resumedFirst) { + this.emit('cdp-event', 'Debugger.resumed', {}); + this.onDap({ seq: 0, type: 'event', event: 'continued', body: { threadId: 1, allThreadsContinued: false } }); + } + const next = this.script.shift(); + if (!next || next === 'runs') { + return; + } + this.current = next; + this.emit('cdp-event', 'Debugger.paused', this.toCdp(next)); + if (next.resumedByJsDebug) { + // js-debug's own resume: the step in flight is gone with the pause. + setImmediate(() => { + this.current = null; + this.advance(true); + }); + return; + } + // js-debug reports a kept pause a timer tick later. + setTimeout(() => { + const hits = this.hitsOf(next); + const reason = next.dapReason ?? (hits.length > 0 ? 'breakpoint' : 'pause'); + this.onDap({ + seq: 0, + type: 'event', + event: 'stopped', + body: { + reason, + description: reason === 'pause' ? 'Paused on debugger statement' : 'Paused on breakpoint', + threadId: 1, + allThreadsStopped: false, + ...(reason === 'breakpoint' ? { hitBreakpointIds: [] } : {}) + } + }); + }, 3); + } + + private hitsOf(pause: ScriptedPause): string[] { + return typeof pause.hits === 'function' ? pause.hits(this.armed) : pause.hits ?? []; + } + + private toCdp(pause: ScriptedPause): Record { + const hits = this.hitsOf(pause); + // Fix the picked ids, so js-debug's later report sees the same pause. + pause.hits = hits; + return { + reason: pause.reason ?? (hits.length > 0 ? 'other' : 'step'), + hitBreakpoints: hits, + callFrames: pause.frames.map((f) => ({ + functionName: f.fn, + functionLocation: { scriptId: f.script ?? 'app', lineNumber: fnLineOf(f), columnNumber: 0 }, + location: { scriptId: f.script ?? 'app', lineNumber: f.line, columnNumber: f.col ?? 0 } + })), + ...(pause.asyncParent + ? { + asyncStackTrace: { + callFrames: [{ + functionName: pause.asyncParent.fn, + scriptId: pause.asyncParent.script ?? 'app', + lineNumber: pause.asyncParent.line, + columnNumber: pause.asyncParent.col ?? 0 + }] + } + } + : {}) + }; + } + + /** js-debug's `stackTrace` answer for the pause V8 is in. */ + stackTrace(levels: number): DebugProtocol.StackTraceResponse { + this.stackTraceCalls.push(levels); + if (this.stackTraceFailures > 0) { + this.stackTraceFailures--; + throw new Error('Thread is not paused'); + } + const pause = this.current; + if (!pause) { + throw new Error('Thread is not paused'); + } + const mark = (f: { fn: string; line: number; skipped?: boolean; origin?: string; script?: string }, id: number): DebugProtocol.StackFrame => ({ + id, + name: f.fn, + line: f.line + 1, + column: 1, + source: { path: `/app/${f.script ?? 'app'}.js`, ...(f.skipped ? { origin: f.origin ?? 'Skipped by skipFiles' } : {}) }, + presentationHint: (f.skipped ? 'deemphasize' : 'normal') as DebugProtocol.StackFrame['presentationHint'] + }); + const frames = pause.frames.map(mark); + if (pause.asyncParent) { + frames.push({ id: 900, name: 'await', line: 0, column: 0, presentationHint: 'label' }); + frames.push(mark(pause.asyncParent, 901)); + } + return { body: { stackFrames: frames.slice(0, levels) } } as DebugProtocol.StackTraceResponse; + } +} + +const tick = (ms = 0): Promise => new Promise((resolve) => setTimeout(resolve, ms)); + +function frames(...list: Frame[]): Frame[] { + return list; +} + +/** A program frame, and a frame of Node's own code. */ +const app = (fn: string, line: number, extra: Partial = {}): Frame => ({ fn, line, ...extra }); +const node = (fn: string, line: number, extra: Partial = {}): Frame => ({ fn, line, script: 'node:internal', skipped: true, ...extra }); + +describe('JsStepper (issue #1130)', () => { + let engine: Engine; + let stepper: JsStepper; + let delivered: DebugProtocol.Event[]; + /** Every DAP event of the target, with whether the stepper kept it. */ + let seen: Array<{ event: string; withheld: boolean }>; + let targetRequests: Array<{ command: string; args: unknown }>; + + const commands = (): string[] => engine.calls.map((c) => c.method).filter((m) => /step|resume/.test(m)); + const setBreakpoints = (): number => engine.calls.filter((c) => c.method === 'Debugger.setBreakpoint').length; + const stopped = (): DebugProtocol.StoppedEvent['body'] => delivered[0].body as DebugProtocol.StoppedEvent['body']; + + /** Wait until the chain is over and every event js-debug owes has arrived. */ + async function settled(): Promise { + await vi.waitFor(() => { + expect(stepper.describe().chain).toBe(false); + }, { timeout: 2000, interval: 2 }); + await tick(12); + } + + beforeEach(() => { + engine = new Engine(); + delivered = []; + seen = []; + targetRequests = []; + stepper = new JsStepper({ + target: { + sendRequest: async (command: string, args?: unknown) => { + targetRequests.push({ command, args }); + if (command !== 'stackTrace') throw new Error(`unexpected ${command}`); + return engine.stackTrace((args as { levels: number }).levels) as never; + } + }, + deliver: (event) => delivered.push(event), + tunables: { settleCeilingMs: 150, verdictCeilingMs: 150 } + }); + engine.onDap = (event) => { + seen.push({ event: event.event, withheld: stepper.withholds(event) }); + }; + stepper.attachCdp(engine); + stepper.setEnabled(true); + }); + + describe('which requests it serves', () => { + it('serves the three steps of a session that steps through skipped code, while V8 is paused', () => { + engine.pauseAt({ frames: frames(app('main', 10)) }); + expect(stepper.handles('stepIn')).toBe(true); + expect(stepper.handles('next')).toBe(true); + expect(stepper.handles('stepOut')).toBe(true); + expect(stepper.handles('continue')).toBe(false); + }); + + it('leaves the steps to the adapter when the session chose plain steps', () => { + engine.pauseAt({ frames: frames(app('main', 10)) }); + stepper.setEnabled(false); + expect(stepper.handles('stepIn')).toBe(false); + }); + + it('leaves a step into a named target to the adapter', () => { + engine.pauseAt({ frames: frames(app('main', 10)) }); + expect(stepper.handles('stepIn', { threadId: 1, targetId: 3 })).toBe(false); + }); + + it('serves nothing without a CDP socket, or before it has seen a pause', () => { + expect(stepper.handles('next')).toBe(false); + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.connected = false; + expect(stepper.handles('next')).toBe(false); + }); + }); + + describe('a step that V8 lands in program code', () => { + it('sends one CDP command and reports one stopped, as a step', async () => { + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [{ frames: frames(app('main', 11)) }]; + + const response = await stepper.request('next', { threadId: 1 }); + expect(response).toMatchObject({ success: true, command: 'next' }); + await settled(); + + expect(commands()).toEqual(['Debugger.stepOver']); + expect(delivered).toHaveLength(1); + // js-debug called it a pause on a debugger statement, which the core + // would read as a breakpoint or an entry stop: it leaves as a step. + expect(stopped()).toMatchObject({ reason: 'step', description: 'Paused', threadId: 1 }); + expect(stopped().text).toBeUndefined(); + // js-debug's own stopped and continued for the step were kept back. + expect(seen).toEqual([{ event: 'continued', withheld: true }, { event: 'stopped', withheld: true }]); + expect(setBreakpoints()).toBe(0); + }); + + it('never asks V8 to follow a call into a later task', async () => { + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [{ frames: frames(app('callee', 30), app('main', 10)) }]; + await stepper.request('stepIn', { threadId: 1 }); + await settled(); + expect(engine.calls.find((c) => c.method === 'Debugger.stepInto')?.params).toEqual({ breakOnAsyncCall: false }); + }); + }); + + describe('a step into skipped code', () => { + it('steps in again until the program\'s code is on top, under a net on the frame it returns to', async () => { + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [ + { frames: frames(node('emit', 5), app('main', 10)) }, + { frames: frames(node('emit', 6), app('main', 10)) }, + { frames: frames(app('listener', 40), node('emit', 7), app('main', 10)) } + ]; + await stepper.request('stepIn', { threadId: 1 }); + await settled(); + + expect(commands()).toEqual(['Debugger.stepInto', 'Debugger.stepInto', 'Debugger.stepInto']); + expect(stopped()).toMatchObject({ reason: 'step' }); + expect(stopped().text).toBeUndefined(); + // The net went up at the first skipped landing, on main's positions, and is gone. + expect(setBreakpoints()).toBeGreaterThan(0); + expect(engine.armed).toEqual([]); + expect(stepper.describe().nets).toBe(0); + // Three kept pauses, three stopped events from js-debug, one reported. + expect(seen.filter((e) => e.event === 'stopped')).toEqual(Array(3).fill({ event: 'stopped', withheld: true })); + expect(delivered).toHaveLength(1); + }); + + it('asks js-debug about a script once: "Skipped by skipFiles" is a verdict on the script', async () => { + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [ + { frames: frames(node('a', 1), app('main', 10)) }, + { frames: frames(node('a', 2), app('main', 10)) }, + { frames: frames(node('a', 3), app('main', 10)) }, + { frames: frames(app('main', 11)) } + ]; + await stepper.request('stepIn', { threadId: 1 }); + await settled(); + // One levels-1 question for the node script, one for the landing; the + // levels-80 one is the net's look at the whole stack. + expect(engine.stackTraceCalls.filter((levels) => levels === 1)).toHaveLength(2); + }); + + it('asks again each time for a frame skipped for its position, not its script', async () => { + const helper = (line: number): Frame => ({ fn: '__awaiter', line, script: 'app', skipped: true, origin: 'Skipped by smartStep' }); + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [ + { frames: frames(helper(1), app('main', 10)) }, + { frames: frames(helper(2), app('main', 10)) }, + { frames: frames(app('callee', 50), helper(3), app('main', 10)) } + ]; + await stepper.request('stepIn', { threadId: 1 }); + await settled(); + expect(engine.stackTraceCalls.filter((levels) => levels === 1)).toHaveLength(3); + expect(stopped()).toMatchObject({ reason: 'step' }); + }); + + it('steps out once the budget is spent, lands by the net when V8 loses the step-out, and says the line called only skipped code', async () => { + stepper = new JsStepper({ + target: { sendRequest: async (_c: string, args?: unknown) => engine.stackTrace((args as { levels: number }).levels) as never }, + deliver: (event) => delivered.push(event), + tunables: { budget: 2, settleCeilingMs: 150, verdictCeilingMs: 150 } + }); + stepper.attachCdp(engine); + stepper.setEnabled(true); + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [ + { frames: frames(node('require', 1), app('main', 10)) }, + { frames: frames(node('require', 2), app('main', 10)) }, + { frames: frames(node('require', 3), app('main', 10)) }, + // The step-out is lost (the frame returns through try...finally, issue + // #1161): no step landing. The net on main catches the return instead. + { frames: frames(app('main', 11)), reason: 'other', hits: (armed) => [armed[0].id] } + ]; + await stepper.request('stepIn', { threadId: 1 }); + await settled(); + + expect(commands()).toEqual(['Debugger.stepInto', 'Debugger.stepInto', 'Debugger.stepInto', 'Debugger.stepOut']); + expect(stopped()).toMatchObject({ reason: 'step', description: 'Paused' }); + // js-debug reported the net hit as a breakpoint with no ids: not what leaves. + expect(stopped().hitBreakpointIds).toBeUndefined(); + expect(stopped().text).toBe(ErrorMessages.stepIntoFoundOnlySkippedCode()); + expect(engine.armed).toEqual([]); + }); + + it('steps in again when it comes back to the line it left, at the same depth', async () => { + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [ + { frames: frames(node('first', 1), app('main', 10)) }, + // Back on line 10 (the line's second call is next), then into it. + { frames: frames(app('main', 10, { col: 14 })) }, + { frames: frames(app('second', 60), app('main', 10, { col: 14 })) } + ]; + await stepper.request('stepIn', { threadId: 1 }); + await settled(); + expect(commands()).toEqual(['Debugger.stepInto', 'Debugger.stepInto', 'Debugger.stepInto']); + expect(stopped()).toMatchObject({ reason: 'step' }); + }); + + it('stops where it is, and says so, when every command it may send is spent in skipped code', async () => { + stepper = new JsStepper({ + target: { sendRequest: async (_c: string, args?: unknown) => engine.stackTrace((args as { levels: number }).levels) as never }, + deliver: (event) => delivered.push(event), + tunables: { budget: 1, commandCap: 3, settleCeilingMs: 150, verdictCeilingMs: 150 } + }); + stepper.attachCdp(engine); + stepper.setEnabled(true); + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = Array.from({ length: 6 }, (_, i) => ({ frames: frames(node('deep', i), node('deeper', 1), app('main', 10)) })); + await stepper.request('stepIn', { threadId: 1 }); + await settled(); + expect(commands()).toHaveLength(3); + expect(stopped()).toMatchObject({ reason: 'step', text: ErrorMessages.stepStillInSkippedCode(3) }); + expect(engine.armed).toEqual([]); + }); + }); + + describe('a step over or out that returns into skipped code', () => { + it('steps out toward the nearest program frame below, at once', async () => { + engine.pauseAt({ frames: frames(app('listener', 40), node('emit', 7), app('main', 10)) }); + engine.script = [ + { frames: frames(node('emit', 8), app('main', 10)) }, + { frames: frames(app('main', 11)) } + ]; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(commands()).toEqual(['Debugger.stepOver', 'Debugger.stepOut']); + expect(stopped()).toMatchObject({ reason: 'step' }); + expect(stopped().text).toBeUndefined(); + }); + + it('resumes and reports nothing when no frame of the program is below: the stack the step started on is gone', async () => { + engine.pauseAt({ frames: frames(app('handler', 20), node('emit', 7), node('parserOnIncoming', 3)) }); + engine.script = [{ frames: frames(node('emit', 8), node('parserOnIncoming', 3)) }, 'runs']; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + // No step-out from the bottom frames: that lands in the next task's internals. + expect(commands()).toEqual(['Debugger.stepOut', 'Debugger.resume']); + expect(delivered).toEqual([]); + expect(engine.armed).toEqual([]); + expect(stepper.describe()).toMatchObject({ chain: false, nets: 0 }); + }); + }); + + describe('nets: a step never counts on V8 alone to come back to a frame (issue #1161)', () => { + it('step_out arms the frame it returns to before the first command, and lands by the net when V8 never pauses', async () => { + engine.pauseAt({ frames: frames(app('withFinally', 5), app('caller', 14)) }); + // V8's step-out is lost; the next thing V8 says is the net's breakpoint. + engine.script = [{ frames: frames(app('caller', 15)), reason: 'other', hits: (armed) => [armed[1].id] }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + + const firstStep = engine.calls.findIndex((c) => c.method === 'Debugger.stepOut'); + const firstNet = engine.calls.findIndex((c) => c.method === 'Debugger.setBreakpoint'); + expect(firstNet).toBeGreaterThanOrEqual(0); + expect(firstNet).toBeLessThan(firstStep); + // The net is on the caller's function, from its own position on. + const netCalls = engine.calls.filter((c) => c.method === 'Debugger.setBreakpoint'); + expect(new Set(netCalls.map((c) => (c.params.location as { scriptId: string }).scriptId))).toEqual(new Set(['app'])); + expect(stopped()).toMatchObject({ reason: 'step' }); + expect(engine.armed).toEqual([]); + expect(engine.removed).toHaveLength(netCalls.length); + }); + + it('a step over arms nothing in a function with no `finally`, and the frame it returns to in one that has it', async () => { + engine.sources.set('app', Array.from({ length: 2000 }, () => 'x();').join('\n')); + engine.pauseAt({ frames: frames(app('plain', 5), app('caller', 14)) }); + engine.script = [{ frames: frames(app('plain', 6), app('caller', 14)) }]; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBe(0); + + delivered.length = 0; + const source = Array.from({ length: 2000 }, () => 'x();'); + source[fnLineOf(app('guarded', 0)) + 2] = 'try { return x(); } finally { done(); }'; + engine.sources.set('lib', source.join('\n')); + engine.pauseAt({ frames: frames(app('guarded', fnLineOf(app('guarded', 0)) + 2, { script: 'lib' }), app('caller', 14)) }); + engine.script = [{ frames: frames(app('caller', 15)), reason: 'other', hits: (armed) => [armed[1].id] }]; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBeGreaterThan(0); + expect(stopped()).toMatchObject({ reason: 'step' }); + expect(engine.armed).toEqual([]); + }); + + it('puts no net on the frame being stepped in: a function with `finally` that returns to itself', async () => { + const source = Array.from({ length: 2000 }, () => 'x();'); + const start = fnLineOf(app('down', 0)); + source[start + 2] = 'try { return down(n - 1); } finally { done(); }'; + engine.sources.set('app', source.join('\n')); + engine.pauseAt({ frames: frames(app('down', start + 2), app('down', start + 2), app('main', 10)) }); + engine.script = [{ frames: frames(app('down', start + 3), app('down', start + 2), app('main', 10)) }]; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBe(0); + expect(stopped()).toMatchObject({ reason: 'step' }); + }); + + it('a net hit deeper than the frame it guards is not a landing: a step-out of a recursive function steps out again', async () => { + const start = fnLineOf(app('down', 0)); + engine.pauseAt({ frames: frames(app('down', start + 3), app('down', start + 5), app('main', 10)) }); + engine.script = [ + // The frame being left runs on to its own finally block: a net position, one frame too deep. + { frames: frames(app('down', start + 7), app('down', start + 5), app('main', 10)), reason: 'ambiguous', hits: (armed) => [armed[0].id] }, + { frames: frames(app('down', start + 7), app('main', 10)), reason: 'other', hits: (armed) => [armed[0].id] } + ]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(commands()).toEqual(['Debugger.stepOut', 'Debugger.stepOut']); + expect(stopped()).toMatchObject({ reason: 'step' }); + expect(engine.armed).toEqual([]); + }); + + it('an async function with no program frame below returns to its awaiter: the net goes on the async parent, at any depth', async () => { + engine.pauseAt({ + frames: frames(app('work', 9), node('processTicksAndRejections', 70)), + asyncParent: { fn: 'main', line: 16, col: 12 } + }); + engine.script = [{ frames: frames(app('main', 17)), reason: 'other', hits: (armed) => [armed[0].id] }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + // Asked from the awaiter's own position, since its frame is not on the stack. + const asked = engine.calls.find((c) => c.method === 'Debugger.getPossibleBreakpoints'); + expect(asked?.params.start).toEqual({ scriptId: 'app', lineNumber: 16, columnNumber: 12 }); + expect(stopped()).toMatchObject({ reason: 'step' }); + expect(engine.armed).toEqual([]); + }); + + it('caps a net, and takes it from the frame\'s own position on', async () => { + const start = fnLineOf(app('big', 0)); + engine.positions.set(`app:${start}`, Array.from({ length: 300 }, (_, i) => ({ lineNumber: start + i }))); + engine.pauseAt({ frames: frames(app('leaf', 5), app('big', start + 200)) }); + engine.script = [{ frames: frames(app('big', start + 201)) }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + const lines = engine.calls + .filter((c) => c.method === 'Debugger.setBreakpoint') + .map((c) => (c.params.location as { lineNumber: number }).lineNumber); + expect(lines).toHaveLength(24); + expect(Math.min(...lines)).toBe(start + 200); + expect(Math.max(...lines)).toBe(start + 223); + }); + + it('asks from the frame\'s own line when the function position answers for a nested function', async () => { + // Top-level code that starts with a function declaration: V8 answers + // the nested function's positions for the module's own position. + const moduleStart = fnLineOf(app('(module)', 0)); + engine.positions.set(`app:${moduleStart}`, [{ lineNumber: moduleStart + 1 }, { lineNumber: moduleStart + 2 }]); + engine.positions.set('app:900', [{ lineNumber: 900 }, { lineNumber: 901 }, { lineNumber: 902 }]); + engine.pauseAt({ frames: frames(app('callee', 5), app('(module)', 900, { fnLine: moduleStart })) }); + engine.script = [{ frames: frames(app('(module)', 901, { fnLine: moduleStart })) }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + const lines = engine.calls + .filter((c) => c.method === 'Debugger.setBreakpoint') + .map((c) => (c.params.location as { lineNumber: number }).lineNumber); + expect(lines).toEqual([900, 901, 902]); + }); + }); + + describe('a pause that is not the stepper\'s', () => { + it('ends the chain as itself when js-debug keeps it: a breakpoint in a callee', async () => { + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [{ frames: frames(app('callee', 30), app('main', 10)), reason: 'ambiguous', hits: ['js-debug:7'], dapReason: 'breakpoint' }]; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(delivered).toHaveLength(1); + // js-debug's own stopped, untouched. + expect(stopped()).toMatchObject({ reason: 'breakpoint', description: 'Paused on breakpoint' }); + expect(commands()).toEqual(['Debugger.stepOver']); + }); + + it('removes its nets before a real stop is forwarded', async () => { + engine.pauseAt({ frames: frames(app('leaf', 5), app('caller', 14)) }); + engine.script = [{ frames: frames(app('other', 80), app('leaf', 5), app('caller', 14)), reason: 'exception', dapReason: 'exception' }]; + let armedAtDelivery = -1; + stepper = new JsStepper({ + target: { sendRequest: async (_c: string, args?: unknown) => engine.stackTrace((args as { levels: number }).levels) as never }, + deliver: (event) => { + armedAtDelivery = engine.armed.length; + delivered.push(event); + }, + tunables: { settleCeilingMs: 150, verdictCeilingMs: 150 } + }); + stepper.attachCdp(engine); + stepper.setEnabled(true); + engine.pauseAt({ frames: frames(app('leaf', 5), app('caller', 14)) }); + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(stopped()).toMatchObject({ reason: 'exception' }); + expect(armedAtDelivery).toBe(0); + }); + + it('waits on when js-debug resumes it by itself, and lands by the net (issue #1162, in a step-in walk)', async () => { + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [ + { frames: frames(node('require', 1), app('main', 10)) }, + // js-debug's module-entry breakpoint: paused and resumed by js-debug. V8 dropped the step. + { frames: frames(app('mod', 0, { script: 'mod' }), node('require', 2), app('main', 10)), reason: 'ambiguous', hits: ['js-debug:entry'], resumedByJsDebug: true }, + { frames: frames(app('main', 11)), reason: 'other', hits: (armed) => [armed[0].id] } + ]; + await stepper.request('stepIn', { threadId: 1 }); + await settled(); + // Nothing was sent after js-debug's resume: the net was already there. + expect(commands()).toEqual(['Debugger.stepInto', 'Debugger.stepInto']); + expect(stopped()).toMatchObject({ reason: 'step' }); + // Two kept pauses, two stopped events withheld; the resumed one had none. + expect(seen.filter((e) => e.event === 'stopped')).toHaveLength(2); + expect(engine.armed).toEqual([]); + }); + }); + + describe('what it reports, and when', () => { + it('reports once, however js-debug orders its stopped and continued events', async () => { + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [ + { frames: frames(node('a', 1), app('main', 10)) }, + { frames: frames(node('a', 2), app('main', 10)) }, + { frames: frames(app('main', 11)) } + ]; + await stepper.request('stepIn', { threadId: 1 }); + await settled(); + // Each stopped arrives a timer tick after its pause: after the continued of the next resume. + expect(seen.map((e) => e.event).join(' ')).toMatch(/continued continued/); + expect(seen.every((e) => e.withheld)).toBe(true); + expect(delivered).toHaveLength(1); + }); + + it('asks again while js-debug says it is not paused yet', async () => { + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [{ frames: frames(app('main', 11)) }]; + engine.stackTraceFailures = 2; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(engine.stackTraceCalls).toEqual([1, 1, 1]); + expect(stopped()).toMatchObject({ reason: 'step' }); + }); + + it('reports the landing even when js-debug\'s stopped never comes, and drops the late one', async () => { + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [{ frames: frames(app('main', 11)) }]; + const late: DebugProtocol.Event[] = []; + engine.onDap = (event) => { + if (event.event === 'stopped') late.push(event); + else stepper.withholds(event); + }; + await stepper.request('next', { threadId: 4 }); + await settled(); + expect(stopped()).toMatchObject({ reason: 'step', threadId: 4, allThreadsStopped: false }); + // The owed event arrives after the chain is over: still the step's own. + expect(stepper.withholds(late[0])).toBe(true); + // Anything after it is somebody else's stop. + expect(stepper.withholds({ seq: 0, type: 'event', event: 'stopped', body: { reason: 'breakpoint', threadId: 4 } })).toBe(false); + }); + + it('lets every event through when no step is in flight', () => { + engine.pauseAt({ frames: frames(app('main', 10)) }); + expect(stepper.withholds({ seq: 0, type: 'event', event: 'stopped', body: { reason: 'breakpoint', threadId: 1 } })).toBe(false); + expect(stepper.withholds({ seq: 0, type: 'event', event: 'continued', body: { threadId: 1 } })).toBe(false); + expect(stepper.withholds({ seq: 0, type: 'event', event: 'output', body: { output: 'x' } })).toBe(false); + }); + }); + + describe('what ends a step still in flight', () => { + async function stepOutAndRun(): Promise { + engine.pauseAt({ frames: frames(app('work', 9), app('main', 14)) }); + engine.script = ['runs']; + await stepper.request('stepOut', { threadId: 1 }); + await tick(10); + // The program is running toward the net; the chain waits. + expect(stepper.describe()).toMatchObject({ chain: true }); + expect(engine.armed.length).toBeGreaterThan(0); + } + + it('a continue request: the net is removed before the request goes on', async () => { + await stepOutAndRun(); + await stepper.beforeRequest('continue'); + expect(engine.armed).toEqual([]); + expect(stepper.describe()).toMatchObject({ chain: false, nets: 0 }); + expect(delivered).toEqual([]); + }); + + it('a request that neither resumes nor ends the target leaves it alone', async () => { + await stepOutAndRun(); + await stepper.beforeRequest('stackTrace'); + await stepper.beforeRequest('pause'); + expect(stepper.describe()).toMatchObject({ chain: true }); + expect(engine.armed.length).toBeGreaterThan(0); + }); + + it('the CDP socket closing: nothing can be removed, and nothing throws', async () => { + await stepOutAndRun(); + stepper.detachCdp(); + await tick(10); + expect(stepper.describe()).toMatchObject({ chain: false, nets: 0, paused: false }); + expect(stepper.handles('next')).toBe(false); + }); + + it('a later landing of that step is still reported: stepping over an await that takes a while', async () => { + await stepOutAndRun(); + // The awaited work is done: V8 reaches the net. + engine.script = []; + const pause: ScriptedPause = { frames: frames(app('main', 15)), reason: 'other', hits: [engine.armed[0].id] }; + engine.current = pause; + engine.emit('cdp-event', 'Debugger.paused', { + reason: 'other', + hitBreakpoints: pause.hits, + callFrames: [{ functionName: 'main', functionLocation: { scriptId: 'app', lineNumber: fnLineOf(app('main', 0)), columnNumber: 0 }, location: { scriptId: 'app', lineNumber: 15, columnNumber: 0 } }] + }); + seen.push({ event: 'stopped', withheld: stepper.withholds({ seq: 0, type: 'event', event: 'stopped', body: { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [] } }) }); + await settled(); + expect(stopped()).toMatchObject({ reason: 'step' }); + expect(engine.armed).toEqual([]); + }); + }); + + it('refuses a step it cannot start, and leaves no net behind', async () => { + engine.pauseAt({ frames: frames(app('leaf', 5), app('caller', 14)) }); + engine.current = null; // V8 resumed behind the stepper's back + await expect(stepper.request('stepOut', { threadId: 1 })).rejects.toThrow(/while paused/); + expect(engine.armed).toEqual([]); + expect(stepper.describe()).toMatchObject({ chain: false, nets: 0 }); + }); +}); diff --git a/tests/unit/proxy/minimal-dap.test.ts b/tests/unit/proxy/minimal-dap.test.ts index 77f5d5072..48cb0c800 100644 --- a/tests/unit/proxy/minimal-dap.test.ts +++ b/tests/unit/proxy/minimal-dap.test.ts @@ -53,6 +53,9 @@ describe('MinimalDapClient', () => { getChildTargetState: Mock; shutdown: Mock; flushEvents: Mock; + stepRequest: Mock; + beforeChildRequest: Mock; + setStepThroughSkippedCode: Mock; }; const createChildSessionManagerStub = (): ChildSessionManagerStub => { @@ -67,6 +70,11 @@ describe('MinimalDapClient', () => { emitter.getChildTargetState = vi.fn().mockReturnValue('none'); emitter.shutdown = vi.fn().mockResolvedValue(undefined); emitter.flushEvents = vi.fn().mockReturnValue(Promise.resolve()); + // The proxy stepper (issue #1130): off unless a case turns it on, so a + // step goes to the child as it is. + emitter.stepRequest = vi.fn().mockReturnValue(null); + emitter.beforeChildRequest = vi.fn().mockResolvedValue(undefined); + emitter.setStepThroughSkippedCode = vi.fn(); return emitter; }; @@ -2488,7 +2496,27 @@ describe('MinimalDapClient', () => { attachArguments: { localRoot: '/app', sourceMaps: false, port: 9229, customAdapterOption: 'preserved' } }); const sent = JSON.parse(mockSocket.write.mock.calls.at(-1)[0].toString().split('\r\n\r\n')[1]); - expect(sent.arguments).toEqual(args); + // Everything the caller sent, plus the one key the proxy owns: the + // adapter's own stepper is always off (issue #1130). + expect(sent.arguments).toEqual({ ...args, smartStep: false }); + }); + + it.each([ + ['launch', { request: 'launch', program: '/app/main.js', smartStep: true }, true], + ['launch', { request: 'launch', program: '/app/main.js', smartStep: false }, false], + ['attach', { request: 'attach', port: 9229, smartStep: true }, true], + ['attach', { request: 'attach', port: 9229 }, false] + ] as const)('reads the %s request\'s smartStep as the session\'s choice and keeps the adapter\'s stepper off (issue #1130)', async (command, start, chose) => { + const manager = (client as unknown as { childSessionManager: ChildSessionManagerStub }).childSessionManager; + manager.setStepThroughSkippedCode = vi.fn(); + const args = Object.freeze({ ...start }); + await client.sendRequest(command, args); + // The session's choice goes to the proxy's stepper... + expect(manager.setStepThroughSkippedCode).toHaveBeenCalledWith(chose); + // ...and js-debug never gets its own stepper turned on, whatever was asked. + const sent = JSON.parse(mockSocket.write.mock.calls.at(-1)[0].toString().split('\r\n\r\n')[1]); + expect(sent.arguments.smartStep).toBe(false); + expect(sent.arguments).toEqual({ ...start, smartStep: false }); }); it.each(['attach', 'launch'] as const)('ignores nonboolean entry intent for %s', async command => { From 483bd076f10303953ea0165b929a964771b994cf Mon Sep 17 00:00:00 2001 From: JF Date: Sun, 15 Nov 2026 21:09:51 -0500 Subject: [PATCH 04/24] fix(javascript): a step-in issued inside a dependency walks on into the handler; what a pending step says (#1130) Found by the e2e suite on the branch. A step_into issued inside express, on the call that leads to the program's handler, answered pending: the stepper looked for a frame of the program below the first skipped landing, found none (express is called by Node) and resumed the program. That is #687's load-bearing case: a request path enters the program by calls, not returns. "The stack the step started on is gone" is a conclusion about stepping OUT. A step-in now walks on while it has budget, with or without a frame of the program below, and the stepper resumes the program only when the walk would have to step out and there is nowhere of the program's to step out to. It looks at the whole stack once per chain, not at every landing. Two unit cases were red on the committed stepper. A pending JavaScript step no longer blames js-debug's smart stepper, which is off. Issued from skipped code, it says the step does not stop in skipped code, names the frame, and names the switch that steps inside that code. Issued from the program's own code, it says the step left its frame and nothing of the program has run since. A pending pause gets no hint of this kind any more: nothing steps away from a pause. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn69pXrYMWc1JUwv5v8 --- .../src/interfaces/adapter-policy-js.ts | 71 +++++------ src/proxy/js-stepper.ts | 20 +++- tests/e2e/mcp-server-smoke-javascript.test.ts | 12 +- tests/proxy/js-stepper.test.ts | 50 ++++++++ tests/unit/shared/adapter-policy-js.test.ts | 111 +++++++++--------- 5 files changed, 160 insertions(+), 104 deletions(-) diff --git a/packages/shared/src/interfaces/adapter-policy-js.ts b/packages/shared/src/interfaces/adapter-policy-js.ts index a107514f7..55a7829a7 100644 --- a/packages/shared/src/interfaces/adapter-policy-js.ts +++ b/packages/shared/src/interfaces/adapter-policy-js.ts @@ -407,21 +407,21 @@ export const JsDebugAdapterPolicy = { hasNoSource(frame.file || '') && (frame.line ?? 0) === 0, /** - * Why a launch-mode pause or step may never stop (issue #678). js-debug's - * smart-stepper (`smartStep`, on by default while justMyCode is true) keeps - * stepping — in the direction that was asked for, step-out after 256 tries — - * while the program is in a frame the skip list blackboxes, and Node - * internals are on the default list: on an idle server every pause lands - * there, and a request path enters user code by calls, not returns, so - * neither the pause nor a step issued from a skipped frame lands. Measured - * on the #686 build: default skip list + smartStep:false → the pause landed; - * internals-only skip list + smartStep:true → the chase, with node_modules - * NOT blackboxed. So the hints key on the effective smartStep plus whether - * the frame in question is skipped, both from the helpers the launch - * transform uses. A caller's own glob (`**\/vendor/**`) is not matched — this - * package has no glob matcher, and an over-match would be a false hint — so - * a step from such a frame gets silence. Attach sessions default neither key - * (#513) and get nothing here. + * What a launch-mode step that has not landed is waiting for (issues #678, + * #1130). The proxy's own stepper serves the steps of a session whose + * effective `smartStep` is on: it never stops in skipped code, it steps out + * toward the nearest frame of the program below, and with none below it + * resumes the program (the stack the step started on is gone). So a step + * still pending after the grace window has run off the program's stack, or + * is waiting on work in flight. A step issued from skipped code (a + * breakpoint inside a dependency) gets the sentence that names the frame + * and the switch that steps inside that code; the frame is matched with the + * helpers the launch transform uses, and a caller's own glob + * (`**\/vendor/**`) is not matched, since this package has no glob matcher. + * A pause gets nothing: js-debug's stepper, which stepped away from a pause + * that landed in skipped code, is off (the pending pause has its own + * wording, issue #1146). Attach sessions default neither key (#513) and get + * nothing here. */ describePendingStop: (info: PendingStopContext): string | undefined => { if (info.attachMode) { @@ -431,34 +431,27 @@ export const JsDebugAdapterPolicy = { if (!resolveJsLaunchSmartStep(merged)) { return undefined; } - const internalsSkipped = jsLaunchSkipsNodeInternals(merged); + // A pause is never stepped away from any more: it lands where the + // program is, in Node's own code if that is where it is. if (info.operation === 'pause') { - return internalsSkipped - ? "js-debug's smart-stepper is on for this launch (smartStep: true, the default while justMyCode is true) and " + - 'Node internals are skipped, so a pause that lands in internals — where an idle server always is — is ' + - 'stepped through instead of reported and may never land. Set a breakpoint in your own code, or relaunch ' + - 'with dapLaunchArgs.justMyCode: false (or adapterLaunchConfig.smartStep: false) to pause where the program is.' - : undefined; - } - const frame = info.fromFrame; - if (!frame) { return undefined; } - const file = frame.file || ''; - const where = `${file}:${frame.line}`; - if (internalsSkipped && (file.includes('') || file.startsWith('node:'))) { - return `The step was issued from a skipped frame in Node internals (${where}); js-debug's smart-stepper keeps ` + - 'stepping while the program is in skipped code, so on a request path the step may never land. Use ' + - 'continue_execution with a breakpoint in your own code, or relaunch with adapterLaunchConfig.smartStep: false ' + - 'to stop in the next frame V8 does not skip.'; - } - if (jsLaunchBlackboxesNodeModules(merged) && NODE_MODULES_SEGMENT.test(file)) { - return `The step was issued from a skipped frame (${where}); this launch blackboxes node_modules ` + - "(justMyCode: true) and js-debug's smart-stepper keeps stepping while the program is in skipped code, so on " + - 'a request path the step may never land. Relaunch with dapLaunchArgs.justMyCode: false to step through ' + - 'dependencies.'; + const frame = info.fromFrame; + const file = frame?.file || ''; + const fromSkippedCode = frame !== undefined && ( + (jsLaunchSkipsNodeInternals(merged) && (file.includes('') || file.startsWith('node:'))) || + (jsLaunchBlackboxesNodeModules(merged) && NODE_MODULES_SEGMENT.test(file)) + ); + if (fromSkippedCode) { + return `The step was issued from skipped code (${file}:${frame.line}), and a step does not stop in skipped code: ` + + "it runs until your program's code is on top again. That has not happened: either nothing of your program " + + "was below that frame, so the step ended in Node's event loop and the program is running, or the call is " + + 'still in flight. It stops at the next breakpoint in your own code. Relaunch with ' + + 'dapLaunchArgs.justMyCode: false (or adapterLaunchConfig.smartStep: false) to step inside that code.'; } - return undefined; + return 'The step left the frame it started in and nothing of your program has run since: a function that Node ' + + 'called returned to the event loop, or the line is waiting on work still in flight. The program is running; ' + + 'wait_for_stop answers when the step lands or a breakpoint is hit.'; }, /** diff --git a/src/proxy/js-stepper.ts b/src/proxy/js-stepper.ts index 230416ffe..0e988cafe 100644 --- a/src/proxy/js-stepper.ts +++ b/src/proxy/js-stepper.ts @@ -189,6 +189,8 @@ interface Chain { steppedOutOfSkipped: boolean; /** Every command the chain may send is spent and skipped code is still on top. */ capped: boolean; + /** The stack holds no frame of the program below the skipped code on top (looked at once). */ + nothingBelow: boolean; startedAt: number; } @@ -326,6 +328,7 @@ export class JsStepper { unwinding: false, steppedOutOfSkipped: false, capped: false, + nothingBelow: false, startedAt: Date.now() }; this.chain = chain; @@ -513,14 +516,25 @@ export class JsStepper { if (skipped) { // Before anything else, a net on the program frame this code returns to. - const guarded = this.nets.some((net) => net.depth < depth || net.depth === Infinity); - if (!guarded && !(await this.armReturnTarget(pause, null))) { - return { kind: 'left-stack' }; + let guarded = this.nets.some((net) => net.depth < depth || net.depth === Infinity); + if (!guarded && !chain.nothingBelow) { + guarded = await this.armReturnTarget(pause, null); + // Nothing of the program can come to be below without the chain + // landing in it first: one look per chain. + chain.nothingBelow = !guarded; } + // A step-in walks on while it has budget, with or without anything + // below: a step issued inside a dependency reaches the program's + // handler by calls, not returns (issue #687). if (chain.kind === 'in' && !chain.unwinding && chain.spent < this.tunables.budget) { chain.spent++; return { kind: 'command', command: CDP_COMMAND.in }; } + // It has to step out now. With nothing of the program below, the stack + // the step started on is gone. + if (!guarded) { + return { kind: 'left-stack' }; + } if (chain.kind === 'in') { chain.steppedOutOfSkipped = true; } diff --git a/tests/e2e/mcp-server-smoke-javascript.test.ts b/tests/e2e/mcp-server-smoke-javascript.test.ts index 4cc5e7ba0..e0298943c 100644 --- a/tests/e2e/mcp-server-smoke-javascript.test.ts +++ b/tests/e2e/mcp-server-smoke-javascript.test.ts @@ -419,12 +419,16 @@ describe('JavaScript Debugging - Simple Smoke Tests', () => { const step = parseSdkToolResult(await mcpClient!.callTool({ name: 'step_over', arguments: { sessionId } })); expect(step.success, JSON.stringify(step)).toBe(true); - // js-debug steps out of the blackboxed frame and the request completes - // without ever reaching unskipped code: the step is lost, and the - // response says why and what to do about it. + // A step does not stop in skipped code: the server's stepper steps out + // toward the nearest frame of the program below, and here there is none + // (express was called by Node), so the program is resumed and the request + // completes. The response says what happened and what steps inside that + // code (issue #1130; it used to blame js-debug's own stepper). expect(step.pending, JSON.stringify(step)).toBe(true); - expect(step.message).toMatch(/skipped frame/); + expect(step.message).toMatch(/issued from skipped code/); + expect(step.message).toMatch(/application\.js:\d+/); expect(step.message).toMatch(/justMyCode: false/); + expect(step.message).not.toMatch(/smart-stepper/); console.log(`[JS Simple Smoke] ✓ Lost dependency step explained (${label})`); }, 60000); diff --git a/tests/proxy/js-stepper.test.ts b/tests/proxy/js-stepper.test.ts index 2b85b7acc..af321e0bc 100644 --- a/tests/proxy/js-stepper.test.ts +++ b/tests/proxy/js-stepper.test.ts @@ -437,6 +437,56 @@ describe('JsStepper (issue #1130)', () => { }); }); + describe('a step issued inside skipped code, with nothing of the program below (issue #687)', () => { + const express = (line: number): Frame => ({ fn: 'handle', line, script: 'express', skipped: true }); + + it('step_into walks on into the program\'s handler: a request path enters it by calls, not returns', async () => { + engine.pauseAt({ frames: frames(express(177), node('emit', 7), node('parserOnIncoming', 3)) }); + engine.script = [ + { frames: frames(node('Url', 77), express(177), node('emit', 7)) }, + { frames: frames(node('Url', 78), express(177), node('emit', 7)) }, + { frames: frames(app('handler', 16), express(250), node('emit', 7)) } + ]; + await stepper.request('stepIn', { threadId: 1 }); + await settled(); + expect(commands()).toEqual(['Debugger.stepInto', 'Debugger.stepInto', 'Debugger.stepInto']); + expect(stopped()).toMatchObject({ reason: 'step' }); + // Nothing to guard: no frame of the program was below. One look at the stack, not one per landing. + expect(setBreakpoints()).toBe(0); + expect(engine.stackTraceCalls.filter((levels) => levels > 1)).toHaveLength(1); + }); + + it('step_into resumes the program only once its budget is spent', async () => { + stepper = new JsStepper({ + target: { sendRequest: async (_c: string, args?: unknown) => engine.stackTrace((args as { levels: number }).levels) as never }, + deliver: (event) => delivered.push(event), + tunables: { budget: 2, settleCeilingMs: 150, verdictCeilingMs: 150 } + }); + stepper.attachCdp(engine); + stepper.setEnabled(true); + engine.pauseAt({ frames: frames(express(177), node('emit', 7)) }); + engine.script = [ + { frames: frames(node('Url', 77), express(177), node('emit', 7)) }, + { frames: frames(node('Url', 78), express(177), node('emit', 7)) }, + { frames: frames(node('Url', 79), express(177), node('emit', 7)) }, + 'runs' + ]; + await stepper.request('stepIn', { threadId: 1 }); + await settled(); + expect(commands()).toEqual(['Debugger.stepInto', 'Debugger.stepInto', 'Debugger.stepInto', 'Debugger.resume']); + expect(delivered).toEqual([]); + }); + + it('step_over resumes at once: it would have to step out, and there is nowhere of the program\'s to step out to', async () => { + engine.pauseAt({ frames: frames(express(177), node('emit', 7)) }); + engine.script = [{ frames: frames(node('emit', 8)) }, 'runs']; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(commands()).toEqual(['Debugger.stepOver', 'Debugger.resume']); + expect(delivered).toEqual([]); + }); + }); + describe('a step over or out that returns into skipped code', () => { it('steps out toward the nearest program frame below, at once', async () => { engine.pauseAt({ frames: frames(app('listener', 40), node('emit', 7), app('main', 10)) }); diff --git a/tests/unit/shared/adapter-policy-js.test.ts b/tests/unit/shared/adapter-policy-js.test.ts index 9b34872b9..81302293d 100644 --- a/tests/unit/shared/adapter-policy-js.test.ts +++ b/tests/unit/shared/adapter-policy-js.test.ts @@ -157,7 +157,7 @@ describe('JsDebugAdapterPolicy', () => { }); }); - describe('describePendingStop (issue #678)', () => { + describe('describePendingStop (issues #678, #1130)', () => { const hook = JsDebugAdapterPolicy.describePendingStop!; const depFrame = { id: 1, name: 'handle', file: 'C:\\app\\node_modules\\router\\index.js', line: 160 }; const internalFrame = { id: 2, name: 'processTicksAndRejections', file: '/internal/process/task_queues', line: 95 }; @@ -165,83 +165,78 @@ describe('JsDebugAdapterPolicy', () => { const launch = (dapLaunchArgs?: Record, adapterLaunchConfig?: Record) => ({ ...(dapLaunchArgs ? { dapLaunchArgs } : {}), ...(adapterLaunchConfig ? { adapterLaunchConfig } : {}) }); - it('says nothing for attach sessions (skipFiles is not defaulted there)', () => { + it('says nothing for attach sessions (neither key is defaulted there)', () => { expect(hook({ operation: 'pause', attachMode: true })).toBeUndefined(); expect(hook({ operation: 'step', attachMode: true, fromFrame: depFrame })).toBeUndefined(); }); - // js-debug's resume-on-skipped-frame lives inside its smart-stepper - // (`getSmartStepDirection` returns early unless launchConfig.smartStep); - // blackboxing is only the condition it reads. Measured on the #686 build: - // default skip list + smartStep:false → the pause landed; internals-only - // skip list + smartStep:true → the #678 chase with node_modules NOT - // blackboxed. + // js-debug's own stepper used to step away from a pause that landed in + // skipped code, which is where an idle server always is (#678). It is + // off for every session now, so a pause lands where the program is and + // there is nothing of that kind to explain. describe('pause', () => { - it('explains a pending pause on the default launch: the smart-stepper is on and internals are skipped', () => { - const text = hook({ operation: 'pause', attachMode: false, launch: {} }); - expect(text).toMatch(/smart-stepper|smartStep/); - expect(text).toMatch(/may never land/); - expect(text).not.toMatch(/does not land/); - expect(text).toMatch(/justMyCode: false/); - expect(text).toMatch(/smartStep: false/); - }); - - it('says nothing once the smart-stepper is off, whichever way it was turned off', () => { - expect(hook({ operation: 'pause', attachMode: false, launch: launch({ justMyCode: false }) })).toBeUndefined(); - expect(hook({ operation: 'pause', attachMode: false, launch: launch(undefined, { smartStep: false }) })).toBeUndefined(); - }); - - it('still explains the pause when justMyCode is off but the stepper was forced back on (run B)', () => { - const text = hook({ operation: 'pause', attachMode: false, launch: launch({ justMyCode: false }, { smartStep: true }) }); - expect(text).toMatch(/smartStep/); - expect(text).toMatch(/may never land/); - }); - - it('says nothing when the caller list does not skip node internals (the stepper has nothing to step out of)', () => { - expect(hook({ operation: 'pause', attachMode: false, launch: launch(undefined, { skipFiles: ['**/node_modules/**'] }) })).toBeUndefined(); - expect(hook({ operation: 'pause', attachMode: false, launch: launch(undefined, { skipFiles: [] }) })).toBeUndefined(); - }); - - it('lets adapterLaunchConfig win over dapLaunchArgs, as the launcher merge does', () => { - expect(hook({ operation: 'pause', attachMode: false, launch: launch({ justMyCode: true }, { smartStep: false }) })).toBeUndefined(); - expect(hook({ operation: 'pause', attachMode: false, launch: launch({ justMyCode: false }, { smartStep: true }) })).toBeDefined(); + it.each([ + ['the default launch', {}], + ['justMyCode off', launch({ justMyCode: false })], + ['the stepper off', launch(undefined, { smartStep: false })], + ['the stepper forced on', launch({ justMyCode: false }, { smartStep: true })], + ['a caller skip list', launch(undefined, { skipFiles: ['**/node_modules/**'] })] + ])('says nothing about a pending pause on %s: no stepper steps away from a pause any more', (_label, start) => { + expect(hook({ operation: 'pause', attachMode: false, launch: start })).toBeUndefined(); }); }); + // The proxy's stepper never stops in skipped code: it steps out toward + // the nearest frame of the program below, and with none it resumes the + // program. A step still pending has run off the program's stack, or is + // waiting on work in flight. describe('step', () => { - it('explains a pending step issued from a blackboxed dependency frame, naming the frame and the justMyCode remedy', () => { + it('explains a pending step issued from a skipped dependency frame, naming the frame and the remedy', () => { const text = hook({ operation: 'step', attachMode: false, launch: {}, fromFrame: depFrame }); - expect(text).toMatch(/skipped frame/); + expect(text).toMatch(/issued from skipped code/); expect(text).toMatch(/router[\\/]index\.js:160/); + expect(text).toMatch(/does not stop in skipped code/); expect(text).toMatch(/justMyCode: false/); - expect(text).toMatch(/may never land/); - expect(text).not.toMatch(/step_out/); - expect(text).not.toMatch(/only steps out/); + // The old wording blamed js-debug's stepper, which is off. + expect(text).not.toMatch(/smart-stepper/); + expect(text).not.toMatch(/may never land/); }); - it('says nothing about a step from a dependency frame once node_modules is not blackboxed or the stepper is off', () => { - expect(hook({ operation: 'step', attachMode: false, launch: launch({ justMyCode: false }), fromFrame: depFrame })).toBeUndefined(); - expect(hook({ operation: 'step', attachMode: false, launch: launch(undefined, { smartStep: false }), fromFrame: depFrame })).toBeUndefined(); - expect(hook({ operation: 'step', attachMode: false, launch: launch(undefined, { skipFiles: ['/**'] }), fromFrame: depFrame })).toBeUndefined(); - }); - - it('explains a step issued from a skipped node-internals frame with the smartStep remedy, never step_out', () => { + it('explains a pending step issued from a skipped Node-internals frame the same way', () => { const text = hook({ operation: 'step', attachMode: false, launch: {}, fromFrame: internalFrame }); - expect(text).toMatch(/node internals/i); + expect(text).toMatch(/issued from skipped code \(\/internal\/process\/task_queues:95\)/); expect(text).toMatch(/smartStep: false/); - expect(text).not.toMatch(/step_out/); - expect(text).not.toMatch(/only steps out/); + expect(text).not.toMatch(/smart-stepper/); + }); + + it('says of a pending step from the program\'s own code that it ran off the stack or is waiting on work in flight', () => { + for (const fromFrame of [userFrame, undefined]) { + const text = hook({ operation: 'step', attachMode: false, launch: {}, ...(fromFrame ? { fromFrame } : {}) }); + expect(text).toMatch(/left the frame it started in/); + expect(text).toMatch(/event loop/); + expect(text).toMatch(/wait_for_stop/); + expect(text).not.toMatch(/skipped code/); + } }); - it('says nothing about an internals frame when internals are not skipped or the stepper is off', () => { - expect(hook({ operation: 'step', attachMode: false, launch: launch(undefined, { skipFiles: ['**/node_modules/**'] }), fromFrame: internalFrame })).toBeUndefined(); - expect(hook({ operation: 'step', attachMode: false, launch: launch(undefined, { skipFiles: [] }), fromFrame: internalFrame })).toBeUndefined(); - expect(hook({ operation: 'step', attachMode: false, launch: launch({ justMyCode: false }), fromFrame: internalFrame })).toBeUndefined(); + it('treats a frame as skipped only when this launch skips it', () => { + // node_modules is not skipped without justMyCode, or on an internals-only list. + expect(hook({ operation: 'step', attachMode: false, launch: launch(undefined, { skipFiles: ['/**'] }), fromFrame: depFrame })) + .toMatch(/left the frame it started in/); + // Internals are not skipped on a list that does not name them. + expect(hook({ operation: 'step', attachMode: false, launch: launch(undefined, { skipFiles: ['**/node_modules/**'] }), fromFrame: internalFrame })) + .toMatch(/left the frame it started in/); }); - it('says nothing about a step from user code or a step whose origin frame is unknown', () => { - expect(hook({ operation: 'step', attachMode: false, launch: {}, fromFrame: userFrame })).toBeUndefined(); - expect(hook({ operation: 'step', attachMode: false, launch: {} })).toBeUndefined(); + it('says nothing when the session chose plain steps: the step lands where V8 lands', () => { + expect(hook({ operation: 'step', attachMode: false, launch: launch({ justMyCode: false }), fromFrame: depFrame })).toBeUndefined(); + expect(hook({ operation: 'step', attachMode: false, launch: launch(undefined, { smartStep: false }), fromFrame: internalFrame })).toBeUndefined(); + expect(hook({ operation: 'step', attachMode: false, launch: launch(undefined, { smartStep: false }), fromFrame: userFrame })).toBeUndefined(); + }); + + it('lets adapterLaunchConfig win over dapLaunchArgs, as the launcher merge does', () => { + expect(hook({ operation: 'step', attachMode: false, launch: launch({ justMyCode: true }, { smartStep: false }), fromFrame: userFrame })).toBeUndefined(); + expect(hook({ operation: 'step', attachMode: false, launch: launch({ justMyCode: false }, { smartStep: true }), fromFrame: userFrame })).toBeDefined(); }); }); }); From 753d884779a9e4ceb09dd74c3c86bbab811078e1 Mon Sep 17 00:00:00 2001 From: JF Date: Sun, 15 Nov 2026 21:14:49 -0500 Subject: [PATCH 05/24] test(javascript): the stepper against a real js-debug, in the integration project (#1130, #1161) CI runs no e2e, so the stepper's behaviour through a real server, the real js-debug and a real Node is pinned where CI does run: twelve cases on one fixture whose lines are found by marker. Against main's sources (built in place, then restored) six of them fail: - step_into on the first console.log of the process, on a require of a module not yet loaded, and all three steps that leave a function through return inside try...finally (step_out; step_over off the finally block; step_out of an async function) answered "Step completed as session exited."; - step_into on a setTimeout line landed inside the timer's callback, a later task, with the lines after it already run. The other six held before and must keep holding: a builtin calling the program, a call through Node's code into the program's listener, a step_out of a callback Node called, a breakpoint reached during a step, a step off the last line of a callback Node called (the program is resumed and the next breakpoint is what stops), and justMyCode: false landing in Node's own code. Each landing must also answer inside 4 s, so a step that would have gone pending fails the case. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn69pXrYMWc1JUwv5v8 --- .../javascript-step-skipped-code.test.ts | 188 ++++++++++++++++++ .../javascript/step-skipped-code/lazy.cjs | 7 + .../javascript/step-skipped-code/steps.cjs | 79 ++++++++ 3 files changed, 274 insertions(+) create mode 100644 tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts create mode 100644 tests/fixtures/javascript/step-skipped-code/lazy.cjs create mode 100644 tests/fixtures/javascript/step-skipped-code/steps.cjs diff --git a/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts b/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts new file mode 100644 index 000000000..d99736349 --- /dev/null +++ b/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts @@ -0,0 +1,188 @@ +/** + * The server's own JavaScript stepper, through a real server, the real + * js-debug and a real Node (issues #1130, #1161). + * + * js-debug's smart stepper is off for every session; the server decides + * where a step ends. What that has to hold, as measured: + * + * - a step_into on a line that calls only Node's own code lands on the + * next line, at once. js-debug's stepper lost that step on the first + * console.log of a process (the session ended), and took about 6 s on a + * Linux host for a later one; + * - a call through Node's code into a callback of the program's is + * followed; a call that only starts a later task is not; + * - a step that leaves a function through `return` inside try...finally + * lands in the caller. V8 loses that step (12.4 to 14.6, a bare CDP + * client), sync and async; the stepper catches the return with temporary + * breakpoints on the frame the step returns to; + * - a breakpoint reached during a step stops as itself; + * - a step off the last line of a callback Node called has no frame of the + * program to return to: the program is resumed, not walked through the + * internals of later tasks; + * - `justMyCode: false` keeps plain steps: the session chose to see + * everything. + */ +import { afterEach, describe, expect, it } from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { startStdioClient, type StdioClientHandle, type ToolAnswer } from '../../../test-utils/helpers/mcp-stdio-client.js'; +import { ErrorMessages } from '../../../../src/utils/error-messages.js'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.resolve(here, '../../../fixtures/javascript/step-skipped-code/steps.cjs'); +const LINES = fs.readFileSync(FIXTURE, 'utf8').split('\n'); + +/** The 1-based line that carries `// MARK: `. */ +function lineOf(marker: string): number { + const index = LINES.findIndex((line) => line.includes(`// MARK: ${marker}`)); + if (index === -1) { + throw new Error(`no line marked "${marker}" in the fixture`); + } + return index + 1; +} + +type StopAnswer = ToolAnswer & { + pending?: boolean; + stopReason?: string; + location?: { file: string; line: number }; +}; + +/** A step that answered inside the grace window is not pending; this bound says it was prompt. */ +const PROMPT_MS = 4000; + +describe('The server\'s JavaScript stepper against a real js-debug (issues #1130, #1161) @requires-node', () => { + let server: StdioClientHandle | undefined; + + afterEach(async () => { + await server?.close(); + server = undefined; + }); + + async function pausedAt(marker: string, launchArgs?: Record, extraBreakpoints: string[] = []): Promise { + server = await startStdioClient({ name: 'js-stepper' }); + await server.createSession('javascript', 'js-stepper'); + for (const at of [marker, ...extraBreakpoints]) { + const set = await server.call('set_breakpoint', { file: FIXTURE, line: lineOf(at) }); + expect(set.success, JSON.stringify(set)).toBe(true); + } + let stop = await server.call('start_debugging', { scriptPath: FIXTURE, ...(launchArgs ? { dapLaunchArgs: launchArgs } : {}) }); + expect(stop.success, JSON.stringify(stop)).toBe(true); + if (stop.state !== 'paused') { + stop = await server.call('wait_for_stop', { timeout: 20000 }); + } + expect(stop, JSON.stringify(stop)).toMatchObject({ success: true, state: 'paused' }); + expect(stop.location?.line, JSON.stringify(stop)).toBe(lineOf(marker)); + return stop; + } + + async function step(tool: 'step_into' | 'step_over' | 'step_out'): Promise { + const started = Date.now(); + const answer = await server!.call(tool, {}); + return { ...answer, ms: Date.now() - started }; + } + + function expectLanding(answer: StopAnswer & { ms: number }, marker: string): void { + expect(answer, JSON.stringify(answer)).toMatchObject({ success: true, state: 'paused' }); + expect(answer.pending, JSON.stringify(answer)).toBeUndefined(); + expect(answer.stopReason, JSON.stringify(answer)).toBeUndefined(); + expect(answer.location?.file ?? '', JSON.stringify(answer)).toMatch(/steps\.cjs$/); + expect(answer.location?.line, JSON.stringify(answer)).toBe(lineOf(marker)); + expect(answer.ms, `took ${answer.ms} ms: ${JSON.stringify(answer)}`).toBeLessThan(PROMPT_MS); + } + + describe('step_into (issue #1130)', () => { + it('lands on the next line when the line calls only Node\'s own code, and says so: the first console.log of the process', async () => { + await pausedAt('the first console.log'); + const answer = await step('step_into'); + // js-debug's own stepper lost this step: "Step completed as session exited." + expectLanding(answer, 'after the first console.log'); + expect(answer.message).toContain(ErrorMessages.stepIntoFoundOnlySkippedCode()); + }, 60000); + + it('enters a function of the program that a builtin calls', async () => { + await pausedAt('a builtin calls the program'); + const answer = await step('step_into'); + expectLanding(answer, 'in the mapper'); + expect(answer.message).toBe('Stepped into'); + }, 60000); + + it('follows a call through Node\'s own code into the program\'s listener', async () => { + await pausedAt('Node code calls the program'); + const answer = await step('step_into'); + expectLanding(answer, 'in the listener'); + expect(answer.message).toBe('Stepped into'); + }, 60000); + + it('does not follow a call into a later task: the next line, not the timer\'s callback', async () => { + await pausedAt('starts a later task'); + expectLanding(await step('step_into'), 'after setTimeout'); + }, 60000); + + it('lands on the next line of a require of a module not yet loaded (the loader returns through try...finally, issue #1161)', async () => { + await pausedAt('first load of a module'); + const answer = await step('step_into'); + expectLanding(answer, 'after the require'); + }, 60000); + }); + + describe('step_out and step_over', () => { + it('step_out of a callback Node called lands back in the program, past Node\'s frames', async () => { + await pausedAt('in the listener'); + expectLanding(await step('step_out'), 'after emit'); + }, 60000); + + it('a breakpoint reached during a step_over stops as itself', async () => { + await pausedAt('calls a function with a breakpoint', undefined, ['a breakpoint in a callee']); + const answer = await step('step_over'); + expect(answer, JSON.stringify(answer)).toMatchObject({ success: true, state: 'paused', stopReason: 'breakpoint' }); + expect(answer.location?.line, JSON.stringify(answer)).toBe(lineOf('a breakpoint in a callee')); + expect(answer.message).toMatch(/stopped on 'breakpoint' rather than on the step itself/); + }, 60000); + + it('a step off the last line of a callback Node called resumes the program: the next breakpoint is what stops', async () => { + await pausedAt('last line of a callback Node called', undefined, ['a later task']); + // V8 stops once more in the callback, on its closing brace. + const brace = await step('step_over'); + expect(brace, JSON.stringify(brace)).toMatchObject({ success: true, state: 'paused' }); + expect(brace.location?.line, JSON.stringify(brace)).toBe(lineOf('last line of a callback Node called') + 1); + const answer = await step('step_over'); + // Nothing of the program is below the timer's callback: the stack the + // step started on is gone. The stepper resumes instead of stepping out + // of the bottom frame, which would walk the internals of later tasks. + expect(answer, JSON.stringify(answer)).toMatchObject({ success: true, state: 'paused', stopReason: 'breakpoint' }); + expect(answer.location?.line, JSON.stringify(answer)).toBe(lineOf('a later task')); + expect(answer.ms, JSON.stringify(answer)).toBeLessThan(PROMPT_MS); + }, 60000); + }); + + describe('a step that leaves a function through return inside try...finally (issue #1161)', () => { + it('step_out lands in the caller', async () => { + await pausedAt('return inside try-finally'); + // V8 never pauses for this step-out: "Step completed as session exited." + expectLanding(await step('step_out'), 'after withFinally'); + }, 60000); + + it('step_over reaches the finally block, then the caller', async () => { + await pausedAt('return inside try-finally'); + expectLanding(await step('step_over'), 'the finally block'); + // The step that leaves the function is the one V8 loses. + expectLanding(await step('step_over'), 'after withFinally'); + }, 60000); + + it('step_out of an async function lands in its awaiter', async () => { + await pausedAt('async return inside try-finally'); + expectLanding(await step('step_out'), 'after the await'); + }, 60000); + }); + + describe('a session that chose plain steps', () => { + it('justMyCode: false lands in Node\'s own code, where V8 lands', async () => { + await pausedAt('the first console.log', { justMyCode: false }); + const answer = await step('step_into'); + expect(answer, JSON.stringify(answer)).toMatchObject({ success: true, state: 'paused' }); + expect(answer.location?.file ?? '', JSON.stringify(answer)).toMatch(/node_internals|^node:/); + expect(answer.message).toBe('Stepped into'); + }, 60000); + }); +}); diff --git a/tests/fixtures/javascript/step-skipped-code/lazy.cjs b/tests/fixtures/javascript/step-skipped-code/lazy.cjs new file mode 100644 index 000000000..a28627abd --- /dev/null +++ b/tests/fixtures/javascript/step-skipped-code/lazy.cjs @@ -0,0 +1,7 @@ +/** + * Loaded for the first time by the line the stepper fixture steps into + * (issue #1161): Node's loader returns through try...finally, the shape V8 + * loses a step-out on. + */ +const value = 1; +module.exports = { value }; diff --git a/tests/fixtures/javascript/step-skipped-code/steps.cjs b/tests/fixtures/javascript/step-skipped-code/steps.cjs new file mode 100644 index 000000000..10c5d5cbb --- /dev/null +++ b/tests/fixtures/javascript/step-skipped-code/steps.cjs @@ -0,0 +1,79 @@ +/** + * Fixture for the server's JavaScript stepper (issues #1130, #1161). + * + * Every line a test steps from carries a marker comment; the tests find + * lines by marker, so this file can be edited without renumbering them. + */ +const { EventEmitter } = require('node:events'); + +const emitter = new EventEmitter(); +function listener(value) { + const doubled = value * 2; // MARK: in the listener + return doubled; +} +emitter.on('x', listener); + +function mapper(value) { + return value + 1; // MARK: in the mapper +} + +function callee() { + const inside = 1; // MARK: a breakpoint in a callee + return inside; +} + +function inner() { + return 1; +} + +function withFinally() { + try { + return inner(); // MARK: return inside try-finally + } finally { + globalThis.cleaned = true; // MARK: the finally block + } +} + +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +async function workWithFinally() { + try { + await sleep(5); + return 2; // MARK: async return inside try-finally + } finally { + globalThis.asyncCleaned = true; + } +} + +function timerCallback() { + globalThis.fired = true; // MARK: last line of a callback Node called +} + +function laterCallback() { + globalThis.later = true; // MARK: a later task +} + +async function main() { + console.log('first line printed'); // MARK: the first console.log + const afterLog = 1; // MARK: after the first console.log + const mapped = [1, 2].map(mapper); // MARK: a builtin calls the program + emitter.emit('x', 1); // MARK: Node code calls the program + const afterEmit = 2; // MARK: after emit + setTimeout(() => {}, 0); // MARK: starts a later task + const afterTimeout = 3; // MARK: after setTimeout + const called = callee(); // MARK: calls a function with a breakpoint + const guarded = withFinally(); // MARK: calls withFinally + const afterFinally = 4; // MARK: after withFinally + const awaited = await workWithFinally(); // MARK: awaits workWithFinally + const afterAwait = 5; // MARK: after the await + const lazy = require('./lazy.cjs'); // MARK: first load of a module + const afterRequire = lazy.value + 6; // MARK: after the require + setTimeout(timerCallback, 0); + setTimeout(laterCallback, 30); + await sleep(120); + return [afterLog, mapped, afterEmit, afterTimeout, called, guarded, afterFinally, awaited, afterAwait, afterRequire]; +} + +main().then(() => { + console.log('done'); +}); From 21001acd58dfb8f9c10a60473862e08fe3484241 Mon Sep 17 00:00:00 2001 From: JF Date: Sun, 15 Nov 2026 21:17:34 -0500 Subject: [PATCH 06/24] docs(javascript): what a step does now, and what the server sets in your process (#1130, #1161) The JavaScript guide's stepping section described js-debug's smart stepper as the thing that steps through skipped code, and explained why a launch kept it on. It is off for every session; the section now says what each step does from each kind of line, what a session that chose plain steps gets, which steps V8 itself loses and how the server catches them (the temporary breakpoints it sets in the debuggee, when, how many and for how long), what is not covered (#1162), and what a step costs on Linux. The tool reference follows: justMyCode for a JavaScript launch, what step_into does there, the sentence a pending step may carry, and the pending pause, which no longer has a JavaScript sentence of its own. The justMyCode text of the start_debugging schema says the same, so the 24 tool-list snapshots change with it. Two changelog fragments, one per issue. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn69pXrYMWc1JUwv5v8 --- changelog.d/1130.fixed.md | 1 + changelog.d/1161.fixed.md | 1 + docs/javascript/README.md | 87 +++++++++++++------ docs/tool-reference.md | 31 +++++-- src/server/tool-schemas.ts | 2 +- .../bp-assert.va-explicit.container-true.json | 2 +- ...bp-assert.va-explicit.container-unset.json | 2 +- .../bp-assert.va-open.container-true.json | 2 +- .../bp-assert.va-open.container-unset.json | 2 +- .../bp-assert.va-unset.container-true.json | 2 +- .../bp-assert.va-unset.container-unset.json | 2 +- ...bp-content.va-explicit.container-true.json | 2 +- ...p-content.va-explicit.container-unset.json | 2 +- .../bp-content.va-open.container-true.json | 2 +- .../bp-content.va-open.container-unset.json | 2 +- .../bp-content.va-unset.container-true.json | 2 +- .../bp-content.va-unset.container-unset.json | 2 +- .../bp-line.va-explicit.container-true.json | 2 +- .../bp-line.va-explicit.container-unset.json | 2 +- .../bp-line.va-open.container-true.json | 2 +- .../bp-line.va-open.container-unset.json | 2 +- .../bp-line.va-unset.container-true.json | 2 +- .../bp-line.va-unset.container-unset.json | 2 +- .../bp-unset.va-explicit.container-true.json | 2 +- .../bp-unset.va-explicit.container-unset.json | 2 +- .../bp-unset.va-open.container-true.json | 2 +- .../bp-unset.va-open.container-unset.json | 2 +- .../bp-unset.va-unset.container-true.json | 2 +- .../bp-unset.va-unset.container-unset.json | 2 +- 29 files changed, 109 insertions(+), 61 deletions(-) create mode 100644 changelog.d/1130.fixed.md create mode 100644 changelog.d/1161.fixed.md diff --git a/changelog.d/1130.fixed.md b/changelog.d/1130.fixed.md new file mode 100644 index 000000000..1f7a8504b --- /dev/null +++ b/changelog.d/1130.fixed.md @@ -0,0 +1 @@ +**A JavaScript step lands where your code next runs, and is no longer lost in Node's own code.** `step_into` on a line that calls a Node builtin took about 6 s on a Linux host and answered `pending`, blaming "a long-running call"; on the first `console.log` of a process it never landed at all and the program ran to its end. js-debug's own "smart stepper" was deciding where such a step ends: while the step was in skipped code it stepped again by itself, one engine step per statement (131 for one `console.log`), with a flag that moves the step to a later task and loses it. That stepper is now off for every session, and the server steps through skipped code itself, over js-debug's raw CDP socket, for `step_into`, `step_over` and `step_out` alike. A `step_into` on a line that calls your own function through skipped code (an event listener behind `emitter.emit`, an array callback, a route handler from inside express) lands in that function; on a line that calls only skipped code it lands on the next line and the message says so (`Stepped into. The call on that line ran only skipped code …`); on a line that only starts a later task (`setTimeout`) it lands on the next line instead of inside the callback some time later. A `step_over` or `step_out` that returns into skipped code steps out to the nearest frame of your program below; when there is none (the last line of a request handler or a timer callback) the program is resumed rather than walked through the internals of later tasks, and the pending answer says the step left its frame. What counts as skipped is still js-debug's own verdict, so `justMyCode`, your `skipFiles` and source maps behave as before, and `justMyCode: false` (or `smartStep: false`) still lands every step where V8 lands. A forked child steps the same way. Changed on purpose: a `debugger;` statement or a pause in a dependency now stops there instead of being stepped away from, and the sentence a pending step carries no longer mentions js-debug's stepper. On Linux every engine step costs about 46 ms whoever sends it, so a `step_into` on a `console.log` line still takes over a second there. (#1130) diff --git a/changelog.d/1161.fixed.md b/changelog.d/1161.fixed.md new file mode 100644 index 000000000..b081e8140 --- /dev/null +++ b/changelog.d/1161.fixed.md @@ -0,0 +1 @@ +**A JavaScript step that leaves a function through `return` inside `try … finally` lands in the caller.** V8 never pauses for such a step (measured on V8 12.4, 13.6 and 14.6 with a bare CDP client): a `step_out` of the function, a `step_over` off its `finally` block, and a `step_out` of an `async` function with that shape all answered `Step completed as session exited.` while the program ran on. Node's own module loader returns that way too, which is how a `step_into` on a `require` line was lost. A step no longer counts on V8 alone to come back to a frame: before it can leave one that way, the server sets temporary breakpoints on the frame the step returns to (the nearest frame of your program below, or the awaiting function of an `async` one), and whichever pauses first is the landing. That is something the server does in your process: at most 24 temporary breakpoints, for the length of one step (every `step_out`; a `step_over` or `step_into` in a function whose text contains `finally`; a step that walks through skipped code), removed when the step ends however it ends. A function that returns to itself gets none for `step_over` and `step_into`. Not covered: a `step_over` across the first load of a module that has a breakpoint in it still runs on (#1162). (#1161) diff --git a/docs/javascript/README.md b/docs/javascript/README.md index 5b3b0e39b..7c2469193 100644 --- a/docs/javascript/README.md +++ b/docs/javascript/README.md @@ -97,41 +97,72 @@ The JavaScript adapter automatically configures: ### Stepping and pausing inside dependencies (`justMyCode`, `skipFiles`) -js-debug has no `justMyCode` key of its own; the launch transform turns the intent into two js-debug keys: -`skipFiles` (V8 blackboxing — `node_modules` is on the list while `justMyCode` is true, Node internals always) and -`smartStep`, whose stepper **keeps stepping while the program is in a skipped frame** — in the direction you asked -for, falling back to step-out — instead of reporting the stop. On a server every pause lands in Node internals, and -a request path enters your code by calls, not returns, so with the stepper on neither a pause nor a `step_over` / -`step_out` issued from a skipped frame lands (issue #678); a `step_into` still reaches the next call into your -code. `justMyCode: false` turns the stepper off and takes `node_modules` off the list. What that means in practice: - -| Launch | `skipFiles` sent | `smartStep` | A breakpoint inside a dependency | `step_over` from that breakpoint | `pause_execution` on an idle server | -|---|---|---|---|---|---| -| default (`justMyCode: true`) | `/**`, `**/node_modules/**` | `true` | fires; frame 0 is the dependency frame | may never land on a request path (`pending: true`; the message names the skipped frame, the stepper and the remedy) | may never land (`pending: true`; the message names the stepper and the remedy) | -| `dapLaunchArgs: { justMyCode: false }` | `/**` | `false` | fires | lands on the next line of the dependency | lands as soon as any JavaScript runs (the next request or timer), in an internal frame if that is where it is (the stack response marks it). With the smart-stepper off, steps also stop in unmapped generated helpers it used to skip | -| `dapLaunchArgs: { skipFiles: [...] }` | exactly your list | follows `justMyCode` unless set | fires | lands unless the frame is on your list and the stepper is on | may never land while the stepper is on and `/**` is on your list | -| `adapterLaunchConfig: { smartStep: false }` (default list) | `/**`, `**/node_modules/**` | `false` | fires | lands in the next frame V8 does not skip (an internals frame on a request path) | lands, in an internals frame | +js-debug has no `justMyCode` key of its own; the launch transform turns the intent into two keys: `skipFiles`, the +code a step does not stop in (Node internals always, `node_modules` while `justMyCode` is true), and `smartStep`, +whether steps step through skipped code at all. `justMyCode: false` takes `node_modules` off the list and turns +that stepping off. + +**The server steps through skipped code itself** (issue #1130). js-debug's own smart stepper did it before, and is +now off for every session whatever `smartStep` says: it re-stepped with a flag that moves the step to a later task +and loses it (a `step_into` on the first `console.log` of a process ended the session), and it took one engine step +per statement of the skipped code (131 for one `console.log`, about 6 s on a Linux host). `smartStep` is read as the +session's choice instead, and a session that chose it has its steps served by the server over js-debug's raw CDP +socket. What "skipped" means is still js-debug's own verdict on the frame, so `justMyCode`, your own `skipFiles` and +source maps (an unmapped helper of a source-mapped file) all count. + +What a step does when the session steps through skipped code (the launch default): + +| Step | From | Lands | +|---|---|---| +| `step_into` | a line that calls your function through skipped code (`emitter.emit` to a listener, an array callback, a route handler from inside express) | in that function | +| `step_into` | a line that calls only skipped code (`console.log`, `require`, `JSON.stringify`) | on the next line; the message says the line called only skipped code | +| `step_into` | a line that only starts a later task (`setTimeout`, a promise callback) | on the next line; a breakpoint in the callback stops there | +| `step_over`, `step_out` | a frame whose caller is skipped code, with your code further down the stack | in that frame of yours | +| `step_over`, `step_out` | the last line of a function Node called (a request handler, a timer callback) | nowhere: nothing of your program is on the stack, so the program is resumed and the answer is `pending: true` with a sentence saying so; the next breakpoint stops it | +| any step | skipped code (a breakpoint inside a dependency) | `step_into` walks on into your handler; `step_over` and `step_out` run on as in the row above. `justMyCode: false` steps inside that code | + +A breakpoint, an exception or a `debugger;` statement reached during a step stops as itself. A pause is never stepped +away from: it lands where the program is, in Node's own code if that is where it is (the stack response marks the +frame). + +| Launch | `skipFiles` sent | Steps through skipped code | `step_over` from a breakpoint inside a dependency | +|---|---|---|---| +| default (`justMyCode: true`) | `/**`, `**/node_modules/**` | yes | runs on (`pending: true`; the message names the skipped frame and the remedy) | +| `dapLaunchArgs: { justMyCode: false }` | `/**` | no | lands on the next line of the dependency | +| `dapLaunchArgs: { skipFiles: [...] }` | exactly your list | follows `justMyCode` unless `smartStep` is set | lands unless the frame is on your list | +| `adapterLaunchConfig: { smartStep: false }` (default list) | `/**`, `**/node_modules/**` | no | lands in the next frame V8 does not skip (an internals frame on a request path) | A caller-supplied `skipFiles` **replaces** the default list (VS Code's launch.json semantics); include `/**` yourself if you still want internals skipped. An explicit `smartStep` always wins over the derived value. Attach defaults `smartStep` to `false` and leaves `skipFiles` unset (issue #513) — see -`attach_to_process` in the tool reference. - -Why launch keeps the stepper on by default while attach turns it off (issue #687, measured on js-debug 1.112): -js-debug's V8 blackbox patterns for `/**` cover `node:internal/*` but not top-level builtins such -as `node:url` or `node:events` (the per-builtin patterns are built with a `.js` suffix the live URLs do not -carry), so with the stepper off a `step_into` from a dependency frame stops in those internals one line at a -time (`/url`) instead of in your handler, which the stepper reaches in one press; and `step_into` -an `async` callee in TypeScript compiled for a target below ES2017 costs four unmapped `__awaiter` stops before -the callee's first line. `step_over` across an `await` is unchanged either way. Those costs have no hint -mechanism, while the two pending cases in the default row name their remedy — so the default stays, and -`justMyCode: false` (or `smartStep: false`) is the switch when a pause or a step from a dependency matters more -than stepping into one. +`attach_to_process` in the tool reference. With the stepping off, a step lands where V8 lands: a `step_into` on a +`console.log` line stops in ``, and an `async` callee in TypeScript compiled for a target below +ES2017 costs four unmapped `__awaiter` stops before its first line (issue #687). + +**Steps V8 itself loses** (issue #1161). V8 never pauses for a step that leaves a function through a `return` +written inside `try … finally` (measured on V8 12.4, 13.6 and 14.6 with a bare CDP client): a `step_out` of such a +function, or a `step_over` off its `finally` block, used to answer `Step completed as session exited.` Node's own +module loader has that shape, which is how a `step_into` on a `require` line was lost too. So a step never counts on +V8 alone to come back to a frame. Before a step can leave a frame that way, the server sets temporary breakpoints on +the frame the step returns to (the nearest frame of your program below, or the awaiting function of an `async` +one), and whichever pauses first is the landing. That is something the server does in your process: up to 24 +temporary breakpoints for the length of one step, for every `step_out`, for a `step_over` or `step_into` in a +function whose text contains `finally`, and for a step that walks through skipped code. They are removed when the +step ends, however it ends. A function that returns to itself (recursion) gets none for `step_over` and +`step_into`, so that one shape keeps V8's own behaviour. + +Not covered: a `step_over` across the first load of a module that has a breakpoint in it still runs on (issue +#1162; js-debug pauses at the module's entry to bind the breakpoint, and V8 drops the step at any pause). A +`step_into` on that line does land. + +On Linux every engine step costs about 46 ms whoever sends it (the inspector's socket), against 1.5 ms on Windows, +so a `step_into` on a `console.log` line, which walks 24 engine steps into Node's code before it comes back, takes +over a second there. A step whose stop is a breakpoint or an exception rather than the step itself is reported as `Stepped over; stopped on 'breakpoint' rather than on the step itself (see stopReason)` — true both when the next -line carries a breakpoint and when a lost step's next request re-hit the same breakpoint; in the second case the -program is back at the line you stepped from, and the message says so. +line carries a breakpoint and when a step that ran on re-hit the same breakpoint on the next request; in the second +case the program is back at the line you stepped from, and the message says so. ### Custom Configuration diff --git a/docs/tool-reference.md b/docs/tool-reference.md index 41ff339d1..9ab35ec93 100644 --- a/docs/tool-reference.md +++ b/docs/tool-reference.md @@ -490,7 +490,7 @@ Starts debugging a script. - `args` (array of strings, optional): Command line arguments for the script. - `dapLaunchArgs` (object, optional): Standard DAP launch arguments: - `stopOnEntry` (boolean): Stop at first line (default `false` — the opposite of attach, which pauses unless `stopOnEntry` is `false`) - - `justMyCode` (boolean): Debug only user code (default `true`). JavaScript launch: `true` blackboxes `node_modules` through js-debug's `skipFiles` and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, `node_modules`) is stepped through and may never land (`pending: true`, with an explanation); `false` drops `node_modules` from the skip list and turns the stepper off, so steps land inside dependencies and `pause_execution` lands as soon as any JavaScript runs (issue #678). A caller `skipFiles` replaces the default list. Source maps are on for every JavaScript launch, `.js` programs included — stops report `src/*.ts` when maps and sources are present; `adapterLaunchConfig: { sourceMaps: false }` opts out (issue #684) + - `justMyCode` (boolean): Debug only user code (default `true`). JavaScript launch: `true` puts `node_modules` on js-debug's `skipFiles` beside Node internals, and a step does not stop in skipped code: the server steps through it itself, so `step_into` follows a call through skipped code into your own function, and otherwise lands on the next line and says the line called only skipped code (issue #1130; see [`step_into`](#step_into)). `false` takes `node_modules` off the list and turns that stepping off, so every step lands where V8 lands, inside dependencies and Node internals. A pause lands where the program is either way. A caller `skipFiles` replaces the default list. Source maps are on for every JavaScript launch, `.js` programs included — stops report `src/*.ts` when maps and sources are present; `adapterLaunchConfig: { sourceMaps: false }` opts out (issue #684) - `noDebug` (boolean): DAP's "launch without enabling debugging" flag (default `false`). What it does depends on the adapter, and the response says which case you are in. **Honoured** — the debugger is off: no breakpoint binds, no exception filter arms, no entry stop lands, and no breakpoint, exception or entry stop ever arrives, so a short script ends `stopped` and a server stays `running`. That is a legitimate plain run and says nothing by itself; when the session has breakpoints (line or function), an explicit `breakOnExceptions` other than `"none"`, or `stopOnEntry`, the `warning` says the debugger is off for this launch and names what will not fire — not that no stop of any kind can come — in place of the unbound-breakpoint diagnostics that would otherwise send you to check paths that are fine (issue #710). js-debug, debugpy, Delve and CodeLLDB honour it (debugpy and Delve open no configuration phase at all, so the launch is complete on the launch response; CodeLLDB refuses the configuration requests, and the refusal reaches the `warning` and `get_output` — issue #746). The run ends `stopped` with the program's output and, where the adapter reports one, the exit code (Delve states it as a console line, `Process N has exited with status S`, which is read back as `exitCode` — issue #753). Under the flag Delve runs the program through Go's `exec`, so on Windows the binary needs its `.exe` extension. **Ignored** — rdbg, netcoredbg and the Java bridge run the debugger regardless, and the rust launch transform never forwards the flag: the `warning` says the flag had no effect and everything works as usual. The same warning comes back from `restart_debugging` and from a `dryRunSpawn` check. While such a launch runs, the session remembers the decision (`list_debug_sessions` reports `debuggerDisabled: true`) and every later surface says why: `set_breakpoint` and `list_breakpoints` keep the adapter's own answer (still sent — e.g. js-debug's "Unbound breakpoint", or CodeLLDB's refusal echoed onto each pre-launch breakpoint) and add "the debugger is off for this launch (noDebug is true)…", `pause_execution` is still sent and the same sentence explains a pause that never lands or one the adapter refused, and `step_*`/`continue_execution`/`get_stack_trace`/`get_local_variables`/`evaluate_expression` append it to their "not paused" answers. A `stopped` event only a live debugger produces — a breakpoint the adapter itself reports (or names in `hitBreakpointIds`), an exception stop, an entry stop — proves the debugger on for that adapter build and clears the decision, and so does a breakpoint the adapter verified (every honouring adapter refuses or unbinds one under the flag, so a bound one can only come from a build that ignores it); a pause, a step taken from one, or a `debugger;` statement do not (js-debug lands all three under the flag while its breakpoints stay unbound; an uncaught throw does not stop). On a paused session the sentence keeps only the clause still true of it — breakpoints cannot bind — and outside a live launch (`initializing`/`running`/`paused`) the decision is neither reported nor consulted (issue #749). - Additional DAP launch keys (`program`, `cwd`, `env`, language-specific options) pass through to the adapter. For Python, `module` (`python -m `) or `code` (`python -c`) replaces `program`: debugpy takes exactly one target, so the launch goes out without `program` and the response's `warning` says so (`dapLaunchArgs.module: launched as a module (python -m); program is not sent …`); `scriptPath` still has to name an existing file, and `cwd` is what `-m` puts on `sys.path`: for these launches it defaults to the directory above the top-most package containing `scriptPath` (the `warning` names it), and a module launch of a project sets it to the project root explicitly (issue #985). `dryRunSpawn` reports such a launch's `data.script` as `module: ` or `code: …`. Top-level parameters do **not** belong here: a nested `breakOnExceptions` is honored as an alias (the top-level value wins if both are given) and reported via a `warning` in the response; other misplaced top-level keys (`dryRunSpawn`, `sessionId`, `scriptPath`, `adapterLaunchConfig`) are stripped with a warning instead of silently riding into the launch config. - `adapterLaunchConfig` (object, optional): Adapter-specific launch configuration overrides. Use this for language-specific settings that go beyond standard DAP arguments (e.g., `mainClass` and `classpath` for Java, `buildCommand` for Rust). For Rust, `_adapterSettings` passes through to CodeLLDB (issue #441) — e.g. `{"_adapterSettings": {"scriptConfig": {"lang": {"rust": {"sysroot": "/path"}}}}}` points the Rust formatter lookup at an explicit sysroot; the `CODELLDB_RUST_SYSROOT` env var does the same without per-launch config (a user-supplied `_adapterSettings` value wins over the env var). @@ -703,9 +703,11 @@ ended by a `pause` from elsewhere is read as a pause and may. The step is not cancelled: the session becomes `"paused"` on its own when it completes — call [`wait_for_stop`](#wait_for_stop) to block until it does (or poll `list_debug_sessions`), or call `pause_execution` to interrupt it. -The adapter may append one sentence to that message explaining why the step may never land — the JavaScript adapter -does so for a step issued from a frame its `skipFiles` blackbox while `smartStep` is on (issue #678) — so match a -pending step by its `pending: true` flag, not by the message text. +The adapter may append one sentence to that message saying what the step is waiting for. The JavaScript adapter +does so for a launch that steps through skipped code (issues #678, #1130): a step issued from skipped code names +the frame and says a step does not stop there, and any other pending step says it left the frame it started in +and nothing of your program has run since (a function Node called returned to the event loop, or the line is +waiting on work in flight). So match a pending step by its `pending: true` flag, not by the message text. Once a stop has been observed, the stop path owns the answer — a step that demonstrably landed is never reported as pending afterwards, at the cost of the response then being bounded by the stack-trace round trip rather than by the ~5s window. If the debuggee ends while the step is in flight the result is still a success, with a terminal `state` and a message such as `"Step completed as session terminated."`. @@ -732,6 +734,19 @@ Steps into function calls on the current line. Same ~5s wait and `pending: true` contract as step_over — see [Pending steps](#pending-steps). +**JavaScript** (a launch that steps through skipped code, the default; issue #1130): + +- A line that calls your own function through skipped code lands in that function: an event listener behind + `emitter.emit`, an array callback, a route handler from inside express. +- A line that calls only skipped code (Node internals, `node_modules`, files on `skipFiles`) lands on the next + line, and the message says so: `Stepped into. The call on that line ran only skipped code (Node internals, + node_modules, or files on skipFiles), so there was nothing of your program to step into and the line ran as a + step over. dapLaunchArgs.justMyCode: false steps into that code.` +- A call that only starts a later task (`setTimeout`, a promise callback) is not followed: the step lands on the + next line. Set a breakpoint in the callback to stop there. + +See [Stepping and pausing inside dependencies](javascript/README.md#stepping-and-pausing-inside-dependencies-justmycode-skipfiles). + --- ### step_out @@ -981,9 +996,9 @@ A frame is program code when the adapter's policy does not call it internal **an } ``` -The adapter may append one sentence explaining why the pause may never land — the JavaScript adapter does so for a -launch whose `smartStep` is on and whose `skipFiles` blackbox Node internals (issue #678) — so match a pending pause -by its `pending: true` flag, not by the message text. +An adapter may append a sentence to that message, so match a pending pause by its `pending: true` flag, not by the +message text. (The JavaScript adapter used to add one about js-debug's own stepper stepping away from a pause that +landed in skipped code; that stepper is off since issue #1130, and a pause lands where the program is.) **Notes:** - The `"state"` field is the session state at the moment the tool answers: `"paused"` once the stop has been observed, and `"running"` **only on the pending path** — the request was delivered but the program has not stopped yet. On that path, call [`wait_for_stop`](#wait_for_stop) to block until the state flips to `"paused"` when the target next executes code (or poll `list_debug_sessions`). @@ -1642,7 +1657,7 @@ When the requested pause has not landed by the time the tool answers (a Ruby pro - The response `warning` reports two distinct `adapterConfig` key outcomes (issues #450/#466): keys the adapter's attach transform genuinely drops (e.g. Python's ptvsd-era `localRoot`/`remoteRoot` — use `pathMappings`) are named as **ignored**, while keys mcp-debugger doesn't recognize are **forwarded to the adapter as-is** and named with an edit-distance suggestion for near-misses (`pathMapping (did you mean pathMappings?)`) — "ignored" means dropped, "forwarded as-is" means the adapter still sees them. The same field also carries the launch-style warning for function breakpoints still unverified at attach (issue #308), and the adapter's own attach-transform notes (issue #908): Dart's note that a `host`/`port` attach built a no-auth `ws://…/ws` URI (and that a `deviceId` is ignored on a Dart runner), COBOL's build options given without `sources` and its C-view-only note. - js-debug attach honors `adapterConfig` too: `localRoot`/`remoteRoot`/`sourceMaps`/`skipFiles`/`continueOnAttach` and other js-debug attach options reach the debugger (issue #466). Two keys are defaulted when absent (issue #655): `resolveSourceMapLocations: ["**", "!**/node_modules/**"]` (js-debug's own attach default collapses to "resolve everywhere", which applied every dependency's `.js.map` and produced phantom `../src/*.ts` frames) and `cwd` (the server's working directory, or the workspace root in container mode — js-debug needs a base path before it resolves any source map's relative `sources`, even ones next to the generated file). Pass your own value, including `resolveSourceMapLocations: null`, to override. `skipFiles` is deliberately left at js-debug's default: blackboxing `node_modules` would turn a `pause_execution` that lands in framework code on an idle server into the endless step-chase of issue #513 — `get_stack_trace` hides those frames instead. - js-debug child auto-attach defaults on only for a target that can read both a temporary probe file created by the server and the installed js-debug bootloader files. Every attach form, including `processId`, is checked: a sidecar can share PIDs without sharing files, and an SSH or `kubectl` port forward can use a loopback address without sharing the server's filesystem. When locality cannot be verified, including a failed probe, `autoAttachChildProcesses` defaults to `false` and the response warns, preventing the injected server-local bootloader path from breaking later forks. An explicit boolean in `adapterConfig.autoAttachChildProcesses` is preserved; use `true` only when the target and its children can load the server's js-debug bootloader and reach its debugger endpoint. -- `justMyCode` has no effect on a JavaScript attach: js-debug has no such key, and the attach transform derives nothing from it (a launch derives `skipFiles` and `smartStep` from it — see [start_debugging](#start_debugging)). Set `adapterConfig.skipFiles` / `adapterConfig.smartStep` yourself; attach defaults `smartStep` to `false` and leaves `skipFiles` unset (issue #513), so pauses and steps land where the program is (issue #678). +- `justMyCode` has no effect on a JavaScript attach: js-debug has no such key, and the attach transform derives nothing from it (a launch derives `skipFiles` and `smartStep` from it — see [start_debugging](#start_debugging)). Set `adapterConfig.skipFiles` / `adapterConfig.smartStep` yourself; attach defaults `smartStep` to `false` and leaves `skipFiles` unset (issue #513), so pauses and steps land where the program is (issue #678). `smartStep: true` there turns on the server's stepping through skipped code, as on a launch (issue #1130); js-debug's own stepper stays off either way. - Breakpoints set before the attach are re-sent once the debuggee-owning session is provably live, so their verified state in `list_breakpoints` is authoritative. - Languages whose adapter has no attach implementation (`rust`, `go`, `mock`) fail fast with a clear error. - A failed attach reports `success: false` with the reason in `message` (`Failed to attach: ...`) and tears the proxy down, so no live proxy is left behind; `state` is then `"error"` (or `"stopped"` if the session was already gone). When the adapter answers the handshake's attach request with its own error response, the attach fails at once in its words (issue #896): `Failed to attach: The javascript debug adapter rejected the attach request: …`. When the adapter itself ended the session while the attach was being verified — it exited, or dropped its DAP connection as js-debug does after failing to reach the inspector — the message says which and quotes the adapter's last stderr line (issue #897): `Failed to attach: The debug adapter ended the session during attach verification: it closed its DAP connection; its last stderr line: "Error: Could not connect to debug target at http://localhost:5678: Could not find any debuggable target"`. When the failure happened during proxy initialization, `data` carries `proxyLogPath`, `proxyLogResource`, and `initProgress` diagnostics. Session-lifecycle failures (unknown or terminated session) return the standard application-level `error` payload instead — see [Error Handling](#error-handling). diff --git a/src/server/tool-schemas.ts b/src/server/tool-schemas.ts index d0e889ea7..f63a160b6 100644 --- a/src/server/tool-schemas.ts +++ b/src/server/tool-schemas.ts @@ -159,7 +159,7 @@ export function buildToolDefinitions(options: BuildToolDefinitionsOptions): Tool description: 'DAP launch arguments. Beyond the three below, adapter keys pass through (program, cwd, env, …). Python: module runs `python -m ` instead of scriptPath (the pytest shape: module "pytest", args [::, "-x"]) and code runs a code string; scriptPath then only names the file the launch is about, and cwd — which `python -m` puts on sys.path — defaults to the directory above the top-most package containing scriptPath', properties: { stopOnEntry: { type: 'boolean', description: 'Pause at the first line before running. Default false — the opposite of attach, which pauses unless stopOnEntry is false' }, - justMyCode: { type: 'boolean', description: 'Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug\'s smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies' }, + justMyCode: { type: 'boolean', description: 'Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way' }, noDebug: { type: 'boolean', description: 'DAP\'s launch-without-debugging flag (default false). Where the adapter honours it (js-debug, debugpy, Delve, CodeLLDB and the Dart SDK adapters) no breakpoint binds, no exception filter arms, no entry stop lands and no breakpoint, exception or entry stop ever arrives (a pause may still land where the runtime allows one) — the response warns when breakpoints, an explicit breakOnExceptions or stopOnEntry are set alongside it, and while the launch runs the session reports debuggerDisabled and every later surface says the debugger is off. rdbg, netcoredbg and the Java bridge ignore the flag, and the rust launch never forwards it: their debugger stays on and the response says so' } }, additionalProperties: true diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-true.json index 8153145e3..b39d748d6 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-true.json @@ -240,7 +240,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-unset.json index 4c84b6483..af6b2c378 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-unset.json @@ -240,7 +240,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-true.json index fe912a77c..82a082572 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-true.json @@ -240,7 +240,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-unset.json index ac5bfb57c..a76305723 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-unset.json @@ -240,7 +240,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-true.json index fe912a77c..82a082572 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-true.json @@ -240,7 +240,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-unset.json index ac5bfb57c..a76305723 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-unset.json @@ -240,7 +240,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-true.json index a3517044e..b03df94a0 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-true.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-unset.json index 2f05191e8..87219da2c 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-unset.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-true.json index c4b0dda8f..0b267c9cf 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-true.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-unset.json index 9190ad605..ead7b4bb9 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-unset.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-true.json index c4b0dda8f..0b267c9cf 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-true.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-unset.json index 9190ad605..ead7b4bb9 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-unset.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-true.json index 9d724300a..d9bdd974f 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-true.json @@ -236,7 +236,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-unset.json index 763b75fa9..b723db9db 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-unset.json @@ -236,7 +236,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-true.json index 1a56f34cd..d0aebdd55 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-true.json @@ -236,7 +236,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-unset.json index 6e4ced0fe..96a5aae0f 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-unset.json @@ -236,7 +236,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-true.json index 1a56f34cd..d0aebdd55 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-true.json @@ -236,7 +236,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-unset.json index 6e4ced0fe..96a5aae0f 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-unset.json @@ -236,7 +236,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-true.json index a3517044e..b03df94a0 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-true.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-unset.json index 2f05191e8..87219da2c 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-unset.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-true.json index c4b0dda8f..0b267c9cf 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-true.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-unset.json index 9190ad605..ead7b4bb9 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-unset.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-true.json index c4b0dda8f..0b267c9cf 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-true.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-unset.json index 9190ad605..ead7b4bb9 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-unset.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", From 54781f4686137a0cb69b37202fa969c1a4775778 Mon Sep 17 00:00:00 2001 From: JF Date: Mon, 16 Nov 2026 00:05:02 -0500 Subject: [PATCH 07/24] fix(javascript): a net never fails a step, and an awaiter is V8's to find (#1130, #1161) The independent review of this branch, and the rows I ran while answering it, found the stepper wrong in five ways. All five are the nets doing more than a safeguard should. A net could fail the step. With a skipFiles list that leaves out , Node's own frames are program code, V8 refuses getPossibleBreakpoints for them, and the rejection escaped: step_out of a timer callback answered an error and left the session in `error`. armReturnTarget now never throws and answers armed, unguarded or nothing-below; unguarded means V8's own step goes on alone. A chain that fails while V8 is paused reports where it is instead of nothing. A net on an awaiter stopped in the wrong call. An async function the event loop resumed returns to the function awaiting it, which is not on the stack, so its net can only guard the FUNCTION. With three calls of it in flight, step_out landed in a sibling. Measured with V8 alone: the link is named `await` (a `Promise.then` or `Timeout` parent only scheduled the code), V8's own step-out finds the call that awaited, and V8 loses the step only when the function left has a return inside try...finally. So the awaiter is netted only for that shape, the landing says it may be another call's, and a `.then` or timer callback's step_out resumes the program. A net stopped a step over an await in its caller. A function whose text has `finally` was netted on every step-over, and a function that awaits suspends: its caller ran on into the net. In a function that can suspend, a step-over or step-in is now netted only on a return line and from its finally on, never on a line that itself awaits. `finally` is read as a clause, not as a word (a comment, a promise's .finally()). The sentence on a step-in said more than was known. "The call ran only skipped code" was attached after the step had gone on into the program's own function, and for a require whose module body had run. It now says how many engine steps the walk took, only when the step ends in the frame it left. A pause asked for during a pending step could be stepped away from. V8 reports a pause taken while a step is in flight as the step, so the pause request itself now marks the chain: the next stop is the caller's, and leaves as a pause. Also: the look at the stack is repeated while js-debug says "not paused" (it used to read that as an empty stack and resume), is made per landing that has to step out (the awaiter of one frame is not the awaiter of the next), and asks for the whole stack up to 200 frames; a late `stopped` is dropped only when it can be the step's own; nothing is sent after a chain is given up. Unit: 40 new cases, 18 of them red on the stepper as committed; the rest pin behaviour the review's mutation pass found unpinned. Through a real server, js-debug and Node, in the project CI runs, on a new fixture (async-steps.cjs): step_out of an async function lands in the call that awaited it with three calls in flight; step_over on an await lands on the next line though the function has a finally clause, and off the finally block is caught at the awaiting function with the sentence that says what that promises; step_out of a .then callback resumes the program; step_out of a timer callback under a skipFiles list without lands in Node's timer code. All four fail on the stepper as committed (built in place, then restored), as does the case whose sentence changed. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn69pXrYMWc1JUwv5v8 --- src/proxy/js-stepper.ts | 481 +++++++++---- src/session/execution/execution-controller.ts | 3 +- src/utils/error-messages.ts | 42 +- .../javascript-step-skipped-code.test.ts | 90 ++- .../step-skipped-code/async-steps.cjs | 61 ++ tests/proxy/js-stepper.test.ts | 636 +++++++++++++++++- 6 files changed, 1147 insertions(+), 166 deletions(-) create mode 100644 tests/fixtures/javascript/step-skipped-code/async-steps.cjs diff --git a/src/proxy/js-stepper.ts b/src/proxy/js-stepper.ts index 0e988cafe..a016b8437 100644 --- a/src/proxy/js-stepper.ts +++ b/src/proxy/js-stepper.ts @@ -26,11 +26,32 @@ * NETS. V8 loses a step in two measured ways: when a frame is left through * a `return` inside try...finally (issue #1161), and when js-debug resumes * a pause of its own, a module-entry breakpoint, while the step is in - * flight (issue #1162). So a step never counts on V8 alone to come BACK to - * a frame. A net is a capped set of temporary CDP breakpoints on the break - * positions of a program frame the step returns to, kept with the stack - * depth of the activation it guards. Any position there is where V8's own - * step-out would stop, so a hit at that depth is a landing. + * flight (issue #1162). So where a step can leave a frame that way, it + * does not count on V8 alone to come BACK to the frame below. A net is a + * capped set of temporary CDP breakpoints on the break positions of a + * program frame the step returns to, kept with the stack depth of the + * activation it guards. Any position there is where V8's own step-out + * would stop, so a hit at that depth is a landing. + * + * A net is a safeguard, never a condition: when one cannot be set (V8 + * refuses break positions for Node's own scripts, which are program code + * on a skip list that leaves them out) the step goes on with V8 alone. + * + * When: every step-out; a step-over or step-in from a function whose text + * has `finally`; a step that walks through skipped code. In a function + * that can SUSPEND (`await`, `yield` in its text) a step-over or step-in + * is netted only where it can leave through `finally`: on a `return` + * line, and from the first `finally` on. Anywhere else the function may + * merely suspend, its caller runs on, and a net there would stop in the + * caller while the step is still on its way to the next line. + * + * An async function the event loop resumed returns to its AWAITER, which + * is not on the stack (the pause's async parent, when V8 calls the link + * `await`; a `Promise.then` or timer parent only scheduled the code). + * V8's own async step finds the one awaiting call. A net there can only + * guard the awaiter's FUNCTION, and stops in whichever call of it runs + * next. So the awaiter is netted only where V8 loses the step (`finally` + * in the function being left), and a landing by that net says so. * * No net is put on the frame being stepped IN. V8 says `ambiguous` for any * breakpoint hit while a step is in flight, and it exposes no statement @@ -41,14 +62,18 @@ * * Skipped code on top: `step_into` repeats up to a budget (that is how a * call through Node's own code reaches a callback of the program's), then - * steps out; `step_over` and `step_out` step out at once. With no program - * frame below, the stack the step started on is gone: the program is - * resumed and nothing is reported (stepping out of the bottom frame would - * land in the next task's internals instead). + * steps out; `step_over` and `step_out` step out at once. With nothing of + * the program below (no frame, no awaiter), the stack the step started on + * is gone: the program is resumed and nothing is reported (stepping out + * of the bottom frame would land in the next task's internals instead). * - * A pause that is not the stepper's (another breakpoint, an exception, a - * `debugger;`) is js-debug's to decide. Resumed by js-debug, the chain - * waits on. Kept, the chain ends and that stop is forwarded as itself. + * A pause that is not the stepper's (another breakpoint, an exception) is + * js-debug's to decide. Resumed by js-debug, the chain waits on. Kept, the + * chain ends and that stop is forwarded as itself. A pause the caller + * asks for during a chain makes the next stop theirs, wherever it is: V8 + * reports it as the step, so only the request tells them apart. (For the + * same reason a `debugger;` statement reached during a step is reported + * as the step's landing, as js-debug's own stepper reports it.) * * js-debug's `stopped` and `continued` events are withheld by count: it * sends one `stopped` per pause it keeps, out of order with the @@ -149,7 +174,8 @@ interface CdpPaused { callFrames: CdpCallFrame[]; reason: string; hitBreakpoints?: string[]; - asyncStackTrace?: { callFrames?: CdpAsyncFrame[] }; + /** `description` is V8's name for the link: `await`, `Promise.then`, `Timeout`, ... */ + asyncStackTrace?: { description?: string; callFrames?: CdpAsyncFrame[] }; } interface Net { @@ -157,14 +183,46 @@ interface Net { name: string; /** Function identity, or the async parent's position. */ fn: string; - /** The stack depth of the guarded activation; Infinity for an async parent, which resumes at any depth. */ + /** The stack depth of the guarded activation; Infinity for an awaiter, which resumes at any depth. */ depth: number; + /** Set on an awaiter's net: the function's name. Such a net guards the function, not one call of it. */ + awaiter?: string; ids: Set; } type Inbox = | { type: 'paused'; pause: CdpPaused } - | { type: 'resumed'; ours: boolean }; + | { type: 'resumed' }; + +/** + * What the code on top returns to: something of the program's that now has a + * net; something of the program's without one (V8's own step goes on alone); + * or nothing of the program's at all. + */ +type ReturnTarget = 'armed' | 'unguarded' | 'nothing-below'; + +/** What a function's text says about how a step can leave it. */ +interface FunctionShape { + /** `finally` in its text: the shape V8 loses a leaving step on (issue #1161). */ + hasFinally: boolean; + /** 0-based script line of the first `finally`. */ + finallyLine: number; + /** `await` or `yield` in its text: it can hand control to its caller without returning. */ + suspends: boolean; +} + +/** How many frames of a stack js-debug is asked to mark, at most. */ +const MAX_MARKED_FRAMES = 200; + +/** + * A `finally` clause on a line of source: after the closing brace of a try + * or catch block, before its own opening brace, or alone on its line. Not + * the word in a comment, and not a promise's `.finally(`. + */ +const FINALLY_CLAUSE = /\}\s*finally\b|\bfinally\s*\{|^\s*finally\s*$/; + +/** `await` or `yield` on a line of source: where a function hands control back without returning. */ +const SUSPENDS = /\b(await|yield)\b/; interface Chain { kind: StepKind; @@ -185,12 +243,20 @@ interface Chain { reissues: number; /** A net fired in recursion and was dropped: V8's own step-outs finish, to the origin depth. */ unwinding: boolean; - /** A step-in spent its budget in skipped code and stepped out: the line called nothing of the program's. */ - steppedOutOfSkipped: boolean; + /** Step-ins a step-in had sent when it gave up on the skipped code and stepped out; 0 if it never did. */ + walkedBeforeSteppingOut: number; /** Every command the chain may send is spent and skipped code is still on top. */ capped: boolean; - /** The stack holds no frame of the program below the skipped code on top (looked at once). */ - nothingBelow: boolean; + /** What the skipped code on top returns to, as last looked at. */ + below: ReturnTarget | null; + /** The caller asked for a pause during the chain: the next stop is theirs. */ + pauseRequested: boolean; + /** That pause was taken on no breakpoint of js-debug's: it is reported as the pause it is. */ + pauseTaken: boolean; + /** The landing came by an awaiter's net: the awaiting function's name. */ + caughtAtAwaiter: string | null; + /** Whether any pause the chain kept was a net's: what a late report of it looks like. */ + netHits: boolean; startedAt: number; } @@ -236,16 +302,16 @@ export class JsStepper { private enabled = false; /** The pause V8 is in now, as CDP reported it; null while running. */ private current: CdpPaused | null = null; - /** Whether the stepper sent a resuming command since the last pause: tells its resumes from js-debug's. */ - private sentSincePause = false; private chain: Chain | null = null; private nets: Net[] = []; /** `stopped` events of a finished chain still on their way; dropped when they arrive, until the deadline. */ private owed = 0; private owedUntil = 0; + /** Whether an owed report can be a net's (`breakpoint`, naming none of js-debug's). */ + private owedNetHit = false; /** Scripts js-debug marked "Skipped by skipFiles": a script-level verdict, not asked again. */ private readonly skippedScripts = new Set(); - private readonly finallyByFunction = new Map(); + private readonly shapes = new Map(); private readonly sources = new Map(); constructor(options: JsStepperOptions) { @@ -260,6 +326,7 @@ export class JsStepper { this.enabled = enabled; } + /** The session's choice as it stands: a forked child's stepper takes it over. */ isEnabled(): boolean { return this.enabled; } @@ -326,21 +393,26 @@ export class JsStepper { spent: 0, reissues: 0, unwinding: false, - steppedOutOfSkipped: false, + walkedBeforeSteppingOut: 0, capped: false, - nothingBelow: false, + below: null, + pauseRequested: false, + pauseTaken: false, + caughtAtAwaiter: null, + netHits: false, startedAt: Date.now() }; this.chain = chain; this.owed = 0; + // A net before the first command only where V8 can lose the step by + // LEAVING the origin frame (issue #1161): a step-out always, a step-over + // or step-in where it can leave through `finally`. Not when it returns + // to itself: that net would sit in the frame being stepped in. Neither + // call can fail the step: a net is a safeguard. try { - // A net before the first command only where V8 can lose the step by - // LEAVING the origin frame (issue #1161): a step-out always, a step-over - // or step-in when the function's text has `finally`. Not when it returns - // to itself: that net would sit in the frame being stepped in. - if (kind === 'out' || await this.hasFinally(top)) { - await this.armReturnTarget(origin, kind === 'out' ? null : chain.originFn); + if (kind === 'out' || await this.canLeaveThroughFinally(top)) { + await this.armReturnTarget(chain, origin, kind === 'out' ? null : chain.originFn); } await this.sendStep(chain, CDP_COMMAND[kind]); } catch (err) { @@ -359,6 +431,11 @@ export class JsStepper { async beforeRequest(command: string): Promise { if (CHAIN_ENDING_REQUESTS.has(command)) { await this.abandonChain(`a '${command}' request`); + } else if (command === 'pause' && this.chain) { + // An explicit pause wins over a step in flight: wherever V8 stops next + // is the caller's pause, in skipped code too. V8 reports a pause taken + // while a step is in flight as the step, so only this tells them apart. + this.chain.pauseRequested = true; } } @@ -376,11 +453,13 @@ export class JsStepper { return true; } if (this.owed > 0) { - if (Date.now() <= this.owedUntil) { + if (Date.now() > this.owedUntil) { + this.owed = 0; + } else if (this.looksOwed(event)) { + // A late report of one of the finished step's own pauses. this.owed--; return true; } - this.owed = 0; } return false; } @@ -400,18 +479,16 @@ export class JsStepper { if (method === 'Debugger.paused') { const pause = params as CdpPaused; this.current = pause; - this.sentSincePause = false; const chain = this.chain; if (chain) { chain.inbox.push({ type: 'paused', pause }); chain.wake?.(); } } else if (method === 'Debugger.resumed') { - const ours = this.sentSincePause; this.current = null; const chain = this.chain; if (chain) { - chain.inbox.push({ type: 'resumed', ours }); + chain.inbox.push({ type: 'resumed' }); chain.wake?.(); } } @@ -439,6 +516,11 @@ export class JsStepper { await this.finish(chain, 'landing', 'the command cap, still in skipped code'); return; } + if (chain.cancelled) { + // Given up while the landing was being judged: nothing more is sent. + await this.finish(chain, 'cancelled'); + return; + } await this.sendStep(chain, verdict.command); continue; } @@ -447,7 +529,12 @@ export class JsStepper { } } catch (err) { logger.warn(`[JsStepper] chain failed: ${errorText(err)}`); - await this.finish(chain, 'error'); + // If V8 is paused, the caller must hear of the stop it can see: where + // the step is now, as the step it is. + const paused = this.current !== null && !chain.cancelled; + await this.finish(chain, paused ? 'landing' : 'error', paused ? 'where it was when the chain failed' : undefined).catch( + (failure) => logger.warn(`[JsStepper] could not end a failed chain: ${errorText(failure)}`) + ); } } @@ -457,7 +544,6 @@ export class JsStepper { throw new Error('the CDP connection closed'); } chain.commands.push(command); - this.sentSincePause = true; await cdp.send(command, command === CDP_COMMAND.in ? { breakOnAsyncCall: false } : {}); } @@ -494,49 +580,57 @@ export class JsStepper { const hits = pause.hitBreakpoints ?? []; const hitNets = [...new Set(hits.map((id) => this.netOf(id)).filter((net): net is Net => net !== undefined))]; const foreignHit = hits.some((id) => !this.netOf(id)); - const ours = !foreignHit && (STEP_REASONS.has(pause.reason) || (pause.reason === 'other' && hitNets.length > 0)); + const ours = !chain.pauseRequested && !foreignHit && + (STEP_REASONS.has(pause.reason) || (pause.reason === 'other' && hitNets.length > 0)); if (!ours) { - // Another breakpoint, an exception, a `debugger;`: js-debug decides. - const decision = await this.jsDebugDecides(chain); - if (decision === 'resumed') { - return { kind: 'wait' }; - } - if (decision === 'cancelled') { + // Another breakpoint, an exception, a pause the caller asked for: + // js-debug decides. Resumed by js-debug, or the chain given up, the run + // loop goes back to waiting. + if ((await this.jsDebugDecides(chain)) !== 'kept') { return { kind: 'wait' }; } chain.kept++; + chain.pauseTaken = chain.pauseRequested && !foreignHit; return { kind: 'real-stop' }; } chain.kept++; + if (hitNets.length > 0) { + chain.netHits = true; + } const top = pause.callFrames[0]; const depth = pause.callFrames.length; const skipped = await this.isSkipped(chain, pause); + if (chain.cancelled) { + // Given up while js-debug was being asked: nothing more is armed or sent. + return { kind: 'wait' }; + } if (skipped) { - // Before anything else, a net on the program frame this code returns to. - let guarded = this.nets.some((net) => net.depth < depth || net.depth === Infinity); - if (!guarded && !chain.nothingBelow) { - guarded = await this.armReturnTarget(pause, null); - // Nothing of the program can come to be below without the chain - // landing in it first: one look per chain. - chain.nothingBelow = !guarded; - } + const guarded = (): boolean => this.nets.some((net) => net.depth < depth || net.depth === Infinity); // A step-in walks on while it has budget, with or without anything // below: a step issued inside a dependency reaches the program's // handler by calls, not returns (issue #687). - if (chain.kind === 'in' && !chain.unwinding && chain.spent < this.tunables.budget) { + const walking = chain.kind === 'in' && chain.spent < this.tunables.budget; + // Before anything else, a net on what this code returns to. A walk + // looks once (nothing of the program comes to be below without the + // walk landing in it first); a landing that has to step out looks for + // itself, because the awaiter of one frame is not the awaiter of the next. + if (!guarded() && (chain.below === null || !walking)) { + chain.below = await this.armReturnTarget(chain, pause, null); + } + if (walking) { chain.spent++; return { kind: 'command', command: CDP_COMMAND.in }; } // It has to step out now. With nothing of the program below, the stack // the step started on is gone. - if (!guarded) { + if (!guarded() && chain.below === 'nothing-below') { return { kind: 'left-stack' }; } - if (chain.kind === 'in') { - chain.steppedOutOfSkipped = true; + if (chain.kind === 'in' && chain.walkedBeforeSteppingOut === 0) { + chain.walkedBeforeSteppingOut = chain.commands.filter((sent) => sent === CDP_COMMAND.in).length; } return { kind: 'command', command: CDP_COMMAND.out }; } @@ -584,6 +678,8 @@ export class JsStepper { chain.reissues++; return { kind: 'command', command: CDP_COMMAND.in }; } + // An awaiter's net guards the function, not the one call that awaited. + chain.caughtAtAwaiter = guarding.find((net) => net.awaiter !== undefined)?.awaiter ?? null; return { kind: 'landing', by: pause.reason === 'ambiguous' ? 'net, with a V8 step in flight' : 'net, V8 had lost the step' }; } @@ -599,11 +695,9 @@ export class JsStepper { } const next = chain.inbox[0]; if (next?.type === 'resumed') { + // The stepper has sent nothing since this pause: js-debug resumed it. chain.inbox.shift(); - if (!next.ours) { - return 'resumed'; - } - continue; + return 'resumed'; } if (next?.type === 'paused') { // A newer pause already: the one being judged was resumed. @@ -623,43 +717,58 @@ export class JsStepper { if (plainLanding && this.skippedScripts.has(scriptId)) { return true; } + const marks = await this.marks(chain, 1); + if (typeof marks === 'string') { + logger.warn(`[JsStepper] no verdict for a landing (${marks}); treating it as program code`); + return false; + } + const skipped = markOf(marks[0]) === 'deemphasize'; + if (skipped && /skipFiles/i.test(marks[0].source?.origin ?? '')) { + this.skippedScripts.add(scriptId); + } + return skipped; + } + + /** + * js-debug's frames for the pause V8 is in, with its marks; or, as a + * string, why there are none. js-debug answers "not paused" until it has + * taken the pause in, so the question is asked again until the ceiling. + */ + private async marks(chain: Chain, levels: number): Promise { const deadline = Date.now() + this.tunables.verdictCeilingMs; for (;;) { let failure: string; try { const answer = await this.target.sendRequest( 'stackTrace', - { threadId: chain.threadId ?? 0, startFrame: 0, levels: 1 }, + { threadId: chain.threadId ?? 0, startFrame: 0, levels }, 5000 ); - const frame = answer?.body?.stackFrames?.[0]; - if (answer?.success !== false && frame) { - const skipped = markOf(frame) === 'deemphasize'; - if (skipped && /skipFiles/i.test(frame.source?.origin ?? '')) { - this.skippedScripts.add(scriptId); - } - return skipped; + const frames = answer?.body?.stackFrames; + if (answer?.success !== false && frames && frames.length > 0) { + return frames; } failure = answer?.message ?? 'no frame'; } catch (err) { failure = errorText(err); } - // js-debug answers "not paused" until it has taken the pause in. if (chain.cancelled || Date.now() >= deadline) { - logger.warn(`[JsStepper] no verdict for a landing (${failure}); treating it as program code`); - return false; + return failure; } await this.sleep(1); } } private async finish(chain: Chain, ender: 'landing' | 'real-stop' | 'left-stack' | 'cancelled' | 'error', by?: string): Promise { + // Where the step is, for what its answer may say about it. + const landed = this.current; + const backInOriginFrame = landed !== null && landed.callFrames.length === chain.originDepth && + fnKey(landed.callFrames[0]) === chain.originFn; await this.disarmAll(); if (ender === 'left-stack') { // Nothing of the program is below: resume, and report nothing. try { chain.commands.push('Debugger.resume'); - this.sentSincePause = true; await this.cdp?.send('Debugger.resume', {}); } catch (err) { logger.warn(`[JsStepper] resume after leaving the stack failed: ${errorText(err)}`); @@ -680,6 +789,7 @@ export class JsStepper { if (missing > 0) { this.owed = missing; this.owedUntil = Date.now() + this.tunables.settleCeilingMs; + this.owedNetHit = chain.netHits; } const count = (name: string): number => chain.commands.filter((c) => c === name).length; logger.info( @@ -701,14 +811,55 @@ export class JsStepper { threadId: (body.threadId as number | undefined) ?? chain.threadId ?? 0, reason: 'step', description: 'Paused', - ...(chain.capped - ? { text: ErrorMessages.stepStillInSkippedCode(chain.commands.length) } - : chain.steppedOutOfSkipped ? { text: ErrorMessages.stepIntoFoundOnlySkippedCode() } : {}) + ...this.landingNote(chain, backInOriginFrame) } }); } else if (ender === 'real-stop' && chain.lastStopped) { - this.deliver(chain.lastStopped); + const stop = chain.lastStopped; + if (chain.pauseTaken) { + // The pause the caller asked for. js-debug may call it a breakpoint + // that names none (it was taken on a net's position): it leaves as + // the pause it is. + const body = { ...((stop.body ?? {}) as Record) }; + delete body.hitBreakpointIds; + this.deliver({ ...stop, body: { ...body, reason: 'pause', description: 'Paused' } }); + } else { + this.deliver(stop); + } + } + } + + /** + * What a landing says beyond where it is. Only what is known: the sentence + * on a step-in that reached nothing of the program's is for one that came + * back to the frame it left, not one that went on into program code. + */ + private landingNote(chain: Chain, backInOriginFrame: boolean): { text?: string } { + if (chain.capped) { + return { text: ErrorMessages.stepStillInSkippedCode(chain.commands.length) }; + } + if (chain.caughtAtAwaiter !== null) { + return { text: ErrorMessages.stepCaughtAtAwaitingFunction(chain.caughtAtAwaiter) }; + } + if (chain.walkedBeforeSteppingOut > 0 && backInOriginFrame) { + return { text: ErrorMessages.stepIntoReachedNoProgramCode(chain.walkedBeforeSteppingOut) }; } + return {}; + } + + /** + * Whether a `stopped` that arrives after a chain ended can be the late + * report of one of that chain's own pauses: js-debug reports a step it did + * not request as `pause` (or `step`), and a net's position as a + * `breakpoint` that names none of its own. Anything else is somebody + * else's stop and goes on. + */ + private looksOwed(event: DebugProtocol.Event): boolean { + const body = (event.body ?? {}) as { reason?: string; hitBreakpointIds?: number[] }; + if (body.reason === 'pause' || body.reason === 'step') { + return true; + } + return this.owedNetHit && body.reason === 'breakpoint' && (body.hitBreakpointIds ?? []).length === 0; } private async abandonChain(why: string): Promise { @@ -800,85 +951,145 @@ export class JsStepper { } } - /** Whether the function's text has `finally`: the one shape V8 loses a leaving step on (issue #1161). */ - private async hasFinally(frame: CdpCallFrame): Promise { + /** + * What the text of the frame's function says about how a step can leave + * it. Read from the function's own lines only. Never throws: a text that + * cannot be read is a function with nothing to guard. + */ + private async shapeOf(frame: CdpCallFrame): Promise { const key = fnKey(frame); - const known = this.finallyByFunction.get(key); - if (known !== undefined) { + const known = this.shapes.get(key); + if (known) { return known; } - let found = false; + let shape: FunctionShape = { hasFinally: false, finallyLine: -1, suspends: false }; try { - const scriptId = frame.location.scriptId; - let lines = this.sources.get(scriptId); - if (!lines) { - const answer = await this.cdp?.send<{ scriptSource?: string }>('Debugger.getScriptSource', { scriptId }); - lines = (answer?.scriptSource ?? '').split('\n'); - this.sources.set(scriptId, lines); - } + const lines = await this.linesOf(frame.location.scriptId); const all = await this.locationsOf(frame); if (all.length > 0) { const from = Math.min(frame.functionLocation?.lineNumber ?? all[0].lineNumber, all[0].lineNumber); - found = /\bfinally\b/.test(lines.slice(from, all[all.length - 1].lineNumber + 1).join('\n')); + const text = lines.slice(from, all[all.length - 1].lineNumber + 1); + const at = text.findIndex((line) => FINALLY_CLAUSE.test(line)); + shape = { + hasFinally: at !== -1, + finallyLine: at === -1 ? -1 : from + at, + suspends: text.some((line) => SUSPENDS.test(line)) + }; } } catch (err) { logger.warn(`[JsStepper] could not read the function's text: ${errorText(err)}`); } - this.finallyByFunction.set(key, found); - return found; + this.shapes.set(key, shape); + return shape; + } + + private async linesOf(scriptId: string): Promise { + let lines = this.sources.get(scriptId); + if (!lines) { + const answer = await this.cdp?.send<{ scriptSource?: string }>('Debugger.getScriptSource', { scriptId }); + lines = (answer?.scriptSource ?? '').split('\n'); + this.sources.set(scriptId, lines); + } + return lines; } /** - * Arm a net on what the top frame of `pause` returns to: the nearest - * program frame below, by js-debug's marks, or the async parent when the - * stack has none. False when nothing of the program is below. + * Whether a step-over or step-in from this frame's position can leave the + * function through `finally`, the shape V8 loses the step on (issue #1161). + * In a function that cannot suspend, anywhere: the frame below is only + * reached by returning. In one that can (`await`, `yield`), only on a + * `return` line and from the first `finally` on, and never on a line + * that itself awaits or yields: there the function suspends first, its + * caller runs on, and a net below would stop in the caller while the + * step is still on its way to the next line. (So a step over an `await` + * that is the last thing a function does before it leaves through + * `finally` is V8's own, and V8 loses it.) */ - private async armReturnTarget(pause: CdpPaused, notFn: string | null): Promise { - const frames = pause.callFrames; - let marks: DebugProtocol.StackFrame[] = []; - try { - const answer = await this.target.sendRequest( - 'stackTrace', - { threadId: this.chain?.threadId ?? 0, startFrame: 0, levels: 80 }, - 5000 - ); - marks = answer?.body?.stackFrames ?? []; - } catch (err) { - logger.warn(`[JsStepper] could not read the stack's marks: ${errorText(err)}`); + private async canLeaveThroughFinally(frame: CdpCallFrame): Promise { + const shape = await this.shapeOf(frame); + if (!shape.hasFinally) { return false; } - // js-debug lists the sync frames, then a label frame per async segment. - const firstLabel = marks.findIndex((frame) => markOf(frame) === 'label'); - const sync = firstLabel === -1 ? marks : marks.slice(0, firstLabel); - for (let i = 1; i < Math.min(sync.length, frames.length); i++) { - if (markOf(sync[i]) === 'deemphasize') { - continue; - } - if (notFn && fnKey(frames[i]) === notFn) { - // It returns to itself (recursion): a net would sit in the frame being stepped in. - return true; - } - return this.arm(await this.locationsOf(frames[i]), frames[i].location, { - name: frames[i].functionName || '(anonymous)', - fn: fnKey(frames[i]), - depth: frames.length - i - }); + if (!shape.suspends) { + return true; } - // No program frame below on this stack: an async function the event loop - // resumed returns to its awaiter, which is not on the stack. - const parent = pause.asyncStackTrace?.callFrames?.[0]; - const firstAsync = firstLabel === -1 ? undefined : marks[firstLabel + 1]; - if (parent && firstAsync && markOf(firstAsync) !== 'deemphasize' && markOf(firstAsync) !== 'label') { - const start: CdpLocation = { scriptId: parent.scriptId, lineNumber: parent.lineNumber, columnNumber: parent.columnNumber }; - const all = await this.possible(start); - if (all.length > 0) { - return this.arm(all, start, { - name: `${parent.functionName || '(anonymous)'} (async parent)`, - fn: `async:${parent.scriptId}:${parent.lineNumber}:${parent.columnNumber}`, - depth: Infinity + const line = frame.location.lineNumber; + const text = this.sources.get(frame.location.scriptId)?.[line] ?? ''; + if (SUSPENDS.test(text)) { + return false; + } + return line >= shape.finallyLine || /\breturn\b/.test(text); + } + + /** + * Arm a net on what the top frame of `pause` returns to. + * + * The nearest program frame below, by js-debug's marks: that activation, + * by its depth. With none on the stack, the awaiter of an async function + * the event loop resumed (the async parent, when V8 calls the link + * `await`): V8's own async step finds that one call, so it is netted only + * where V8 loses the step, `finally` in the function being left, and that + * net guards the awaiter's function in whichever call runs next. + * + * Never throws. A net is a safeguard: whatever goes wrong (V8 refuses + * break positions for Node's own scripts; js-debug does not answer), the + * answer is `unguarded` and V8's own step goes on alone. + */ + private async armReturnTarget(chain: Chain, pause: CdpPaused, notFn: string | null): Promise { + try { + const frames = pause.callFrames; + // Every sync frame, the label of the first async segment, and its first frame. + const marks = await this.marks(chain, Math.min(frames.length + 2, MAX_MARKED_FRAMES)); + if (typeof marks === 'string') { + logger.warn(`[JsStepper] could not read the stack's marks (${marks}); V8's own step goes on alone`); + return 'unguarded'; + } + // js-debug lists the sync frames, then a label frame per async segment. + const firstLabel = marks.findIndex((frame) => markOf(frame) === 'label'); + const sync = firstLabel === -1 ? marks : marks.slice(0, firstLabel); + for (let i = 1; i < Math.min(sync.length, frames.length); i++) { + if (markOf(sync[i]) === 'deemphasize') { + continue; + } + if (notFn && fnKey(frames[i]) === notFn) { + // It returns to itself (recursion): a net would sit in the frame being stepped in. + return 'unguarded'; + } + const armed = await this.arm(await this.locationsOf(frames[i]), frames[i].location, { + name: frames[i].functionName || '(anonymous)', + fn: fnKey(frames[i]), + depth: frames.length - i }); + return armed ? 'armed' : 'unguarded'; + } + if (firstLabel === -1 && sync.length < frames.length) { + // A deeper stack than was asked about: what is under it is not known. + return 'unguarded'; + } + // No program frame below on this stack. + const parent = pause.asyncStackTrace?.callFrames?.[0]; + const firstAsync = firstLabel === -1 ? undefined : marks[firstLabel + 1]; + const awaitedByTheProgram = pause.asyncStackTrace?.description === 'await' && parent !== undefined && + firstAsync !== undefined && markOf(firstAsync) !== 'deemphasize' && markOf(firstAsync) !== 'label'; + if (!awaitedByTheProgram) { + return 'nothing-below'; } + if (!(await this.shapeOf(frames[0])).hasFinally) { + // V8's own async step finds the one awaiting call. + return 'unguarded'; + } + const start: CdpLocation = { scriptId: parent.scriptId, lineNumber: parent.lineNumber, columnNumber: parent.columnNumber }; + const name = parent.functionName || '(anonymous)'; + const armed = await this.arm(await this.possible(start), start, { + name: `${name} (awaiter)`, + fn: `async:${parent.scriptId}:${parent.lineNumber}:${parent.columnNumber}`, + depth: Infinity, + awaiter: name + }); + return armed ? 'armed' : 'unguarded'; + } catch (err) { + logger.warn(`[JsStepper] no net for this step, V8's own step goes on alone: ${errorText(err)}`); + return 'unguarded'; } - return false; } } diff --git a/src/session/execution/execution-controller.ts b/src/session/execution/execution-controller.ts index f4516ee42..754a22c3e 100644 --- a/src/session/execution/execution-controller.ts +++ b/src/session/execution/execution-controller.ts @@ -397,7 +397,8 @@ export class ExecutionController { return; } // What the step itself has to say about how it landed (the JavaScript - // stepper: the line called only skipped code; issue #1130). + // stepper: how far a step-in walked without reaching the program's + // code, or that it was caught at an awaiting function; issue #1130). const stepNote = ownStop?.reason === 'step' ? ownStop.text : undefined; success(stepNote ? `${options.successMessage}. ${stepNote}` : options.successMessage, landing); }; diff --git a/src/utils/error-messages.ts b/src/utils/error-messages.ts index 95bb0f75b..7aba89ee6 100644 --- a/src/utils/error-messages.ts +++ b/src/utils/error-messages.ts @@ -306,19 +306,43 @@ export const ErrorMessages = { : `${stepped} in ${steps} steps: this adapter stops once per expression on a line, so the step was repeated until the line changed.`, /** - * The sentence on a step_into whose line called only skipped code (issue #1130) - * Occurs when: the proxy's JavaScript stepper walked into the call, found - * nothing of the program's within its budget and came back out. The line - * ran as a step over would have run it, and the caller should know that - * was not a refusal to step in. + * The sentence on a step that left an async function through try...finally and + * was caught at the awaiting function (issues #1130, #1161) + * Occurs when: V8 loses a step that leaves a function through `finally`, so + * the proxy's JavaScript stepper set its net on the function that awaits it. + * An awaiter is not on the stack, so the net guards the FUNCTION: with + * several calls of it in flight, the one that ran next is where the step + * stopped. The caller must not take its variables for the awaited call's + * without looking. * Used in: src/proxy/js-stepper.ts (the `text` of the step's stopped * event), appended to the step's message by * src/session/execution/execution-controller.ts + * @param awaiter - The awaiting function's name */ - stepIntoFoundOnlySkippedCode: () => - 'The call on that line ran only skipped code (Node internals, node_modules, or files on skipFiles), ' + - 'so there was nothing of your program to step into and the line ran as a step over. ' + - 'dapLaunchArgs.justMyCode: false steps into that code.', + stepCaughtAtAwaitingFunction: (awaiter: string) => + `The engine loses a step that leaves a function through try...finally, so this step was caught where the ` + + `awaiting function, ${awaiter}, next ran. If several calls of ${awaiter} are in flight, this stop may be in ` + + `another call's continuation than the one that awaited the function you stepped out of: check its variables.`, + + /** + * The sentence on a step_into that reached no code of the program (issue #1130) + * Occurs when: the proxy's JavaScript stepper walked into the call on the + * line, stayed in skipped code for its whole budget, stepped back out and + * landed in the frame the step started in. It says what is known: how far + * the walk went. Not that the call reaches nothing of the program's: a + * module the line loads, a late callback, ran during the step out. The + * remedy is worded for a launch and an attach alike. + * Used in: src/proxy/js-stepper.ts (the `text` of the step's stopped + * event), appended to the step's message by + * src/session/execution/execution-controller.ts + * @param stepIns - How many engine step-ins the walk took before it stepped out + */ + stepIntoReachedNoProgramCode: (stepIns: number) => + `step_into walked ${stepIns} engine steps into the call on that line and was still in skipped code ` + + '(Node internals, node_modules, or files on skipFiles), so it stepped back out and the rest of the line ran ' + + 'as a step over runs it. Code of yours that the call reaches further in (a module it loads, a late callback) ' + + 'ran without stopping: a breakpoint there stops in it. To stop inside the skipped code instead, turn ' + + 'stepping through it off: justMyCode: false on a launch, smartStep: false on a launch or an attach.', /** * The sentence on a step that is still in skipped code after every engine diff --git a/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts b/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts index d99736349..a79a79441 100644 --- a/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts +++ b/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts @@ -92,12 +92,13 @@ describe('The server\'s JavaScript stepper against a real js-debug (issues #1130 } describe('step_into (issue #1130)', () => { - it('lands on the next line when the line calls only Node\'s own code, and says so: the first console.log of the process', async () => { + it('lands on the next line when the walk into the call stays in Node\'s own code, and says how far it went: the first console.log of the process', async () => { await pausedAt('the first console.log'); const answer = await step('step_into'); // js-debug's own stepper lost this step: "Step completed as session exited." expectLanding(answer, 'after the first console.log'); - expect(answer.message).toContain(ErrorMessages.stepIntoFoundOnlySkippedCode()); + // The first command and the whole budget, 25 step-ins, before it stepped out. + expect(answer.message).toBe(`Stepped into. ${ErrorMessages.stepIntoReachedNoProgramCode(25)}`); }, 60000); it('enters a function of the program that a builtin calls', async () => { @@ -185,4 +186,89 @@ describe('The server\'s JavaScript stepper against a real js-debug (issues #1130 expect(answer.message).toBe('Stepped into'); }, 60000); }); + + describe('async functions, callbacks the program only scheduled, and a caller\'s own skip list', () => { + const ASYNC_FIXTURE = path.resolve(here, '../../../fixtures/javascript/step-skipped-code/async-steps.cjs'); + const ASYNC_LINES = fs.readFileSync(ASYNC_FIXTURE, 'utf8').split('\n'); + const at = (marker: string): number => { + const index = ASYNC_LINES.findIndex((line) => line.includes(`// MARK: ${marker}`)); + if (index === -1) { + throw new Error(`no line marked "${marker}" in the async fixture`); + } + return index + 1; + }; + + async function asyncPausedAt(marker: string, options: { condition?: string; launchArgs?: Record } = {}): Promise { + server = await startStdioClient({ name: 'js-stepper-async' }); + await server.createSession('javascript', 'js-stepper-async'); + const set = await server.call('set_breakpoint', { + file: ASYNC_FIXTURE, + line: at(marker), + ...(options.condition ? { condition: options.condition } : {}) + }); + expect(set.success, JSON.stringify(set)).toBe(true); + let stop = await server.call('start_debugging', { + scriptPath: ASYNC_FIXTURE, + ...(options.launchArgs ? { dapLaunchArgs: options.launchArgs } : {}) + }); + expect(stop.success, JSON.stringify(stop)).toBe(true); + if (stop.state !== 'paused') { + stop = await server.call('wait_for_stop', { timeout: 20000 }); + } + expect(stop, JSON.stringify(stop)).toMatchObject({ success: true, state: 'paused' }); + expect(stop.location?.line, JSON.stringify(stop)).toBe(at(marker)); + } + + function expectAsyncLanding(answer: StopAnswer & { ms: number }, marker: string): void { + expect(answer, JSON.stringify(answer)).toMatchObject({ success: true, state: 'paused' }); + expect(answer.pending, JSON.stringify(answer)).toBeUndefined(); + expect(answer.location?.file ?? '', JSON.stringify(answer)).toMatch(/async-steps\.cjs$/); + expect(answer.location?.line, JSON.stringify(answer)).toBe(at(marker)); + expect(answer.ms, `took ${answer.ms} ms: ${JSON.stringify(answer)}`).toBeLessThan(PROMPT_MS); + } + + it('step_out of an async function lands in the call that awaited it, with other calls of the same function in flight', async () => { + await asyncPausedAt('in inner, after the gate', { condition: 'id === 2' }); + const answer = await step('step_out'); + expectAsyncLanding(answer, 'the continuation of handler'); + // A temporary breakpoint on `handler` stopped in handler(1), whose + // continuation was queued first. V8's own step finds handler(2). + const id = await server!.call('evaluate_expression', { expression: 'id' }); + expect(id.result, JSON.stringify(id)).toBe('2'); + expect(answer.message).toBe('Stepped out'); + }, 60000); + + it('step_over on an await lands on the next line of the same function, though the function has a finally clause', async () => { + await asyncPausedAt('an await before the try'); + // With a temporary breakpoint on the caller, the step stopped there the + // moment this function suspended. + expectAsyncLanding(await step('step_over'), 'an await inside the try'); + expectAsyncLanding(await step('step_over'), 'the return inside the try'); + expectAsyncLanding(await step('step_over'), 'the finally block of an async function'); + // Off the finally block V8 loses the step; it is caught at the awaiting + // function, and the answer says what that can and cannot promise. + const out = await step('step_over'); + expectAsyncLanding(out, 'after closing'); + expect(out.message).toBe(`Stepped over. ${ErrorMessages.stepCaughtAtAwaitingFunction('main')}`); + }, 60000); + + it('step_out of a .then callback resumes the program: what registered the callback is not what it returns to', async () => { + await asyncPausedAt('in a then callback'); + const answer = await step('step_out'); + // Nothing of the program is on the stack and nothing awaits the + // callback: the program runs to its end, 150 ms later. + expect(answer, JSON.stringify(answer)).toMatchObject({ success: true }); + expect(answer.state, JSON.stringify(answer)).not.toBe('paused'); + }, 60000); + + it('steps with V8 alone where Node\'s own code is program code: a skip list without ', async () => { + await asyncPausedAt('in a timer callback', { launchArgs: { skipFiles: ['**/node_modules/**'] } }); + const answer = await step('step_out'); + // V8 gives no break positions for Node's own scripts, so there is no + // temporary breakpoint to set on the timer code this returns to. The + // step used to fail for it, and leave the session in `error`. + expect(answer, JSON.stringify(answer)).toMatchObject({ success: true, state: 'paused' }); + expect(answer.location?.file ?? '', JSON.stringify(answer)).toMatch(/timers/); + }, 60000); + }); }); diff --git a/tests/fixtures/javascript/step-skipped-code/async-steps.cjs b/tests/fixtures/javascript/step-skipped-code/async-steps.cjs new file mode 100644 index 000000000..93fb7b865 --- /dev/null +++ b/tests/fixtures/javascript/step-skipped-code/async-steps.cjs @@ -0,0 +1,61 @@ +/** + * Fixture for the server's JavaScript stepper: async functions, callbacks + * the program only scheduled, and a caller's own skip list (issues #1130, + * #1161). + * + * Every line a test steps from carries a marker comment; the tests find + * lines by marker, so this file can be edited without renumbering them. + */ +let release; +const gate = new Promise((resolve) => { + release = resolve; +}); +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +async function inner(id) { + await gate; + const tag = id; // MARK: in inner, after the gate + return tag; +} + +async function handler(id) { + const got = await inner(id); + const out = got * 10; // MARK: the continuation of handler + return out; +} + +async function closing() { + const opened = await sleep(5); // MARK: an await before the try + try { + const row = await sleep(5); // MARK: an await inside the try + return [opened, row]; // MARK: the return inside the try + } finally { + globalThis.closed = true; // MARK: the finally block of an async function + } +} + +function onDone(value) { + const seen = value; // MARK: in a then callback + return seen; +} + +function onTimer() { + globalThis.ticked = true; // MARK: in a timer callback +} + +async function main() { + // Three calls of handler in flight at once, each awaiting its own inner. + const all = Promise.all([handler(1), handler(2), handler(3)]); + release(); + await all; + await closing(); // MARK: awaits closing + const afterClosing = 1; // MARK: after closing + Promise.resolve(7).then(onDone); + setTimeout(onTimer, 10); + await sleep(150); + return afterClosing; +} + +main().then(() => { + console.log('done'); +}); diff --git a/tests/proxy/js-stepper.test.ts b/tests/proxy/js-stepper.test.ts index af321e0bc..2fd80587f 100644 --- a/tests/proxy/js-stepper.test.ts +++ b/tests/proxy/js-stepper.test.ts @@ -13,7 +13,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; import { EventEmitter } from 'events'; import type { DebugProtocol } from '@vscode/debugprotocol'; -import { JsStepper } from '../../src/proxy/js-stepper.js'; +import { JsStepper, type JsStepperTunables } from '../../src/proxy/js-stepper.js'; import { ErrorMessages } from '../../src/utils/error-messages.js'; interface Frame { @@ -39,7 +39,12 @@ interface ScriptedPause { resumedByJsDebug?: boolean; /** What js-debug reports this pause as. */ dapReason?: string; - asyncParent?: { fn: string; script?: string; line: number; col?: number; skipped?: boolean }; + /** + * The first frame of the async stack, and what V8 calls the link: `await` + * (the default: the function on top returns to it), `Promise.then`, + * `Timeout` (it only scheduled the code on top). + */ + asyncParent?: { fn: string; script?: string; line: number; col?: number; skipped?: boolean; description?: string }; } interface ArmedBreakpoint { @@ -72,6 +77,11 @@ class Engine extends EventEmitter { onDap: (event: DebugProtocol.Event) => void = () => undefined; stackTraceFailures = 0; stackTraceCalls: number[] = []; + /** Scripts V8 refuses break positions for (Node's own, measured). */ + refuse = new Set(); + /** A CDP method that fails the next time it is sent, and ones that always fail. */ + failOnce: string | null = null; + failAlways = new Set(); private nextId = 0; isConnected(): boolean { @@ -80,6 +90,13 @@ class Engine extends EventEmitter { async send(method: string, params: Record = {}): Promise { this.calls.push({ method, params }); + if (this.failAlways.has(method)) { + throw new Error(`${method}: refused`); + } + if (this.failOnce === method) { + this.failOnce = null; + throw new Error(`${method}: refused`); + } switch (method) { case 'Debugger.stepInto': case 'Debugger.stepOver': @@ -91,6 +108,9 @@ class Engine extends EventEmitter { return {} as T; case 'Debugger.getPossibleBreakpoints': { const start = params.start as { scriptId: string; lineNumber: number; columnNumber: number }; + if (this.refuse.has(start.scriptId)) { + throw new Error('Debugger.getPossibleBreakpoints: Cannot retrive script context'); + } const own = [...this.positions.entries()].find(([key]) => key === `${start.scriptId}:${start.lineNumber}`)?.[1]; const list = own ?? Array.from({ length: 10 }, (_, i) => ({ lineNumber: start.lineNumber + i })); return { locations: list.map((l) => ({ scriptId: start.scriptId, columnNumber: 0, ...l })) } as T; @@ -118,6 +138,12 @@ class Engine extends EventEmitter { this.emit('cdp-event', 'Debugger.paused', this.toCdp(pause)); } + /** The running program pauses here by itself (a net, a breakpoint, a pause request), js-debug's report included. */ + arrive(pause: ScriptedPause): void { + this.script.unshift(pause); + this.advance(false); + } + private advance(resumedFirst: boolean): void { if (resumedFirst) { this.emit('cdp-event', 'Debugger.resumed', {}); @@ -175,6 +201,7 @@ class Engine extends EventEmitter { ...(pause.asyncParent ? { asyncStackTrace: { + description: pause.asyncParent.description ?? 'await', callFrames: [{ functionName: pause.asyncParent.fn, scriptId: pause.asyncParent.script ?? 'app', @@ -208,7 +235,7 @@ class Engine extends EventEmitter { }); const frames = pause.frames.map(mark); if (pause.asyncParent) { - frames.push({ id: 900, name: 'await', line: 0, column: 0, presentationHint: 'label' }); + frames.push({ id: 900, name: pause.asyncParent.description ?? 'await', line: 0, column: 0, presentationHint: 'label' }); frames.push(mark(pause.asyncParent, 901)); } return { body: { stackFrames: frames.slice(0, levels) } } as DebugProtocol.StackTraceResponse; @@ -231,7 +258,6 @@ describe('JsStepper (issue #1130)', () => { let delivered: DebugProtocol.Event[]; /** Every DAP event of the target, with whether the stepper kept it. */ let seen: Array<{ event: string; withheld: boolean }>; - let targetRequests: Array<{ command: string; args: unknown }>; const commands = (): string[] => engine.calls.map((c) => c.method).filter((m) => /step|resume/.test(m)); const setBreakpoints = (): number => engine.calls.filter((c) => c.method === 'Debugger.setBreakpoint').length; @@ -249,11 +275,9 @@ describe('JsStepper (issue #1130)', () => { engine = new Engine(); delivered = []; seen = []; - targetRequests = []; stepper = new JsStepper({ target: { sendRequest: async (command: string, args?: unknown) => { - targetRequests.push({ command, args }); if (command !== 'stackTrace') throw new Error(`unexpected ${command}`); return engine.stackTrace((args as { levels: number }).levels) as never; } @@ -377,7 +401,7 @@ describe('JsStepper (issue #1130)', () => { expect(stopped()).toMatchObject({ reason: 'step' }); }); - it('steps out once the budget is spent, lands by the net when V8 loses the step-out, and says the line called only skipped code', async () => { + it('steps out once the budget is spent, lands by the net when V8 loses the step-out, and says how far it walked without reaching the program', async () => { stepper = new JsStepper({ target: { sendRequest: async (_c: string, args?: unknown) => engine.stackTrace((args as { levels: number }).levels) as never }, deliver: (event) => delivered.push(event), @@ -401,7 +425,8 @@ describe('JsStepper (issue #1130)', () => { expect(stopped()).toMatchObject({ reason: 'step', description: 'Paused' }); // js-debug reported the net hit as a breakpoint with no ids: not what leaves. expect(stopped().hitBreakpointIds).toBeUndefined(); - expect(stopped().text).toBe(ErrorMessages.stepIntoFoundOnlySkippedCode()); + // Three step-ins, back in the frame it left: that much is known, and said. + expect(stopped().text).toBe(ErrorMessages.stepIntoReachedNoProgramCode(3)); expect(engine.armed).toEqual([]); }); @@ -583,19 +608,20 @@ describe('JsStepper (issue #1130)', () => { expect(engine.armed).toEqual([]); }); - it('an async function with no program frame below returns to its awaiter: the net goes on the async parent, at any depth', async () => { - engine.pauseAt({ - frames: frames(app('work', 9), node('processTicksAndRejections', 70)), - asyncParent: { fn: 'main', line: 16, col: 12 } - }); - engine.script = [{ frames: frames(app('main', 17)), reason: 'other', hits: (armed) => [armed[0].id] }]; + it('caps a net, and wraps to the function\'s start when the frame is near its end', async () => { + const start = fnLineOf(app('wrap', 0)); + engine.positions.set(`app:${start}`, Array.from({ length: 300 }, (_, i) => ({ lineNumber: start + i }))); + engine.pauseAt({ frames: frames(app('leaf', 5), app('wrap', start + 290)) }); + engine.script = [{ frames: frames(app('wrap', start + 291)) }]; await stepper.request('stepOut', { threadId: 1 }); await settled(); - // Asked from the awaiter's own position, since its frame is not on the stack. - const asked = engine.calls.find((c) => c.method === 'Debugger.getPossibleBreakpoints'); - expect(asked?.params.start).toEqual({ scriptId: 'app', lineNumber: 16, columnNumber: 12 }); - expect(stopped()).toMatchObject({ reason: 'step' }); - expect(engine.armed).toEqual([]); + const lines = engine.calls + .filter((c) => c.method === 'Debugger.setBreakpoint') + .map((c) => (c.params.location as { lineNumber: number }).lineNumber); + expect(lines).toHaveLength(24); + // Ten to the end of the function (a loop comes back to its top), fourteen from its start. + expect(lines.filter((line) => line >= start + 290)).toHaveLength(10); + expect(lines.filter((line) => line < start + 14)).toHaveLength(14); }); it('caps a net, and takes it from the frame\'s own position on', async () => { @@ -752,6 +778,13 @@ describe('JsStepper (issue #1130)', () => { expect(delivered).toEqual([]); }); + it.each(['disconnect', 'terminate', 'restart', 'goto', 'restartFrame'])('a %s request ends it too, net removed first', async (command) => { + await stepOutAndRun(); + await stepper.beforeRequest(command); + expect(engine.armed).toEqual([]); + expect(stepper.describe()).toMatchObject({ chain: false, nets: 0 }); + }); + it('a request that neither resumes nor ends the target leaves it alone', async () => { await stepOutAndRun(); await stepper.beforeRequest('stackTrace'); @@ -786,6 +819,571 @@ describe('JsStepper (issue #1130)', () => { }); }); + // ----- what the review of the branch found (cases written red first) ----- + + /** A stepper with its own tunables, on the same engine. */ + function withTunables(tunables: Partial, onDeliver?: (event: DebugProtocol.Event) => void): void { + stepper = new JsStepper({ + target: { sendRequest: async (_c: string, args?: unknown) => engine.stackTrace((args as { levels: number }).levels) as never }, + deliver: (event) => { + onDeliver?.(event); + delivered.push(event); + }, + tunables: { settleCeilingMs: 150, verdictCeilingMs: 150, ...tunables } + }); + engine.onDap = (event) => { + seen.push({ event: event.event, withheld: stepper.withholds(event) }); + }; + stepper.attachCdp(engine); + stepper.setEnabled(true); + } + + /** The text of a script, with these 0-based lines set. */ + function sourceWith(lines: Record, script = 'app'): void { + const source = Array.from({ length: 2000 }, () => 'x();'); + for (const [line, text] of Object.entries(lines)) { + source[Number(line)] = text; + } + engine.sources.set(script, source.join('\n')); + } + + /** How many net breakpoints were set in V8 when each step command went out. */ + function armedAtEachStep(): number[] { + const counts: number[] = []; + const send = engine.send.bind(engine); + engine.send = (async (method: string, params?: Record) => { + if (/Debugger\.step/.test(method)) { + counts.push(engine.armed.length); + } + return send(method, params); + }) as typeof engine.send; + return counts; + } + + describe('a net is a safeguard: a step never fails for one', () => { + /** Node's own code on a skip list that leaves it out: not marked skipped, and V8 refuses its break positions. */ + const timers = (fn: string, line: number): Frame => ({ fn, line, script: 'node:timers' }); + + it('serves the step with V8 alone when V8 refuses break positions for the frame it returns to', async () => { + engine.refuse.add('node:timers'); + engine.pauseAt({ frames: frames(app('onTimer', 5), timers('listOnTimeout', 605), timers('processTimers', 541)) }); + engine.script = [{ frames: frames(timers('listOnTimeout', 609), timers('processTimers', 541)) }]; + + const response = await stepper.request('stepOut', { threadId: 1 }); + expect(response).toMatchObject({ success: true }); + await settled(); + + expect(commands()).toEqual(['Debugger.stepOut']); + expect(stopped()).toMatchObject({ reason: 'step' }); + expect(setBreakpoints()).toBe(0); + }); + + it('goes on with V8 alone when the net cannot be set at a skipped landing', async () => { + engine.refuse.add('weird'); + engine.pauseAt({ frames: frames(app('listener', 40), node('emit', 7), app('caller', 10, { script: 'weird' })) }); + engine.script = [ + { frames: frames(node('emit', 8), app('caller', 10, { script: 'weird' })) }, + { frames: frames(app('caller', 11, { script: 'weird' })) } + ]; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(commands()).toEqual(['Debugger.stepOver', 'Debugger.stepOut']); + expect(stopped()).toMatchObject({ reason: 'step' }); + }); + + it('reports a stop when the chain fails while V8 is paused: the caller is never left without one', async () => { + engine.pauseAt({ frames: frames(app('listener', 40), node('emit', 7), app('main', 10)) }); + engine.script = [{ frames: frames(node('emit', 8), app('main', 10)) }]; + // The step-out the chain sends from Node's code is refused: V8 stays paused there. + engine.failOnce = 'Debugger.stepOut'; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(delivered).toHaveLength(1); + expect(stopped()).toMatchObject({ reason: 'step' }); + expect(engine.armed).toEqual([]); + expect(stepper.describe()).toMatchObject({ chain: false, nets: 0 }); + }); + + it('a first command V8 refuses leaves no net behind', async () => { + engine.pauseAt({ frames: frames(app('leaf', 5), app('caller', 14)) }); + engine.failOnce = 'Debugger.stepOut'; + await expect(stepper.request('stepOut', { threadId: 1 })).rejects.toThrow(/refused/); + // The net on the caller was set before the command, and is gone. + expect(setBreakpoints()).toBeGreaterThan(0); + expect(engine.armed).toEqual([]); + expect(stepper.describe()).toMatchObject({ chain: false, nets: 0 }); + }); + + it('counts a net with no breakpoint set as no net', async () => { + engine.failAlways.add('Debugger.setBreakpoint'); + engine.pauseAt({ frames: frames(app('leaf', 5), app('caller', 14)) }); + engine.script = ['runs']; + await stepper.request('stepOut', { threadId: 1 }); + await tick(5); + expect(stepper.describe()).toMatchObject({ chain: true, nets: 0 }); + await stepper.beforeRequest('continue'); + }); + + it('asks again for the stack while js-debug says it is not paused yet, rather than taking it for an empty one', async () => { + // A first step teaches the stepper that Node's script is skipped: it is not asked about again. + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [{ frames: frames(node('log', 1), app('main', 10)) }, { frames: frames(app('main', 11)) }]; + await stepper.request('stepIn', { threadId: 1 }); + await settled(); + delivered.length = 0; + engine.calls.length = 0; + + // So the first thing js-debug is asked about the next landing is the whole stack, and it is not ready. + engine.pauseAt({ frames: frames(app('listener', 40), node('emit', 7), app('main', 10)) }); + engine.script = [{ frames: frames(node('emit', 8), app('main', 10)) }, { frames: frames(app('main', 11)) }]; + engine.stackTraceFailures = 1; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(commands()).toEqual(['Debugger.stepOver', 'Debugger.stepOut']); + expect(stopped()).toMatchObject({ reason: 'step' }); + }); + + it('does not take a stack deeper than it asked about for an empty one', async () => { + const deep = Array.from({ length: 230 }, (_, i) => node(`f${i % 5}`, i)); + engine.pauseAt({ frames: frames(app('listener', 40), ...deep, app('main', 10)) }); + engine.script = [{ frames: frames(...deep, app('main', 10)) }, { frames: frames(app('main', 11)) }]; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(commands()).toEqual(['Debugger.stepOver', 'Debugger.stepOut']); + expect(stopped()).toMatchObject({ reason: 'step' }); + }); + }); + + describe('an async function the event loop resumed', () => { + it('steps out by V8 alone: its own async step finds the one awaiting call, where a net on the function would stop in any', async () => { + engine.pauseAt({ frames: frames(app('inner', 5)), asyncParent: { fn: 'handler', line: 9, col: 14 } }); + engine.script = [{ frames: frames(app('handler', 10)), asyncParent: { fn: 'main', line: 14 } }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBe(0); + expect(commands()).toEqual(['Debugger.stepOut']); + expect(stopped()).toMatchObject({ reason: 'step' }); + expect(stopped().text).toBeUndefined(); + }); + + it('nets the awaiting function only where V8 loses the step (`finally` in the function left), and says the stop may be another call\'s', async () => { + const start = fnLineOf(app('innerF', 0)); + sourceWith({ [start + 1]: 'try {', [start + 2]: ' await gate; return tag;', [start + 3]: '} finally { noop(); }' }); + engine.pauseAt({ frames: frames(app('innerF', start + 2)), asyncParent: { fn: 'handler', line: 9, col: 14 } }); + // V8's step-out is lost; the next thing V8 says is the net in `handler`. + engine.script = [{ frames: frames(app('handler', 10)), reason: 'other', hits: (armed) => [armed[0].id] }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + // Asked from the awaiter's own position, since its frame is not on the stack. + const asked = engine.calls.filter((c) => c.method === 'Debugger.getPossibleBreakpoints').map((c) => c.params.start); + expect(asked).toContainEqual({ scriptId: 'app', lineNumber: 9, columnNumber: 14 }); + expect(stopped()).toMatchObject({ reason: 'step', text: ErrorMessages.stepCaughtAtAwaitingFunction('handler') }); + expect(engine.armed).toEqual([]); + }); + + it('nets no awaiter that is skipped code', async () => { + const start = fnLineOf(app('innerG', 0)); + sourceWith({ [start + 1]: 'try {', [start + 2]: ' await gate; return tag;', [start + 3]: '} finally { noop(); }' }); + engine.pauseAt({ frames: frames(app('innerG', start + 2)), asyncParent: { fn: 'libRun', line: 9, script: 'lib', skipped: true } }); + engine.script = ['runs']; + await stepper.request('stepOut', { threadId: 1 }); + await tick(5); + expect(setBreakpoints()).toBe(0); + await stepper.beforeRequest('continue'); + }); + + it('does not take what only scheduled the code for what it returns to: a step out of a `.then` callback resumes', async () => { + engine.pauseAt({ frames: frames(app('onDone', 3)), asyncParent: { fn: 'work', line: 7, description: 'Promise.then' } }); + engine.script = [{ frames: frames(node('processTimers', 527)) }, 'runs']; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBe(0); + expect(commands()).toEqual(['Debugger.stepOut', 'Debugger.resume']); + expect(delivered).toEqual([]); + }); + + it('follows V8 through a skipped awaiter to the program\'s, looking again at each landing', async () => { + engine.pauseAt({ frames: frames(app('handler', 20)), asyncParent: { fn: 'libRun', line: 5, script: 'lib', skipped: true } }); + engine.script = [ + { frames: frames({ fn: 'libRun', line: 6, script: 'lib', skipped: true }), asyncParent: { fn: 'main', line: 30 } }, + { frames: frames(app('main', 31)) } + ]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(commands()).toEqual(['Debugger.stepOut', 'Debugger.stepOut']); + expect(stopped()).toMatchObject({ reason: 'step' }); + expect(setBreakpoints()).toBe(0); + }); + + it('resumes once the awaiting chain ends in skipped code: no walk through the next tasks', async () => { + engine.pauseAt({ frames: frames(app('handler', 20)), asyncParent: { fn: 'libRun', line: 5, script: 'lib', skipped: true } }); + engine.script = [ + { frames: frames({ fn: 'libRun', line: 6, script: 'lib', skipped: true }), asyncParent: { fn: 'main', line: 30 } }, + // Nothing awaited it after all: the next task's internals. + { frames: frames(node('processTicksAndRejections', 70)) }, + 'runs' + ]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(commands()).toEqual(['Debugger.stepOut', 'Debugger.stepOut', 'Debugger.resume']); + expect(delivered).toEqual([]); + }); + + it('a step over arms nothing while the step cannot leave a function that can suspend: only on a `return` line, and from its `finally` on', async () => { + const start = fnLineOf(app('mainAsync', 0)); + sourceWith({ + [start + 1]: 'const first = await sleep(20);', + [start + 2]: 'try {', + [start + 3]: ' const second = await sleep(20);', + [start + 4]: ' return second;', + [start + 5]: '} finally {', + [start + 6]: ' done();', + [start + 7]: '}' + }); + // On an await line the function suspends and its caller runs on: a net on the caller would stop there. + engine.pauseAt({ frames: frames(app('mainAsync', start + 1), app('caller', 14)) }); + engine.script = [{ frames: frames(app('mainAsync', start + 3)) }]; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBe(0); + expect(stopped()).toMatchObject({ reason: 'step' }); + + // On the return line the step can leave through `finally`: the frame it returns to is netted. + delivered.length = 0; + engine.calls.length = 0; + engine.pauseAt({ frames: frames(app('mainAsync', start + 4), app('caller', 14)) }); + engine.script = [{ frames: frames(app('mainAsync', start + 6), app('caller', 14)) }]; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBeGreaterThan(0); + expect(engine.armed).toEqual([]); + + // And in the finally block, where V8 loses it. + delivered.length = 0; + engine.calls.length = 0; + engine.pauseAt({ frames: frames(app('mainAsync', start + 6), app('caller', 14)) }); + engine.script = [{ frames: frames(app('caller', 15)), reason: 'other', hits: (armed) => [armed[1].id] }]; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBeGreaterThan(0); + expect(stopped()).toMatchObject({ reason: 'step' }); + expect(engine.armed).toEqual([]); + }); + + it('reads `finally` in the function\'s own text only', async () => { + const start = fnLineOf(app('plainF', 0)); + // Another function, further down the script. + sourceWith({ [start + 40]: 'try { a(); } finally { b(); }' }); + engine.pauseAt({ frames: frames(app('plainF', start + 2), app('caller', 14)) }); + engine.script = [{ frames: frames(app('plainF', start + 3), app('caller', 14)) }]; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBe(0); + }); + }); + + describe('the sentence on a step-in that reached nothing of the program', () => { + it('says nothing when the step went on into the program\'s code after all: the line\'s next call', async () => { + withTunables({ budget: 2 }); + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [ + { frames: frames(node('log', 1), app('main', 10)) }, + { frames: frames(node('log', 2), app('main', 10)) }, + { frames: frames(node('log', 3), app('main', 10)) }, + // Stepped out, back on the line: the line's second call is the program's own. + { frames: frames(app('main', 10, { col: 14 })) }, + { frames: frames(app('helper', 60), app('main', 10, { col: 14 })) } + ]; + await stepper.request('stepIn', { threadId: 1 }); + await settled(); + expect(commands()).toEqual(['Debugger.stepInto', 'Debugger.stepInto', 'Debugger.stepInto', 'Debugger.stepOut', 'Debugger.stepInto']); + expect(stopped()).toMatchObject({ reason: 'step' }); + expect(stopped().text).toBeUndefined(); + }); + + it('steps in again when the net brings it back to its own line, and says how far the walk went when it ends in the frame it left', async () => { + withTunables({ budget: 2 }); + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [ + { frames: frames(node('log', 1), app('main', 10)) }, + { frames: frames(node('log', 2), app('main', 10)) }, + { frames: frames(node('log', 3), app('main', 10)) }, + // What the real walk out of console.log does: V8's step-out and the net agree, mid-line. + { frames: frames(app('main', 10, { col: 14 })), reason: 'ambiguous', hits: (armed) => [armed[0].id] }, + { frames: frames(app('main', 11)) } + ]; + await stepper.request('stepIn', { threadId: 1 }); + await settled(); + expect(commands()).toEqual(['Debugger.stepInto', 'Debugger.stepInto', 'Debugger.stepInto', 'Debugger.stepOut', 'Debugger.stepInto']); + expect(stopped()).toMatchObject({ reason: 'step', text: ErrorMessages.stepIntoReachedNoProgramCode(3) }); + }); + }); + + describe('a pause the caller asks for during a step', () => { + async function stepOverAndRun(): Promise { + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = ['runs']; + await stepper.request('next', { threadId: 1 }); + await tick(10); + await stepper.beforeRequest('pause'); + } + + it('is theirs wherever V8 stops, even in skipped code: the chain does not step away from it', async () => { + await stepOverAndRun(); + // V8 reports a pause taken while a step is in flight as the step. + engine.arrive({ frames: frames(node('formatValue', 300), app('main', 10)), reason: 'ambiguous', dapReason: 'pause' }); + await settled(); + expect(commands()).toEqual(['Debugger.stepOver']); + expect(delivered).toHaveLength(1); + expect(stopped()).toMatchObject({ reason: 'pause' }); + expect(setBreakpoints()).toBe(0); + }); + + it('is reported as a pause in program code too, not as the step', async () => { + await stepOverAndRun(); + engine.arrive({ frames: frames(app('main', 12)), reason: 'ambiguous', dapReason: 'pause' }); + await settled(); + expect(stopped()).toMatchObject({ reason: 'pause' }); + }); + + it('gives way to a breakpoint that fires first: that stop goes out as itself', async () => { + await stepOverAndRun(); + engine.arrive({ frames: frames(app('callee', 30), app('main', 10)), reason: 'other', hits: ['js-debug:7'], dapReason: 'breakpoint' }); + await settled(); + expect(stopped()).toMatchObject({ reason: 'breakpoint', description: 'Paused on breakpoint' }); + }); + }); + + describe('edges the mutation pass found unpinned', () => { + it('a new step gives up the one in flight: its nets are gone before the new command', async () => { + engine.pauseAt({ frames: frames(app('work', 9), app('main', 14)) }); + engine.script = ['runs']; + await stepper.request('stepOut', { threadId: 1 }); + await tick(10); + expect(engine.armed.length).toBeGreaterThan(0); + + // V8 is paused again by something else, and the caller steps from there. + engine.pauseAt({ frames: frames(app('other', 50), app('main', 14)), reason: 'other' }); + engine.script = [{ frames: frames(app('other', 51), app('main', 14)) }]; + const armed = armedAtEachStep(); + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(armed).toEqual([0]); + expect(delivered).toHaveLength(1); + expect(stopped()).toMatchObject({ reason: 'step' }); + }); + + it('a new step owes nothing of the last one', async () => { + // js-debug's stopped for the first step never comes. + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [{ frames: frames(app('main', 11)) }]; + engine.onDap = (event) => { + if (event.event !== 'stopped') stepper.withholds(event); + }; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(stepper.describe().owed).toBe(1); + + // The next step is complete: nothing is owed after it. + engine.onDap = (event) => { + seen.push({ event: event.event, withheld: stepper.withholds(event) }); + }; + engine.script = [{ frames: frames(app('main', 12)) }]; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(stepper.describe().owed).toBe(0); + expect(stepper.withholds({ seq: 0, type: 'event', event: 'stopped', body: { reason: 'pause', threadId: 1 } })).toBe(false); + }); + + it('drops only what can be the step\'s own late report: an exception stop right after is forwarded', async () => { + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [{ frames: frames(app('main', 11)) }]; + const late: DebugProtocol.Event[] = []; + engine.onDap = (event) => { + if (event.event === 'stopped') late.push(event); + else stepper.withholds(event); + }; + await stepper.request('next', { threadId: 4 }); + await settled(); + expect(stepper.withholds({ seq: 0, type: 'event', event: 'stopped', body: { reason: 'exception', threadId: 4 } })).toBe(false); + expect(stepper.withholds({ seq: 0, type: 'event', event: 'stopped', body: { reason: 'breakpoint', threadId: 4, hitBreakpointIds: [7] } })).toBe(false); + // The step's own, late: still dropped. + expect(stepper.withholds(late[0])).toBe(true); + }); + + it('sends nothing more once the step is given up while a landing is being judged', async () => { + let gated = false; + let release: () => void = () => undefined; + stepper = new JsStepper({ + target: { + sendRequest: async (_c: string, args?: unknown) => { + if (gated) { + await new Promise((resolve) => { + release = resolve; + }); + } + return engine.stackTrace((args as { levels: number }).levels) as never; + } + }, + deliver: (event) => delivered.push(event), + tunables: { settleCeilingMs: 150, verdictCeilingMs: 150 } + }); + stepper.attachCdp(engine); + stepper.setEnabled(true); + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [{ frames: frames(node('log', 1), app('main', 10)) }]; + gated = true; + await stepper.request('stepIn', { threadId: 1 }); + await tick(10); + // js-debug has not answered about the landing yet, and the caller continues. + await stepper.beforeRequest('continue'); + gated = false; + release(); + await tick(20); + expect(commands()).toEqual(['Debugger.stepInto']); + expect(engine.armed).toEqual([]); + expect(stepper.describe()).toMatchObject({ chain: false, nets: 0 }); + expect(delivered).toEqual([]); + }); + + it('serves no step while the program runs', async () => { + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = ['runs']; + await stepper.request('next', { threadId: 1 }); + await tick(5); + expect(stepper.handles('next')).toBe(false); + await stepper.beforeRequest('continue'); + }); + + it('a net at the landing\'s own depth guards nothing below it: the stack is gone, and the program resumes', async () => { + engine.pauseAt({ frames: frames(app('work', 9), app('main', 14)) }); + // V8's step-out comes back in the next task: Node's own code, nothing of the program under it. + engine.script = [{ frames: frames(node('processTicksAndRejections', 70)) }, 'runs']; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(commands()).toEqual(['Debugger.stepOut', 'Debugger.resume']); + expect(delivered).toEqual([]); + expect(engine.armed).toEqual([]); + }); + + it('a net hit deeper than the frame it guards, on a step over: the net is dropped and V8\'s own step-outs finish at the origin depth', async () => { + const start = fnLineOf(app('guardedF', 0)); + sourceWith({ [start + 2]: 'try { return work(); } finally { done(); }' }); + engine.pauseAt({ frames: frames(app('guardedF', start + 2), app('g', 14)) }); + engine.script = [ + // work() called g again: a net position of g, three frames above the call it guards. + { frames: frames(app('g', 15), app('work', 70), app('guardedF', start + 2), app('g', 14)), reason: 'ambiguous', hits: (armed) => [armed[0].id] }, + { frames: frames(app('work', 71), app('guardedF', start + 2), app('g', 14)) }, + { frames: frames(app('guardedF', start + 3), app('g', 14)) } + ]; + const armed = armedAtEachStep(); + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(commands()).toEqual(['Debugger.stepOver', 'Debugger.stepOut', 'Debugger.stepOut']); + expect(armed[0]).toBeGreaterThan(0); + expect(armed.slice(1)).toEqual([0, 0]); + expect(stopped()).toMatchObject({ reason: 'step' }); + }); + + it('and when the dropped net fired no deeper than the step began, that is the landing', async () => { + const start = fnLineOf(app('guardedH', 0)); + sourceWith({ [start + 2]: 'try { return work(); } finally { done(); }' }); + engine.pauseAt({ frames: frames(app('guardedH', start + 2), app('x', 20), app('g', 14)) }); + engine.script = [ + { frames: frames(app('x', 21), app('x', 20), app('g', 14)), reason: 'ambiguous', hits: (armed) => [armed[0].id] }, + 'runs' + ]; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(commands()).toEqual(['Debugger.stepOver']); + expect(stopped()).toMatchObject({ reason: 'step' }); + expect(engine.armed).toEqual([]); + }); + + it('a step-in that lands on its own line in a deeper call of the same function has landed', async () => { + const start = fnLineOf(app('walk', 0)); + engine.pauseAt({ frames: frames(app('walk', start + 1), app('main', 10)) }); + engine.script = [{ frames: frames(app('walk', start + 1), app('walk', start + 1), app('main', 10)) }, 'runs']; + await stepper.request('stepIn', { threadId: 1 }); + await settled(); + expect(commands()).toEqual(['Debugger.stepInto']); + }); + + it('only a step-in steps in again on its own line: a step over that stops there has landed', async () => { + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [{ frames: frames(app('main', 10, { col: 14 })) }, 'runs']; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(commands()).toEqual(['Debugger.stepOver']); + }); + + it('stops stepping in again on its own line after the cap', async () => { + withTunables({ reissueCap: 2 }); + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [ + { frames: frames(app('main', 10, { col: 5 })) }, + { frames: frames(app('main', 10, { col: 9 })) }, + { frames: frames(app('main', 10, { col: 13 })) }, + 'runs' + ]; + await stepper.request('stepIn', { threadId: 1 }); + await settled(); + expect(commands()).toEqual(['Debugger.stepInto', 'Debugger.stepInto', 'Debugger.stepInto']); + expect(stopped()).toMatchObject({ reason: 'step' }); + }); + + it('a step-in under a net that stops in a deeper frame of the program has landed there', async () => { + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [ + { frames: frames(node('log', 1), app('main', 10)) }, + // Node's code called back into main's own function: a net position, deeper. + { frames: frames(app('main', 15), node('cb', 4), node('log', 2), app('main', 10)), reason: 'ambiguous', hits: (armed) => [armed[0].id] }, + 'runs' + ]; + await stepper.request('stepIn', { threadId: 1 }); + await settled(); + expect(commands()).toEqual(['Debugger.stepInto', 'Debugger.stepInto']); + expect(stopped()).toMatchObject({ reason: 'step' }); + expect(engine.armed).toEqual([]); + }); + + it('waits for js-debug\'s own verdict on a pause that is not the stepper\'s, however its earlier reports stand', async () => { + engine.pauseAt({ frames: frames(app('work', 9), app('main', 14)) }); + engine.script = ['runs']; + await stepper.request('stepOut', { threadId: 1 }); + await tick(10); + // js-debug's module-entry breakpoint: it resumes the pause itself. Nothing was kept so far, and nothing reported. + engine.script = [{ frames: frames(app('main', 15)), reason: 'other', hits: (armed) => [armed[0].id] }]; + engine.arrive({ frames: frames(app('mod', 0, { script: 'mod' }), app('work', 9), app('main', 14)), reason: 'other', hits: ['js-debug:entry'], resumedByJsDebug: true }); + await settled(); + expect(delivered).toHaveLength(1); + expect(stopped()).toMatchObject({ reason: 'step' }); + expect(commands()).toEqual(['Debugger.stepOut']); + }); + + it('takes a landing js-debug never answers for as program code, once the ceiling is passed', async () => { + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [{ frames: frames(app('main', 11)) }, 'runs']; + engine.stackTraceFailures = 1e6; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(commands()).toEqual(['Debugger.stepOver']); + expect(stopped()).toMatchObject({ reason: 'step' }); + }); + + it('reports only after js-debug has reported the pause itself', async () => { + let reportsSeenAtDelivery = -1; + withTunables({}, () => { + reportsSeenAtDelivery = seen.filter((e) => e.event === 'stopped').length; + }); + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [{ frames: frames(app('main', 11)) }]; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(reportsSeenAtDelivery).toBe(1); + }); + }); + it('refuses a step it cannot start, and leaves no net behind', async () => { engine.pauseAt({ frames: frames(app('leaf', 5), app('caller', 14)) }); engine.current = null; // V8 resumed behind the stepper's back From 153fd0989f8443f35410e62f779ea50553f87810 Mon Sep 17 00:00:00 2001 From: JF Date: Mon, 16 Nov 2026 00:05:03 -0500 Subject: [PATCH 08/24] fix(javascript): an attach's child sessions keep js-debug's stepper off and take the root's choice; the wiring's unit cases (#1130) Two things the review found in the wiring, and the coverage it found missing. The start request's smartStep was overridden after the parent's start was snapshotted, so an attach session's child `attach` request, built from that snapshot, went out with the caller's smartStep: true and turned js-debug's own stepper back on beside the proxy's. The override now comes first. A forked child's stepper read the launch configuration only, so a child of an attach root never got one. It now asks the root what its own start request said (MinimalDapClient.stepsThroughSkippedCode), and falls back to the launch configuration when the root cannot say. The wiring had almost no unit coverage: 23 of the review's 30 wiring mutants survived. New cases in the minimal-dap, child-session-manager, child-connections, worker, policy and step-message suites kill 24 of the 25 listed (the last is equivalent: the branch it changes is unreachable for a non-step stop). One test seam: ChildSessionOptions.cdpClientFactory. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn69pXrYMWc1JUwv5v8 --- src/proxy/child-connections.ts | 14 +- src/proxy/child-session-manager.ts | 12 +- src/proxy/dap-proxy-interfaces.ts | 6 + src/proxy/dap-proxy-worker.ts | 4 +- src/proxy/minimal-dap.ts | 28 +- .../unit/session/session-manager-dap.test.ts | 60 ++++ tests/proxy/child-connections.test.ts | 266 ++++++++++++++++ tests/proxy/child-session-manager.test.ts | 289 ++++++++++++++++++ .../dap-proxy-worker-child-sessions.test.ts | 154 +++++++++- tests/unit/proxy/minimal-dap.test.ts | 272 ++++++++++++++++- tests/unit/shared/adapter-policy-js.test.ts | 10 + 11 files changed, 1094 insertions(+), 21 deletions(-) diff --git a/src/proxy/child-connections.ts b/src/proxy/child-connections.ts index 824a61d33..8dd5e06d8 100644 --- a/src/proxy/child-connections.ts +++ b/src/proxy/child-connections.ts @@ -59,6 +59,12 @@ export interface ChildAdoptionDeps { breakOnExceptions?: 'uncaught' | 'all' | 'none'; launchConfig?: LanguageSpecificLaunchConfig; initializedTimeoutMs?: number; + /** + * Whether the root session steps through skipped code (issue #1130), as its + * own start request said: a launch's or an attach's. A child's stepper + * takes that choice over. Undefined (or absent) when the root cannot say. + */ + stepsThroughSkippedCode?: () => boolean | undefined; } export interface ChildConnectionsOptions { @@ -438,8 +444,12 @@ export class ChildConnections extends EventEmitter { target: { sendRequest: (command, args, timeoutMs) => client.sendRequest(command, args, timeoutMs) as Promise }, deliver: (event) => this.sendEvent(sessionId, event.event, event.body) }); - // The session's choice is the root's: the start request's `smartStep`. - stepper.setEnabled((deps.launchConfig as { smartStep?: unknown } | undefined)?.smartStep === true); + // The session's choice is the root's: its start request's `smartStep`, a + // launch's or an attach's. The launch configuration is the fallback for a + // root that cannot say. + stepper.setEnabled( + deps.stepsThroughSkippedCode?.() ?? (deps.launchConfig as { smartStep?: unknown } | undefined)?.smartStep === true + ); connection.stepper = stepper; try { const response = (await client.sendRequest('requestCDPProxy', {}, 5000)) as { body?: { host?: string; port?: number; path?: string } }; diff --git a/src/proxy/child-session-manager.ts b/src/proxy/child-session-manager.ts index d481e0c8a..d08233d1e 100644 --- a/src/proxy/child-session-manager.ts +++ b/src/proxy/child-session-manager.ts @@ -46,6 +46,8 @@ export interface ChildSessionOptions { port: number; /** DI seam for tests; only consulted when the policy delivers function breakpoints via CDP (issue #295). */ cdpBridgeFactory?: () => CdpFunctionBreakpointBridge; + /** DI seam for tests: the CDP socket the default bridge opens, which the proxy stepper shares (issue #1130). */ + cdpClientFactory?: () => CdpProxyClient; /** * Read once per adoption (#712). Start intent never modifies parentConfig (#730). */ @@ -214,7 +216,7 @@ export class ChildSessionManager extends EventEmitter { // One CDP socket per target: the bridge opens it, the stepper listens on it too. this.cdpBridge = options.cdpBridgeFactory?.() ?? new CdpFunctionBreakpointBridge({ clientFactory: () => { - const client = new CdpProxyClient(); + const client = options.cdpClientFactory?.() ?? new CdpProxyClient(); this.stepper?.attachCdp(client); return client; } @@ -328,6 +330,14 @@ export class ChildSessionManager extends EventEmitter { logger.info(`[ChildSessionManager:${this.instanceId}] stepping through skipped code: ${enabled ? 'the proxy stepper' : 'off'}`); } + /** + * The session's choice as it stands, for a forked child's stepper to take + * over. Undefined when this manager has no stepper (another adapter). + */ + isSteppingThroughSkippedCode(): boolean | undefined { + return this.stepper?.isEnabled(); + } + /** * A step the proxy's stepper serves now, or null when it goes to the * adapter as it is (the session chose plain steps, no CDP socket, a step diff --git a/src/proxy/dap-proxy-interfaces.ts b/src/proxy/dap-proxy-interfaces.ts index a59d9042e..e78518328 100644 --- a/src/proxy/dap-proxy-interfaces.ts +++ b/src/proxy/dap-proxy-interfaces.ts @@ -282,6 +282,12 @@ export interface IDapClient { * has no child sessions — nothing to flush (issue #378). */ flushChildEvents?(): Promise | undefined; + /** + * Whether the session steps through skipped code, as its start request + * said (issue #1130). Optional: only MinimalDapClient implements it, and + * it answers undefined for an adapter with no proxy stepper. + */ + stepsThroughSkippedCode?(): boolean | undefined; } /** diff --git a/src/proxy/dap-proxy-worker.ts b/src/proxy/dap-proxy-worker.ts index 016a3375c..3bd954383 100644 --- a/src/proxy/dap-proxy-worker.ts +++ b/src/proxy/dap-proxy-worker.ts @@ -766,7 +766,9 @@ export class DapProxyWorker { port: spawnConfig.port, adapterId: this.adapterPolicy.getDapAdapterConfiguration().type, breakOnExceptions: payload.breakOnExceptions, - launchConfig: payload.launchConfig + launchConfig: payload.launchConfig, + // The root's own start request decides, a launch's or an attach's (issue #1130). + stepsThroughSkippedCode: () => this.dapClient?.stepsThroughSkippedCode?.() } }); this.childConnections.attach(this.dapClient, payload.sessionId); diff --git a/src/proxy/minimal-dap.ts b/src/proxy/minimal-dap.ts index bfd1ea5cc..ce0726eb6 100644 --- a/src/proxy/minimal-dap.ts +++ b/src/proxy/minimal-dap.ts @@ -209,6 +209,16 @@ export class MinimalDapClient extends EventEmitter implements IDapClient { return this.childSessionManager?.flushEvents(); } + /** + * Whether this session steps through skipped code, as its start request + * said (a launch's or an attach's `smartStep`, issue #1130). A forked + * child's stepper takes the root's choice over. Undefined when this client + * has no proxy stepper to ask: the caller falls back to what it knows. + */ + stepsThroughSkippedCode(): boolean | undefined { + return this.childSessionManager?.isSteppingThroughSkippedCode(); + } + /** * Handle raw data using the same algorithm as vscode's ProtocolServer * (extracted to DapFrameDecoder). This ensures compatibility and proper @@ -554,23 +564,25 @@ export class MinimalDapClient extends EventEmitter implements IDapClient { // only carries {type, name, __pendingTargetId} — request mode and // stopOnEntry never round-trip through the adapter (issue #124). if (command === 'attach' || command === 'launch') { - const { request: _request, stopOnEntry, ...attachArguments } = - (args as Record | undefined) ?? {}; - void _request; - const intent = typeof stopOnEntry === 'boolean' ? { stopOnEntry } : {}; - this.parentStart = command === 'attach' - ? { request: command, ...intent, attachArguments } - : { request: command, ...intent }; - // The start request's `smartStep` is the session's choice, not the // adapter's setting (issue #1130): the proxy's stepper steps through // skipped code, and the adapter's own stepper stays off whatever was // asked, because it loses steps and re-steps a statement at a time. + // Before the snapshot below: an attach's child session sends these + // arguments again, and they must not turn that stepper back on. if (this.dapBehavior.stepsThroughSkippedCode && this.childSessionManager && args !== null && typeof args === 'object') { const start = args as Record; this.childSessionManager.setStepThroughSkippedCode(start.smartStep === true); args = { ...start, smartStep: false }; } + + const { request: _request, stopOnEntry, ...attachArguments } = + (args as Record | undefined) ?? {}; + void _request; + const intent = typeof stopOnEntry === 'boolean' ? { stopOnEntry } : {}; + this.parentStart = command === 'attach' + ? { request: command, ...intent, attachArguments } + : { request: command, ...intent }; } // CDP-delivered function breakpoints (issue #295): the adapter has no diff --git a/tests/core/unit/session/session-manager-dap.test.ts b/tests/core/unit/session/session-manager-dap.test.ts index 5b73c3fbe..2d5b2ff38 100644 --- a/tests/core/unit/session/session-manager-dap.test.ts +++ b/tests/core/unit/session/session-manager-dap.test.ts @@ -1927,6 +1927,66 @@ describe('SessionManager - DAP Operations', () => { expect(data.message).toBe('Stepped over'); }); + // The JavaScript stepper reports a landing as reason `step` and puts what + // it has to say about it (the line called only skipped code) in the + // event's `text`. A literal here: the sentence is the stepper's, and any + // text a `step` stop carries is appended. + const STEP_NOTE = 'The line called only code this session skips; the step is back in the frame it started in.'; + + it.each([ + ['step_over', 'next', 'Stepped over', (id: string) => sessionManager.stepOver(id)], + ['step_into', 'stepIn', 'Stepped into', (id: string) => sessionManager.stepInto(id)], + ['step_out', 'stepOut', 'Stepped out', (id: string) => sessionManager.stepOut(id)] + ] as const)('%s appends what the step itself says about its landing to the completion wording (issue #1130)', async (_tool, command, stepped, step) => { + const session = await createPausedSession(sessionManager, dependencies); + dependencies.mockProxyManager.sendDapRequest = vi.fn().mockImplementation(async (sent: string) => { + if (sent === command) { + process.nextTick(() => { + dependencies.mockProxyManager.simulateStopped(1, 'step', { reason: 'step', threadId: 1, text: STEP_NOTE }); + }); + } + return { success: true }; + }); + + const stepPromise = step(session.id); + await vi.runAllTimersAsync(); + const result = await stepPromise; + + expect(result.success).toBe(true); + const data = result.data as { message?: string; stopReason?: string; pending?: boolean }; + expect(data.pending).toBeUndefined(); + // Still the step's own stop: no stopReason, the note after the wording. + expect(data.stopReason).toBeUndefined(); + expect(data.message).toBe(`${stepped}. ${STEP_NOTE}`); + }); + + it.each([ + // A breakpoint or an exception names itself; its text is not the step's to repeat. + ['breakpoint', ErrorMessages.stepStoppedOn('Stepped over', 'breakpoint')], + ['exception', ErrorMessages.stepStoppedOn('Stepped over', 'exception')], + // Any other stop keeps the plain wording. + ['pause', 'Stepped over'] + ])("appends the text of the step's own stop only: a '%s' stop that carries one keeps its wording (issue #1130)", async (reason, wording) => { + const session = await createPausedSession(sessionManager, dependencies); + dependencies.mockProxyManager.sendDapRequest = vi.fn().mockImplementation(async (sent: string) => { + if (sent === 'next') { + process.nextTick(() => { + dependencies.mockProxyManager.simulateStopped(1, reason, { reason, threadId: 1, text: STEP_NOTE }); + }); + } + return { success: true }; + }); + + const stepPromise = sessionManager.stepOver(session.id); + await vi.runAllTimersAsync(); + const result = await stepPromise; + + const data = result.data as { message?: string; stopReason?: string }; + expect(data.stopReason).toBe(reason); + expect(data.message).toBe(wording); + expect(data.message).not.toContain(STEP_NOTE); + }); + it('should treat termination during step as a successful completion', async () => { const session = await createPausedSession(sessionManager, dependencies); diff --git a/tests/proxy/child-connections.test.ts b/tests/proxy/child-connections.test.ts index 31dd19448..8989a287b 100644 --- a/tests/proxy/child-connections.test.ts +++ b/tests/proxy/child-connections.test.ts @@ -5,8 +5,10 @@ * the child itself); a report nobody answers is released by a safety timer. */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { EventEmitter } from 'events'; import type { DebugProtocol } from '@vscode/debugprotocol'; import { ChildConnections, type ChildAdoptionDeps } from '../../src/proxy/child-connections.js'; +import type { CdpProxyClient } from '../../src/proxy/cdp-proxy-client.js'; import type { IDapClientFactory, StatusMessage } from '../../src/proxy/dap-proxy-interfaces.js'; import { createMockDapClient } from '../test-utils/mocks/dap-client.js'; import { JsDebugAdapterPolicy, PythonAdapterPolicy, type AdapterPolicy } from '@debugmcp/shared'; @@ -824,3 +826,267 @@ describe('ChildConnections under the throwaway-attach lever (js-debug, issue #10 expect(connections.liveCount()).toBe(0); }); }); + +/** + * The proxy's own stepper for an adopted child (issue #1130): js-debug's is + * kept off, so a child of that adapter gets a JsStepper over its own CDP + * socket. The stepper here is the real one; the socket is the fake below, + * handed in through `cdpClientFactory`, and the test plays V8 and js-debug. + */ +describe("ChildConnections: an adopted child's proxy stepper (issue #1130)", () => { + /** The child's CDP socket (js-debug's `requestCDPProxy`): every command is answered, the test sends V8's events. */ + class FakeCdpClient extends EventEmitter { + readonly sent: string[] = []; + connectedTo: { host: string; port: number; path: string } | null = null; + disposed = false; + + async connect(host: string, port: number, path: string): Promise { + this.connectedTo = { host, port, path }; + } + + async send(method: string): Promise { + this.sent.push(method); + return {}; + } + + isConnected(): boolean { + return this.connectedTo !== null && !this.disposed; + } + + dispose(): void { + this.disposed = true; + } + + /** V8 pauses in `f`, as CDP reports it. */ + paused(reason: string, line: number): void { + this.emit('cdp-event', 'Debugger.paused', { + reason, + callFrames: [{ functionName: 'f', location: { scriptId: '1', lineNumber: line, columnNumber: 0 } }] + }); + } + + resumed(): void { + this.emit('cdp-event', 'Debugger.resumed', {}); + } + } + + interface StepperSetup { + policy?: AdapterPolicy; + launchConfig?: Record; + /** What the root's own start request said. Left out: nothing is wired to ask the root. */ + rootSteps?: () => boolean | undefined; + } + + const sent: Array> = []; + const logger = { info: vi.fn(), error: vi.fn(), debug: vi.fn(), warn: vi.fn() }; + const cdpAddress = { host: '127.0.0.1', port: 9333, path: '/cdp-of-the-child' }; + const jsConfiguration = { type: 'pwa-node', name: 'child.js [4242]', __pendingTargetId: 'a1b2c3d4e5f60718293a4b5c' }; + const jsReport = { targetId: 'a1b2c3d4e5f60718293a4b5c', name: 'child.js [4242]', configuration: jsConfiguration }; + const STEP = { threadId: 1 }; + let root: ReturnType; + let childClient: ReturnType; + let cdpClients: FakeCdpClient[]; + let connections: ChildConnections; + + /** The child's events the parent process was sent, in order. */ + const childEvents = () => + sent.filter((m) => m.type === 'dapEvent' && m.sessionId === 'child-1').map((m) => ({ event: m.event, body: m.body })); + + function build(setup: StepperSetup = {}): void { + sent.length = 0; + cdpClients = []; + root = createMockDapClient(); + childClient = createMockDapClient(); + childClient.sendRequest.mockImplementation(async (command: string) => { + if (command === 'requestCDPProxy') { + return { body: cdpAddress }; + } + if (command === 'stackTrace') { + // js-debug's frame for the pause, unmarked: program code. + return { success: true, body: { stackFrames: [{ id: 1, name: 'f', line: 3, column: 1 }] } }; + } + return { body: {} }; + }); + let resolveAttach: () => void = () => undefined; + const connectionManager = { + initializeSession: vi.fn(async () => ({ supportsConfigurationDoneRequest: true })), + sendAttachRequest: vi.fn(() => new Promise((resolve) => { resolveAttach = resolve; })), + setExceptionBreakpoints: vi.fn(async () => ({ body: {} })), + setBreakpoints: vi.fn(async () => ({ body: { breakpoints: [] } })), + sendConfigurationDone: vi.fn(async () => { resolveAttach(); }), + disconnect: vi.fn(async () => {}) + }; + connections = new ChildConnections({ + messageSender: { send: (message: unknown) => { sent.push(message as Record); } }, + logger, + cdpClientFactory: () => { + const cdp = new FakeCdpClient(); + cdpClients.push(cdp); + return cdp as unknown as CdpProxyClient; + }, + adoption: { + dapClientFactory: { create: vi.fn(() => childClient) } as unknown as IDapClientFactory, + connectionManager: connectionManager as unknown as ChildAdoptionDeps['connectionManager'], + policy: setup.policy ?? JsDebugAdapterPolicy, + host: '127.0.0.1', + port: 9229, + adapterId: 'pwa-node', + breakOnExceptions: 'none', + ...(setup.launchConfig ? { launchConfig: setup.launchConfig as never } : {}), + ...(setup.rootSteps ? { stepsThroughSkippedCode: setup.rootSteps } : {}) + } + }); + connections.attach(root, 'js-root'); + } + + /** Report a child on the root and adopt it as `child-1`. */ + async function adoptChild(reported: { request: DebugProtocol.Request; report: typeof jsReport | typeof report } = { + request: { seq: 7, type: 'request', command: 'startDebugging', arguments: { request: 'launch', configuration: jsConfiguration } }, + report: jsReport + }): Promise { + root.emit('child-report', reported); + const reportId = sent.filter((m) => m.status === 'child_reported').at(-1)!.reportId as string; + const adopting = connections.adopt('child-1', { reportId, breakpoints: [] }); + await new Promise((resolve) => setImmediate(resolve)); + childClient.emit('initialized'); + await adopting; + } + + /** The stepper is opened after the adoption answers: wait until it is listening on the child's socket. */ + async function stepperOnItsSocket(): Promise { + await vi.waitFor(() => expect(cdpClients[0]?.sent).toContain('Debugger.enable')); + return cdpClients[0]; + } + + /** An adopted child whose stepper is on its socket and has seen V8 pause in program code. */ + async function pausedChild(setup: StepperSetup = { rootSteps: () => true }): Promise { + build(setup); + await adoptChild(); + const cdp = await stepperOnItsSocket(); + cdp.paused('other', 1); + return cdp; + } + + it("opens the stepper on the child's own CDP socket, and it serves the child's steps", async () => { + build({ rootSteps: () => true }); + await adoptChild(); + const cdp = await stepperOnItsSocket(); + + // The socket is the one js-debug hands out for this target, subscribed to V8's pauses. + expect(childClient.sendRequest).toHaveBeenCalledWith('requestCDPProxy', {}, 5000); + expect(cdpClients).toHaveLength(1); + expect(cdp.connectedTo).toEqual(cdpAddress); + expect(cdp.sent).toEqual(['JsDebug.subscribe', 'Debugger.enable']); + // Running, there is nothing to step from: the request is the adapter's. + expect(connections.stepRequest('child-1', 'next', STEP)).toBeNull(); + + cdp.paused('other', 1); + const stepped = connections.stepRequest('child-1', 'next', STEP); + + expect(stepped).not.toBeNull(); + await expect(stepped).resolves.toMatchObject({ type: 'response', command: 'next', success: true }); + // One engine step over the CDP socket; js-debug is never sent the `next`. + expect(cdp.sent).toContain('Debugger.stepOver'); + expect(childClient.sendRequest).not.toHaveBeenCalledWith('next', expect.anything(), expect.anything()); + // Not a step, or not a session of this worker: the adapter's as it is. + expect(connections.stepRequest('child-1', 'evaluate', { expression: 'x' })).toBeNull(); + expect(connections.stepRequest('nobody', 'next', STEP)).toBeNull(); + }); + + it('opens no stepper for a child of an adapter that does its own stepping', async () => { + build({ policy: PythonAdapterPolicy, rootSteps: () => true }); + await adoptChild({ request: startDebugging(7), report }); + + expect(connections.has('child-1')).toBe(true); + expect(childClient.sendRequest).not.toHaveBeenCalledWith('requestCDPProxy', expect.anything(), expect.anything()); + expect(cdpClients).toHaveLength(0); + expect(connections.stepRequest('child-1', 'next', STEP)).toBeNull(); + }); + + // The child's stepper takes the root's choice over: the root's own start + // request (a launch's or an attach's `smartStep`), and the launch + // configuration only when the root cannot say. + it.each<[string, StepperSetup, boolean]>([ + ['the root steps through skipped code and the configuration has no smartStep (an attach root)', { rootSteps: () => true, launchConfig: { request: 'attach', port: 9229 } }, true], + ['the root does not, though the configuration asked for smartStep', { rootSteps: () => false, launchConfig: { smartStep: true } }, false], + ['the root cannot say and the configuration asked for smartStep', { rootSteps: () => undefined, launchConfig: { smartStep: true } }, true], + ['the root cannot say and the configuration did not ask', { rootSteps: () => undefined, launchConfig: { smartStep: false } }, false], + ['nothing is wired to ask the root and the configuration asked for smartStep', { launchConfig: { smartStep: true } }, true], + ['nothing is wired to ask the root and there is no configuration', {}, false] + ])("takes the session's choice from the root: %s", async (_case, setup, serves) => { + await pausedChild(setup); + + const stepped = connections.stepRequest('child-1', 'next', STEP); + + expect(stepped !== null).toBe(serves); + await stepped; + }); + + it("withholds the child's stopped and continued events while a step is in flight, and reports one stopped for the step", async () => { + const cdp = await pausedChild(); + await connections.stepRequest('child-1', 'next', STEP); + + // V8 resumes and lands on the next line; js-debug reports both, the + // landing as a pause it did not ask for. + cdp.resumed(); + childClient.emit('continued', { threadId: 1, allThreadsContinued: false }); + cdp.paused('step', 2); + childClient.emit('stopped', { reason: 'pause', description: 'Paused on debugger statement', threadId: 1 }); + await vi.waitFor(() => expect(childEvents()).not.toHaveLength(0)); + + // One `stopped`, the stepper's, under the child's session; nothing of js-debug's. + expect(childEvents()).toEqual([ + { event: 'stopped', body: expect.objectContaining({ reason: 'step', threadId: 1 }) } + ]); + + // With no step in flight the child's events are forwarded as they are. + sent.length = 0; + childClient.emit('continued', { threadId: 1, allThreadsContinued: true }); + childClient.emit('stopped', { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [4] }); + expect(childEvents()).toEqual([ + { event: 'continued', body: { threadId: 1, allThreadsContinued: true } }, + { event: 'stopped', body: { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [4] } } + ]); + }); + + it('a request that resumes the child ends a step in flight; any other request leaves it', async () => { + await pausedChild(); + await connections.stepRequest('child-1', 'next', STEP); + + await connections.beforeRequest('child-1', 'threads'); + childClient.emit('stopped', { reason: 'pause', threadId: 1 }); + // Still the step's: withheld. + expect(childEvents()).toEqual([]); + + await connections.beforeRequest('child-1', 'continue'); + childClient.emit('stopped', { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [4] }); + // The step was given up: the stop is the program's own. + expect(childEvents()).toEqual([ + { event: 'stopped', body: { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [4] } } + ]); + // A session this worker does not know has nothing to end. + await expect(connections.beforeRequest('nobody', 'continue')).resolves.toBeUndefined(); + }); + + it("close() takes the stepper off the child's CDP socket and closes the socket", async () => { + const cdp = await pausedChild(); + expect(cdp.listenerCount('cdp-event')).toBe(1); + + await connections.close('child-1', { terminateDebuggee: true }); + + // By close() itself: this client never reports its connection closed. + expect(cdp.listenerCount('cdp-event')).toBe(0); + expect(cdp.disposed).toBe(true); + }); + + it("a child connection that closes by itself takes its stepper and CDP socket down with it", async () => { + const cdp = await pausedChild(); + expect(cdp.listenerCount('cdp-event')).toBe(1); + + childClient.emit('close'); + + expect(cdp.listenerCount('cdp-event')).toBe(0); + expect(cdp.disposed).toBe(true); + expect(connections.has('child-1')).toBe(false); + }); +}); diff --git a/tests/proxy/child-session-manager.test.ts b/tests/proxy/child-session-manager.test.ts index f92c79238..ed81df4df 100644 --- a/tests/proxy/child-session-manager.test.ts +++ b/tests/proxy/child-session-manager.test.ts @@ -9,6 +9,7 @@ import type { AdapterPolicy, ParentStart, ReverseRequestResult } from '@debugmcp import { JsDebugAdapterPolicy, PythonAdapterPolicy, DefaultAdapterPolicy } from '@debugmcp/shared'; import { ChildSessionManager } from '../../src/proxy/child-session-manager.js'; import type { CdpFunctionBreakpointBridge } from '../../src/proxy/cdp-function-breakpoint-bridge.js'; +import type { CdpProxyClient } from '../../src/proxy/cdp-proxy-client.js'; // Mock MinimalDapClient class MockMinimalDapClient extends EventEmitter { // Knobs for death-aware adoption tests (issue #248); reset in beforeEach @@ -48,6 +49,13 @@ class MockMinimalDapClient extends EventEmitter { // compiles the breakpoints it buffered on a pending-target connection while // answering attach, and reports their syntax errors then (issue #853) static stderrOnAttach: string[] = []; + // When set, returned verbatim for 'requestCDPProxy': the address js-debug + // hands out for the target's raw CDP socket. Unset, the answer is `{}` and + // the CDP bridge finds no socket to open. + static cdpProxyResponse: unknown | undefined = undefined; + // When set, returned verbatim for 'stackTrace' (js-debug's frames, with its + // marks, for the pause the target is in; the proxy stepper asks, issue #1130) + static stackTraceResponse: unknown | undefined = undefined; host: string; port: number; @@ -114,6 +122,12 @@ class MockMinimalDapClient extends EventEmitter { } return { body: { threads: [{ id: 1, name: 'main' }] } }; } + if (command === 'requestCDPProxy' && MockMinimalDapClient.cdpProxyResponse !== undefined) { + return MockMinimalDapClient.cdpProxyResponse; + } + if (command === 'stackTrace' && MockMinimalDapClient.stackTraceResponse !== undefined) { + return MockMinimalDapClient.stackTraceResponse; + } if (command === 'setBreakpoints') { for (const output of MockMinimalDapClient.stderrOnSetBreakpoints) { this.emit('output', { category: 'stderr', output }); @@ -199,6 +213,8 @@ describe('ChildSessionManager', () => { MockMinimalDapClient.shutdownThrows = false; MockMinimalDapClient.stderrOnSetBreakpoints = []; MockMinimalDapClient.stderrOnAttach = []; + MockMinimalDapClient.cdpProxyResponse = undefined; + MockMinimalDapClient.stackTraceResponse = undefined; }); describe('JavaScript policy (multi-session)', () => { @@ -1601,6 +1617,279 @@ describe('ChildSessionManager', () => { }); }); + /** + * The proxy's own stepper for the program's target (issue #1130): js-debug's + * is kept off, and a session that asked for `smartStep` has its steps served + * over the target's CDP socket, the one the function-breakpoint bridge + * opens. The stepper and the bridge are the real ones here; the socket is + * the fake below, handed in through `cdpClientFactory`, and the test plays + * V8 (the socket's events) and js-debug (the child's DAP events). + */ + describe('the proxy stepper of the program target (issue #1130)', () => { + class FakeCdpClient extends EventEmitter { + readonly sent: string[] = []; + /** Results by method; any other command is answered `{}`. */ + answers: Record = {}; + private open = false; + + async connect(): Promise { + this.open = true; + } + + async send(method: string): Promise { + this.sent.push(method); + return this.answers[method] ?? {}; + } + + isConnected(): boolean { + return this.open; + } + + dispose(): void { + this.open = false; + } + + /** V8 pauses, as CDP reports it: in `fn` (default `f`), which `f` called when it is another. */ + paused(pause: { reason: string; line: number; fn?: string; hitBreakpoints?: string[] }): void { + const frame = (functionName: string, lineNumber: number) => + ({ functionName, location: { scriptId: '1', lineNumber, columnNumber: 0 } }); + this.emit('cdp-event', 'Debugger.paused', { + reason: pause.reason, + ...(pause.hitBreakpoints ? { hitBreakpoints: pause.hitBreakpoints } : {}), + callFrames: pause.fn ? [frame(pause.fn, pause.line), frame('f', 1)] : [frame('f', pause.line)] + }); + } + + resumed(): void { + this.emit('cdp-event', 'Debugger.resumed', {}); + } + } + + const STEP = { threadId: 1 }; + const dapEvent = (event: string, body: Record): DebugProtocol.Event => ({ seq: 0, type: 'event', event, body }); + /** js-debug's sessions and CDP bridge, with an adapter that does its own stepping. */ + const ownStepperPolicy: AdapterPolicy = { + ...JsDebugAdapterPolicy, + getDapClientBehavior: () => ({ ...JsDebugAdapterPolicy.getDapClientBehavior(), stepsThroughSkippedCode: undefined }) + }; + let cdpClients: FakeCdpClient[]; + + function makeManager(policy: AdapterPolicy = JsDebugAdapterPolicy): ChildSessionManager { + return new ChildSessionManager({ + policy, + host: 'localhost', + port: 9229, + cdpClientFactory: () => { + const cdp = new FakeCdpClient(); + cdpClients.push(cdp); + return cdp as unknown as CdpProxyClient; + } + }); + } + + /** Adopt the program's target: its CDP socket is open when this returns. */ + async function adoptTarget(mgr: ChildSessionManager): Promise<{ child: MockMinimalDapClient; cdp: FakeCdpClient }> { + vi.useFakeTimers(); + try { + const adoption = mgr.createChildSession({ + pendingId: 'stepper-target', + host: 'localhost', + port: 9229, + parentConfig: { type: 'pwa-node' } + }); + await vi.advanceTimersByTimeAsync(20000); + await adoption; + } finally { + vi.useRealTimers(); + } + return { child: MockMinimalDapClient.lastInstance!, cdp: cdpClients[cdpClients.length - 1] }; + } + + /** + * A session that chose to step through skipped code, its target adopted + * and paused in program code. `forwarded` is what the parent connection is + * handed from here on. + */ + async function steppingTarget(): Promise<{ + mgr: ChildSessionManager; + child: MockMinimalDapClient; + cdp: FakeCdpClient; + forwarded: DebugProtocol.Event[]; + }> { + const mgr = makeManager(); + // The start request comes before the target exists. + mgr.setStepThroughSkippedCode(true); + const { child, cdp } = await adoptTarget(mgr); + const forwarded: DebugProtocol.Event[] = []; + mgr.on('childEvent', (evt: DebugProtocol.Event) => forwarded.push(evt)); + cdp.paused({ reason: 'other', line: 1 }); + return { mgr, child, cdp, forwarded }; + } + + beforeEach(() => { + cdpClients = []; + MockMinimalDapClient.cdpProxyResponse = { body: { host: '127.0.0.1', port: 9333, path: '/cdp-of-the-target' } }; + // js-debug's frame for a pause, unmarked: program code. + MockMinimalDapClient.stackTraceResponse = { success: true, body: { stackFrames: [{ id: 1, name: 'f', line: 3, column: 1 }] } }; + }); + + it("serves the target's steps over the CDP socket the bridge opens, once the session chose to step through skipped code", async () => { + const mgr = makeManager(); + // A stepper from the start, not asked for yet. + expect(mgr.isSteppingThroughSkippedCode()).toBe(false); + mgr.setStepThroughSkippedCode(true); + expect(mgr.isSteppingThroughSkippedCode()).toBe(true); + + const { child, cdp } = await adoptTarget(mgr); + // One CDP socket per target: the bridge's, and the stepper listens on it too. + expect(cdpClients).toHaveLength(1); + expect(cdp.listenerCount('cdp-event')).toBe(2); + // Running, there is nothing to step from: the request is the adapter's. + expect(mgr.stepRequest('next', STEP)).toBeNull(); + + cdp.paused({ reason: 'other', line: 1 }); + const stepped = mgr.stepRequest('next', STEP); + + expect(stepped).not.toBeNull(); + await expect(stepped).resolves.toMatchObject({ type: 'response', command: 'next', success: true }); + // One engine step over the CDP socket; js-debug is never sent the `next`. + expect(cdp.sent).toContain('Debugger.stepOver'); + expect(child.requests.map((r) => r.command)).not.toContain('next'); + // Not a step: the adapter's as it is. + expect(mgr.stepRequest('evaluate', { expression: 'x' })).toBeNull(); + }); + + it("leaves the steps to js-debug until the session asks, and again when it stops asking", async () => { + const mgr = makeManager(); + const { cdp } = await adoptTarget(mgr); + cdp.paused({ reason: 'other', line: 1 }); + + // Never asked: plain steps. + expect(mgr.stepRequest('next', STEP)).toBeNull(); + expect(cdp.sent).not.toContain('Debugger.stepOver'); + + mgr.setStepThroughSkippedCode(true); + await mgr.stepRequest('next', STEP); + expect(cdp.sent).toContain('Debugger.stepOver'); + + mgr.setStepThroughSkippedCode(false); + expect(mgr.isSteppingThroughSkippedCode()).toBe(false); + expect(mgr.stepRequest('next', STEP)).toBeNull(); + }); + + it('builds no stepper for a policy whose adapter does its own stepping', async () => { + // No child sessions of this kind at all (Python): nothing to ask, nothing to serve. + const python = makeManager(PythonAdapterPolicy); + python.setStepThroughSkippedCode(true); + expect(python.isSteppingThroughSkippedCode()).toBeUndefined(); + expect(python.stepRequest('next', STEP)).toBeNull(); + await expect(python.beforeChildRequest('continue')).resolves.toBeUndefined(); + + // js-debug's sessions and bridge without the pin: the socket is the bridge's alone. + const ownStepper = makeManager(ownStepperPolicy); + ownStepper.setStepThroughSkippedCode(true); + const { cdp } = await adoptTarget(ownStepper); + cdp.paused({ reason: 'other', line: 1 }); + expect(cdp.listenerCount('cdp-event')).toBe(1); + expect(ownStepper.isSteppingThroughSkippedCode()).toBeUndefined(); + expect(ownStepper.stepRequest('next', STEP)).toBeNull(); + }); + + it("withholds the target's stopped and continued events while a step is in flight, and reports one stopped for the step", async () => { + const { mgr, child, cdp, forwarded } = await steppingTarget(); + await mgr.stepRequest('next', STEP); + + // V8 resumes and lands on the next line; js-debug reports both, the + // landing as a pause it did not ask for. + cdp.resumed(); + child.emit('event', dapEvent('continued', { threadId: 1, allThreadsContinued: false })); + cdp.paused({ reason: 'step', line: 2 }); + child.emit('event', dapEvent('stopped', { reason: 'pause', description: 'Paused on debugger statement', threadId: 1 })); + await vi.waitFor(() => expect(forwarded).not.toHaveLength(0)); + await mgr.flushEvents(); + + // One `stopped`, the stepper's; nothing of js-debug's. + expect(forwarded).toEqual([ + expect.objectContaining({ event: 'stopped', body: expect.objectContaining({ reason: 'step', threadId: 1 }) }) + ]); + + // With no step in flight the target's events are forwarded as they are. + forwarded.length = 0; + const resumed = dapEvent('continued', { threadId: 1, allThreadsContinued: true }); + const breakpointStop = dapEvent('stopped', { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [4] }); + child.emit('event', resumed); + child.emit('event', breakpointStop); + await mgr.flushEvents(); + expect(forwarded).toEqual([resumed, breakpointStop]); + }); + + it('a request that resumes the target ends a step in flight; any other request leaves it', async () => { + const { mgr, child, forwarded } = await steppingTarget(); + await mgr.stepRequest('next', STEP); + + await mgr.beforeChildRequest('threads'); + child.emit('event', dapEvent('stopped', { reason: 'pause', threadId: 1 })); + await mgr.flushEvents(); + // Still the step's: withheld. + expect(forwarded).toEqual([]); + + await mgr.beforeChildRequest('continue'); + const breakpointStop = dapEvent('stopped', { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [4] }); + child.emit('event', breakpointStop); + await mgr.flushEvents(); + // The step was given up: the stop is the program's own. + expect(forwarded).toEqual([breakpointStop]); + }); + + it("hands the stepper's own report to the function-breakpoint bridge like any stop of the target", async () => { + const { mgr, child, cdp, forwarded } = await steppingTarget(); + cdp.answers = { + 'Runtime.evaluate': { result: { type: 'function', objectId: 'greet-object' } }, + 'Debugger.setBreakpointOnFunctionCall': { breakpointId: 'fn-call:1' } + }; + const { breakpoints: [armed] } = await mgr.syncFunctionBreakpoints([{ name: 'greet' }]); + expect(armed).toMatchObject({ verified: true }); + await mgr.stepRequest('next', STEP); + + // The step runs into the armed function: V8 pauses on the bridge's + // breakpoint, which js-debug reports as a breakpoint that names none. + // The step ends there, and the stop the stepper hands on is that one. + cdp.resumed(); + cdp.paused({ reason: 'other', line: 10, fn: 'greet', hitBreakpoints: ['fn-call:1'] }); + child.emit('event', dapEvent('stopped', { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [] })); + await vi.waitFor(() => expect(forwarded).not.toHaveLength(0)); + await mgr.flushEvents(); + + // Through the bridge: named as the function breakpoint it is. + expect(forwarded).toHaveLength(1); + expect(forwarded[0]).toMatchObject({ + event: 'stopped', + body: { reason: 'function breakpoint', threadId: 1, hitBreakpointIds: [armed.id] } + }); + }); + + it("takes the stepper off the target's CDP socket when the target's connection closes", async () => { + const { mgr, child, cdp } = await steppingTarget(); + expect(cdp.listenerCount('cdp-event')).toBe(2); + + child.emit('close'); + + // The bridge's listener and the stepper's are both gone. + expect(cdp.listenerCount('cdp-event')).toBe(0); + expect(mgr.stepRequest('next', STEP)).toBeNull(); + }); + + it("takes the stepper off the target's CDP socket on shutdown", async () => { + const { mgr, cdp } = await steppingTarget(); + expect(cdp.listenerCount('cdp-event')).toBe(2); + + await mgr.shutdown(); + + expect(cdp.listenerCount('cdp-event')).toBe(0); + expect(mgr.stepRequest('next', STEP)).toBeNull(); + }); + }); + describe('adoption edges and the child-safe policy (coverage sprint)', () => { const childConfig = { pendingId: 'edge-pending-1', diff --git a/tests/proxy/dap-proxy-worker-child-sessions.test.ts b/tests/proxy/dap-proxy-worker-child-sessions.test.ts index 50275a6c1..ae9dcaf3e 100644 --- a/tests/proxy/dap-proxy-worker-child-sessions.test.ts +++ b/tests/proxy/dap-proxy-worker-child-sessions.test.ts @@ -66,16 +66,19 @@ describe('DapProxyWorker child sessions (issue #1081)', () => { adapterCommand: { command: 'python', args: ['-m', 'debugpy.adapter'] } }; - async function connectUnder(policy: typeof PythonAdapterPolicy | typeof JsDebugAdapterPolicy): Promise { + async function connectUnder( + policy: typeof PythonAdapterPolicy | typeof JsDebugAdapterPolicy, + init: ProxyInitPayload = payload + ): Promise { (worker as any).logger = mockLogger; (worker as any).processManager = processStub; (worker as any).connectionManager = connectionStub; (worker as any).adapterPolicy = policy; (worker as any).adapterState = policy.createInitialState(); - (worker as any).currentInitPayload = payload; - (worker as any).currentSessionId = payload.sessionId; + (worker as any).currentInitPayload = init; + (worker as any).currentSessionId = init.sessionId; (worker as any).state = ProxyState.INITIALIZING; - await (worker as any).startAdapterAndConnect(payload); + await (worker as any).startAdapterAndConnect(init); } const statuses = (status: string): StatusMessage[] => @@ -412,4 +415,147 @@ describe('DapProxyWorker child sessions (issue #1081)', () => { expect(processStub.shutdown).toHaveBeenCalledTimes(1); expect(responseTo('failed-adopt')).toMatchObject({ success: false, sessionId: 'child-1', error: 'child exited during attach' }); }); + + /** + * The proxy's own stepper for a js-debug child (issue #1130), through the + * worker's real ChildConnections and the real stepper. The worker has no + * seam for the child's CDP socket (ChildConnections opens a CdpProxyClient, + * which opens the Node global WebSocket), so the global is the fake here: + * it answers every command, and the test sends V8's events. + */ + describe("a js-debug child's steps and its proxy stepper (issue #1130)", () => { + class FakeCdpSocket { + static opened: FakeCdpSocket[] = []; + onopen: (() => void) | null = null; + onmessage: ((event: { data: unknown }) => void) | null = null; + onclose: (() => void) | null = null; + onerror: ((event: { message?: string }) => void) | null = null; + readonly sent: string[] = []; + + constructor(readonly url: string) { + FakeCdpSocket.opened.push(this); + queueMicrotask(() => this.onopen?.()); + } + + send(data: string): void { + const { id, method } = JSON.parse(data) as { id: number; method: string }; + this.sent.push(method); + queueMicrotask(() => this.onmessage?.({ data: JSON.stringify({ id, result: {} }) })); + } + + close(): void { + this.onclose?.(); + } + + /** V8 pauses in `f`, as CDP reports it. */ + paused(): void { + this.onmessage?.({ + data: JSON.stringify({ + method: 'Debugger.paused', + params: { reason: 'other', callFrames: [{ functionName: 'f', location: { scriptId: '1', lineNumber: 1, columnNumber: 0 } }] } + }) + }); + } + } + + const forkConfiguration = { type: 'pwa-node', name: 'child.js [7]', __pendingTargetId: 'fork-1' }; + + /** The child's `stopped` events the parent process was sent. */ + const childStops = (): unknown[] => + send.mock.calls + .map(([m]) => m) + .filter((m): m is DapEventMessage => m.type === 'dapEvent' && m.sessionId === 'child-1' && m.event === 'stopped') + .map((m) => m.body); + + beforeEach(() => { + FakeCdpSocket.opened = []; + vi.stubGlobal('WebSocket', FakeCdpSocket); + childClient.sendRequest.mockImplementation(async (command: string) => + command === 'requestCDPProxy' + ? { body: { host: '127.0.0.1', port: 9333, path: '/cdp-of-the-fork' } } + : { type: 'response', success: true, command, body: {} }); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + }); + + /** + * A js-debug root, a fork adopted as `child-1`, its stepper on the fork's + * CDP socket, and V8 paused in the fork's program code. + */ + async function pausedFork(start: { rootSteps?: boolean; smartStep?: boolean }): Promise { + if (start.rootSteps !== undefined) { + // What MinimalDapClient answers from the root's own start request. + rootClient.stepsThroughSkippedCode = () => start.rootSteps; + } + await connectUnder( + JsDebugAdapterPolicy, + start.smartStep === undefined ? payload : { ...payload, launchConfig: { smartStep: start.smartStep } } + ); + rootClient.emit('child-report', { + request: { seq: 9, type: 'request', command: 'startDebugging', arguments: { request: 'launch', configuration: forkConfiguration } }, + report: { targetId: 'fork-1', name: 'child.js [7]', configuration: forkConfiguration } + }); + const reportId = statuses('child_reported')[0].reportId as string; + const adopting = worker.handleCommand({ cmd: 'dap', sessionId: 'child-1', requestId: 'adopt-fork', dapCommand: CHILD_ADOPT_COMMAND, dapArgs: { reportId } }); + await new Promise((resolve) => setImmediate(resolve)); + childClient.emit('initialized'); + await adopting; + // The stepper is opened after the adoption answers. + await vi.waitFor(() => expect(FakeCdpSocket.opened[0]?.sent).toContain('Debugger.enable')); + const socket = FakeCdpSocket.opened[0]; + socket.paused(); + return socket; + } + + const stepTheFork = (requestId: string): Promise => + worker.handleCommand({ cmd: 'dap', sessionId: 'child-1', requestId, dapCommand: 'next', dapArgs: { threadId: 1 } }); + + // The child's stepper takes over the choice of the root's own start + // request, which the root's client answers; the init payload's launch + // configuration only when that client cannot say. + it.each<[string, { rootSteps?: boolean; smartStep?: boolean }]>([ + ['the root steps through skipped code (an attach root: no smartStep in the payload)', { rootSteps: true }], + ["the root's client cannot say and the payload's launch configuration asked for smartStep", { smartStep: true }] + ])("the child's stepper serves its step over the child's CDP socket when %s", async (_case, start) => { + const socket = await pausedFork(start); + expect(socket.url).toBe('ws://127.0.0.1:9333/cdp-of-the-fork'); + + await stepTheFork('step-1'); + + // One engine step over CDP, answered on the child's envelope; js-debug is never sent the `next`. + expect(socket.sent).toContain('Debugger.stepOver'); + expect(childClient.sendRequest).not.toHaveBeenCalledWith('next', expect.anything(), expect.anything()); + expect(responseTo('step-1')).toMatchObject({ success: true, sessionId: 'child-1', response: { command: 'next', success: true } }); + }); + + it("the child's step is js-debug's own when the root does not step through skipped code, whatever the payload asked", async () => { + const socket = await pausedFork({ rootSteps: false, smartStep: true }); + + await stepTheFork('step-2'); + + expect(childClient.sendRequest).toHaveBeenCalledWith('next', { threadId: 1 }, undefined); + expect(socket.sent).not.toContain('Debugger.stepOver'); + expect(responseTo('step-2')).toMatchObject({ success: true, sessionId: 'child-1' }); + }); + + it("any other request for the child passes its stepper first: a continue ends a step in flight, an evaluate does not", async () => { + await pausedFork({ rootSteps: true }); + await stepTheFork('step-3'); + + await worker.handleCommand({ cmd: 'dap', sessionId: 'child-1', requestId: 'eval-3', dapCommand: 'evaluate', dapArgs: { expression: 'x' } }); + childClient.emit('stopped', { reason: 'pause', threadId: 1 }); + // Still the step's own pause: withheld. + expect(childClient.sendRequest).toHaveBeenCalledWith('evaluate', { expression: 'x' }, undefined); + expect(childStops()).toEqual([]); + + await worker.handleCommand({ cmd: 'dap', sessionId: 'child-1', requestId: 'continue-3', dapCommand: 'continue', dapArgs: { threadId: 1 } }); + childClient.emit('stopped', { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [4] }); + // The step was given up before the continue went out: this stop is the program's own. + expect(childClient.sendRequest).toHaveBeenCalledWith('continue', { threadId: 1 }, undefined); + expect(childStops()).toEqual([{ reason: 'breakpoint', threadId: 1, hitBreakpointIds: [4] }]); + expect(responseTo('continue-3')).toMatchObject({ success: true, sessionId: 'child-1' }); + }); + }); }); diff --git a/tests/unit/proxy/minimal-dap.test.ts b/tests/unit/proxy/minimal-dap.test.ts index 48cb0c800..dd1e51bae 100644 --- a/tests/unit/proxy/minimal-dap.test.ts +++ b/tests/unit/proxy/minimal-dap.test.ts @@ -3,13 +3,14 @@ import net from 'net'; import fs from 'fs'; import { EventEmitter } from 'events'; import { MinimalDapClient } from '../../../src/proxy/minimal-dap.js'; -import type { +import { ChildSessionManager, - ChildSessionOptions + type ChildSessionOptions } from '../../../src/proxy/child-session-manager.js'; +import type { CdpProxyClient } from '../../../src/proxy/cdp-proxy-client.js'; import { DebugProtocol } from '@vscode/debugprotocol'; import { JsDebugAdapterPolicy } from '@debugmcp/shared'; -import type { ChildSessionConfig, DapClientBehavior, ReverseRequestResult } from '@debugmcp/shared'; +import type { AdapterPolicy, ChildSessionConfig, DapClientBehavior, ReverseRequestResult } from '@debugmcp/shared'; import { createMockDapClient } from '../../test-utils/mocks/dap-client.js'; // Mock the net module @@ -2491,9 +2492,11 @@ describe('MinimalDapClient', () => { port: 9229, customAdapterOption: 'preserved' }); await client.sendRequest('attach', args); + // The snapshot is what the child session sends again, so it carries the + // one key the proxy owns as the adapter was sent it (issue #1130). expect(options.getParentStart!()).toEqual({ request: 'attach', stopOnEntry: false, - attachArguments: { localRoot: '/app', sourceMaps: false, port: 9229, customAdapterOption: 'preserved' } + attachArguments: { localRoot: '/app', sourceMaps: false, port: 9229, customAdapterOption: 'preserved', smartStep: false } }); const sent = JSON.parse(mockSocket.write.mock.calls.at(-1)[0].toString().split('\r\n\r\n')[1]); // Everything the caller sent, plus the one key the proxy owns: the @@ -2501,6 +2504,27 @@ describe('MinimalDapClient', () => { expect(sent.arguments).toEqual({ ...args, smartStep: false }); }); + it.each([ + ['asked for smartStep', { smartStep: true }], + ['refused smartStep', { smartStep: false }], + ['said nothing of smartStep', {}] + ])("keeps the adapter's stepper off in what an attach's child session sends again, when the caller %s (issue #1130)", async (_case, asked) => { + await client.sendRequest('attach', { request: 'attach', port: 9229, localRoot: '/app', ...asked }); + + // The override is applied before the snapshot: the child's attach is + // built from these arguments, and must not turn js-debug's stepper on. + const start = options.getParentStart!(); + expect(start).toEqual({ request: 'attach', attachArguments: { port: 9229, localRoot: '/app', smartStep: false } }); + // What the policy makes of them for the target's own connection. + const childStart = JsDebugAdapterPolicy.buildChildStartArgs( + 'target-1', + { type: 'pwa-node', name: 'target', __pendingTargetId: 'target-1' }, + start?.request === 'attach' ? start.attachArguments : undefined + ); + expect(childStart.command).toBe('attach'); + expect(childStart.args).toMatchObject({ __pendingTargetId: 'target-1', localRoot: '/app', smartStep: false }); + }); + it.each([ ['launch', { request: 'launch', program: '/app/main.js', smartStep: true }, true], ['launch', { request: 'launch', program: '/app/main.js', smartStep: false }, false], @@ -2530,7 +2554,7 @@ describe('MinimalDapClient', () => { const previous = options.getParentStart!(); await client.sendRequest('launch', { stopOnEntry: true }); expect(options.getParentStart!()).toEqual({ request: 'launch', stopOnEntry: true }); - expect(previous).toEqual({ request: 'attach', stopOnEntry: false, attachArguments: { localRoot: '/old' } }); + expect(previous).toEqual({ request: 'attach', stopOnEntry: false, attachArguments: { localRoot: '/old', smartStep: false } }); }); it('re-emits childCreated as child-adopted (issue #704)', () => { @@ -2768,4 +2792,242 @@ describe('MinimalDapClient', () => { }); }); + /** + * js-debug's own stepper is off for every session, and the proxy's serves + * the steps of a session whose start request asked for `smartStep` (issue + * #1130). This client owns three pieces of that: the start request's + * `smartStep` (the session's choice, never the adapter's setting), the + * order a child-routed request passes the stepper in, and the answer a + * forked child's stepper takes the root's choice from. + */ + describe('the proxy stepper (issue #1130)', () => { + /** One adapter connection: it answers every request, and records it. */ + interface AdapterSocket { + requests: DebugProtocol.Request[]; + /** An event, or a reverse request, from the adapter. */ + push(message: Record): void; + } + + /** The target's CDP socket, handed to the real child-session manager: every command is answered. */ + class FakeCdpClient extends EventEmitter { + readonly sent: string[] = []; + private open = false; + + async connect(): Promise { + this.open = true; + } + + async send(method: string): Promise { + this.sent.push(method); + return {}; + } + + isConnected(): boolean { + return this.open; + } + + dispose(): void { + this.open = false; + } + + /** V8 pauses in `f`, as CDP reports it. */ + paused(): void { + this.emit('cdp-event', 'Debugger.paused', { + reason: 'other', + callFrames: [{ functionName: 'f', location: { scriptId: '1', lineNumber: 1, columnNumber: 0 } }] + }); + } + } + + /** A policy with js-debug's child sessions whose adapter does its own stepping. */ + const ownStepperPolicy: AdapterPolicy = { + ...JsDebugAdapterPolicy, + getDapClientBehavior: () => ({ ...JsDebugAdapterPolicy.getDapClientBehavior(), stepsThroughSkippedCode: undefined }) + }; + + /** In connection order: the root's, then the program target's. */ + let adapterSockets: AdapterSocket[]; + /** Response bodies by command; anything else is answered with an empty body. */ + let answers: Record; + + beforeEach(() => { + adapterSockets = []; + answers = {}; + vi.mocked(net.createConnection).mockImplementation((_target: unknown, callback?: () => void) => { + const socket = createMockSocket(); + const requests: DebugProtocol.Request[] = []; + const push = (message: Record): void => { + socket.emit('data', createDapMessage({ seq: 0, ...message })); + }; + socket.write.mockImplementation((frame: Buffer | string, cb?: (err?: Error | null) => void) => { + cb?.(null); + const message = JSON.parse(frame.toString().split('\r\n\r\n')[1]) as DebugProtocol.ProtocolMessage; + if (message.type === 'request') { + const request = message as DebugProtocol.Request; + requests.push(request); + queueMicrotask(() => { + push({ type: 'response', request_seq: request.seq, command: request.command, success: true, body: answers[request.command] ?? {} }); + // js-debug announces `initialized` after initialize, and again after a target's attach. + if (request.command === 'initialize' || request.command === 'attach') { + push({ type: 'event', event: 'initialized' }); + } + }); + } + return true; + }); + adapterSockets.push({ requests, push }); + if (callback) { + setImmediate(callback); + } + return socket; + }); + }); + + it.each<[string, AdapterPolicy | undefined]>([ + ['has child sessions but an adapter that does its own stepping', ownStepperPolicy], + ['has no child sessions', undefined] + ])('leaves the start request as the caller sent it for a policy that %s', async (_case, policy) => { + client = new MinimalDapClient('localhost', 5678, policy); + await client.connect(); + + await client.sendRequest('launch', { request: 'launch', program: '/app/main.js', smartStep: true }); + await client.sendRequest('attach', { request: 'attach', port: 9229, smartStep: true }); + + // smartStep is that adapter's own setting: nothing is forced off, and + // there is no proxy stepper whose choice could be asked for. + expect(adapterSockets[0].requests.map((request) => request.arguments)).toEqual([ + { request: 'launch', program: '/app/main.js', smartStep: true }, + { request: 'attach', port: 9229, smartStep: true } + ]); + expect(client.stepsThroughSkippedCode()).toBeUndefined(); + }); + + it("answers the session's choice as its start request left it, a launch's or an attach's", async () => { + // The real child-session manager and its stepper answer. + client = new MinimalDapClient('localhost', 5678, JsDebugAdapterPolicy); + await client.connect(); + // Before any start request: a stepper, not yet asked for. + expect(client.stepsThroughSkippedCode()).toBe(false); + + await client.sendRequest('launch', { request: 'launch', program: '/app/main.js', smartStep: true }); + expect(client.stepsThroughSkippedCode()).toBe(true); + + await client.sendRequest('attach', { request: 'attach', port: 9229 }); + expect(client.stepsThroughSkippedCode()).toBe(false); + + await client.sendRequest('attach', { request: 'attach', port: 9229, smartStep: true }); + expect(client.stepsThroughSkippedCode()).toBe(true); + // js-debug's own stepper was never turned on. + expect(adapterSockets[0].requests.map((request) => (request.arguments as { smartStep?: unknown }).smartStep)).toEqual([false, false, false]); + }); + + describe('a request routed to the child session', () => { + /** A client whose child session is `childClient`; `parentWrite` is its own (the parent's) socket. */ + const routedTo = (stubManager: ChildSessionManagerStub, childClient: MinimalDapClient): { routed: MinimalDapClient; parentWrite: Mock } => { + const routed = new MinimalDapClient('localhost', 5678, JsDebugAdapterPolicy, { + childSessionManagerFactory: () => stubManager + }); + const parentWrite = vi.fn(); + const internals = routed as unknown as { socket: net.Socket; activeChild: MinimalDapClient | null }; + internals.socket = { destroyed: false, write: parentWrite, end: vi.fn(), destroy: vi.fn() } as unknown as net.Socket; + internals.activeChild = childClient; + return { routed, parentWrite }; + }; + + it('is offered to the proxy stepper first: a step it serves never reaches the child session', async () => { + const stubManager = createChildSessionManagerStub(); + stubManager.shouldRouteToChild.mockReturnValue(true); + const served: DebugProtocol.Response = { type: 'response', seq: 0, request_seq: -1, command: 'next', success: true, body: {} }; + stubManager.stepRequest.mockReturnValue(Promise.resolve(served)); + const childClient = { sendRequest: vi.fn().mockResolvedValue({ success: true }) } as unknown as MinimalDapClient; + const { routed, parentWrite } = routedTo(stubManager, childClient); + + const result = await routed.sendRequest('next', { threadId: 1 }); + + expect(stubManager.stepRequest).toHaveBeenCalledExactlyOnceWith('next', { threadId: 1 }); + expect(result).toBe(served); + expect(childClient.sendRequest).not.toHaveBeenCalled(); + // Its own step ends nothing: no request-before hook, nothing on the parent socket. + expect(stubManager.beforeChildRequest).not.toHaveBeenCalled(); + expect(parentWrite).not.toHaveBeenCalled(); + routed.shutdown(); + }); + + it('that the stepper does not serve passes it before it goes out, and waits for it', async () => { + const stubManager = createChildSessionManagerStub(); + stubManager.shouldRouteToChild.mockReturnValue(true); + let stepGivenUp!: () => void; + stubManager.beforeChildRequest.mockImplementation(() => new Promise((resolve) => { stepGivenUp = resolve; })); + const childResponse = { seq: 1, type: 'response', request_seq: 1, command: 'continue', success: true }; + const childClient = { sendRequest: vi.fn().mockResolvedValue(childResponse) } as unknown as MinimalDapClient; + const { routed } = routedTo(stubManager, childClient); + + const sending = routed.sendRequest('continue', { threadId: 1 }); + await new Promise((resolve) => setImmediate(resolve)); + + // The stepper was asked whether it serves the request, said no, and + // is given the request to end a step in flight: nothing is sent yet. + expect(stubManager.stepRequest).toHaveBeenCalledExactlyOnceWith('continue', { threadId: 1 }); + expect(stubManager.beforeChildRequest).toHaveBeenCalledExactlyOnceWith('continue'); + expect(childClient.sendRequest).not.toHaveBeenCalled(); + + stepGivenUp(); + await expect(sending).resolves.toBe(childResponse); + expect(childClient.sendRequest).toHaveBeenCalledExactlyOnceWith('continue', { threadId: 1 }, 30000); + routed.shutdown(); + }); + }); + + it('end to end with the real child-session manager and stepper: an attach that asked for smartStep', async () => { + const cdp = new FakeCdpClient(); + answers.requestCDPProxy = { host: '127.0.0.1', port: 9333, path: '/cdp-of-the-target' }; + client = new MinimalDapClient('localhost', 5678, JsDebugAdapterPolicy, { + childSessionManagerFactory: (opts) => new ChildSessionManager({ ...opts, cdpClientFactory: () => cdp as unknown as CdpProxyClient }) + }); + const stops: unknown[] = []; + client.on('stopped', (body: unknown) => stops.push(body)); + const adopted = new Promise((resolve) => client.once('child-adopted', () => resolve())); + await client.connect(); + + await client.sendRequest('attach', { type: 'pwa-node', request: 'attach', port: 9229, localRoot: '/app', smartStep: true }); + + // The session chose to step through skipped code; js-debug's stepper stays off. + expect(client.stepsThroughSkippedCode()).toBe(true); + expect(adapterSockets[0].requests.at(-1)?.arguments).toEqual({ type: 'pwa-node', request: 'attach', port: 9229, localRoot: '/app', smartStep: false }); + + // js-debug reports the target; the manager adopts it on a connection of its own. + adapterSockets[0].push({ + seq: 90, type: 'request', command: 'startDebugging', + arguments: { request: 'attach', configuration: { type: 'pwa-node', name: 'target', __pendingTargetId: 'target-1' } } + }); + await adopted; + await vi.waitFor(() => expect(cdp.sent).toContain('Debugger.enable')); + const target = adapterSockets[1]; + + // The target's attach repeats the root's arguments, and must not turn + // js-debug's stepper back on. + expect(target.requests.find((request) => request.command === 'attach')?.arguments).toMatchObject({ + request: 'attach', __pendingTargetId: 'target-1', localRoot: '/app', smartStep: false + }); + + // A step: served over the CDP socket, never sent to js-debug. + cdp.paused(); + const stepped = await client.sendRequest('next', { threadId: 1 }); + expect(stepped).toMatchObject({ command: 'next', success: true }); + expect(cdp.sent).toContain('Debugger.stepOver'); + expect(target.requests.map((request) => request.command)).not.toContain('next'); + + // While the step is in flight its pauses are the stepper's... + target.push({ type: 'event', event: 'stopped', body: { reason: 'pause', threadId: 1 } }); + await client.flushChildEvents(); + expect(stops).toEqual([]); + + // ...and a continue gives the step up before it goes out: the next stop is the program's own. + await client.sendRequest('continue', { threadId: 1 }); + expect(target.requests.at(-1)).toMatchObject({ command: 'continue', arguments: { threadId: 1 } }); + target.push({ type: 'event', event: 'stopped', body: { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [4] } }); + await vi.waitFor(() => expect(stops).toEqual([{ reason: 'breakpoint', threadId: 1, hitBreakpointIds: [4] }])); + }); + }); + }); diff --git a/tests/unit/shared/adapter-policy-js.test.ts b/tests/unit/shared/adapter-policy-js.test.ts index 81302293d..9f657507e 100644 --- a/tests/unit/shared/adapter-policy-js.test.ts +++ b/tests/unit/shared/adapter-policy-js.test.ts @@ -209,6 +209,16 @@ describe('JsDebugAdapterPolicy', () => { expect(text).not.toMatch(/smart-stepper/); }); + it('reads a bare node: frame as Node\'s own code too: the form js-debug has not rewritten to ', () => { + const bareInternalFrame = { id: 4, name: 'processTicksAndRejections', file: 'node:internal/process/task_queues', line: 95 }; + const text = hook({ operation: 'step', attachMode: false, launch: {}, fromFrame: bareInternalFrame }); + expect(text).toMatch(/issued from skipped code \(node:internal\/process\/task_queues:95\)/); + expect(text).not.toMatch(/left the frame it started in/); + // Under the same rule as the rewritten form: only while this launch skips Node's own code. + expect(hook({ operation: 'step', attachMode: false, launch: launch(undefined, { skipFiles: ['**/node_modules/**'] }), fromFrame: bareInternalFrame })) + .toMatch(/left the frame it started in/); + }); + it('says of a pending step from the program\'s own code that it ran off the stack or is waiting on work in flight', () => { for (const fromFrame of [userFrame, undefined]) { const text = hook({ operation: 'step', attachMode: false, launch: {}, ...(fromFrame ? { fromFrame } : {}) }); From 55052ad6e716533a0d8b0d5cd317fdfdd9b0fcc6 Mon Sep 17 00:00:00 2001 From: JF Date: Mon, 16 Nov 2026 00:05:10 -0500 Subject: [PATCH 09/24] docs(javascript): what a step does, said as it is (#1130, #1161) The review read every sentence of the stepping section against the code and found ten false. Rewritten in the JavaScript guide, the tool reference and both changelog fragments: - what a step_into says when the walk stayed in skipped code, and that a call into native code says nothing; - that a `debugger;` reached during a step is reported as the step's landing, and that a pause asked for during a pending step is the caller's; - that a step off a function nothing of yours called or awaits answers with the next stop if one comes, and pending only if none does; - that V8 "can" lose a step through try...finally, where the temporary breakpoints are set and where they are not, and what is left to V8 on purpose: recursion, a line that awaits, and the awaiting function of an async one; - that a skipFiles list without makes Node's code program code to a step. The sentence a pending step carries no longer claims nothing of the program has run since; the justMyCode schema text follows the new wording (24 tool-list snapshots). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn69pXrYMWc1JUwv5v8 --- changelog.d/1130.fixed.md | 2 +- changelog.d/1161.fixed.md | 2 +- docs/javascript/README.md | 63 ++++++++++++------- docs/tool-reference.md | 41 +++++++++--- .../src/interfaces/adapter-policy-js.ts | 7 ++- src/server/tool-schemas.ts | 2 +- .../bp-assert.va-explicit.container-true.json | 2 +- ...bp-assert.va-explicit.container-unset.json | 2 +- .../bp-assert.va-open.container-true.json | 2 +- .../bp-assert.va-open.container-unset.json | 2 +- .../bp-assert.va-unset.container-true.json | 2 +- .../bp-assert.va-unset.container-unset.json | 2 +- ...bp-content.va-explicit.container-true.json | 2 +- ...p-content.va-explicit.container-unset.json | 2 +- .../bp-content.va-open.container-true.json | 2 +- .../bp-content.va-open.container-unset.json | 2 +- .../bp-content.va-unset.container-true.json | 2 +- .../bp-content.va-unset.container-unset.json | 2 +- .../bp-line.va-explicit.container-true.json | 2 +- .../bp-line.va-explicit.container-unset.json | 2 +- .../bp-line.va-open.container-true.json | 2 +- .../bp-line.va-open.container-unset.json | 2 +- .../bp-line.va-unset.container-true.json | 2 +- .../bp-line.va-unset.container-unset.json | 2 +- .../bp-unset.va-explicit.container-true.json | 2 +- .../bp-unset.va-explicit.container-unset.json | 2 +- .../bp-unset.va-open.container-true.json | 2 +- .../bp-unset.va-open.container-unset.json | 2 +- .../bp-unset.va-unset.container-true.json | 2 +- .../bp-unset.va-unset.container-unset.json | 2 +- 30 files changed, 105 insertions(+), 60 deletions(-) diff --git a/changelog.d/1130.fixed.md b/changelog.d/1130.fixed.md index 1f7a8504b..6db3b5a40 100644 --- a/changelog.d/1130.fixed.md +++ b/changelog.d/1130.fixed.md @@ -1 +1 @@ -**A JavaScript step lands where your code next runs, and is no longer lost in Node's own code.** `step_into` on a line that calls a Node builtin took about 6 s on a Linux host and answered `pending`, blaming "a long-running call"; on the first `console.log` of a process it never landed at all and the program ran to its end. js-debug's own "smart stepper" was deciding where such a step ends: while the step was in skipped code it stepped again by itself, one engine step per statement (131 for one `console.log`), with a flag that moves the step to a later task and loses it. That stepper is now off for every session, and the server steps through skipped code itself, over js-debug's raw CDP socket, for `step_into`, `step_over` and `step_out` alike. A `step_into` on a line that calls your own function through skipped code (an event listener behind `emitter.emit`, an array callback, a route handler from inside express) lands in that function; on a line that calls only skipped code it lands on the next line and the message says so (`Stepped into. The call on that line ran only skipped code …`); on a line that only starts a later task (`setTimeout`) it lands on the next line instead of inside the callback some time later. A `step_over` or `step_out` that returns into skipped code steps out to the nearest frame of your program below; when there is none (the last line of a request handler or a timer callback) the program is resumed rather than walked through the internals of later tasks, and the pending answer says the step left its frame. What counts as skipped is still js-debug's own verdict, so `justMyCode`, your `skipFiles` and source maps behave as before, and `justMyCode: false` (or `smartStep: false`) still lands every step where V8 lands. A forked child steps the same way. Changed on purpose: a `debugger;` statement or a pause in a dependency now stops there instead of being stepped away from, and the sentence a pending step carries no longer mentions js-debug's stepper. On Linux every engine step costs about 46 ms whoever sends it, so a `step_into` on a `console.log` line still takes over a second there. (#1130) +**A JavaScript step lands where your code next runs, and is no longer lost in Node's own code.** `step_into` on a line that calls a Node builtin took about 6 s on a Linux host and answered `pending`, blaming "a long-running call"; on the first `console.log` of a process it never landed at all and the program ran to its end. js-debug's own "smart stepper" was deciding where such a step ends: while the step was in skipped code it stepped again by itself, one engine step per statement (131 for one `console.log`), with a flag that moves the step to a later task and loses it. That stepper is now off for every session, and the server steps through skipped code itself, over js-debug's raw CDP socket, for `step_into`, `step_over` and `step_out` alike. A `step_into` on a line that calls your own function through skipped code (an event listener behind `emitter.emit`, an array callback, a route handler from inside express) lands in that function; on a line whose call stays in skipped code for the whole walk (`console.log`, a `require`) it lands on the next line and the message says how far the walk went (`Stepped into. step_into walked 25 engine steps into the call on that line and was still in skipped code …`) and that code of yours the call reaches further in ran without stopping; on a line that only starts a later task (`setTimeout`) it lands on the next line instead of inside the callback some time later. A `step_over` or `step_out` that returns into skipped code steps out to the nearest frame of your program below; when nothing of your program called or awaits the function (the last line of a request handler, a timer callback, a `.then` callback) the program is resumed rather than walked through the internals of later tasks, and the pending answer says the step left its frame. What counts as skipped is still js-debug's own verdict, so `justMyCode`, your `skipFiles` and source maps decide it as before, and `justMyCode: false` (or `smartStep: false`) still lands every step where V8 lands. A forked child steps the way its root session does, launched or attached. Changed on purpose: a pause asked for while a step is still pending is reported as the pause, where the program is, and is not stepped away from; and the sentence a pending step carries no longer mentions js-debug's stepper. On Linux every engine step costs about 46 ms whoever sends it (#1163), so a `step_into` on a `console.log` line still takes over a second there. (#1130) diff --git a/changelog.d/1161.fixed.md b/changelog.d/1161.fixed.md index b081e8140..dece24d95 100644 --- a/changelog.d/1161.fixed.md +++ b/changelog.d/1161.fixed.md @@ -1 +1 @@ -**A JavaScript step that leaves a function through `return` inside `try … finally` lands in the caller.** V8 never pauses for such a step (measured on V8 12.4, 13.6 and 14.6 with a bare CDP client): a `step_out` of the function, a `step_over` off its `finally` block, and a `step_out` of an `async` function with that shape all answered `Step completed as session exited.` while the program ran on. Node's own module loader returns that way too, which is how a `step_into` on a `require` line was lost. A step no longer counts on V8 alone to come back to a frame: before it can leave one that way, the server sets temporary breakpoints on the frame the step returns to (the nearest frame of your program below, or the awaiting function of an `async` one), and whichever pauses first is the landing. That is something the server does in your process: at most 24 temporary breakpoints, for the length of one step (every `step_out`; a `step_over` or `step_into` in a function whose text contains `finally`; a step that walks through skipped code), removed when the step ends however it ends. A function that returns to itself gets none for `step_over` and `step_into`. Not covered: a `step_over` across the first load of a module that has a breakpoint in it still runs on (#1162). (#1161) +**A JavaScript step that leaves a function through `return` inside `try … finally` lands in the caller.** V8 can lose such a step (measured on V8 12.4, 13.6 and 14.6 with a bare CDP client): a `step_out` of the function, a `step_over` off its `finally` block, and a `step_out` of an `async` function with that shape all answered `Step completed as session exited.` while the program ran on. Node's own module loader returns that way too, which is how a `step_into` on a `require` line was lost. Where a step can leave a frame that way, the server no longer counts on V8 alone to come back to the frame below: it sets temporary breakpoints on that frame, and whichever pauses first is the landing. That is something the server does in your process: at most 24 temporary breakpoints per guarded frame, for the length of one step (every `step_out`; a `step_over` or `step_into` from a function whose text has a `finally` clause; a step that walks through skipped code), removed when the step ends however it ends. Left to V8 on purpose: a function that returns to itself (`step_over`, `step_into`); and, in a function that can suspend, any line that itself awaits or yields, so a `step_over` on an `await` that is the last thing a function does before it leaves through `finally` can still be lost. An `async` function the event loop resumed returns to the function awaiting it, which is not on the stack: V8's own step finds the call that awaited, and only where V8 loses the step does the server guard the awaiting function, in whichever call of it runs next; that answer says the stop may be another call's. Not covered: a `step_over` across the first load of a module that has a breakpoint in it still runs on (#1162). (#1161) diff --git a/docs/javascript/README.md b/docs/javascript/README.md index 7c2469193..fcf03c8aa 100644 --- a/docs/javascript/README.md +++ b/docs/javascript/README.md @@ -115,15 +115,19 @@ What a step does when the session steps through skipped code (the launch default | Step | From | Lands | |---|---|---| | `step_into` | a line that calls your function through skipped code (`emitter.emit` to a listener, an array callback, a route handler from inside express) | in that function | -| `step_into` | a line that calls only skipped code (`console.log`, `require`, `JSON.stringify`) | on the next line; the message says the line called only skipped code | -| `step_into` | a line that only starts a later task (`setTimeout`, a promise callback) | on the next line; a breakpoint in the callback stops there | +| `step_into` | a line whose call stays in skipped code for the whole walk (`console.log`, a `require`) | on the next line. The message says how many engine steps the walk took, and that code of yours the call reaches further in (the module a `require` loads, a late callback) ran without stopping | +| `step_into` | a line that calls native code only (`JSON.stringify`) | on the next line, as a plain `Stepped into`: there is nothing to walk into | +| `step_into` | a line that only starts a later task (`setTimeout`, a `.then` callback) | on the next line; a breakpoint in the callback stops there | | `step_over`, `step_out` | a frame whose caller is skipped code, with your code further down the stack | in that frame of yours | -| `step_over`, `step_out` | the last line of a function Node called (a request handler, a timer callback) | nowhere: nothing of your program is on the stack, so the program is resumed and the answer is `pending: true` with a sentence saying so; the next breakpoint stops it | +| `step_out` | an `async` function the event loop resumed | in the function that awaits it, in the call that awaited | +| `step_over`, `step_out` | the last line of a function that nothing of yours called or awaits (a request handler, a timer callback, a `.then` callback) | nowhere: nothing of your program is on the stack, so the program is resumed. The answer is the next stop if one comes while the step waits (a breakpoint, the program's end), and `pending: true` with a sentence saying so if none does | | any step | skipped code (a breakpoint inside a dependency) | `step_into` walks on into your handler; `step_over` and `step_out` run on as in the row above. `justMyCode: false` steps inside that code | -A breakpoint, an exception or a `debugger;` statement reached during a step stops as itself. A pause is never stepped -away from: it lands where the program is, in Node's own code if that is where it is (the stack response marks the -frame). +A breakpoint or an exception reached during a step stops as itself. A `debugger;` statement reached during a step is +reported as the step's landing: V8 reports the two alike, and it is where the program stopped. (A `debugger;` in +skipped code does not stop at all, with or without a step in flight.) A pause asked for while a step +is still pending is the caller's: the next stop is reported as the pause, where the program is, in Node's own code +if that is where it is (the stack response marks the frame). A step never steps away from it. | Launch | `skipFiles` sent | Steps through skipped code | `step_over` from a breakpoint inside a dependency | |---|---|---|---| @@ -133,31 +137,48 @@ frame). | `adapterLaunchConfig: { smartStep: false }` (default list) | `/**`, `**/node_modules/**` | no | lands in the next frame V8 does not skip (an internals frame on a request path) | A caller-supplied `skipFiles` **replaces** the default list (VS Code's launch.json semantics); include -`/**` yourself if you still want internals skipped. An explicit `smartStep` always wins over the +`/**` yourself if you still want internals skipped. Without it Node's own code is program code to a +step: a `step_out` of a timer callback lands in Node's timer code. An explicit `smartStep` always wins over the derived value. Attach defaults `smartStep` to `false` and leaves `skipFiles` unset (issue #513) — see `attach_to_process` in the tool reference. With the stepping off, a step lands where V8 lands: a `step_into` on a `console.log` line stops in ``, and an `async` callee in TypeScript compiled for a target below ES2017 costs four unmapped `__awaiter` stops before its first line (issue #687). -**Steps V8 itself loses** (issue #1161). V8 never pauses for a step that leaves a function through a `return` -written inside `try … finally` (measured on V8 12.4, 13.6 and 14.6 with a bare CDP client): a `step_out` of such a -function, or a `step_over` off its `finally` block, used to answer `Step completed as session exited.` Node's own -module loader has that shape, which is how a `step_into` on a `require` line was lost too. So a step never counts on -V8 alone to come back to a frame. Before a step can leave a frame that way, the server sets temporary breakpoints on -the frame the step returns to (the nearest frame of your program below, or the awaiting function of an `async` -one), and whichever pauses first is the landing. That is something the server does in your process: up to 24 -temporary breakpoints for the length of one step, for every `step_out`, for a `step_over` or `step_into` in a -function whose text contains `finally`, and for a step that walks through skipped code. They are removed when the -step ends, however it ends. A function that returns to itself (recursion) gets none for `step_over` and -`step_into`, so that one shape keeps V8's own behaviour. +**Steps V8 itself loses** (issue #1161). V8 can lose a step that leaves a function through a `return` written +inside `try … finally` (measured on V8 12.4, 13.6 and 14.6 with a bare CDP client): a `step_out` of such a function, +or a `step_over` off its `finally` block, used to answer `Step completed as session exited.` Node's own module +loader has that shape, which is how a `step_into` on a `require` line was lost too. So where a step can leave a +frame that way, the server does not count on V8 alone to come back to the frame below: it sets temporary +breakpoints on that frame (the nearest frame of your program down the stack), and whichever pauses first is the +landing. That is something the server does in your process: up to 24 temporary breakpoints per guarded frame, for +the length of one step. They are set for every `step_out`, for a `step_over` or `step_into` from a function whose +text has a `finally` clause, and for a step that walks through skipped code, and they are removed when the step +ends, however it ends. Where they cannot be set (V8 gives no break positions for Node's own scripts) the step goes +on with V8 alone. + +What that leaves to V8, on purpose: + +- **Recursion.** A function that returns to itself gets no such breakpoints for `step_over` and `step_into`: they + would sit in the frame being stepped in. +- **A function that can suspend** (`await` or `yield` in its text). A `step_over` or `step_into` there is guarded + only on a `return` line and from its `finally` on, and never on a line that itself awaits or yields: on such a + line the function suspends, its caller runs on, and a breakpoint in the caller would stop the step there instead + of on the next line. So a `step_over` on an `await` that is the last thing a function does before it leaves + through `finally` is V8's own, and V8 can lose it: the program runs on. +- **The function awaiting an `async` one.** An `async` function the event loop resumed returns to the function that + awaits it, which is not on the stack. V8's own step finds the call that awaited. Only where V8 loses the step + (`finally` in the function being left) does the server guard the awaiting function, and there it can only guard + the *function*: the step stops in whichever call of it runs next, and the answer says so (`… this stop may be in + another call's continuation than the one that awaited the function you stepped out of: check its variables.`). + With one call in flight, that is the right one. Not covered: a `step_over` across the first load of a module that has a breakpoint in it still runs on (issue #1162; js-debug pauses at the module's entry to bind the breakpoint, and V8 drops the step at any pause). A `step_into` on that line does land. -On Linux every engine step costs about 46 ms whoever sends it (the inspector's socket), against 1.5 ms on Windows, -so a `step_into` on a `console.log` line, which walks 24 engine steps into Node's code before it comes back, takes -over a second there. +On Linux every engine step costs about 46 ms whoever sends it (the inspector's socket; issue #1163), against 1.5 ms +on Windows, so a `step_into` on a `console.log` line, which walks 25 engine steps into Node's code and a few back +out, takes over a second there. A step whose stop is a breakpoint or an exception rather than the step itself is reported as `Stepped over; stopped on 'breakpoint' rather than on the step itself (see stopReason)` — true both when the next diff --git a/docs/tool-reference.md b/docs/tool-reference.md index 9ab35ec93..f04d39dde 100644 --- a/docs/tool-reference.md +++ b/docs/tool-reference.md @@ -490,7 +490,7 @@ Starts debugging a script. - `args` (array of strings, optional): Command line arguments for the script. - `dapLaunchArgs` (object, optional): Standard DAP launch arguments: - `stopOnEntry` (boolean): Stop at first line (default `false` — the opposite of attach, which pauses unless `stopOnEntry` is `false`) - - `justMyCode` (boolean): Debug only user code (default `true`). JavaScript launch: `true` puts `node_modules` on js-debug's `skipFiles` beside Node internals, and a step does not stop in skipped code: the server steps through it itself, so `step_into` follows a call through skipped code into your own function, and otherwise lands on the next line and says the line called only skipped code (issue #1130; see [`step_into`](#step_into)). `false` takes `node_modules` off the list and turns that stepping off, so every step lands where V8 lands, inside dependencies and Node internals. A pause lands where the program is either way. A caller `skipFiles` replaces the default list. Source maps are on for every JavaScript launch, `.js` programs included — stops report `src/*.ts` when maps and sources are present; `adapterLaunchConfig: { sourceMaps: false }` opts out (issue #684) + - `justMyCode` (boolean): Debug only user code (default `true`). JavaScript launch: `true` puts `node_modules` on js-debug's `skipFiles` beside Node internals, and a step does not stop in skipped code: the server steps through it itself, so `step_into` follows a call through skipped code into your own function, and otherwise lands on the next line and says how far it walked without reaching your code (issue #1130; see [`step_into`](#step_into)). `false` takes `node_modules` off the list and turns that stepping off, so every step lands where V8 lands, inside dependencies and Node internals. A pause lands where the program is either way. A caller `skipFiles` replaces the default list. Source maps are on for every JavaScript launch, `.js` programs included — stops report `src/*.ts` when maps and sources are present; `adapterLaunchConfig: { sourceMaps: false }` opts out (issue #684) - `noDebug` (boolean): DAP's "launch without enabling debugging" flag (default `false`). What it does depends on the adapter, and the response says which case you are in. **Honoured** — the debugger is off: no breakpoint binds, no exception filter arms, no entry stop lands, and no breakpoint, exception or entry stop ever arrives, so a short script ends `stopped` and a server stays `running`. That is a legitimate plain run and says nothing by itself; when the session has breakpoints (line or function), an explicit `breakOnExceptions` other than `"none"`, or `stopOnEntry`, the `warning` says the debugger is off for this launch and names what will not fire — not that no stop of any kind can come — in place of the unbound-breakpoint diagnostics that would otherwise send you to check paths that are fine (issue #710). js-debug, debugpy, Delve and CodeLLDB honour it (debugpy and Delve open no configuration phase at all, so the launch is complete on the launch response; CodeLLDB refuses the configuration requests, and the refusal reaches the `warning` and `get_output` — issue #746). The run ends `stopped` with the program's output and, where the adapter reports one, the exit code (Delve states it as a console line, `Process N has exited with status S`, which is read back as `exitCode` — issue #753). Under the flag Delve runs the program through Go's `exec`, so on Windows the binary needs its `.exe` extension. **Ignored** — rdbg, netcoredbg and the Java bridge run the debugger regardless, and the rust launch transform never forwards the flag: the `warning` says the flag had no effect and everything works as usual. The same warning comes back from `restart_debugging` and from a `dryRunSpawn` check. While such a launch runs, the session remembers the decision (`list_debug_sessions` reports `debuggerDisabled: true`) and every later surface says why: `set_breakpoint` and `list_breakpoints` keep the adapter's own answer (still sent — e.g. js-debug's "Unbound breakpoint", or CodeLLDB's refusal echoed onto each pre-launch breakpoint) and add "the debugger is off for this launch (noDebug is true)…", `pause_execution` is still sent and the same sentence explains a pause that never lands or one the adapter refused, and `step_*`/`continue_execution`/`get_stack_trace`/`get_local_variables`/`evaluate_expression` append it to their "not paused" answers. A `stopped` event only a live debugger produces — a breakpoint the adapter itself reports (or names in `hitBreakpointIds`), an exception stop, an entry stop — proves the debugger on for that adapter build and clears the decision, and so does a breakpoint the adapter verified (every honouring adapter refuses or unbinds one under the flag, so a bound one can only come from a build that ignores it); a pause, a step taken from one, or a `debugger;` statement do not (js-debug lands all three under the flag while its breakpoints stay unbound; an uncaught throw does not stop). On a paused session the sentence keeps only the clause still true of it — breakpoints cannot bind — and outside a live launch (`initializing`/`running`/`paused`) the decision is neither reported nor consulted (issue #749). - Additional DAP launch keys (`program`, `cwd`, `env`, language-specific options) pass through to the adapter. For Python, `module` (`python -m `) or `code` (`python -c`) replaces `program`: debugpy takes exactly one target, so the launch goes out without `program` and the response's `warning` says so (`dapLaunchArgs.module: launched as a module (python -m); program is not sent …`); `scriptPath` still has to name an existing file, and `cwd` is what `-m` puts on `sys.path`: for these launches it defaults to the directory above the top-most package containing `scriptPath` (the `warning` names it), and a module launch of a project sets it to the project root explicitly (issue #985). `dryRunSpawn` reports such a launch's `data.script` as `module: ` or `code: …`. Top-level parameters do **not** belong here: a nested `breakOnExceptions` is honored as an alias (the top-level value wins if both are given) and reported via a `warning` in the response; other misplaced top-level keys (`dryRunSpawn`, `sessionId`, `scriptPath`, `adapterLaunchConfig`) are stripped with a warning instead of silently riding into the launch config. - `adapterLaunchConfig` (object, optional): Adapter-specific launch configuration overrides. Use this for language-specific settings that go beyond standard DAP arguments (e.g., `mainClass` and `classpath` for Java, `buildCommand` for Rust). For Rust, `_adapterSettings` passes through to CodeLLDB (issue #441) — e.g. `{"_adapterSettings": {"scriptConfig": {"lang": {"rust": {"sysroot": "/path"}}}}}` points the Rust formatter lookup at an explicit sysroot; the `CODELLDB_RUST_SYSROOT` env var does the same without per-launch config (a user-supplied `_adapterSettings` value wins over the env var). @@ -706,8 +706,9 @@ The step is not cancelled: the session becomes `"paused"` on its own when it com The adapter may append one sentence to that message saying what the step is waiting for. The JavaScript adapter does so for a launch that steps through skipped code (issues #678, #1130): a step issued from skipped code names the frame and says a step does not stop there, and any other pending step says it left the frame it started in -and nothing of your program has run since (a function Node called returned to the event loop, or the line is -waiting on work in flight). So match a pending step by its `pending: true` flag, not by the message text. +and has not stopped in your program since (a function Node called returned to the event loop, the line is +waiting on work in flight, or the engine lost the step: an `await` that was the last thing a function did before +it left through `try … finally`). So match a pending step by its `pending: true` flag, not by the message text. Once a stop has been observed, the stop path owns the answer — a step that demonstrably landed is never reported as pending afterwards, at the cost of the response then being bounded by the stack-trace round trip rather than by the ~5s window. If the debuggee ends while the step is in flight the result is still a success, with a terminal `state` and a message such as `"Step completed as session terminated."`. @@ -738,11 +739,16 @@ Same ~5s wait and `pending: true` contract as step_over — see [Pending steps]( - A line that calls your own function through skipped code lands in that function: an event listener behind `emitter.emit`, an array callback, a route handler from inside express. -- A line that calls only skipped code (Node internals, `node_modules`, files on `skipFiles`) lands on the next - line, and the message says so: `Stepped into. The call on that line ran only skipped code (Node internals, - node_modules, or files on skipFiles), so there was nothing of your program to step into and the line ran as a - step over. dapLaunchArgs.justMyCode: false steps into that code.` -- A call that only starts a later task (`setTimeout`, a promise callback) is not followed: the step lands on the +- A line whose call stays in skipped code (Node internals, `node_modules`, files on `skipFiles`) for the whole + walk lands on the next line, and the message says what is known: `Stepped into. step_into walked 25 engine steps + into the call on that line and was still in skipped code (Node internals, node_modules, or files on skipFiles), + so it stepped back out and the rest of the line ran as a step over runs it. Code of yours that the call reaches + further in (a module it loads, a late callback) ran without stopping: a breakpoint there stops in it. To stop + inside the skipped code instead, turn stepping through it off: justMyCode: false on a launch, smartStep: false + on a launch or an attach.` A `console.log` and a `require` answer this way. +- A line that calls native code only (`JSON.stringify`) has nothing to walk into: a plain `Stepped into` on the + next line. +- A call that only starts a later task (`setTimeout`, a `.then` callback) is not followed: the step lands on the next line. Set a breakpoint in the callback to stop there. See [Stepping and pausing inside dependencies](javascript/README.md#stepping-and-pausing-inside-dependencies-justmycode-skipfiles). @@ -768,6 +774,22 @@ Steps out of the current function. Same ~5s wait and `pending: true` contract as step_over — see [Pending steps](#pending-steps). +**JavaScript** (a launch that steps through skipped code, the default; issues #1130, #1161): + +- Out of an `async` function the event loop resumed, the step lands in the function that awaits it, in the + call that awaited. +- When that `async` function has a `finally` clause, the engine can lose the step, so the server catches it + at the awaiting function instead, in whichever call of that function runs next, and the message says so: + `Stepped out. The engine loses a step that leaves a function through try...finally, so this step was caught + where the awaiting function, handler, next ran. If several calls of handler are in flight, this stop may be + in another call's continuation than the one that awaited the function you stepped out of: check its + variables.` +- Out of a function that nothing of your program called or awaits (a timer callback, a `.then` callback, a + request handler) there is nowhere to land: the program is resumed, and the answer is the next stop or + `pending: true`. + +See [Stepping and pausing inside dependencies](javascript/README.md#stepping-and-pausing-inside-dependencies-justmycode-skipfiles). + --- ### continue_execution @@ -998,7 +1020,8 @@ A frame is program code when the adapter's policy does not call it internal **an An adapter may append a sentence to that message, so match a pending pause by its `pending: true` flag, not by the message text. (The JavaScript adapter used to add one about js-debug's own stepper stepping away from a pause that -landed in skipped code; that stepper is off since issue #1130, and a pause lands where the program is.) +landed in skipped code; that stepper is off since issue #1130, and a pause lands where the program is, also when +it is asked for while a step is still pending.) **Notes:** - The `"state"` field is the session state at the moment the tool answers: `"paused"` once the stop has been observed, and `"running"` **only on the pending path** — the request was delivered but the program has not stopped yet. On that path, call [`wait_for_stop`](#wait_for_stop) to block until the state flips to `"paused"` when the target next executes code (or poll `list_debug_sessions`). diff --git a/packages/shared/src/interfaces/adapter-policy-js.ts b/packages/shared/src/interfaces/adapter-policy-js.ts index 55a7829a7..ebe26cb5a 100644 --- a/packages/shared/src/interfaces/adapter-policy-js.ts +++ b/packages/shared/src/interfaces/adapter-policy-js.ts @@ -449,9 +449,10 @@ export const JsDebugAdapterPolicy = { 'still in flight. It stops at the next breakpoint in your own code. Relaunch with ' + 'dapLaunchArgs.justMyCode: false (or adapterLaunchConfig.smartStep: false) to step inside that code.'; } - return 'The step left the frame it started in and nothing of your program has run since: a function that Node ' + - 'called returned to the event loop, or the line is waiting on work still in flight. The program is running; ' + - 'wait_for_stop answers when the step lands or a breakpoint is hit.'; + return 'The step left the frame it started in and has not stopped in your program since: a function that Node ' + + 'called returned to the event loop, the line is waiting on work still in flight, or the engine lost the step ' + + '(an await that was the last thing a function did before it left through try...finally). The program is ' + + 'running; wait_for_stop answers when the step lands, a breakpoint is hit, or the program ends.'; }, /** diff --git a/src/server/tool-schemas.ts b/src/server/tool-schemas.ts index f63a160b6..87008f52c 100644 --- a/src/server/tool-schemas.ts +++ b/src/server/tool-schemas.ts @@ -159,7 +159,7 @@ export function buildToolDefinitions(options: BuildToolDefinitionsOptions): Tool description: 'DAP launch arguments. Beyond the three below, adapter keys pass through (program, cwd, env, …). Python: module runs `python -m ` instead of scriptPath (the pytest shape: module "pytest", args [::, "-x"]) and code runs a code string; scriptPath then only names the file the launch is about, and cwd — which `python -m` puts on sys.path — defaults to the directory above the top-most package containing scriptPath', properties: { stopOnEntry: { type: 'boolean', description: 'Pause at the first line before running. Default false — the opposite of attach, which pauses unless stopOnEntry is false' }, - justMyCode: { type: 'boolean', description: 'Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way' }, + justMyCode: { type: 'boolean', description: 'Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way' }, noDebug: { type: 'boolean', description: 'DAP\'s launch-without-debugging flag (default false). Where the adapter honours it (js-debug, debugpy, Delve, CodeLLDB and the Dart SDK adapters) no breakpoint binds, no exception filter arms, no entry stop lands and no breakpoint, exception or entry stop ever arrives (a pause may still land where the runtime allows one) — the response warns when breakpoints, an explicit breakOnExceptions or stopOnEntry are set alongside it, and while the launch runs the session reports debuggerDisabled and every later surface says the debugger is off. rdbg, netcoredbg and the Java bridge ignore the flag, and the rust launch never forwards it: their debugger stays on and the response says so' } }, additionalProperties: true diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-true.json index b39d748d6..5f9da8feb 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-true.json @@ -240,7 +240,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-unset.json index af6b2c378..3157a2450 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-unset.json @@ -240,7 +240,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-true.json index 82a082572..0f7668313 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-true.json @@ -240,7 +240,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-unset.json index a76305723..dc23b8756 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-unset.json @@ -240,7 +240,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-true.json index 82a082572..0f7668313 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-true.json @@ -240,7 +240,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-unset.json index a76305723..dc23b8756 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-unset.json @@ -240,7 +240,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-true.json index b03df94a0..f224bcb08 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-true.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-unset.json index 87219da2c..5b740732a 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-unset.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-true.json index 0b267c9cf..6dfc4ffbd 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-true.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-unset.json index ead7b4bb9..26ffcf8b4 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-unset.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-true.json index 0b267c9cf..6dfc4ffbd 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-true.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-unset.json index ead7b4bb9..26ffcf8b4 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-unset.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-true.json index d9bdd974f..873381aac 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-true.json @@ -236,7 +236,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-unset.json index b723db9db..22127557d 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-unset.json @@ -236,7 +236,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-true.json index d0aebdd55..c0950fcb2 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-true.json @@ -236,7 +236,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-unset.json index 96a5aae0f..fc6d2805d 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-unset.json @@ -236,7 +236,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-true.json index d0aebdd55..c0950fcb2 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-true.json @@ -236,7 +236,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-unset.json index 96a5aae0f..fc6d2805d 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-unset.json @@ -236,7 +236,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-true.json index b03df94a0..f224bcb08 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-true.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-unset.json index 87219da2c..5b740732a 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-unset.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-true.json index 0b267c9cf..6dfc4ffbd 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-true.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-unset.json index ead7b4bb9..26ffcf8b4 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-unset.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-true.json index 0b267c9cf..6dfc4ffbd 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-true.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-unset.json index ead7b4bb9..26ffcf8b4 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-unset.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says the line called only skipped code); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", From 5895a6dc78ea9745f323dd5674cacd94b7585265 Mon Sep 17 00:00:00 2001 From: JF Date: Mon, 16 Nov 2026 01:34:40 -0500 Subject: [PATCH 10/24] fix(javascript): one rule for where a step is netted, applied in one place (#1130, #1161) The second review found the first round's fix incomplete twice, and both were the shape that round had already fixed twice: a temporary breakpoint below a function that suspends instead of returning. - A step over a statement that awaits on a later line (`return {` with the awaits two lines down) was still netted, because only the paused line's text was read. The function suspended, its caller ran on into the net, and the step stopped in the caller. - A step out of an async function still in its first run was netted on its caller by depth, like any step out. The caller was waiting at its own await, left the stack, and the net stopped in the next call of that function entered at the same depth: a sibling, with nothing said. So the arming is no longer decided at four sites. One rule, in `guard()`, before every command that can leave the frame on top: (a) A net only where V8 can lose the step and the frame cannot hand control down without returning. For a frame of the program that is read from its text: a finally clause, and from the paused line no way to suspend before the function exits (no await or yield ahead, no loop above that leads back to one). Measured with V8 alone: V8 keeps a step across an await and lands in the awaiting function even when the function then leaves through finally, so a function that can still suspend needs no rescue. Skipped code is netted without being read (V8 refuses the positions of Node's own scripts, and Node's loader has the shape): however control comes down from it, the program frame below is the landing. A step out is no longer netted unconditionally. (b) A net names one call only while the frame it guards stays on the stack. When that frame is itself waiting at an await for the call the step leaves, or is an awaiter that was never on the stack, the net guards the function, and the landing says the stop may be another call's. The sentence no longer claims the engine lost the step: the pause's reason does not say, and nothing is decided on it. The awaiter is now found behind the empty `await` links V8 lists for a function's later awaits. Also from the review: a resume V8 refuses when the stack is gone reports where the step is instead of nothing; a pause asked for while a landing is being judged gets no further command and is reported as the pause. Unit: 95 cases (19 new, 14 of the file red on the stepper as committed). Real server: two new cases on async-steps.cjs, both red on the committed build: a step over a statement that awaits on later lines lands on its second await, and a step out of an async function in its first run lands in the call that awaits it with three calls in flight. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn69pXrYMWc1JUwv5v8 --- src/proxy/js-stepper.ts | 447 +++++++++++------- src/utils/error-messages.ts | 33 +- .../javascript-step-skipped-code.test.ts | 23 +- .../step-skipped-code/async-steps.cjs | 44 ++ tests/proxy/js-stepper.test.ts | 387 +++++++++++++-- 5 files changed, 688 insertions(+), 246 deletions(-) diff --git a/src/proxy/js-stepper.ts b/src/proxy/js-stepper.ts index a016b8437..ed934a9f1 100644 --- a/src/proxy/js-stepper.ts +++ b/src/proxy/js-stepper.ts @@ -24,34 +24,40 @@ * a timer tick later, which costs 12 ms a landing on Windows. * * NETS. V8 loses a step in two measured ways: when a frame is left through - * a `return` inside try...finally (issue #1161), and when js-debug resumes - * a pause of its own, a module-entry breakpoint, while the step is in - * flight (issue #1162). So where a step can leave a frame that way, it - * does not count on V8 alone to come BACK to the frame below. A net is a - * capped set of temporary CDP breakpoints on the break positions of a - * program frame the step returns to, kept with the stack depth of the - * activation it guards. Any position there is where V8's own step-out - * would stop, so a hit at that depth is a landing. + * a `return` inside try...finally within the run the step began in (issue + * #1161), and when js-debug resumes a pause of its own, a module-entry + * breakpoint, while the step is in flight (issue #1162). A net is a capped + * set of temporary CDP breakpoints on the break positions of the frame a + * step returns to, kept with the stack depth of the activation it guards. + * Any position there is where V8's own step-out would stop, so a hit at + * that depth is a landing. * - * A net is a safeguard, never a condition: when one cannot be set (V8 - * refuses break positions for Node's own scripts, which are program code - * on a skip list that leaves them out) the step goes on with V8 alone. + * ONE RULE says where a net is set, and it is applied in one place, before + * every command that can leave the frame on top (`guard`): * - * When: every step-out; a step-over or step-in from a function whose text - * has `finally`; a step that walks through skipped code. In a function - * that can SUSPEND (`await`, `yield` in its text) a step-over or step-in - * is netted only where it can leave through `finally`: on a `return` - * line, and from the first `finally` on. Anywhere else the function may - * merely suspend, its caller runs on, and a net there would stop in the - * caller while the step is still on its way to the next line. + * (a) Only where V8 can lose the step, and the frame cannot hand control + * down without returning. For a frame of the program that is read + * from its text: a `finally` clause, and from the paused line no way + * to suspend before the function exits (no `await` or `yield` ahead, + * and no loop that leads back to one). A function that suspends does + * not return: its caller runs on, and a net below would stop there + * while V8's own step is still on its way; and V8 keeps a step across + * an `await`, so nothing needs rescuing. Skipped code is netted + * without being read (V8 refuses the break positions of Node's own + * scripts, and Node's module loader has the shape): whichever way + * control comes down from it, the program frame below is the landing. * - * An async function the event loop resumed returns to its AWAITER, which - * is not on the stack (the pause's async parent, when V8 calls the link - * `await`; a `Promise.then` or timer parent only scheduled the code). - * V8's own async step finds the one awaiting call. A net there can only - * guard the awaiter's FUNCTION, and stops in whichever call of it runs - * next. So the awaiter is netted only where V8 loses the step (`finally` - * in the function being left), and a landing by that net says so. + * (b) A net names an activation only while that activation stays on the + * stack. A guarded frame that is itself waiting at an `await` when + * the step leaves has left the stack by the time anything stops, and + * an awaiter (the function awaiting an async one the event loop + * resumed: the pause's async parent, when V8 calls the link `await`) + * was never on it. There the net guards the FUNCTION, stops in + * whichever call of it runs next, and the landing says so. An + * awaiter is netted only where the loss is known from the text. + * + * A net is a safeguard, never a condition: when one cannot be set the step + * goes on with V8 alone. * * No net is put on the frame being stepped IN. V8 says `ambiguous` for any * breakpoint hit while a step is in flight, and it exposes no statement @@ -174,8 +180,14 @@ interface CdpPaused { callFrames: CdpCallFrame[]; reason: string; hitBreakpoints?: string[]; - /** `description` is V8's name for the link: `await`, `Promise.then`, `Timeout`, ... */ - asyncStackTrace?: { description?: string; callFrames?: CdpAsyncFrame[] }; + asyncStackTrace?: CdpAsyncTrace; +} + +/** One link of V8's async stack. `description` names it: `await`, `Promise.then`, `Timeout`, ... */ +interface CdpAsyncTrace { + description?: string; + callFrames?: CdpAsyncFrame[]; + parent?: CdpAsyncTrace; } interface Net { @@ -185,8 +197,12 @@ interface Net { fn: string; /** The stack depth of the guarded activation; Infinity for an awaiter, which resumes at any depth. */ depth: number; - /** Set on an awaiter's net: the function's name. Such a net guards the function, not one call of it. */ - awaiter?: string; + /** + * Set when the net cannot name one call of the function: the function's + * name. An awaiter is not on the stack; a guarded frame waiting at an + * `await` has left it by the time anything stops. + */ + anotherCall?: string; ids: Set; } @@ -194,26 +210,35 @@ type Inbox = | { type: 'paused'; pause: CdpPaused } | { type: 'resumed' }; -/** - * What the code on top returns to: something of the program's that now has a - * net; something of the program's without one (V8's own step goes on alone); - * or nothing of the program's at all. - */ -type ReturnTarget = 'armed' | 'unguarded' | 'nothing-below'; +/** What the code on top of a pause returns to. */ +type ReturnTarget = + /** A frame of the program on the stack, at this index. */ + | { kind: 'frame'; index: number } + /** The function of the program awaiting it, which is not on the stack. */ + | { kind: 'awaiter'; parent: CdpAsyncFrame } + /** Nothing of the program's. */ + | { kind: 'nothing' } + /** js-debug did not say, or the stack is deeper than was asked about. */ + | { kind: 'unknown' }; /** What a function's text says about how a step can leave it. */ interface FunctionShape { - /** `finally` in its text: the shape V8 loses a leaving step on (issue #1161). */ + /** A `finally` clause in its text: the shape V8 loses a leaving step on (issue #1161). */ hasFinally: boolean; - /** 0-based script line of the first `finally`. */ - finallyLine: number; - /** `await` or `yield` in its text: it can hand control to its caller without returning. */ - suspends: boolean; + /** 0-based script lines its text runs from and to. */ + from: number; + to: number; } /** How many frames of a stack js-debug is asked to mark, at most. */ const MAX_MARKED_FRAMES = 200; +/** How far past the sync frames js-debug is asked: the labels of the async segments and the awaiter's frame. */ +const ASYNC_MARKS = 12; + +/** A loop on a line of source: the only way execution goes back up a function's text. */ +const LOOPS = /\b(for|while|do)\b/; + /** * A `finally` clause on a line of source: after the closing brace of a try * or catch block, before its own opening brace, or alone on its line. Not @@ -247,14 +272,14 @@ interface Chain { walkedBeforeSteppingOut: number; /** Every command the chain may send is spent and skipped code is still on top. */ capped: boolean; - /** What the skipped code on top returns to, as last looked at. */ - below: ReturnTarget | null; + /** A step-in's walk found nothing of the program below the skipped code: not looked at again while it walks. */ + walkHasNothingBelow: boolean; /** The caller asked for a pause during the chain: the next stop is theirs. */ pauseRequested: boolean; /** That pause was taken on no breakpoint of js-debug's: it is reported as the pause it is. */ pauseTaken: boolean; - /** The landing came by an awaiter's net: the awaiting function's name. */ - caughtAtAwaiter: string | null; + /** The landing came by a net that cannot name one call: the guarded function's name. */ + caughtInFunction: string | null; /** Whether any pause the chain kept was a net's: what a late report of it looks like. */ netHits: boolean; startedAt: number; @@ -262,7 +287,8 @@ interface Chain { type Verdict = | { kind: 'wait' } - | { kind: 'command'; command: string } + /** `skipped`: the frame the command steps from is skipped code. */ + | { kind: 'command'; command: string; skipped: boolean } | { kind: 'landing'; by: string } | { kind: 'real-stop' } | { kind: 'left-stack' }; @@ -311,7 +337,9 @@ export class JsStepper { private owedNetHit = false; /** Scripts js-debug marked "Skipped by skipFiles": a script-level verdict, not asked again. */ private readonly skippedScripts = new Set(); - private readonly shapes = new Map(); + private readonly shapes = new Map(); + /** What each pause's top frame returns to: asked of js-debug once per pause. */ + private readonly targets = new WeakMap(); private readonly sources = new Map(); constructor(options: JsStepperOptions) { @@ -395,25 +423,19 @@ export class JsStepper { unwinding: false, walkedBeforeSteppingOut: 0, capped: false, - below: null, + walkHasNothingBelow: false, pauseRequested: false, pauseTaken: false, - caughtAtAwaiter: null, + caughtInFunction: null, netHits: false, startedAt: Date.now() }; this.chain = chain; this.owed = 0; - // A net before the first command only where V8 can lose the step by - // LEAVING the origin frame (issue #1161): a step-out always, a step-over - // or step-in where it can leave through `finally`. Not when it returns - // to itself: that net would sit in the frame being stepped in. Neither - // call can fail the step: a net is a safeguard. try { - if (kind === 'out' || await this.canLeaveThroughFinally(top)) { - await this.armReturnTarget(chain, origin, kind === 'out' ? null : chain.originFn); - } + // The one rule, before the first command as before every other. + await this.guard(chain, origin, await this.isSkipped(chain, origin)); await this.sendStep(chain, CDP_COMMAND[kind]); } catch (err) { await this.disarmAll(); @@ -521,6 +543,18 @@ export class JsStepper { await this.finish(chain, 'cancelled'); return; } + if (chain.pauseRequested) { + // The caller asked for a pause while this landing was being + // judged: V8 is paused, and this stop is theirs. + chain.pauseTaken = true; + await this.finish(chain, 'real-stop'); + return; + } + await this.guard(chain, pause, verdict.skipped); + if (chain.cancelled) { + await this.finish(chain, 'cancelled'); + return; + } await this.sendStep(chain, verdict.command); continue; } @@ -608,37 +642,28 @@ export class JsStepper { } if (skipped) { - const guarded = (): boolean => this.nets.some((net) => net.depth < depth || net.depth === Infinity); // A step-in walks on while it has budget, with or without anything // below: a step issued inside a dependency reaches the program's // handler by calls, not returns (issue #687). - const walking = chain.kind === 'in' && chain.spent < this.tunables.budget; - // Before anything else, a net on what this code returns to. A walk - // looks once (nothing of the program comes to be below without the - // walk landing in it first); a landing that has to step out looks for - // itself, because the awaiter of one frame is not the awaiter of the next. - if (!guarded() && (chain.below === null || !walking)) { - chain.below = await this.armReturnTarget(chain, pause, null); - } - if (walking) { + if (chain.kind === 'in' && chain.spent < this.tunables.budget) { chain.spent++; - return { kind: 'command', command: CDP_COMMAND.in }; + return { kind: 'command', command: CDP_COMMAND.in, skipped: true }; } - // It has to step out now. With nothing of the program below, the stack - // the step started on is gone. - if (!guarded() && chain.below === 'nothing-below') { + // It has to step out now. With nothing of the program below (no frame, + // no awaiter), the stack the step started on is gone. + if (!this.guardedBelow(depth) && (await this.returnTarget(chain, pause)).kind === 'nothing') { return { kind: 'left-stack' }; } if (chain.kind === 'in' && chain.walkedBeforeSteppingOut === 0) { chain.walkedBeforeSteppingOut = chain.commands.filter((sent) => sent === CDP_COMMAND.in).length; } - return { kind: 'command', command: CDP_COMMAND.out }; + return { kind: 'command', command: CDP_COMMAND.out, skipped: true }; } // Program code on top. if (chain.unwinding) { return depth > chain.originDepth - ? { kind: 'command', command: CDP_COMMAND.out } + ? { kind: 'command', command: CDP_COMMAND.out, skipped: false } : { kind: 'landing', by: 'V8 step-outs after a net was dropped (recursion)' }; } const backOnOriginStatement = depth === chain.originDepth && fnKey(top) === chain.originFn && top.location.lineNumber === chain.originLine; @@ -647,7 +672,7 @@ export class JsStepper { // again: that enters the line's next call, or moves on. if (chain.kind === 'in' && backOnOriginStatement && chain.reissues < this.tunables.reissueCap) { chain.reissues++; - return { kind: 'command', command: CDP_COMMAND.in }; + return { kind: 'command', command: CDP_COMMAND.in, skipped: false }; } return { kind: 'landing', by: 'V8 step' }; } @@ -660,7 +685,7 @@ export class JsStepper { // The frame being left is the same function as its caller (recursion) // and is still running: step out again. chain.reissues++; - return { kind: 'command', command: CDP_COMMAND.out }; + return { kind: 'command', command: CDP_COMMAND.out, skipped: false }; } // The net fired in a deeper activation than the one it guards. Drop it; // V8's own step-outs from here, until the depth is the origin's. @@ -671,16 +696,17 @@ export class JsStepper { if (depth <= chain.originDepth) { return { kind: 'landing', by: 'net dropped (recursion)' }; } - return { kind: 'command', command: CDP_COMMAND.out }; + return { kind: 'command', command: CDP_COMMAND.out, skipped: false }; } // Control is back in a frame a net guards: where V8's own step-out would stop. if (chain.kind === 'in' && backOnOriginStatement && chain.reissues < this.tunables.reissueCap) { chain.reissues++; - return { kind: 'command', command: CDP_COMMAND.in }; + return { kind: 'command', command: CDP_COMMAND.in, skipped: false }; } - // An awaiter's net guards the function, not the one call that awaited. - chain.caughtAtAwaiter = guarding.find((net) => net.awaiter !== undefined)?.awaiter ?? null; - return { kind: 'landing', by: pause.reason === 'ambiguous' ? 'net, with a V8 step in flight' : 'net, V8 had lost the step' }; + // A net that cannot name one call of the function it guards says so. + chain.caughtInFunction = guarding.find((net) => net.anotherCall !== undefined)?.anotherCall ?? null; + // The pause's reason does not say whether V8 had lost the step: it is logged, and nothing is decided on it. + return { kind: 'landing', by: `net (${pause.reason})` }; } /** @@ -759,7 +785,9 @@ export class JsStepper { } } - private async finish(chain: Chain, ender: 'landing' | 'real-stop' | 'left-stack' | 'cancelled' | 'error', by?: string): Promise { + private async finish(chain: Chain, ended: 'landing' | 'real-stop' | 'left-stack' | 'cancelled' | 'error', why?: string): Promise { + let ender = ended; + let by = why; // Where the step is, for what its answer may say about it. const landed = this.current; const backInOriginFrame = landed !== null && landed.callFrames.length === chain.originDepth && @@ -772,6 +800,11 @@ export class JsStepper { await this.cdp?.send('Debugger.resume', {}); } catch (err) { logger.warn(`[JsStepper] resume after leaving the stack failed: ${errorText(err)}`); + if (this.current !== null) { + // V8 is still paused: the caller hears of the stop it can see. + ender = 'landing'; + by = 'where it was: V8 refused the resume'; + } } } const reports = ender === 'landing' || ender === 'real-stop'; @@ -814,18 +847,27 @@ export class JsStepper { ...this.landingNote(chain, backInOriginFrame) } }); + } else if (ender === 'real-stop' && chain.pauseTaken) { + // The pause the caller asked for. js-debug may call it a breakpoint + // that names none (it was taken on a net's position), or may not have + // reported it yet: it leaves as the pause it is. + const body = { ...((chain.lastStopped?.body ?? {}) as Record) }; + delete body.hitBreakpointIds; + delete body.text; + this.deliver({ + seq: 0, + type: 'event', + event: 'stopped', + body: { + allThreadsStopped: false, + ...body, + threadId: (body.threadId as number | undefined) ?? chain.threadId ?? 0, + reason: 'pause', + description: 'Paused' + } + }); } else if (ender === 'real-stop' && chain.lastStopped) { - const stop = chain.lastStopped; - if (chain.pauseTaken) { - // The pause the caller asked for. js-debug may call it a breakpoint - // that names none (it was taken on a net's position): it leaves as - // the pause it is. - const body = { ...((stop.body ?? {}) as Record) }; - delete body.hitBreakpointIds; - this.deliver({ ...stop, body: { ...body, reason: 'pause', description: 'Paused' } }); - } else { - this.deliver(stop); - } + this.deliver(chain.lastStopped); } } @@ -838,8 +880,8 @@ export class JsStepper { if (chain.capped) { return { text: ErrorMessages.stepStillInSkippedCode(chain.commands.length) }; } - if (chain.caughtAtAwaiter !== null) { - return { text: ErrorMessages.stepCaughtAtAwaitingFunction(chain.caughtAtAwaiter) }; + if (chain.caughtInFunction !== null) { + return { text: ErrorMessages.stepCaughtWhereItReturns(chain.caughtInFunction) }; } if (chain.walkedBeforeSteppingOut > 0 && backInOriginFrame) { return { text: ErrorMessages.stepIntoReachedNoProgramCode(chain.walkedBeforeSteppingOut) }; @@ -953,31 +995,26 @@ export class JsStepper { /** * What the text of the frame's function says about how a step can leave - * it. Read from the function's own lines only. Never throws: a text that - * cannot be read is a function with nothing to guard. + * it; null when it cannot be read (V8 refuses the break positions of + * Node's own scripts). The text is the function's own lines, nested + * functions and comments included: a text test, not a parse. Never throws. */ - private async shapeOf(frame: CdpCallFrame): Promise { + private async shapeOf(frame: CdpCallFrame): Promise { const key = fnKey(frame); - const known = this.shapes.get(key); - if (known) { - return known; + if (this.shapes.has(key)) { + return this.shapes.get(key) ?? null; } - let shape: FunctionShape = { hasFinally: false, finallyLine: -1, suspends: false }; + let shape: FunctionShape | null = null; try { const lines = await this.linesOf(frame.location.scriptId); const all = await this.locationsOf(frame); if (all.length > 0) { const from = Math.min(frame.functionLocation?.lineNumber ?? all[0].lineNumber, all[0].lineNumber); - const text = lines.slice(from, all[all.length - 1].lineNumber + 1); - const at = text.findIndex((line) => FINALLY_CLAUSE.test(line)); - shape = { - hasFinally: at !== -1, - finallyLine: at === -1 ? -1 : from + at, - suspends: text.some((line) => SUSPENDS.test(line)) - }; + const to = all[all.length - 1].lineNumber; + shape = { hasFinally: lines.slice(from, to + 1).some((line) => FINALLY_CLAUSE.test(line)), from, to }; } } catch (err) { - logger.warn(`[JsStepper] could not read the function's text: ${errorText(err)}`); + logger.debug(`[JsStepper] could not read the function's text: ${errorText(err)}`); } this.shapes.set(key, shape); return shape; @@ -994,102 +1031,144 @@ export class JsStepper { } /** - * Whether a step-over or step-in from this frame's position can leave the - * function through `finally`, the shape V8 loses the step on (issue #1161). - * In a function that cannot suspend, anywhere: the frame below is only - * reached by returning. In one that can (`await`, `yield`), only on a - * `return` line and from the first `finally` on, and never on a line - * that itself awaits or yields: there the function suspends first, its - * caller runs on, and a net below would stop in the caller while the - * step is still on its way to the next line. (So a step over an `await` - * that is the last thing a function does before it leaves through - * `finally` is V8's own, and V8 loses it.) + * Rule (a), for a frame of the program: whether V8 can lose a step that + * leaves this frame from its paused line (issue #1161). Its function has a + * `finally` clause, and from here it cannot suspend before it exits: no + * `await` or `yield` from the paused line to its end, and no loop above + * that leads back to one. A function that can still suspend is V8's own: + * measured, V8 keeps a step across an `await` and lands in the awaiting + * function even when the function then leaves through `finally`. */ - private async canLeaveThroughFinally(frame: CdpCallFrame): Promise { + private async canLoseALeavingStep(frame: CdpCallFrame): Promise { const shape = await this.shapeOf(frame); - if (!shape.hasFinally) { + if (!shape?.hasFinally) { return false; } - if (!shape.suspends) { - return true; - } + const lines = this.sources.get(frame.location.scriptId) ?? []; const line = frame.location.lineNumber; - const text = this.sources.get(frame.location.scriptId)?.[line] ?? ''; - if (SUSPENDS.test(text)) { + if (lines.slice(line, shape.to + 1).some((text) => SUSPENDS.test(text))) { return false; } - return line >= shape.finallyLine || /\breturn\b/.test(text); + const above = lines.slice(shape.from, line); + return !(above.some((text) => LOOPS.test(text)) && above.some((text) => SUSPENDS.test(text))); + } + + /** Whether a net guards something below a pause of this depth. */ + private guardedBelow(depth: number): boolean { + return this.nets.some((net) => net.depth < depth || net.depth === Infinity); } /** - * Arm a net on what the top frame of `pause` returns to. - * - * The nearest program frame below, by js-debug's marks: that activation, - * by its depth. With none on the stack, the awaiter of an async function - * the event loop resumed (the async parent, when V8 calls the link - * `await`): V8's own async step finds that one call, so it is netted only - * where V8 loses the step, `finally` in the function being left, and that - * net guards the awaiter's function in whichever call runs next. - * - * Never throws. A net is a safeguard: whatever goes wrong (V8 refuses - * break positions for Node's own scripts; js-debug does not answer), the - * answer is `unguarded` and V8's own step goes on alone. + * THE ONE RULE (see the head of this file), applied before every command + * that can leave the frame on top of `pause`: a net on what that frame + * returns to, where V8 can lose the step. Never throws: a net is a + * safeguard, and without one V8's own step goes on alone. */ - private async armReturnTarget(chain: Chain, pause: CdpPaused, notFn: string | null): Promise { + private async guard(chain: Chain, pause: CdpPaused, skipped: boolean): Promise { try { const frames = pause.callFrames; - // Every sync frame, the label of the first async segment, and its first frame. - const marks = await this.marks(chain, Math.min(frames.length + 2, MAX_MARKED_FRAMES)); - if (typeof marks === 'string') { - logger.warn(`[JsStepper] could not read the stack's marks (${marks}); V8's own step goes on alone`); - return 'unguarded'; + const top = frames[0]; + if (this.guardedBelow(frames.length) || (skipped && chain.walkHasNothingBelow)) { + return; } - // js-debug lists the sync frames, then a label frame per async segment. - const firstLabel = marks.findIndex((frame) => markOf(frame) === 'label'); - const sync = firstLabel === -1 ? marks : marks.slice(0, firstLabel); - for (let i = 1; i < Math.min(sync.length, frames.length); i++) { - if (markOf(sync[i]) === 'deemphasize') { - continue; - } - if (notFn && fnKey(frames[i]) === notFn) { + // (a) A frame of the program is read. Skipped code is not. + if (!skipped && !(await this.canLoseALeavingStep(top))) { + return; + } + const target = await this.returnTarget(chain, pause); + if (target.kind === 'frame') { + const frame = frames[target.index]; + if (chain.kind !== 'out' && fnKey(frame) === fnKey(top)) { // It returns to itself (recursion): a net would sit in the frame being stepped in. - return 'unguarded'; + return; } - const armed = await this.arm(await this.locationsOf(frames[i]), frames[i].location, { - name: frames[i].functionName || '(anonymous)', - fn: fnKey(frames[i]), - depth: frames.length - i + const name = frame.functionName || '(anonymous)'; + // (b) A guarded frame waiting at an await leaves the stack before anything stops. + const waiting = SUSPENDS.test((await this.linesOf(frame.location.scriptId))[frame.location.lineNumber] ?? ''); + await this.arm(await this.locationsOf(frame), frame.location, { + name, + fn: fnKey(frame), + depth: frames.length - target.index, + ...(waiting ? { anotherCall: name } : {}) }); - return armed ? 'armed' : 'unguarded'; - } - if (firstLabel === -1 && sync.length < frames.length) { - // A deeper stack than was asked about: what is under it is not known. - return 'unguarded'; - } - // No program frame below on this stack. - const parent = pause.asyncStackTrace?.callFrames?.[0]; - const firstAsync = firstLabel === -1 ? undefined : marks[firstLabel + 1]; - const awaitedByTheProgram = pause.asyncStackTrace?.description === 'await' && parent !== undefined && - firstAsync !== undefined && markOf(firstAsync) !== 'deemphasize' && markOf(firstAsync) !== 'label'; - if (!awaitedByTheProgram) { - return 'nothing-below'; - } - if (!(await this.shapeOf(frames[0])).hasFinally) { - // V8's own async step finds the one awaiting call. - return 'unguarded'; + } else if (target.kind === 'awaiter') { + // (b) An awaiter's net can never name the call: only where the loss is known from the text. + if (skipped && !(await this.canLoseALeavingStep(top))) { + return; + } + const parent = target.parent; + const start: CdpLocation = { scriptId: parent.scriptId, lineNumber: parent.lineNumber, columnNumber: parent.columnNumber }; + const name = parent.functionName || '(anonymous)'; + await this.arm(await this.possible(start), start, { + name: `${name} (awaiter)`, + fn: `async:${parent.scriptId}:${parent.lineNumber}:${parent.columnNumber}`, + depth: Infinity, + anotherCall: name + }); + } else if (target.kind === 'nothing' && skipped && chain.kind === 'in') { + // Nothing of the program comes to be below without the walk landing in it first. + chain.walkHasNothingBelow = true; } - const start: CdpLocation = { scriptId: parent.scriptId, lineNumber: parent.lineNumber, columnNumber: parent.columnNumber }; - const name = parent.functionName || '(anonymous)'; - const armed = await this.arm(await this.possible(start), start, { - name: `${name} (awaiter)`, - fn: `async:${parent.scriptId}:${parent.lineNumber}:${parent.columnNumber}`, - depth: Infinity, - awaiter: name - }); - return armed ? 'armed' : 'unguarded'; } catch (err) { logger.warn(`[JsStepper] no net for this step, V8's own step goes on alone: ${errorText(err)}`); - return 'unguarded'; } } + + /** What the top frame of `pause` returns to; js-debug is asked once per pause. Never throws. */ + private async returnTarget(chain: Chain, pause: CdpPaused): Promise { + const known = this.targets.get(pause); + if (known) { + return known; + } + let target: ReturnTarget = { kind: 'unknown' }; + try { + target = await this.findReturnTarget(chain, pause); + } catch (err) { + logger.warn(`[JsStepper] could not tell what the stack returns to: ${errorText(err)}`); + } + this.targets.set(pause, target); + return target; + } + + /** + * The nearest frame of the program below the top one, by js-debug's marks. + * With none on the stack, the function awaiting an async one the event + * loop resumed: the first frame of V8's async stack, when every link down + * to it is an `await` (a `Promise.then` or timer link only scheduled the + * code on top) and js-debug marks it program code. + */ + private async findReturnTarget(chain: Chain, pause: CdpPaused): Promise { + const frames = pause.callFrames; + const asked = Math.min(frames.length + ASYNC_MARKS, MAX_MARKED_FRAMES); + const marks = await this.marks(chain, asked); + if (typeof marks === 'string') { + logger.warn(`[JsStepper] could not read the stack's marks (${marks})`); + return { kind: 'unknown' }; + } + // js-debug lists the sync frames, then a label frame per async segment and that segment's frames. + const firstLabel = marks.findIndex((frame) => markOf(frame) === 'label'); + const sync = firstLabel === -1 ? marks : marks.slice(0, firstLabel); + for (let i = 1; i < Math.min(sync.length, frames.length); i++) { + if (markOf(sync[i]) !== 'deemphasize') { + return { kind: 'frame', index: i }; + } + } + if (firstLabel === -1) { + // No async part was listed: the stack ends here, unless it is deeper than was asked about. + return marks.length >= asked ? { kind: 'unknown' } : { kind: 'nothing' }; + } + let link = pause.asyncStackTrace; + while (link && link.description === 'await' && !link.callFrames?.length) { + link = link.parent; + } + const parent = link?.description === 'await' ? link.callFrames?.[0] : undefined; + if (!parent) { + return { kind: 'nothing' }; + } + const awaiter = marks.slice(firstLabel).find((frame) => markOf(frame) !== 'label'); + if (!awaiter) { + return { kind: 'unknown' }; + } + return markOf(awaiter) === 'deemphasize' ? { kind: 'nothing' } : { kind: 'awaiter', parent }; + } } diff --git a/src/utils/error-messages.ts b/src/utils/error-messages.ts index 7aba89ee6..88f4e02bc 100644 --- a/src/utils/error-messages.ts +++ b/src/utils/error-messages.ts @@ -306,23 +306,25 @@ export const ErrorMessages = { : `${stepped} in ${steps} steps: this adapter stops once per expression on a line, so the step was repeated until the line changed.`, /** - * The sentence on a step that left an async function through try...finally and - * was caught at the awaiting function (issues #1130, #1161) - * Occurs when: V8 loses a step that leaves a function through `finally`, so - * the proxy's JavaScript stepper set its net on the function that awaits it. - * An awaiter is not on the stack, so the net guards the FUNCTION: with - * several calls of it in flight, the one that ran next is where the step - * stopped. The caller must not take its variables for the awaited call's - * without looking. + * The sentence on a step caught by a temporary breakpoint that cannot name + * one call of the function it is in (issues #1130, #1161) + * Occurs when: the engine can lose a step that leaves a function through + * try...finally, so the proxy's JavaScript stepper set temporary + * breakpoints on the function the step returns to. That function was + * waiting at an `await` (its frame was not on the stack, or left it before + * anything stopped), so the breakpoints guard the FUNCTION: with several + * calls of it in flight, the one that ran next is where the step stopped. + * It does not say the engine lost this step: that cannot be told. * Used in: src/proxy/js-stepper.ts (the `text` of the step's stopped * event), appended to the step's message by * src/session/execution/execution-controller.ts - * @param awaiter - The awaiting function's name + * @param fn - The name of the function the step returns to */ - stepCaughtAtAwaitingFunction: (awaiter: string) => - `The engine loses a step that leaves a function through try...finally, so this step was caught where the ` + - `awaiting function, ${awaiter}, next ran. If several calls of ${awaiter} are in flight, this stop may be in ` + - `another call's continuation than the one that awaited the function you stepped out of: check its variables.`, + stepCaughtWhereItReturns: (fn: string) => + `This step was caught by a temporary breakpoint in ${fn}, the function it returns to, because the engine can ` + + `lose a step that leaves a function through try...finally. ${fn} was waiting at an await meanwhile, so if ` + + `several calls of ${fn} are in flight this stop may be in another of them than the one the step returns to: ` + + 'check its variables.', /** * The sentence on a step_into that reached no code of the program (issue #1130) @@ -340,8 +342,9 @@ export const ErrorMessages = { stepIntoReachedNoProgramCode: (stepIns: number) => `step_into walked ${stepIns} engine steps into the call on that line and was still in skipped code ` + '(Node internals, node_modules, or files on skipFiles), so it stepped back out and the rest of the line ran ' + - 'as a step over runs it. Code of yours that the call reaches further in (a module it loads, a late callback) ' + - 'ran without stopping: a breakpoint there stops in it. To stop inside the skipped code instead, turn ' + + 'as a step over runs it. Code of yours that the call runs further in (a module it loads) or only schedules ' + + '(a timer or promise callback) does not stop the step: a breakpoint there stops in it. To stop inside the ' + + 'skipped code instead, turn ' + 'stepping through it off: justMyCode: false on a launch, smartStep: false on a launch or an attach.', /** diff --git a/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts b/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts index a79a79441..dafe76f9e 100644 --- a/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts +++ b/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts @@ -249,7 +249,28 @@ describe('The server\'s JavaScript stepper against a real js-debug (issues #1130 // function, and the answer says what that can and cannot promise. const out = await step('step_over'); expectAsyncLanding(out, 'after closing'); - expect(out.message).toBe(`Stepped over. ${ErrorMessages.stepCaughtAtAwaitingFunction('main')}`); + expect(out.message).toBe(`Stepped over. ${ErrorMessages.stepCaughtWhereItReturns('main')}`); + }, 60000); + + it('step_over on a statement that awaits on a later line stays in the function: its caller runs on, and is not where the step stops', async () => { + await asyncPausedAt('a statement that awaits on later lines'); + // The function has a finally clause above, and the paused line itself + // awaits nothing. A temporary breakpoint on the caller stopped the step + // at the caller's next statement, the moment this function suspended. + const answer = await step('step_over'); + expectAsyncLanding(answer, 'the second await of the statement'); + expect(answer.message).toBe('Stepped over'); + }, 60000); + + it('step_out of an async function still in its first run lands in the call that awaits it, with other calls in flight', async () => { + await asyncPausedAt('in early, before its first await', { condition: 'id === 2' }); + const answer = await step('step_out'); + expectAsyncLanding(answer, 'the continuation of relay'); + // A temporary breakpoint on `relay`, kept by depth, stopped in relay(3) + // as it was entered: relay(2) had left the stack at its own await. + const id = await server!.call('evaluate_expression', { expression: 'id' }); + expect(id.result, JSON.stringify(id)).toBe('2'); + expect(answer.message).toBe('Stepped out'); }, 60000); it('step_out of a .then callback resumes the program: what registered the callback is not what it returns to', async () => { diff --git a/tests/fixtures/javascript/step-skipped-code/async-steps.cjs b/tests/fixtures/javascript/step-skipped-code/async-steps.cjs index 93fb7b865..5fcec5555 100644 --- a/tests/fixtures/javascript/step-skipped-code/async-steps.cjs +++ b/tests/fixtures/javascript/step-skipped-code/async-steps.cjs @@ -34,6 +34,41 @@ async function closing() { } } +async function getUser(id) { + await sleep(5); + return { id }; +} + +async function load(id) { + try { + globalThis.loading = id; + } finally { + globalThis.loading = 0; + } + const first = id + 1; + return { // MARK: a statement that awaits on later lines + user: await getUser(first), + posts: await getUser(first + 1), // MARK: the second await of the statement + }; +} + +let releaseEarly; +const earlyGate = new Promise((resolve) => { + releaseEarly = resolve; +}); + +async function early(id) { + const tag = id; // MARK: in early, before its first await + await earlyGate; + return tag; +} + +async function relay(id) { + const got = await early(id); + const out = got * 10; // MARK: the continuation of relay + return out; +} + function onDone(value) { const seen = value; // MARK: in a then callback return seen; @@ -50,6 +85,15 @@ async function main() { await all; await closing(); // MARK: awaits closing const afterClosing = 1; // MARK: after closing + // The caller does not await the call at once: it runs on while load is suspended. + const loading = load(1); + const marker = 2; // MARK: the statement of the caller after load + await loading; + // Three calls of relay in flight at once, each awaiting its own early. + const relays = Promise.all([relay(1), relay(2), relay(3)]); + releaseEarly(); + await relays; + globalThis.marker = marker; Promise.resolve(7).then(onDone); setTimeout(onTimer, 10); await sleep(150); diff --git a/tests/proxy/js-stepper.test.ts b/tests/proxy/js-stepper.test.ts index 2fd80587f..7b465531c 100644 --- a/tests/proxy/js-stepper.test.ts +++ b/tests/proxy/js-stepper.test.ts @@ -44,7 +44,11 @@ interface ScriptedPause { * (the default: the function on top returns to it), `Promise.then`, * `Timeout` (it only scheduled the code on top). */ - asyncParent?: { fn: string; script?: string; line: number; col?: number; skipped?: boolean; description?: string }; + asyncParent?: { + fn: string; script?: string; line: number; col?: number; skipped?: boolean; description?: string; + /** `await` links with no frames before the one that has the awaiter (V8 lists them for later awaits). */ + emptyLinks?: number; + }; } interface ArmedBreakpoint { @@ -198,22 +202,21 @@ class Engine extends EventEmitter { functionLocation: { scriptId: f.script ?? 'app', lineNumber: fnLineOf(f), columnNumber: 0 }, location: { scriptId: f.script ?? 'app', lineNumber: f.line, columnNumber: f.col ?? 0 } })), - ...(pause.asyncParent - ? { - asyncStackTrace: { - description: pause.asyncParent.description ?? 'await', - callFrames: [{ - functionName: pause.asyncParent.fn, - scriptId: pause.asyncParent.script ?? 'app', - lineNumber: pause.asyncParent.line, - columnNumber: pause.asyncParent.col ?? 0 - }] - } - } - : {}) + ...(pause.asyncParent ? { asyncStackTrace: this.asyncTrace(pause.asyncParent) } : {}) }; } + private asyncTrace(parent: NonNullable): Record { + let trace: Record = { + description: parent.description ?? 'await', + callFrames: [{ functionName: parent.fn, scriptId: parent.script ?? 'app', lineNumber: parent.line, columnNumber: parent.col ?? 0 }] + }; + for (let i = 0; i < (parent.emptyLinks ?? 0); i++) { + trace = { description: 'await', callFrames: [], parent: trace }; + } + return trace; + } + /** js-debug's `stackTrace` answer for the pause V8 is in. */ stackTrace(levels: number): DebugProtocol.StackTraceResponse { this.stackTraceCalls.push(levels); @@ -235,6 +238,9 @@ class Engine extends EventEmitter { }); const frames = pause.frames.map(mark); if (pause.asyncParent) { + for (let i = 0; i < (pause.asyncParent.emptyLinks ?? 0); i++) { + frames.push({ id: 890 + i, name: 'await', line: 0, column: 0, presentationHint: 'label' }); + } frames.push({ id: 900, name: pause.asyncParent.description ?? 'await', line: 0, column: 0, presentationHint: 'label' }); frames.push(mark(pause.asyncParent, 901)); } @@ -271,8 +277,35 @@ describe('JsStepper (issue #1130)', () => { await tick(12); } + /** Lines set in each script's text so far in this test (0-based). */ + let written: Map>; + + /** Set lines of a script's text, keeping the ones set before. */ + function sourceWith(lines: Record, script = 'app'): void { + const known = written.get(script) ?? new Map(); + written.set(script, known); + for (const [line, text] of Object.entries(lines)) { + known.set(Number(line), text); + } + const source = Array.from({ length: 2000 }, () => 'x();'); + for (const [line, text] of known) { + source[line] = text; + } + engine.sources.set(script, source.join('\n')); + } + + /** + * The frame, with a `finally` clause in its function's text below its + * line and nothing that suspends: the shape V8 loses a leaving step on. + */ + function lossy(frame: Frame): Frame { + sourceWith({ [frame.line + 5]: '} finally { done(); }' }, frame.script ?? 'app'); + return frame; + } + beforeEach(() => { engine = new Engine(); + written = new Map(); delivered = []; seen = []; stepper = new JsStepper({ @@ -382,9 +415,10 @@ describe('JsStepper (issue #1130)', () => { ]; await stepper.request('stepIn', { threadId: 1 }); await settled(); - // One levels-1 question for the node script, one for the landing; the - // levels-80 one is the net's look at the whole stack. - expect(engine.stackTraceCalls.filter((levels) => levels === 1)).toHaveLength(2); + // One levels-1 question for the frame the step starts from, one for + // the node script, one for the landing; the longer one is the look at + // the whole stack for the net. + expect(engine.stackTraceCalls.filter((levels) => levels === 1)).toHaveLength(3); }); it('asks again each time for a frame skipped for its position, not its script', async () => { @@ -397,7 +431,7 @@ describe('JsStepper (issue #1130)', () => { ]; await stepper.request('stepIn', { threadId: 1 }); await settled(); - expect(engine.stackTraceCalls.filter((levels) => levels === 1)).toHaveLength(3); + expect(engine.stackTraceCalls.filter((levels) => levels === 1)).toHaveLength(4); expect(stopped()).toMatchObject({ reason: 'step' }); }); @@ -541,7 +575,7 @@ describe('JsStepper (issue #1130)', () => { describe('nets: a step never counts on V8 alone to come back to a frame (issue #1161)', () => { it('step_out arms the frame it returns to before the first command, and lands by the net when V8 never pauses', async () => { - engine.pauseAt({ frames: frames(app('withFinally', 5), app('caller', 14)) }); + engine.pauseAt({ frames: frames(lossy(app('withFinally', 5)), app('caller', 14)) }); // V8's step-out is lost; the next thing V8 says is the net's breakpoint. engine.script = [{ frames: frames(app('caller', 15)), reason: 'other', hits: (armed) => [armed[1].id] }]; await stepper.request('stepOut', { threadId: 1 }); @@ -595,7 +629,7 @@ describe('JsStepper (issue #1130)', () => { it('a net hit deeper than the frame it guards is not a landing: a step-out of a recursive function steps out again', async () => { const start = fnLineOf(app('down', 0)); - engine.pauseAt({ frames: frames(app('down', start + 3), app('down', start + 5), app('main', 10)) }); + engine.pauseAt({ frames: frames(lossy(app('down', start + 3)), app('down', start + 5), app('main', 10)) }); engine.script = [ // The frame being left runs on to its own finally block: a net position, one frame too deep. { frames: frames(app('down', start + 7), app('down', start + 5), app('main', 10)), reason: 'ambiguous', hits: (armed) => [armed[0].id] }, @@ -611,7 +645,7 @@ describe('JsStepper (issue #1130)', () => { it('caps a net, and wraps to the function\'s start when the frame is near its end', async () => { const start = fnLineOf(app('wrap', 0)); engine.positions.set(`app:${start}`, Array.from({ length: 300 }, (_, i) => ({ lineNumber: start + i }))); - engine.pauseAt({ frames: frames(app('leaf', 5), app('wrap', start + 290)) }); + engine.pauseAt({ frames: frames(lossy(app('leaf', 5)), app('wrap', start + 290)) }); engine.script = [{ frames: frames(app('wrap', start + 291)) }]; await stepper.request('stepOut', { threadId: 1 }); await settled(); @@ -627,7 +661,7 @@ describe('JsStepper (issue #1130)', () => { it('caps a net, and takes it from the frame\'s own position on', async () => { const start = fnLineOf(app('big', 0)); engine.positions.set(`app:${start}`, Array.from({ length: 300 }, (_, i) => ({ lineNumber: start + i }))); - engine.pauseAt({ frames: frames(app('leaf', 5), app('big', start + 200)) }); + engine.pauseAt({ frames: frames(lossy(app('leaf', 5)), app('big', start + 200)) }); engine.script = [{ frames: frames(app('big', start + 201)) }]; await stepper.request('stepOut', { threadId: 1 }); await settled(); @@ -645,7 +679,7 @@ describe('JsStepper (issue #1130)', () => { const moduleStart = fnLineOf(app('(module)', 0)); engine.positions.set(`app:${moduleStart}`, [{ lineNumber: moduleStart + 1 }, { lineNumber: moduleStart + 2 }]); engine.positions.set('app:900', [{ lineNumber: 900 }, { lineNumber: 901 }, { lineNumber: 902 }]); - engine.pauseAt({ frames: frames(app('callee', 5), app('(module)', 900, { fnLine: moduleStart })) }); + engine.pauseAt({ frames: frames(lossy(app('callee', 5)), app('(module)', 900, { fnLine: moduleStart })) }); engine.script = [{ frames: frames(app('(module)', 901, { fnLine: moduleStart })) }]; await stepper.request('stepOut', { threadId: 1 }); await settled(); @@ -682,7 +716,7 @@ describe('JsStepper (issue #1130)', () => { }); stepper.attachCdp(engine); stepper.setEnabled(true); - engine.pauseAt({ frames: frames(app('leaf', 5), app('caller', 14)) }); + engine.pauseAt({ frames: frames(lossy(app('leaf', 5)), app('caller', 14)) }); await stepper.request('stepOut', { threadId: 1 }); await settled(); expect(stopped()).toMatchObject({ reason: 'exception' }); @@ -727,10 +761,11 @@ describe('JsStepper (issue #1130)', () => { it('asks again while js-debug says it is not paused yet', async () => { engine.pauseAt({ frames: frames(app('main', 10)) }); engine.script = [{ frames: frames(app('main', 11)) }]; - engine.stackTraceFailures = 2; await stepper.request('next', { threadId: 1 }); + engine.stackTraceFailures = 2; await settled(); - expect(engine.stackTraceCalls).toEqual([1, 1, 1]); + // One for the frame the step started from, three for the landing. + expect(engine.stackTraceCalls).toEqual([1, 1, 1, 1]); expect(stopped()).toMatchObject({ reason: 'step' }); }); @@ -761,7 +796,7 @@ describe('JsStepper (issue #1130)', () => { describe('what ends a step still in flight', () => { async function stepOutAndRun(): Promise { - engine.pauseAt({ frames: frames(app('work', 9), app('main', 14)) }); + engine.pauseAt({ frames: frames(lossy(app('work', 9)), app('main', 14)) }); engine.script = ['runs']; await stepper.request('stepOut', { threadId: 1 }); await tick(10); @@ -838,15 +873,6 @@ describe('JsStepper (issue #1130)', () => { stepper.setEnabled(true); } - /** The text of a script, with these 0-based lines set. */ - function sourceWith(lines: Record, script = 'app'): void { - const source = Array.from({ length: 2000 }, () => 'x();'); - for (const [line, text] of Object.entries(lines)) { - source[Number(line)] = text; - } - engine.sources.set(script, source.join('\n')); - } - /** How many net breakpoints were set in V8 when each step command went out. */ function armedAtEachStep(): number[] { const counts: number[] = []; @@ -866,7 +892,7 @@ describe('JsStepper (issue #1130)', () => { it('serves the step with V8 alone when V8 refuses break positions for the frame it returns to', async () => { engine.refuse.add('node:timers'); - engine.pauseAt({ frames: frames(app('onTimer', 5), timers('listOnTimeout', 605), timers('processTimers', 541)) }); + engine.pauseAt({ frames: frames(lossy(app('onTimer', 5)), timers('listOnTimeout', 605), timers('processTimers', 541)) }); engine.script = [{ frames: frames(timers('listOnTimeout', 609), timers('processTimers', 541)) }]; const response = await stepper.request('stepOut', { threadId: 1 }); @@ -905,7 +931,7 @@ describe('JsStepper (issue #1130)', () => { }); it('a first command V8 refuses leaves no net behind', async () => { - engine.pauseAt({ frames: frames(app('leaf', 5), app('caller', 14)) }); + engine.pauseAt({ frames: frames(lossy(app('leaf', 5)), app('caller', 14)) }); engine.failOnce = 'Debugger.stepOut'; await expect(stepper.request('stepOut', { threadId: 1 })).rejects.toThrow(/refused/); // The net on the caller was set before the command, and is gone. @@ -916,7 +942,7 @@ describe('JsStepper (issue #1130)', () => { it('counts a net with no breakpoint set as no net', async () => { engine.failAlways.add('Debugger.setBreakpoint'); - engine.pauseAt({ frames: frames(app('leaf', 5), app('caller', 14)) }); + engine.pauseAt({ frames: frames(lossy(app('leaf', 5)), app('caller', 14)) }); engine.script = ['runs']; await stepper.request('stepOut', { threadId: 1 }); await tick(5); @@ -968,7 +994,7 @@ describe('JsStepper (issue #1130)', () => { it('nets the awaiting function only where V8 loses the step (`finally` in the function left), and says the stop may be another call\'s', async () => { const start = fnLineOf(app('innerF', 0)); - sourceWith({ [start + 1]: 'try {', [start + 2]: ' await gate; return tag;', [start + 3]: '} finally { noop(); }' }); + sourceWith({ [start + 1]: 'try { await gate;', [start + 2]: ' const tag = id; return tag;', [start + 3]: '} finally { noop(); }' }); engine.pauseAt({ frames: frames(app('innerF', start + 2)), asyncParent: { fn: 'handler', line: 9, col: 14 } }); // V8's step-out is lost; the next thing V8 says is the net in `handler`. engine.script = [{ frames: frames(app('handler', 10)), reason: 'other', hits: (armed) => [armed[0].id] }]; @@ -977,13 +1003,13 @@ describe('JsStepper (issue #1130)', () => { // Asked from the awaiter's own position, since its frame is not on the stack. const asked = engine.calls.filter((c) => c.method === 'Debugger.getPossibleBreakpoints').map((c) => c.params.start); expect(asked).toContainEqual({ scriptId: 'app', lineNumber: 9, columnNumber: 14 }); - expect(stopped()).toMatchObject({ reason: 'step', text: ErrorMessages.stepCaughtAtAwaitingFunction('handler') }); + expect(stopped()).toMatchObject({ reason: 'step', text: ErrorMessages.stepCaughtWhereItReturns('handler') }); expect(engine.armed).toEqual([]); }); it('nets no awaiter that is skipped code', async () => { const start = fnLineOf(app('innerG', 0)); - sourceWith({ [start + 1]: 'try {', [start + 2]: ' await gate; return tag;', [start + 3]: '} finally { noop(); }' }); + sourceWith({ [start + 1]: 'try { await gate;', [start + 2]: ' const tag = id; return tag;', [start + 3]: '} finally { noop(); }' }); engine.pauseAt({ frames: frames(app('innerG', start + 2)), asyncParent: { fn: 'libRun', line: 9, script: 'lib', skipped: true } }); engine.script = ['runs']; await stepper.request('stepOut', { threadId: 1 }); @@ -1156,7 +1182,7 @@ describe('JsStepper (issue #1130)', () => { describe('edges the mutation pass found unpinned', () => { it('a new step gives up the one in flight: its nets are gone before the new command', async () => { - engine.pauseAt({ frames: frames(app('work', 9), app('main', 14)) }); + engine.pauseAt({ frames: frames(lossy(app('work', 9)), app('main', 14)) }); engine.script = ['runs']; await stepper.request('stepOut', { threadId: 1 }); await tick(10); @@ -1232,8 +1258,8 @@ describe('JsStepper (issue #1130)', () => { stepper.setEnabled(true); engine.pauseAt({ frames: frames(app('main', 10)) }); engine.script = [{ frames: frames(node('log', 1), app('main', 10)) }]; - gated = true; await stepper.request('stepIn', { threadId: 1 }); + gated = true; await tick(10); // js-debug has not answered about the landing yet, and the caller continues. await stepper.beforeRequest('continue'); @@ -1256,7 +1282,7 @@ describe('JsStepper (issue #1130)', () => { }); it('a net at the landing\'s own depth guards nothing below it: the stack is gone, and the program resumes', async () => { - engine.pauseAt({ frames: frames(app('work', 9), app('main', 14)) }); + engine.pauseAt({ frames: frames(lossy(app('work', 9)), app('main', 14)) }); // V8's step-out comes back in the next task: Node's own code, nothing of the program under it. engine.script = [{ frames: frames(node('processTicksAndRejections', 70)) }, 'runs']; await stepper.request('stepOut', { threadId: 1 }); @@ -1348,7 +1374,7 @@ describe('JsStepper (issue #1130)', () => { }); it('waits for js-debug\'s own verdict on a pause that is not the stepper\'s, however its earlier reports stand', async () => { - engine.pauseAt({ frames: frames(app('work', 9), app('main', 14)) }); + engine.pauseAt({ frames: frames(lossy(app('work', 9)), app('main', 14)) }); engine.script = ['runs']; await stepper.request('stepOut', { threadId: 1 }); await tick(10); @@ -1384,6 +1410,275 @@ describe('JsStepper (issue #1130)', () => { }); }); + // ----- the one rule for where a net is set (what the second review found) ----- + + describe('rule (a): a net only where V8 can lose the step and the frame cannot suspend first', () => { + it('sets none for a step out of a function with no finally clause: V8 does not lose that step', async () => { + engine.pauseAt({ frames: frames(app('plainOut', 5), app('caller', 14)) }); + engine.script = [{ frames: frames(app('caller', 15)) }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBe(0); + expect(stopped()).toMatchObject({ reason: 'step' }); + }); + + it('sets none when the statement awaits on a later line: the function suspends, and its caller runs on', async () => { + const start = fnLineOf(app('load', 0)); + sourceWith({ + [start + 1]: 'try { noop(); } finally { noop(); }', + [start + 2]: 'return {', + [start + 3]: ' user: await getUser(first),', + [start + 4]: '};' + }); + engine.pauseAt({ frames: frames(app('load', start + 2), app('caller', 14)) }); + engine.script = [{ frames: frames(app('caller', 15)) }]; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBe(0); + }); + + it('sets none when a loop above leads back to an await, and one when no loop does', async () => { + const start = fnLineOf(app('looped', 0)); + sourceWith({ + [start + 1]: 'for (const x of xs) {', + [start + 2]: ' await tick();', + [start + 3]: ' const tag = x;', + [start + 4]: '}', + [start + 5]: 'try { return 1; } finally { done(); }' + }); + // The same text without the loop (the stepper reads a script's text once). + const other = fnLineOf(app('straight', 0)); + sourceWith({ + [other + 1]: 'await ready;', + [other + 3]: 'const tag = x;', + [other + 5]: 'try { return 1; } finally { done(); }' + }); + engine.pauseAt({ frames: frames(app('looped', start + 3), app('caller', 14)) }); + engine.script = [{ frames: frames(app('caller', 15)) }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBe(0); + + // Without the loop nothing can suspend it before it exits. + engine.calls.length = 0; + engine.pauseAt({ frames: frames(app('straight', other + 3), app('caller', 14)) }); + engine.script = [{ frames: frames(app('caller', 15)), reason: 'other', hits: (armed) => [armed[0].id] }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBeGreaterThan(0); + expect(engine.armed).toEqual([]); + }); + + it('reads a yield ahead as a suspension too', async () => { + const start = fnLineOf(app('gen', 0)); + sourceWith({ [start + 1]: 'try { noop(); } finally { noop(); }', [start + 4]: 'yield value;' }); + engine.pauseAt({ frames: frames(app('gen', start + 2), app('caller', 14)) }); + engine.script = [{ frames: frames(app('caller', 15)) }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBe(0); + }); + + it.each([ + ['the word in a comment', '// and finally we are done'], + ['a promise chain', 'work().finally(() => done());'] + ])('does not take %s for a finally clause', async (_what, text) => { + const start = fnLineOf(app('wordy', 0)); + sourceWith({ [start + 4]: text }); + engine.pauseAt({ frames: frames(app('wordy', start + 2), app('caller', 14)) }); + engine.script = [{ frames: frames(app('caller', 15)) }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBe(0); + }); + + it.each([ + ['after the closing brace', '} finally {'], + ['before its own brace', 'finally {'], + ['alone on its line', ' finally'] + ])('reads a finally clause written %s', async (_what, text) => { + const start = fnLineOf(app('claused', 0)); + sourceWith({ [start + 4]: text }); + engine.pauseAt({ frames: frames(app('claused', start + 2), app('caller', 14)) }); + engine.script = [{ frames: frames(app('caller', 15)) }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBeGreaterThan(0); + }); + + it('does not take what only scheduled a function that can lose the step for its awaiter', async () => { + // A `.then` callback with a finally clause: its async parent registered it, and is not what it returns to. + engine.pauseAt({ frames: frames(lossy(app('onDone', 3))), asyncParent: { fn: 'work', line: 7, description: 'Promise.then' } }); + engine.script = ['runs']; + await stepper.request('stepOut', { threadId: 1 }); + await tick(5); + expect(setBreakpoints()).toBe(0); + await stepper.beforeRequest('continue'); + }); + + it('finds the awaiter behind the empty links V8 lists for the function\'s later awaits', async () => { + const start = fnLineOf(app('later', 0)); + sourceWith({ [start + 1]: 'try { await a; await b;', [start + 2]: ' return tag;', [start + 3]: '} finally { noop(); }' }); + engine.pauseAt({ frames: frames(app('later', start + 2)), asyncParent: { fn: 'handler', line: 9, col: 14, emptyLinks: 2 } }); + engine.script = [{ frames: frames(app('handler', 10)), reason: 'other', hits: (armed) => [armed[0].id] }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBeGreaterThan(0); + expect(stopped()).toMatchObject({ reason: 'step', text: ErrorMessages.stepCaughtWhereItReturns('handler') }); + }); + + it('steps out with V8 alone, and does not resume, when js-debug never says what is below', async () => { + // A first step teaches the stepper that Node's script is skipped. + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [{ frames: frames(node('log', 1), app('main', 10)) }, { frames: frames(app('main', 11)) }]; + await stepper.request('stepIn', { threadId: 1 }); + await settled(); + delivered.length = 0; + engine.calls.length = 0; + + engine.pauseAt({ frames: frames(app('listener', 40), node('emit', 7), app('main', 10)) }); + engine.script = [{ frames: frames(node('emit', 8), app('main', 10)) }, { frames: frames(app('main', 11)) }]; + await stepper.request('next', { threadId: 1 }); + engine.stackTraceFailures = 1e6; + await settled(); + expect(commands()).toEqual(['Debugger.stepOver', 'Debugger.stepOut']); + expect(stopped()).toMatchObject({ reason: 'step' }); + }); + }); + + describe('rule (b): a net that cannot name one call says so', () => { + it('says the stop may be another call\'s when the frame it guards was waiting at an await', async () => { + // handler awaits the call: it suspends as soon as the call returns, and leaves the stack. + sourceWith({ 14: 'const got = await inner(id);' }); + engine.pauseAt({ frames: frames(lossy(app('innerSync', 30)), app('handler', 14)) }); + engine.script = [{ frames: frames(app('handler', 15)), reason: 'other', hits: (armed) => [armed[1].id] }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(stopped()).toMatchObject({ reason: 'step', text: ErrorMessages.stepCaughtWhereItReturns('handler') }); + }); + + it('says nothing when the frame it guards stays on the stack', async () => { + sourceWith({ 14: 'const got = inner(id);' }); + engine.pauseAt({ frames: frames(lossy(app('innerSync', 30)), app('handler', 14)) }); + engine.script = [{ frames: frames(app('handler', 15)), reason: 'other', hits: (armed) => [armed[1].id] }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(stopped()).toMatchObject({ reason: 'step' }); + expect(stopped().text).toBeUndefined(); + }); + }); + + describe('more edges the second mutation pass found unpinned', () => { + it('reports a pause taken on one of its own net positions as the pause, though js-debug calls it a breakpoint', async () => { + engine.pauseAt({ frames: frames(lossy(app('work', 9)), app('main', 14)) }); + engine.script = ['runs']; + await stepper.request('stepOut', { threadId: 1 }); + await tick(10); + await stepper.beforeRequest('pause'); + engine.arrive({ frames: frames(app('main', 15)), reason: 'other', hits: [engine.armed[0].id] }); + await settled(); + expect(delivered).toHaveLength(1); + expect(stopped()).toMatchObject({ reason: 'pause', description: 'Paused' }); + expect(stopped().hitBreakpointIds).toBeUndefined(); + expect(engine.armed).toEqual([]); + }); + + it('sends nothing more when the pause is asked for while a landing is being judged, and reports that landing as the pause', async () => { + let gated = false; + let release: () => void = () => undefined; + stepper = new JsStepper({ + target: { + sendRequest: async (_c: string, args?: unknown) => { + if (gated) { + await new Promise((resolve) => { + release = resolve; + }); + } + return engine.stackTrace((args as { levels: number }).levels) as never; + } + }, + deliver: (event) => delivered.push(event), + tunables: { settleCeilingMs: 150, verdictCeilingMs: 150 } + }); + engine.onDap = (event) => { + seen.push({ event: event.event, withheld: stepper.withholds(event) }); + }; + stepper.attachCdp(engine); + stepper.setEnabled(true); + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [{ frames: frames(node('log', 1), app('main', 10)) }]; + await stepper.request('stepIn', { threadId: 1 }); + gated = true; + await tick(10); + await stepper.beforeRequest('pause'); + gated = false; + release(); + await settled(); + expect(commands()).toEqual(['Debugger.stepInto']); + expect(delivered).toHaveLength(1); + expect(stopped()).toMatchObject({ reason: 'pause' }); + expect(engine.armed).toEqual([]); + }); + + it('reports where it is when V8 refuses the resume of a stack that is gone', async () => { + engine.pauseAt({ frames: frames(app('handler', 20), node('emit', 7), node('parserOnIncoming', 3)) }); + engine.script = [{ frames: frames(node('emit', 8), node('parserOnIncoming', 3)) }]; + engine.failOnce = 'Debugger.resume'; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(delivered).toHaveLength(1); + expect(stopped()).toMatchObject({ reason: 'step' }); + }); + + it('owes a late report that names no breakpoint only to a step that kept a net\'s pause, and only for a while', async () => { + // (The stepper reads a script's text once: the function of the second step is written first.) + const work = lossy(app('work', 9)); + // A step with no net: a `breakpoint` naming none right after it is somebody else's stop. + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [{ frames: frames(app('main', 11)) }]; + engine.onDap = (event) => { + if (event.event !== 'stopped') stepper.withholds(event); + }; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(stepper.describe().owed).toBe(1); + expect(stepper.withholds({ seq: 0, type: 'event', event: 'stopped', body: { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [] } })).toBe(false); + + // A step that landed by its net owes exactly that. + engine.pauseAt({ frames: frames(work, app('main', 14)) }); + engine.script = [{ frames: frames(app('main', 15)), reason: 'other', hits: (armed) => [armed[0].id] }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(stepper.describe().owed).toBe(1); + expect(stepper.withholds({ seq: 0, type: 'event', event: 'stopped', body: { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [7] } })).toBe(false); + expect(stepper.withholds({ seq: 0, type: 'event', event: 'stopped', body: { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [] } })).toBe(true); + + // And not for ever: past the ceiling nothing is owed. + engine.pauseAt({ frames: frames(app('main', 20)) }); + engine.script = [{ frames: frames(app('main', 21)) }]; + await stepper.request('next', { threadId: 1 }); + await settled(); + await tick(200); + expect(stepper.withholds({ seq: 0, type: 'event', event: 'stopped', body: { reason: 'pause', threadId: 1 } })).toBe(false); + }); + + it('says how far the walk went only for a step back in the very frame it left: not a deeper call of the same function', async () => { + withTunables({ budget: 1 }); + const start = fnLineOf(app('recur', 0)); + engine.pauseAt({ frames: frames(app('recur', start + 1), app('main', 10)) }); + engine.script = [ + { frames: frames(node('log', 1), app('recur', start + 1), app('main', 10)) }, + { frames: frames(node('log', 2), app('recur', start + 1), app('main', 10)) }, + // Stepped out: Node's code had called recur again, one frame deeper. + { frames: frames(app('recur', start + 3), node('cb', 4), app('recur', start + 1), app('main', 10)), reason: 'ambiguous', hits: (armed) => [armed[0].id] } + ]; + await stepper.request('stepIn', { threadId: 1 }); + await settled(); + expect(stopped()).toMatchObject({ reason: 'step' }); + expect(stopped().text).toBeUndefined(); + }); + }); + it('refuses a step it cannot start, and leaves no net behind', async () => { engine.pauseAt({ frames: frames(app('leaf', 5), app('caller', 14)) }); engine.current = null; // V8 resumed behind the stepper's back From cd0e6bb13a2188a0c8d9ba97c3765b0188da9cce Mon Sep 17 00:00:00 2001 From: JF Date: Mon, 16 Nov 2026 01:34:41 -0500 Subject: [PATCH 11/24] docs(javascript): the one rule for the temporary breakpoints, and four sentences the second review found false (#1130, #1161) The JavaScript guide, the tool reference and both fragments state the rule as the code now applies it: from your own code only where the function has a finally clause and cannot suspend before it exits; from skipped code always; never on the frame being stepped in; and where the breakpoints cannot name one call, the answer says so. Corrected: - "A step over an await that is the last thing a function does before it leaves through finally can be lost." It is not: measured with V8 alone, V8 keeps a step across an await. The pending-step sentence no longer offers that as a cause. - A step out of a `.then` callback lands "nowhere": with another callback of the program queued behind it, V8's own step stops there. - "The pending answer says the step left its frame": on a launch. An attach that steps through skipped code gets the generic sentence. - A `setTimeout` line answers with the walk's sentence, as `console.log` does, and that sentence no longer says a callback the line only scheduled "ran". Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn69pXrYMWc1JUwv5v8 --- changelog.d/1130.fixed.md | 2 +- changelog.d/1161.fixed.md | 2 +- docs/javascript/README.md | 63 +++++++++++-------- docs/tool-reference.md | 33 +++++----- .../src/interfaces/adapter-policy-js.ts | 5 +- 5 files changed, 58 insertions(+), 47 deletions(-) diff --git a/changelog.d/1130.fixed.md b/changelog.d/1130.fixed.md index 6db3b5a40..ac9137293 100644 --- a/changelog.d/1130.fixed.md +++ b/changelog.d/1130.fixed.md @@ -1 +1 @@ -**A JavaScript step lands where your code next runs, and is no longer lost in Node's own code.** `step_into` on a line that calls a Node builtin took about 6 s on a Linux host and answered `pending`, blaming "a long-running call"; on the first `console.log` of a process it never landed at all and the program ran to its end. js-debug's own "smart stepper" was deciding where such a step ends: while the step was in skipped code it stepped again by itself, one engine step per statement (131 for one `console.log`), with a flag that moves the step to a later task and loses it. That stepper is now off for every session, and the server steps through skipped code itself, over js-debug's raw CDP socket, for `step_into`, `step_over` and `step_out` alike. A `step_into` on a line that calls your own function through skipped code (an event listener behind `emitter.emit`, an array callback, a route handler from inside express) lands in that function; on a line whose call stays in skipped code for the whole walk (`console.log`, a `require`) it lands on the next line and the message says how far the walk went (`Stepped into. step_into walked 25 engine steps into the call on that line and was still in skipped code …`) and that code of yours the call reaches further in ran without stopping; on a line that only starts a later task (`setTimeout`) it lands on the next line instead of inside the callback some time later. A `step_over` or `step_out` that returns into skipped code steps out to the nearest frame of your program below; when nothing of your program called or awaits the function (the last line of a request handler, a timer callback, a `.then` callback) the program is resumed rather than walked through the internals of later tasks, and the pending answer says the step left its frame. What counts as skipped is still js-debug's own verdict, so `justMyCode`, your `skipFiles` and source maps decide it as before, and `justMyCode: false` (or `smartStep: false`) still lands every step where V8 lands. A forked child steps the way its root session does, launched or attached. Changed on purpose: a pause asked for while a step is still pending is reported as the pause, where the program is, and is not stepped away from; and the sentence a pending step carries no longer mentions js-debug's stepper. On Linux every engine step costs about 46 ms whoever sends it (#1163), so a `step_into` on a `console.log` line still takes over a second there. (#1130) +**A JavaScript step lands where your code next runs, and is no longer lost in Node's own code.** `step_into` on a line that calls a Node builtin took about 6 s on a Linux host and answered `pending`, blaming "a long-running call"; on the first `console.log` of a process it never landed at all and the program ran to its end. js-debug's own "smart stepper" was deciding where such a step ends: while the step was in skipped code it stepped again by itself, one engine step per statement (131 for one `console.log`), with a flag that moves the step to a later task and loses it. That stepper is now off for every session, and the server steps through skipped code itself, over js-debug's raw CDP socket, for `step_into`, `step_over` and `step_out` alike. A `step_into` on a line that calls your own function through skipped code (an event listener behind `emitter.emit`, an array callback, a route handler from inside express) lands in that function; on a line whose call stays in skipped code for the whole walk (`console.log`, a `require`) it lands on the next line and the message says how far the walk went (`Stepped into. step_into walked 25 engine steps into the call on that line and was still in skipped code …`) and that code of yours the call runs further in or only schedules does not stop the step; on a line that only starts a later task (`setTimeout`) it lands on the next line instead of inside the callback some time later. A `step_over` or `step_out` that returns into skipped code steps out to the nearest frame of your program below; when nothing of your program called or awaits the function (the last line of a request handler, a timer callback, a `.then` callback) the program is resumed rather than walked through the internals of later tasks (a callback of yours already queued behind a `.then` callback is where V8's own step stops), and on a launch the pending answer says the step left its frame. What counts as skipped is still js-debug's own verdict, so `justMyCode`, your `skipFiles` and source maps decide it as before, and `justMyCode: false` (or `smartStep: false`) still lands every step where V8 lands. A forked child steps the way its root session does, launched or attached. Changed on purpose: a pause asked for while a step is still pending is reported as the pause, where the program is, and is not stepped away from; and the sentence a pending step carries no longer mentions js-debug's stepper. On Linux every engine step costs about 46 ms whoever sends it (#1163), so a `step_into` on a `console.log` line still takes over a second there. (#1130) diff --git a/changelog.d/1161.fixed.md b/changelog.d/1161.fixed.md index dece24d95..9a852a207 100644 --- a/changelog.d/1161.fixed.md +++ b/changelog.d/1161.fixed.md @@ -1 +1 @@ -**A JavaScript step that leaves a function through `return` inside `try … finally` lands in the caller.** V8 can lose such a step (measured on V8 12.4, 13.6 and 14.6 with a bare CDP client): a `step_out` of the function, a `step_over` off its `finally` block, and a `step_out` of an `async` function with that shape all answered `Step completed as session exited.` while the program ran on. Node's own module loader returns that way too, which is how a `step_into` on a `require` line was lost. Where a step can leave a frame that way, the server no longer counts on V8 alone to come back to the frame below: it sets temporary breakpoints on that frame, and whichever pauses first is the landing. That is something the server does in your process: at most 24 temporary breakpoints per guarded frame, for the length of one step (every `step_out`; a `step_over` or `step_into` from a function whose text has a `finally` clause; a step that walks through skipped code), removed when the step ends however it ends. Left to V8 on purpose: a function that returns to itself (`step_over`, `step_into`); and, in a function that can suspend, any line that itself awaits or yields, so a `step_over` on an `await` that is the last thing a function does before it leaves through `finally` can still be lost. An `async` function the event loop resumed returns to the function awaiting it, which is not on the stack: V8's own step finds the call that awaited, and only where V8 loses the step does the server guard the awaiting function, in whichever call of it runs next; that answer says the stop may be another call's. Not covered: a `step_over` across the first load of a module that has a breakpoint in it still runs on (#1162). (#1161) +**A JavaScript step that leaves a function through `return` inside `try … finally` lands in the caller.** V8 can lose such a step (measured on V8 12.4, 13.6 and 14.6 with a bare CDP client): a `step_out` of the function, a `step_over` off its `finally` block, and a `step_out` of an `async` function with that shape all answered `Step completed as session exited.` while the program ran on. Node's own module loader returns that way too, which is how a `step_into` on a `require` line was lost. Where V8 can lose a step, the server no longer counts on V8 alone to come back to the frame below: it sets temporary breakpoints on that frame, and whichever pauses first is the landing. That is something the server does in your process: at most 24 temporary breakpoints per guarded frame, for the length of one step, removed when the step ends however it ends. One rule says when, for all three steps: from your own code only where the function has a `finally` clause and cannot suspend before it exits from the paused line (a function that awaits does not return to its caller, and V8 keeps a step across an `await`); from skipped code always; never on the frame being stepped in. The breakpoints name one call only while the frame they guard stays on the stack. Where it does not (it was waiting at an `await` for the call the step leaves, or it is the function awaiting an `async` one the event loop resumed) the step stops in whichever call of that function runs next, and the answer says so (#1166). Not covered: a `step_over` across the first load of a module that has a breakpoint in it still runs on (#1162). (#1161) diff --git a/docs/javascript/README.md b/docs/javascript/README.md index fcf03c8aa..1ff29ea25 100644 --- a/docs/javascript/README.md +++ b/docs/javascript/README.md @@ -115,12 +115,12 @@ What a step does when the session steps through skipped code (the launch default | Step | From | Lands | |---|---|---| | `step_into` | a line that calls your function through skipped code (`emitter.emit` to a listener, an array callback, a route handler from inside express) | in that function | -| `step_into` | a line whose call stays in skipped code for the whole walk (`console.log`, a `require`) | on the next line. The message says how many engine steps the walk took, and that code of yours the call reaches further in (the module a `require` loads, a late callback) ran without stopping | +| `step_into` | a line whose call stays in skipped code for the whole walk (`console.log`, a `require`, `setTimeout`) | on the next line. The message says how many engine steps the walk took, and that code of yours the call runs further in (the module a `require` loads) or only schedules (a timer callback) does not stop the step | | `step_into` | a line that calls native code only (`JSON.stringify`) | on the next line, as a plain `Stepped into`: there is nothing to walk into | -| `step_into` | a line that only starts a later task (`setTimeout`, a `.then` callback) | on the next line; a breakpoint in the callback stops there | +| `step_into` | a line that only starts a later task (`setTimeout`, a `.then` callback) | on the next line, never in the callback some time later; a breakpoint in the callback stops there | | `step_over`, `step_out` | a frame whose caller is skipped code, with your code further down the stack | in that frame of yours | | `step_out` | an `async` function the event loop resumed | in the function that awaits it, in the call that awaited | -| `step_over`, `step_out` | the last line of a function that nothing of yours called or awaits (a request handler, a timer callback, a `.then` callback) | nowhere: nothing of your program is on the stack, so the program is resumed. The answer is the next stop if one comes while the step waits (a breakpoint, the program's end), and `pending: true` with a sentence saying so if none does | +| `step_over`, `step_out` | the last line of a function that nothing of yours called or awaits (a request handler, a timer callback, a `.then` callback) | nowhere of its own: nothing of your program is on the stack. If another callback of yours is already queued behind a `.then` callback, V8's step stops in it; otherwise the program is resumed, and the answer is the next stop if one comes while the step waits (a breakpoint, the program's end), or `pending: true` if none does (on a launch, with a sentence saying the step left its frame) | | any step | skipped code (a breakpoint inside a dependency) | `step_into` walks on into your handler; `step_over` and `step_out` run on as in the row above. `justMyCode: false` steps inside that code | A breakpoint or an exception reached during a step stops as itself. A `debugger;` statement reached during a step is @@ -147,30 +147,39 @@ ES2017 costs four unmapped `__awaiter` stops before its first line (issue #687). **Steps V8 itself loses** (issue #1161). V8 can lose a step that leaves a function through a `return` written inside `try … finally` (measured on V8 12.4, 13.6 and 14.6 with a bare CDP client): a `step_out` of such a function, or a `step_over` off its `finally` block, used to answer `Step completed as session exited.` Node's own module -loader has that shape, which is how a `step_into` on a `require` line was lost too. So where a step can leave a -frame that way, the server does not count on V8 alone to come back to the frame below: it sets temporary -breakpoints on that frame (the nearest frame of your program down the stack), and whichever pauses first is the -landing. That is something the server does in your process: up to 24 temporary breakpoints per guarded frame, for -the length of one step. They are set for every `step_out`, for a `step_over` or `step_into` from a function whose -text has a `finally` clause, and for a step that walks through skipped code, and they are removed when the step -ends, however it ends. Where they cannot be set (V8 gives no break positions for Node's own scripts) the step goes -on with V8 alone. - -What that leaves to V8, on purpose: - -- **Recursion.** A function that returns to itself gets no such breakpoints for `step_over` and `step_into`: they - would sit in the frame being stepped in. -- **A function that can suspend** (`await` or `yield` in its text). A `step_over` or `step_into` there is guarded - only on a `return` line and from its `finally` on, and never on a line that itself awaits or yields: on such a - line the function suspends, its caller runs on, and a breakpoint in the caller would stop the step there instead - of on the next line. So a `step_over` on an `await` that is the last thing a function does before it leaves - through `finally` is V8's own, and V8 can lose it: the program runs on. -- **The function awaiting an `async` one.** An `async` function the event loop resumed returns to the function that - awaits it, which is not on the stack. V8's own step finds the call that awaited. Only where V8 loses the step - (`finally` in the function being left) does the server guard the awaiting function, and there it can only guard - the *function*: the step stops in whichever call of it runs next, and the answer says so (`… this stop may be in - another call's continuation than the one that awaited the function you stepped out of: check its variables.`). - With one call in flight, that is the right one. +loader has that shape, which is how a `step_into` on a `require` line was lost too. So where V8 can lose a step, the +server does not count on V8 alone to come back to the frame below: it sets temporary breakpoints on that frame (the +nearest frame of your program down the stack), and whichever pauses first is the landing. That is something the +server does in your process: up to 24 temporary breakpoints per guarded frame, for the length of one step, removed +when the step ends, however it ends. Where they cannot be set (V8 gives no break positions for Node's own scripts) +the step goes on with V8 alone. + +One rule says when they are set, for all three steps: + +- **From your own code**, only when the function has a `finally` clause and, from the paused line, cannot suspend + before it exits: no `await` or `yield` ahead, and no loop above that leads back to one. A function that suspends + does not return to its caller: the caller runs on, and a breakpoint there would stop the step in the caller while + V8 is still on its way to the next line. And V8 keeps a step across an `await` (measured: it lands in the awaiting + function even when the function then leaves through `finally`), so there is nothing to rescue. This reads the + function's text; it is not a parse, and it errs toward V8's own step. +- **From skipped code** (a step that walks through Node's code or a dependency), always. That code is not read, and + wherever control comes down from it, your frame below is the landing. +- **Never on the frame being stepped in**: a function that returns to itself (recursion) gets none for `step_over` + and `step_into`. + +The breakpoints are kept with the depth of the frame they guard, which names that one call while it stays on the +stack. Two cases have no such frame. There the step stops in whichever call of the function runs next, and the +answer says so (`This step was caught by a temporary breakpoint in handler, the function it returns to, … if +several calls of handler are in flight this stop may be in another of them than the one the step returns to: check +its variables.`): + +- the guarded frame was itself waiting at an `await` for the call the step leaves (`const got = await inner(id)`): + it leaves the stack before anything stops; +- the function the step returns to was never on the stack: the one awaiting an `async` function the event loop + resumed. V8's own step finds the call that awaited, so that function is guarded only where the loss is known from + the text. + +With one call in flight the stop is the right one (issue #1166). Not covered: a `step_over` across the first load of a module that has a breakpoint in it still runs on (issue #1162; js-debug pauses at the module's entry to bind the breakpoint, and V8 drops the step at any pause). A diff --git a/docs/tool-reference.md b/docs/tool-reference.md index f04d39dde..5ccc9c421 100644 --- a/docs/tool-reference.md +++ b/docs/tool-reference.md @@ -706,9 +706,9 @@ The step is not cancelled: the session becomes `"paused"` on its own when it com The adapter may append one sentence to that message saying what the step is waiting for. The JavaScript adapter does so for a launch that steps through skipped code (issues #678, #1130): a step issued from skipped code names the frame and says a step does not stop there, and any other pending step says it left the frame it started in -and has not stopped in your program since (a function Node called returned to the event loop, the line is -waiting on work in flight, or the engine lost the step: an `await` that was the last thing a function did before -it left through `try … finally`). So match a pending step by its `pending: true` flag, not by the message text. +and has not stopped in your program since (a function Node called returned to the event loop, or the line is +waiting on work in flight). An attach that steps through skipped code (`smartStep: true`) gets no such sentence. +So match a pending step by its `pending: true` flag, not by the message text. Once a stop has been observed, the stop path owns the answer — a step that demonstrably landed is never reported as pending afterwards, at the cost of the response then being bounded by the stack-trace round trip rather than by the ~5s window. If the debuggee ends while the step is in flight the result is still a success, with a terminal `state` and a message such as `"Step completed as session terminated."`. @@ -742,10 +742,11 @@ Same ~5s wait and `pending: true` contract as step_over — see [Pending steps]( - A line whose call stays in skipped code (Node internals, `node_modules`, files on `skipFiles`) for the whole walk lands on the next line, and the message says what is known: `Stepped into. step_into walked 25 engine steps into the call on that line and was still in skipped code (Node internals, node_modules, or files on skipFiles), - so it stepped back out and the rest of the line ran as a step over runs it. Code of yours that the call reaches - further in (a module it loads, a late callback) ran without stopping: a breakpoint there stops in it. To stop - inside the skipped code instead, turn stepping through it off: justMyCode: false on a launch, smartStep: false - on a launch or an attach.` A `console.log` and a `require` answer this way. + so it stepped back out and the rest of the line ran as a step over runs it. Code of yours that the call runs + further in (a module it loads) or only schedules (a timer or promise callback) does not stop the step: a + breakpoint there stops in it. To stop inside the skipped code instead, turn stepping through it off: + justMyCode: false on a launch, smartStep: false on a launch or an attach.` A `console.log`, a `require` and a + `setTimeout` line answer this way. - A line that calls native code only (`JSON.stringify`) has nothing to walk into: a plain `Stepped into` on the next line. - A call that only starts a later task (`setTimeout`, a `.then` callback) is not followed: the step lands on the @@ -777,15 +778,17 @@ Same ~5s wait and `pending: true` contract as step_over — see [Pending steps]( **JavaScript** (a launch that steps through skipped code, the default; issues #1130, #1161): - Out of an `async` function the event loop resumed, the step lands in the function that awaits it, in the - call that awaited. -- When that `async` function has a `finally` clause, the engine can lose the step, so the server catches it - at the awaiting function instead, in whichever call of that function runs next, and the message says so: - `Stepped out. The engine loses a step that leaves a function through try...finally, so this step was caught - where the awaiting function, handler, next ran. If several calls of handler are in flight, this stop may be - in another call's continuation than the one that awaited the function you stepped out of: check its - variables.` + call that awaited: that is the engine's own step. +- The engine can lose a step that leaves a function through `try … finally`. Where the function has a `finally` + clause and cannot suspend before it exits, the server catches the step with temporary breakpoints on the function + it returns to. When those cannot name one call (that function was waiting at an `await`), the stop is in + whichever call of it runs next, and the message says so: `Stepped out. This step was caught by a temporary + breakpoint in handler, the function it returns to, because the engine can lose a step that leaves a function + through try...finally. handler was waiting at an await meanwhile, so if several calls of handler are in flight + this stop may be in another of them than the one the step returns to: check its variables.` The same sentence + can follow a `step_over` or `step_into` that leaves such a function. - Out of a function that nothing of your program called or awaits (a timer callback, a `.then` callback, a - request handler) there is nowhere to land: the program is resumed, and the answer is the next stop or + request handler) there is nowhere of its own to land: the program is resumed, and the answer is the next stop or `pending: true`. See [Stepping and pausing inside dependencies](javascript/README.md#stepping-and-pausing-inside-dependencies-justmycode-skipfiles). diff --git a/packages/shared/src/interfaces/adapter-policy-js.ts b/packages/shared/src/interfaces/adapter-policy-js.ts index ebe26cb5a..6d756f33d 100644 --- a/packages/shared/src/interfaces/adapter-policy-js.ts +++ b/packages/shared/src/interfaces/adapter-policy-js.ts @@ -450,9 +450,8 @@ export const JsDebugAdapterPolicy = { 'dapLaunchArgs.justMyCode: false (or adapterLaunchConfig.smartStep: false) to step inside that code.'; } return 'The step left the frame it started in and has not stopped in your program since: a function that Node ' + - 'called returned to the event loop, the line is waiting on work still in flight, or the engine lost the step ' + - '(an await that was the last thing a function did before it left through try...finally). The program is ' + - 'running; wait_for_stop answers when the step lands, a breakpoint is hit, or the program ends.'; + 'called returned to the event loop, or the line is waiting on work still in flight. The program is running; ' + + 'wait_for_stop answers when the step lands, a breakpoint is hit, or the program ends.'; }, /** From dfc7b851c494cd0c6b5790828fb5f1e4022935fc Mon Sep 17 00:00:00 2001 From: JF Date: Mon, 16 Nov 2026 10:46:55 -0500 Subject: [PATCH 12/24] fix(javascript): a net only where a hit proves the step came back (#1130, #1161, #1174) The third review found the one rule of the round before unsound in both directions: it lost nine steps V8 loses that the round before had rescued, and it still set nets below functions that suspend. Three rules in a row failed the same way, for one reason: they read a function's text to guess whether control coming back to the frame below means the function returned or merely paused at an await, and text cannot say. Nor does CDP name one call of a function, so a net on a frame that can leave the stack can stop in another call. So the nets are set only where a hit is a proof: (a) The frame being left is a plain function: not async, not a generator, not module code. That is read from its header, the text V8's functionLocation points at, for Node's own scripts as for the program's (V8 gives their source; it refuses only their break positions). Doubt reads as "can suspend". A plain function comes down only by returning, so control back below means it returned. (b) The frame guarded stays on the stack until it reaches a net position: a plain function does; an async one does unless it can suspend between the call returning and its next break location. Measured: V8 puts a break location at every statement's start and at every call, so that happens only when the calling statement awaits or yields, or the function suspends with no keyword there (`for await`, `await using`). src/proxy/js-statement-scan.ts reads that statement: strings and comments masked, the span found by brackets, semicolons and line breaks, and "it can" whenever it is unsure (an unterminated string, a template expression, a regular expression literal, a statement longer than 40 lines). Its first draft read the wrong span and took a comment on the line above ("after the await") for a suspension: safe, but it lost the `require` rescue in an async main. Nothing off the stack is netted any more: the awaiter net, its sentence (stepCaughtWhereItReturns) and the text tests for finally clauses, loops and suspensions are gone. One text test is kept only to spare breakpoints: a plain function whose text names nothing that closes through a finally (`finally`, `for...of`, `using`) is not netted, and that test can only err toward netting. What that leaves lost, as in 0.26.0 and now filed as #1174: a step V8 loses while leaving an async function or a generator, and a step out of a plain function whose caller awaits the call. The pending sentence names the case. Measured with V8 alone: a step parked across an await survives an unrelated breakpoint pause and resume, so nothing about async stepping is worse than V8's own. Also from the third review: a pause asked for while the stack turns out to be gone, or while a net is being set, no longer resumes the program. The cause in V8 is now understood and tracked in #1173 (the return replayed after a finally carries no source position, so it is not a break location). Unit: tests/proxy/js-statement-scan.test.ts, 27 cases of the shapes the reviews found and the ways the scan could be fooled. js-stepper: 122 cases. The rule's cases are rewritten: function forms read from headers as measured on Node 24, async and generator frames get no net whatever they contain, plain frames get one whatever their comments say, the implicit finally of for...of and using, an async caller that awaits the call. Integration: the two cases that expected an async function's lost step to be rescued now pin it as lost. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015BDrn69pXrYMWc1JUwv5v8 --- src/proxy/js-statement-scan.ts | 266 ++++++++++++ src/proxy/js-stepper.ts | 320 ++++++++------ src/utils/error-messages.ts | 21 - .../javascript-step-skipped-code.test.ts | 18 +- tests/proxy/js-statement-scan.test.ts | 79 ++++ tests/proxy/js-stepper.test.ts | 401 ++++++++++-------- 6 files changed, 764 insertions(+), 341 deletions(-) create mode 100644 src/proxy/js-statement-scan.ts create mode 100644 tests/proxy/js-statement-scan.test.ts diff --git a/src/proxy/js-statement-scan.ts b/src/proxy/js-statement-scan.ts new file mode 100644 index 000000000..6c5b63a85 --- /dev/null +++ b/src/proxy/js-statement-scan.ts @@ -0,0 +1,266 @@ +/** + * Reading JavaScript source just far enough to answer one question for the + * proxy's stepper (issues #1130, #1161): can a frame of an async function or + * a generator suspend between a call returning and the next break location? + * + * Measured on V8 13.6: every statement has a break location at its start (a + * statement that begins with a call has it at that call), and every call is + * one. So a frame that returns from a call reaches a break location before it + * can suspend unless the statement making the call awaits or yields, or the + * function suspends without a keyword in that statement (`for await`, + * `await using`). + * + * This is not a parser. It masks out strings and comments, finds the + * statement around a position by brackets, semicolons and line breaks, and + * errs toward "can suspend" whenever it is unsure: an unterminated string, + * template or comment on a line it reads, a statement longer than it will + * scan, an ambiguous line break. "Can suspend" costs a rescue; "cannot" when + * the frame can would cost a wrong landing. + */ + +/** How many lines a statement may span before the scan gives up (and says it can suspend). */ +const MAX_STATEMENT_LINES = 40; + +const SUSPENDS = /\b(await|yield)\b/; +const IMPLICIT_SUSPENSION = /\bfor\s+await\b|\bawait\s+using\b/; + +/** A line with its strings and comments blanked out; `unsafe` when it cannot be blanked with confidence. */ +interface MaskedLine { + code: string; + unsafe: boolean; +} + +/** + * Blank string, template and comment contents on one line, keeping columns. + * `inBlockComment` carries a `/* ... *\/` comment across lines. A string or + * template that does not end on the line, and anything that looks like a + * regular expression literal, makes the line unsafe. + */ +function maskLine(line: string, inBlockComment: { open: boolean }): MaskedLine { + let code = ''; + let unsafe = false; + let i = 0; + while (i < line.length) { + const ch = line[i]; + if (inBlockComment.open) { + const end = line.indexOf('*/', i); + if (end === -1) { + code += ' '.repeat(line.length - i); + return { code, unsafe }; + } + code += ' '.repeat(end + 2 - i); + i = end + 2; + inBlockComment.open = false; + continue; + } + if (ch === '/' && line[i + 1] === '/') { + code += ' '.repeat(line.length - i); + return { code, unsafe }; + } + if (ch === '/' && line[i + 1] === '*') { + inBlockComment.open = true; + code += ' '; + i += 2; + continue; + } + if (ch === '"' || ch === "'" || ch === '`') { + let j = i + 1; + while (j < line.length && line[j] !== ch) { + if (line[j] === '\\') { + j++; + } else if (ch === '`' && line[j] === '$' && line[j + 1] === '{') { + // An expression inside a template: not read. + unsafe = true; + } + j++; + } + if (j >= line.length) { + // Not closed on this line (or a line continuation): not read with confidence. + unsafe = true; + code += ' '.repeat(line.length - i); + return { code, unsafe }; + } + code += ch + ' '.repeat(j - i - 1) + ch; + i = j + 1; + continue; + } + if (ch === '/') { + // Division or a regular expression literal: told apart only by context. + const before = code.trimEnd(); + const prev = before[before.length - 1] ?? ''; + if (prev === '' || /[(,=:[!&|?{};+\-*%<>~^]/.test(prev) || /\b(return|typeof|case|do|else|in|of|yield|await)$/.test(before)) { + unsafe = true; + } + } + code += ch; + i++; + } + return { code, unsafe }; +} + +/** Whether a line break between these two lines ends a statement (automatic semicolon insertion). */ +function lineBreakEndsStatement(previous: string, next: string): boolean { + const before = previous.trimEnd(); + const after = next.trimStart(); + if (before === '' || after === '') { + return false; + } + const last = before[before.length - 1]; + const first = after[0]; + // The line before must end like an expression or a statement can end ... + if (!/[\w$)\]}"'`]/.test(last)) { + return false; + } + if (/\b(await|yield|return|new|typeof|instanceof|in|of|void|delete|case|else|extends)$/.test(before)) { + return false; + } + // ... and the next must start like a statement, not continue an expression. + return /[\w$'"{}]/.test(first) && !/^(in|of|instanceof)\b/.test(after); +} + +/** + * Whether the statement containing `column` of `line` (0-based) awaits or + * yields, or the function containing it can suspend without saying so in + * that statement. `from` and `to` bound the function's own lines. Errs toward + * true. + */ +export function statementCanSuspend(lines: readonly string[], line: number, column: number, from: number, to: number): boolean { + const first = Math.max(0, from); + const last = Math.min(lines.length - 1, to); + if (line < first || line > last) { + return true; + } + const comment = { open: false }; + const masked: MaskedLine[] = []; + for (let i = first; i <= last; i++) { + masked.push(maskLine(lines[i] ?? '', comment)); + } + const at = (n: number): MaskedLine => masked[n - first]; + if (masked.some((entry) => IMPLICIT_SUSPENSION.test(entry.code))) { + return true; + } + + // Backward to the start of the statement. + let startLine = line; + let startCol = 0; + { + let depth = 0; + let n = line; + let c = column - 1; + let found = false; + while (!found) { + const code = at(n).code; + for (; c >= 0; c--) { + const ch = code[c]; + if (ch === ')' || ch === ']') { + depth++; + } else if (ch === '(' || ch === '[') { + depth = Math.max(0, depth - 1); + } else if (ch === '}') { + if (depth === 0 && code.slice(c + 1).trim() === '' && n < line) { + // A brace that ends its line, before the statement's line: the end of an earlier block. + startLine = n + 1; + startCol = 0; + found = true; + break; + } + depth++; + } else if (ch === '{') { + if (depth > 0) { + depth--; + } else { + const before = code.slice(0, c).trimEnd(); + const prev = before[before.length - 1] ?? ''; + const objectLiteral = /[(,=:[?!&|]/.test(prev) || /\b(return|await|yield)$/.test(before); + if (!objectLiteral) { + startLine = n; + startCol = c + 1; + found = true; + break; + } + } + } else if (ch === ';' && depth === 0) { + startLine = n; + startCol = c + 1; + found = true; + break; + } + } + if (found) { + break; + } + if (n === first) { + startLine = first; + startCol = 0; + break; + } + if (line - n >= MAX_STATEMENT_LINES) { + return true; + } + if (depth === 0 && lineBreakEndsStatement(at(n - 1).code, code)) { + startLine = n; + startCol = 0; + break; + } + n--; + c = at(n).code.length - 1; + } + } + + // Forward to its end. + let endLine = line; + let endCol = at(line).code.length; + { + let depth = 0; + let n = line; + let c = column; + let found = false; + while (!found) { + const code = at(n).code; + for (; c < code.length; c++) { + const ch = code[c]; + if (ch === '(' || ch === '[' || ch === '{') { + depth++; + } else if (ch === ')' || ch === ']' || ch === '}') { + // Closing a group the statement started in: it goes on after it. + depth = Math.max(0, depth - 1); + } else if (ch === ';' && depth === 0) { + endLine = n; + endCol = c; + found = true; + break; + } + } + if (found) { + break; + } + if (n === last) { + endLine = last; + endCol = code.length; + break; + } + if (n - line >= MAX_STATEMENT_LINES) { + return true; + } + if (depth === 0 && lineBreakEndsStatement(code, at(n + 1).code)) { + endLine = n; + endCol = code.length; + break; + } + n++; + c = 0; + } + } + + let text = ''; + for (let n = startLine; n <= endLine; n++) { + const entry = at(n); + if (entry.unsafe) { + return true; + } + const from = n === startLine ? startCol : 0; + const to = n === endLine ? endCol : entry.code.length; + text += entry.code.slice(from, to) + '\n'; + } + return SUSPENDS.test(text); +} diff --git a/src/proxy/js-stepper.ts b/src/proxy/js-stepper.ts index ed934a9f1..37d953354 100644 --- a/src/proxy/js-stepper.ts +++ b/src/proxy/js-stepper.ts @@ -24,37 +24,47 @@ * a timer tick later, which costs 12 ms a landing on Windows. * * NETS. V8 loses a step in two measured ways: when a frame is left through - * a `return` inside try...finally within the run the step began in (issue - * #1161), and when js-debug resumes a pause of its own, a module-entry + * a `return` that runs a `finally` first, within the run the step began in + * (issue #1161: the replayed Return bytecode has no source position, so it + * is not a break location, and V8's step-out floods return locations only; + * a `return` out of for...of and a `using` declaration close the same + * way), and when js-debug resumes a pause of its own, a module-entry * breakpoint, while the step is in flight (issue #1162). A net is a capped * set of temporary CDP breakpoints on the break positions of the frame a * step returns to, kept with the stack depth of the activation it guards. * Any position there is where V8's own step-out would stop, so a hit at * that depth is a landing. * - * ONE RULE says where a net is set, and it is applied in one place, before - * every command that can leave the frame on top (`guard`): + * A NET IS SET ONLY WHERE A HIT PROVES THE STEP CAME BACK. Three versions + * of a wider rule each stopped steps in the wrong place, because nothing + * V8 exposes tells "the function returned" from "it suspended at an + * await", nor one call of a function from another. So, in one place, + * before every command that can leave the frame on top (`guard`): * - * (a) Only where V8 can lose the step, and the frame cannot hand control - * down without returning. For a frame of the program that is read - * from its text: a `finally` clause, and from the paused line no way - * to suspend before the function exits (no `await` or `yield` ahead, - * and no loop that leads back to one). A function that suspends does - * not return: its caller runs on, and a net below would stop there - * while V8's own step is still on its way; and V8 keeps a step across - * an `await`, so nothing needs rescuing. Skipped code is netted - * without being read (V8 refuses the break positions of Node's own - * scripts, and Node's module loader has the shape): whichever way - * control comes down from it, the program frame below is the landing. + * (a) The frame being left is a PLAIN function: not async, not a + * generator, not module code. That is read from its header (the text + * V8's functionLocation points at), for Node's own code as for the + * program's; a header that cannot be read counts as one that can + * suspend. A plain function comes down only by returning, so + * control back in the frame below means it returned: V8 landed + * there too, or lost the step. A function that can suspend is V8's + * own: V8 keeps a step across an `await`, and what it loses there + * (a leave through `finally` within one run) stays lost, and the + * answer says so. To spare the breakpoints where they cannot matter, + * a plain function whose text names nothing that closes through a + * finally (`finally`, `for...of`, `using`) is not netted either: + * that test only ever errs toward netting, and a miss costs a + * rescue, never a wrong landing. * - * (b) A net names an activation only while that activation stays on the - * stack. A guarded frame that is itself waiting at an `await` when - * the step leaves has left the stack by the time anything stops, and - * an awaiter (the function awaiting an async one the event loop - * resumed: the pause's async parent, when V8 calls the link `await`) - * was never on it. There the net guards the FUNCTION, stops in - * whichever call of it runs next, and the landing says so. An - * awaiter is netted only where the loss is known from the text. + * (b) The frame guarded is on the stack and stays there until it + * reaches a net position. A plain function does. One that can + * suspend does unless the statement making the call awaits or + * yields: then it can leave the stack before any position, another + * call of the same function can take its depth, and no net is set. + * + * Nothing is ever guarded that is not on the stack (no net on an awaiting + * function), and nothing is decided on a pause's reason, which does not + * say whether V8 had lost the step. * * A net is a safeguard, never a condition: when one cannot be set the step * goes on with V8 alone. @@ -92,6 +102,7 @@ import type { DebugProtocol } from '@vscode/debugprotocol'; import { createLogger } from '../utils/logger.js'; import { ErrorMessages } from '../utils/error-messages.js'; +import { statementCanSuspend } from './js-statement-scan.js'; // redirectable: re-pointed into the per-session proxy log at worker init (#519) const logger = createLogger('js-stepper', { redirectable: true }); @@ -167,6 +178,8 @@ interface CdpCallFrame { functionName?: string; functionLocation?: CdpLocation; location: CdpLocation; + /** Innermost scope first; `module` before any `local` means the frame is a module's own code. */ + scopeChain?: Array<{ type?: string }>; } interface CdpAsyncFrame { @@ -195,14 +208,8 @@ interface Net { name: string; /** Function identity, or the async parent's position. */ fn: string; - /** The stack depth of the guarded activation; Infinity for an awaiter, which resumes at any depth. */ + /** The stack depth of the guarded activation. */ depth: number; - /** - * Set when the net cannot name one call of the function: the function's - * name. An awaiter is not on the stack; a guarded frame waiting at an - * `await` has left it by the time anything stops. - */ - anotherCall?: string; ids: Set; } @@ -221,33 +228,14 @@ type ReturnTarget = /** js-debug did not say, or the stack is deeper than was asked about. */ | { kind: 'unknown' }; -/** What a function's text says about how a step can leave it. */ -interface FunctionShape { - /** A `finally` clause in its text: the shape V8 loses a leaving step on (issue #1161). */ - hasFinally: boolean; - /** 0-based script lines its text runs from and to. */ - from: number; - to: number; -} - /** How many frames of a stack js-debug is asked to mark, at most. */ const MAX_MARKED_FRAMES = 200; /** How far past the sync frames js-debug is asked: the labels of the async segments and the awaiter's frame. */ const ASYNC_MARKS = 12; -/** A loop on a line of source: the only way execution goes back up a function's text. */ -const LOOPS = /\b(for|while|do)\b/; - -/** - * A `finally` clause on a line of source: after the closing brace of a try - * or catch block, before its own opening brace, or alone on its line. Not - * the word in a comment, and not a promise's `.finally(`. - */ -const FINALLY_CLAUSE = /\}\s*finally\b|\bfinally\s*\{|^\s*finally\s*$/; - -/** `await` or `yield` on a line of source: where a function hands control back without returning. */ -const SUSPENDS = /\b(await|yield)\b/; +/** What closes through a finally, written or implied: the exits V8 loses a step on (issue #1161). */ +const CLOSES_THROUGH_FINALLY = /\b(finally|using|of)\b/; interface Chain { kind: StepKind; @@ -278,8 +266,6 @@ interface Chain { pauseRequested: boolean; /** That pause was taken on no breakpoint of js-debug's: it is reported as the pause it is. */ pauseTaken: boolean; - /** The landing came by a net that cannot name one call: the guarded function's name. */ - caughtInFunction: string | null; /** Whether any pause the chain kept was a net's: what a late report of it looks like. */ netHits: boolean; startedAt: number; @@ -337,7 +323,10 @@ export class JsStepper { private owedNetHit = false; /** Scripts js-debug marked "Skipped by skipFiles": a script-level verdict, not asked again. */ private readonly skippedScripts = new Set(); - private readonly shapes = new Map(); + /** Whether a function can suspend, by its header: read once per function. */ + private readonly suspending = new Map(); + /** Whether a function's text names a construct that closes through a finally. */ + private readonly closing = new Map(); /** What each pause's top frame returns to: asked of js-debug once per pause. */ private readonly targets = new WeakMap(); private readonly sources = new Map(); @@ -426,7 +415,6 @@ export class JsStepper { walkHasNothingBelow: false, pauseRequested: false, pauseTaken: false, - caughtInFunction: null, netHits: false, startedAt: Date.now() }; @@ -555,9 +543,21 @@ export class JsStepper { await this.finish(chain, 'cancelled'); return; } + if (chain.pauseRequested) { + chain.pauseTaken = true; + await this.finish(chain, 'real-stop'); + return; + } await this.sendStep(chain, verdict.command); continue; } + if (verdict.kind === 'left-stack' && chain.pauseRequested && !chain.cancelled) { + // The stack is gone, but the caller asked for a pause while that + // was being found out: V8 is paused, and the stop is theirs. + chain.pauseTaken = true; + await this.finish(chain, 'real-stop'); + return; + } await this.finish(chain, verdict.kind, verdict.kind === 'landing' ? verdict.by : undefined); return; } @@ -703,8 +703,6 @@ export class JsStepper { chain.reissues++; return { kind: 'command', command: CDP_COMMAND.in, skipped: false }; } - // A net that cannot name one call of the function it guards says so. - chain.caughtInFunction = guarding.find((net) => net.anotherCall !== undefined)?.anotherCall ?? null; // The pause's reason does not say whether V8 had lost the step: it is logged, and nothing is decided on it. return { kind: 'landing', by: `net (${pause.reason})` }; } @@ -880,9 +878,6 @@ export class JsStepper { if (chain.capped) { return { text: ErrorMessages.stepStillInSkippedCode(chain.commands.length) }; } - if (chain.caughtInFunction !== null) { - return { text: ErrorMessages.stepCaughtWhereItReturns(chain.caughtInFunction) }; - } if (chain.walkedBeforeSteppingOut > 0 && backInOriginFrame) { return { text: ErrorMessages.stepIntoReachedNoProgramCode(chain.walkedBeforeSteppingOut) }; } @@ -993,76 +988,114 @@ export class JsStepper { } } + private async linesOf(scriptId: string): Promise { + let lines = this.sources.get(scriptId); + if (!lines) { + const answer = await this.cdp?.send<{ scriptSource?: string }>('Debugger.getScriptSource', { scriptId }); + lines = (answer?.scriptSource ?? '').split('\n'); + this.sources.set(scriptId, lines); + } + return lines; + } + /** - * What the text of the frame's function says about how a step can leave - * it; null when it cannot be read (V8 refuses the break positions of - * Node's own scripts). The text is the function's own lines, nested - * functions and comments included: a text test, not a parse. Never throws. + * Rule (a): whether the frame's function can hand control down without + * returning: an async function, a generator, or a module's own code (which + * may await at its top level). Read from the function's header, the text + * V8's functionLocation points at, which is the parameter list of a + * function or method (`async`, `*` stand right before it) and the first + * token of an arrow (`async` itself). V8 gives the source of Node's own + * scripts too. Doubt reads as "can suspend": no net. Never throws. */ - private async shapeOf(frame: CdpCallFrame): Promise { + private async canSuspend(frame: CdpCallFrame): Promise { const key = fnKey(frame); - if (this.shapes.has(key)) { - return this.shapes.get(key) ?? null; + const known = this.suspending.get(key); + if (known !== undefined) { + return known; } - let shape: FunctionShape | null = null; + let suspends = true; try { - const lines = await this.linesOf(frame.location.scriptId); - const all = await this.locationsOf(frame); - if (all.length > 0) { - const from = Math.min(frame.functionLocation?.lineNumber ?? all[0].lineNumber, all[0].lineNumber); - const to = all[all.length - 1].lineNumber; - shape = { hasFinally: lines.slice(from, to + 1).some((line) => FINALLY_CLAUSE.test(line)), from, to }; + const scopes = frame.scopeChain ?? []; + const firstFunctionScope = scopes.find((scope) => scope.type === 'local' || scope.type === 'module'); + const at = frame.functionLocation; + if (firstFunctionScope?.type === 'module') { + suspends = true; + } else if (at) { + const line = (await this.linesOf(at.scriptId))[at.lineNumber]; + if (line !== undefined) { + suspends = suspendsByHeader(line, at.columnNumber ?? 0); + } } } catch (err) { - logger.debug(`[JsStepper] could not read the function's text: ${errorText(err)}`); + logger.debug(`[JsStepper] could not read a function's header: ${errorText(err)}`); } - this.shapes.set(key, shape); - return shape; + this.suspending.set(key, suspends); + return suspends; } - private async linesOf(scriptId: string): Promise { - let lines = this.sources.get(scriptId); - if (!lines) { - const answer = await this.cdp?.send<{ scriptSource?: string }>('Debugger.getScriptSource', { scriptId }); - lines = (answer?.scriptSource ?? '').split('\n'); - this.sources.set(scriptId, lines); + /** + * Rule (b), for a guarded frame that can suspend: whether it can suspend + * between the call it is making returning and its next break location. V8 + * puts a break location at every statement's start and at every call, so + * it cannot unless the calling statement awaits or yields, or the function + * suspends without a keyword there (`for await`, `await using`): read by + * `statementCanSuspend`, which errs toward "it can". Never throws. + */ + private async callStatementSuspends(frame: CdpCallFrame): Promise { + try { + const here = frame.location; + const all = await this.locationsOf(frame); + if (all.length === 0) { + return true; + } + const lines = await this.linesOf(here.scriptId); + const from = Math.min(frame.functionLocation?.lineNumber ?? all[0].lineNumber, all[0].lineNumber); + const to = all[all.length - 1].lineNumber; + return statementCanSuspend(lines, here.lineNumber, here.columnNumber ?? 0, from, to); + } catch (err) { + logger.debug(`[JsStepper] could not read the calling statement: ${errorText(err)}`); + return true; } - return lines; } /** - * Rule (a), for a frame of the program: whether V8 can lose a step that - * leaves this frame from its paused line (issue #1161). Its function has a - * `finally` clause, and from here it cannot suspend before it exits: no - * `await` or `yield` from the paused line to its end, and no loop above - * that leads back to one. A function that can still suspend is V8's own: - * measured, V8 keeps a step across an `await` and lands in the awaiting - * function even when the function then leaves through `finally`. + * Whether the function's text names a construct that closes through a + * finally, the only exits V8 loses a step on: `finally`, `for...of`, + * `using`. Only spares breakpoints where they cannot matter: a word in a + * comment nets a function that did not need it, and a text that cannot be + * read (V8 refuses the positions of Node's own start-up scripts) is netted. */ - private async canLoseALeavingStep(frame: CdpCallFrame): Promise { - const shape = await this.shapeOf(frame); - if (!shape?.hasFinally) { - return false; + private async namesAFinally(frame: CdpCallFrame): Promise { + const key = fnKey(frame); + const known = this.closing.get(key); + if (known !== undefined) { + return known; } - const lines = this.sources.get(frame.location.scriptId) ?? []; - const line = frame.location.lineNumber; - if (lines.slice(line, shape.to + 1).some((text) => SUSPENDS.test(text))) { - return false; + let names = true; + try { + const all = await this.locationsOf(frame); + if (all.length > 0) { + const lines = await this.linesOf(frame.location.scriptId); + const from = Math.min(frame.functionLocation?.lineNumber ?? all[0].lineNumber, all[0].lineNumber); + names = lines.slice(from, all[all.length - 1].lineNumber + 1).some((line) => CLOSES_THROUGH_FINALLY.test(line)); + } + } catch { + // Not readable: net it. } - const above = lines.slice(shape.from, line); - return !(above.some((text) => LOOPS.test(text)) && above.some((text) => SUSPENDS.test(text))); + this.closing.set(key, names); + return names; } /** Whether a net guards something below a pause of this depth. */ private guardedBelow(depth: number): boolean { - return this.nets.some((net) => net.depth < depth || net.depth === Infinity); + return this.nets.some((net) => net.depth < depth); } /** - * THE ONE RULE (see the head of this file), applied before every command - * that can leave the frame on top of `pause`: a net on what that frame - * returns to, where V8 can lose the step. Never throws: a net is a - * safeguard, and without one V8's own step goes on alone. + * THE RULE (see the head of this file), applied before every command that + * can leave the frame on top of `pause`: a net on the frame it returns to, + * only where a hit there proves the step came back. Never throws: a net is + * a safeguard, and without one V8's own step goes on alone. */ private async guard(chain: Chain, pause: CdpPaused, skipped: boolean): Promise { try { @@ -1071,44 +1104,33 @@ export class JsStepper { if (this.guardedBelow(frames.length) || (skipped && chain.walkHasNothingBelow)) { return; } - // (a) A frame of the program is read. Skipped code is not. - if (!skipped && !(await this.canLoseALeavingStep(top))) { + // (a) Only below a frame that comes down by returning, and no other way; + // and only where its text names something V8 can lose the step on. + if ((await this.canSuspend(top)) || !(await this.namesAFinally(top))) { return; } const target = await this.returnTarget(chain, pause); - if (target.kind === 'frame') { - const frame = frames[target.index]; - if (chain.kind !== 'out' && fnKey(frame) === fnKey(top)) { - // It returns to itself (recursion): a net would sit in the frame being stepped in. - return; - } - const name = frame.functionName || '(anonymous)'; - // (b) A guarded frame waiting at an await leaves the stack before anything stops. - const waiting = SUSPENDS.test((await this.linesOf(frame.location.scriptId))[frame.location.lineNumber] ?? ''); - await this.arm(await this.locationsOf(frame), frame.location, { - name, - fn: fnKey(frame), - depth: frames.length - target.index, - ...(waiting ? { anotherCall: name } : {}) - }); - } else if (target.kind === 'awaiter') { - // (b) An awaiter's net can never name the call: only where the loss is known from the text. - if (skipped && !(await this.canLoseALeavingStep(top))) { - return; + if (target.kind !== 'frame') { + if (target.kind === 'nothing' && skipped && chain.kind === 'in') { + // Nothing of the program comes to be below without the walk landing in it first. + chain.walkHasNothingBelow = true; } - const parent = target.parent; - const start: CdpLocation = { scriptId: parent.scriptId, lineNumber: parent.lineNumber, columnNumber: parent.columnNumber }; - const name = parent.functionName || '(anonymous)'; - await this.arm(await this.possible(start), start, { - name: `${name} (awaiter)`, - fn: `async:${parent.scriptId}:${parent.lineNumber}:${parent.columnNumber}`, - depth: Infinity, - anotherCall: name - }); - } else if (target.kind === 'nothing' && skipped && chain.kind === 'in') { - // Nothing of the program comes to be below without the walk landing in it first. - chain.walkHasNothingBelow = true; + return; + } + const frame = frames[target.index]; + if (chain.kind !== 'out' && fnKey(frame) === fnKey(top)) { + // It returns to itself (recursion): a net would sit in the frame being stepped in. + return; } + // (b) The guarded frame must still be on the stack when it reaches a net position. + if ((await this.canSuspend(frame)) && (await this.callStatementSuspends(frame))) { + return; + } + await this.arm(await this.locationsOf(frame), frame.location, { + name: frame.functionName || '(anonymous)', + fn: fnKey(frame), + depth: frames.length - target.index + }); } catch (err) { logger.warn(`[JsStepper] no net for this step, V8's own step goes on alone: ${errorText(err)}`); } @@ -1135,7 +1157,8 @@ export class JsStepper { * With none on the stack, the function awaiting an async one the event * loop resumed: the first frame of V8's async stack, when every link down * to it is an `await` (a `Promise.then` or timer link only scheduled the - * code on top) and js-debug marks it program code. + * code on top) and js-debug marks it program code. An awaiter is never + * netted; it only says the stack is not gone, and V8's own step leads to it. */ private async findReturnTarget(chain: Chain, pause: CdpPaused): Promise { const frames = pause.callFrames; @@ -1172,3 +1195,20 @@ export class JsStepper { return markOf(awaiter) === 'deemphasize' ? { kind: 'nothing' } : { kind: 'awaiter', parent }; } } + +/** + * Whether the function whose header is at `column` of `line` is async or a + * generator. V8's functionLocation points at the parameter list of a function + * or a method, with `[static] [async] [function] [*] [get|set] name` right + * before it, and at the first token of an arrow, which is `async` itself for + * an async one. Erring toward "it can suspend" is the safe side: a plain + * method named `async`, or a comment before the header, reads as one that can. + */ +export function suspendsByHeader(line: string, column: number): boolean { + if (/^async\b/.test(line.slice(column))) { + return true; + } + // The header's own tokens: what stands between the last delimiter and the parameter list. + const header = line.slice(0, column).split(/[=,:(;{}?!&|]/).pop() ?? ''; + return /\basync\b/.test(header) || header.includes('*'); +} diff --git a/src/utils/error-messages.ts b/src/utils/error-messages.ts index 88f4e02bc..97566d2be 100644 --- a/src/utils/error-messages.ts +++ b/src/utils/error-messages.ts @@ -305,27 +305,6 @@ export const ErrorMessages = { 'step_over again to go on, or set a breakpoint on the next line.' : `${stepped} in ${steps} steps: this adapter stops once per expression on a line, so the step was repeated until the line changed.`, - /** - * The sentence on a step caught by a temporary breakpoint that cannot name - * one call of the function it is in (issues #1130, #1161) - * Occurs when: the engine can lose a step that leaves a function through - * try...finally, so the proxy's JavaScript stepper set temporary - * breakpoints on the function the step returns to. That function was - * waiting at an `await` (its frame was not on the stack, or left it before - * anything stopped), so the breakpoints guard the FUNCTION: with several - * calls of it in flight, the one that ran next is where the step stopped. - * It does not say the engine lost this step: that cannot be told. - * Used in: src/proxy/js-stepper.ts (the `text` of the step's stopped - * event), appended to the step's message by - * src/session/execution/execution-controller.ts - * @param fn - The name of the function the step returns to - */ - stepCaughtWhereItReturns: (fn: string) => - `This step was caught by a temporary breakpoint in ${fn}, the function it returns to, because the engine can ` + - `lose a step that leaves a function through try...finally. ${fn} was waiting at an await meanwhile, so if ` + - `several calls of ${fn} are in flight this stop may be in another of them than the one the step returns to: ` + - 'check its variables.', - /** * The sentence on a step_into that reached no code of the program (issue #1130) * Occurs when: the proxy's JavaScript stepper walked into the call on the diff --git a/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts b/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts index dafe76f9e..c6fd9ce0d 100644 --- a/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts +++ b/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts @@ -171,9 +171,15 @@ describe('The server\'s JavaScript stepper against a real js-debug (issues #1130 expectLanding(await step('step_over'), 'after withFinally'); }, 60000); - it('step_out of an async function lands in its awaiter', async () => { + it('step_out of an async function with that shape is the engine\'s own, and the engine loses it (#1174)', async () => { await pausedAt('async return inside try-finally'); - expectLanding(await step('step_out'), 'after the await'); + // A temporary breakpoint below a function that can suspend cannot tell + // it returning from it pausing at an await: the server sets none, and + // the step is lost as it was before the server had a stepper. If this + // starts landing, V8 has fixed it (#1173): update the docs. + const answer = await step('step_out'); + expect(answer, JSON.stringify(answer)).toMatchObject({ success: true }); + expect(answer.state, JSON.stringify(answer)).not.toBe('paused'); }, 60000); }); @@ -245,11 +251,11 @@ describe('The server\'s JavaScript stepper against a real js-debug (issues #1130 expectAsyncLanding(await step('step_over'), 'an await inside the try'); expectAsyncLanding(await step('step_over'), 'the return inside the try'); expectAsyncLanding(await step('step_over'), 'the finally block of an async function'); - // Off the finally block V8 loses the step; it is caught at the awaiting - // function, and the answer says what that can and cannot promise. + // Off the finally block of an async function V8 loses the step, and the + // server does not rescue it (#1174): the program runs on to its end. const out = await step('step_over'); - expectAsyncLanding(out, 'after closing'); - expect(out.message).toBe(`Stepped over. ${ErrorMessages.stepCaughtWhereItReturns('main')}`); + expect(out, JSON.stringify(out)).toMatchObject({ success: true }); + expect(out.state, JSON.stringify(out)).not.toBe('paused'); }, 60000); it('step_over on a statement that awaits on a later line stays in the function: its caller runs on, and is not where the step stops', async () => { diff --git a/tests/proxy/js-statement-scan.test.ts b/tests/proxy/js-statement-scan.test.ts new file mode 100644 index 000000000..b17b88f8d --- /dev/null +++ b/tests/proxy/js-statement-scan.test.ts @@ -0,0 +1,79 @@ +/** + * The one question the proxy's JavaScript stepper asks of a caller's source + * (issues #1130, #1161): can the caller suspend between the call it is + * making returning and its next break location? Every case below is a shape + * one of the stepper's reviews found, or a way the scan could be fooled. The + * scan must err toward "it can": that costs a rescue, never a wrong landing. + */ +import { describe, it, expect } from 'vitest'; +import { statementCanSuspend } from '../../src/proxy/js-statement-scan.js'; + +/** The source, and the 0-based line and column of the call marked `@` (the marker is removed). */ +function at(source: string): { lines: string[]; line: number; column: number } { + const lines = source.split('\n'); + const line = lines.findIndex((text) => text.includes('@')); + const column = lines[line].indexOf('@'); + lines[line] = lines[line].replace('@', ''); + return { lines, line, column }; +} + +function suspends(source: string): boolean { + const { lines, line, column } = at(source); + return statementCanSuspend(lines, line, column, 0, lines.length - 1); +} + +describe('statementCanSuspend', () => { + describe('a statement that does not await: the caller reaches a break location first', () => { + it.each([ + ['a plain call', 'async function f() {\n const got = @inner(id);\n return got;\n}'], + ['a call whose line has a comment about await', 'async function f() {\n const got = @inner(id); // after the await\n}'], + ['a comment about await on the line before', 'async function f() {\n const a = 1; // MARK: after the await\n const lazy = @require("./lazy.cjs");\n}'], + ['await in a string', 'async function f() {\n const got = @inner("await me");\n}'], + ['an await in an earlier statement', 'async function f() {\n await ready;\n const got = @inner(id);\n}'], + ['an await in a later statement', 'async function f() {\n const got = @inner(id);\n await done(got);\n}'], + ['no semicolons, an await on the next statement', 'async function f() {\n const got = @inner(id)\n const more = await other(got)\n}'], + ['no semicolons, an await on the statement before', 'async function f() {\n const first = await other()\n const got = @inner(id)\n}'], + ['an await inside the block before', 'async function f() {\n try {\n await a;\n } finally {\n b();\n }\n const got = @inner(id);\n}'], + ['an object literal around the call', 'async function f() {\n const o = {\n a: @inner(id),\n b: 2\n };\n}'], + ['the call inside an if', 'async function f() {\n if (ok) {\n @inner(id);\n }\n await later;\n}'] + ])('%s', (_what, source) => { + expect(suspends(source)).toBe(false); + }); + }); + + describe('a statement that can suspend before its next break location', () => { + it.each([ + ['the call awaited', 'async function f() {\n const got = await @inner(id);\n}'], + ['returned awaited', 'async function f() {\n return await @inner(id);\n}'], + ['awaited through a member chain on the next line', 'async function f() {\n const got = await api\n .@inner(id);\n}'], + ['awaited on the line above the argument', 'async function f() {\n const total = await fetchA(\n id,\n @compute(id));\n}'], + ['an await later in the statement', 'async function f() {\n const v = @inner(id) + await other();\n}'], + ['an await in a sibling argument', 'async function f() {\n use(@inner(id), await other(id));\n}'], + ['an await in a multi-line object around the call', 'async function f() {\n return {\n user: await getUser(id),\n posts: @inner(id),\n };\n}'], + ['a yield', 'function* g() {\n const got = yield @inner(id);\n}'], + ['a for await loop anywhere in the function', 'async function f() {\n for await (const x of xs) {\n @inner(x);\n }\n}'], + ['an await using anywhere in the function', 'async function f() {\n await using h = open();\n @inner(1);\n}'], + ['a nested async callback that awaits', 'async function f() {\n @inner(items.map(async (i) => { await send(i); }));\n}'] + ])('%s', (_what, source) => { + expect(suspends(source)).toBe(true); + }); + }); + + describe('errs toward "it can" where it cannot read with confidence', () => { + it.each([ + ['a template literal with an expression', 'async function f() {\n const got = @inner(`${id}`);\n}'], + ['a string that does not end on its line', 'async function f() {\n const got = @inner("a\\\n b");\n}'], + ['a regular expression literal', 'async function f() {\n const got = @inner(/;/.test(id));\n}'], + ['a call outside the function', 'const got = @inner(id);'] + ])('%s', (_what, source) => { + const { lines, line, column } = at(source); + const outside = _what === 'a call outside the function'; + expect(statementCanSuspend(lines, line, column, outside ? line + 1 : 0, lines.length - 1)).toBe(true); + }); + + it('a statement longer than it will scan', () => { + const body = Array.from({ length: 60 }, (_, i) => ` arg${i},`).join('\n'); + expect(suspends(`async function f() {\n const got = use(\n${body}\n @inner(id));\n}`)).toBe(true); + }); + }); +}); diff --git a/tests/proxy/js-stepper.test.ts b/tests/proxy/js-stepper.test.ts index 7b465531c..319923b1a 100644 --- a/tests/proxy/js-stepper.test.ts +++ b/tests/proxy/js-stepper.test.ts @@ -13,7 +13,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; import { EventEmitter } from 'events'; import type { DebugProtocol } from '@vscode/debugprotocol'; -import { JsStepper, type JsStepperTunables } from '../../src/proxy/js-stepper.js'; +import { JsStepper, suspendsByHeader, type JsStepperTunables } from '../../src/proxy/js-stepper.js'; import { ErrorMessages } from '../../src/utils/error-messages.js'; interface Frame { @@ -24,6 +24,10 @@ interface Frame { col?: number; /** 0-based line the function starts on; defaults to a line per function name. */ fnLine?: number; + /** Column V8 reports for the function: its parameter list, or the first token of an arrow. */ + fnCol?: number; + /** The frame is a module's own code (its scope chain starts with `module`). */ + module?: boolean; /** js-debug marks it skipped code. */ skipped?: boolean; /** The mark's wording; "Skipped by skipFiles" is a script-level verdict. */ @@ -65,6 +69,12 @@ function fnLineOf(frame: Frame): number { return FN_LINES[frame.fn]; } +/** Lines in a scripted script: every function name a test uses gets a hundred of its own (see fnLineOf). */ +const SOURCE_LINES = 30000; + +/** A script's text when a test writes none: plain statements, nothing that suspends or closes through a finally. */ +const DEFAULT_SOURCE = Array.from({ length: SOURCE_LINES }, () => 'x();').join('\n'); + /** A scripted V8 behind a CDP socket, and the js-debug that watches it. */ class Engine extends EventEmitter { calls: Array<{ method: string; params: Record }> = []; @@ -82,7 +92,7 @@ class Engine extends EventEmitter { stackTraceFailures = 0; stackTraceCalls: number[] = []; /** Scripts V8 refuses break positions for (Node's own, measured). */ - refuse = new Set(); + refuse = new Set(['node:internal']); /** A CDP method that fails the next time it is sent, and ones that always fail. */ failOnce: string | null = null; failAlways = new Set(); @@ -130,7 +140,8 @@ class Engine extends EventEmitter { this.armed = this.armed.filter((bp) => bp.id !== params.breakpointId); return {} as T; case 'Debugger.getScriptSource': - return { scriptSource: this.sources.get(params.scriptId as string) ?? '' } as T; + // V8 gives the source of every script, Node's own included. + return { scriptSource: this.sources.get(params.scriptId as string) ?? DEFAULT_SOURCE } as T; default: return {} as T; } @@ -199,8 +210,9 @@ class Engine extends EventEmitter { hitBreakpoints: hits, callFrames: pause.frames.map((f) => ({ functionName: f.fn, - functionLocation: { scriptId: f.script ?? 'app', lineNumber: fnLineOf(f), columnNumber: 0 }, - location: { scriptId: f.script ?? 'app', lineNumber: f.line, columnNumber: f.col ?? 0 } + functionLocation: { scriptId: f.script ?? 'app', lineNumber: fnLineOf(f), columnNumber: f.fnCol ?? 0 }, + location: { scriptId: f.script ?? 'app', lineNumber: f.line, columnNumber: f.col ?? 0 }, + scopeChain: f.module ? [{ type: 'module' }, { type: 'global' }] : [{ type: 'local' }, { type: 'global' }] })), ...(pause.asyncParent ? { asyncStackTrace: this.asyncTrace(pause.asyncParent) } : {}) }; @@ -287,7 +299,7 @@ describe('JsStepper (issue #1130)', () => { for (const [line, text] of Object.entries(lines)) { known.set(Number(line), text); } - const source = Array.from({ length: 2000 }, () => 'x();'); + const source = Array.from({ length: SOURCE_LINES }, () => 'x();'); for (const [line, text] of known) { source[line] = text; } @@ -594,7 +606,7 @@ describe('JsStepper (issue #1130)', () => { }); it('a step over arms nothing in a function with no `finally`, and the frame it returns to in one that has it', async () => { - engine.sources.set('app', Array.from({ length: 2000 }, () => 'x();').join('\n')); + engine.sources.set('app', Array.from({ length: SOURCE_LINES }, () => 'x();').join('\n')); engine.pauseAt({ frames: frames(app('plain', 5), app('caller', 14)) }); engine.script = [{ frames: frames(app('plain', 6), app('caller', 14)) }]; await stepper.request('next', { threadId: 1 }); @@ -602,7 +614,7 @@ describe('JsStepper (issue #1130)', () => { expect(setBreakpoints()).toBe(0); delivered.length = 0; - const source = Array.from({ length: 2000 }, () => 'x();'); + const source = Array.from({ length: SOURCE_LINES }, () => 'x();'); source[fnLineOf(app('guarded', 0)) + 2] = 'try { return x(); } finally { done(); }'; engine.sources.set('lib', source.join('\n')); engine.pauseAt({ frames: frames(app('guarded', fnLineOf(app('guarded', 0)) + 2, { script: 'lib' }), app('caller', 14)) }); @@ -615,7 +627,7 @@ describe('JsStepper (issue #1130)', () => { }); it('puts no net on the frame being stepped in: a function with `finally` that returns to itself', async () => { - const source = Array.from({ length: 2000 }, () => 'x();'); + const source = Array.from({ length: SOURCE_LINES }, () => 'x();'); const start = fnLineOf(app('down', 0)); source[start + 2] = 'try { return down(n - 1); } finally { done(); }'; engine.sources.set('app', source.join('\n')); @@ -981,7 +993,7 @@ describe('JsStepper (issue #1130)', () => { }); describe('an async function the event loop resumed', () => { - it('steps out by V8 alone: its own async step finds the one awaiting call, where a net on the function would stop in any', async () => { + it('steps out by V8 alone: its own async step finds the one awaiting call, and nothing off the stack is ever netted', async () => { engine.pauseAt({ frames: frames(app('inner', 5)), asyncParent: { fn: 'handler', line: 9, col: 14 } }); engine.script = [{ frames: frames(app('handler', 10)), asyncParent: { fn: 'main', line: 14 } }]; await stepper.request('stepOut', { threadId: 1 }); @@ -992,31 +1004,7 @@ describe('JsStepper (issue #1130)', () => { expect(stopped().text).toBeUndefined(); }); - it('nets the awaiting function only where V8 loses the step (`finally` in the function left), and says the stop may be another call\'s', async () => { - const start = fnLineOf(app('innerF', 0)); - sourceWith({ [start + 1]: 'try { await gate;', [start + 2]: ' const tag = id; return tag;', [start + 3]: '} finally { noop(); }' }); - engine.pauseAt({ frames: frames(app('innerF', start + 2)), asyncParent: { fn: 'handler', line: 9, col: 14 } }); - // V8's step-out is lost; the next thing V8 says is the net in `handler`. - engine.script = [{ frames: frames(app('handler', 10)), reason: 'other', hits: (armed) => [armed[0].id] }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - // Asked from the awaiter's own position, since its frame is not on the stack. - const asked = engine.calls.filter((c) => c.method === 'Debugger.getPossibleBreakpoints').map((c) => c.params.start); - expect(asked).toContainEqual({ scriptId: 'app', lineNumber: 9, columnNumber: 14 }); - expect(stopped()).toMatchObject({ reason: 'step', text: ErrorMessages.stepCaughtWhereItReturns('handler') }); - expect(engine.armed).toEqual([]); - }); - it('nets no awaiter that is skipped code', async () => { - const start = fnLineOf(app('innerG', 0)); - sourceWith({ [start + 1]: 'try { await gate;', [start + 2]: ' const tag = id; return tag;', [start + 3]: '} finally { noop(); }' }); - engine.pauseAt({ frames: frames(app('innerG', start + 2)), asyncParent: { fn: 'libRun', line: 9, script: 'lib', skipped: true } }); - engine.script = ['runs']; - await stepper.request('stepOut', { threadId: 1 }); - await tick(5); - expect(setBreakpoints()).toBe(0); - await stepper.beforeRequest('continue'); - }); it('does not take what only scheduled the code for what it returns to: a step out of a `.then` callback resumes', async () => { engine.pauseAt({ frames: frames(app('onDone', 3)), asyncParent: { fn: 'work', line: 7, description: 'Promise.then' } }); @@ -1055,46 +1043,6 @@ describe('JsStepper (issue #1130)', () => { expect(delivered).toEqual([]); }); - it('a step over arms nothing while the step cannot leave a function that can suspend: only on a `return` line, and from its `finally` on', async () => { - const start = fnLineOf(app('mainAsync', 0)); - sourceWith({ - [start + 1]: 'const first = await sleep(20);', - [start + 2]: 'try {', - [start + 3]: ' const second = await sleep(20);', - [start + 4]: ' return second;', - [start + 5]: '} finally {', - [start + 6]: ' done();', - [start + 7]: '}' - }); - // On an await line the function suspends and its caller runs on: a net on the caller would stop there. - engine.pauseAt({ frames: frames(app('mainAsync', start + 1), app('caller', 14)) }); - engine.script = [{ frames: frames(app('mainAsync', start + 3)) }]; - await stepper.request('next', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBe(0); - expect(stopped()).toMatchObject({ reason: 'step' }); - - // On the return line the step can leave through `finally`: the frame it returns to is netted. - delivered.length = 0; - engine.calls.length = 0; - engine.pauseAt({ frames: frames(app('mainAsync', start + 4), app('caller', 14)) }); - engine.script = [{ frames: frames(app('mainAsync', start + 6), app('caller', 14)) }]; - await stepper.request('next', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBeGreaterThan(0); - expect(engine.armed).toEqual([]); - - // And in the finally block, where V8 loses it. - delivered.length = 0; - engine.calls.length = 0; - engine.pauseAt({ frames: frames(app('mainAsync', start + 6), app('caller', 14)) }); - engine.script = [{ frames: frames(app('caller', 15)), reason: 'other', hits: (armed) => [armed[1].id] }]; - await stepper.request('next', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBeGreaterThan(0); - expect(stopped()).toMatchObject({ reason: 'step' }); - expect(engine.armed).toEqual([]); - }); it('reads `finally` in the function\'s own text only', async () => { const start = fnLineOf(app('plainF', 0)); @@ -1412,8 +1360,8 @@ describe('JsStepper (issue #1130)', () => { // ----- the one rule for where a net is set (what the second review found) ----- - describe('rule (a): a net only where V8 can lose the step and the frame cannot suspend first', () => { - it('sets none for a step out of a function with no finally clause: V8 does not lose that step', async () => { + describe('a net only where a hit proves the step came back', () => { + it('spares the breakpoints for a plain function whose text names nothing that closes through a finally', async () => { engine.pauseAt({ frames: frames(app('plainOut', 5), app('caller', 14)) }); engine.script = [{ frames: frames(app('caller', 15)) }]; await stepper.request('stepOut', { threadId: 1 }); @@ -1422,75 +1370,9 @@ describe('JsStepper (issue #1130)', () => { expect(stopped()).toMatchObject({ reason: 'step' }); }); - it('sets none when the statement awaits on a later line: the function suspends, and its caller runs on', async () => { - const start = fnLineOf(app('load', 0)); - sourceWith({ - [start + 1]: 'try { noop(); } finally { noop(); }', - [start + 2]: 'return {', - [start + 3]: ' user: await getUser(first),', - [start + 4]: '};' - }); - engine.pauseAt({ frames: frames(app('load', start + 2), app('caller', 14)) }); - engine.script = [{ frames: frames(app('caller', 15)) }]; - await stepper.request('next', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBe(0); - }); - - it('sets none when a loop above leads back to an await, and one when no loop does', async () => { - const start = fnLineOf(app('looped', 0)); - sourceWith({ - [start + 1]: 'for (const x of xs) {', - [start + 2]: ' await tick();', - [start + 3]: ' const tag = x;', - [start + 4]: '}', - [start + 5]: 'try { return 1; } finally { done(); }' - }); - // The same text without the loop (the stepper reads a script's text once). - const other = fnLineOf(app('straight', 0)); - sourceWith({ - [other + 1]: 'await ready;', - [other + 3]: 'const tag = x;', - [other + 5]: 'try { return 1; } finally { done(); }' - }); - engine.pauseAt({ frames: frames(app('looped', start + 3), app('caller', 14)) }); - engine.script = [{ frames: frames(app('caller', 15)) }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBe(0); - // Without the loop nothing can suspend it before it exits. - engine.calls.length = 0; - engine.pauseAt({ frames: frames(app('straight', other + 3), app('caller', 14)) }); - engine.script = [{ frames: frames(app('caller', 15)), reason: 'other', hits: (armed) => [armed[0].id] }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBeGreaterThan(0); - expect(engine.armed).toEqual([]); - }); - it('reads a yield ahead as a suspension too', async () => { - const start = fnLineOf(app('gen', 0)); - sourceWith({ [start + 1]: 'try { noop(); } finally { noop(); }', [start + 4]: 'yield value;' }); - engine.pauseAt({ frames: frames(app('gen', start + 2), app('caller', 14)) }); - engine.script = [{ frames: frames(app('caller', 15)) }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBe(0); - }); - it.each([ - ['the word in a comment', '// and finally we are done'], - ['a promise chain', 'work().finally(() => done());'] - ])('does not take %s for a finally clause', async (_what, text) => { - const start = fnLineOf(app('wordy', 0)); - sourceWith({ [start + 4]: text }); - engine.pauseAt({ frames: frames(app('wordy', start + 2), app('caller', 14)) }); - engine.script = [{ frames: frames(app('caller', 15)) }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBe(0); - }); it.each([ ['after the closing brace', '} finally {'], @@ -1506,7 +1388,7 @@ describe('JsStepper (issue #1130)', () => { expect(setBreakpoints()).toBeGreaterThan(0); }); - it('does not take what only scheduled a function that can lose the step for its awaiter', async () => { + it('sets none for a callback nothing of the program called: what registered it is not on the stack', async () => { // A `.then` callback with a finally clause: its async parent registered it, and is not what it returns to. engine.pauseAt({ frames: frames(lossy(app('onDone', 3))), asyncParent: { fn: 'work', line: 7, description: 'Promise.then' } }); engine.script = ['runs']; @@ -1516,16 +1398,6 @@ describe('JsStepper (issue #1130)', () => { await stepper.beforeRequest('continue'); }); - it('finds the awaiter behind the empty links V8 lists for the function\'s later awaits', async () => { - const start = fnLineOf(app('later', 0)); - sourceWith({ [start + 1]: 'try { await a; await b;', [start + 2]: ' return tag;', [start + 3]: '} finally { noop(); }' }); - engine.pauseAt({ frames: frames(app('later', start + 2)), asyncParent: { fn: 'handler', line: 9, col: 14, emptyLinks: 2 } }); - engine.script = [{ frames: frames(app('handler', 10)), reason: 'other', hits: (armed) => [armed[0].id] }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBeGreaterThan(0); - expect(stopped()).toMatchObject({ reason: 'step', text: ErrorMessages.stepCaughtWhereItReturns('handler') }); - }); it('steps out with V8 alone, and does not resume, when js-debug never says what is below', async () => { // A first step teaches the stepper that Node's script is skipped. @@ -1546,27 +1418,6 @@ describe('JsStepper (issue #1130)', () => { }); }); - describe('rule (b): a net that cannot name one call says so', () => { - it('says the stop may be another call\'s when the frame it guards was waiting at an await', async () => { - // handler awaits the call: it suspends as soon as the call returns, and leaves the stack. - sourceWith({ 14: 'const got = await inner(id);' }); - engine.pauseAt({ frames: frames(lossy(app('innerSync', 30)), app('handler', 14)) }); - engine.script = [{ frames: frames(app('handler', 15)), reason: 'other', hits: (armed) => [armed[1].id] }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - expect(stopped()).toMatchObject({ reason: 'step', text: ErrorMessages.stepCaughtWhereItReturns('handler') }); - }); - - it('says nothing when the frame it guards stays on the stack', async () => { - sourceWith({ 14: 'const got = inner(id);' }); - engine.pauseAt({ frames: frames(lossy(app('innerSync', 30)), app('handler', 14)) }); - engine.script = [{ frames: frames(app('handler', 15)), reason: 'other', hits: (armed) => [armed[1].id] }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - expect(stopped()).toMatchObject({ reason: 'step' }); - expect(stopped().text).toBeUndefined(); - }); - }); describe('more edges the second mutation pass found unpinned', () => { it('reports a pause taken on one of its own net positions as the pause, though js-debug calls it a breakpoint', async () => { @@ -1679,6 +1530,208 @@ describe('JsStepper (issue #1130)', () => { }); }); + // ----- the provable rule: rule (a), the frame being left; rule (b), the frame guarded ----- + + describe('what can suspend, read from the function\'s header', () => { + // [the header's line, where V8's functionLocation points in it, whether it can suspend]: as measured. + it.each([ + ['function plainDecl() { }', 18, false], + ['const plainExpr = function () { };', 27, false], + ['const plainArrow = () => { };', 19, false], + ['async function asyncDecl() { }', 24, true], + ['const asyncExpr = async function () { };', 33, true], + ['const asyncArrow = async () => { };', 19, true], + ['const asyncArrowBare = async a => { };', 23, true], + ['function* genDecl() { }', 17, true], + ['const genExpr = function* () { };', 26, true], + ['async function* asyncGen() { }', 24, true], + [' method() { }', 8, false], + [' async asyncMethod() { }', 19, true], + [' *genMethod() { }', 12, true], + [' async *asyncGenMethod() { }', 23, true], + [' static async staticAsync() { }', 26, true], + [' get prop() { return 1; }', 10, false], + [' objPlain() { },', 10, false], + [' arrowProp: async () => { }', 13, true], + ['Module.prototype.require = function(id) {', 35, false], + ['run(function inner() { }, async function next() { });', 18, false], + ['run(function inner() { }, async function next() { });', 45, true] + ])('%s at column %i', (line, column, expected) => { + expect(suspendsByHeader(line, column)).toBe(expected); + }); + + it('errs toward "it can": a plain method named async, a comment before the header', () => { + expect(suspendsByHeader(' async() { }', 7)).toBe(true); + expect(suspendsByHeader('/* async */ function f() { }', 22)).toBe(true); + }); + }); + + describe('rule (a): only a plain function is netted', () => { + /** The frame, with its function written as this header (V8 points at the parameter list). */ + function headed(frame: Frame, header: string): Frame { + sourceWith({ [fnLineOf(frame)]: header }, frame.script ?? 'app'); + return { ...frame, fnCol: header.includes('=>') && !header.includes('(') ? header.indexOf('async') : header.indexOf('(') }; + } + + it.each([ + ['an async function', 'async function work() {'], + ['a generator', 'function* work() {'], + ['an async method', ' async work() {'] + ])('sets none below %s, whatever it contains: V8 keeps a step across an await, and what it loses there stays lost', async (_what, header) => { + const start = fnLineOf(app('suspender', 0)); + const top = headed(app('suspender', start + 2), header); + sourceWith({ [start + 4]: 'try { return x(); } finally { done(); }' }); + engine.pauseAt({ frames: frames(top, app('caller', 14)) }); + engine.script = [{ frames: frames(app('caller', 15)) }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBe(0); + expect(stopped()).toMatchObject({ reason: 'step' }); + }); + + it('sets none below a module\'s own code, which may await at its top level', async () => { + const start = fnLineOf(app('(module code)', 0)); + sourceWith({ [start + 4]: 'try { x(); } finally { done(); }' }); + engine.pauseAt({ frames: frames(app('(module code)', start + 2, { module: true }), app('caller', 14)) }); + engine.script = [{ frames: frames(app('caller', 15)) }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBe(0); + }); + + it.each([ + ['a comment that says await', '// nothing to await here'], + ['a nested async callback', 'items.map(async (item) => { await send(item); });'], + ['a loop', 'for (const item of items) { use(item); }'] + ])('nets a plain function whatever its text says: %s', async (_what, text) => { + const start = fnLineOf(app('plainWith', 0)); + sourceWith({ [start + 1]: text, [start + 4]: 'try { return x(); } finally { done(); }' }); + engine.pauseAt({ frames: frames(app('plainWith', start + 2), app('caller', 14)) }); + engine.script = [{ frames: frames(app('caller', 15)), reason: 'other', hits: (armed) => [armed[0].id] }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBeGreaterThan(0); + expect(stopped()).toMatchObject({ reason: 'step' }); + expect(stopped().text).toBeUndefined(); + expect(engine.armed).toEqual([]); + }); + + it.each([ + ['a return out of for...of', 'for (const item of items) { if (item) return item; }'], + ['a using declaration', 'using handle = open();'] + ])('nets the exits V8 loses with no finally written: %s', async (_what, text) => { + const start = fnLineOf(app('implicit', 0)); + sourceWith({ [start + 3]: text }); + engine.pauseAt({ frames: frames(app('implicit', start + 2), app('caller', 14)) }); + engine.script = [{ frames: frames(app('caller', 15)), reason: 'other', hits: (armed) => [armed[0].id] }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBeGreaterThan(0); + expect(stopped()).toMatchObject({ reason: 'step' }); + }); + + it('nets Node\'s own code without reading its text for a finally: V8 refuses its break positions', async () => { + // A step over that returns into Node's code: the frame left next is Node's, plain by its header. + engine.pauseAt({ frames: frames(app('listener', 40), node('emit', 7), app('main', 10)) }); + engine.script = [ + { frames: frames(node('emit', 8), app('main', 10)) }, + { frames: frames(app('main', 11)), reason: 'other', hits: (armed) => [armed[0].id] } + ]; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBeGreaterThan(0); + expect(commands()).toEqual(['Debugger.stepOver', 'Debugger.stepOut']); + expect(stopped()).toMatchObject({ reason: 'step' }); + }); + + it('sets none below Node\'s own async code: its header is read like any other', async () => { + sourceWith({ [fnLineOf(node('readFile', 0))]: 'async function readFile(path, options) {' }, 'node:internal'); + const top: Frame = { ...node('readFile', 7), fnCol: 23 }; + engine.pauseAt({ frames: frames(app('callback', 40), top, app('main', 10)) }); + engine.script = [ + { frames: frames({ ...top, line: 8 }, app('main', 10)) }, + { frames: frames(app('main', 11)) } + ]; + await stepper.request('next', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBe(0); + expect(commands()).toEqual(['Debugger.stepOver', 'Debugger.stepOut']); + }); + }); + + describe('rule (b): the frame guarded must still be on the stack when it reaches a net position', () => { + /** `handler` at line 14, written as an async function or a plain one, calling the function being left. */ + async function stepOutInto(header: string, statement: string): Promise { + const handler = app('handler', 14, { fnCol: header.indexOf('(') }); + sourceWith({ [fnLineOf(handler)]: header, 14: statement }); + engine.pauseAt({ frames: frames(lossy(app('innerSync', 30)), handler) }); + engine.script = [{ frames: frames({ ...handler, line: 15 }) }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + } + + it('sets none when an async caller awaits the call: it leaves the stack at once, and another call can take its depth', async () => { + await stepOutInto('async function handler(id) {', 'const got = await inner(id);'); + expect(setBreakpoints()).toBe(0); + expect(stopped()).toMatchObject({ reason: 'step' }); + }); + + it('sets none when the await stands elsewhere in the calling statement', async () => { + await stepOutInto('async function handler(id) {', 'use(inner(id), await other(id));'); + expect(setBreakpoints()).toBe(0); + }); + + it('nets an async caller whose statement awaits nothing: it reaches its next position before it can suspend', async () => { + await stepOutInto('async function handler(id) {', 'const got = inner(id);'); + expect(setBreakpoints()).toBeGreaterThan(0); + expect(stopped().text).toBeUndefined(); + }); + + it('nets a plain caller whatever its statement says', async () => { + await stepOutInto('function handler(id) {', 'const got = wait(inner(id)); // await it later'); + expect(setBreakpoints()).toBeGreaterThan(0); + }); + }); + + describe('a pause asked for while the stack turns out to be gone', () => { + it('does not resume the program: V8 is paused, and that stop is the caller\'s', async () => { + let gated = false; + let release: () => void = () => undefined; + stepper = new JsStepper({ + target: { + sendRequest: async (_c: string, args?: unknown) => { + if (gated) { + await new Promise((resolve) => { + release = resolve; + }); + } + return engine.stackTrace((args as { levels: number }).levels) as never; + } + }, + deliver: (event) => delivered.push(event), + tunables: { settleCeilingMs: 150, verdictCeilingMs: 150 } + }); + engine.onDap = (event) => { + seen.push({ event: event.event, withheld: stepper.withholds(event) }); + }; + stepper.attachCdp(engine); + stepper.setEnabled(true); + // A handler Node called: stepping out of it leaves nothing of the program on the stack. + engine.pauseAt({ frames: frames(app('handler', 20), node('emit', 7), node('parserOnIncoming', 3)) }); + engine.script = [{ frames: frames(node('emit', 8), node('parserOnIncoming', 3)) }]; + await stepper.request('stepOut', { threadId: 1 }); + gated = true; + await tick(10); + await stepper.beforeRequest('pause'); + gated = false; + release(); + await settled(); + expect(commands()).toEqual(['Debugger.stepOut']); + expect(delivered).toHaveLength(1); + expect(stopped()).toMatchObject({ reason: 'pause' }); + }); + }); + it('refuses a step it cannot start, and leaves no net behind', async () => { engine.pauseAt({ frames: frames(app('leaf', 5), app('caller', 14)) }); engine.current = null; // V8 resumed behind the stepper's back From f6d5265202adeeb39f12ed24a8426d9e35bbc832 Mon Sep 17 00:00:00 2001 From: JF Date: Mon, 16 Nov 2026 10:46:56 -0500 Subject: [PATCH 13/24] docs(javascript): what the server rescues, and what it leaves to V8 (#1161, #1173, #1174) The JavaScript guide, the tool reference and the #1161 fragment state the provable rule: temporary breakpoints only below a plain function, on a caller that stays on the stack until it reaches one. They name what that leaves lost, as in 0.26.0: a step V8 loses while leaving an async function or a generator, and a step out of a plain function whose caller awaits the call (#1174). The cause in V8 is named, with its issue (#1173). The pending-step sentence names that case among the reasons a step can be pending. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015BDrn69pXrYMWc1JUwv5v8 --- changelog.d/1161.fixed.md | 2 +- docs/javascript/README.md | 60 ++++++++----------- docs/tool-reference.md | 20 +++---- .../src/interfaces/adapter-policy-js.ts | 4 +- 4 files changed, 40 insertions(+), 46 deletions(-) diff --git a/changelog.d/1161.fixed.md b/changelog.d/1161.fixed.md index 9a852a207..03ec96b7a 100644 --- a/changelog.d/1161.fixed.md +++ b/changelog.d/1161.fixed.md @@ -1 +1 @@ -**A JavaScript step that leaves a function through `return` inside `try … finally` lands in the caller.** V8 can lose such a step (measured on V8 12.4, 13.6 and 14.6 with a bare CDP client): a `step_out` of the function, a `step_over` off its `finally` block, and a `step_out` of an `async` function with that shape all answered `Step completed as session exited.` while the program ran on. Node's own module loader returns that way too, which is how a `step_into` on a `require` line was lost. Where V8 can lose a step, the server no longer counts on V8 alone to come back to the frame below: it sets temporary breakpoints on that frame, and whichever pauses first is the landing. That is something the server does in your process: at most 24 temporary breakpoints per guarded frame, for the length of one step, removed when the step ends however it ends. One rule says when, for all three steps: from your own code only where the function has a `finally` clause and cannot suspend before it exits from the paused line (a function that awaits does not return to its caller, and V8 keeps a step across an `await`); from skipped code always; never on the frame being stepped in. The breakpoints name one call only while the frame they guard stays on the stack. Where it does not (it was waiting at an `await` for the call the step leaves, or it is the function awaiting an `async` one the event loop resumed) the step stops in whichever call of that function runs next, and the answer says so (#1166). Not covered: a `step_over` across the first load of a module that has a breakpoint in it still runs on (#1162). (#1161) +**A JavaScript step out of a function that returns inside `try … finally` lands in the caller.** V8 loses such a step (measured on V8 12.4, 13.6 and 14.6 with a bare CDP client; also a `return` out of a `for … of` loop and out of a function with a `using` declaration): a `step_out` of the function and a `step_over` off its `finally` block answered `Step completed as session exited.` while the program ran on. Node's own module loader returns that way too, which is how a `step_into` on a `require` line was lost. The server now sets temporary breakpoints on the frame such a step returns to, and whichever pauses first is the landing. That is something the server does in your process: at most 24 temporary breakpoints per guarded frame, for the length of one step, removed when the step ends however it ends. They are set only where a hit proves the step came back: the function being left is a plain one (not `async`, not a generator), and the frame it returns to stays on the stack until it reaches one. A step V8 loses in an `async` function or a generator is not rescued: a breakpoint below a function that can suspend cannot tell it returning from it pausing at an `await`, so that step stays lost as before and its pending answer says so (#1174). Not covered either: a `step_over` across the first load of a module that has a breakpoint in it (#1162). (#1161) diff --git a/docs/javascript/README.md b/docs/javascript/README.md index 1ff29ea25..3306a5dbb 100644 --- a/docs/javascript/README.md +++ b/docs/javascript/README.md @@ -119,7 +119,7 @@ What a step does when the session steps through skipped code (the launch default | `step_into` | a line that calls native code only (`JSON.stringify`) | on the next line, as a plain `Stepped into`: there is nothing to walk into | | `step_into` | a line that only starts a later task (`setTimeout`, a `.then` callback) | on the next line, never in the callback some time later; a breakpoint in the callback stops there | | `step_over`, `step_out` | a frame whose caller is skipped code, with your code further down the stack | in that frame of yours | -| `step_out` | an `async` function the event loop resumed | in the function that awaits it, in the call that awaited | +| `step_out` | an `async` function the event loop resumed | in the function that awaits it, in the call that awaited (V8's own step) | | `step_over`, `step_out` | the last line of a function that nothing of yours called or awaits (a request handler, a timer callback, a `.then` callback) | nowhere of its own: nothing of your program is on the stack. If another callback of yours is already queued behind a `.then` callback, V8's step stops in it; otherwise the program is resumed, and the answer is the next stop if one comes while the step waits (a breakpoint, the program's end), or `pending: true` if none does (on a launch, with a sentence saying the step left its frame) | | any step | skipped code (a breakpoint inside a dependency) | `step_into` walks on into your handler; `step_over` and `step_out` run on as in the row above. `justMyCode: false` steps inside that code | @@ -144,42 +144,34 @@ derived value. Attach defaults `smartStep` to `false` and leaves `skipFiles` uns `console.log` line stops in ``, and an `async` callee in TypeScript compiled for a target below ES2017 costs four unmapped `__awaiter` stops before its first line (issue #687). -**Steps V8 itself loses** (issue #1161). V8 can lose a step that leaves a function through a `return` written -inside `try … finally` (measured on V8 12.4, 13.6 and 14.6 with a bare CDP client): a `step_out` of such a function, -or a `step_over` off its `finally` block, used to answer `Step completed as session exited.` Node's own module -loader has that shape, which is how a `step_into` on a `require` line was lost too. So where V8 can lose a step, the -server does not count on V8 alone to come back to the frame below: it sets temporary breakpoints on that frame (the -nearest frame of your program down the stack), and whichever pauses first is the landing. That is something the -server does in your process: up to 24 temporary breakpoints per guarded frame, for the length of one step, removed -when the step ends, however it ends. Where they cannot be set (V8 gives no break positions for Node's own scripts) -the step goes on with V8 alone. - -One rule says when they are set, for all three steps: - -- **From your own code**, only when the function has a `finally` clause and, from the paused line, cannot suspend - before it exits: no `await` or `yield` ahead, and no loop above that leads back to one. A function that suspends - does not return to its caller: the caller runs on, and a breakpoint there would stop the step in the caller while - V8 is still on its way to the next line. And V8 keeps a step across an `await` (measured: it lands in the awaiting - function even when the function then leaves through `finally`), so there is nothing to rescue. This reads the - function's text; it is not a parse, and it errs toward V8's own step. -- **From skipped code** (a step that walks through Node's code or a dependency), always. That code is not read, and - wherever control comes down from it, your frame below is the landing. +**Steps V8 itself loses** (issue #1161). V8 loses a step that leaves a function through a `return` that runs a +`finally` first (measured on V8 12.4, 13.6 and 14.6 with a bare CDP client): a `step_out` of such a function, or a +`step_over` off its last statement, used to answer `Step completed as session exited.` A `return` out of a +`for … of` loop and out of a function with a `using` declaration close the same way. Node's own module loader has +that shape, which is how a `step_into` on a `require` line was lost too. (The cause is in V8: the return replayed +after the `finally` block carries no source position, so it is not a place a step can stop; issue #1173.) + +So where a step can be lost that way, the server sets temporary breakpoints on the frame the step returns to, and +whichever pauses first is the landing. That is something the server does in your process: up to 24 temporary +breakpoints per guarded frame, for the length of one step, removed when the step ends, however it ends. Where they +cannot be set the step goes on with V8 alone. + +They are set only where a hit there proves the step came back: + +- **The function being left is a plain one**: not `async`, not a generator, not a module's own code (read from the + function's header, for Node's own code as for yours). A plain function comes down only by returning, so control + back in the frame below means it returned. An `async` function or a generator can also hand control down by + suspending at an `await` or `yield`, and a breakpoint below would then stop the step in the caller while it is + still on its way to the next line, or in another call of the same function. So those steps are V8's own. +- **The frame it returns to stays on the stack** until it reaches one of them: a plain function does; an `async` + one does unless the statement making the call awaits (`const got = await inner(id)` suspends the caller as soon + as the call returns, and another call of the same function can take its place). - **Never on the frame being stepped in**: a function that returns to itself (recursion) gets none for `step_over` and `step_into`. -The breakpoints are kept with the depth of the frame they guard, which names that one call while it stays on the -stack. Two cases have no such frame. There the step stops in whichever call of the function runs next, and the -answer says so (`This step was caught by a temporary breakpoint in handler, the function it returns to, … if -several calls of handler are in flight this stop may be in another of them than the one the step returns to: check -its variables.`): - -- the guarded frame was itself waiting at an `await` for the call the step leaves (`const got = await inner(id)`): - it leaves the stack before anything stops; -- the function the step returns to was never on the stack: the one awaiting an `async` function the event loop - resumed. V8's own step finds the call that awaited, so that function is guarded only where the loss is known from - the text. - -With one call in flight the stop is the right one (issue #1166). +What that leaves lost, as in 0.26.0: a step V8 loses in an `async` function or a generator, and a step out of a +plain function whose caller awaits the call. Such a step answers `pending: true`, and its sentence names the case. +A breakpoint on the line you expected the step to reach stops there. Not covered: a `step_over` across the first load of a module that has a breakpoint in it still runs on (issue #1162; js-debug pauses at the module's entry to bind the breakpoint, and V8 drops the step at any pause). A diff --git a/docs/tool-reference.md b/docs/tool-reference.md index 5ccc9c421..2ba66724c 100644 --- a/docs/tool-reference.md +++ b/docs/tool-reference.md @@ -706,8 +706,10 @@ The step is not cancelled: the session becomes `"paused"` on its own when it com The adapter may append one sentence to that message saying what the step is waiting for. The JavaScript adapter does so for a launch that steps through skipped code (issues #678, #1130): a step issued from skipped code names the frame and says a step does not stop there, and any other pending step says it left the frame it started in -and has not stopped in your program since (a function Node called returned to the event loop, or the line is -waiting on work in flight). An attach that steps through skipped code (`smartStep: true`) gets no such sentence. +and has not stopped in your program since (a function Node called returned to the event loop, the line is +waiting on work in flight, or the engine lost the step: V8 loses one that leaves an `async` function or a +generator through `try … finally`, a `for … of` loop or a `using` declaration, and the server rescues only +plain functions). An attach that steps through skipped code (`smartStep: true`) gets no such sentence. So match a pending step by its `pending: true` flag, not by the message text. Once a stop has been observed, the stop path owns the answer — a step that demonstrably landed is never reported as pending afterwards, at the cost of the response then being bounded by the stack-trace round trip rather than by the ~5s window. If the debuggee ends while the step is in flight the result is still a success, with a terminal `state` and a message such as `"Step completed as session terminated."`. @@ -779,14 +781,12 @@ Same ~5s wait and `pending: true` contract as step_over — see [Pending steps]( - Out of an `async` function the event loop resumed, the step lands in the function that awaits it, in the call that awaited: that is the engine's own step. -- The engine can lose a step that leaves a function through `try … finally`. Where the function has a `finally` - clause and cannot suspend before it exits, the server catches the step with temporary breakpoints on the function - it returns to. When those cannot name one call (that function was waiting at an `await`), the stop is in - whichever call of it runs next, and the message says so: `Stepped out. This step was caught by a temporary - breakpoint in handler, the function it returns to, because the engine can lose a step that leaves a function - through try...finally. handler was waiting at an await meanwhile, so if several calls of handler are in flight - this stop may be in another of them than the one the step returns to: check its variables.` The same sentence - can follow a `step_over` or `step_into` that leaves such a function. +- The engine loses a step that leaves a function through `try … finally` (also a `return` out of `for … of`, + and a function with a `using` declaration). Out of a plain function the server catches it with temporary + breakpoints on the caller, so the step lands there. Out of an `async` function or a generator it does not: a + breakpoint below a function that can suspend cannot tell the function returning from it pausing at an `await`. + Such a step stays lost, as in 0.26.0, and answers `pending: true`; a breakpoint on the caller's next line stops + there. - Out of a function that nothing of your program called or awaits (a timer callback, a `.then` callback, a request handler) there is nowhere of its own to land: the program is resumed, and the answer is the next stop or `pending: true`. diff --git a/packages/shared/src/interfaces/adapter-policy-js.ts b/packages/shared/src/interfaces/adapter-policy-js.ts index 6d756f33d..66644b202 100644 --- a/packages/shared/src/interfaces/adapter-policy-js.ts +++ b/packages/shared/src/interfaces/adapter-policy-js.ts @@ -450,7 +450,9 @@ export const JsDebugAdapterPolicy = { 'dapLaunchArgs.justMyCode: false (or adapterLaunchConfig.smartStep: false) to step inside that code.'; } return 'The step left the frame it started in and has not stopped in your program since: a function that Node ' + - 'called returned to the event loop, or the line is waiting on work still in flight. The program is running; ' + + 'called returned to the event loop, the line is waiting on work still in flight, or the engine lost the step ' + + '(V8 loses one that leaves an async function or a generator through try...finally, a for...of loop or a ' + + 'using declaration; a breakpoint on the line you expected it to reach stops there). The program is running; ' + 'wait_for_stop answers when the step lands, a breakpoint is hit, or the program ends.'; }, From 6e1a665fa693a99052bef7f8f7800b57208eb3cb Mon Sep 17 00:00:00 2001 From: JF Date: Mon, 16 Nov 2026 12:19:02 -0500 Subject: [PATCH 14/24] fix(javascript): a net covers all of a function or none; headers read as tokens; an async generator's return awaits (#1161) The fourth review, judging outcomes against V8 alone, found three ways the provable rule's implementation still landed a rescue in the wrong call or iteration. The rule held; the code did not. A net covered at most 24 break positions, taken from the call on and wrapping to the function's start. In a bigger function the position control comes back to could be outside it: a loop's top (the next iteration was where it stopped), the code after a long else (the next call was). A net now covers every break position of the function it guards, or the function is not netted: above 100 positions the step is V8's own. The first hit is then the first position the activation reaches. The header read kept only the text after the last delimiter, so a method whose name is a string or computed key holding `:` or `,` (`async 'GET /users/:id'(req)`) read as plain, and a step that suspended in it was netted below. functionKind (js-statement-scan.ts) now reads the header as tokens, backward from the parameter list: the name as one token, whatever it is (identifier, private name, string, computed key), then `*` and the modifiers, across a few lines and through comments. A header it cannot read with confidence (a template expression in a computed key) is unknown, and unknown means "can suspend". An async generator's `return x` awaits x, with no keyword in the statement, so its caller could leave the stack before any net position. statementCanSuspend now counts a `return` in an async generator. It also masks templates that span lines, reads an object literal after a spread, keeps an argument list going past a brace that ends its line, and treats a `//` after a lone slash on the line as unreadable (a regular expression may hold it). Measured on the reviewer's scenarios, with the value of a per-call variable after each landing: the string-key, computed-key and async-generator rows now behave as V8 alone; the loop rescue lands at the loop's top in the same iteration (i=0), the if/else rescue after the else in the same call (x=1), the async worker's in worker a, iteration 0. Unit: header forms (the measured ones, the keys the old read lost, headers split across lines) and the new scan shapes in tests/proxy/js-statement-scan.test.ts; all-or-none and the unpinned mutants of the fourth review in tests/proxy/js-stepper.test.ts. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015BDrn69pXrYMWc1JUwv5v8 --- changelog.d/1161.fixed.md | 2 +- docs/javascript/README.md | 27 ++- docs/tool-reference.md | 11 +- .../src/interfaces/adapter-policy-js.ts | 5 +- src/proxy/js-statement-scan.ts | 199 ++++++++++++++++-- src/proxy/js-stepper.ts | 107 +++++----- tests/proxy/js-statement-scan.test.ts | 102 ++++++++- tests/proxy/js-stepper.test.ts | 105 +++++---- 8 files changed, 412 insertions(+), 146 deletions(-) diff --git a/changelog.d/1161.fixed.md b/changelog.d/1161.fixed.md index 03ec96b7a..8f44e82e3 100644 --- a/changelog.d/1161.fixed.md +++ b/changelog.d/1161.fixed.md @@ -1 +1 @@ -**A JavaScript step out of a function that returns inside `try … finally` lands in the caller.** V8 loses such a step (measured on V8 12.4, 13.6 and 14.6 with a bare CDP client; also a `return` out of a `for … of` loop and out of a function with a `using` declaration): a `step_out` of the function and a `step_over` off its `finally` block answered `Step completed as session exited.` while the program ran on. Node's own module loader returns that way too, which is how a `step_into` on a `require` line was lost. The server now sets temporary breakpoints on the frame such a step returns to, and whichever pauses first is the landing. That is something the server does in your process: at most 24 temporary breakpoints per guarded frame, for the length of one step, removed when the step ends however it ends. They are set only where a hit proves the step came back: the function being left is a plain one (not `async`, not a generator), and the frame it returns to stays on the stack until it reaches one. A step V8 loses in an `async` function or a generator is not rescued: a breakpoint below a function that can suspend cannot tell it returning from it pausing at an `await`, so that step stays lost as before and its pending answer says so (#1174). Not covered either: a `step_over` across the first load of a module that has a breakpoint in it (#1162). (#1161) +**A JavaScript step out of a function that returns inside `try … finally` lands in the caller.** V8 loses such a step (measured on V8 12.4, 13.6 and 14.6 with a bare CDP client; also a `return` out of a `for … of` loop and out of a function with a `using` declaration): a `step_out` of the function and a `step_over` off its `finally` block answered `Step completed as session exited.` while the program ran on. Node's own module loader returns that way too, which is how a `step_into` on a `require` line was lost. The server now sets temporary breakpoints on the frame such a step returns to, and whichever pauses first is the landing. That is something the server does in your process: a temporary breakpoint on every break location of the frame the step returns to (a function with more than 100 is not guarded), for the length of one step, removed when the step ends however it ends. The step then lands at the caller's next break location after the call. The breakpoints are set only where a hit proves the step came back: the function being left is a plain one (not `async`, not a generator), and the frame it returns to stays on the stack until it reaches one (a caller that awaits the call does not). A step V8 loses in an `async` function or a generator is not rescued: a breakpoint below a function that can suspend cannot tell it returning from it pausing at an `await`, so that step stays lost as before (#1174): it answers `pending: true` with a sentence naming the case while the program keeps running, and `Step completed as session exited.` when it ends first. Not covered either: a `step_over` across the first load of a module that has a breakpoint in it (#1162). (#1161) diff --git a/docs/javascript/README.md b/docs/javascript/README.md index 3306a5dbb..fbdda9409 100644 --- a/docs/javascript/README.md +++ b/docs/javascript/README.md @@ -151,10 +151,13 @@ ES2017 costs four unmapped `__awaiter` stops before its first line (issue #687). that shape, which is how a `step_into` on a `require` line was lost too. (The cause is in V8: the return replayed after the `finally` block carries no source position, so it is not a place a step can stop; issue #1173.) -So where a step can be lost that way, the server sets temporary breakpoints on the frame the step returns to, and -whichever pauses first is the landing. That is something the server does in your process: up to 24 temporary -breakpoints per guarded frame, for the length of one step, removed when the step ends, however it ends. Where they -cannot be set the step goes on with V8 alone. +So where a step can be lost that way, the server sets temporary breakpoints on every break location of the frame +the step returns to, and whichever pauses first is the landing: the caller's next break location after the call +(the next statement, or the next call in the same statement; V8's own step-out, where it does not lose the step, +can stop once more on the call's own line first). That is something the server does in your process: a breakpoint +on each break location of one function, for the length of one step, removed when the step ends, however it ends. +A function with more than 100 break locations is not guarded, and where the breakpoints cannot be set the step +goes on with V8 alone. They are set only where a hit there proves the step came back: @@ -164,14 +167,20 @@ They are set only where a hit there proves the step came back: suspending at an `await` or `yield`, and a breakpoint below would then stop the step in the caller while it is still on its way to the next line, or in another call of the same function. So those steps are V8's own. - **The frame it returns to stays on the stack** until it reaches one of them: a plain function does; an `async` - one does unless the statement making the call awaits (`const got = await inner(id)` suspends the caller as soon - as the call returns, and another call of the same function can take its place). + one does unless the statement making the call awaits or yields (`const got = await inner(id)` suspends the + caller as soon as the call returns, and another call of the same function can take its place), or the function + suspends with no keyword there (`for await`, `await using`, a `return` in an async generator). +- **Every break location of that frame, or none**: a breakpoint on part of a function can miss the place control + comes back to (a loop's top, the code after a long `else`) and stop later, in another iteration or another + call. - **Never on the frame being stepped in**: a function that returns to itself (recursion) gets none for `step_over` and `step_into`. -What that leaves lost, as in 0.26.0: a step V8 loses in an `async` function or a generator, and a step out of a -plain function whose caller awaits the call. Such a step answers `pending: true`, and its sentence names the case. -A breakpoint on the line you expected the step to reach stops there. +What that leaves lost, as in 0.26.0: a step V8 loses in an `async` function or a generator, a step out of a +plain function whose caller awaits the call, and one out of a plain function whose caller has more than 100 break +locations. Such a step runs on: while the program keeps running it answers `pending: true`, with a sentence that +names these cases; when the program ends first it answers `Step completed as session exited.` A breakpoint on the +line you expected the step to reach stops there (issue #1174). Not covered: a `step_over` across the first load of a module that has a breakpoint in it still runs on (issue #1162; js-debug pauses at the module's entry to bind the breakpoint, and V8 drops the step at any pause). A diff --git a/docs/tool-reference.md b/docs/tool-reference.md index 2ba66724c..db9dc658d 100644 --- a/docs/tool-reference.md +++ b/docs/tool-reference.md @@ -708,8 +708,9 @@ does so for a launch that steps through skipped code (issues #678, #1130): a ste the frame and says a step does not stop there, and any other pending step says it left the frame it started in and has not stopped in your program since (a function Node called returned to the event loop, the line is waiting on work in flight, or the engine lost the step: V8 loses one that leaves an `async` function or a -generator through `try … finally`, a `for … of` loop or a `using` declaration, and the server rescues only -plain functions). An attach that steps through skipped code (`smartStep: true`) gets no such sentence. +generator through `try … finally`, a `for … of` loop or a `using` declaration, or one out of a plain function +whose caller awaits the call; the server rescues only steps out of a plain function into a caller that stays on +the stack). An attach that steps through skipped code (`smartStep: true`) gets no such sentence. So match a pending step by its `pending: true` flag, not by the message text. Once a stop has been observed, the stop path owns the answer — a step that demonstrably landed is never reported as pending afterwards, at the cost of the response then being bounded by the stack-trace round trip rather than by the ~5s window. If the debuggee ends while the step is in flight the result is still a success, with a terminal `state` and a message such as `"Step completed as session terminated."`. @@ -782,8 +783,10 @@ Same ~5s wait and `pending: true` contract as step_over — see [Pending steps]( - Out of an `async` function the event loop resumed, the step lands in the function that awaits it, in the call that awaited: that is the engine's own step. - The engine loses a step that leaves a function through `try … finally` (also a `return` out of `for … of`, - and a function with a `using` declaration). Out of a plain function the server catches it with temporary - breakpoints on the caller, so the step lands there. Out of an `async` function or a generator it does not: a + and a function with a `using` declaration). Out of a plain function the server catches it with a temporary + breakpoint on every break location of the caller, so the step lands at the caller's next one: the next + statement, or the next call in the same statement. Not when the caller awaits the call, or has more than 100 + break locations: then the step is lost, as below. Out of an `async` function or a generator it does not: a breakpoint below a function that can suspend cannot tell the function returning from it pausing at an `await`. Such a step stays lost, as in 0.26.0, and answers `pending: true`; a breakpoint on the caller's next line stops there. diff --git a/packages/shared/src/interfaces/adapter-policy-js.ts b/packages/shared/src/interfaces/adapter-policy-js.ts index 66644b202..b46db4e48 100644 --- a/packages/shared/src/interfaces/adapter-policy-js.ts +++ b/packages/shared/src/interfaces/adapter-policy-js.ts @@ -451,8 +451,9 @@ export const JsDebugAdapterPolicy = { } return 'The step left the frame it started in and has not stopped in your program since: a function that Node ' + 'called returned to the event loop, the line is waiting on work still in flight, or the engine lost the step ' + - '(V8 loses one that leaves an async function or a generator through try...finally, a for...of loop or a ' + - 'using declaration; a breakpoint on the line you expected it to reach stops there). The program is running; ' + + '(V8 loses one that leaves a function through try...finally, a for...of loop or a using declaration, and the ' + + 'server rescues it only out of a plain function into a caller that does not await the call; a breakpoint on ' + + 'the line you expected it to reach stops there). The program is running; ' + 'wait_for_stop answers when the step lands, a breakpoint is hit, or the program ends.'; }, diff --git a/src/proxy/js-statement-scan.ts b/src/proxy/js-statement-scan.ts index 6c5b63a85..844e157cf 100644 --- a/src/proxy/js-statement-scan.ts +++ b/src/proxy/js-statement-scan.ts @@ -1,14 +1,15 @@ /** - * Reading JavaScript source just far enough to answer one question for the - * proxy's stepper (issues #1130, #1161): can a frame of an async function or - * a generator suspend between a call returning and the next break location? + * Reading JavaScript source just far enough to answer two questions for the + * proxy's stepper (issues #1130, #1161): is a function async or a generator + * (`functionKind`, from its header), and can a frame of one suspend between a + * call returning and its next break location (`statementCanSuspend`)? * * Measured on V8 13.6: every statement has a break location at its start (a * statement that begins with a call has it at that call), and every call is * one. So a frame that returns from a call reaches a break location before it * can suspend unless the statement making the call awaits or yields, or the * function suspends without a keyword in that statement (`for await`, - * `await using`). + * `await using`, a `return` in an async generator, which awaits its value). * * This is not a parser. It masks out strings and comments, finds the * statement around a position by brackets, semicolons and line breaks, and @@ -30,19 +31,50 @@ interface MaskedLine { unsafe: boolean; } +/** What a line starts inside of, carried from the line before. */ +interface MaskState { + /** A `/* ... *\/` comment. */ + comment: boolean; + /** A template literal that did not end on its line. */ + template: boolean; +} + +function maskLines(lines: readonly string[], from: number, to: number): MaskedLine[] { + const state: MaskState = { comment: false, template: false }; + const masked: MaskedLine[] = []; + for (let i = from; i <= to; i++) { + masked.push(maskLine(lines[i] ?? '', state)); + } + return masked; +} + /** * Blank string, template and comment contents on one line, keeping columns. - * `inBlockComment` carries a `/* ... *\/` comment across lines. A string or - * template that does not end on the line, and anything that looks like a - * regular expression literal, makes the line unsafe. + * `state` carries a block comment and a template literal across lines. A + * line inside a template that spans lines, a string that does not end on its + * line, a template expression, and anything that looks like a regular + * expression literal make the line unsafe. */ -function maskLine(line: string, inBlockComment: { open: boolean }): MaskedLine { +function maskLine(line: string, state: MaskState): MaskedLine { let code = ''; let unsafe = false; let i = 0; + if (state.template) { + unsafe = true; + let j = 0; + while (j < line.length && line[j] !== '`') { + j += line[j] === '\\' ? 2 : 1; + } + if (j >= line.length) { + return { code: ' '.repeat(line.length), unsafe }; + } + code = ' '.repeat(j) + '`'; + i = j + 1; + state.template = false; + } while (i < line.length) { const ch = line[i]; - if (inBlockComment.open) { + if (state.comment) { const end = line.indexOf('*/', i); if (end === -1) { code += ' '.repeat(line.length - i); @@ -50,15 +82,20 @@ function maskLine(line: string, inBlockComment: { open: boolean }): MaskedLine { } code += ' '.repeat(end + 2 - i); i = end + 2; - inBlockComment.open = false; + state.comment = false; continue; } if (ch === '/' && line[i + 1] === '/') { + // After a lone slash on the line (a division, or a regular expression + // whose own slashes these may be) this is not surely a comment. + if (code.includes('/')) { + unsafe = true; + } code += ' '.repeat(line.length - i); return { code, unsafe }; } if (ch === '/' && line[i + 1] === '*') { - inBlockComment.open = true; + state.comment = true; code += ' '; i += 2; continue; @@ -77,6 +114,9 @@ function maskLine(line: string, inBlockComment: { open: boolean }): MaskedLine { if (j >= line.length) { // Not closed on this line (or a line continuation): not read with confidence. unsafe = true; + if (ch === '`') { + state.template = true; + } code += ' '.repeat(line.length - i); return { code, unsafe }; } @@ -124,17 +164,20 @@ function lineBreakEndsStatement(previous: string, next: string): boolean { * that statement. `from` and `to` bound the function's own lines. Errs toward * true. */ -export function statementCanSuspend(lines: readonly string[], line: number, column: number, from: number, to: number): boolean { +export function statementCanSuspend( + lines: readonly string[], + line: number, + column: number, + from: number, + to: number, + options: { asyncGenerator?: boolean } = {} +): boolean { const first = Math.max(0, from); const last = Math.min(lines.length - 1, to); if (line < first || line > last) { return true; } - const comment = { open: false }; - const masked: MaskedLine[] = []; - for (let i = first; i <= last; i++) { - masked.push(maskLine(lines[i] ?? '', comment)); - } + const masked = maskLines(lines, first, last); const at = (n: number): MaskedLine => masked[n - first]; if (masked.some((entry) => IMPLICIT_SUSPENSION.test(entry.code))) { return true; @@ -157,8 +200,9 @@ export function statementCanSuspend(lines: readonly string[], line: number, colu } else if (ch === '(' || ch === '[') { depth = Math.max(0, depth - 1); } else if (ch === '}') { - if (depth === 0 && code.slice(c + 1).trim() === '' && n < line) { - // A brace that ends its line, before the statement's line: the end of an earlier block. + if (depth === 0 && code.slice(c + 1).trim() === '' && n < line && lineBreakEndsStatement(code, at(n + 1).code)) { + // A brace that ends its line, before the statement's line, and + // the next line starts a statement: the end of an earlier block. startLine = n + 1; startCol = 0; found = true; @@ -171,7 +215,7 @@ export function statementCanSuspend(lines: readonly string[], line: number, colu } else { const before = code.slice(0, c).trimEnd(); const prev = before[before.length - 1] ?? ''; - const objectLiteral = /[(,=:[?!&|]/.test(prev) || /\b(return|await|yield)$/.test(before); + const objectLiteral = /[(,=:[?!&|.]/.test(prev) || /\b(return|await|yield)$/.test(before); if (!objectLiteral) { startLine = n; startCol = c + 1; @@ -262,5 +306,120 @@ export function statementCanSuspend(lines: readonly string[], line: number, colu const to = n === endLine ? endCol : entry.code.length; text += entry.code.slice(from, to) + '\n'; } + if (options.asyncGenerator && /\breturn\b/.test(text)) { + // An async generator's return awaits its value. + return true; + } return SUSPENDS.test(text); } + +/** What a function's header says it is. */ +export interface FunctionKind { + async: boolean; + generator: boolean; +} + +/** Header words that can stand before a method's or function's name. */ +const MODIFIERS = new Set(['async', 'function', 'static', 'get', 'set', 'accessor']); + +/** + * Whether the function whose header V8's functionLocation points at is async + * or a generator; null when the header cannot be read with confidence. V8 + * points at the parameter list of a function or a method, with + * `[static] [async] [function] [*] [get|set] name` before it, and at the + * first token of an arrow (`async` itself for an async one). The name may be + * an identifier, a private name, a string or a computed key: it is skipped as + * a token, so what it contains does not matter. Reads at most a few lines + * back. + */ +export function functionKind(lines: readonly string[], line: number, column: number): FunctionKind | null { + const first = Math.max(0, line - 4); + const masked = maskLines(lines, first, line); + if (masked.some((entry) => entry.unsafe)) { + return null; + } + const text = masked.map((entry) => entry.code).join('\n'); + let p = masked.slice(0, line - first).reduce((sum, entry) => sum + entry.code.length + 1, 0) + column; + const original = lines[line] ?? ''; + if (/^async\b/.test(original.slice(column))) { + return { async: true, generator: false }; + } + if (text[p] !== '(') { + // An arrow with one bare parameter, or a script's own code: plain. + return { async: false, generator: false }; + } + const isWord = (ch: string | undefined): boolean => ch !== undefined && /[\w$#]/.test(ch); + const skipSpace = (): void => { + while (p > 0 && /\s/.test(text[p - 1])) { + p--; + } + }; + const word = (): string => { + const end = p; + while (p > 0 && isWord(text[p - 1])) { + p--; + } + return text.slice(p, end); + }; + const kind: FunctionKind = { async: false, generator: false }; + + // The name: an identifier, a string, or a computed key; or none (an arrow, an anonymous function). + skipSpace(); + const last = text[p - 1]; + if (last === undefined) { + return null; + } + if (last === ']') { + let depth = 0; + do { + p--; + if (text[p] === ']') { + depth++; + } else if (text[p] === '[') { + depth--; + } + } while (p > 0 && depth > 0); + if (depth !== 0) { + return null; + } + } else if (last === '"' || last === "'") { + p--; + while (p > 0 && text[p - 1] !== last) { + p--; + } + if (p === 0) { + return null; + } + p--; + } else if (isWord(last)) { + const name = word(); + if (name === 'function') { + p += name.length; + } + } else if (last !== '*') { + // `= (`, `, (`, `((`: the parameter list of an arrow. + return kind; + } + + // Then `*`, and the modifiers. + for (;;) { + skipSpace(); + if (text[p - 1] === '*') { + kind.generator = true; + p--; + continue; + } + if (!isWord(text[p - 1])) { + return kind; + } + const before = p; + const modifier = word(); + if (!MODIFIERS.has(modifier)) { + p = before; + return kind; + } + if (modifier === 'async') { + kind.async = true; + } + } +} diff --git a/src/proxy/js-stepper.ts b/src/proxy/js-stepper.ts index 37d953354..591dc4498 100644 --- a/src/proxy/js-stepper.ts +++ b/src/proxy/js-stepper.ts @@ -58,9 +58,20 @@ * * (b) The frame guarded is on the stack and stays there until it * reaches a net position. A plain function does. One that can - * suspend does unless the statement making the call awaits or - * yields: then it can leave the stack before any position, another - * call of the same function can take its depth, and no net is set. + * suspend does unless it can suspend between the call returning + * and its next break location: V8 puts one at every statement's + * start and every call, so only when the calling statement awaits + * or yields, or the function suspends with no keyword there (`for + * await`, `await using`, an async generator's `return`). Then it can + * leave the stack before any position, another call of the same + * function can take its depth, and no net is set. + * + * (c) The net covers every break position of the frame it guards, or + * there is none: a hit is then the first position control reaches + * in that activation. A function with more than `netSize` + * positions is not netted. A rescue lands at the caller's next + * break location after the call; V8's own step-out, when it does + * not lose the step, can stop once more on the call's own line. * * Nothing is ever guarded that is not on the stack (no net on an awaiting * function), and nothing is decided on a pause's reason, which does not @@ -102,7 +113,7 @@ import type { DebugProtocol } from '@vscode/debugprotocol'; import { createLogger } from '../utils/logger.js'; import { ErrorMessages } from '../utils/error-messages.js'; -import { statementCanSuspend } from './js-statement-scan.js'; +import { functionKind, statementCanSuspend, type FunctionKind } from './js-statement-scan.js'; // redirectable: re-pointed into the per-session proxy log at worker init (#519) const logger = createLogger('js-stepper', { redirectable: true }); @@ -125,7 +136,13 @@ export interface JsStepperTunables { budget: number; /** CDP step commands in one chain, all told. */ commandCap: number; - /** Break positions in one net. A breakpoint in a big function is slow to set (1000 took 2.4 s). */ + /** + * The most break positions a net may have. A net covers every position of + * the function it guards, or the function is not netted: a net on part of + * it can miss the position control comes back to (a loop's back edge, the + * code after a long else) and fire later, in another iteration or another + * call. A breakpoint is slow to set in a big function (1000 took 2.4 s). + */ netSize: number; /** Re-issued commands on a net position that is not a landing (recursion; the origin statement). */ reissueCap: number; @@ -138,7 +155,7 @@ export interface JsStepperTunables { export const DEFAULT_JS_STEPPER_TUNABLES: JsStepperTunables = { budget: 24, commandCap: 128, - netSize: 24, + netSize: 100, reissueCap: 24, settleCeilingMs: 2000, verdictCeilingMs: 2000 @@ -324,7 +341,7 @@ export class JsStepper { /** Scripts js-debug marked "Skipped by skipFiles": a script-level verdict, not asked again. */ private readonly skippedScripts = new Set(); /** Whether a function can suspend, by its header: read once per function. */ - private readonly suspending = new Map(); + private readonly kinds = new Map(); /** Whether a function's text names a construct that closes through a finally. */ private readonly closing = new Map(); /** What each pause's top frame returns to: asked of js-debug once per pause. */ @@ -936,19 +953,8 @@ export class JsStepper { return all; } - /** At most `netSize` positions, from the frame's own position on. */ - private window(all: CdpBreakLocation[], here: CdpLocation): CdpBreakLocation[] { - const size = this.tunables.netSize; - if (all.length <= size) { - return all; - } - const at = all.findIndex((location) => sameOrAfter(location, here)); - const from = at === -1 ? 0 : at; - const part = all.slice(from, from + size); - return part.length === size ? part : [...part, ...all.slice(0, size - part.length)]; - } - - private async arm(all: CdpBreakLocation[], here: CdpLocation, net: Omit): Promise { + /** A net on every one of `all`, the break positions of the function it guards. */ + private async arm(all: CdpBreakLocation[], net: Omit): Promise { if (this.nets.some((existing) => existing.fn === net.fn && existing.depth === net.depth)) { return true; } @@ -957,7 +963,7 @@ export class JsStepper { return false; } const answers = await Promise.all( - this.window(all, here).map((location) => + all.map((location) => cdp .send<{ breakpointId?: string }>('Debugger.setBreakpoint', { location: { scriptId: location.scriptId, lineNumber: location.lineNumber, columnNumber: location.columnNumber ?? 0 } @@ -1008,29 +1014,33 @@ export class JsStepper { * scripts too. Doubt reads as "can suspend": no net. Never throws. */ private async canSuspend(frame: CdpCallFrame): Promise { + const kind = await this.kindOf(frame); + return kind === null || kind.async || kind.generator; + } + + /** + * What the frame's function is, by `functionKind`; null when that is not + * known with confidence, and for a module's own code (which may await at + * its top level). Read once per function. Never throws. + */ + private async kindOf(frame: CdpCallFrame): Promise { const key = fnKey(frame); - const known = this.suspending.get(key); - if (known !== undefined) { - return known; + if (this.kinds.has(key)) { + return this.kinds.get(key) ?? null; } - let suspends = true; + let kind: FunctionKind | null = null; try { const scopes = frame.scopeChain ?? []; const firstFunctionScope = scopes.find((scope) => scope.type === 'local' || scope.type === 'module'); const at = frame.functionLocation; - if (firstFunctionScope?.type === 'module') { - suspends = true; - } else if (at) { - const line = (await this.linesOf(at.scriptId))[at.lineNumber]; - if (line !== undefined) { - suspends = suspendsByHeader(line, at.columnNumber ?? 0); - } + if (firstFunctionScope?.type !== 'module' && at) { + kind = functionKind(await this.linesOf(at.scriptId), at.lineNumber, at.columnNumber ?? 0); } } catch (err) { logger.debug(`[JsStepper] could not read a function's header: ${errorText(err)}`); } - this.suspending.set(key, suspends); - return suspends; + this.kinds.set(key, kind); + return kind; } /** @@ -1051,7 +1061,10 @@ export class JsStepper { const lines = await this.linesOf(here.scriptId); const from = Math.min(frame.functionLocation?.lineNumber ?? all[0].lineNumber, all[0].lineNumber); const to = all[all.length - 1].lineNumber; - return statementCanSuspend(lines, here.lineNumber, here.columnNumber ?? 0, from, to); + const kind = await this.kindOf(frame); + return statementCanSuspend(lines, here.lineNumber, here.columnNumber ?? 0, from, to, { + asyncGenerator: kind === null || (kind.async && kind.generator) + }); } catch (err) { logger.debug(`[JsStepper] could not read the calling statement: ${errorText(err)}`); return true; @@ -1126,7 +1139,12 @@ export class JsStepper { if ((await this.canSuspend(frame)) && (await this.callStatementSuspends(frame))) { return; } - await this.arm(await this.locationsOf(frame), frame.location, { + // (c) Every position of it, or none. + const all = await this.locationsOf(frame); + if (all.length === 0 || all.length > this.tunables.netSize) { + return; + } + await this.arm(all, { name: frame.functionName || '(anonymous)', fn: fnKey(frame), depth: frames.length - target.index @@ -1195,20 +1213,3 @@ export class JsStepper { return markOf(awaiter) === 'deemphasize' ? { kind: 'nothing' } : { kind: 'awaiter', parent }; } } - -/** - * Whether the function whose header is at `column` of `line` is async or a - * generator. V8's functionLocation points at the parameter list of a function - * or a method, with `[static] [async] [function] [*] [get|set] name` right - * before it, and at the first token of an arrow, which is `async` itself for - * an async one. Erring toward "it can suspend" is the safe side: a plain - * method named `async`, or a comment before the header, reads as one that can. - */ -export function suspendsByHeader(line: string, column: number): boolean { - if (/^async\b/.test(line.slice(column))) { - return true; - } - // The header's own tokens: what stands between the last delimiter and the parameter list. - const header = line.slice(0, column).split(/[=,:(;{}?!&|]/).pop() ?? ''; - return /\basync\b/.test(header) || header.includes('*'); -} diff --git a/tests/proxy/js-statement-scan.test.ts b/tests/proxy/js-statement-scan.test.ts index b17b88f8d..6cf6f5d24 100644 --- a/tests/proxy/js-statement-scan.test.ts +++ b/tests/proxy/js-statement-scan.test.ts @@ -6,7 +6,7 @@ * scan must err toward "it can": that costs a rescue, never a wrong landing. */ import { describe, it, expect } from 'vitest'; -import { statementCanSuspend } from '../../src/proxy/js-statement-scan.js'; +import { functionKind, statementCanSuspend } from '../../src/proxy/js-statement-scan.js'; /** The source, and the 0-based line and column of the call marked `@` (the marker is removed). */ function at(source: string): { lines: string[]; line: number; column: number } { @@ -53,17 +53,43 @@ describe('statementCanSuspend', () => { ['a yield', 'function* g() {\n const got = yield @inner(id);\n}'], ['a for await loop anywhere in the function', 'async function f() {\n for await (const x of xs) {\n @inner(x);\n }\n}'], ['an await using anywhere in the function', 'async function f() {\n await using h = open();\n @inner(1);\n}'], - ['a nested async callback that awaits', 'async function f() {\n @inner(items.map(async (i) => { await send(i); }));\n}'] + ['a nested async callback that awaits', 'async function f() {\n @inner(items.map(async (i) => { await send(i); }));\n}'], + ['an await around a spread object', 'async function f(id) {\n const v = await {\n ...{ a: @work(id) }\n };\n}'], + ['an await before an object argument that closes on its own line', 'async function f(id) {\n const v = await wrap(function () {\n return 1;\n }\n , @work(id));\n}'], + ['an await before an arrow argument', 'async function f(id) {\n const v = await both(() => {\n return 1;\n }, @work(id));\n}'], + ['a line that ends in await', 'async function f(id) {\n const v = await\n @work(id);\n}'] ])('%s', (_what, source) => { expect(suspends(source)).toBe(true); }); }); + describe('an async generator', () => { + it('awaits the value it returns: a return of the call can suspend', () => { + const { lines, line, column } = at('async function* g(id) {\n noop();\n return @work(id);\n}'); + expect(statementCanSuspend(lines, line, column, 0, lines.length - 1, { asyncGenerator: true })).toBe(true); + expect(statementCanSuspend(lines, line, column, 0, lines.length - 1)).toBe(false); + }); + + it('reads a return that ends its line as part of the statement on the next', () => { + const { lines, line, column } = at('async function* g(id) {\n noop();\n return (\n @work(id));\n}'); + expect(statementCanSuspend(lines, line, column, 0, lines.length - 1, { asyncGenerator: true })).toBe(true); + }); + }); + + describe('a block comment', () => { + it('is not read as code', () => { + expect(suspends('async function f(id) {\n /* await later */ const v = @work(id);\n}')).toBe(false); + }); + }); + describe('errs toward "it can" where it cannot read with confidence', () => { it.each([ ['a template literal with an expression', 'async function f() {\n const got = @inner(`${id}`);\n}'], ['a string that does not end on its line', 'async function f() {\n const got = @inner("a\\\n b");\n}'], ['a regular expression literal', 'async function f() {\n const got = @inner(/;/.test(id));\n}'], + ['a regular expression with slashes after a paren', 'async function f(id, s) {\n if (s) /\\/\\//.test(s) && await use(@work(id));\n}'], + ['a template that spans lines', 'async function f(id) {\n const css = await `\n .a { color: ${@work(id)}; }\n`;\n}'], + ['a block comment that hides an await', 'async function f(id) {\n const v = /* x */ await /* y */ @work(id);\n}'], ['a call outside the function', 'const got = @inner(id);'] ])('%s', (_what, source) => { const { lines, line, column } = at(source); @@ -77,3 +103,75 @@ describe('statementCanSuspend', () => { }); }); }); + +/** + * What a function is, read from the header V8's functionLocation points at: + * the parameter list of a function or a method, the first token of an arrow. + * Columns below are where V8 points (measured on Node 24 for the first + * group; the rest follow the same rule). + */ +describe('functionKind', () => { + /** The header, with the position V8 points at marked `@` (the marker is removed). */ + function kindOf(source: string): { async: boolean; generator: boolean } | null { + const { lines, line, column } = at(source); + return functionKind(lines, line, column); + } + const plain = { async: false, generator: false }; + const isAsync = { async: true, generator: false }; + const generator = { async: false, generator: true }; + const asyncGenerator = { async: true, generator: true }; + + it.each([ + ['function plainDecl@() { }', plain], + ['const plainExpr = function @() { };', plain], + ['const plainArrow = @() => { };', plain], + ['async function asyncDecl@() { }', isAsync], + ['const asyncExpr = async function @() { };', isAsync], + ['const asyncArrow = @async () => { };', isAsync], + ['const asyncArrowBare = @async a => { };', isAsync], + ['function* genDecl@() { }', generator], + ['const genExpr = function* @() { };', generator], + ['async function* asyncGen@() { }', asyncGenerator], + [' method@() { }', plain], + [' async asyncMethod@() { }', isAsync], + [' *genMethod@() { }', generator], + [' async *asyncGenMethod@() { }', asyncGenerator], + [' static async staticAsync@() { }', isAsync], + [' get prop@() { return 1; }', plain], + [' objPlain@() { },', plain], + [' arrowProp: @async () => { }', isAsync], + ['Module.prototype.require = function@(id) {', plain], + ['run(function inner@() { }, async function next() { });', plain], + ['run(function inner() { }, async function next@() { });', isAsync], + [' constructor@(a) { }', plain], + [' #secret@() { }', plain], + [' async #secret@() { }', isAsync], + [' async() { }'.replace('()', '@()'), plain] + ])('%s', (source, expected) => { + expect(kindOf(source)).toEqual(expected); + }); + + it.each([ + ['a string key holding a colon', " async 'GET /users/:id'@(req) { }", isAsync], + ['a string key holding a comma', " async 'a,b'@(x) { }", isAsync], + ['a computed key holding a colon', " async [Symbol.for('a:b')]@(x) { }", isAsync], + ['a generator with a computed key holding a comma', " *[Symbol.for('g,h')]@() { }", generator], + ['a static async computed key', " static async ['s:A']@(x) { }", isAsync], + ['an async generator computed key', ' async *[Symbol.asyncIterator]@() { }', asyncGenerator], + ['a plain string key holding the word async', " 'async (x)'@(x) { }", plain] + ])('a key the old read lost: %s', (_what, source, expected) => { + expect(kindOf(source)).toEqual(expected); + }); + + it.each([ + ['a function header split across lines', 'async function\nname@(x) { }', isAsync], + ['a generator header split across lines', 'function*\nname@() { }', generator], + ['a comment inside the header', 'async /* the handler */ function handler@(req) { }', isAsync] + ])('reads %s', (_what, source, expected) => { + expect(kindOf(source)).toEqual(expected); + }); + + it('does not know a header it cannot read with confidence: a computed key with a template expression', () => { + expect(kindOf(' async [`k${1}`]@(x) { }')).toBeNull(); + }); +}); diff --git a/tests/proxy/js-stepper.test.ts b/tests/proxy/js-stepper.test.ts index 319923b1a..604043be4 100644 --- a/tests/proxy/js-stepper.test.ts +++ b/tests/proxy/js-stepper.test.ts @@ -13,7 +13,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; import { EventEmitter } from 'events'; import type { DebugProtocol } from '@vscode/debugprotocol'; -import { JsStepper, suspendsByHeader, type JsStepperTunables } from '../../src/proxy/js-stepper.js'; +import { JsStepper, type JsStepperTunables } from '../../src/proxy/js-stepper.js'; import { ErrorMessages } from '../../src/utils/error-messages.js'; interface Frame { @@ -654,35 +654,31 @@ describe('JsStepper (issue #1130)', () => { expect(engine.armed).toEqual([]); }); - it('caps a net, and wraps to the function\'s start when the frame is near its end', async () => { - const start = fnLineOf(app('wrap', 0)); - engine.positions.set(`app:${start}`, Array.from({ length: 300 }, (_, i) => ({ lineNumber: start + i }))); - engine.pauseAt({ frames: frames(lossy(app('leaf', 5)), app('wrap', start + 290)) }); - engine.script = [{ frames: frames(app('wrap', start + 291)) }]; + + it('nets every break position of the frame it guards, those before the call too: a loop comes back to its top', async () => { + const start = fnLineOf(app('looping', 0)); + engine.positions.set(`app:${start}`, Array.from({ length: 60 }, (_, i) => ({ lineNumber: start + i }))); + engine.pauseAt({ frames: frames(lossy(app('leaf', 5)), app('looping', start + 50)) }); + engine.script = [{ frames: frames(app('looping', start + 2)), reason: 'other', hits: (armed) => [armed.find((bp) => bp.lineNumber === start + 2)!.id] }]; await stepper.request('stepOut', { threadId: 1 }); await settled(); const lines = engine.calls .filter((c) => c.method === 'Debugger.setBreakpoint') .map((c) => (c.params.location as { lineNumber: number }).lineNumber); - expect(lines).toHaveLength(24); - // Ten to the end of the function (a loop comes back to its top), fourteen from its start. - expect(lines.filter((line) => line >= start + 290)).toHaveLength(10); - expect(lines.filter((line) => line < start + 14)).toHaveLength(14); + expect(lines).toHaveLength(60); + expect(Math.min(...lines)).toBe(start); + expect(stopped()).toMatchObject({ reason: 'step' }); }); - it('caps a net, and takes it from the frame\'s own position on', async () => { - const start = fnLineOf(app('big', 0)); - engine.positions.set(`app:${start}`, Array.from({ length: 300 }, (_, i) => ({ lineNumber: start + i }))); - engine.pauseAt({ frames: frames(lossy(app('leaf', 5)), app('big', start + 200)) }); - engine.script = [{ frames: frames(app('big', start + 201)) }]; + it('nets none in a function with more break positions than a net may have: a part of it could miss where control comes back', async () => { + const start = fnLineOf(app('huge', 0)); + engine.positions.set(`app:${start}`, Array.from({ length: 101 }, (_, i) => ({ lineNumber: start + i }))); + engine.pauseAt({ frames: frames(lossy(app('leaf', 5)), app('huge', start + 50)) }); + engine.script = [{ frames: frames(app('huge', start + 51)) }]; await stepper.request('stepOut', { threadId: 1 }); await settled(); - const lines = engine.calls - .filter((c) => c.method === 'Debugger.setBreakpoint') - .map((c) => (c.params.location as { lineNumber: number }).lineNumber); - expect(lines).toHaveLength(24); - expect(Math.min(...lines)).toBe(start + 200); - expect(Math.max(...lines)).toBe(start + 223); + expect(setBreakpoints()).toBe(0); + expect(stopped()).toMatchObject({ reason: 'step' }); }); it('asks from the frame\'s own line when the function position answers for a nested function', async () => { @@ -1532,39 +1528,6 @@ describe('JsStepper (issue #1130)', () => { // ----- the provable rule: rule (a), the frame being left; rule (b), the frame guarded ----- - describe('what can suspend, read from the function\'s header', () => { - // [the header's line, where V8's functionLocation points in it, whether it can suspend]: as measured. - it.each([ - ['function plainDecl() { }', 18, false], - ['const plainExpr = function () { };', 27, false], - ['const plainArrow = () => { };', 19, false], - ['async function asyncDecl() { }', 24, true], - ['const asyncExpr = async function () { };', 33, true], - ['const asyncArrow = async () => { };', 19, true], - ['const asyncArrowBare = async a => { };', 23, true], - ['function* genDecl() { }', 17, true], - ['const genExpr = function* () { };', 26, true], - ['async function* asyncGen() { }', 24, true], - [' method() { }', 8, false], - [' async asyncMethod() { }', 19, true], - [' *genMethod() { }', 12, true], - [' async *asyncGenMethod() { }', 23, true], - [' static async staticAsync() { }', 26, true], - [' get prop() { return 1; }', 10, false], - [' objPlain() { },', 10, false], - [' arrowProp: async () => { }', 13, true], - ['Module.prototype.require = function(id) {', 35, false], - ['run(function inner() { }, async function next() { });', 18, false], - ['run(function inner() { }, async function next() { });', 45, true] - ])('%s at column %i', (line, column, expected) => { - expect(suspendsByHeader(line, column)).toBe(expected); - }); - - it('errs toward "it can": a plain method named async, a comment before the header', () => { - expect(suspendsByHeader(' async() { }', 7)).toBe(true); - expect(suspendsByHeader('/* async */ function f() { }', 22)).toBe(true); - }); - }); describe('rule (a): only a plain function is netted', () => { /** The frame, with its function written as this header (V8 points at the parameter list). */ @@ -1662,7 +1625,8 @@ describe('JsStepper (issue #1130)', () => { describe('rule (b): the frame guarded must still be on the stack when it reaches a net position', () => { /** `handler` at line 14, written as an async function or a plain one, calling the function being left. */ async function stepOutInto(header: string, statement: string): Promise { - const handler = app('handler', 14, { fnCol: header.indexOf('(') }); + // The caller is paused at its call of `inner`, as V8 reports it. + const handler = app('handler', 14, { fnCol: header.indexOf('('), col: Math.max(0, statement.indexOf('inner(')) }); sourceWith({ [fnLineOf(handler)]: header, 14: statement }); engine.pauseAt({ frames: frames(lossy(app('innerSync', 30)), handler) }); engine.script = [{ frames: frames({ ...handler, line: 15 }) }]; @@ -1670,6 +1634,37 @@ describe('JsStepper (issue #1130)', () => { await settled(); } + it('reads the statement the call is in, not the one before it on the same line', async () => { + await stepOutInto('async function handler(id) {', 'await ready; const got = inner(id);'); + expect(setBreakpoints()).toBeGreaterThan(0); + }); + + it('nets a plain caller even where its statement cannot be read with confidence: a plain frame cannot suspend', async () => { + await stepOutInto('function handler(id) {', 'const got = log(`${inner(id)}`);'); + expect(setBreakpoints()).toBeGreaterThan(0); + }); + + it('nets a caller whose header cannot be read when its statement cannot suspend either way', async () => { + await stepOutInto('async [`k${1}`](id) {', 'const got = inner(id);'); + expect(setBreakpoints()).toBeGreaterThan(0); + }); + + it('sets none below a function being left whose header cannot be read: it might suspend', async () => { + const header = ' [`k${1}`](x) {'; + const top = app('unreadable', 30, { fnCol: header.indexOf('(') }); + sourceWith({ [fnLineOf(top)]: header, [fnLineOf(top) + 5]: '} finally { done(); }' }); + engine.pauseAt({ frames: frames(top, app('caller', 14)) }); + engine.script = [{ frames: frames(app('caller', 15)) }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBe(0); + }); + + it('sets none when the caller is an async generator returning the call: its return awaits', async () => { + await stepOutInto('async *handler(id) {', 'return inner(id);'); + expect(setBreakpoints()).toBe(0); + }); + it('sets none when an async caller awaits the call: it leaves the stack at once, and another call can take its depth', async () => { await stepOutInto('async function handler(id) {', 'const got = await inner(id);'); expect(setBreakpoints()).toBe(0); From 0f4112d1e74fff486d049340d06c95ecfd8f1342 Mon Sep 17 00:00:00 2001 From: JF Date: Mon, 16 Nov 2026 13:48:29 -0500 Subject: [PATCH 15/24] fix(javascript): V8 says which frames come down only by returning; the stepper stops reading source (#1161, #1174) Five versions of the rule for where to set a net read the program's source to tell a function that returns from one that suspends at an await or yield. Each review fooled the reading: names with non-ASCII letters, numeric keys, a string or computed key holding a delimiter, an object literal whose brace starts its line, a template that spans lines. V8 knows, and says so on every frame of a pause: `canBeRestarted` is false for an async function, a generator and module code that may await, and for every frame below one. Measured on Node 22, 24 and 26 over every function form (declarations, expressions, arrows, methods, getters, constructors, private and computed names, eval, new Function, ESM module code with and without top-level await, Node's own async code): no frame that can suspend reads as restartable. So the rule is one V8 fact on the frame a net would guard: it can be restarted. Then it and every frame above it, the one being left and any skipped code between, are plain functions that come down only by returning, and a hit in the guarded frame is the step coming back in the same call. The header tokenizer and the statement scan (src/proxy/js-statement-scan.ts) are deleted. What that costs: a plain function with a try...finally (or Node's loader behind a require) called from an async function is no longer rescued: the async caller can suspend before any net position, and nothing V8 exposes names one call of it. The step is V8's own there, and lost as in 0.26.0 (#1174). The first console.log of an async main still lands: V8 does not lose that step. Two holes in "all or none" are closed. Top-level code whose first token is a function declaration got the nested function's positions for its own, and a fallback that asked from the frame's line on, so a loop's top was not netted and a rescue landed an iteration late: the positions are now asked again from just past each nested function until they hold the frame's own, or there is no net. And a net with a breakpoint V8 refused is removed whole. Lines are split as V8 counts them (CR, LF, CRLF, U+2028, U+2029), and a net that fired too deep (recursion) is not followed by new ones while V8's own step-outs finish. Measured on the fourth and fifth reviewers' scenarios with a per-call variable: every rescue lands in the same call or iteration (constructor and getter callers, recursion, loops, if/else, the top-level loop at i=0, 100 positions rescued, 101 not); every row they found wrong now behaves as V8 alone. Unit: the rule's cases rewritten on a scripted V8 that reports canBeRestarted as measured, plus the top-level walk, a refused breakpoint and a V8 that does not report the field. Integration: the rescue rows step from a plain caller; a new case pins the async caller as lost. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015BDrn69pXrYMWc1JUwv5v8 --- changelog.d/1161.fixed.md | 2 +- docs/javascript/README.md | 34 +- docs/tool-reference.md | 21 +- .../src/interfaces/adapter-policy-js.ts | 4 +- src/proxy/js-statement-scan.ts | 425 ------------------ src/proxy/js-stepper.ts | 189 +++----- .../javascript-step-skipped-code.test.ts | 16 + .../javascript/step-skipped-code/steps.cjs | 20 +- tests/proxy/js-statement-scan.test.ts | 177 -------- tests/proxy/js-stepper.test.ts | 219 ++++----- 10 files changed, 226 insertions(+), 881 deletions(-) delete mode 100644 src/proxy/js-statement-scan.ts delete mode 100644 tests/proxy/js-statement-scan.test.ts diff --git a/changelog.d/1161.fixed.md b/changelog.d/1161.fixed.md index 8f44e82e3..ed599689e 100644 --- a/changelog.d/1161.fixed.md +++ b/changelog.d/1161.fixed.md @@ -1 +1 @@ -**A JavaScript step out of a function that returns inside `try … finally` lands in the caller.** V8 loses such a step (measured on V8 12.4, 13.6 and 14.6 with a bare CDP client; also a `return` out of a `for … of` loop and out of a function with a `using` declaration): a `step_out` of the function and a `step_over` off its `finally` block answered `Step completed as session exited.` while the program ran on. Node's own module loader returns that way too, which is how a `step_into` on a `require` line was lost. The server now sets temporary breakpoints on the frame such a step returns to, and whichever pauses first is the landing. That is something the server does in your process: a temporary breakpoint on every break location of the frame the step returns to (a function with more than 100 is not guarded), for the length of one step, removed when the step ends however it ends. The step then lands at the caller's next break location after the call. The breakpoints are set only where a hit proves the step came back: the function being left is a plain one (not `async`, not a generator), and the frame it returns to stays on the stack until it reaches one (a caller that awaits the call does not). A step V8 loses in an `async` function or a generator is not rescued: a breakpoint below a function that can suspend cannot tell it returning from it pausing at an `await`, so that step stays lost as before (#1174): it answers `pending: true` with a sentence naming the case while the program keeps running, and `Step completed as session exited.` when it ends first. Not covered either: a `step_over` across the first load of a module that has a breakpoint in it (#1162). (#1161) +**A JavaScript step out of a function that returns inside `try … finally` lands in the caller.** V8 loses such a step (measured on V8 12.4, 13.6 and 14.6 with a bare CDP client; also a `return` out of a `for … of` loop and out of a function with a `using` declaration): a `step_out` of the function and a `step_over` off its `finally` block answered `Step completed as session exited.` while the program ran on. Node's own module loader returns that way too, which is how a `step_into` on a `require` line was lost. The server now sets temporary breakpoints on the frame such a step returns to, and whichever pauses first is the landing. That is something the server does in your process: a temporary breakpoint on every break location of the frame the step returns to (a function with more than 100 is not guarded), for the length of one step, removed when the step ends however it ends. The step then lands at the caller's next break location after the call. The breakpoints are set only where a hit proves the step came back, and V8 decides that rather than the server reading your code: V8 says the frame the step returns to could be restarted, which it says of no `async` function, generator or module code that may await, nor of any frame below one, so that frame and every frame above it come down only by returning. A step that leaves or returns into an `async` function or a generator is not rescued: a breakpoint there cannot tell a function returning from one pausing at an `await`, so that step stays lost as before (#1174): it answers `pending: true` with a sentence naming the case while the program keeps running, and `Step completed as session exited.` when it ends first. Not covered either: a `step_over` across the first load of a module that has a breakpoint in it (#1162). (#1161) diff --git a/docs/javascript/README.md b/docs/javascript/README.md index fbdda9409..e714b0f53 100644 --- a/docs/javascript/README.md +++ b/docs/javascript/README.md @@ -159,28 +159,26 @@ on each break location of one function, for the length of one step, removed when A function with more than 100 break locations is not guarded, and where the breakpoints cannot be set the step goes on with V8 alone. -They are set only where a hit there proves the step came back: - -- **The function being left is a plain one**: not `async`, not a generator, not a module's own code (read from the - function's header, for Node's own code as for yours). A plain function comes down only by returning, so control - back in the frame below means it returned. An `async` function or a generator can also hand control down by - suspending at an `await` or `yield`, and a breakpoint below would then stop the step in the caller while it is - still on its way to the next line, or in another call of the same function. So those steps are V8's own. -- **The frame it returns to stays on the stack** until it reaches one of them: a plain function does; an `async` - one does unless the statement making the call awaits or yields (`const got = await inner(id)` suspends the - caller as soon as the call returns, and another call of the same function can take its place), or the function - suspends with no keyword there (`for await`, `await using`, a `return` in an async generator). +They are set only where a hit there proves the step came back, and V8 decides that, not the server reading +your code: + +- **The frame the step returns to, and every frame above it, are plain functions**: V8 says it could restart that + frame, which it says of no `async` function, generator or module code that may await, nor of any frame below one + (checked on Node 22, 24 and 26 over every way of writing a function). A plain function comes down only by + returning, so control back in that frame means the step came back, in the same call. A function that can suspend + at an `await` or `yield` hands control down without returning, and a breakpoint below it would stop the step in + the caller while it is still on its way, or in another call of the same function. - **Every break location of that frame, or none**: a breakpoint on part of a function can miss the place control - comes back to (a loop's top, the code after a long `else`) and stop later, in another iteration or another - call. + comes back to (a loop's top, the code after a long `else`) and stop later, in another iteration or another call. + A function with more than 100 break locations, or whose locations cannot all be found, is not guarded. - **Never on the frame being stepped in**: a function that returns to itself (recursion) gets none for `step_over` and `step_into`. -What that leaves lost, as in 0.26.0: a step V8 loses in an `async` function or a generator, a step out of a -plain function whose caller awaits the call, and one out of a plain function whose caller has more than 100 break -locations. Such a step runs on: while the program keeps running it answers `pending: true`, with a sentence that -names these cases; when the program ends first it answers `Step completed as session exited.` A breakpoint on the -line you expected the step to reach stops there (issue #1174). +What that leaves lost, as in 0.26.0: a step V8 loses while leaving an `async` function or a generator, and one that +leaves a plain function back into an `async` function or a generator (a helper with a `try … finally`, or a +`require`, called from an `async` function). Such a step runs on: while the program keeps running it answers +`pending: true`, with a sentence that names these cases; when the program ends first it answers `Step completed as +session exited.` A breakpoint on the line you expected the step to reach stops there (issue #1174). Not covered: a `step_over` across the first load of a module that has a breakpoint in it still runs on (issue #1162; js-debug pauses at the module's entry to bind the breakpoint, and V8 drops the step at any pause). A diff --git a/docs/tool-reference.md b/docs/tool-reference.md index db9dc658d..a7beaaaf7 100644 --- a/docs/tool-reference.md +++ b/docs/tool-reference.md @@ -707,10 +707,9 @@ The adapter may append one sentence to that message saying what the step is wait does so for a launch that steps through skipped code (issues #678, #1130): a step issued from skipped code names the frame and says a step does not stop there, and any other pending step says it left the frame it started in and has not stopped in your program since (a function Node called returned to the event loop, the line is -waiting on work in flight, or the engine lost the step: V8 loses one that leaves an `async` function or a -generator through `try … finally`, a `for … of` loop or a `using` declaration, or one out of a plain function -whose caller awaits the call; the server rescues only steps out of a plain function into a caller that stays on -the stack). An attach that steps through skipped code (`smartStep: true`) gets no such sentence. +waiting on work in flight, or the engine lost the step: V8 loses one that leaves a function through `try … +finally`, a `for … of` loop or a `using` declaration, and the server rescues it only when it returns into a plain +function). An attach that steps through skipped code (`smartStep: true`) gets no such sentence. So match a pending step by its `pending: true` flag, not by the message text. Once a stop has been observed, the stop path owns the answer — a step that demonstrably landed is never reported as pending afterwards, at the cost of the response then being bounded by the stack-trace round trip rather than by the ~5s window. If the debuggee ends while the step is in flight the result is still a success, with a terminal `state` and a message such as `"Step completed as session terminated."`. @@ -783,13 +782,13 @@ Same ~5s wait and `pending: true` contract as step_over — see [Pending steps]( - Out of an `async` function the event loop resumed, the step lands in the function that awaits it, in the call that awaited: that is the engine's own step. - The engine loses a step that leaves a function through `try … finally` (also a `return` out of `for … of`, - and a function with a `using` declaration). Out of a plain function the server catches it with a temporary - breakpoint on every break location of the caller, so the step lands at the caller's next one: the next - statement, or the next call in the same statement. Not when the caller awaits the call, or has more than 100 - break locations: then the step is lost, as below. Out of an `async` function or a generator it does not: a - breakpoint below a function that can suspend cannot tell the function returning from it pausing at an `await`. - Such a step stays lost, as in 0.26.0, and answers `pending: true`; a breakpoint on the caller's next line stops - there. + and a function with a `using` declaration). When the step returns into a plain function, the server catches it + with a temporary breakpoint on every break location of that function, so the step lands at its next one: the + next statement, or the next call in the same statement. When it leaves or returns into an `async` function or a + generator (or a function with more than 100 break locations), it does not: a breakpoint there cannot tell a + function returning from one pausing at an `await`. Such a step stays lost, as in 0.26.0, and answers + `pending: true`, or `Step completed as session exited.` when the program ends first; a breakpoint on the line + you expected it to reach stops there (issue #1174). - Out of a function that nothing of your program called or awaits (a timer callback, a `.then` callback, a request handler) there is nowhere of its own to land: the program is resumed, and the answer is the next stop or `pending: true`. diff --git a/packages/shared/src/interfaces/adapter-policy-js.ts b/packages/shared/src/interfaces/adapter-policy-js.ts index b46db4e48..cea50606c 100644 --- a/packages/shared/src/interfaces/adapter-policy-js.ts +++ b/packages/shared/src/interfaces/adapter-policy-js.ts @@ -452,8 +452,8 @@ export const JsDebugAdapterPolicy = { return 'The step left the frame it started in and has not stopped in your program since: a function that Node ' + 'called returned to the event loop, the line is waiting on work still in flight, or the engine lost the step ' + '(V8 loses one that leaves a function through try...finally, a for...of loop or a using declaration, and the ' + - 'server rescues it only out of a plain function into a caller that does not await the call; a breakpoint on ' + - 'the line you expected it to reach stops there). The program is running; ' + + 'server rescues it only when it returns into a plain function, not into an async function or a generator; ' + + 'a breakpoint on the line you expected it to reach stops there). The program is running; ' + 'wait_for_stop answers when the step lands, a breakpoint is hit, or the program ends.'; }, diff --git a/src/proxy/js-statement-scan.ts b/src/proxy/js-statement-scan.ts deleted file mode 100644 index 844e157cf..000000000 --- a/src/proxy/js-statement-scan.ts +++ /dev/null @@ -1,425 +0,0 @@ -/** - * Reading JavaScript source just far enough to answer two questions for the - * proxy's stepper (issues #1130, #1161): is a function async or a generator - * (`functionKind`, from its header), and can a frame of one suspend between a - * call returning and its next break location (`statementCanSuspend`)? - * - * Measured on V8 13.6: every statement has a break location at its start (a - * statement that begins with a call has it at that call), and every call is - * one. So a frame that returns from a call reaches a break location before it - * can suspend unless the statement making the call awaits or yields, or the - * function suspends without a keyword in that statement (`for await`, - * `await using`, a `return` in an async generator, which awaits its value). - * - * This is not a parser. It masks out strings and comments, finds the - * statement around a position by brackets, semicolons and line breaks, and - * errs toward "can suspend" whenever it is unsure: an unterminated string, - * template or comment on a line it reads, a statement longer than it will - * scan, an ambiguous line break. "Can suspend" costs a rescue; "cannot" when - * the frame can would cost a wrong landing. - */ - -/** How many lines a statement may span before the scan gives up (and says it can suspend). */ -const MAX_STATEMENT_LINES = 40; - -const SUSPENDS = /\b(await|yield)\b/; -const IMPLICIT_SUSPENSION = /\bfor\s+await\b|\bawait\s+using\b/; - -/** A line with its strings and comments blanked out; `unsafe` when it cannot be blanked with confidence. */ -interface MaskedLine { - code: string; - unsafe: boolean; -} - -/** What a line starts inside of, carried from the line before. */ -interface MaskState { - /** A `/* ... *\/` comment. */ - comment: boolean; - /** A template literal that did not end on its line. */ - template: boolean; -} - -function maskLines(lines: readonly string[], from: number, to: number): MaskedLine[] { - const state: MaskState = { comment: false, template: false }; - const masked: MaskedLine[] = []; - for (let i = from; i <= to; i++) { - masked.push(maskLine(lines[i] ?? '', state)); - } - return masked; -} - -/** - * Blank string, template and comment contents on one line, keeping columns. - * `state` carries a block comment and a template literal across lines. A - * line inside a template that spans lines, a string that does not end on its - * line, a template expression, and anything that looks like a regular - * expression literal make the line unsafe. - */ -function maskLine(line: string, state: MaskState): MaskedLine { - let code = ''; - let unsafe = false; - let i = 0; - if (state.template) { - unsafe = true; - let j = 0; - while (j < line.length && line[j] !== '`') { - j += line[j] === '\\' ? 2 : 1; - } - if (j >= line.length) { - return { code: ' '.repeat(line.length), unsafe }; - } - code = ' '.repeat(j) + '`'; - i = j + 1; - state.template = false; - } - while (i < line.length) { - const ch = line[i]; - if (state.comment) { - const end = line.indexOf('*/', i); - if (end === -1) { - code += ' '.repeat(line.length - i); - return { code, unsafe }; - } - code += ' '.repeat(end + 2 - i); - i = end + 2; - state.comment = false; - continue; - } - if (ch === '/' && line[i + 1] === '/') { - // After a lone slash on the line (a division, or a regular expression - // whose own slashes these may be) this is not surely a comment. - if (code.includes('/')) { - unsafe = true; - } - code += ' '.repeat(line.length - i); - return { code, unsafe }; - } - if (ch === '/' && line[i + 1] === '*') { - state.comment = true; - code += ' '; - i += 2; - continue; - } - if (ch === '"' || ch === "'" || ch === '`') { - let j = i + 1; - while (j < line.length && line[j] !== ch) { - if (line[j] === '\\') { - j++; - } else if (ch === '`' && line[j] === '$' && line[j + 1] === '{') { - // An expression inside a template: not read. - unsafe = true; - } - j++; - } - if (j >= line.length) { - // Not closed on this line (or a line continuation): not read with confidence. - unsafe = true; - if (ch === '`') { - state.template = true; - } - code += ' '.repeat(line.length - i); - return { code, unsafe }; - } - code += ch + ' '.repeat(j - i - 1) + ch; - i = j + 1; - continue; - } - if (ch === '/') { - // Division or a regular expression literal: told apart only by context. - const before = code.trimEnd(); - const prev = before[before.length - 1] ?? ''; - if (prev === '' || /[(,=:[!&|?{};+\-*%<>~^]/.test(prev) || /\b(return|typeof|case|do|else|in|of|yield|await)$/.test(before)) { - unsafe = true; - } - } - code += ch; - i++; - } - return { code, unsafe }; -} - -/** Whether a line break between these two lines ends a statement (automatic semicolon insertion). */ -function lineBreakEndsStatement(previous: string, next: string): boolean { - const before = previous.trimEnd(); - const after = next.trimStart(); - if (before === '' || after === '') { - return false; - } - const last = before[before.length - 1]; - const first = after[0]; - // The line before must end like an expression or a statement can end ... - if (!/[\w$)\]}"'`]/.test(last)) { - return false; - } - if (/\b(await|yield|return|new|typeof|instanceof|in|of|void|delete|case|else|extends)$/.test(before)) { - return false; - } - // ... and the next must start like a statement, not continue an expression. - return /[\w$'"{}]/.test(first) && !/^(in|of|instanceof)\b/.test(after); -} - -/** - * Whether the statement containing `column` of `line` (0-based) awaits or - * yields, or the function containing it can suspend without saying so in - * that statement. `from` and `to` bound the function's own lines. Errs toward - * true. - */ -export function statementCanSuspend( - lines: readonly string[], - line: number, - column: number, - from: number, - to: number, - options: { asyncGenerator?: boolean } = {} -): boolean { - const first = Math.max(0, from); - const last = Math.min(lines.length - 1, to); - if (line < first || line > last) { - return true; - } - const masked = maskLines(lines, first, last); - const at = (n: number): MaskedLine => masked[n - first]; - if (masked.some((entry) => IMPLICIT_SUSPENSION.test(entry.code))) { - return true; - } - - // Backward to the start of the statement. - let startLine = line; - let startCol = 0; - { - let depth = 0; - let n = line; - let c = column - 1; - let found = false; - while (!found) { - const code = at(n).code; - for (; c >= 0; c--) { - const ch = code[c]; - if (ch === ')' || ch === ']') { - depth++; - } else if (ch === '(' || ch === '[') { - depth = Math.max(0, depth - 1); - } else if (ch === '}') { - if (depth === 0 && code.slice(c + 1).trim() === '' && n < line && lineBreakEndsStatement(code, at(n + 1).code)) { - // A brace that ends its line, before the statement's line, and - // the next line starts a statement: the end of an earlier block. - startLine = n + 1; - startCol = 0; - found = true; - break; - } - depth++; - } else if (ch === '{') { - if (depth > 0) { - depth--; - } else { - const before = code.slice(0, c).trimEnd(); - const prev = before[before.length - 1] ?? ''; - const objectLiteral = /[(,=:[?!&|.]/.test(prev) || /\b(return|await|yield)$/.test(before); - if (!objectLiteral) { - startLine = n; - startCol = c + 1; - found = true; - break; - } - } - } else if (ch === ';' && depth === 0) { - startLine = n; - startCol = c + 1; - found = true; - break; - } - } - if (found) { - break; - } - if (n === first) { - startLine = first; - startCol = 0; - break; - } - if (line - n >= MAX_STATEMENT_LINES) { - return true; - } - if (depth === 0 && lineBreakEndsStatement(at(n - 1).code, code)) { - startLine = n; - startCol = 0; - break; - } - n--; - c = at(n).code.length - 1; - } - } - - // Forward to its end. - let endLine = line; - let endCol = at(line).code.length; - { - let depth = 0; - let n = line; - let c = column; - let found = false; - while (!found) { - const code = at(n).code; - for (; c < code.length; c++) { - const ch = code[c]; - if (ch === '(' || ch === '[' || ch === '{') { - depth++; - } else if (ch === ')' || ch === ']' || ch === '}') { - // Closing a group the statement started in: it goes on after it. - depth = Math.max(0, depth - 1); - } else if (ch === ';' && depth === 0) { - endLine = n; - endCol = c; - found = true; - break; - } - } - if (found) { - break; - } - if (n === last) { - endLine = last; - endCol = code.length; - break; - } - if (n - line >= MAX_STATEMENT_LINES) { - return true; - } - if (depth === 0 && lineBreakEndsStatement(code, at(n + 1).code)) { - endLine = n; - endCol = code.length; - break; - } - n++; - c = 0; - } - } - - let text = ''; - for (let n = startLine; n <= endLine; n++) { - const entry = at(n); - if (entry.unsafe) { - return true; - } - const from = n === startLine ? startCol : 0; - const to = n === endLine ? endCol : entry.code.length; - text += entry.code.slice(from, to) + '\n'; - } - if (options.asyncGenerator && /\breturn\b/.test(text)) { - // An async generator's return awaits its value. - return true; - } - return SUSPENDS.test(text); -} - -/** What a function's header says it is. */ -export interface FunctionKind { - async: boolean; - generator: boolean; -} - -/** Header words that can stand before a method's or function's name. */ -const MODIFIERS = new Set(['async', 'function', 'static', 'get', 'set', 'accessor']); - -/** - * Whether the function whose header V8's functionLocation points at is async - * or a generator; null when the header cannot be read with confidence. V8 - * points at the parameter list of a function or a method, with - * `[static] [async] [function] [*] [get|set] name` before it, and at the - * first token of an arrow (`async` itself for an async one). The name may be - * an identifier, a private name, a string or a computed key: it is skipped as - * a token, so what it contains does not matter. Reads at most a few lines - * back. - */ -export function functionKind(lines: readonly string[], line: number, column: number): FunctionKind | null { - const first = Math.max(0, line - 4); - const masked = maskLines(lines, first, line); - if (masked.some((entry) => entry.unsafe)) { - return null; - } - const text = masked.map((entry) => entry.code).join('\n'); - let p = masked.slice(0, line - first).reduce((sum, entry) => sum + entry.code.length + 1, 0) + column; - const original = lines[line] ?? ''; - if (/^async\b/.test(original.slice(column))) { - return { async: true, generator: false }; - } - if (text[p] !== '(') { - // An arrow with one bare parameter, or a script's own code: plain. - return { async: false, generator: false }; - } - const isWord = (ch: string | undefined): boolean => ch !== undefined && /[\w$#]/.test(ch); - const skipSpace = (): void => { - while (p > 0 && /\s/.test(text[p - 1])) { - p--; - } - }; - const word = (): string => { - const end = p; - while (p > 0 && isWord(text[p - 1])) { - p--; - } - return text.slice(p, end); - }; - const kind: FunctionKind = { async: false, generator: false }; - - // The name: an identifier, a string, or a computed key; or none (an arrow, an anonymous function). - skipSpace(); - const last = text[p - 1]; - if (last === undefined) { - return null; - } - if (last === ']') { - let depth = 0; - do { - p--; - if (text[p] === ']') { - depth++; - } else if (text[p] === '[') { - depth--; - } - } while (p > 0 && depth > 0); - if (depth !== 0) { - return null; - } - } else if (last === '"' || last === "'") { - p--; - while (p > 0 && text[p - 1] !== last) { - p--; - } - if (p === 0) { - return null; - } - p--; - } else if (isWord(last)) { - const name = word(); - if (name === 'function') { - p += name.length; - } - } else if (last !== '*') { - // `= (`, `, (`, `((`: the parameter list of an arrow. - return kind; - } - - // Then `*`, and the modifiers. - for (;;) { - skipSpace(); - if (text[p - 1] === '*') { - kind.generator = true; - p--; - continue; - } - if (!isWord(text[p - 1])) { - return kind; - } - const before = p; - const modifier = word(); - if (!MODIFIERS.has(modifier)) { - p = before; - return kind; - } - if (modifier === 'async') { - kind.async = true; - } - } -} diff --git a/src/proxy/js-stepper.ts b/src/proxy/js-stepper.ts index 591dc4498..46b6f10b6 100644 --- a/src/proxy/js-stepper.ts +++ b/src/proxy/js-stepper.ts @@ -35,43 +35,36 @@ * Any position there is where V8's own step-out would stop, so a hit at * that depth is a landing. * - * A NET IS SET ONLY WHERE A HIT PROVES THE STEP CAME BACK. Three versions - * of a wider rule each stopped steps in the wrong place, because nothing - * V8 exposes tells "the function returned" from "it suspended at an - * await", nor one call of a function from another. So, in one place, - * before every command that can leave the frame on top (`guard`): + * A NET IS SET ONLY WHERE A HIT PROVES THE STEP CAME BACK. Five versions + * of the rule that decided where read the program's source to tell a + * function that returns from one that suspends at an `await` or `yield`, + * and each was fooled by some way of writing JavaScript. V8 knows, and + * says so on every frame of a pause: `canBeRestarted` is false for an + * async function, a generator and module code that may await, and for + * every frame below one (measured on Node 22, 24 and 26 over every + * function form). So, in one place, before every command that can leave + * the frame on top (`guard`): * - * (a) The frame being left is a PLAIN function: not async, not a - * generator, not module code. That is read from its header (the text - * V8's functionLocation points at), for Node's own code as for the - * program's; a header that cannot be read counts as one that can - * suspend. A plain function comes down only by returning, so - * control back in the frame below means it returned: V8 landed - * there too, or lost the step. A function that can suspend is V8's - * own: V8 keeps a step across an `await`, and what it loses there - * (a leave through `finally` within one run) stays lost, and the - * answer says so. To spare the breakpoints where they cannot matter, - * a plain function whose text names nothing that closes through a - * finally (`finally`, `for...of`, `using`) is not netted either: - * that test only ever errs toward netting, and a miss costs a - * rescue, never a wrong landing. + * (a) The frame guarded, the nearest frame of the program below, can be + * restarted. Then it and every frame above it are plain functions: + * each comes down only by returning, so control back in the guarded + * frame means the step came back, and the guarded frame stays on the + * stack until it reaches a net position. A frame that cannot be + * restarted is not netted: a step that leaves through an async + * function or a generator, or returns to one, is V8's own, and what + * V8 loses there stays lost (issue #1174). To spare breakpoints, a + * function being left whose text names nothing that closes through + * a finally (`finally`, `for...of`, `using`) is not netted either; + * that test only ever errs toward netting. * - * (b) The frame guarded is on the stack and stays there until it - * reaches a net position. A plain function does. One that can - * suspend does unless it can suspend between the call returning - * and its next break location: V8 puts one at every statement's - * start and every call, so only when the calling statement awaits - * or yields, or the function suspends with no keyword there (`for - * await`, `await using`, an async generator's `return`). Then it can - * leave the stack before any position, another call of the same - * function can take its depth, and no net is set. - * - * (c) The net covers every break position of the frame it guards, or + * (b) The net covers every break position of the frame it guards, or * there is none: a hit is then the first position control reaches - * in that activation. A function with more than `netSize` - * positions is not netted. A rescue lands at the caller's next - * break location after the call; V8's own step-out, when it does - * not lose the step, can stop once more on the call's own line. + * in that activation. A function with more than `netSize` positions, + * or whose positions cannot all be found, is not netted, and when + * V8 refuses one of them none is kept. A rescue lands at the + * caller's next break location after the call; V8's own step-out, + * when it does not lose the step, can stop once more on the call's + * own line. * * Nothing is ever guarded that is not on the stack (no net on an awaiting * function), and nothing is decided on a pause's reason, which does not @@ -113,7 +106,6 @@ import type { DebugProtocol } from '@vscode/debugprotocol'; import { createLogger } from '../utils/logger.js'; import { ErrorMessages } from '../utils/error-messages.js'; -import { functionKind, statementCanSuspend, type FunctionKind } from './js-statement-scan.js'; // redirectable: re-pointed into the per-session proxy log at worker init (#519) const logger = createLogger('js-stepper', { redirectable: true }); @@ -195,8 +187,11 @@ interface CdpCallFrame { functionName?: string; functionLocation?: CdpLocation; location: CdpLocation; - /** Innermost scope first; `module` before any `local` means the frame is a module's own code. */ - scopeChain?: Array<{ type?: string }>; + /** + * V8's word on restarting the frame: false for an async function, a + * generator, module code that may await, and every frame below one. + */ + canBeRestarted?: boolean; } interface CdpAsyncFrame { @@ -340,8 +335,6 @@ export class JsStepper { private owedNetHit = false; /** Scripts js-debug marked "Skipped by skipFiles": a script-level verdict, not asked again. */ private readonly skippedScripts = new Set(); - /** Whether a function can suspend, by its header: read once per function. */ - private readonly kinds = new Map(); /** Whether a function's text names a construct that closes through a finally. */ private readonly closing = new Map(); /** What each pause's top frame returns to: asked of js-debug once per pause. */ @@ -943,14 +936,27 @@ export class JsStepper { /** The break positions of the frame's function. */ private async locationsOf(frame: CdpCallFrame): Promise { const here = frame.location; - let all = frame.functionLocation ? await this.possible(frame.functionLocation) : []; - // Top-level code whose first token is a function declaration: the function - // at that position is the nested one. Ask from the frame's own line. - const spans = all.length > 0 && sameOrAfter(here, all[0]) && sameOrAfter(all[all.length - 1], here); - if (!spans) { - all = await this.possible({ scriptId: here.scriptId, lineNumber: here.lineNumber, columnNumber: 0 }); + let start = frame.functionLocation; + // Top-level code whose first token is a function declaration: V8 answers + // the nested function's positions for the script's own position. The + // script's code goes on after that function, so ask again from just after + // its last position, until the answer holds the frame's position. Every + // position of the frame's function, or none: a part of it is not a net. + for (let tries = 0; start && tries < 16; tries++) { + const all = await this.possible(start); + if (all.length === 0) { + return []; + } + if (sameOrAfter(here, all[0]) && sameOrAfter(all[all.length - 1], here)) { + return all; + } + const last = all[all.length - 1]; + if (!sameOrAfter(here, last)) { + return []; + } + start = { scriptId: last.scriptId, lineNumber: last.lineNumber, columnNumber: (last.columnNumber ?? 0) + 1 }; } - return all; + return []; } /** A net on every one of `all`, the break positions of the function it guards. */ @@ -972,7 +978,9 @@ export class JsStepper { ) ); const ids = new Set(answers.map((answer) => answer?.breakpointId).filter((id): id is string => typeof id === 'string')); - if (ids.size === 0) { + if (ids.size < all.length) { + // A net with a hole is no net: remove what was set. + await Promise.all([...ids].map((breakpointId) => cdp.send('Debugger.removeBreakpoint', { breakpointId }).catch(() => undefined))); return false; } this.nets.push({ ...net, ids }); @@ -998,79 +1006,13 @@ export class JsStepper { let lines = this.sources.get(scriptId); if (!lines) { const answer = await this.cdp?.send<{ scriptSource?: string }>('Debugger.getScriptSource', { scriptId }); - lines = (answer?.scriptSource ?? '').split('\n'); + // V8 ends a line at CR LF, LF, CR, U+2028 and U+2029. + lines = (answer?.scriptSource ?? '').split(/\r\n|[\n\r\u2028\u2029]/); this.sources.set(scriptId, lines); } return lines; } - /** - * Rule (a): whether the frame's function can hand control down without - * returning: an async function, a generator, or a module's own code (which - * may await at its top level). Read from the function's header, the text - * V8's functionLocation points at, which is the parameter list of a - * function or method (`async`, `*` stand right before it) and the first - * token of an arrow (`async` itself). V8 gives the source of Node's own - * scripts too. Doubt reads as "can suspend": no net. Never throws. - */ - private async canSuspend(frame: CdpCallFrame): Promise { - const kind = await this.kindOf(frame); - return kind === null || kind.async || kind.generator; - } - - /** - * What the frame's function is, by `functionKind`; null when that is not - * known with confidence, and for a module's own code (which may await at - * its top level). Read once per function. Never throws. - */ - private async kindOf(frame: CdpCallFrame): Promise { - const key = fnKey(frame); - if (this.kinds.has(key)) { - return this.kinds.get(key) ?? null; - } - let kind: FunctionKind | null = null; - try { - const scopes = frame.scopeChain ?? []; - const firstFunctionScope = scopes.find((scope) => scope.type === 'local' || scope.type === 'module'); - const at = frame.functionLocation; - if (firstFunctionScope?.type !== 'module' && at) { - kind = functionKind(await this.linesOf(at.scriptId), at.lineNumber, at.columnNumber ?? 0); - } - } catch (err) { - logger.debug(`[JsStepper] could not read a function's header: ${errorText(err)}`); - } - this.kinds.set(key, kind); - return kind; - } - - /** - * Rule (b), for a guarded frame that can suspend: whether it can suspend - * between the call it is making returning and its next break location. V8 - * puts a break location at every statement's start and at every call, so - * it cannot unless the calling statement awaits or yields, or the function - * suspends without a keyword there (`for await`, `await using`): read by - * `statementCanSuspend`, which errs toward "it can". Never throws. - */ - private async callStatementSuspends(frame: CdpCallFrame): Promise { - try { - const here = frame.location; - const all = await this.locationsOf(frame); - if (all.length === 0) { - return true; - } - const lines = await this.linesOf(here.scriptId); - const from = Math.min(frame.functionLocation?.lineNumber ?? all[0].lineNumber, all[0].lineNumber); - const to = all[all.length - 1].lineNumber; - const kind = await this.kindOf(frame); - return statementCanSuspend(lines, here.lineNumber, here.columnNumber ?? 0, from, to, { - asyncGenerator: kind === null || (kind.async && kind.generator) - }); - } catch (err) { - logger.debug(`[JsStepper] could not read the calling statement: ${errorText(err)}`); - return true; - } - } - /** * Whether the function's text names a construct that closes through a * finally, the only exits V8 loses a step on: `finally`, `for...of`, @@ -1114,12 +1056,14 @@ export class JsStepper { try { const frames = pause.callFrames; const top = frames[0]; - if (this.guardedBelow(frames.length) || (skipped && chain.walkHasNothingBelow)) { + if (chain.unwinding || this.guardedBelow(frames.length) || (skipped && chain.walkHasNothingBelow)) { + // Unwinding: a net fired in a deeper call and was dropped; V8's own + // step-outs finish the step. return; } - // (a) Only below a frame that comes down by returning, and no other way; - // and only where its text names something V8 can lose the step on. - if ((await this.canSuspend(top)) || !(await this.namesAFinally(top))) { + // Only where the text of the function being left names something V8 can + // lose the step on: this spares breakpoints, and errs toward netting. + if (!(await this.namesAFinally(top))) { return; } const target = await this.returnTarget(chain, pause); @@ -1135,11 +1079,12 @@ export class JsStepper { // It returns to itself (recursion): a net would sit in the frame being stepped in. return; } - // (b) The guarded frame must still be on the stack when it reaches a net position. - if ((await this.canSuspend(frame)) && (await this.callStatementSuspends(frame))) { + // (a) V8's own word: the guarded frame and every frame above it are + // plain functions, which come down only by returning. + if (frame.canBeRestarted !== true) { return; } - // (c) Every position of it, or none. + // (b) Every position of it, or none. const all = await this.locationsOf(frame); if (all.length === 0 || all.length > this.tunables.netSize) { return; diff --git a/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts b/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts index c6fd9ce0d..49e3f389a 100644 --- a/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts +++ b/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts @@ -171,6 +171,22 @@ describe('The server\'s JavaScript stepper against a real js-debug (issues #1130 expectLanding(await step('step_over'), 'after withFinally'); }, 60000); + it('step_out into an async caller is the engine\'s own, and the engine loses it (#1174)', async () => { + // The function being left is plain; the caller is async. It could + // suspend before a temporary breakpoint proves the step came back, so + // the server sets none. The program runs on to its end. + await pausedAt('return inside try-finally', undefined, ['calls withFinally from an async function']); + // The first stop is the call from the plain caller: run to the second. + let stop = await server!.call('continue_execution', {}); + stop = await server!.call('wait_for_stop', { timeout: 20000 }); + expect(stop.location?.line, JSON.stringify(stop)).toBe(lineOf('calls withFinally from an async function')); + stop = await server!.call('step_into', {}); + expect(stop.location?.line, JSON.stringify(stop)).toBe(lineOf('return inside try-finally')); + const answer = await step('step_out'); + expect(answer, JSON.stringify(answer)).toMatchObject({ success: true }); + expect(answer.state, JSON.stringify(answer)).not.toBe('paused'); + }, 60000); + it('step_out of an async function with that shape is the engine\'s own, and the engine loses it (#1174)', async () => { await pausedAt('async return inside try-finally'); // A temporary breakpoint below a function that can suspend cannot tell diff --git a/tests/fixtures/javascript/step-skipped-code/steps.cjs b/tests/fixtures/javascript/step-skipped-code/steps.cjs index 10c5d5cbb..a0e283fb4 100644 --- a/tests/fixtures/javascript/step-skipped-code/steps.cjs +++ b/tests/fixtures/javascript/step-skipped-code/steps.cjs @@ -53,6 +53,17 @@ function laterCallback() { globalThis.later = true; // MARK: a later task } +// A plain function, so the steps below return into a frame that comes down +// only by returning: the one shape the server rescues a lost step into +// (issue #1161). The same calls from an async function are left to V8 (#1174). +function syncPart() { + const guarded = withFinally(); // MARK: calls withFinally + const afterFinally = 4; // MARK: after withFinally + const lazy = require('./lazy.cjs'); // MARK: first load of a module + const afterRequire = lazy.value + 6; // MARK: after the require + return [guarded, afterFinally, afterRequire]; +} + async function main() { console.log('first line printed'); // MARK: the first console.log const afterLog = 1; // MARK: after the first console.log @@ -62,16 +73,15 @@ async function main() { setTimeout(() => {}, 0); // MARK: starts a later task const afterTimeout = 3; // MARK: after setTimeout const called = callee(); // MARK: calls a function with a breakpoint - const guarded = withFinally(); // MARK: calls withFinally - const afterFinally = 4; // MARK: after withFinally + const fromSync = syncPart(); const awaited = await workWithFinally(); // MARK: awaits workWithFinally const afterAwait = 5; // MARK: after the await - const lazy = require('./lazy.cjs'); // MARK: first load of a module - const afterRequire = lazy.value + 6; // MARK: after the require + const again = withFinally(); // MARK: calls withFinally from an async function + const afterAgain = 7; // MARK: after withFinally from an async function setTimeout(timerCallback, 0); setTimeout(laterCallback, 30); await sleep(120); - return [afterLog, mapped, afterEmit, afterTimeout, called, guarded, afterFinally, awaited, afterAwait, afterRequire]; + return [afterLog, mapped, afterEmit, afterTimeout, called, fromSync, awaited, afterAwait, again, afterAgain]; } main().then(() => { diff --git a/tests/proxy/js-statement-scan.test.ts b/tests/proxy/js-statement-scan.test.ts deleted file mode 100644 index 6cf6f5d24..000000000 --- a/tests/proxy/js-statement-scan.test.ts +++ /dev/null @@ -1,177 +0,0 @@ -/** - * The one question the proxy's JavaScript stepper asks of a caller's source - * (issues #1130, #1161): can the caller suspend between the call it is - * making returning and its next break location? Every case below is a shape - * one of the stepper's reviews found, or a way the scan could be fooled. The - * scan must err toward "it can": that costs a rescue, never a wrong landing. - */ -import { describe, it, expect } from 'vitest'; -import { functionKind, statementCanSuspend } from '../../src/proxy/js-statement-scan.js'; - -/** The source, and the 0-based line and column of the call marked `@` (the marker is removed). */ -function at(source: string): { lines: string[]; line: number; column: number } { - const lines = source.split('\n'); - const line = lines.findIndex((text) => text.includes('@')); - const column = lines[line].indexOf('@'); - lines[line] = lines[line].replace('@', ''); - return { lines, line, column }; -} - -function suspends(source: string): boolean { - const { lines, line, column } = at(source); - return statementCanSuspend(lines, line, column, 0, lines.length - 1); -} - -describe('statementCanSuspend', () => { - describe('a statement that does not await: the caller reaches a break location first', () => { - it.each([ - ['a plain call', 'async function f() {\n const got = @inner(id);\n return got;\n}'], - ['a call whose line has a comment about await', 'async function f() {\n const got = @inner(id); // after the await\n}'], - ['a comment about await on the line before', 'async function f() {\n const a = 1; // MARK: after the await\n const lazy = @require("./lazy.cjs");\n}'], - ['await in a string', 'async function f() {\n const got = @inner("await me");\n}'], - ['an await in an earlier statement', 'async function f() {\n await ready;\n const got = @inner(id);\n}'], - ['an await in a later statement', 'async function f() {\n const got = @inner(id);\n await done(got);\n}'], - ['no semicolons, an await on the next statement', 'async function f() {\n const got = @inner(id)\n const more = await other(got)\n}'], - ['no semicolons, an await on the statement before', 'async function f() {\n const first = await other()\n const got = @inner(id)\n}'], - ['an await inside the block before', 'async function f() {\n try {\n await a;\n } finally {\n b();\n }\n const got = @inner(id);\n}'], - ['an object literal around the call', 'async function f() {\n const o = {\n a: @inner(id),\n b: 2\n };\n}'], - ['the call inside an if', 'async function f() {\n if (ok) {\n @inner(id);\n }\n await later;\n}'] - ])('%s', (_what, source) => { - expect(suspends(source)).toBe(false); - }); - }); - - describe('a statement that can suspend before its next break location', () => { - it.each([ - ['the call awaited', 'async function f() {\n const got = await @inner(id);\n}'], - ['returned awaited', 'async function f() {\n return await @inner(id);\n}'], - ['awaited through a member chain on the next line', 'async function f() {\n const got = await api\n .@inner(id);\n}'], - ['awaited on the line above the argument', 'async function f() {\n const total = await fetchA(\n id,\n @compute(id));\n}'], - ['an await later in the statement', 'async function f() {\n const v = @inner(id) + await other();\n}'], - ['an await in a sibling argument', 'async function f() {\n use(@inner(id), await other(id));\n}'], - ['an await in a multi-line object around the call', 'async function f() {\n return {\n user: await getUser(id),\n posts: @inner(id),\n };\n}'], - ['a yield', 'function* g() {\n const got = yield @inner(id);\n}'], - ['a for await loop anywhere in the function', 'async function f() {\n for await (const x of xs) {\n @inner(x);\n }\n}'], - ['an await using anywhere in the function', 'async function f() {\n await using h = open();\n @inner(1);\n}'], - ['a nested async callback that awaits', 'async function f() {\n @inner(items.map(async (i) => { await send(i); }));\n}'], - ['an await around a spread object', 'async function f(id) {\n const v = await {\n ...{ a: @work(id) }\n };\n}'], - ['an await before an object argument that closes on its own line', 'async function f(id) {\n const v = await wrap(function () {\n return 1;\n }\n , @work(id));\n}'], - ['an await before an arrow argument', 'async function f(id) {\n const v = await both(() => {\n return 1;\n }, @work(id));\n}'], - ['a line that ends in await', 'async function f(id) {\n const v = await\n @work(id);\n}'] - ])('%s', (_what, source) => { - expect(suspends(source)).toBe(true); - }); - }); - - describe('an async generator', () => { - it('awaits the value it returns: a return of the call can suspend', () => { - const { lines, line, column } = at('async function* g(id) {\n noop();\n return @work(id);\n}'); - expect(statementCanSuspend(lines, line, column, 0, lines.length - 1, { asyncGenerator: true })).toBe(true); - expect(statementCanSuspend(lines, line, column, 0, lines.length - 1)).toBe(false); - }); - - it('reads a return that ends its line as part of the statement on the next', () => { - const { lines, line, column } = at('async function* g(id) {\n noop();\n return (\n @work(id));\n}'); - expect(statementCanSuspend(lines, line, column, 0, lines.length - 1, { asyncGenerator: true })).toBe(true); - }); - }); - - describe('a block comment', () => { - it('is not read as code', () => { - expect(suspends('async function f(id) {\n /* await later */ const v = @work(id);\n}')).toBe(false); - }); - }); - - describe('errs toward "it can" where it cannot read with confidence', () => { - it.each([ - ['a template literal with an expression', 'async function f() {\n const got = @inner(`${id}`);\n}'], - ['a string that does not end on its line', 'async function f() {\n const got = @inner("a\\\n b");\n}'], - ['a regular expression literal', 'async function f() {\n const got = @inner(/;/.test(id));\n}'], - ['a regular expression with slashes after a paren', 'async function f(id, s) {\n if (s) /\\/\\//.test(s) && await use(@work(id));\n}'], - ['a template that spans lines', 'async function f(id) {\n const css = await `\n .a { color: ${@work(id)}; }\n`;\n}'], - ['a block comment that hides an await', 'async function f(id) {\n const v = /* x */ await /* y */ @work(id);\n}'], - ['a call outside the function', 'const got = @inner(id);'] - ])('%s', (_what, source) => { - const { lines, line, column } = at(source); - const outside = _what === 'a call outside the function'; - expect(statementCanSuspend(lines, line, column, outside ? line + 1 : 0, lines.length - 1)).toBe(true); - }); - - it('a statement longer than it will scan', () => { - const body = Array.from({ length: 60 }, (_, i) => ` arg${i},`).join('\n'); - expect(suspends(`async function f() {\n const got = use(\n${body}\n @inner(id));\n}`)).toBe(true); - }); - }); -}); - -/** - * What a function is, read from the header V8's functionLocation points at: - * the parameter list of a function or a method, the first token of an arrow. - * Columns below are where V8 points (measured on Node 24 for the first - * group; the rest follow the same rule). - */ -describe('functionKind', () => { - /** The header, with the position V8 points at marked `@` (the marker is removed). */ - function kindOf(source: string): { async: boolean; generator: boolean } | null { - const { lines, line, column } = at(source); - return functionKind(lines, line, column); - } - const plain = { async: false, generator: false }; - const isAsync = { async: true, generator: false }; - const generator = { async: false, generator: true }; - const asyncGenerator = { async: true, generator: true }; - - it.each([ - ['function plainDecl@() { }', plain], - ['const plainExpr = function @() { };', plain], - ['const plainArrow = @() => { };', plain], - ['async function asyncDecl@() { }', isAsync], - ['const asyncExpr = async function @() { };', isAsync], - ['const asyncArrow = @async () => { };', isAsync], - ['const asyncArrowBare = @async a => { };', isAsync], - ['function* genDecl@() { }', generator], - ['const genExpr = function* @() { };', generator], - ['async function* asyncGen@() { }', asyncGenerator], - [' method@() { }', plain], - [' async asyncMethod@() { }', isAsync], - [' *genMethod@() { }', generator], - [' async *asyncGenMethod@() { }', asyncGenerator], - [' static async staticAsync@() { }', isAsync], - [' get prop@() { return 1; }', plain], - [' objPlain@() { },', plain], - [' arrowProp: @async () => { }', isAsync], - ['Module.prototype.require = function@(id) {', plain], - ['run(function inner@() { }, async function next() { });', plain], - ['run(function inner() { }, async function next@() { });', isAsync], - [' constructor@(a) { }', plain], - [' #secret@() { }', plain], - [' async #secret@() { }', isAsync], - [' async() { }'.replace('()', '@()'), plain] - ])('%s', (source, expected) => { - expect(kindOf(source)).toEqual(expected); - }); - - it.each([ - ['a string key holding a colon', " async 'GET /users/:id'@(req) { }", isAsync], - ['a string key holding a comma', " async 'a,b'@(x) { }", isAsync], - ['a computed key holding a colon', " async [Symbol.for('a:b')]@(x) { }", isAsync], - ['a generator with a computed key holding a comma', " *[Symbol.for('g,h')]@() { }", generator], - ['a static async computed key', " static async ['s:A']@(x) { }", isAsync], - ['an async generator computed key', ' async *[Symbol.asyncIterator]@() { }', asyncGenerator], - ['a plain string key holding the word async', " 'async (x)'@(x) { }", plain] - ])('a key the old read lost: %s', (_what, source, expected) => { - expect(kindOf(source)).toEqual(expected); - }); - - it.each([ - ['a function header split across lines', 'async function\nname@(x) { }', isAsync], - ['a generator header split across lines', 'function*\nname@() { }', generator], - ['a comment inside the header', 'async /* the handler */ function handler@(req) { }', isAsync] - ])('reads %s', (_what, source, expected) => { - expect(kindOf(source)).toEqual(expected); - }); - - it('does not know a header it cannot read with confidence: a computed key with a template expression', () => { - expect(kindOf(' async [`k${1}`]@(x) { }')).toBeNull(); - }); -}); diff --git a/tests/proxy/js-stepper.test.ts b/tests/proxy/js-stepper.test.ts index 604043be4..69675dce8 100644 --- a/tests/proxy/js-stepper.test.ts +++ b/tests/proxy/js-stepper.test.ts @@ -26,8 +26,11 @@ interface Frame { fnLine?: number; /** Column V8 reports for the function: its parameter list, or the first token of an arrow. */ fnCol?: number; - /** The frame is a module's own code (its scope chain starts with `module`). */ - module?: boolean; + /** + * An async function, a generator or module code that may await: V8 says it + * cannot be restarted, and neither can any frame below it. + */ + resumable?: boolean; /** js-debug marks it skipped code. */ skipped?: boolean; /** The mark's wording; "Skipped by skipFiles" is a script-level verdict. */ @@ -48,6 +51,8 @@ interface ScriptedPause { * (the default: the function on top returns to it), `Promise.then`, * `Timeout` (it only scheduled the code on top). */ + /** V8 too old to say whether a frame can be restarted: the field is left out. */ + noRestartInfo?: boolean; asyncParent?: { fn: string; script?: string; line: number; col?: number; skipped?: boolean; description?: string; /** `await` links with no frames before the one that has the awaiter (V8 lists them for later awaits). */ @@ -126,7 +131,15 @@ class Engine extends EventEmitter { throw new Error('Debugger.getPossibleBreakpoints: Cannot retrive script context'); } const own = [...this.positions.entries()].find(([key]) => key === `${start.scriptId}:${start.lineNumber}`)?.[1]; - const list = own ?? Array.from({ length: 10 }, (_, i) => ({ lineNumber: start.lineNumber + i })); + // By default a function's positions are ten lines from its start, and + // every line a frame of it is at in this test: as V8 answers, the + // function's positions hold every place it can be paused. + const framesOfIt = [this.current, ...this.script] + .flatMap((p) => (p && p !== 'runs' ? p.frames : [])) + .filter((f) => (f.script ?? 'app') === start.scriptId && fnLineOf(f) === start.lineNumber) + .map((f) => f.line); + const lines = [...new Set([...Array.from({ length: 10 }, (_, i) => start.lineNumber + i), ...framesOfIt])].sort((a, b) => a - b); + const list = own ?? lines.map((lineNumber) => ({ lineNumber })); return { locations: list.map((l) => ({ scriptId: start.scriptId, columnNumber: 0, ...l })) } as T; } case 'Debugger.setBreakpoint': { @@ -208,11 +221,12 @@ class Engine extends EventEmitter { return { reason: pause.reason ?? (hits.length > 0 ? 'other' : 'step'), hitBreakpoints: hits, - callFrames: pause.frames.map((f) => ({ + callFrames: pause.frames.map((f, i) => ({ functionName: f.fn, functionLocation: { scriptId: f.script ?? 'app', lineNumber: fnLineOf(f), columnNumber: f.fnCol ?? 0 }, location: { scriptId: f.script ?? 'app', lineNumber: f.line, columnNumber: f.col ?? 0 }, - scopeChain: f.module ? [{ type: 'module' }, { type: 'global' }] : [{ type: 'local' }, { type: 'global' }] + // As measured on Node 22, 24 and 26: false for a resumable frame and every frame below one. + ...(pause.noRestartInfo ? {} : { canBeRestarted: !pause.frames.slice(0, i + 1).some((above) => above.resumable) }) })), ...(pause.asyncParent ? { asyncStackTrace: this.asyncTrace(pause.asyncParent) } : {}) }; @@ -681,20 +695,51 @@ describe('JsStepper (issue #1130)', () => { expect(stopped()).toMatchObject({ reason: 'step' }); }); - it('asks from the frame\'s own line when the function position answers for a nested function', async () => { - // Top-level code that starts with a function declaration: V8 answers - // the nested function's positions for the module's own position. + it('nets every position of top-level code that starts with a function: asked again past the nested one', async () => { + // V8 answers the nested function's positions for the script's own + // position; the script's code goes on after it, before the frame's line too. const moduleStart = fnLineOf(app('(module)', 0)); engine.positions.set(`app:${moduleStart}`, [{ lineNumber: moduleStart + 1 }, { lineNumber: moduleStart + 2 }]); - engine.positions.set('app:900', [{ lineNumber: 900 }, { lineNumber: 901 }, { lineNumber: 902 }]); - engine.pauseAt({ frames: frames(lossy(app('callee', 5)), app('(module)', 900, { fnLine: moduleStart })) }); - engine.script = [{ frames: frames(app('(module)', 901, { fnLine: moduleStart })) }]; + engine.positions.set(`app:${moduleStart + 2}`, [{ lineNumber: moduleStart + 4 }, { lineNumber: moduleStart + 19 }, { lineNumber: moduleStart + 20 }, { lineNumber: moduleStart + 21 }]); + engine.pauseAt({ frames: frames(lossy(app('callee', 5)), app('(module)', moduleStart + 20, { fnLine: moduleStart })) }); + engine.script = [{ frames: frames(app('(module)', moduleStart + 21, { fnLine: moduleStart })), reason: 'other', hits: (armed) => [armed[armed.length - 1].id] }]; await stepper.request('stepOut', { threadId: 1 }); await settled(); const lines = engine.calls .filter((c) => c.method === 'Debugger.setBreakpoint') .map((c) => (c.params.location as { lineNumber: number }).lineNumber); - expect(lines).toEqual([900, 901, 902]); + expect(lines).toEqual([moduleStart + 4, moduleStart + 19, moduleStart + 20, moduleStart + 21]); + expect(stopped()).toMatchObject({ reason: 'step' }); + }); + + it('nets nothing when the frame\'s own positions cannot all be found', async () => { + const moduleStart = fnLineOf(app('(lost module)', 0)); + engine.positions.set(`app:${moduleStart}`, [{ lineNumber: moduleStart + 1 }]); + engine.positions.set(`app:${moduleStart + 1}`, []); + engine.pauseAt({ frames: frames(lossy(app('callee', 5)), app('(lost module)', moduleStart + 20, { fnLine: moduleStart })) }); + engine.script = [{ frames: frames(app('(lost module)', moduleStart + 21, { fnLine: moduleStart })) }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(setBreakpoints()).toBe(0); + }); + + it('keeps no part of a net when V8 refuses one of its breakpoints', async () => { + let n = 0; + const send = engine.send.bind(engine); + engine.send = (async (method: string, params?: Record) => { + if (method === 'Debugger.setBreakpoint' && ++n === 3) { + throw new Error('Debugger.setBreakpoint: refused'); + } + return send(method, params); + }) as typeof engine.send; + engine.pauseAt({ frames: frames(lossy(app('leaf', 5)), app('caller', 14)) }); + engine.script = [{ frames: frames(app('caller', 15)) }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); + expect(n).toBeGreaterThan(3); + expect(engine.armed).toEqual([]); + expect(engine.removed.length).toBe(n - 1); + expect(stopped()).toMatchObject({ reason: 'step' }); }); }); @@ -1529,22 +1574,13 @@ describe('JsStepper (issue #1130)', () => { // ----- the provable rule: rule (a), the frame being left; rule (b), the frame guarded ----- - describe('rule (a): only a plain function is netted', () => { - /** The frame, with its function written as this header (V8 points at the parameter list). */ - function headed(frame: Frame, header: string): Frame { - sourceWith({ [fnLineOf(frame)]: header }, frame.script ?? 'app'); - return { ...frame, fnCol: header.includes('=>') && !header.includes('(') ? header.indexOf('async') : header.indexOf('(') }; - } - + describe('V8\'s word on the guarded frame: a net only below frames that come down by returning', () => { it.each([ - ['an async function', 'async function work() {'], - ['a generator', 'function* work() {'], - ['an async method', ' async work() {'] - ])('sets none below %s, whatever it contains: V8 keeps a step across an await, and what it loses there stays lost', async (_what, header) => { - const start = fnLineOf(app('suspender', 0)); - const top = headed(app('suspender', start + 2), header); - sourceWith({ [start + 4]: 'try { return x(); } finally { done(); }' }); - engine.pauseAt({ frames: frames(top, app('caller', 14)) }); + ['an async function', 'async function'], + ['a generator', 'generator'], + ['module code that may await', 'module code'] + ])('sets none when the function being left is %s, whatever it contains', async (_what) => { + engine.pauseAt({ frames: frames(lossy(app('suspender', 5, { resumable: true })), app('caller', 14)) }); engine.script = [{ frames: frames(app('caller', 15)) }]; await stepper.request('stepOut', { threadId: 1 }); await settled(); @@ -1552,49 +1588,33 @@ describe('JsStepper (issue #1130)', () => { expect(stopped()).toMatchObject({ reason: 'step' }); }); - it('sets none below a module\'s own code, which may await at its top level', async () => { - const start = fnLineOf(app('(module code)', 0)); - sourceWith({ [start + 4]: 'try { x(); } finally { done(); }' }); - engine.pauseAt({ frames: frames(app('(module code)', start + 2, { module: true }), app('caller', 14)) }); - engine.script = [{ frames: frames(app('caller', 15)) }]; + it('sets none when the caller is async, though the function being left is plain: it can suspend before any position', async () => { + engine.pauseAt({ frames: frames(lossy(app('innerSync', 30)), app('handler', 14, { resumable: true })) }); + engine.script = [{ frames: frames(app('handler', 15, { resumable: true })) }]; await stepper.request('stepOut', { threadId: 1 }); await settled(); expect(setBreakpoints()).toBe(0); }); - it.each([ - ['a comment that says await', '// nothing to await here'], - ['a nested async callback', 'items.map(async (item) => { await send(item); });'], - ['a loop', 'for (const item of items) { use(item); }'] - ])('nets a plain function whatever its text says: %s', async (_what, text) => { - const start = fnLineOf(app('plainWith', 0)); - sourceWith({ [start + 1]: text, [start + 4]: 'try { return x(); } finally { done(); }' }); - engine.pauseAt({ frames: frames(app('plainWith', start + 2), app('caller', 14)) }); - engine.script = [{ frames: frames(app('caller', 15)), reason: 'other', hits: (armed) => [armed[0].id] }]; + it('nets a plain caller of a plain function, whatever is below the caller', async () => { + engine.pauseAt({ frames: frames(lossy(app('innerSync', 30)), app('handler', 14), app('main', 40, { resumable: true })) }); + engine.script = [{ frames: frames(app('handler', 15), app('main', 40, { resumable: true })), reason: 'other', hits: (armed) => [armed[0].id] }]; await stepper.request('stepOut', { threadId: 1 }); await settled(); expect(setBreakpoints()).toBeGreaterThan(0); expect(stopped()).toMatchObject({ reason: 'step' }); - expect(stopped().text).toBeUndefined(); expect(engine.armed).toEqual([]); }); - it.each([ - ['a return out of for...of', 'for (const item of items) { if (item) return item; }'], - ['a using declaration', 'using handle = open();'] - ])('nets the exits V8 loses with no finally written: %s', async (_what, text) => { - const start = fnLineOf(app('implicit', 0)); - sourceWith({ [start + 3]: text }); - engine.pauseAt({ frames: frames(app('implicit', start + 2), app('caller', 14)) }); - engine.script = [{ frames: frames(app('caller', 15)), reason: 'other', hits: (armed) => [armed[0].id] }]; + it('sets none when async skipped code stands between: it can suspend and hand control down', async () => { + engine.pauseAt({ frames: frames(lossy(app('callback', 40)), node('readFile', 7, { resumable: true }), app('main', 10)) }); + engine.script = [{ frames: frames(app('main', 11)) }]; await stepper.request('stepOut', { threadId: 1 }); await settled(); - expect(setBreakpoints()).toBeGreaterThan(0); - expect(stopped()).toMatchObject({ reason: 'step' }); + expect(setBreakpoints()).toBe(0); }); - it('nets Node\'s own code without reading its text for a finally: V8 refuses its break positions', async () => { - // A step over that returns into Node's code: the frame left next is Node's, plain by its header. + it('nets through plain skipped code: Node\'s own code is not read', async () => { engine.pauseAt({ frames: frames(app('listener', 40), node('emit', 7), app('main', 10)) }); engine.script = [ { frames: frames(node('emit', 8), app('main', 10)) }, @@ -1607,84 +1627,43 @@ describe('JsStepper (issue #1130)', () => { expect(stopped()).toMatchObject({ reason: 'step' }); }); - it('sets none below Node\'s own async code: its header is read like any other', async () => { - sourceWith({ [fnLineOf(node('readFile', 0))]: 'async function readFile(path, options) {' }, 'node:internal'); - const top: Frame = { ...node('readFile', 7), fnCol: 23 }; - engine.pauseAt({ frames: frames(app('callback', 40), top, app('main', 10)) }); - engine.script = [ - { frames: frames({ ...top, line: 8 }, app('main', 10)) }, - { frames: frames(app('main', 11)) } - ]; - await stepper.request('next', { threadId: 1 }); + it('sets none when V8 does not say whether a frame can be restarted', async () => { + engine.pauseAt({ frames: frames(lossy(app('leaf', 5)), app('caller', 14)), noRestartInfo: true }); + engine.script = [{ frames: frames(app('caller', 15)), noRestartInfo: true }]; + await stepper.request('stepOut', { threadId: 1 }); await settled(); expect(setBreakpoints()).toBe(0); - expect(commands()).toEqual(['Debugger.stepOver', 'Debugger.stepOut']); }); - }); - describe('rule (b): the frame guarded must still be on the stack when it reaches a net position', () => { - /** `handler` at line 14, written as an async function or a plain one, calling the function being left. */ - async function stepOutInto(header: string, statement: string): Promise { - // The caller is paused at its call of `inner`, as V8 reports it. - const handler = app('handler', 14, { fnCol: header.indexOf('('), col: Math.max(0, statement.indexOf('inner(')) }); - sourceWith({ [fnLineOf(handler)]: header, 14: statement }); - engine.pauseAt({ frames: frames(lossy(app('innerSync', 30)), handler) }); - engine.script = [{ frames: frames({ ...handler, line: 15 }) }]; + it.each([ + ['a comment that says await', '// nothing to await here'], + ['a nested async callback', 'items.map(async (item) => { await send(item); });'], + ['a loop', 'for (const item of items) { use(item); }'] + ])('nets a plain function whatever its text says: %s', async (_what, text) => { + const start = fnLineOf(app('plainWith', 0)); + sourceWith({ [start + 1]: text, [start + 4]: 'try { return x(); } finally { done(); }' }); + engine.pauseAt({ frames: frames(app('plainWith', start + 2), app('caller', 14)) }); + engine.script = [{ frames: frames(app('caller', 15)), reason: 'other', hits: (armed) => [armed[0].id] }]; await stepper.request('stepOut', { threadId: 1 }); await settled(); - } - - it('reads the statement the call is in, not the one before it on the same line', async () => { - await stepOutInto('async function handler(id) {', 'await ready; const got = inner(id);'); expect(setBreakpoints()).toBeGreaterThan(0); - }); - - it('nets a plain caller even where its statement cannot be read with confidence: a plain frame cannot suspend', async () => { - await stepOutInto('function handler(id) {', 'const got = log(`${inner(id)}`);'); - expect(setBreakpoints()).toBeGreaterThan(0); - }); - - it('nets a caller whose header cannot be read when its statement cannot suspend either way', async () => { - await stepOutInto('async [`k${1}`](id) {', 'const got = inner(id);'); - expect(setBreakpoints()).toBeGreaterThan(0); - }); - - it('sets none below a function being left whose header cannot be read: it might suspend', async () => { - const header = ' [`k${1}`](x) {'; - const top = app('unreadable', 30, { fnCol: header.indexOf('(') }); - sourceWith({ [fnLineOf(top)]: header, [fnLineOf(top) + 5]: '} finally { done(); }' }); - engine.pauseAt({ frames: frames(top, app('caller', 14)) }); - engine.script = [{ frames: frames(app('caller', 15)) }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBe(0); - }); - - it('sets none when the caller is an async generator returning the call: its return awaits', async () => { - await stepOutInto('async *handler(id) {', 'return inner(id);'); - expect(setBreakpoints()).toBe(0); - }); - - it('sets none when an async caller awaits the call: it leaves the stack at once, and another call can take its depth', async () => { - await stepOutInto('async function handler(id) {', 'const got = await inner(id);'); - expect(setBreakpoints()).toBe(0); expect(stopped()).toMatchObject({ reason: 'step' }); - }); - - it('sets none when the await stands elsewhere in the calling statement', async () => { - await stepOutInto('async function handler(id) {', 'use(inner(id), await other(id));'); - expect(setBreakpoints()).toBe(0); - }); - - it('nets an async caller whose statement awaits nothing: it reaches its next position before it can suspend', async () => { - await stepOutInto('async function handler(id) {', 'const got = inner(id);'); - expect(setBreakpoints()).toBeGreaterThan(0); expect(stopped().text).toBeUndefined(); + expect(engine.armed).toEqual([]); }); - it('nets a plain caller whatever its statement says', async () => { - await stepOutInto('function handler(id) {', 'const got = wait(inner(id)); // await it later'); + it.each([ + ['a return out of for...of', 'for (const item of items) { if (item) return item; }'], + ['a using declaration', 'using handle = open();'] + ])('nets the exits V8 loses with no finally written: %s', async (_what, text) => { + const start = fnLineOf(app('implicit', 0)); + sourceWith({ [start + 3]: text }); + engine.pauseAt({ frames: frames(app('implicit', start + 2), app('caller', 14)) }); + engine.script = [{ frames: frames(app('caller', 15)), reason: 'other', hits: (armed) => [armed[0].id] }]; + await stepper.request('stepOut', { threadId: 1 }); + await settled(); expect(setBreakpoints()).toBeGreaterThan(0); + expect(stopped()).toMatchObject({ reason: 'step' }); }); }); From 83b424fc9fbbbb6b36908807ba40b461785f98ea Mon Sep 17 00:00:00 2001 From: JF Date: Tue, 17 Nov 2026 22:37:08 -0500 Subject: [PATCH 16/24] fix(javascript): the stepper leaves the steps V8 loses to V8; no temporary breakpoints (#1130, #1161, #1174) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Six reviews each found a wrong landing in the rescue for a step that leaves a function through `return` inside `try…finally`: a breakpoint hit in the caller cannot be told from a hit in a later call of the caller. The rescue goes. A step V8 loses stays lost, the answer says the program ran on or ended, and the docs give the workaround (a breakpoint where execution should come back, then continue_execution). - src/proxy/js-stepper.ts: the nets, the net branch of the verdict and their bookkeeping are removed. The walk through skipped code, the return target and the re-issue cap stay. - The pending sentence, the tool reference, the JavaScript README and KNOWN_ISSUES say what is lost, on which Node versions, and where the fix is (V8 issue 569814973, tracked here as #1173). - Measured without the rescue: a step_into on a `require` line is lost (Node's loader returns through try…finally). The docs and the changelog fragment said it lands; corrected. On a `require` of a built-in module this is worse than 0.26.0, which stops three lines late. - Tests: the net cases leave the unit file. The integration file accepts a fixed runtime or today's for each step V8 loses, and names V8's stop in the next call of the function for a step_over off a finally block. - changelog.d/1161.fixed.md is removed: #1161 is not fixed here. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn69pXrYMWc1JUwv5v8 --- changelog.d/1130.fixed.md | 2 +- changelog.d/1161.fixed.md | 1 - docs/KNOWN_ISSUES.md | 17 + docs/javascript/README.md | 65 +- docs/tool-reference.md | 27 +- .../src/interfaces/adapter-policy-js.ts | 6 +- src/proxy/js-stepper.ts | 427 +--------- src/session/execution/execution-controller.ts | 2 +- .../javascript-step-skipped-code.test.ts | 124 ++- .../javascript/step-skipped-code/steps.cjs | 5 +- tests/proxy/js-stepper.test.ts | 757 ++---------------- 11 files changed, 274 insertions(+), 1159 deletions(-) delete mode 100644 changelog.d/1161.fixed.md diff --git a/changelog.d/1130.fixed.md b/changelog.d/1130.fixed.md index ac9137293..6012052a8 100644 --- a/changelog.d/1130.fixed.md +++ b/changelog.d/1130.fixed.md @@ -1 +1 @@ -**A JavaScript step lands where your code next runs, and is no longer lost in Node's own code.** `step_into` on a line that calls a Node builtin took about 6 s on a Linux host and answered `pending`, blaming "a long-running call"; on the first `console.log` of a process it never landed at all and the program ran to its end. js-debug's own "smart stepper" was deciding where such a step ends: while the step was in skipped code it stepped again by itself, one engine step per statement (131 for one `console.log`), with a flag that moves the step to a later task and loses it. That stepper is now off for every session, and the server steps through skipped code itself, over js-debug's raw CDP socket, for `step_into`, `step_over` and `step_out` alike. A `step_into` on a line that calls your own function through skipped code (an event listener behind `emitter.emit`, an array callback, a route handler from inside express) lands in that function; on a line whose call stays in skipped code for the whole walk (`console.log`, a `require`) it lands on the next line and the message says how far the walk went (`Stepped into. step_into walked 25 engine steps into the call on that line and was still in skipped code …`) and that code of yours the call runs further in or only schedules does not stop the step; on a line that only starts a later task (`setTimeout`) it lands on the next line instead of inside the callback some time later. A `step_over` or `step_out` that returns into skipped code steps out to the nearest frame of your program below; when nothing of your program called or awaits the function (the last line of a request handler, a timer callback, a `.then` callback) the program is resumed rather than walked through the internals of later tasks (a callback of yours already queued behind a `.then` callback is where V8's own step stops), and on a launch the pending answer says the step left its frame. What counts as skipped is still js-debug's own verdict, so `justMyCode`, your `skipFiles` and source maps decide it as before, and `justMyCode: false` (or `smartStep: false`) still lands every step where V8 lands. A forked child steps the way its root session does, launched or attached. Changed on purpose: a pause asked for while a step is still pending is reported as the pause, where the program is, and is not stepped away from; and the sentence a pending step carries no longer mentions js-debug's stepper. On Linux every engine step costs about 46 ms whoever sends it (#1163), so a `step_into` on a `console.log` line still takes over a second there. (#1130) +**A JavaScript step lands where your code next runs, and is no longer lost in Node's own code.** `step_into` on a line that calls a Node builtin took about 6 s on a Linux host and answered `pending`, blaming "a long-running call"; on the first `console.log` of a process it never landed at all and the program ran to its end. js-debug's own "smart stepper" was deciding where such a step ends: while the step was in skipped code it stepped again by itself, one engine step per statement (131 for one `console.log`), with a flag that moves the step to a later task and loses it. That stepper is now off for every session, and the server steps through skipped code itself, over js-debug's raw CDP socket, for `step_into`, `step_over` and `step_out` alike. A `step_into` on a line that calls your own function through skipped code (an event listener behind `emitter.emit`, an array callback, a route handler from inside express) lands in that function; on a line whose call stays in skipped code for the whole walk (`console.log`) it lands on the next line and the message says how far the walk went (`Stepped into. step_into walked 25 engine steps into the call on that line and was still in skipped code …`) and that code of yours the call runs further in or only schedules does not stop the step; on a line that only starts a later task (`setTimeout`) it lands on the next line instead of inside the callback some time later. A `step_over` or `step_out` that returns into skipped code steps out to the nearest frame of your program below; when nothing of your program called or awaits the function (the last line of a request handler, a timer callback, a `.then` callback) the program is resumed rather than walked through the internals of later tasks (a callback of yours already queued behind a `.then` callback is where V8's own step stops), and on a launch the pending answer says the step left its frame. What counts as skipped is still js-debug's own verdict, so `justMyCode`, your `skipFiles` and source maps decide it as before, and `justMyCode: false` (or `smartStep: false`) still lands every step where V8 lands. A forked child steps the way its root session does, launched or attached. Changed on purpose: a pause asked for while a step is still pending is reported as the pause, where the program is, and is not stepped away from; and the sentence a pending step carries no longer mentions js-debug's stepper. On Linux every engine step costs about 46 ms whoever sends it (#1163), so a `step_into` on a `console.log` line still takes over a second there. Not fixed here: a `step_into` on a `require` line is still lost (Node's loader returns through `try … finally`, one of the steps V8 itself loses, #1161); `step_over` on such a line lands on the next one. (#1130) diff --git a/changelog.d/1161.fixed.md b/changelog.d/1161.fixed.md deleted file mode 100644 index ed599689e..000000000 --- a/changelog.d/1161.fixed.md +++ /dev/null @@ -1 +0,0 @@ -**A JavaScript step out of a function that returns inside `try … finally` lands in the caller.** V8 loses such a step (measured on V8 12.4, 13.6 and 14.6 with a bare CDP client; also a `return` out of a `for … of` loop and out of a function with a `using` declaration): a `step_out` of the function and a `step_over` off its `finally` block answered `Step completed as session exited.` while the program ran on. Node's own module loader returns that way too, which is how a `step_into` on a `require` line was lost. The server now sets temporary breakpoints on the frame such a step returns to, and whichever pauses first is the landing. That is something the server does in your process: a temporary breakpoint on every break location of the frame the step returns to (a function with more than 100 is not guarded), for the length of one step, removed when the step ends however it ends. The step then lands at the caller's next break location after the call. The breakpoints are set only where a hit proves the step came back, and V8 decides that rather than the server reading your code: V8 says the frame the step returns to could be restarted, which it says of no `async` function, generator or module code that may await, nor of any frame below one, so that frame and every frame above it come down only by returning. A step that leaves or returns into an `async` function or a generator is not rescued: a breakpoint there cannot tell a function returning from one pausing at an `await`, so that step stays lost as before (#1174): it answers `pending: true` with a sentence naming the case while the program keeps running, and `Step completed as session exited.` when it ends first. Not covered either: a `step_over` across the first load of a module that has a breakpoint in it (#1162). (#1161) diff --git a/docs/KNOWN_ISSUES.md b/docs/KNOWN_ISSUES.md index 670a02c9a..81f81dd7a 100644 --- a/docs/KNOWN_ISSUES.md +++ b/docs/KNOWN_ISSUES.md @@ -86,6 +86,23 @@ pause on raised exceptions in Ruby — it will also stop on caught ones. (Attach sessions never apply a language default; their `breakOnExceptions` default is `"none"` for every language.) +## JavaScript: a step that leaves a function through `finally` is lost + +V8 loses a step that leaves a function through a `return` that runs a `finally` first: a +`return` inside `try … finally`, a `return` out of a `for … of` loop, a function with a +`using` declaration, and every async generator (#1161; in `async` functions and generators, +#1174). That is a `step_out` of such a function, or a `step_over` / `step_into` off its last +statement; a step that crosses an `await` first is not lost. Measured on Node 22.23.2, 24.14.1 +and 26.9.0 (Node 16.3.0 lands these steps, 16.4.0 and later do not). The step either never +lands, and the program runs on or ends (`pending: true`, or `Step completed as session +exited.`), or, for a `step_over` off the end of a `finally` block, can stop in the next call +of the same function instead of the caller. mcp-debugger does not rescue these steps. + +Workaround: set a breakpoint on the line where you expect execution to come back, then +`continue_execution`. The fix is in V8: V8 issue 569814973 has one in review (tracked here as +#1173), and it reaches you only through a Node release. See the +[JavaScript guide](./javascript/README.md). + ## Dart/Flutter: what the SDK debug adapter does differently The Dart adapter drives the SDK's own `dart debug_adapter` / `flutter debug-adapter`, so diff --git a/docs/javascript/README.md b/docs/javascript/README.md index e714b0f53..5a09e0eab 100644 --- a/docs/javascript/README.md +++ b/docs/javascript/README.md @@ -115,7 +115,8 @@ What a step does when the session steps through skipped code (the launch default | Step | From | Lands | |---|---|---| | `step_into` | a line that calls your function through skipped code (`emitter.emit` to a listener, an array callback, a route handler from inside express) | in that function | -| `step_into` | a line whose call stays in skipped code for the whole walk (`console.log`, a `require`, `setTimeout`) | on the next line. The message says how many engine steps the walk took, and that code of yours the call runs further in (the module a `require` loads) or only schedules (a timer callback) does not stop the step | +| `step_into` | a line whose call stays in skipped code for the whole walk (`console.log`, `setTimeout`) | on the next line. The message says how many engine steps the walk took, and that code of yours the call runs further in or only schedules (a timer callback) does not stop the step | +| `step_into` | a `require` line | nowhere on today's Node versions: the step is lost and the program runs on. Node's loader returns through `try … finally`, so stepping back out of it is one of the steps V8 loses (issue #1161, below). Use `step_over` on a `require` line (it lands on the next line), or set a breakpoint in the module | | `step_into` | a line that calls native code only (`JSON.stringify`) | on the next line, as a plain `Stepped into`: there is nothing to walk into | | `step_into` | a line that only starts a later task (`setTimeout`, a `.then` callback) | on the next line, never in the callback some time later; a breakpoint in the callback stops there | | `step_over`, `step_out` | a frame whose caller is skipped code, with your code further down the stack | in that frame of yours | @@ -144,45 +145,29 @@ derived value. Attach defaults `smartStep` to `false` and leaves `skipFiles` uns `console.log` line stops in ``, and an `async` callee in TypeScript compiled for a target below ES2017 costs four unmapped `__awaiter` stops before its first line (issue #687). -**Steps V8 itself loses** (issue #1161). V8 loses a step that leaves a function through a `return` that runs a -`finally` first (measured on V8 12.4, 13.6 and 14.6 with a bare CDP client): a `step_out` of such a function, or a -`step_over` off its last statement, used to answer `Step completed as session exited.` A `return` out of a -`for … of` loop and out of a function with a `using` declaration close the same way. Node's own module loader has -that shape, which is how a `step_into` on a `require` line was lost too. (The cause is in V8: the return replayed -after the `finally` block carries no source position, so it is not a place a step can stop; issue #1173.) - -So where a step can be lost that way, the server sets temporary breakpoints on every break location of the frame -the step returns to, and whichever pauses first is the landing: the caller's next break location after the call -(the next statement, or the next call in the same statement; V8's own step-out, where it does not lose the step, -can stop once more on the call's own line first). That is something the server does in your process: a breakpoint -on each break location of one function, for the length of one step, removed when the step ends, however it ends. -A function with more than 100 break locations is not guarded, and where the breakpoints cannot be set the step -goes on with V8 alone. - -They are set only where a hit there proves the step came back, and V8 decides that, not the server reading -your code: - -- **The frame the step returns to, and every frame above it, are plain functions**: V8 says it could restart that - frame, which it says of no `async` function, generator or module code that may await, nor of any frame below one - (checked on Node 22, 24 and 26 over every way of writing a function). A plain function comes down only by - returning, so control back in that frame means the step came back, in the same call. A function that can suspend - at an `await` or `yield` hands control down without returning, and a breakpoint below it would stop the step in - the caller while it is still on its way, or in another call of the same function. -- **Every break location of that frame, or none**: a breakpoint on part of a function can miss the place control - comes back to (a loop's top, the code after a long `else`) and stop later, in another iteration or another call. - A function with more than 100 break locations, or whose locations cannot all be found, is not guarded. -- **Never on the frame being stepped in**: a function that returns to itself (recursion) gets none for `step_over` - and `step_into`. - -What that leaves lost, as in 0.26.0: a step V8 loses while leaving an `async` function or a generator, and one that -leaves a plain function back into an `async` function or a generator (a helper with a `try … finally`, or a -`require`, called from an `async` function). Such a step runs on: while the program keeps running it answers -`pending: true`, with a sentence that names these cases; when the program ends first it answers `Step completed as -session exited.` A breakpoint on the line you expected the step to reach stops there (issue #1174). - -Not covered: a `step_over` across the first load of a module that has a breakpoint in it still runs on (issue -#1162; js-debug pauses at the module's entry to bind the breakpoint, and V8 drops the step at any pause). A -`step_into` on that line does land. +**Steps V8 itself loses** (issue #1161; in `async` functions and generators, issue #1174). V8 loses a step that +leaves a function through a `return` that runs a `finally` first: a `return` inside `try … finally`, a `return` out +of a `for … of` loop, a function with a `using` declaration, and every async generator. The steps lost are a +`step_out` of such a function, and a `step_over` or `step_into` off its last statement. Measured on Node 22.23.2, +24.14.1 and 26.9.0; Node 16.3.0 lands these steps, 16.4.0 and later do not. A step that crosses an `await` first +is not lost. + +Such a step shows one of two symptoms: + +- It never lands, and the program runs on or ends: the step answers `pending: true` while the program keeps + running, or `Step completed as session exited.` when it ends first. +- A `step_over` off the end of a `finally` block can instead stop in the next call of the same function, not in + the caller. Check the stack before you take that stop for the caller. + +The server does not rescue these steps and sets no temporary breakpoints for them: a breakpoint hit in the caller +cannot be told from a hit in a later call of the caller, so the step is V8's own. To get past such a return, set a +breakpoint on the line where you expect execution to come back, then `continue_execution`. The fix belongs in V8: +V8 issue 569814973 has a fix in review (tracked here as issue #1173), and it reaches you only through a Node +release. + +A different loss, in js-debug: a `step_over` across the first load of a module that has a breakpoint in it runs on +(issue #1162). js-debug pauses at the module's entry to bind the breakpoint and resumes that pause itself while the +step is in flight, and the step is lost with it. On Linux every engine step costs about 46 ms whoever sends it (the inspector's socket; issue #1163), against 1.5 ms on Windows, so a `step_into` on a `console.log` line, which walks 25 engine steps into Node's code and a few back diff --git a/docs/tool-reference.md b/docs/tool-reference.md index a7beaaaf7..ec98940ec 100644 --- a/docs/tool-reference.md +++ b/docs/tool-reference.md @@ -707,9 +707,10 @@ The adapter may append one sentence to that message saying what the step is wait does so for a launch that steps through skipped code (issues #678, #1130): a step issued from skipped code names the frame and says a step does not stop there, and any other pending step says it left the frame it started in and has not stopped in your program since (a function Node called returned to the event loop, the line is -waiting on work in flight, or the engine lost the step: V8 loses one that leaves a function through `try … -finally`, a `for … of` loop or a `using` declaration, and the server rescues it only when it returns into a plain -function). An attach that steps through skipped code (`smartStep: true`) gets no such sentence. +waiting on work in flight, or the engine lost the step: V8 loses one that leaves a function through a `return` +inside `try … finally`, out of a `for … of` loop, or from a function with a `using` declaration, issue #1161), and +says to set a breakpoint where you expect execution to come back. An attach that steps through skipped code +(`smartStep: true`) gets no such sentence. So match a pending step by its `pending: true` flag, not by the message text. Once a stop has been observed, the stop path owns the answer — a step that demonstrably landed is never reported as pending afterwards, at the cost of the response then being bounded by the stack-trace round trip rather than by the ~5s window. If the debuggee ends while the step is in flight the result is still a success, with a terminal `state` and a message such as `"Step completed as session terminated."`. @@ -747,8 +748,10 @@ Same ~5s wait and `pending: true` contract as step_over — see [Pending steps]( so it stepped back out and the rest of the line ran as a step over runs it. Code of yours that the call runs further in (a module it loads) or only schedules (a timer or promise callback) does not stop the step: a breakpoint there stops in it. To stop inside the skipped code instead, turn stepping through it off: - justMyCode: false on a launch, smartStep: false on a launch or an attach.` A `console.log`, a `require` and a - `setTimeout` line answer this way. + justMyCode: false on a launch, smartStep: false on a launch or an attach.` A `console.log` and a `setTimeout` line + answer this way. A `require` line does not: Node's loader returns through `try … finally`, so a `step_into` on + it is one of the steps V8 loses (issue #1161) and the program runs on. Use `step_over` on a `require` line, or + a breakpoint in the module. - A line that calls native code only (`JSON.stringify`) has nothing to walk into: a plain `Stepped into` on the next line. - A call that only starts a later task (`setTimeout`, a `.then` callback) is not followed: the step lands on the @@ -781,14 +784,12 @@ Same ~5s wait and `pending: true` contract as step_over — see [Pending steps]( - Out of an `async` function the event loop resumed, the step lands in the function that awaits it, in the call that awaited: that is the engine's own step. -- The engine loses a step that leaves a function through `try … finally` (also a `return` out of `for … of`, - and a function with a `using` declaration). When the step returns into a plain function, the server catches it - with a temporary breakpoint on every break location of that function, so the step lands at its next one: the - next statement, or the next call in the same statement. When it leaves or returns into an `async` function or a - generator (or a function with more than 100 break locations), it does not: a breakpoint there cannot tell a - function returning from one pausing at an `await`. Such a step stays lost, as in 0.26.0, and answers - `pending: true`, or `Step completed as session exited.` when the program ends first; a breakpoint on the line - you expected it to reach stops there (issue #1174). +- The engine loses a step that leaves a function through a `return` that runs a `finally` first: a `return` + inside `try … finally`, a `return` out of `for … of`, a function with a `using` declaration, and every async + generator (issues #1161, #1174). The server does not rescue it and sets no temporary breakpoint: the step answers + `pending: true`, or `Step completed as session exited.` when the program ends first, and a `step_over` off the + end of a `finally` block can stop in the next call of the same function instead of the caller. Set a breakpoint + on the line where you expect execution to come back, then `continue_execution`. - Out of a function that nothing of your program called or awaits (a timer callback, a `.then` callback, a request handler) there is nowhere of its own to land: the program is resumed, and the answer is the next stop or `pending: true`. diff --git a/packages/shared/src/interfaces/adapter-policy-js.ts b/packages/shared/src/interfaces/adapter-policy-js.ts index cea50606c..981e9c257 100644 --- a/packages/shared/src/interfaces/adapter-policy-js.ts +++ b/packages/shared/src/interfaces/adapter-policy-js.ts @@ -451,9 +451,9 @@ export const JsDebugAdapterPolicy = { } return 'The step left the frame it started in and has not stopped in your program since: a function that Node ' + 'called returned to the event loop, the line is waiting on work still in flight, or the engine lost the step ' + - '(V8 loses one that leaves a function through try...finally, a for...of loop or a using declaration, and the ' + - 'server rescues it only when it returns into a plain function, not into an async function or a generator; ' + - 'a breakpoint on the line you expected it to reach stops there). The program is running; ' + + '(when the function left returns from inside try...finally, or out of a for...of loop, or declares using, ' + + 'V8 loses the step, issue #1161; set a breakpoint where you expect execution to come back and continue). ' + + 'The program is running; ' + 'wait_for_stop answers when the step lands, a breakpoint is hit, or the program ends.'; }, diff --git a/src/proxy/js-stepper.ts b/src/proxy/js-stepper.ts index 46b6f10b6..c23578896 100644 --- a/src/proxy/js-stepper.ts +++ b/src/proxy/js-stepper.ts @@ -23,62 +23,17 @@ * maps. js-debug's `stopped` for the pause is never waited for: it is sent * a timer tick later, which costs 12 ms a landing on Windows. * - * NETS. V8 loses a step in two measured ways: when a frame is left through - * a `return` that runs a `finally` first, within the run the step began in - * (issue #1161: the replayed Return bytecode has no source position, so it - * is not a break location, and V8's step-out floods return locations only; - * a `return` out of for...of and a `using` declaration close the same - * way), and when js-debug resumes a pause of its own, a module-entry - * breakpoint, while the step is in flight (issue #1162). A net is a capped - * set of temporary CDP breakpoints on the break positions of the frame a - * step returns to, kept with the stack depth of the activation it guards. - * Any position there is where V8's own step-out would stop, so a hit at - * that depth is a landing. - * - * A NET IS SET ONLY WHERE A HIT PROVES THE STEP CAME BACK. Five versions - * of the rule that decided where read the program's source to tell a - * function that returns from one that suspends at an `await` or `yield`, - * and each was fooled by some way of writing JavaScript. V8 knows, and - * says so on every frame of a pause: `canBeRestarted` is false for an - * async function, a generator and module code that may await, and for - * every frame below one (measured on Node 22, 24 and 26 over every - * function form). So, in one place, before every command that can leave - * the frame on top (`guard`): - * - * (a) The frame guarded, the nearest frame of the program below, can be - * restarted. Then it and every frame above it are plain functions: - * each comes down only by returning, so control back in the guarded - * frame means the step came back, and the guarded frame stays on the - * stack until it reaches a net position. A frame that cannot be - * restarted is not netted: a step that leaves through an async - * function or a generator, or returns to one, is V8's own, and what - * V8 loses there stays lost (issue #1174). To spare breakpoints, a - * function being left whose text names nothing that closes through - * a finally (`finally`, `for...of`, `using`) is not netted either; - * that test only ever errs toward netting. - * - * (b) The net covers every break position of the frame it guards, or - * there is none: a hit is then the first position control reaches - * in that activation. A function with more than `netSize` positions, - * or whose positions cannot all be found, is not netted, and when - * V8 refuses one of them none is kept. A rescue lands at the - * caller's next break location after the call; V8's own step-out, - * when it does not lose the step, can stop once more on the call's - * own line. - * - * Nothing is ever guarded that is not on the stack (no net on an awaiting - * function), and nothing is decided on a pause's reason, which does not - * say whether V8 had lost the step. - * - * A net is a safeguard, never a condition: when one cannot be set the step - * goes on with V8 alone. - * - * No net is put on the frame being stepped IN. V8 says `ambiguous` for any - * breakpoint hit while a step is in flight, and it exposes no statement - * boundaries, so a hit on a later position of the same statement (the - * second argument of a multi-line call) cannot be told from the next - * statement. In-frame stepping stays V8's own. That is why a plain - * `step_over` across issue #1162's module load is not recovered here. + * STEPS V8 LOSES STAY LOST. V8 loses a step that leaves a function + * through a `return` that runs a `finally` first: a `return` inside + * try...finally, a `return` out of for...of, a function with a `using` + * declaration, every async generator (issue #1161; V8 issue 569814973). + * js-debug resuming its own module-entry pause while a step is in flight + * loses one too (issue #1162). The stepper does not rescue these: the + * step is V8's own, and the program runs on (or, for a `step_over` off the + * end of a `finally` block, V8 can stop in the next call of the same + * function). There is no rescue because a breakpoint hit in the caller + * cannot be told from a hit in a later call of the caller: CDP names no + * single activation. * * Skipped code on top: `step_into` repeats up to a budget (that is how a * call through Node's own code reaches a callback of the program's), then @@ -98,10 +53,8 @@ * js-debug's `stopped` and `continued` events are withheld by count: it * sends one `stopped` per pause it keeps, out of order with the * `continued` of the next resume. The last one is forwarded: as reason - * `step` on a landing (it arrives as `pause` or `breakpoint`), unchanged on - * a real stop. - * - * Every ender removes every net. + * `step` on a landing (it arrives as `pause`, or `step`), unchanged on a + * real stop. */ import type { DebugProtocol } from '@vscode/debugprotocol'; import { createLogger } from '../utils/logger.js'; @@ -128,15 +81,7 @@ export interface JsStepperTunables { budget: number; /** CDP step commands in one chain, all told. */ commandCap: number; - /** - * The most break positions a net may have. A net covers every position of - * the function it guards, or the function is not netted: a net on part of - * it can miss the position control comes back to (a loop's back edge, the - * code after a long else) and fire later, in another iteration or another - * call. A breakpoint is slow to set in a big function (1000 took 2.4 s). - */ - netSize: number; - /** Re-issued commands on a net position that is not a landing (recursion; the origin statement). */ + /** Re-issued step-ins when a step-in lands back on the statement it started from. */ reissueCap: number; /** How long a finished chain waits for js-debug's `stopped` events before it reports without them. */ settleCeilingMs: number; @@ -147,7 +92,6 @@ export interface JsStepperTunables { export const DEFAULT_JS_STEPPER_TUNABLES: JsStepperTunables = { budget: 24, commandCap: 128, - netSize: 100, reissueCap: 24, settleCeilingMs: 2000, verdictCeilingMs: 2000 @@ -167,10 +111,10 @@ export type StepKind = 'in' | 'over' | 'out'; const STEP_OF_COMMAND: Record = { stepIn: 'in', next: 'over', stepOut: 'out' }; const CDP_COMMAND: Record = { in: 'Debugger.stepInto', over: 'Debugger.stepOver', out: 'Debugger.stepOut' }; -/** Requests that resume or end the target: a chain still waiting on a net must give it up first. */ +/** Requests that resume or end the target: a chain still in flight must give it up first. */ const CHAIN_ENDING_REQUESTS = new Set(['continue', 'disconnect', 'terminate', 'restart', 'goto', 'reverseContinue', 'restartFrame']); -/** What ends a chain as a real stop when the pause carries no breakpoint of ours. */ +/** The reasons of a pause that is the step's own, when it hits no breakpoint; any other reason is a real stop. */ const STEP_REASONS = new Set(['step', 'ambiguous']); interface CdpLocation { @@ -179,19 +123,10 @@ interface CdpLocation { columnNumber?: number; } -interface CdpBreakLocation extends CdpLocation { - type?: string; -} - interface CdpCallFrame { functionName?: string; functionLocation?: CdpLocation; location: CdpLocation; - /** - * V8's word on restarting the frame: false for an async function, a - * generator, module code that may await, and every frame below one. - */ - canBeRestarted?: boolean; } interface CdpAsyncFrame { @@ -215,16 +150,6 @@ interface CdpAsyncTrace { parent?: CdpAsyncTrace; } -interface Net { - /** What it guards, for the log. */ - name: string; - /** Function identity, or the async parent's position. */ - fn: string; - /** The stack depth of the guarded activation. */ - depth: number; - ids: Set; -} - type Inbox = | { type: 'paused'; pause: CdpPaused } | { type: 'resumed' }; @@ -246,9 +171,6 @@ const MAX_MARKED_FRAMES = 200; /** How far past the sync frames js-debug is asked: the labels of the async segments and the awaiter's frame. */ const ASYNC_MARKS = 12; -/** What closes through a finally, written or implied: the exits V8 loses a step on (issue #1161). */ -const CLOSES_THROUGH_FINALLY = /\b(finally|using|of)\b/; - interface Chain { kind: StepKind; threadId: number | undefined; @@ -266,27 +188,20 @@ interface Chain { commands: string[]; spent: number; reissues: number; - /** A net fired in recursion and was dropped: V8's own step-outs finish, to the origin depth. */ - unwinding: boolean; /** Step-ins a step-in had sent when it gave up on the skipped code and stepped out; 0 if it never did. */ walkedBeforeSteppingOut: number; /** Every command the chain may send is spent and skipped code is still on top. */ capped: boolean; - /** A step-in's walk found nothing of the program below the skipped code: not looked at again while it walks. */ - walkHasNothingBelow: boolean; /** The caller asked for a pause during the chain: the next stop is theirs. */ pauseRequested: boolean; /** That pause was taken on no breakpoint of js-debug's: it is reported as the pause it is. */ pauseTaken: boolean; - /** Whether any pause the chain kept was a net's: what a late report of it looks like. */ - netHits: boolean; startedAt: number; } type Verdict = | { kind: 'wait' } - /** `skipped`: the frame the command steps from is skipped code. */ - | { kind: 'command'; command: string; skipped: boolean } + | { kind: 'command'; command: string } | { kind: 'landing'; by: string } | { kind: 'real-stop' } | { kind: 'left-stack' }; @@ -296,10 +211,6 @@ function fnKey(frame: CdpCallFrame): string { return `${l.scriptId}:${l.lineNumber}:${l.columnNumber ?? 0}`; } -function sameOrAfter(a: CdpLocation, b: CdpLocation): boolean { - return a.lineNumber > b.lineNumber || (a.lineNumber === b.lineNumber && (a.columnNumber ?? 0) >= (b.columnNumber ?? 0)); -} - function errorText(err: unknown): string { return err instanceof Error ? err.message : String(err); } @@ -327,19 +238,13 @@ export class JsStepper { /** The pause V8 is in now, as CDP reported it; null while running. */ private current: CdpPaused | null = null; private chain: Chain | null = null; - private nets: Net[] = []; /** `stopped` events of a finished chain still on their way; dropped when they arrive, until the deadline. */ private owed = 0; private owedUntil = 0; - /** Whether an owed report can be a net's (`breakpoint`, naming none of js-debug's). */ - private owedNetHit = false; /** Scripts js-debug marked "Skipped by skipFiles": a script-level verdict, not asked again. */ private readonly skippedScripts = new Set(); - /** Whether a function's text names a construct that closes through a finally. */ - private readonly closing = new Map(); /** What each pause's top frame returns to: asked of js-debug once per pause. */ private readonly targets = new WeakMap(); - private readonly sources = new Map(); constructor(options: JsStepperOptions) { this.target = options.target; @@ -365,12 +270,11 @@ export class JsStepper { cdp.on('cdp-event', this.onCdpEvent); } - /** The socket is gone (the target ended): nothing can be removed any more. */ + /** The socket is gone (the target ended): a chain in flight is given up. */ detachCdp(): void { this.cdp?.off('cdp-event', this.onCdpEvent); this.cdp = null; this.current = null; - this.nets = []; this.owed = 0; const chain = this.chain; if (chain) { @@ -419,24 +323,21 @@ export class JsStepper { commands: [], spent: 0, reissues: 0, - unwinding: false, walkedBeforeSteppingOut: 0, capped: false, - walkHasNothingBelow: false, pauseRequested: false, pauseTaken: false, - netHits: false, startedAt: Date.now() }; this.chain = chain; this.owed = 0; try { - // The one rule, before the first command as before every other. - await this.guard(chain, origin, await this.isSkipped(chain, origin)); + // js-debug's mark on the frame the step starts from: a script it skips + // as a whole is then not asked about again at a landing. + await this.isSkipped(chain, origin); await this.sendStep(chain, CDP_COMMAND[kind]); } catch (err) { - await this.disarmAll(); this.chain = null; throw err; } @@ -446,7 +347,7 @@ export class JsStepper { /** * A request for the target that is not a step. One that resumes or ends - * the target ends a chain still waiting on a net, and removes the net first. + * the target ends a chain still in flight first. */ async beforeRequest(command: string): Promise { if (CHAIN_ENDING_REQUESTS.has(command)) { @@ -489,8 +390,8 @@ export class JsStepper { } /** For the log and the tests. */ - describe(): { enabled: boolean; chain: boolean; nets: number; owed: number; paused: boolean } { - return { enabled: this.enabled, chain: this.chain !== null, nets: this.nets.length, owed: this.owed, paused: this.current !== null }; + describe(): { enabled: boolean; chain: boolean; owed: number; paused: boolean } { + return { enabled: this.enabled, chain: this.chain !== null, owed: this.owed, paused: this.current !== null }; } // ----- CDP events ----- @@ -548,16 +449,6 @@ export class JsStepper { await this.finish(chain, 'real-stop'); return; } - await this.guard(chain, pause, verdict.skipped); - if (chain.cancelled) { - await this.finish(chain, 'cancelled'); - return; - } - if (chain.pauseRequested) { - chain.pauseTaken = true; - await this.finish(chain, 'real-stop'); - return; - } await this.sendStep(chain, verdict.command); continue; } @@ -616,16 +507,10 @@ export class JsStepper { } } - private netOf(id: string): Net | undefined { - return this.nets.find((net) => net.ids.has(id)); - } - private async judge(chain: Chain, pause: CdpPaused): Promise { - const hits = pause.hitBreakpoints ?? []; - const hitNets = [...new Set(hits.map((id) => this.netOf(id)).filter((net): net is Net => net !== undefined))]; - const foreignHit = hits.some((id) => !this.netOf(id)); - const ours = !chain.pauseRequested && !foreignHit && - (STEP_REASONS.has(pause.reason) || (pause.reason === 'other' && hitNets.length > 0)); + // Every breakpoint V8 reports is js-debug's: the stepper sets none. + const foreignHit = (pause.hitBreakpoints ?? []).length > 0; + const ours = !chain.pauseRequested && !foreignHit && STEP_REASONS.has(pause.reason); if (!ours) { // Another breakpoint, an exception, a pause the caller asked for: @@ -639,15 +524,12 @@ export class JsStepper { return { kind: 'real-stop' }; } chain.kept++; - if (hitNets.length > 0) { - chain.netHits = true; - } const top = pause.callFrames[0]; const depth = pause.callFrames.length; const skipped = await this.isSkipped(chain, pause); if (chain.cancelled) { - // Given up while js-debug was being asked: nothing more is armed or sent. + // Given up while js-debug was being asked: nothing more is sent. return { kind: 'wait' }; } @@ -657,64 +539,27 @@ export class JsStepper { // handler by calls, not returns (issue #687). if (chain.kind === 'in' && chain.spent < this.tunables.budget) { chain.spent++; - return { kind: 'command', command: CDP_COMMAND.in, skipped: true }; + return { kind: 'command', command: CDP_COMMAND.in }; } // It has to step out now. With nothing of the program below (no frame, // no awaiter), the stack the step started on is gone. - if (!this.guardedBelow(depth) && (await this.returnTarget(chain, pause)).kind === 'nothing') { + if ((await this.returnTarget(chain, pause)).kind === 'nothing') { return { kind: 'left-stack' }; } if (chain.kind === 'in' && chain.walkedBeforeSteppingOut === 0) { chain.walkedBeforeSteppingOut = chain.commands.filter((sent) => sent === CDP_COMMAND.in).length; } - return { kind: 'command', command: CDP_COMMAND.out, skipped: true }; + return { kind: 'command', command: CDP_COMMAND.out }; } - // Program code on top. - if (chain.unwinding) { - return depth > chain.originDepth - ? { kind: 'command', command: CDP_COMMAND.out, skipped: false } - : { kind: 'landing', by: 'V8 step-outs after a net was dropped (recursion)' }; - } + // Program code on top: V8's step landed. A step-in that is back on the + // line it left steps in again: that enters the line's next call, or moves on. const backOnOriginStatement = depth === chain.originDepth && fnKey(top) === chain.originFn && top.location.lineNumber === chain.originLine; - if (hits.length === 0) { - // V8's step landed. A step-in that is back on the line it left steps in - // again: that enters the line's next call, or moves on. - if (chain.kind === 'in' && backOnOriginStatement && chain.reissues < this.tunables.reissueCap) { - chain.reissues++; - return { kind: 'command', command: CDP_COMMAND.in, skipped: false }; - } - return { kind: 'landing', by: 'V8 step' }; - } - if (chain.kind === 'in' && depth > chain.originDepth) { - return { kind: 'landing', by: 'net, in a deeper frame of the program' }; - } - const guarding = hitNets.filter((net) => depth <= net.depth); - if (guarding.length === 0) { - if (chain.kind === 'out' && depth >= chain.originDepth && chain.reissues < this.tunables.reissueCap) { - // The frame being left is the same function as its caller (recursion) - // and is still running: step out again. - chain.reissues++; - return { kind: 'command', command: CDP_COMMAND.out, skipped: false }; - } - // The net fired in a deeper activation than the one it guards. Drop it; - // V8's own step-outs from here, until the depth is the origin's. - for (const net of hitNets) { - await this.disarm(net); - } - chain.unwinding = true; - if (depth <= chain.originDepth) { - return { kind: 'landing', by: 'net dropped (recursion)' }; - } - return { kind: 'command', command: CDP_COMMAND.out, skipped: false }; - } - // Control is back in a frame a net guards: where V8's own step-out would stop. if (chain.kind === 'in' && backOnOriginStatement && chain.reissues < this.tunables.reissueCap) { chain.reissues++; - return { kind: 'command', command: CDP_COMMAND.in, skipped: false }; + return { kind: 'command', command: CDP_COMMAND.in }; } - // The pause's reason does not say whether V8 had lost the step: it is logged, and nothing is decided on it. - return { kind: 'landing', by: `net (${pause.reason})` }; + return { kind: 'landing', by: 'V8 step' }; } /** @@ -800,7 +645,6 @@ export class JsStepper { const landed = this.current; const backInOriginFrame = landed !== null && landed.callFrames.length === chain.originDepth && fnKey(landed.callFrames[0]) === chain.originFn; - await this.disarmAll(); if (ender === 'left-stack') { // Nothing of the program is below: resume, and report nothing. try { @@ -830,7 +674,6 @@ export class JsStepper { if (missing > 0) { this.owed = missing; this.owedUntil = Date.now() + this.tunables.settleCeilingMs; - this.owedNetHit = chain.netHits; } const count = (name: string): number => chain.commands.filter((c) => c === name).length; logger.info( @@ -856,9 +699,8 @@ export class JsStepper { } }); } else if (ender === 'real-stop' && chain.pauseTaken) { - // The pause the caller asked for. js-debug may call it a breakpoint - // that names none (it was taken on a net's position), or may not have - // reported it yet: it leaves as the pause it is. + // The pause the caller asked for. js-debug may report it under another + // reason, or may not have reported it yet: it leaves as the pause it is. const body = { ...((chain.lastStopped?.body ?? {}) as Record) }; delete body.hitBreakpointIds; delete body.text; @@ -897,16 +739,12 @@ export class JsStepper { /** * Whether a `stopped` that arrives after a chain ended can be the late * report of one of that chain's own pauses: js-debug reports a step it did - * not request as `pause` (or `step`), and a net's position as a - * `breakpoint` that names none of its own. Anything else is somebody - * else's stop and goes on. + * not request as `pause` (or `step`). Anything else is somebody else's + * stop and goes on. */ private looksOwed(event: DebugProtocol.Event): boolean { - const body = (event.body ?? {}) as { reason?: string; hitBreakpointIds?: number[] }; - if (body.reason === 'pause' || body.reason === 'step') { - return true; - } - return this.owedNetHit && body.reason === 'breakpoint' && (body.hitBreakpointIds ?? []).length === 0; + const body = (event.body ?? {}) as { reason?: string }; + return body.reason === 'pause' || body.reason === 'step'; } private async abandonChain(why: string): Promise { @@ -916,189 +754,12 @@ export class JsStepper { } chain.cancelled = why; chain.wake?.(); - // The run loop ends the chain; the nets must be gone before the caller goes on. - await this.disarmAll(); + // The run loop ends the chain; the caller goes on without waiting for it. if (this.chain === chain) { this.chain = null; } } - // ----- nets ----- - - private async possible(start: CdpLocation): Promise { - const answer = await this.cdp?.send<{ locations?: CdpBreakLocation[] }>('Debugger.getPossibleBreakpoints', { - start: { scriptId: start.scriptId, lineNumber: start.lineNumber, columnNumber: start.columnNumber ?? 0 }, - restrictToFunction: true - }); - return answer?.locations ?? []; - } - - /** The break positions of the frame's function. */ - private async locationsOf(frame: CdpCallFrame): Promise { - const here = frame.location; - let start = frame.functionLocation; - // Top-level code whose first token is a function declaration: V8 answers - // the nested function's positions for the script's own position. The - // script's code goes on after that function, so ask again from just after - // its last position, until the answer holds the frame's position. Every - // position of the frame's function, or none: a part of it is not a net. - for (let tries = 0; start && tries < 16; tries++) { - const all = await this.possible(start); - if (all.length === 0) { - return []; - } - if (sameOrAfter(here, all[0]) && sameOrAfter(all[all.length - 1], here)) { - return all; - } - const last = all[all.length - 1]; - if (!sameOrAfter(here, last)) { - return []; - } - start = { scriptId: last.scriptId, lineNumber: last.lineNumber, columnNumber: (last.columnNumber ?? 0) + 1 }; - } - return []; - } - - /** A net on every one of `all`, the break positions of the function it guards. */ - private async arm(all: CdpBreakLocation[], net: Omit): Promise { - if (this.nets.some((existing) => existing.fn === net.fn && existing.depth === net.depth)) { - return true; - } - const cdp = this.cdp; - if (!cdp) { - return false; - } - const answers = await Promise.all( - all.map((location) => - cdp - .send<{ breakpointId?: string }>('Debugger.setBreakpoint', { - location: { scriptId: location.scriptId, lineNumber: location.lineNumber, columnNumber: location.columnNumber ?? 0 } - }) - .catch(() => undefined) - ) - ); - const ids = new Set(answers.map((answer) => answer?.breakpointId).filter((id): id is string => typeof id === 'string')); - if (ids.size < all.length) { - // A net with a hole is no net: remove what was set. - await Promise.all([...ids].map((breakpointId) => cdp.send('Debugger.removeBreakpoint', { breakpointId }).catch(() => undefined))); - return false; - } - this.nets.push({ ...net, ids }); - return true; - } - - private async disarm(net: Net): Promise { - this.nets = this.nets.filter((other) => other !== net); - const cdp = this.cdp; - if (!cdp) { - return; - } - await Promise.all([...net.ids].map((breakpointId) => cdp.send('Debugger.removeBreakpoint', { breakpointId }).catch(() => undefined))); - } - - private async disarmAll(): Promise { - for (const net of [...this.nets]) { - await this.disarm(net); - } - } - - private async linesOf(scriptId: string): Promise { - let lines = this.sources.get(scriptId); - if (!lines) { - const answer = await this.cdp?.send<{ scriptSource?: string }>('Debugger.getScriptSource', { scriptId }); - // V8 ends a line at CR LF, LF, CR, U+2028 and U+2029. - lines = (answer?.scriptSource ?? '').split(/\r\n|[\n\r\u2028\u2029]/); - this.sources.set(scriptId, lines); - } - return lines; - } - - /** - * Whether the function's text names a construct that closes through a - * finally, the only exits V8 loses a step on: `finally`, `for...of`, - * `using`. Only spares breakpoints where they cannot matter: a word in a - * comment nets a function that did not need it, and a text that cannot be - * read (V8 refuses the positions of Node's own start-up scripts) is netted. - */ - private async namesAFinally(frame: CdpCallFrame): Promise { - const key = fnKey(frame); - const known = this.closing.get(key); - if (known !== undefined) { - return known; - } - let names = true; - try { - const all = await this.locationsOf(frame); - if (all.length > 0) { - const lines = await this.linesOf(frame.location.scriptId); - const from = Math.min(frame.functionLocation?.lineNumber ?? all[0].lineNumber, all[0].lineNumber); - names = lines.slice(from, all[all.length - 1].lineNumber + 1).some((line) => CLOSES_THROUGH_FINALLY.test(line)); - } - } catch { - // Not readable: net it. - } - this.closing.set(key, names); - return names; - } - - /** Whether a net guards something below a pause of this depth. */ - private guardedBelow(depth: number): boolean { - return this.nets.some((net) => net.depth < depth); - } - - /** - * THE RULE (see the head of this file), applied before every command that - * can leave the frame on top of `pause`: a net on the frame it returns to, - * only where a hit there proves the step came back. Never throws: a net is - * a safeguard, and without one V8's own step goes on alone. - */ - private async guard(chain: Chain, pause: CdpPaused, skipped: boolean): Promise { - try { - const frames = pause.callFrames; - const top = frames[0]; - if (chain.unwinding || this.guardedBelow(frames.length) || (skipped && chain.walkHasNothingBelow)) { - // Unwinding: a net fired in a deeper call and was dropped; V8's own - // step-outs finish the step. - return; - } - // Only where the text of the function being left names something V8 can - // lose the step on: this spares breakpoints, and errs toward netting. - if (!(await this.namesAFinally(top))) { - return; - } - const target = await this.returnTarget(chain, pause); - if (target.kind !== 'frame') { - if (target.kind === 'nothing' && skipped && chain.kind === 'in') { - // Nothing of the program comes to be below without the walk landing in it first. - chain.walkHasNothingBelow = true; - } - return; - } - const frame = frames[target.index]; - if (chain.kind !== 'out' && fnKey(frame) === fnKey(top)) { - // It returns to itself (recursion): a net would sit in the frame being stepped in. - return; - } - // (a) V8's own word: the guarded frame and every frame above it are - // plain functions, which come down only by returning. - if (frame.canBeRestarted !== true) { - return; - } - // (b) Every position of it, or none. - const all = await this.locationsOf(frame); - if (all.length === 0 || all.length > this.tunables.netSize) { - return; - } - await this.arm(all, { - name: frame.functionName || '(anonymous)', - fn: fnKey(frame), - depth: frames.length - target.index - }); - } catch (err) { - logger.warn(`[JsStepper] no net for this step, V8's own step goes on alone: ${errorText(err)}`); - } - } - /** What the top frame of `pause` returns to; js-debug is asked once per pause. Never throws. */ private async returnTarget(chain: Chain, pause: CdpPaused): Promise { const known = this.targets.get(pause); @@ -1120,8 +781,8 @@ export class JsStepper { * With none on the stack, the function awaiting an async one the event * loop resumed: the first frame of V8's async stack, when every link down * to it is an `await` (a `Promise.then` or timer link only scheduled the - * code on top) and js-debug marks it program code. An awaiter is never - * netted; it only says the stack is not gone, and V8's own step leads to it. + * code on top) and js-debug marks it program code. An awaiter only says + * the stack is not gone; V8's own step leads to it. */ private async findReturnTarget(chain: Chain, pause: CdpPaused): Promise { const frames = pause.callFrames; diff --git a/src/session/execution/execution-controller.ts b/src/session/execution/execution-controller.ts index 754a22c3e..30cdba80d 100644 --- a/src/session/execution/execution-controller.ts +++ b/src/session/execution/execution-controller.ts @@ -398,7 +398,7 @@ export class ExecutionController { } // What the step itself has to say about how it landed (the JavaScript // stepper: how far a step-in walked without reaching the program's - // code, or that it was caught at an awaiting function; issue #1130). + // code, or that every command it may send was spent there; issue #1130). const stepNote = ownStop?.reason === 'step' ? ownStop.text : undefined; success(stepNote ? `${options.successMessage}. ${stepNote}` : options.successMessage, landing); }; diff --git a/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts b/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts index 49e3f389a..b6a0a7adb 100644 --- a/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts +++ b/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts @@ -12,9 +12,11 @@ * - a call through Node's code into a callback of the program's is * followed; a call that only starts a later task is not; * - a step that leaves a function through `return` inside try...finally - * lands in the caller. V8 loses that step (12.4 to 14.6, a bare CDP - * client), sync and async; the stepper catches the return with temporary - * breakpoints on the frame the step returns to; + * is the engine's own. V8 loses it (issues #1161, #1174; Node 22, 24 + * and 26), sync and async, and the server does not rescue it. Those + * tests accept both a runtime that loses the step and one that lands it + * in the caller, and fail on a stop anywhere else (another call of the + * same function); * - a breakpoint reached during a step stops as itself; * - a step off the last line of a callback Node called has no frame of the * program to return to: the program is resumed, not walked through the @@ -46,11 +48,33 @@ type StopAnswer = ToolAnswer & { pending?: boolean; stopReason?: string; location?: { file: string; line: number }; + snapshot?: { frames?: Array<{ name: string; line: number }> }; }; /** A step that answered inside the grace window is not pending; this bound says it was prompt. */ const PROMPT_MS = 4000; +/** + * A step V8 loses (issues #1161, #1174) is the engine's own, and the server + * does not rescue it. On a runtime that loses it the step does not land: the + * program runs on (`pending: true`, state `running`) or ends. On one that + * does not, it lands in the caller. Either passes; a stop anywhere else + * fails, another call of the function left included. Every caller these + * tests name runs once, so a line of it identifies the call. + */ +function expectInCallerOrLost(answer: StopAnswer & { ms: number }, file: RegExp, callerLines: number[]): void { + expect(answer.success, JSON.stringify(answer)).toBe(true); + if (answer.state !== 'paused') { + // Lost: the program ran on, or ended. + return; + } + expect(answer.pending, JSON.stringify(answer)).toBeUndefined(); + expect(answer.stopReason, JSON.stringify(answer)).toBeUndefined(); + expect(answer.location?.file ?? '', JSON.stringify(answer)).toMatch(file); + expect(callerLines, JSON.stringify(answer)).toContain(answer.location?.line); + expect(answer.ms, `took ${answer.ms} ms: ${JSON.stringify(answer)}`).toBeLessThan(PROMPT_MS); +} + describe('The server\'s JavaScript stepper against a real js-debug (issues #1130, #1161) @requires-node', () => { let server: StdioClientHandle | undefined; @@ -91,6 +115,12 @@ describe('The server\'s JavaScript stepper against a real js-debug (issues #1130 expect(answer.ms, `took ${answer.ms} ms: ${JSON.stringify(answer)}`).toBeLessThan(PROMPT_MS); } + /** Removes the breakpoint on a marked line, so a later call through that line does not stop on it. */ + async function removeBreakpointAt(marker: string): Promise { + const removed = await server!.call('remove_breakpoint', { file: FIXTURE, line: lineOf(marker) }); + expect(removed.success, JSON.stringify(removed)).toBe(true); + } + describe('step_into (issue #1130)', () => { it('lands on the next line when the walk into the call stays in Node\'s own code, and says how far it went: the first console.log of the process', async () => { await pausedAt('the first console.log'); @@ -120,10 +150,10 @@ describe('The server\'s JavaScript stepper against a real js-debug (issues #1130 expectLanding(await step('step_into'), 'after setTimeout'); }, 60000); - it('lands on the next line of a require of a module not yet loaded (the loader returns through try...finally, issue #1161)', async () => { + it('lands on the next line of a require of a module not yet loaded, or V8 loses the step (the loader returns through try...finally, issue #1161)', async () => { await pausedAt('first load of a module'); const answer = await step('step_into'); - expectLanding(answer, 'after the require'); + expectInCallerOrLost(answer, /steps\.cjs$/, [lineOf('after the require')]); }, 60000); }); @@ -157,24 +187,41 @@ describe('The server\'s JavaScript stepper against a real js-debug (issues #1130 }, 60000); }); - describe('a step that leaves a function through return inside try...finally (issue #1161)', () => { - it('step_out lands in the caller', async () => { + describe('a step that leaves a function through return inside try...finally (issues #1161, #1174)', () => { + // withFinally is called twice: from syncPart, where these tests pause, + // and later from main. Its caller here is syncPart, which runs once. + const CALLER = (): number[] => [lineOf('calls withFinally'), lineOf('after withFinally')]; + + it('step_out lands in the caller, or V8 loses it: never in another call', async () => { await pausedAt('return inside try-finally'); - // V8 never pauses for this step-out: "Step completed as session exited." - expectLanding(await step('step_out'), 'after withFinally'); + // So main's later call of withFinally does not stop on it. + await removeBreakpointAt('return inside try-finally'); + // The call's own line too: V8's step-out can stop there once more. + expectInCallerOrLost(await step('step_out'), /steps\.cjs$/, CALLER()); }, 60000); - it('step_over reaches the finally block, then the caller', async () => { + it('step_over reaches the finally block; the step off it is V8\'s: the caller, lost, or the known stop in the next call of the function (#1161)', async () => { await pausedAt('return inside try-finally'); + await removeBreakpointAt('return inside try-finally'); expectLanding(await step('step_over'), 'the finally block'); - // The step that leaves the function is the one V8 loses. - expectLanding(await step('step_over'), 'after withFinally'); + // The step that leaves the function is V8's own, and the server does not + // rescue it. A runtime with V8's fix lands it in the caller; one that + // loses it runs on. Today's V8 does a third thing, the known defect that + // docs/javascript/README.md states ("can instead stop in the next call + // of the same function"): it stops on the first statement of main's + // later call of withFinally and reports that as the step. This test + // names that stop, the frame under it included, so any other stop fails. + const answer = await step('step_over'); + const inTheNextCall = answer.state === 'paused' && answer.location?.line === lineOf('return inside try-finally'); + if (inTheNextCall) { + expect(answer.stopReason, JSON.stringify(answer)).toBeUndefined(); + expect(answer.snapshot?.frames?.[1]?.line, JSON.stringify(answer)).toBe(lineOf('calls withFinally from an async function')); + return; + } + expectInCallerOrLost(answer, /steps\.cjs$/, CALLER()); }, 60000); - it('step_out into an async caller is the engine\'s own, and the engine loses it (#1174)', async () => { - // The function being left is plain; the caller is async. It could - // suspend before a temporary breakpoint proves the step came back, so - // the server sets none. The program runs on to its end. + it('step_out into an async caller lands in that caller, or V8 loses it (#1174)', async () => { await pausedAt('return inside try-finally', undefined, ['calls withFinally from an async function']); // The first stop is the call from the plain caller: run to the second. let stop = await server!.call('continue_execution', {}); @@ -182,20 +229,17 @@ describe('The server\'s JavaScript stepper against a real js-debug (issues #1130 expect(stop.location?.line, JSON.stringify(stop)).toBe(lineOf('calls withFinally from an async function')); stop = await server!.call('step_into', {}); expect(stop.location?.line, JSON.stringify(stop)).toBe(lineOf('return inside try-finally')); - const answer = await step('step_out'); - expect(answer, JSON.stringify(answer)).toMatchObject({ success: true }); - expect(answer.state, JSON.stringify(answer)).not.toBe('paused'); + // main runs once; withFinally is not called again after this. + expectInCallerOrLost(await step('step_out'), /steps\.cjs$/, [ + lineOf('calls withFinally from an async function'), + lineOf('after withFinally from an async function') + ]); }, 60000); - it('step_out of an async function with that shape is the engine\'s own, and the engine loses it (#1174)', async () => { + it('step_out of an async function with that shape lands in the function that awaits it, or V8 loses it (#1174)', async () => { await pausedAt('async return inside try-finally'); - // A temporary breakpoint below a function that can suspend cannot tell - // it returning from it pausing at an await: the server sets none, and - // the step is lost as it was before the server had a stepper. If this - // starts landing, V8 has fixed it (#1173): update the docs. - const answer = await step('step_out'); - expect(answer, JSON.stringify(answer)).toMatchObject({ success: true }); - expect(answer.state, JSON.stringify(answer)).not.toBe('paused'); + // A runtime with V8's fix (#1173) lands it; the docs then need updating. + expectInCallerOrLost(await step('step_out'), /steps\.cjs$/, [lineOf('awaits workWithFinally'), lineOf('after the await')]); }, 60000); }); @@ -253,8 +297,8 @@ describe('The server\'s JavaScript stepper against a real js-debug (issues #1130 await asyncPausedAt('in inner, after the gate', { condition: 'id === 2' }); const answer = await step('step_out'); expectAsyncLanding(answer, 'the continuation of handler'); - // A temporary breakpoint on `handler` stopped in handler(1), whose - // continuation was queued first. V8's own step finds handler(2). + // Three calls of handler are in flight, handler(1)'s continuation + // queued first: V8's own step finds handler(2), the one that awaited. const id = await server!.call('evaluate_expression', { expression: 'id' }); expect(id.result, JSON.stringify(id)).toBe('2'); expect(answer.message).toBe('Stepped out'); @@ -262,23 +306,20 @@ describe('The server\'s JavaScript stepper against a real js-debug (issues #1130 it('step_over on an await lands on the next line of the same function, though the function has a finally clause', async () => { await asyncPausedAt('an await before the try'); - // With a temporary breakpoint on the caller, the step stopped there the - // moment this function suspended. + // None of these steps leaves the function without crossing an await first: V8 does not lose them. expectAsyncLanding(await step('step_over'), 'an await inside the try'); expectAsyncLanding(await step('step_over'), 'the return inside the try'); expectAsyncLanding(await step('step_over'), 'the finally block of an async function'); // Off the finally block of an async function V8 loses the step, and the - // server does not rescue it (#1174): the program runs on to its end. - const out = await step('step_over'); - expect(out, JSON.stringify(out)).toMatchObject({ success: true }); - expect(out.state, JSON.stringify(out)).not.toBe('paused'); + // server does not rescue it (#1174). closing is called once, from main. + expectInCallerOrLost(await step('step_over'), /async-steps\.cjs$/, [at('awaits closing'), at('after closing')]); }, 60000); it('step_over on a statement that awaits on a later line stays in the function: its caller runs on, and is not where the step stops', async () => { await asyncPausedAt('a statement that awaits on later lines'); // The function has a finally clause above, and the paused line itself - // awaits nothing. A temporary breakpoint on the caller stopped the step - // at the caller's next statement, the moment this function suspended. + // awaits nothing: the step crosses the await on the next line and stays + // in the function while its caller runs on. const answer = await step('step_over'); expectAsyncLanding(answer, 'the second await of the statement'); expect(answer.message).toBe('Stepped over'); @@ -288,8 +329,8 @@ describe('The server\'s JavaScript stepper against a real js-debug (issues #1130 await asyncPausedAt('in early, before its first await', { condition: 'id === 2' }); const answer = await step('step_out'); expectAsyncLanding(answer, 'the continuation of relay'); - // A temporary breakpoint on `relay`, kept by depth, stopped in relay(3) - // as it was entered: relay(2) had left the stack at its own await. + // Three calls of relay are in flight: the id says the step landed in + // relay(2), the one that awaited this early. const id = await server!.call('evaluate_expression', { expression: 'id' }); expect(id.result, JSON.stringify(id)).toBe('2'); expect(answer.message).toBe('Stepped out'); @@ -307,9 +348,8 @@ describe('The server\'s JavaScript stepper against a real js-debug (issues #1130 it('steps with V8 alone where Node\'s own code is program code: a skip list without ', async () => { await asyncPausedAt('in a timer callback', { launchArgs: { skipFiles: ['**/node_modules/**'] } }); const answer = await step('step_out'); - // V8 gives no break positions for Node's own scripts, so there is no - // temporary breakpoint to set on the timer code this returns to. The - // step used to fail for it, and leave the session in `error`. + // Node's own code is program code to this step: V8's step-out lands + // in the timer code it returns to. expect(answer, JSON.stringify(answer)).toMatchObject({ success: true, state: 'paused' }); expect(answer.location?.file ?? '', JSON.stringify(answer)).toMatch(/timers/); }, 60000); diff --git a/tests/fixtures/javascript/step-skipped-code/steps.cjs b/tests/fixtures/javascript/step-skipped-code/steps.cjs index a0e283fb4..e3c4792bb 100644 --- a/tests/fixtures/javascript/step-skipped-code/steps.cjs +++ b/tests/fixtures/javascript/step-skipped-code/steps.cjs @@ -53,9 +53,8 @@ function laterCallback() { globalThis.later = true; // MARK: a later task } -// A plain function, so the steps below return into a frame that comes down -// only by returning: the one shape the server rescues a lost step into -// (issue #1161). The same calls from an async function are left to V8 (#1174). +// A plain function, called once: a step that V8 does not lose returns into +// this one call (issue #1161). The same call from an async function is #1174. function syncPart() { const guarded = withFinally(); // MARK: calls withFinally const afterFinally = 4; // MARK: after withFinally diff --git a/tests/proxy/js-stepper.test.ts b/tests/proxy/js-stepper.test.ts index 69675dce8..9a7800802 100644 --- a/tests/proxy/js-stepper.test.ts +++ b/tests/proxy/js-stepper.test.ts @@ -7,8 +7,8 @@ * and the next scripted `Debugger.paused` arrive; js-debug marks frame 0 of a * `stackTrace` answer `deemphasize` for skipped code; and for every pause it * keeps it sends one DAP `stopped` (reason `pause` for a step it did not - * request, `breakpoint` for a breakpoint it does not know) a moment later, - * and one `continued` per resume. + * request, `breakpoint` for a breakpoint hit) a moment later, and one + * `continued` per resume. */ import { describe, it, expect, beforeEach, vi } from 'vitest'; import { EventEmitter } from 'events'; @@ -22,15 +22,6 @@ interface Frame { /** 0-based line of the frame's position. */ line: number; col?: number; - /** 0-based line the function starts on; defaults to a line per function name. */ - fnLine?: number; - /** Column V8 reports for the function: its parameter list, or the first token of an arrow. */ - fnCol?: number; - /** - * An async function, a generator or module code that may await: V8 says it - * cannot be restarted, and neither can any frame below it. - */ - resumable?: boolean; /** js-debug marks it skipped code. */ skipped?: boolean; /** The mark's wording; "Skipped by skipFiles" is a script-level verdict. */ @@ -40,8 +31,8 @@ interface Frame { interface ScriptedPause { frames: Frame[]; reason?: string; - /** Breakpoint ids V8 reports; a function picks from the nets armed at that moment. */ - hits?: string[] | ((armed: ArmedBreakpoint[]) => string[]); + /** Breakpoint ids V8 reports: js-debug's own, the stepper sets none. */ + hits?: string[]; /** js-debug resumes this pause itself (a module-entry breakpoint): no `stopped`, then a `resumed`. */ resumedByJsDebug?: boolean; /** What js-debug reports this pause as. */ @@ -51,8 +42,6 @@ interface ScriptedPause { * (the default: the function on top returns to it), `Promise.then`, * `Timeout` (it only scheduled the code on top). */ - /** V8 too old to say whether a frame can be restarted: the field is left out. */ - noRestartInfo?: boolean; asyncParent?: { fn: string; script?: string; line: number; col?: number; skipped?: boolean; description?: string; /** `await` links with no frames before the one that has the awaiter (V8 lists them for later awaits). */ @@ -60,48 +49,26 @@ interface ScriptedPause { }; } -interface ArmedBreakpoint { - id: string; - scriptId: string; - lineNumber: number; - columnNumber: number; -} - +/** The 0-based line a function starts on: a hundred lines of its own per function name. */ const FN_LINES: Record = {}; function fnLineOf(frame: Frame): number { - if (frame.fnLine !== undefined) return frame.fnLine; FN_LINES[frame.fn] ??= 1000 + Object.keys(FN_LINES).length * 100; return FN_LINES[frame.fn]; } -/** Lines in a scripted script: every function name a test uses gets a hundred of its own (see fnLineOf). */ -const SOURCE_LINES = 30000; - -/** A script's text when a test writes none: plain statements, nothing that suspends or closes through a finally. */ -const DEFAULT_SOURCE = Array.from({ length: SOURCE_LINES }, () => 'x();').join('\n'); - /** A scripted V8 behind a CDP socket, and the js-debug that watches it. */ class Engine extends EventEmitter { calls: Array<{ method: string; params: Record }> = []; /** What the next resuming command leads to: a pause, or nothing (the program runs). */ script: Array = []; - armed: ArmedBreakpoint[] = []; - removed: string[] = []; - /** Break positions per function, keyed `script:fnLine`; default: ten lines from the function's start. */ - positions = new Map>(); - sources = new Map(); connected = true; current: ScriptedPause | null = null; /** DAP events js-debug sent, in order: the test feeds them to the stepper. */ onDap: (event: DebugProtocol.Event) => void = () => undefined; stackTraceFailures = 0; stackTraceCalls: number[] = []; - /** Scripts V8 refuses break positions for (Node's own, measured). */ - refuse = new Set(['node:internal']); - /** A CDP method that fails the next time it is sent, and ones that always fail. */ + /** A CDP method that fails the next time it is sent. */ failOnce: string | null = null; - failAlways = new Set(); - private nextId = 0; isConnected(): boolean { return this.connected; @@ -109,9 +76,6 @@ class Engine extends EventEmitter { async send(method: string, params: Record = {}): Promise { this.calls.push({ method, params }); - if (this.failAlways.has(method)) { - throw new Error(`${method}: refused`); - } if (this.failOnce === method) { this.failOnce = null; throw new Error(`${method}: refused`); @@ -125,36 +89,6 @@ class Engine extends EventEmitter { this.current = null; setImmediate(() => this.advance(true)); return {} as T; - case 'Debugger.getPossibleBreakpoints': { - const start = params.start as { scriptId: string; lineNumber: number; columnNumber: number }; - if (this.refuse.has(start.scriptId)) { - throw new Error('Debugger.getPossibleBreakpoints: Cannot retrive script context'); - } - const own = [...this.positions.entries()].find(([key]) => key === `${start.scriptId}:${start.lineNumber}`)?.[1]; - // By default a function's positions are ten lines from its start, and - // every line a frame of it is at in this test: as V8 answers, the - // function's positions hold every place it can be paused. - const framesOfIt = [this.current, ...this.script] - .flatMap((p) => (p && p !== 'runs' ? p.frames : [])) - .filter((f) => (f.script ?? 'app') === start.scriptId && fnLineOf(f) === start.lineNumber) - .map((f) => f.line); - const lines = [...new Set([...Array.from({ length: 10 }, (_, i) => start.lineNumber + i), ...framesOfIt])].sort((a, b) => a - b); - const list = own ?? lines.map((lineNumber) => ({ lineNumber })); - return { locations: list.map((l) => ({ scriptId: start.scriptId, columnNumber: 0, ...l })) } as T; - } - case 'Debugger.setBreakpoint': { - const location = params.location as { scriptId: string; lineNumber: number; columnNumber: number }; - const id = `net:${++this.nextId}`; - this.armed.push({ id, ...location }); - return { breakpointId: id } as T; - } - case 'Debugger.removeBreakpoint': - this.removed.push(params.breakpointId as string); - this.armed = this.armed.filter((bp) => bp.id !== params.breakpointId); - return {} as T; - case 'Debugger.getScriptSource': - // V8 gives the source of every script, Node's own included. - return { scriptSource: this.sources.get(params.scriptId as string) ?? DEFAULT_SOURCE } as T; default: return {} as T; } @@ -166,7 +100,7 @@ class Engine extends EventEmitter { this.emit('cdp-event', 'Debugger.paused', this.toCdp(pause)); } - /** The running program pauses here by itself (a net, a breakpoint, a pause request), js-debug's report included. */ + /** The running program pauses here by itself (a breakpoint, a pause request, a late landing), js-debug's report included. */ arrive(pause: ScriptedPause): void { this.script.unshift(pause); this.advance(false); @@ -211,22 +145,18 @@ class Engine extends EventEmitter { } private hitsOf(pause: ScriptedPause): string[] { - return typeof pause.hits === 'function' ? pause.hits(this.armed) : pause.hits ?? []; + return pause.hits ?? []; } private toCdp(pause: ScriptedPause): Record { const hits = this.hitsOf(pause); - // Fix the picked ids, so js-debug's later report sees the same pause. - pause.hits = hits; return { reason: pause.reason ?? (hits.length > 0 ? 'other' : 'step'), hitBreakpoints: hits, - callFrames: pause.frames.map((f, i) => ({ + callFrames: pause.frames.map((f) => ({ functionName: f.fn, - functionLocation: { scriptId: f.script ?? 'app', lineNumber: fnLineOf(f), columnNumber: f.fnCol ?? 0 }, - location: { scriptId: f.script ?? 'app', lineNumber: f.line, columnNumber: f.col ?? 0 }, - // As measured on Node 22, 24 and 26: false for a resumable frame and every frame below one. - ...(pause.noRestartInfo ? {} : { canBeRestarted: !pause.frames.slice(0, i + 1).some((above) => above.resumable) }) + functionLocation: { scriptId: f.script ?? 'app', lineNumber: fnLineOf(f), columnNumber: 0 }, + location: { scriptId: f.script ?? 'app', lineNumber: f.line, columnNumber: f.col ?? 0 } })), ...(pause.asyncParent ? { asyncStackTrace: this.asyncTrace(pause.asyncParent) } : {}) }; @@ -292,7 +222,6 @@ describe('JsStepper (issue #1130)', () => { let seen: Array<{ event: string; withheld: boolean }>; const commands = (): string[] => engine.calls.map((c) => c.method).filter((m) => /step|resume/.test(m)); - const setBreakpoints = (): number => engine.calls.filter((c) => c.method === 'Debugger.setBreakpoint').length; const stopped = (): DebugProtocol.StoppedEvent['body'] => delivered[0].body as DebugProtocol.StoppedEvent['body']; /** Wait until the chain is over and every event js-debug owes has arrived. */ @@ -303,35 +232,8 @@ describe('JsStepper (issue #1130)', () => { await tick(12); } - /** Lines set in each script's text so far in this test (0-based). */ - let written: Map>; - - /** Set lines of a script's text, keeping the ones set before. */ - function sourceWith(lines: Record, script = 'app'): void { - const known = written.get(script) ?? new Map(); - written.set(script, known); - for (const [line, text] of Object.entries(lines)) { - known.set(Number(line), text); - } - const source = Array.from({ length: SOURCE_LINES }, () => 'x();'); - for (const [line, text] of known) { - source[line] = text; - } - engine.sources.set(script, source.join('\n')); - } - - /** - * The frame, with a `finally` clause in its function's text below its - * line and nothing that suspends: the shape V8 loses a leaving step on. - */ - function lossy(frame: Frame): Frame { - sourceWith({ [frame.line + 5]: '} finally { done(); }' }, frame.script ?? 'app'); - return frame; - } - beforeEach(() => { engine = new Engine(); - written = new Map(); delivered = []; seen = []; stepper = new JsStepper({ @@ -396,7 +298,6 @@ describe('JsStepper (issue #1130)', () => { expect(stopped().text).toBeUndefined(); // js-debug's own stopped and continued for the step were kept back. expect(seen).toEqual([{ event: 'continued', withheld: true }, { event: 'stopped', withheld: true }]); - expect(setBreakpoints()).toBe(0); }); it('never asks V8 to follow a call into a later task', async () => { @@ -409,7 +310,7 @@ describe('JsStepper (issue #1130)', () => { }); describe('a step into skipped code', () => { - it('steps in again until the program\'s code is on top, under a net on the frame it returns to', async () => { + it('steps in again until the program\'s code is on top', async () => { engine.pauseAt({ frames: frames(app('main', 10)) }); engine.script = [ { frames: frames(node('emit', 5), app('main', 10)) }, @@ -422,10 +323,6 @@ describe('JsStepper (issue #1130)', () => { expect(commands()).toEqual(['Debugger.stepInto', 'Debugger.stepInto', 'Debugger.stepInto']); expect(stopped()).toMatchObject({ reason: 'step' }); expect(stopped().text).toBeUndefined(); - // The net went up at the first skipped landing, on main's positions, and is gone. - expect(setBreakpoints()).toBeGreaterThan(0); - expect(engine.armed).toEqual([]); - expect(stepper.describe().nets).toBe(0); // Three kept pauses, three stopped events from js-debug, one reported. expect(seen.filter((e) => e.event === 'stopped')).toEqual(Array(3).fill({ event: 'stopped', withheld: true })); expect(delivered).toHaveLength(1); @@ -442,8 +339,7 @@ describe('JsStepper (issue #1130)', () => { await stepper.request('stepIn', { threadId: 1 }); await settled(); // One levels-1 question for the frame the step starts from, one for - // the node script, one for the landing; the longer one is the look at - // the whole stack for the net. + // the node script, one for the landing. expect(engine.stackTraceCalls.filter((levels) => levels === 1)).toHaveLength(3); }); @@ -461,7 +357,7 @@ describe('JsStepper (issue #1130)', () => { expect(stopped()).toMatchObject({ reason: 'step' }); }); - it('steps out once the budget is spent, lands by the net when V8 loses the step-out, and says how far it walked without reaching the program', async () => { + it('steps out once the budget is spent, and says how far it walked without reaching the program', async () => { stepper = new JsStepper({ target: { sendRequest: async (_c: string, args?: unknown) => engine.stackTrace((args as { levels: number }).levels) as never }, deliver: (event) => delivered.push(event), @@ -474,20 +370,16 @@ describe('JsStepper (issue #1130)', () => { { frames: frames(node('require', 1), app('main', 10)) }, { frames: frames(node('require', 2), app('main', 10)) }, { frames: frames(node('require', 3), app('main', 10)) }, - // The step-out is lost (the frame returns through try...finally, issue - // #1161): no step landing. The net on main catches the return instead. - { frames: frames(app('main', 11)), reason: 'other', hits: (armed) => [armed[0].id] } + // V8's step-out lands in main. + { frames: frames(app('main', 11)) } ]; await stepper.request('stepIn', { threadId: 1 }); await settled(); expect(commands()).toEqual(['Debugger.stepInto', 'Debugger.stepInto', 'Debugger.stepInto', 'Debugger.stepOut']); expect(stopped()).toMatchObject({ reason: 'step', description: 'Paused' }); - // js-debug reported the net hit as a breakpoint with no ids: not what leaves. - expect(stopped().hitBreakpointIds).toBeUndefined(); // Three step-ins, back in the frame it left: that much is known, and said. expect(stopped().text).toBe(ErrorMessages.stepIntoReachedNoProgramCode(3)); - expect(engine.armed).toEqual([]); }); it('steps in again when it comes back to the line it left, at the same depth', async () => { @@ -518,7 +410,6 @@ describe('JsStepper (issue #1130)', () => { await settled(); expect(commands()).toHaveLength(3); expect(stopped()).toMatchObject({ reason: 'step', text: ErrorMessages.stepStillInSkippedCode(3) }); - expect(engine.armed).toEqual([]); }); }); @@ -536,9 +427,8 @@ describe('JsStepper (issue #1130)', () => { await settled(); expect(commands()).toEqual(['Debugger.stepInto', 'Debugger.stepInto', 'Debugger.stepInto']); expect(stopped()).toMatchObject({ reason: 'step' }); - // Nothing to guard: no frame of the program was below. One look at the stack, not one per landing. - expect(setBreakpoints()).toBe(0); - expect(engine.stackTraceCalls.filter((levels) => levels > 1)).toHaveLength(1); + // A walk asks js-debug about the stack below only when it has to step out. + expect(engine.stackTraceCalls.filter((levels) => levels > 1)).toHaveLength(0); }); it('step_into resumes the program only once its budget is spent', async () => { @@ -594,152 +484,7 @@ describe('JsStepper (issue #1130)', () => { // No step-out from the bottom frames: that lands in the next task's internals. expect(commands()).toEqual(['Debugger.stepOut', 'Debugger.resume']); expect(delivered).toEqual([]); - expect(engine.armed).toEqual([]); - expect(stepper.describe()).toMatchObject({ chain: false, nets: 0 }); - }); - }); - - describe('nets: a step never counts on V8 alone to come back to a frame (issue #1161)', () => { - it('step_out arms the frame it returns to before the first command, and lands by the net when V8 never pauses', async () => { - engine.pauseAt({ frames: frames(lossy(app('withFinally', 5)), app('caller', 14)) }); - // V8's step-out is lost; the next thing V8 says is the net's breakpoint. - engine.script = [{ frames: frames(app('caller', 15)), reason: 'other', hits: (armed) => [armed[1].id] }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - - const firstStep = engine.calls.findIndex((c) => c.method === 'Debugger.stepOut'); - const firstNet = engine.calls.findIndex((c) => c.method === 'Debugger.setBreakpoint'); - expect(firstNet).toBeGreaterThanOrEqual(0); - expect(firstNet).toBeLessThan(firstStep); - // The net is on the caller's function, from its own position on. - const netCalls = engine.calls.filter((c) => c.method === 'Debugger.setBreakpoint'); - expect(new Set(netCalls.map((c) => (c.params.location as { scriptId: string }).scriptId))).toEqual(new Set(['app'])); - expect(stopped()).toMatchObject({ reason: 'step' }); - expect(engine.armed).toEqual([]); - expect(engine.removed).toHaveLength(netCalls.length); - }); - - it('a step over arms nothing in a function with no `finally`, and the frame it returns to in one that has it', async () => { - engine.sources.set('app', Array.from({ length: SOURCE_LINES }, () => 'x();').join('\n')); - engine.pauseAt({ frames: frames(app('plain', 5), app('caller', 14)) }); - engine.script = [{ frames: frames(app('plain', 6), app('caller', 14)) }]; - await stepper.request('next', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBe(0); - - delivered.length = 0; - const source = Array.from({ length: SOURCE_LINES }, () => 'x();'); - source[fnLineOf(app('guarded', 0)) + 2] = 'try { return x(); } finally { done(); }'; - engine.sources.set('lib', source.join('\n')); - engine.pauseAt({ frames: frames(app('guarded', fnLineOf(app('guarded', 0)) + 2, { script: 'lib' }), app('caller', 14)) }); - engine.script = [{ frames: frames(app('caller', 15)), reason: 'other', hits: (armed) => [armed[1].id] }]; - await stepper.request('next', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBeGreaterThan(0); - expect(stopped()).toMatchObject({ reason: 'step' }); - expect(engine.armed).toEqual([]); - }); - - it('puts no net on the frame being stepped in: a function with `finally` that returns to itself', async () => { - const source = Array.from({ length: SOURCE_LINES }, () => 'x();'); - const start = fnLineOf(app('down', 0)); - source[start + 2] = 'try { return down(n - 1); } finally { done(); }'; - engine.sources.set('app', source.join('\n')); - engine.pauseAt({ frames: frames(app('down', start + 2), app('down', start + 2), app('main', 10)) }); - engine.script = [{ frames: frames(app('down', start + 3), app('down', start + 2), app('main', 10)) }]; - await stepper.request('next', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBe(0); - expect(stopped()).toMatchObject({ reason: 'step' }); - }); - - it('a net hit deeper than the frame it guards is not a landing: a step-out of a recursive function steps out again', async () => { - const start = fnLineOf(app('down', 0)); - engine.pauseAt({ frames: frames(lossy(app('down', start + 3)), app('down', start + 5), app('main', 10)) }); - engine.script = [ - // The frame being left runs on to its own finally block: a net position, one frame too deep. - { frames: frames(app('down', start + 7), app('down', start + 5), app('main', 10)), reason: 'ambiguous', hits: (armed) => [armed[0].id] }, - { frames: frames(app('down', start + 7), app('main', 10)), reason: 'other', hits: (armed) => [armed[0].id] } - ]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - expect(commands()).toEqual(['Debugger.stepOut', 'Debugger.stepOut']); - expect(stopped()).toMatchObject({ reason: 'step' }); - expect(engine.armed).toEqual([]); - }); - - - it('nets every break position of the frame it guards, those before the call too: a loop comes back to its top', async () => { - const start = fnLineOf(app('looping', 0)); - engine.positions.set(`app:${start}`, Array.from({ length: 60 }, (_, i) => ({ lineNumber: start + i }))); - engine.pauseAt({ frames: frames(lossy(app('leaf', 5)), app('looping', start + 50)) }); - engine.script = [{ frames: frames(app('looping', start + 2)), reason: 'other', hits: (armed) => [armed.find((bp) => bp.lineNumber === start + 2)!.id] }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - const lines = engine.calls - .filter((c) => c.method === 'Debugger.setBreakpoint') - .map((c) => (c.params.location as { lineNumber: number }).lineNumber); - expect(lines).toHaveLength(60); - expect(Math.min(...lines)).toBe(start); - expect(stopped()).toMatchObject({ reason: 'step' }); - }); - - it('nets none in a function with more break positions than a net may have: a part of it could miss where control comes back', async () => { - const start = fnLineOf(app('huge', 0)); - engine.positions.set(`app:${start}`, Array.from({ length: 101 }, (_, i) => ({ lineNumber: start + i }))); - engine.pauseAt({ frames: frames(lossy(app('leaf', 5)), app('huge', start + 50)) }); - engine.script = [{ frames: frames(app('huge', start + 51)) }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBe(0); - expect(stopped()).toMatchObject({ reason: 'step' }); - }); - - it('nets every position of top-level code that starts with a function: asked again past the nested one', async () => { - // V8 answers the nested function's positions for the script's own - // position; the script's code goes on after it, before the frame's line too. - const moduleStart = fnLineOf(app('(module)', 0)); - engine.positions.set(`app:${moduleStart}`, [{ lineNumber: moduleStart + 1 }, { lineNumber: moduleStart + 2 }]); - engine.positions.set(`app:${moduleStart + 2}`, [{ lineNumber: moduleStart + 4 }, { lineNumber: moduleStart + 19 }, { lineNumber: moduleStart + 20 }, { lineNumber: moduleStart + 21 }]); - engine.pauseAt({ frames: frames(lossy(app('callee', 5)), app('(module)', moduleStart + 20, { fnLine: moduleStart })) }); - engine.script = [{ frames: frames(app('(module)', moduleStart + 21, { fnLine: moduleStart })), reason: 'other', hits: (armed) => [armed[armed.length - 1].id] }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - const lines = engine.calls - .filter((c) => c.method === 'Debugger.setBreakpoint') - .map((c) => (c.params.location as { lineNumber: number }).lineNumber); - expect(lines).toEqual([moduleStart + 4, moduleStart + 19, moduleStart + 20, moduleStart + 21]); - expect(stopped()).toMatchObject({ reason: 'step' }); - }); - - it('nets nothing when the frame\'s own positions cannot all be found', async () => { - const moduleStart = fnLineOf(app('(lost module)', 0)); - engine.positions.set(`app:${moduleStart}`, [{ lineNumber: moduleStart + 1 }]); - engine.positions.set(`app:${moduleStart + 1}`, []); - engine.pauseAt({ frames: frames(lossy(app('callee', 5)), app('(lost module)', moduleStart + 20, { fnLine: moduleStart })) }); - engine.script = [{ frames: frames(app('(lost module)', moduleStart + 21, { fnLine: moduleStart })) }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBe(0); - }); - - it('keeps no part of a net when V8 refuses one of its breakpoints', async () => { - let n = 0; - const send = engine.send.bind(engine); - engine.send = (async (method: string, params?: Record) => { - if (method === 'Debugger.setBreakpoint' && ++n === 3) { - throw new Error('Debugger.setBreakpoint: refused'); - } - return send(method, params); - }) as typeof engine.send; - engine.pauseAt({ frames: frames(lossy(app('leaf', 5)), app('caller', 14)) }); - engine.script = [{ frames: frames(app('caller', 15)) }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - expect(n).toBeGreaterThan(3); - expect(engine.armed).toEqual([]); - expect(engine.removed.length).toBe(n - 1); - expect(stopped()).toMatchObject({ reason: 'step' }); + expect(stepper.describe()).toMatchObject({ chain: false }); }); }); @@ -755,43 +500,33 @@ describe('JsStepper (issue #1130)', () => { expect(commands()).toEqual(['Debugger.stepOver']); }); - it('removes its nets before a real stop is forwarded', async () => { + it('forwards an exception reached during a step as itself', async () => { engine.pauseAt({ frames: frames(app('leaf', 5), app('caller', 14)) }); engine.script = [{ frames: frames(app('other', 80), app('leaf', 5), app('caller', 14)), reason: 'exception', dapReason: 'exception' }]; - let armedAtDelivery = -1; - stepper = new JsStepper({ - target: { sendRequest: async (_c: string, args?: unknown) => engine.stackTrace((args as { levels: number }).levels) as never }, - deliver: (event) => { - armedAtDelivery = engine.armed.length; - delivered.push(event); - }, - tunables: { settleCeilingMs: 150, verdictCeilingMs: 150 } - }); - stepper.attachCdp(engine); - stepper.setEnabled(true); - engine.pauseAt({ frames: frames(lossy(app('leaf', 5)), app('caller', 14)) }); await stepper.request('stepOut', { threadId: 1 }); await settled(); + expect(delivered).toHaveLength(1); expect(stopped()).toMatchObject({ reason: 'exception' }); - expect(armedAtDelivery).toBe(0); + expect(commands()).toEqual(['Debugger.stepOut']); }); - it('waits on when js-debug resumes it by itself, and lands by the net (issue #1162, in a step-in walk)', async () => { + it('waits on when js-debug resumes a pause of its own: the step is lost with it (issue #1162), and the next stop goes out as itself', async () => { engine.pauseAt({ frames: frames(app('main', 10)) }); engine.script = [ { frames: frames(node('require', 1), app('main', 10)) }, // js-debug's module-entry breakpoint: paused and resumed by js-debug. V8 dropped the step. { frames: frames(app('mod', 0, { script: 'mod' }), node('require', 2), app('main', 10)), reason: 'ambiguous', hits: ['js-debug:entry'], resumedByJsDebug: true }, - { frames: frames(app('main', 11)), reason: 'other', hits: (armed) => [armed[0].id] } + // The program runs on to a breakpoint of the caller's. + { frames: frames(app('later', 30), app('main', 20)), reason: 'other', hits: ['js-debug:7'], dapReason: 'breakpoint' } ]; await stepper.request('stepIn', { threadId: 1 }); await settled(); - // Nothing was sent after js-debug's resume: the net was already there. + // Nothing was sent after js-debug's resume. expect(commands()).toEqual(['Debugger.stepInto', 'Debugger.stepInto']); - expect(stopped()).toMatchObject({ reason: 'step' }); + expect(delivered).toHaveLength(1); + expect(stopped()).toMatchObject({ reason: 'breakpoint', description: 'Paused on breakpoint' }); // Two kept pauses, two stopped events withheld; the resumed one had none. - expect(seen.filter((e) => e.event === 'stopped')).toHaveLength(2); - expect(engine.armed).toEqual([]); + expect(seen.filter((e) => e.event === 'stopped')).toEqual(Array(2).fill({ event: 'stopped', withheld: true })); }); }); @@ -848,29 +583,29 @@ describe('JsStepper (issue #1130)', () => { }); describe('what ends a step still in flight', () => { + /** A step out with no landing yet: the program runs, and the chain waits for V8's next pause. */ async function stepOutAndRun(): Promise { - engine.pauseAt({ frames: frames(lossy(app('work', 9)), app('main', 14)) }); + engine.pauseAt({ frames: frames(app('work', 9), app('main', 14)) }); engine.script = ['runs']; await stepper.request('stepOut', { threadId: 1 }); await tick(10); - // The program is running toward the net; the chain waits. expect(stepper.describe()).toMatchObject({ chain: true }); - expect(engine.armed.length).toBeGreaterThan(0); + // The step is V8's own: the command went out and nothing else, no + // temporary breakpoint (a step V8 loses stays lost, issue #1161). + expect(engine.calls.map((c) => c.method)).toEqual(['Debugger.stepOut']); } - it('a continue request: the net is removed before the request goes on', async () => { + it('a continue request ends it', async () => { await stepOutAndRun(); await stepper.beforeRequest('continue'); - expect(engine.armed).toEqual([]); - expect(stepper.describe()).toMatchObject({ chain: false, nets: 0 }); + expect(stepper.describe()).toMatchObject({ chain: false }); expect(delivered).toEqual([]); }); - it.each(['disconnect', 'terminate', 'restart', 'goto', 'restartFrame'])('a %s request ends it too, net removed first', async (command) => { + it.each(['disconnect', 'terminate', 'restart', 'goto', 'restartFrame'])('a %s request ends it too', async (command) => { await stepOutAndRun(); await stepper.beforeRequest(command); - expect(engine.armed).toEqual([]); - expect(stepper.describe()).toMatchObject({ chain: false, nets: 0 }); + expect(stepper.describe()).toMatchObject({ chain: false }); }); it('a request that neither resumes nor ends the target leaves it alone', async () => { @@ -878,32 +613,23 @@ describe('JsStepper (issue #1130)', () => { await stepper.beforeRequest('stackTrace'); await stepper.beforeRequest('pause'); expect(stepper.describe()).toMatchObject({ chain: true }); - expect(engine.armed.length).toBeGreaterThan(0); }); - it('the CDP socket closing: nothing can be removed, and nothing throws', async () => { + it('the CDP socket closing ends it, and nothing throws', async () => { await stepOutAndRun(); stepper.detachCdp(); await tick(10); - expect(stepper.describe()).toMatchObject({ chain: false, nets: 0, paused: false }); + expect(stepper.describe()).toMatchObject({ chain: false, paused: false }); expect(stepper.handles('next')).toBe(false); }); - it('a later landing of that step is still reported: stepping over an await that takes a while', async () => { + it('a later landing of that step is still reported: the call it steps out of took a while', async () => { await stepOutAndRun(); - // The awaited work is done: V8 reaches the net. - engine.script = []; - const pause: ScriptedPause = { frames: frames(app('main', 15)), reason: 'other', hits: [engine.armed[0].id] }; - engine.current = pause; - engine.emit('cdp-event', 'Debugger.paused', { - reason: 'other', - hitBreakpoints: pause.hits, - callFrames: [{ functionName: 'main', functionLocation: { scriptId: 'app', lineNumber: fnLineOf(app('main', 0)), columnNumber: 0 }, location: { scriptId: 'app', lineNumber: 15, columnNumber: 0 } }] - }); - seen.push({ event: 'stopped', withheld: stepper.withholds({ seq: 0, type: 'event', event: 'stopped', body: { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [] } }) }); + // The call returns at last: V8's step lands. + engine.arrive({ frames: frames(app('main', 15)) }); await settled(); + expect(delivered).toHaveLength(1); expect(stopped()).toMatchObject({ reason: 'step' }); - expect(engine.armed).toEqual([]); }); }); @@ -926,50 +652,7 @@ describe('JsStepper (issue #1130)', () => { stepper.setEnabled(true); } - /** How many net breakpoints were set in V8 when each step command went out. */ - function armedAtEachStep(): number[] { - const counts: number[] = []; - const send = engine.send.bind(engine); - engine.send = (async (method: string, params?: Record) => { - if (/Debugger\.step/.test(method)) { - counts.push(engine.armed.length); - } - return send(method, params); - }) as typeof engine.send; - return counts; - } - - describe('a net is a safeguard: a step never fails for one', () => { - /** Node's own code on a skip list that leaves it out: not marked skipped, and V8 refuses its break positions. */ - const timers = (fn: string, line: number): Frame => ({ fn, line, script: 'node:timers' }); - - it('serves the step with V8 alone when V8 refuses break positions for the frame it returns to', async () => { - engine.refuse.add('node:timers'); - engine.pauseAt({ frames: frames(lossy(app('onTimer', 5)), timers('listOnTimeout', 605), timers('processTimers', 541)) }); - engine.script = [{ frames: frames(timers('listOnTimeout', 609), timers('processTimers', 541)) }]; - - const response = await stepper.request('stepOut', { threadId: 1 }); - expect(response).toMatchObject({ success: true }); - await settled(); - - expect(commands()).toEqual(['Debugger.stepOut']); - expect(stopped()).toMatchObject({ reason: 'step' }); - expect(setBreakpoints()).toBe(0); - }); - - it('goes on with V8 alone when the net cannot be set at a skipped landing', async () => { - engine.refuse.add('weird'); - engine.pauseAt({ frames: frames(app('listener', 40), node('emit', 7), app('caller', 10, { script: 'weird' })) }); - engine.script = [ - { frames: frames(node('emit', 8), app('caller', 10, { script: 'weird' })) }, - { frames: frames(app('caller', 11, { script: 'weird' })) } - ]; - await stepper.request('next', { threadId: 1 }); - await settled(); - expect(commands()).toEqual(['Debugger.stepOver', 'Debugger.stepOut']); - expect(stopped()).toMatchObject({ reason: 'step' }); - }); - + describe('when V8 or js-debug does not answer as asked', () => { it('reports a stop when the chain fails while V8 is paused: the caller is never left without one', async () => { engine.pauseAt({ frames: frames(app('listener', 40), node('emit', 7), app('main', 10)) }); engine.script = [{ frames: frames(node('emit', 8), app('main', 10)) }]; @@ -979,28 +662,7 @@ describe('JsStepper (issue #1130)', () => { await settled(); expect(delivered).toHaveLength(1); expect(stopped()).toMatchObject({ reason: 'step' }); - expect(engine.armed).toEqual([]); - expect(stepper.describe()).toMatchObject({ chain: false, nets: 0 }); - }); - - it('a first command V8 refuses leaves no net behind', async () => { - engine.pauseAt({ frames: frames(lossy(app('leaf', 5)), app('caller', 14)) }); - engine.failOnce = 'Debugger.stepOut'; - await expect(stepper.request('stepOut', { threadId: 1 })).rejects.toThrow(/refused/); - // The net on the caller was set before the command, and is gone. - expect(setBreakpoints()).toBeGreaterThan(0); - expect(engine.armed).toEqual([]); - expect(stepper.describe()).toMatchObject({ chain: false, nets: 0 }); - }); - - it('counts a net with no breakpoint set as no net', async () => { - engine.failAlways.add('Debugger.setBreakpoint'); - engine.pauseAt({ frames: frames(lossy(app('leaf', 5)), app('caller', 14)) }); - engine.script = ['runs']; - await stepper.request('stepOut', { threadId: 1 }); - await tick(5); - expect(stepper.describe()).toMatchObject({ chain: true, nets: 0 }); - await stepper.beforeRequest('continue'); + expect(stepper.describe()).toMatchObject({ chain: false }); }); it('asks again for the stack while js-debug says it is not paused yet, rather than taking it for an empty one', async () => { @@ -1031,28 +693,42 @@ describe('JsStepper (issue #1130)', () => { expect(commands()).toEqual(['Debugger.stepOver', 'Debugger.stepOut']); expect(stopped()).toMatchObject({ reason: 'step' }); }); + + it('steps out with V8 alone, and does not resume, when js-debug never says what is below', async () => { + // A first step teaches the stepper that Node's script is skipped. + engine.pauseAt({ frames: frames(app('main', 10)) }); + engine.script = [{ frames: frames(node('log', 1), app('main', 10)) }, { frames: frames(app('main', 11)) }]; + await stepper.request('stepIn', { threadId: 1 }); + await settled(); + delivered.length = 0; + engine.calls.length = 0; + + engine.pauseAt({ frames: frames(app('listener', 40), node('emit', 7), app('main', 10)) }); + engine.script = [{ frames: frames(node('emit', 8), app('main', 10)) }, { frames: frames(app('main', 11)) }]; + await stepper.request('next', { threadId: 1 }); + engine.stackTraceFailures = 1e6; + await settled(); + expect(commands()).toEqual(['Debugger.stepOver', 'Debugger.stepOut']); + expect(stopped()).toMatchObject({ reason: 'step' }); + }); }); describe('an async function the event loop resumed', () => { - it('steps out by V8 alone: its own async step finds the one awaiting call, and nothing off the stack is ever netted', async () => { + it('steps out by V8 alone: its own async step finds the one awaiting call', async () => { engine.pauseAt({ frames: frames(app('inner', 5)), asyncParent: { fn: 'handler', line: 9, col: 14 } }); engine.script = [{ frames: frames(app('handler', 10)), asyncParent: { fn: 'main', line: 14 } }]; await stepper.request('stepOut', { threadId: 1 }); await settled(); - expect(setBreakpoints()).toBe(0); expect(commands()).toEqual(['Debugger.stepOut']); expect(stopped()).toMatchObject({ reason: 'step' }); expect(stopped().text).toBeUndefined(); }); - - it('does not take what only scheduled the code for what it returns to: a step out of a `.then` callback resumes', async () => { engine.pauseAt({ frames: frames(app('onDone', 3)), asyncParent: { fn: 'work', line: 7, description: 'Promise.then' } }); engine.script = [{ frames: frames(node('processTimers', 527)) }, 'runs']; await stepper.request('stepOut', { threadId: 1 }); await settled(); - expect(setBreakpoints()).toBe(0); expect(commands()).toEqual(['Debugger.stepOut', 'Debugger.resume']); expect(delivered).toEqual([]); }); @@ -1067,7 +743,6 @@ describe('JsStepper (issue #1130)', () => { await settled(); expect(commands()).toEqual(['Debugger.stepOut', 'Debugger.stepOut']); expect(stopped()).toMatchObject({ reason: 'step' }); - expect(setBreakpoints()).toBe(0); }); it('resumes once the awaiting chain ends in skipped code: no walk through the next tasks', async () => { @@ -1083,18 +758,6 @@ describe('JsStepper (issue #1130)', () => { expect(commands()).toEqual(['Debugger.stepOut', 'Debugger.stepOut', 'Debugger.resume']); expect(delivered).toEqual([]); }); - - - it('reads `finally` in the function\'s own text only', async () => { - const start = fnLineOf(app('plainF', 0)); - // Another function, further down the script. - sourceWith({ [start + 40]: 'try { a(); } finally { b(); }' }); - engine.pauseAt({ frames: frames(app('plainF', start + 2), app('caller', 14)) }); - engine.script = [{ frames: frames(app('plainF', start + 3), app('caller', 14)) }]; - await stepper.request('next', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBe(0); - }); }); describe('the sentence on a step-in that reached nothing of the program', () => { @@ -1116,15 +779,15 @@ describe('JsStepper (issue #1130)', () => { expect(stopped().text).toBeUndefined(); }); - it('steps in again when the net brings it back to its own line, and says how far the walk went when it ends in the frame it left', async () => { + it('steps in again when the step-out brings it back to its own line, and says how far the walk went when it ends in the frame it left', async () => { withTunables({ budget: 2 }); engine.pauseAt({ frames: frames(app('main', 10)) }); engine.script = [ { frames: frames(node('log', 1), app('main', 10)) }, { frames: frames(node('log', 2), app('main', 10)) }, { frames: frames(node('log', 3), app('main', 10)) }, - // What the real walk out of console.log does: V8's step-out and the net agree, mid-line. - { frames: frames(app('main', 10, { col: 14 })), reason: 'ambiguous', hits: (armed) => [armed[0].id] }, + // V8's step-out stops once more on the call's own line, mid-line. + { frames: frames(app('main', 10, { col: 14 })) }, { frames: frames(app('main', 11)) } ]; await stepper.request('stepIn', { threadId: 1 }); @@ -1151,7 +814,6 @@ describe('JsStepper (issue #1130)', () => { expect(commands()).toEqual(['Debugger.stepOver']); expect(delivered).toHaveLength(1); expect(stopped()).toMatchObject({ reason: 'pause' }); - expect(setBreakpoints()).toBe(0); }); it('is reported as a pause in program code too, not as the step', async () => { @@ -1170,20 +832,19 @@ describe('JsStepper (issue #1130)', () => { }); describe('edges the mutation pass found unpinned', () => { - it('a new step gives up the one in flight: its nets are gone before the new command', async () => { - engine.pauseAt({ frames: frames(lossy(app('work', 9)), app('main', 14)) }); + it('a new step gives up the one in flight', async () => { + engine.pauseAt({ frames: frames(app('work', 9), app('main', 14)) }); engine.script = ['runs']; await stepper.request('stepOut', { threadId: 1 }); await tick(10); - expect(engine.armed.length).toBeGreaterThan(0); + expect(stepper.describe()).toMatchObject({ chain: true }); // V8 is paused again by something else, and the caller steps from there. engine.pauseAt({ frames: frames(app('other', 50), app('main', 14)), reason: 'other' }); engine.script = [{ frames: frames(app('other', 51), app('main', 14)) }]; - const armed = armedAtEachStep(); await stepper.request('next', { threadId: 1 }); await settled(); - expect(armed).toEqual([0]); + expect(commands()).toEqual(['Debugger.stepOut', 'Debugger.stepOver']); expect(delivered).toHaveLength(1); expect(stopped()).toMatchObject({ reason: 'step' }); }); @@ -1256,8 +917,7 @@ describe('JsStepper (issue #1130)', () => { release(); await tick(20); expect(commands()).toEqual(['Debugger.stepInto']); - expect(engine.armed).toEqual([]); - expect(stepper.describe()).toMatchObject({ chain: false, nets: 0 }); + expect(stepper.describe()).toMatchObject({ chain: false }); expect(delivered).toEqual([]); }); @@ -1270,49 +930,14 @@ describe('JsStepper (issue #1130)', () => { await stepper.beforeRequest('continue'); }); - it('a net at the landing\'s own depth guards nothing below it: the stack is gone, and the program resumes', async () => { - engine.pauseAt({ frames: frames(lossy(app('work', 9)), app('main', 14)) }); + it('a step-out that comes back in another task, with nothing of the program below, resumes the program', async () => { + engine.pauseAt({ frames: frames(app('work', 9), app('main', 14)) }); // V8's step-out comes back in the next task: Node's own code, nothing of the program under it. engine.script = [{ frames: frames(node('processTicksAndRejections', 70)) }, 'runs']; await stepper.request('stepOut', { threadId: 1 }); await settled(); expect(commands()).toEqual(['Debugger.stepOut', 'Debugger.resume']); expect(delivered).toEqual([]); - expect(engine.armed).toEqual([]); - }); - - it('a net hit deeper than the frame it guards, on a step over: the net is dropped and V8\'s own step-outs finish at the origin depth', async () => { - const start = fnLineOf(app('guardedF', 0)); - sourceWith({ [start + 2]: 'try { return work(); } finally { done(); }' }); - engine.pauseAt({ frames: frames(app('guardedF', start + 2), app('g', 14)) }); - engine.script = [ - // work() called g again: a net position of g, three frames above the call it guards. - { frames: frames(app('g', 15), app('work', 70), app('guardedF', start + 2), app('g', 14)), reason: 'ambiguous', hits: (armed) => [armed[0].id] }, - { frames: frames(app('work', 71), app('guardedF', start + 2), app('g', 14)) }, - { frames: frames(app('guardedF', start + 3), app('g', 14)) } - ]; - const armed = armedAtEachStep(); - await stepper.request('next', { threadId: 1 }); - await settled(); - expect(commands()).toEqual(['Debugger.stepOver', 'Debugger.stepOut', 'Debugger.stepOut']); - expect(armed[0]).toBeGreaterThan(0); - expect(armed.slice(1)).toEqual([0, 0]); - expect(stopped()).toMatchObject({ reason: 'step' }); - }); - - it('and when the dropped net fired no deeper than the step began, that is the landing', async () => { - const start = fnLineOf(app('guardedH', 0)); - sourceWith({ [start + 2]: 'try { return work(); } finally { done(); }' }); - engine.pauseAt({ frames: frames(app('guardedH', start + 2), app('x', 20), app('g', 14)) }); - engine.script = [ - { frames: frames(app('x', 21), app('x', 20), app('g', 14)), reason: 'ambiguous', hits: (armed) => [armed[0].id] }, - 'runs' - ]; - await stepper.request('next', { threadId: 1 }); - await settled(); - expect(commands()).toEqual(['Debugger.stepOver']); - expect(stopped()).toMatchObject({ reason: 'step' }); - expect(engine.armed).toEqual([]); }); it('a step-in that lands on its own line in a deeper call of the same function has landed', async () => { @@ -1347,35 +972,6 @@ describe('JsStepper (issue #1130)', () => { expect(stopped()).toMatchObject({ reason: 'step' }); }); - it('a step-in under a net that stops in a deeper frame of the program has landed there', async () => { - engine.pauseAt({ frames: frames(app('main', 10)) }); - engine.script = [ - { frames: frames(node('log', 1), app('main', 10)) }, - // Node's code called back into main's own function: a net position, deeper. - { frames: frames(app('main', 15), node('cb', 4), node('log', 2), app('main', 10)), reason: 'ambiguous', hits: (armed) => [armed[0].id] }, - 'runs' - ]; - await stepper.request('stepIn', { threadId: 1 }); - await settled(); - expect(commands()).toEqual(['Debugger.stepInto', 'Debugger.stepInto']); - expect(stopped()).toMatchObject({ reason: 'step' }); - expect(engine.armed).toEqual([]); - }); - - it('waits for js-debug\'s own verdict on a pause that is not the stepper\'s, however its earlier reports stand', async () => { - engine.pauseAt({ frames: frames(lossy(app('work', 9)), app('main', 14)) }); - engine.script = ['runs']; - await stepper.request('stepOut', { threadId: 1 }); - await tick(10); - // js-debug's module-entry breakpoint: it resumes the pause itself. Nothing was kept so far, and nothing reported. - engine.script = [{ frames: frames(app('main', 15)), reason: 'other', hits: (armed) => [armed[0].id] }]; - engine.arrive({ frames: frames(app('mod', 0, { script: 'mod' }), app('work', 9), app('main', 14)), reason: 'other', hits: ['js-debug:entry'], resumedByJsDebug: true }); - await settled(); - expect(delivered).toHaveLength(1); - expect(stopped()).toMatchObject({ reason: 'step' }); - expect(commands()).toEqual(['Debugger.stepOut']); - }); - it('takes a landing js-debug never answers for as program code, once the ceiling is passed', async () => { engine.pauseAt({ frames: frames(app('main', 10)) }); engine.script = [{ frames: frames(app('main', 11)) }, 'runs']; @@ -1399,82 +995,7 @@ describe('JsStepper (issue #1130)', () => { }); }); - // ----- the one rule for where a net is set (what the second review found) ----- - - describe('a net only where a hit proves the step came back', () => { - it('spares the breakpoints for a plain function whose text names nothing that closes through a finally', async () => { - engine.pauseAt({ frames: frames(app('plainOut', 5), app('caller', 14)) }); - engine.script = [{ frames: frames(app('caller', 15)) }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBe(0); - expect(stopped()).toMatchObject({ reason: 'step' }); - }); - - - - - - it.each([ - ['after the closing brace', '} finally {'], - ['before its own brace', 'finally {'], - ['alone on its line', ' finally'] - ])('reads a finally clause written %s', async (_what, text) => { - const start = fnLineOf(app('claused', 0)); - sourceWith({ [start + 4]: text }); - engine.pauseAt({ frames: frames(app('claused', start + 2), app('caller', 14)) }); - engine.script = [{ frames: frames(app('caller', 15)) }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBeGreaterThan(0); - }); - - it('sets none for a callback nothing of the program called: what registered it is not on the stack', async () => { - // A `.then` callback with a finally clause: its async parent registered it, and is not what it returns to. - engine.pauseAt({ frames: frames(lossy(app('onDone', 3))), asyncParent: { fn: 'work', line: 7, description: 'Promise.then' } }); - engine.script = ['runs']; - await stepper.request('stepOut', { threadId: 1 }); - await tick(5); - expect(setBreakpoints()).toBe(0); - await stepper.beforeRequest('continue'); - }); - - - it('steps out with V8 alone, and does not resume, when js-debug never says what is below', async () => { - // A first step teaches the stepper that Node's script is skipped. - engine.pauseAt({ frames: frames(app('main', 10)) }); - engine.script = [{ frames: frames(node('log', 1), app('main', 10)) }, { frames: frames(app('main', 11)) }]; - await stepper.request('stepIn', { threadId: 1 }); - await settled(); - delivered.length = 0; - engine.calls.length = 0; - - engine.pauseAt({ frames: frames(app('listener', 40), node('emit', 7), app('main', 10)) }); - engine.script = [{ frames: frames(node('emit', 8), app('main', 10)) }, { frames: frames(app('main', 11)) }]; - await stepper.request('next', { threadId: 1 }); - engine.stackTraceFailures = 1e6; - await settled(); - expect(commands()).toEqual(['Debugger.stepOver', 'Debugger.stepOut']); - expect(stopped()).toMatchObject({ reason: 'step' }); - }); - }); - - describe('more edges the second mutation pass found unpinned', () => { - it('reports a pause taken on one of its own net positions as the pause, though js-debug calls it a breakpoint', async () => { - engine.pauseAt({ frames: frames(lossy(app('work', 9)), app('main', 14)) }); - engine.script = ['runs']; - await stepper.request('stepOut', { threadId: 1 }); - await tick(10); - await stepper.beforeRequest('pause'); - engine.arrive({ frames: frames(app('main', 15)), reason: 'other', hits: [engine.armed[0].id] }); - await settled(); - expect(delivered).toHaveLength(1); - expect(stopped()).toMatchObject({ reason: 'pause', description: 'Paused' }); - expect(stopped().hitBreakpointIds).toBeUndefined(); - expect(engine.armed).toEqual([]); - }); - it('sends nothing more when the pause is asked for while a landing is being judged, and reports that landing as the pause', async () => { let gated = false; let release: () => void = () => undefined; @@ -1509,7 +1030,6 @@ describe('JsStepper (issue #1130)', () => { expect(commands()).toEqual(['Debugger.stepInto']); expect(delivered).toHaveLength(1); expect(stopped()).toMatchObject({ reason: 'pause' }); - expect(engine.armed).toEqual([]); }); it('reports where it is when V8 refuses the resume of a stack that is gone', async () => { @@ -1522,10 +1042,8 @@ describe('JsStepper (issue #1130)', () => { expect(stopped()).toMatchObject({ reason: 'step' }); }); - it('owes a late report that names no breakpoint only to a step that kept a net\'s pause, and only for a while', async () => { - // (The stepper reads a script's text once: the function of the second step is written first.) - const work = lossy(app('work', 9)); - // A step with no net: a `breakpoint` naming none right after it is somebody else's stop. + it('owes a late report only as a pause or a step, and only for a while', async () => { + // js-debug's stopped for the step never comes in time. engine.pauseAt({ frames: frames(app('main', 10)) }); engine.script = [{ frames: frames(app('main', 11)) }]; engine.onDap = (event) => { @@ -1534,24 +1052,14 @@ describe('JsStepper (issue #1130)', () => { await stepper.request('next', { threadId: 1 }); await settled(); expect(stepper.describe().owed).toBe(1); + // A `breakpoint` naming none right after it is somebody else's stop, and leaves the count alone. expect(stepper.withholds({ seq: 0, type: 'event', event: 'stopped', body: { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [] } })).toBe(false); - - // A step that landed by its net owes exactly that. - engine.pauseAt({ frames: frames(work, app('main', 14)) }); - engine.script = [{ frames: frames(app('main', 15)), reason: 'other', hits: (armed) => [armed[0].id] }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); expect(stepper.describe().owed).toBe(1); - expect(stepper.withholds({ seq: 0, type: 'event', event: 'stopped', body: { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [7] } })).toBe(false); - expect(stepper.withholds({ seq: 0, type: 'event', event: 'stopped', body: { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [] } })).toBe(true); // And not for ever: past the ceiling nothing is owed. - engine.pauseAt({ frames: frames(app('main', 20)) }); - engine.script = [{ frames: frames(app('main', 21)) }]; - await stepper.request('next', { threadId: 1 }); - await settled(); await tick(200); expect(stepper.withholds({ seq: 0, type: 'event', event: 'stopped', body: { reason: 'pause', threadId: 1 } })).toBe(false); + expect(stepper.describe().owed).toBe(0); }); it('says how far the walk went only for a step back in the very frame it left: not a deeper call of the same function', async () => { @@ -1561,112 +1069,18 @@ describe('JsStepper (issue #1130)', () => { engine.script = [ { frames: frames(node('log', 1), app('recur', start + 1), app('main', 10)) }, { frames: frames(node('log', 2), app('recur', start + 1), app('main', 10)) }, - // Stepped out: Node's code had called recur again, one frame deeper. - { frames: frames(app('recur', start + 3), node('cb', 4), app('recur', start + 1), app('main', 10)), reason: 'ambiguous', hits: (armed) => [armed[0].id] } + // Stepped out, back on the line: its next call is recur again, one frame deeper. + { frames: frames(app('recur', start + 1, { col: 14 }), app('main', 10)) }, + { frames: frames(app('recur', start + 1), app('recur', start + 1, { col: 14 }), app('main', 10)) } ]; await stepper.request('stepIn', { threadId: 1 }); await settled(); + expect(commands()).toEqual(['Debugger.stepInto', 'Debugger.stepInto', 'Debugger.stepOut', 'Debugger.stepInto']); expect(stopped()).toMatchObject({ reason: 'step' }); expect(stopped().text).toBeUndefined(); }); }); - // ----- the provable rule: rule (a), the frame being left; rule (b), the frame guarded ----- - - - describe('V8\'s word on the guarded frame: a net only below frames that come down by returning', () => { - it.each([ - ['an async function', 'async function'], - ['a generator', 'generator'], - ['module code that may await', 'module code'] - ])('sets none when the function being left is %s, whatever it contains', async (_what) => { - engine.pauseAt({ frames: frames(lossy(app('suspender', 5, { resumable: true })), app('caller', 14)) }); - engine.script = [{ frames: frames(app('caller', 15)) }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBe(0); - expect(stopped()).toMatchObject({ reason: 'step' }); - }); - - it('sets none when the caller is async, though the function being left is plain: it can suspend before any position', async () => { - engine.pauseAt({ frames: frames(lossy(app('innerSync', 30)), app('handler', 14, { resumable: true })) }); - engine.script = [{ frames: frames(app('handler', 15, { resumable: true })) }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBe(0); - }); - - it('nets a plain caller of a plain function, whatever is below the caller', async () => { - engine.pauseAt({ frames: frames(lossy(app('innerSync', 30)), app('handler', 14), app('main', 40, { resumable: true })) }); - engine.script = [{ frames: frames(app('handler', 15), app('main', 40, { resumable: true })), reason: 'other', hits: (armed) => [armed[0].id] }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBeGreaterThan(0); - expect(stopped()).toMatchObject({ reason: 'step' }); - expect(engine.armed).toEqual([]); - }); - - it('sets none when async skipped code stands between: it can suspend and hand control down', async () => { - engine.pauseAt({ frames: frames(lossy(app('callback', 40)), node('readFile', 7, { resumable: true }), app('main', 10)) }); - engine.script = [{ frames: frames(app('main', 11)) }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBe(0); - }); - - it('nets through plain skipped code: Node\'s own code is not read', async () => { - engine.pauseAt({ frames: frames(app('listener', 40), node('emit', 7), app('main', 10)) }); - engine.script = [ - { frames: frames(node('emit', 8), app('main', 10)) }, - { frames: frames(app('main', 11)), reason: 'other', hits: (armed) => [armed[0].id] } - ]; - await stepper.request('next', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBeGreaterThan(0); - expect(commands()).toEqual(['Debugger.stepOver', 'Debugger.stepOut']); - expect(stopped()).toMatchObject({ reason: 'step' }); - }); - - it('sets none when V8 does not say whether a frame can be restarted', async () => { - engine.pauseAt({ frames: frames(lossy(app('leaf', 5)), app('caller', 14)), noRestartInfo: true }); - engine.script = [{ frames: frames(app('caller', 15)), noRestartInfo: true }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBe(0); - }); - - it.each([ - ['a comment that says await', '// nothing to await here'], - ['a nested async callback', 'items.map(async (item) => { await send(item); });'], - ['a loop', 'for (const item of items) { use(item); }'] - ])('nets a plain function whatever its text says: %s', async (_what, text) => { - const start = fnLineOf(app('plainWith', 0)); - sourceWith({ [start + 1]: text, [start + 4]: 'try { return x(); } finally { done(); }' }); - engine.pauseAt({ frames: frames(app('plainWith', start + 2), app('caller', 14)) }); - engine.script = [{ frames: frames(app('caller', 15)), reason: 'other', hits: (armed) => [armed[0].id] }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBeGreaterThan(0); - expect(stopped()).toMatchObject({ reason: 'step' }); - expect(stopped().text).toBeUndefined(); - expect(engine.armed).toEqual([]); - }); - - it.each([ - ['a return out of for...of', 'for (const item of items) { if (item) return item; }'], - ['a using declaration', 'using handle = open();'] - ])('nets the exits V8 loses with no finally written: %s', async (_what, text) => { - const start = fnLineOf(app('implicit', 0)); - sourceWith({ [start + 3]: text }); - engine.pauseAt({ frames: frames(app('implicit', start + 2), app('caller', 14)) }); - engine.script = [{ frames: frames(app('caller', 15)), reason: 'other', hits: (armed) => [armed[0].id] }]; - await stepper.request('stepOut', { threadId: 1 }); - await settled(); - expect(setBreakpoints()).toBeGreaterThan(0); - expect(stopped()).toMatchObject({ reason: 'step' }); - }); - }); - describe('a pause asked for while the stack turns out to be gone', () => { it('does not resume the program: V8 is paused, and that stop is the caller\'s', async () => { let gated = false; @@ -1706,11 +1120,10 @@ describe('JsStepper (issue #1130)', () => { }); }); - it('refuses a step it cannot start, and leaves no net behind', async () => { + it('refuses a step it cannot start, and leaves no chain behind', async () => { engine.pauseAt({ frames: frames(app('leaf', 5), app('caller', 14)) }); engine.current = null; // V8 resumed behind the stepper's back await expect(stepper.request('stepOut', { threadId: 1 })).rejects.toThrow(/while paused/); - expect(engine.armed).toEqual([]); - expect(stepper.describe()).toMatchObject({ chain: false, nets: 0 }); + expect(stepper.describe()).toMatchObject({ chain: false }); }); }); From a2db462f5036b07ca1015176bce53b1aac09bbc1 Mon Sep 17 00:00:00 2001 From: JF Date: Wed, 18 Nov 2026 03:04:22 -0500 Subject: [PATCH 17/24] fix(javascript): a pause in program code is the landing; the walk has two bounds; a bundle's lines are asked about each time (#1130) An independent review of this branch found the stepper worse than main in four places. Each is now a row in an A/B gate (main against this branch, three runs a row, kept outside the repository) and is fixed here. - A bundle. js-debug's "skipped" verdict was remembered per script, but js-debug decides per original source: one stop in a bundled dependency made the program's own lines of that script count as skipped, and steps ran past them. The verdict is remembered only when js-debug names the source ; everything else is asked at each landing. - The walk. A step_into through skipped code gave up after 24 engine steps, before a once() listener (35 steps) or a custom util.inspect function. It now walks while it is inside two bounds, whichever comes first: 512 engine steps taken in skipped code, or 3 s from its first landing there. Then it steps out, and the message names the bound. - The origin line. A step_into that came back to its origin line stepped in again, which ran a one-line loop through many iterations. In the traces V8's step-out lands on the caller's next break position, never back on the call it left, so a pause in program code is the landing. - The pending sentence. "The step left the frame it started in" was added to steps that never left it. The stepper records the one case it knows (it resumed the program because nothing of the program was below) as a proxy event of its own, the sentence is added only then, and it says the step will not land. The docs say what was measured, per host. On Linux an engine step costs about 44 ms (#1163), so the time bound comes first there, at about 60 engine steps. Measured: on Windows the gate passes, 101 rows, 96 the same as main and 5 better. On Linux (walk, require and review rows) one row is worse than main and is not fixed here: a custom util.inspect function behind console.log is entered by main after 4.5 s and not by this branch, whose walk ends at 3 s. A step_into on a built-in require is lost there, where main stops three lines late. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn69pXrYMWc1JUwv5v8 --- .gitignore | 6 + changelog.d/1130.fixed.md | 2 +- docs/javascript/README.md | 33 +- docs/tool-reference.md | 58 ++-- .../src/interfaces/adapter-policy-js.ts | 34 +- .../shared/src/interfaces/adapter-policy.ts | 7 + src/proxy/dap-proxy-interfaces.ts | 7 + src/proxy/dap-proxy-worker.ts | 10 +- src/proxy/js-stepper.ts | 126 ++++--- src/server/tool-schemas.ts | 2 +- src/session/execution/execution-controller.ts | 42 ++- src/utils/error-messages.ts | 29 +- .../javascript-step-skipped-code.test.ts | 125 ++++++- .../bp-assert.va-explicit.container-true.json | 2 +- ...bp-assert.va-explicit.container-unset.json | 2 +- .../bp-assert.va-open.container-true.json | 2 +- .../bp-assert.va-open.container-unset.json | 2 +- .../bp-assert.va-unset.container-true.json | 2 +- .../bp-assert.va-unset.container-unset.json | 2 +- ...bp-content.va-explicit.container-true.json | 2 +- ...p-content.va-explicit.container-unset.json | 2 +- .../bp-content.va-open.container-true.json | 2 +- .../bp-content.va-open.container-unset.json | 2 +- .../bp-content.va-unset.container-true.json | 2 +- .../bp-content.va-unset.container-unset.json | 2 +- .../bp-line.va-explicit.container-true.json | 2 +- .../bp-line.va-explicit.container-unset.json | 2 +- .../bp-line.va-open.container-true.json | 2 +- .../bp-line.va-open.container-unset.json | 2 +- .../bp-line.va-unset.container-true.json | 2 +- .../bp-line.va-unset.container-unset.json | 2 +- .../bp-unset.va-explicit.container-true.json | 2 +- .../bp-unset.va-explicit.container-unset.json | 2 +- .../bp-unset.va-open.container-true.json | 2 +- .../bp-unset.va-open.container-unset.json | 2 +- .../bp-unset.va-unset.container-true.json | 2 +- .../bp-unset.va-unset.container-unset.json | 2 +- .../unit/session/session-manager-dap.test.ts | 64 ++++ .../bundle/node_modules/blib/index.js | 11 + .../step-skipped-code/bundle/out/bundle.js | 43 +++ .../bundle/out/bundle.js.map | 7 + .../step-skipped-code/bundle/src/app.js | 17 + .../javascript/step-skipped-code/steps.cjs | 14 +- .../dap-proxy-worker-live-update.test.ts | 12 +- tests/proxy/js-stepper.test.ts | 324 +++++++++++++----- tests/unit/shared/adapter-policy-js.test.ts | 24 +- 46 files changed, 797 insertions(+), 248 deletions(-) create mode 100644 tests/fixtures/javascript/step-skipped-code/bundle/node_modules/blib/index.js create mode 100644 tests/fixtures/javascript/step-skipped-code/bundle/out/bundle.js create mode 100644 tests/fixtures/javascript/step-skipped-code/bundle/out/bundle.js.map create mode 100644 tests/fixtures/javascript/step-skipped-code/bundle/src/app.js diff --git a/.gitignore b/.gitignore index 3bee4d9fc..646d9065e 100644 --- a/.gitignore +++ b/.gitignore @@ -24,6 +24,12 @@ tests/**/*.js.map # negation, `git add` silently skips new fixtures (how PR #252 lost one) !tests/fixtures/debug-scripts/*.js !tests/fixtures/javascript/subprocess-tree/*.js +# The JavaScript stepper's bundle fixture (issue #1130): an esbuild bundle, its +# source map, and both of its sources, the dependency under node_modules/ where +# the bundler found it. Hand-written fixtures, not build output. +!tests/fixtures/javascript/step-skipped-code/bundle/node_modules/ +!tests/fixtures/javascript/step-skipped-code/bundle/**/*.js +!tests/fixtures/javascript/step-skipped-code/bundle/**/*.js.map # Package source compilation artifacts packages/*/src/**/*.js diff --git a/changelog.d/1130.fixed.md b/changelog.d/1130.fixed.md index 6012052a8..f9efd33e3 100644 --- a/changelog.d/1130.fixed.md +++ b/changelog.d/1130.fixed.md @@ -1 +1 @@ -**A JavaScript step lands where your code next runs, and is no longer lost in Node's own code.** `step_into` on a line that calls a Node builtin took about 6 s on a Linux host and answered `pending`, blaming "a long-running call"; on the first `console.log` of a process it never landed at all and the program ran to its end. js-debug's own "smart stepper" was deciding where such a step ends: while the step was in skipped code it stepped again by itself, one engine step per statement (131 for one `console.log`), with a flag that moves the step to a later task and loses it. That stepper is now off for every session, and the server steps through skipped code itself, over js-debug's raw CDP socket, for `step_into`, `step_over` and `step_out` alike. A `step_into` on a line that calls your own function through skipped code (an event listener behind `emitter.emit`, an array callback, a route handler from inside express) lands in that function; on a line whose call stays in skipped code for the whole walk (`console.log`) it lands on the next line and the message says how far the walk went (`Stepped into. step_into walked 25 engine steps into the call on that line and was still in skipped code …`) and that code of yours the call runs further in or only schedules does not stop the step; on a line that only starts a later task (`setTimeout`) it lands on the next line instead of inside the callback some time later. A `step_over` or `step_out` that returns into skipped code steps out to the nearest frame of your program below; when nothing of your program called or awaits the function (the last line of a request handler, a timer callback, a `.then` callback) the program is resumed rather than walked through the internals of later tasks (a callback of yours already queued behind a `.then` callback is where V8's own step stops), and on a launch the pending answer says the step left its frame. What counts as skipped is still js-debug's own verdict, so `justMyCode`, your `skipFiles` and source maps decide it as before, and `justMyCode: false` (or `smartStep: false`) still lands every step where V8 lands. A forked child steps the way its root session does, launched or attached. Changed on purpose: a pause asked for while a step is still pending is reported as the pause, where the program is, and is not stepped away from; and the sentence a pending step carries no longer mentions js-debug's stepper. On Linux every engine step costs about 46 ms whoever sends it (#1163), so a `step_into` on a `console.log` line still takes over a second there. Not fixed here: a `step_into` on a `require` line is still lost (Node's loader returns through `try … finally`, one of the steps V8 itself loses, #1161); `step_over` on such a line lands on the next one. (#1130) +**A JavaScript step lands where your code next runs, and is no longer lost in Node's own code.** `step_into` on a line that calls a Node builtin took about 6 s on a Linux host and answered `pending`, blaming "a long-running call"; on the first `console.log` of a process it never landed at all and the program ran to its end. js-debug's own "smart stepper" was deciding where such a step ends: while the step was in skipped code it stepped again by itself, one engine step per statement (131 for one `console.log`), with a flag that moves the step to a later task and loses it. That stepper is now off for every session, and the server steps through skipped code itself, over js-debug's raw CDP socket, for `step_into`, `step_over` and `step_out` alike. A `step_into` that lands in skipped code walks on, one engine step at a time, until your code is on top again or the walk reaches one of its two bounds, 512 engine steps or 3 s, whichever comes first; then it steps out. A `step_into` on a line that calls your own function through skipped code (an `on` or `once` event listener behind `emitter.emit`, an array callback, a route handler from inside express) lands in that function when the walk reaches it inside those bounds; on a line whose call stays in skipped code (`console.log`) it lands where the call returned, and when the walk ended on a bound first, the message says how far it went and which bound ended it (`Stepped into. step_into walked 60 engine steps into the call and was still in skipped code … when the walk reached its 3 s limit, and stepped out …`, a later `console.log` on Linux) and that code of yours the call runs further in or only schedules did not stop the step; a pause in your code on the line the step started from is where it stops (the line's next statement, or a one-line loop's header in its first iteration); on a line that only starts a later task (`setTimeout`) it lands on the next line instead of inside the callback some time later. A `step_over` or `step_out` that returns into skipped code steps out to the nearest frame of your program below; when nothing of your program called or awaits the function (the last line of a request handler, a timer callback, a `.then` callback) the program is resumed rather than walked through the internals of later tasks (a callback of yours already queued behind a `.then` callback is where V8's own step stops), and on a launch the pending answer then says the step left its frame (a step still executing, such as a `step_over` of a long call, gets no such sentence). What counts as skipped is still js-debug's own verdict, asked at every landing, so `justMyCode`, your `skipFiles` and source maps decide it as before, and in a bundle your own lines stay program code after a stop in a bundled dependency; `justMyCode: false` (or `smartStep: false`) still lands every step where V8 lands. A forked child steps the way its root session does, launched or attached. Changed on purpose: a pause asked for while a step is still pending is reported as the pause, where the program is, and is not stepped away from; and the sentence a pending step carries no longer mentions js-debug's stepper. On Linux every engine step costs about 44 ms whoever sends it (#1163), so there the walk's 3 s bound comes first, at about 60 engine steps: a `step_into` on a `console.log` line answers in about 3.7 s there, and a function of yours that Node's code reaches only further in than that is not entered. Not fixed here: a `step_into` on a `require` line does not land where the call returned (Node's loader returns through `try … finally`, one of the steps V8 itself loses, #1161): the first load of a module of yours is lost, and in the measured cases of a built-in or already loaded module the step stops further down the same function, with the lines between run, as before; `step_over` on such a line lands on the next one. (#1130) diff --git a/docs/javascript/README.md b/docs/javascript/README.md index 5a09e0eab..4e54aa234 100644 --- a/docs/javascript/README.md +++ b/docs/javascript/README.md @@ -108,21 +108,31 @@ and loses it (a `step_into` on the first `console.log` of a process ended the se per statement of the skipped code (131 for one `console.log`, about 6 s on a Linux host). `smartStep` is read as the session's choice instead, and a session that chose it has its steps served by the server over js-debug's raw CDP socket. What "skipped" means is still js-debug's own verdict on the frame, so `justMyCode`, your own `skipFiles` and -source maps (an unmapped helper of a source-mapped file) all count. +source maps (an unmapped helper of a source-mapped file) all count. It is asked at every landing, so in a bundle the +dependency's lines are skipped and your own lines of the same script are not; only a module of Node's own, one source +per script, is not asked about twice. + +A `step_into` that lands in skipped code walks on, one engine step at a time, until your code is on top again or the +walk reaches one of its two bounds, whichever comes first: 512 engine steps taken in skipped code, or 3 s from its +first landing there. Then it steps out. On Windows an engine step costs about 1.6 to 2.5 ms through the server, so +the step bound comes first; on +Linux it costs about 44 ms (issue #1163), so the time bound comes first: about 60 engine steps, measured in the +Docker image. What a step does when the session steps through skipped code (the launch default): | Step | From | Lands | |---|---|---| -| `step_into` | a line that calls your function through skipped code (`emitter.emit` to a listener, an array callback, a route handler from inside express) | in that function | -| `step_into` | a line whose call stays in skipped code for the whole walk (`console.log`, `setTimeout`) | on the next line. The message says how many engine steps the walk took, and that code of yours the call runs further in or only schedules (a timer callback) does not stop the step | -| `step_into` | a `require` line | nowhere on today's Node versions: the step is lost and the program runs on. Node's loader returns through `try … finally`, so stepping back out of it is one of the steps V8 loses (issue #1161, below). Use `step_over` on a `require` line (it lands on the next line), or set a breakpoint in the module | +| `step_into` | a line that calls your function through skipped code (`emitter.emit` to an `on` or `once` listener, an array callback, a route handler from inside express) | in that function, when the walk reaches it inside its bounds. Measured through the server on Windows: 11 engine steps to an `on` listener, 35 to a `once` listener, 84 to a custom `util.inspect` function behind a later `console.log`. Beyond the bounds the step steps out, as in the next row | +| `step_into` | a line whose call stays in skipped code (`console.log`) | where the call returned: the next line, or the line's next statement. A walk that comes back out by itself is a plain `Stepped into`. One that ends on a bound steps out, and the message says how many engine steps the walk took, which bound ended it, and that code of yours the call runs further in or only schedules (a timer callback) did not stop the step. Measured through the server on Windows, the walk comes back out by itself: about 390 engine steps for the first `console.log` of a process, 130 for a later one. On Linux it ends on the 3 s bound (below) | +| `step_into` | a line that goes on after the call (`console.log(a); console.log(b);`, a one-line `for … of` loop) | at the next position on that line where your code runs: the next statement, or the loop header's next position, in the first iteration. `step_into` again goes on | +| `step_into` | a `require` line | not where the call returned, on today's Node versions: Node's loader returns through `try … finally`, so stepping back out of it is one of the steps V8 loses (issue #1161, below). The first load of a module of yours is lost and the program runs on. In the measured cases of a built-in module or one already loaded (`require('node:fs')`, a second `require` of a loaded file, on Windows), the walk ended on its step bound inside the loader and the step stopped further down the same function, with the lines between run, as without the server's stepper. Use `step_over` on a `require` line (it lands on the next line), or set a breakpoint in the module | | `step_into` | a line that calls native code only (`JSON.stringify`) | on the next line, as a plain `Stepped into`: there is nothing to walk into | | `step_into` | a line that only starts a later task (`setTimeout`, a `.then` callback) | on the next line, never in the callback some time later; a breakpoint in the callback stops there | | `step_over`, `step_out` | a frame whose caller is skipped code, with your code further down the stack | in that frame of yours | -| `step_out` | an `async` function the event loop resumed | in the function that awaits it, in the call that awaited (V8's own step) | +| `step_out` | an `async` function the event loop resumed | in the function that awaits it, in the call that awaited (V8's own step). Not for TypeScript compiled for a target below ES2017 (issue #1165): there the step does not land in the awaiting function, and the program runs on to the next breakpoint or its end | | `step_over`, `step_out` | the last line of a function that nothing of yours called or awaits (a request handler, a timer callback, a `.then` callback) | nowhere of its own: nothing of your program is on the stack. If another callback of yours is already queued behind a `.then` callback, V8's step stops in it; otherwise the program is resumed, and the answer is the next stop if one comes while the step waits (a breakpoint, the program's end), or `pending: true` if none does (on a launch, with a sentence saying the step left its frame) | -| any step | skipped code (a breakpoint inside a dependency) | `step_into` walks on into your handler; `step_over` and `step_out` run on as in the row above. `justMyCode: false` steps inside that code | +| any step | skipped code (a breakpoint inside a dependency) | `step_into` walks on, into your handler when the walk reaches it inside its bounds. `step_over` and `step_out`: when your code called the dependency, in your caller at once, where the call returned; when nothing of yours is on the stack (a request path inside a framework), the program runs on, as in the row above. `justMyCode: false` steps inside that code | A breakpoint or an exception reached during a step stops as itself. A `debugger;` statement reached during a step is reported as the step's landing: V8 reports the two alike, and it is where the program stopped. (A `debugger;` in @@ -132,7 +142,7 @@ if that is where it is (the stack response marks the frame). A step never steps | Launch | `skipFiles` sent | Steps through skipped code | `step_over` from a breakpoint inside a dependency | |---|---|---|---| -| default (`justMyCode: true`) | `/**`, `**/node_modules/**` | yes | runs on (`pending: true`; the message names the skipped frame and the remedy) | +| default (`justMyCode: true`) | `/**`, `**/node_modules/**` | yes | lands in your caller when your code called the dependency; runs on when nothing of yours is on the stack (`pending: true`; the message names the skipped frame and the remedy) | | `dapLaunchArgs: { justMyCode: false }` | `/**` | no | lands on the next line of the dependency | | `dapLaunchArgs: { skipFiles: [...] }` | exactly your list | follows `justMyCode` unless `smartStep` is set | lands unless the frame is on your list | | `adapterLaunchConfig: { smartStep: false }` (default list) | `/**`, `**/node_modules/**` | no | lands in the next frame V8 does not skip (an internals frame on a request path) | @@ -169,9 +179,12 @@ A different loss, in js-debug: a `step_over` across the first load of a module t (issue #1162). js-debug pauses at the module's entry to bind the breakpoint and resumes that pause itself while the step is in flight, and the step is lost with it. -On Linux every engine step costs about 46 ms whoever sends it (the inspector's socket; issue #1163), against 1.5 ms -on Windows, so a `step_into` on a `console.log` line, which walks 25 engine steps into Node's code and a few back -out, takes over a second there. +On Linux every engine step costs about 44 ms whoever sends it (the inspector's socket; issue #1163), against about +1.6 to 2.5 ms through the server on Windows. There the walk's time bound comes first, at about 60 engine steps (measured in the Docker image): +a `step_into` on a `console.log` line walks for 3 s, steps out and lands on the next line, answering in about 3.7 s, +and a function of yours that Node's code reaches only after more engine steps than that (a custom `util.inspect` +function behind `console.log`) is not entered. A `once` listener behind `emitter.emit` (35 engine steps) is entered +there, in about 2 s. A step whose stop is a breakpoint or an exception rather than the step itself is reported as `Stepped over; stopped on 'breakpoint' rather than on the step itself (see stopReason)` — true both when the next diff --git a/docs/tool-reference.md b/docs/tool-reference.md index ec98940ec..11fdd6753 100644 --- a/docs/tool-reference.md +++ b/docs/tool-reference.md @@ -490,7 +490,7 @@ Starts debugging a script. - `args` (array of strings, optional): Command line arguments for the script. - `dapLaunchArgs` (object, optional): Standard DAP launch arguments: - `stopOnEntry` (boolean): Stop at first line (default `false` — the opposite of attach, which pauses unless `stopOnEntry` is `false`) - - `justMyCode` (boolean): Debug only user code (default `true`). JavaScript launch: `true` puts `node_modules` on js-debug's `skipFiles` beside Node internals, and a step does not stop in skipped code: the server steps through it itself, so `step_into` follows a call through skipped code into your own function, and otherwise lands on the next line and says how far it walked without reaching your code (issue #1130; see [`step_into`](#step_into)). `false` takes `node_modules` off the list and turns that stepping off, so every step lands where V8 lands, inside dependencies and Node internals. A pause lands where the program is either way. A caller `skipFiles` replaces the default list. Source maps are on for every JavaScript launch, `.js` programs included — stops report `src/*.ts` when maps and sources are present; `adapterLaunchConfig: { sourceMaps: false }` opts out (issue #684) + - `justMyCode` (boolean): Debug only user code (default `true`). JavaScript launch: `true` puts `node_modules` on js-debug's `skipFiles` beside Node internals, and a step does not stop in skipped code: the server steps through it itself, so `step_into` follows a call through skipped code into your own function when its walk reaches it within 512 engine steps or 3 s, whichever comes first, and otherwise steps out and says how far it walked (issue #1130; see [`step_into`](#step_into)). `false` takes `node_modules` off the list and turns that stepping off, so every step lands where V8 lands, inside dependencies and Node internals. A pause lands where the program is either way. A caller `skipFiles` replaces the default list. Source maps are on for every JavaScript launch, `.js` programs included — stops report `src/*.ts` when maps and sources are present; `adapterLaunchConfig: { sourceMaps: false }` opts out (issue #684) - `noDebug` (boolean): DAP's "launch without enabling debugging" flag (default `false`). What it does depends on the adapter, and the response says which case you are in. **Honoured** — the debugger is off: no breakpoint binds, no exception filter arms, no entry stop lands, and no breakpoint, exception or entry stop ever arrives, so a short script ends `stopped` and a server stays `running`. That is a legitimate plain run and says nothing by itself; when the session has breakpoints (line or function), an explicit `breakOnExceptions` other than `"none"`, or `stopOnEntry`, the `warning` says the debugger is off for this launch and names what will not fire — not that no stop of any kind can come — in place of the unbound-breakpoint diagnostics that would otherwise send you to check paths that are fine (issue #710). js-debug, debugpy, Delve and CodeLLDB honour it (debugpy and Delve open no configuration phase at all, so the launch is complete on the launch response; CodeLLDB refuses the configuration requests, and the refusal reaches the `warning` and `get_output` — issue #746). The run ends `stopped` with the program's output and, where the adapter reports one, the exit code (Delve states it as a console line, `Process N has exited with status S`, which is read back as `exitCode` — issue #753). Under the flag Delve runs the program through Go's `exec`, so on Windows the binary needs its `.exe` extension. **Ignored** — rdbg, netcoredbg and the Java bridge run the debugger regardless, and the rust launch transform never forwards the flag: the `warning` says the flag had no effect and everything works as usual. The same warning comes back from `restart_debugging` and from a `dryRunSpawn` check. While such a launch runs, the session remembers the decision (`list_debug_sessions` reports `debuggerDisabled: true`) and every later surface says why: `set_breakpoint` and `list_breakpoints` keep the adapter's own answer (still sent — e.g. js-debug's "Unbound breakpoint", or CodeLLDB's refusal echoed onto each pre-launch breakpoint) and add "the debugger is off for this launch (noDebug is true)…", `pause_execution` is still sent and the same sentence explains a pause that never lands or one the adapter refused, and `step_*`/`continue_execution`/`get_stack_trace`/`get_local_variables`/`evaluate_expression` append it to their "not paused" answers. A `stopped` event only a live debugger produces — a breakpoint the adapter itself reports (or names in `hitBreakpointIds`), an exception stop, an entry stop — proves the debugger on for that adapter build and clears the decision, and so does a breakpoint the adapter verified (every honouring adapter refuses or unbinds one under the flag, so a bound one can only come from a build that ignores it); a pause, a step taken from one, or a `debugger;` statement do not (js-debug lands all three under the flag while its breakpoints stay unbound; an uncaught throw does not stop). On a paused session the sentence keeps only the clause still true of it — breakpoints cannot bind — and outside a live launch (`initializing`/`running`/`paused`) the decision is neither reported nor consulted (issue #749). - Additional DAP launch keys (`program`, `cwd`, `env`, language-specific options) pass through to the adapter. For Python, `module` (`python -m `) or `code` (`python -c`) replaces `program`: debugpy takes exactly one target, so the launch goes out without `program` and the response's `warning` says so (`dapLaunchArgs.module: launched as a module (python -m); program is not sent …`); `scriptPath` still has to name an existing file, and `cwd` is what `-m` puts on `sys.path`: for these launches it defaults to the directory above the top-most package containing `scriptPath` (the `warning` names it), and a module launch of a project sets it to the project root explicitly (issue #985). `dryRunSpawn` reports such a launch's `data.script` as `module: ` or `code: …`. Top-level parameters do **not** belong here: a nested `breakOnExceptions` is honored as an alias (the top-level value wins if both are given) and reported via a `warning` in the response; other misplaced top-level keys (`dryRunSpawn`, `sessionId`, `scriptPath`, `adapterLaunchConfig`) are stripped with a warning instead of silently riding into the launch config. - `adapterLaunchConfig` (object, optional): Adapter-specific launch configuration overrides. Use this for language-specific settings that go beyond standard DAP arguments (e.g., `mainClass` and `classpath` for Java, `buildCommand` for Rust). For Rust, `_adapterSettings` passes through to CodeLLDB (issue #441) — e.g. `{"_adapterSettings": {"scriptConfig": {"lang": {"rust": {"sysroot": "/path"}}}}}` points the Rust formatter lookup at an explicit sysroot; the `CODELLDB_RUST_SYSROOT` env var does the same without per-launch config (a user-supplied `_adapterSettings` value wins over the env var). @@ -705,12 +705,15 @@ The step is not cancelled: the session becomes `"paused"` on its own when it com The adapter may append one sentence to that message saying what the step is waiting for. The JavaScript adapter does so for a launch that steps through skipped code (issues #678, #1130): a step issued from skipped code names -the frame and says a step does not stop there, and any other pending step says it left the frame it started in -and has not stopped in your program since (a function Node called returned to the event loop, the line is -waiting on work in flight, or the engine lost the step: V8 loses one that leaves a function through a `return` -inside `try … finally`, out of a `for … of` loop, or from a function with a `using` declaration, issue #1161), and -says to set a breakpoint where you expect execution to come back. An attach that steps through skipped code -(`smartStep: true`) gets no such sentence. +the frame and says a step does not stop there. Any other pending step gets a sentence only when the server's +stepper ended it by resuming the program: the step left the frame it started in and reached skipped code with +nothing of your program below it (a function Node called, such as a timer or event callback, returned to the +event loop), so it will not land, and `wait_for_stop` answers at the next breakpoint or when the program ends. A +step still executing (a `step_over` of a long call in the function's own frame) gets no sentence. Neither does a +step V8 itself lost (issue #1161: one that leaves a function through a `return` inside `try … finally`, out of a +`for … of` loop, or from a function with a `using` declaration): the server cannot tell it from a step still +executing, so set a breakpoint where you expect execution to come back. An attach that steps through skipped +code (`smartStep: true`) gets no such sentence. So match a pending step by its `pending: true` flag, not by the message text. Once a stop has been observed, the stop path owns the answer — a step that demonstrably landed is never reported as pending afterwards, at the cost of the response then being bounded by the stack-trace round trip rather than by the ~5s window. If the debuggee ends while the step is in flight the result is still a success, with a terminal `state` and a message such as `"Step completed as session terminated."`. @@ -740,18 +743,31 @@ Same ~5s wait and `pending: true` contract as step_over — see [Pending steps]( **JavaScript** (a launch that steps through skipped code, the default; issue #1130): -- A line that calls your own function through skipped code lands in that function: an event listener behind - `emitter.emit`, an array callback, a route handler from inside express. -- A line whose call stays in skipped code (Node internals, `node_modules`, files on `skipFiles`) for the whole - walk lands on the next line, and the message says what is known: `Stepped into. step_into walked 25 engine steps - into the call on that line and was still in skipped code (Node internals, node_modules, or files on skipFiles), - so it stepped back out and the rest of the line ran as a step over runs it. Code of yours that the call runs - further in (a module it loads) or only schedules (a timer or promise callback) does not stop the step: a - breakpoint there stops in it. To stop inside the skipped code instead, turn stepping through it off: - justMyCode: false on a launch, smartStep: false on a launch or an attach.` A `console.log` and a `setTimeout` line - answer this way. A `require` line does not: Node's loader returns through `try … finally`, so a `step_into` on - it is one of the steps V8 loses (issue #1161) and the program runs on. Use `step_over` on a `require` line, or - a breakpoint in the module. +- A `step_into` that lands in skipped code (Node internals, `node_modules`, files on `skipFiles`) walks on, one + engine step at a time, until your code is on top again or the walk reaches one of its bounds, whichever comes + first: 512 engine steps in skipped code, or 3 s. Then it steps out. On Linux, at about 44 ms an engine step + (issue #1163), the time bound comes first, at about 60 steps (measured in the Docker image). +- A line that calls your own function through skipped code lands in that function when the walk reaches it inside + those bounds: an `on` or `once` event listener behind `emitter.emit`, an array callback, a route handler from + inside express. +- A line whose call stays in skipped code lands where the call returned: the next line, or the line's next + statement. A walk that came back out by itself answers a plain `Stepped into`; one that ended on a bound says + what is known: `Stepped into. step_into walked 60 engine steps into the call and was still in skipped code + (Node internals, node_modules, or files on skipFiles) when the walk reached its 3 s limit, and stepped out. Code + of yours that the call runs further in, or only schedules (a timer or promise callback), did not stop the step: + a breakpoint there stops in it. To stop inside the skipped code instead, turn stepping through it off: + justMyCode: false on a launch, smartStep: false on a launch or an attach.` (a later `console.log`, measured in + the Docker image; a walk that ends on the step bound says `its 512-step limit`). A `console.log` line comes back out by itself on Windows (measured through the server: about 390 + engine steps for the first `console.log` of a process, 130 for a later one) and ends on the 3 s bound on Linux. + A `require` line does not land where the call returned: Node's loader returns through `try … finally`, so + stepping back out of it is one of the steps V8 loses (issue #1161). The first load of a module of yours is lost + and the program runs on. In the measured cases of a built-in module or one already loaded (`require('node:fs')`, + a second `require` of a loaded file, on Windows) the walk ended on its step bound inside the loader and the step + stopped further down the same function, with the lines between run, as without the server's stepper. + Use `step_over` on a `require` line, or a breakpoint in the module. +- A pause in your code is the landing, on the line the step started from too: on `console.log(a); console.log(b);` + the step stops at the second statement, and on a one-line `for … of` loop at the header's next position, in the + first iteration. - A line that calls native code only (`JSON.stringify`) has nothing to walk into: a plain `Stepped into` on the next line. - A call that only starts a later task (`setTimeout`, a `.then` callback) is not followed: the step lands on the @@ -783,7 +799,9 @@ Same ~5s wait and `pending: true` contract as step_over — see [Pending steps]( **JavaScript** (a launch that steps through skipped code, the default; issues #1130, #1161): - Out of an `async` function the event loop resumed, the step lands in the function that awaits it, in the - call that awaited: that is the engine's own step. + call that awaited: that is the engine's own step. Not for TypeScript compiled for a target below ES2017 (issue + #1165): there the step does not land in the awaiting function, and the program runs on to the next breakpoint + or its end. - The engine loses a step that leaves a function through a `return` that runs a `finally` first: a `return` inside `try … finally`, a `return` out of `for … of`, a function with a `using` declaration, and every async generator (issues #1161, #1174). The server does not rescue it and sets no temporary breakpoint: the step answers diff --git a/packages/shared/src/interfaces/adapter-policy-js.ts b/packages/shared/src/interfaces/adapter-policy-js.ts index 981e9c257..bef749a70 100644 --- a/packages/shared/src/interfaces/adapter-policy-js.ts +++ b/packages/shared/src/interfaces/adapter-policy-js.ts @@ -411,13 +411,15 @@ export const JsDebugAdapterPolicy = { * #1130). The proxy's own stepper serves the steps of a session whose * effective `smartStep` is on: it never stops in skipped code, it steps out * toward the nearest frame of the program below, and with none below it - * resumes the program (the stack the step started on is gone). So a step - * still pending after the grace window has run off the program's stack, or - * is waiting on work in flight. A step issued from skipped code (a - * breakpoint inside a dependency) gets the sentence that names the frame - * and the switch that steps inside that code; the frame is matched with the - * helpers the launch transform uses, and a caller's own glob - * (`**\/vendor/**`) is not matched, since this package has no glob matcher. + * resumes the program (the stack the step started on is gone). A step + * issued from skipped code (a breakpoint inside a dependency) gets the + * sentence that names the frame and the switch that steps inside that + * code; the frame is matched with the helpers the launch transform uses, + * and a caller's own glob (`**\/vendor/**`) is not matched, since this + * package has no glob matcher. Any other step gets the sentence that it + * left its frame only when the stepper recorded that it ended the step by + * resuming the program (`stepLeftStack`): a step still executing (a + * `step_over` of a long call in its own frame) gets the generic wording. * A pause gets nothing: js-debug's stepper, which stepped away from a pause * that landed in skipped code, is off (the pending pause has its own * wording, issue #1146). Attach sessions default neither key (#513) and get @@ -449,12 +451,18 @@ export const JsDebugAdapterPolicy = { 'still in flight. It stops at the next breakpoint in your own code. Relaunch with ' + 'dapLaunchArgs.justMyCode: false (or adapterLaunchConfig.smartStep: false) to step inside that code.'; } - return 'The step left the frame it started in and has not stopped in your program since: a function that Node ' + - 'called returned to the event loop, the line is waiting on work still in flight, or the engine lost the step ' + - '(when the function left returns from inside try...finally, or out of a for...of loop, or declares using, ' + - 'V8 loses the step, issue #1161; set a breakpoint where you expect execution to come back and continue). ' + - 'The program is running; ' + - 'wait_for_stop answers when the step lands, a breakpoint is hit, or the program ends.'; + // Only what the stepper recorded: a step it did not end by leaving the + // stack may still be executing in the frame it started in (I3). + if (info.stepLeftStack !== true) { + return undefined; + } + // What the record means, and no more: the stepper resumed the program, so + // this step is over. (A step V8 itself lost, issue #1161, leaves no + // record and cannot be told from one still executing.) + return 'The step left the frame it started in and reached skipped code with nothing of your program below it ' + + '(a function that Node called, such as a timer or event callback, returned to the event loop), so the ' + + 'program was resumed and this step will not land. The program is running; wait_for_stop answers when a ' + + 'breakpoint is hit or the program ends.'; }, /** diff --git a/packages/shared/src/interfaces/adapter-policy.ts b/packages/shared/src/interfaces/adapter-policy.ts index 50c8d5979..152ea9b33 100644 --- a/packages/shared/src/interfaces/adapter-policy.ts +++ b/packages/shared/src/interfaces/adapter-policy.ts @@ -230,6 +230,13 @@ export interface PendingStopContext { }; /** The raw top frame the step was issued from — step only, and only when it could be read. */ fromFrame?: StackFrame; + /** + * Step only: the proxy's own stepper (issue #1130) ended this step by + * resuming the program, by the time the grace window elapsed. The step had + * reached skipped code with nothing of the program below it, so the stack + * it started on is gone. Absent for a step that is still executing. + */ + stepLeftStack?: boolean; } /** Context passed to AdapterPolicy.describeUnresolvedSource (issue #816). */ diff --git a/src/proxy/dap-proxy-interfaces.ts b/src/proxy/dap-proxy-interfaces.ts index e78518328..b728c70ef 100644 --- a/src/proxy/dap-proxy-interfaces.ts +++ b/src/proxy/dap-proxy-interfaces.ts @@ -421,6 +421,13 @@ export interface DapProxyDependencies { export const MIRROR_EXPOSE_COMMAND = 'mirrorExpose'; export const MIRROR_UNEXPOSE_COMMAND = 'mirrorUnexpose'; +// The proxy's JavaScript stepper (issue #1130) ended a step by resuming the +// program: the step reached skipped code with nothing of the program below +// it, so the stack it started on is gone and the step will not land. A DAP +// event of the proxy's own, sent to the parent process only (the mirror does +// not forward it); a pending step's answer reads it. +export const PROXY_STEP_LEFT_STACK_EVENT = 'proxyStepLeftStack'; + // The session tree (issue #1081): the parent process's answers to a // 'child_reported' status, and the close of an adopted child's connection. // They ride the `dap` envelope too; the envelope's sessionId names the diff --git a/src/proxy/dap-proxy-worker.ts b/src/proxy/dap-proxy-worker.ts index 3bd954383..298f0d88d 100644 --- a/src/proxy/dap-proxy-worker.ts +++ b/src/proxy/dap-proxy-worker.ts @@ -24,6 +24,7 @@ import { BreakpointSyncResult, MIRROR_EXPOSE_COMMAND, MIRROR_UNEXPOSE_COMMAND, + PROXY_STEP_LEFT_STACK_EVENT, CHILD_ADOPT_COMMAND, CHILD_RELEASE_COMMAND, CHILD_CLOSE_COMMAND, @@ -357,7 +358,8 @@ export class DapProxyWorker { // handlers (post threadId-backfill); this generic-channel forwarder covers // everything else. initialized is per-client handshake, never replicated. private readonly mirrorEventForwarder = (evt: DebugProtocol.Event): void => { - if (evt.event === 'stopped' || evt.event === 'continued' || evt.event === 'initialized') { + // The proxy stepper's record (issue #1130) is the proxy's own, not the adapter's. + if (evt.event === 'stopped' || evt.event === 'continued' || evt.event === 'initialized' || evt.event === PROXY_STEP_LEFT_STACK_EVENT) { return; } this.mirrorServer?.broadcastEvent(evt.event, evt.body); @@ -1202,6 +1204,12 @@ export class DapProxyWorker { this.sendDapEvent(name, body as DebugProtocol.Event['body']); }); } + // The proxy stepper's record that it ended a step by resuming the program + // (issue #1130): the pending step's answer reads it. A child connection's + // stepper sends its own straight to the parent (child-connections.ts). + this.dapClient.on(PROXY_STEP_LEFT_STACK_EVENT, (body: unknown) => { + this.sendDapEvent(PROXY_STEP_LEFT_STACK_EVENT, body as DebugProtocol.Event['body']); + }); this.connectionManager.setupEventHandlers(this.dapClient, { onInitialized: async () => { diff --git a/src/proxy/js-stepper.ts b/src/proxy/js-stepper.ts index c23578896..c192420ea 100644 --- a/src/proxy/js-stepper.ts +++ b/src/proxy/js-stepper.ts @@ -35,12 +35,20 @@ * cannot be told from a hit in a later call of the caller: CDP names no * single activation. * - * Skipped code on top: `step_into` repeats up to a budget (that is how a - * call through Node's own code reaches a callback of the program's), then - * steps out; `step_over` and `step_out` step out at once. With nothing of - * the program below (no frame, no awaiter), the stack the step started on - * is gone: the program is resumed and nothing is reported (stepping out - * of the bottom frame would land in the next task's internals instead). + * Skipped code on top: `step_into` steps in again (that is how a call + * through Node's own code reaches a callback of the program's) while the + * walk is inside both of its bounds, engine steps taken in skipped code and + * time since its first landing there, then steps out; `step_over` and + * `step_out` step out at once. A pause in the program's code is the + * landing, on the line the step started from too: in the measured traces + * V8's step-out lands on the caller's next break position (11:17 after a + * call at 11:1), never back on the call it left, and a first step-in on a + * one-line for...of lands on the header's next position (9:17 to 9:12): + * where the program's code next runs. With nothing + * of the program below (no frame, no awaiter), the stack the step started + * on is gone: the program is resumed, and the only word of it is the + * proxy's own `proxyStepLeftStack` event, for the pending answer (stepping + * out of the bottom frame would land in the next task's internals instead). * * A pause that is not the stepper's (another breakpoint, an exception) is * js-debug's to decide. Resumed by js-debug, the chain waits on. Kept, the @@ -59,6 +67,7 @@ import type { DebugProtocol } from '@vscode/debugprotocol'; import { createLogger } from '../utils/logger.js'; import { ErrorMessages } from '../utils/error-messages.js'; +import { PROXY_STEP_LEFT_STACK_EVENT } from './dap-proxy-interfaces.js'; // redirectable: re-pointed into the per-session proxy log at worker init (#519) const logger = createLogger('js-stepper', { redirectable: true }); @@ -77,12 +86,16 @@ export interface StepperCdp { } export interface JsStepperTunables { - /** Repeats of a step-in while the landing is skipped code, before stepping out. */ - budget: number; - /** CDP step commands in one chain, all told. */ + /** Engine steps a step-in may take in skipped code before it steps out. */ + walkBudgetSteps: number; + /** + * How long a step-in may walk through skipped code, from the chain's first + * landing there, before it steps out. A step answers `pending` after about + * 5 s; the step-outs after the walk need room inside that. + */ + walkBudgetMs: number; + /** CDP step commands in one chain, all told: a backstop above both walk bounds. */ commandCap: number; - /** Re-issued step-ins when a step-in lands back on the statement it started from. */ - reissueCap: number; /** How long a finished chain waits for js-debug's `stopped` events before it reports without them. */ settleCeilingMs: number; /** How long `stackTrace` may answer "not paused" for a pause js-debug keeps. */ @@ -90,9 +103,9 @@ export interface JsStepperTunables { } export const DEFAULT_JS_STEPPER_TUNABLES: JsStepperTunables = { - budget: 24, - commandCap: 128, - reissueCap: 24, + walkBudgetSteps: 512, + walkBudgetMs: 3000, + commandCap: 2048, settleCeilingMs: 2000, verdictCeilingMs: 2000 }; @@ -104,6 +117,8 @@ export interface JsStepperOptions { tunables?: Partial; /** Test seam. */ sleep?: (ms: number) => Promise; + /** Test seam: the clock the walk's time bound reads. */ + now?: () => number; } export type StepKind = 'in' | 'over' | 'out'; @@ -175,7 +190,6 @@ interface Chain { kind: StepKind; threadId: number | undefined; originDepth: number; - originLine: number; originFn: string; inbox: Inbox[]; wake: (() => void) | null; @@ -186,10 +200,12 @@ interface Chain { stoppedSeen: number; lastStopped: DebugProtocol.Event | null; commands: string[]; + /** Step-ins sent from a landing in skipped code: the walk's engine steps. */ spent: number; - reissues: number; - /** Step-ins a step-in had sent when it gave up on the skipped code and stepped out; 0 if it never did. */ - walkedBeforeSteppingOut: number; + /** When the walk's first landing in skipped code was judged; null before it. */ + walkStartedAt: number | null; + /** How the walk through skipped code ended, when a step-in gave up on it and stepped out. */ + walkEnded: { steps: number; by: 'steps' | 'time' } | null; /** Every command the chain may send is spent and skipped code is still on top. */ capped: boolean; /** The caller asked for a pause during the chain: the next stop is theirs. */ @@ -229,6 +245,7 @@ export class JsStepper { private readonly deliver: (event: DebugProtocol.Event) => void; private readonly tunables: JsStepperTunables; private readonly sleep: (ms: number) => Promise; + private readonly now: () => number; private cdp: StepperCdp | null = null; private readonly onCdpEvent = (method: string, params: unknown): void => this.handleCdpEvent(method, params); @@ -241,7 +258,13 @@ export class JsStepper { /** `stopped` events of a finished chain still on their way; dropped when they arrive, until the deadline. */ private owed = 0; private owedUntil = 0; - /** Scripts js-debug marked "Skipped by skipFiles": a script-level verdict, not asked again. */ + /** + * Scripts of Node's own that js-debug marked "Skipped by skipFiles", not + * asked about again. js-debug decides per original source; a Node module + * is one script and one source (`/...`), so its verdict + * holds at every position. A bundle or a node_modules file is not + * remembered: some of its lines can be the program's. + */ private readonly skippedScripts = new Set(); /** What each pause's top frame returns to: asked of js-debug once per pause. */ private readonly targets = new WeakMap(); @@ -251,6 +274,7 @@ export class JsStepper { this.deliver = options.deliver; this.tunables = { ...DEFAULT_JS_STEPPER_TUNABLES, ...(options.tunables ?? {}) }; this.sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))); + this.now = options.now ?? Date.now; } /** The session's choice: step through skipped code (on), or land where V8 lands (off). */ @@ -312,7 +336,6 @@ export class JsStepper { kind, threadId: (args as { threadId?: number } | undefined)?.threadId, originDepth: origin.callFrames.length, - originLine: top.location.lineNumber, originFn: fnKey(top), inbox: [], wake: null, @@ -322,8 +345,8 @@ export class JsStepper { lastStopped: null, commands: [], spent: 0, - reissues: 0, - walkedBeforeSteppingOut: 0, + walkStartedAt: null, + walkEnded: null, capped: false, pauseRequested: false, pauseTaken: false, @@ -333,8 +356,8 @@ export class JsStepper { this.owed = 0; try { - // js-debug's mark on the frame the step starts from: a script it skips - // as a whole is then not asked about again at a landing. + // js-debug's mark on the frame the step starts from: a module of Node's + // own it skips is then not asked about again at a landing. await this.isSkipped(chain, origin); await this.sendStep(chain, CDP_COMMAND[kind]); } catch (err) { @@ -525,8 +548,6 @@ export class JsStepper { } chain.kept++; - const top = pause.callFrames[0]; - const depth = pause.callFrames.length; const skipped = await this.isSkipped(chain, pause); if (chain.cancelled) { // Given up while js-debug was being asked: nothing more is sent. @@ -534,31 +555,36 @@ export class JsStepper { } if (skipped) { - // A step-in walks on while it has budget, with or without anything - // below: a step issued inside a dependency reaches the program's - // handler by calls, not returns (issue #687). - if (chain.kind === 'in' && chain.spent < this.tunables.budget) { - chain.spent++; - return { kind: 'command', command: CDP_COMMAND.in }; + // A step-in walks on while it is inside both bounds, with or without + // anything below: a step issued inside a dependency reaches the + // program's handler by calls, not returns (issue #687). The bounds keep + // the answer inside the window after which a step answers `pending` + // (the time, which is what an engine step costs over a slow inspector + // link decides), and keep a walk that never reaches the program's code + // from costing all of that time on a fast one (the steps). + if (chain.kind === 'in' && chain.walkEnded === null) { + const now = this.now(); + chain.walkStartedAt ??= now; + const withinSteps = chain.spent < this.tunables.walkBudgetSteps; + const withinTime = now - chain.walkStartedAt < this.tunables.walkBudgetMs; + if (withinSteps && withinTime) { + chain.spent++; + return { kind: 'command', command: CDP_COMMAND.in }; + } + chain.walkEnded = { steps: chain.spent, by: withinSteps ? 'time' : 'steps' }; } // It has to step out now. With nothing of the program below (no frame, // no awaiter), the stack the step started on is gone. if ((await this.returnTarget(chain, pause)).kind === 'nothing') { return { kind: 'left-stack' }; } - if (chain.kind === 'in' && chain.walkedBeforeSteppingOut === 0) { - chain.walkedBeforeSteppingOut = chain.commands.filter((sent) => sent === CDP_COMMAND.in).length; - } return { kind: 'command', command: CDP_COMMAND.out }; } - // Program code on top: V8's step landed. A step-in that is back on the - // line it left steps in again: that enters the line's next call, or moves on. - const backOnOriginStatement = depth === chain.originDepth && fnKey(top) === chain.originFn && top.location.lineNumber === chain.originLine; - if (chain.kind === 'in' && backOnOriginStatement && chain.reissues < this.tunables.reissueCap) { - chain.reissues++; - return { kind: 'command', command: CDP_COMMAND.in }; - } + // Program code on top: V8's step landed. On the line the step started + // from too: a new position there (after a step-out, the caller's next + // break position on the line; in a one-line loop, the header's next + // position, as the traces show), where the program's code next runs. return { kind: 'landing', by: 'V8 step' }; } @@ -602,7 +628,9 @@ export class JsStepper { return false; } const skipped = markOf(marks[0]) === 'deemphasize'; - if (skipped && /skipFiles/i.test(marks[0].source?.origin ?? '')) { + // Remembered only for a module of Node's own, by js-debug's own name for + // its source: one script, one source, no source map (C1). + if (skipped && /skipFiles/i.test(marks[0].source?.origin ?? '') && (marks[0].source?.path ?? '').startsWith('')) { this.skippedScripts.add(scriptId); } return skipped; @@ -675,6 +703,12 @@ export class JsStepper { this.owed = missing; this.owedUntil = Date.now() + this.tunables.settleCeilingMs; } + if (ender === 'left-stack') { + // The program runs on and the step will not land: no stop to report. + // The record goes to the parent process, whose pending answer may then + // say the step left its frame (I3). + this.deliver({ seq: 0, type: 'event', event: PROXY_STEP_LEFT_STACK_EVENT, body: { threadId: chain.threadId ?? 0 } }); + } const count = (name: string): number => chain.commands.filter((c) => c === name).length; logger.info( `[JsStepper] step ${chain.kind} ended: ${ender}${by ? ` (${by})` : ''}${chain.cancelled ? ` [${chain.cancelled}]` : ''}; ` + @@ -730,8 +764,10 @@ export class JsStepper { if (chain.capped) { return { text: ErrorMessages.stepStillInSkippedCode(chain.commands.length) }; } - if (chain.walkedBeforeSteppingOut > 0 && backInOriginFrame) { - return { text: ErrorMessages.stepIntoReachedNoProgramCode(chain.walkedBeforeSteppingOut) }; + const walk = chain.walkEnded; + if (walk && backInOriginFrame) { + const limit = walk.by === 'time' ? this.tunables.walkBudgetMs : this.tunables.walkBudgetSteps; + return { text: ErrorMessages.stepIntoReachedNoProgramCode(walk.steps, walk.by, limit) }; } return {}; } diff --git a/src/server/tool-schemas.ts b/src/server/tool-schemas.ts index 87008f52c..d1a4a24a3 100644 --- a/src/server/tool-schemas.ts +++ b/src/server/tool-schemas.ts @@ -159,7 +159,7 @@ export function buildToolDefinitions(options: BuildToolDefinitionsOptions): Tool description: 'DAP launch arguments. Beyond the three below, adapter keys pass through (program, cwd, env, …). Python: module runs `python -m ` instead of scriptPath (the pytest shape: module "pytest", args [::, "-x"]) and code runs a code string; scriptPath then only names the file the launch is about, and cwd — which `python -m` puts on sys.path — defaults to the directory above the top-most package containing scriptPath', properties: { stopOnEntry: { type: 'boolean', description: 'Pause at the first line before running. Default false — the opposite of attach, which pauses unless stopOnEntry is false' }, - justMyCode: { type: 'boolean', description: 'Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way' }, + justMyCode: { type: 'boolean', description: 'Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way' }, noDebug: { type: 'boolean', description: 'DAP\'s launch-without-debugging flag (default false). Where the adapter honours it (js-debug, debugpy, Delve, CodeLLDB and the Dart SDK adapters) no breakpoint binds, no exception filter arms, no entry stop lands and no breakpoint, exception or entry stop ever arrives (a pause may still land where the runtime allows one) — the response warns when breakpoints, an explicit breakOnExceptions or stopOnEntry are set alongside it, and while the launch runs the session reports debuggerDisabled and every later surface says the debugger is off. rdbg, netcoredbg and the Java bridge ignore the flag, and the rust launch never forwards it: their debugger stays on and the response says so' } }, additionalProperties: true diff --git a/src/session/execution/execution-controller.ts b/src/session/execution/execution-controller.ts index 30cdba80d..e32030aa1 100644 --- a/src/session/execution/execution-controller.ts +++ b/src/session/execution/execution-controller.ts @@ -53,6 +53,7 @@ import { import { DebugProtocol } from '@vscode/debugprotocol'; import { ProxyNotRunningError, SessionTerminatedError } from '../../errors/debug-errors.js'; import { ErrorMessages } from '../../utils/error-messages.js'; +import { PROXY_STEP_LEFT_STACK_EVENT } from '../../proxy/dap-proxy-interfaces.js'; import type { ManagedSession } from '../session-store.js'; import type { DebugResult, @@ -123,11 +124,12 @@ export interface StepOperationOptions { exitedMessage?: string; /** * The adapter policy's explanation for a step that may never land (issue - * #678), appended to the grace-window message. Computed by the step preamble - * before the request is sent, because it depends on the frame the step was - * issued from. + * #678), appended to the grace-window message. Built by the step preamble + * over the frame the step was issued from, and asked when the window + * elapses, with whether the proxy's stepper recorded that it ended the step + * by resuming the program (issue #1130, I3). */ - pendingHint?: string; + describePending?: (stepLeftStack: boolean) => string | undefined; /** * Where the step was issued from (issue #678), when the preamble read it — * only for policies with `describePendingStop`, which need the frame anyway. @@ -234,7 +236,8 @@ export class ExecutionController { kind === 'stepOver' && this.ctx.selectPolicy(session.language).stepsByTokenPosition === true; const origin = await this.readStepOrigin(session, sessionId, threadId, repeatsOnSameLine); const fromFrame = origin?.frame; - const pendingHint = await this.describePendingStop(session, sessionId, 'step', fromFrame); + const describePending = (stepLeftStack: boolean): string | undefined => + this.describePendingStop(session, sessionId, 'step', fromFrame, stepLeftStack); // Re-check after the awaits — the origin read is a real DAP round trip // — in the order and spirit of pause()'s re-check (#574): a @@ -264,7 +267,7 @@ export class ExecutionController { threadId, logTag, successMessage, - ...(pendingHint ? { pendingHint } : {}), + describePending, ...(fromFrame ? { origin: { file: fromFrame.file, line: fromFrame.line, column: fromFrame.column } } : {}), onLanding: (landing) => { finalLanding = landing; }, }; @@ -327,6 +330,16 @@ export class ExecutionController { // it or something else did (issue #678) — the same discipline pause uses. const lastStopBefore = session.lastStop; + // The proxy's JavaScript stepper ended this step by resuming the program + // (issue #1130): the step will not land, and the pending answer may say + // it left its frame. Only a record that arrives while this step waits. + let stepLeftStack = false; + const onDapEvent = (event: string): void => { + if (event === PROXY_STEP_LEFT_STACK_EVENT) { + stepLeftStack = true; + } + }; + return new Promise((resolve) => { let settled = false; // Rule 1's flag: "a stop has been observed, the stop path owns the @@ -339,6 +352,7 @@ export class ExecutionController { proxyManager.off('terminated', onTerminated); proxyManager.off('exited', onExited); proxyManager.off('exit', onExit); + proxyManager.off('dap-event', onDapEvent); clearTimeout(timeout); }; @@ -426,11 +440,12 @@ export class ExecutionController { `[SM ${options.logTag} ${sessionId}] Step still running after ${this.ctx.tunables.stepGraceMs}ms grace window; completing asynchronously` ); const stillRunning = ErrorMessages.stepStillRunning(this.ctx.tunables.stepGraceMs / 1000); + const pendingHint = options.describePending?.(stepLeftStack); settle({ success: true, state: session.state, data: { - message: options.pendingHint ? `${stillRunning} ${options.pendingHint}` : stillRunning, + message: pendingHint ? `${stillRunning} ${pendingHint}` : stillRunning, pending: true, }, }); @@ -440,6 +455,7 @@ export class ExecutionController { proxyManager.on('terminated', onTerminated); proxyManager.on('exited', onExited); proxyManager.on('exit', onExit); + proxyManager.on('dap-event', onDapEvent); this.ctx.updateState(session, SessionState.RUNNING); @@ -696,7 +712,7 @@ export class ExecutionController { this.ctx.logger.info( `[SessionManager pause] No stopped event within ${this.ctx.tunables.pauseGraceMs}ms grace window in session ${sessionId}; completing asynchronously` ); - const hint = await this.describePendingStop(session, sessionId, 'pause'); + const hint = this.describePendingStop(session, sessionId, 'pause'); // With the debugger off for this launch the why is known (issue #749): // one message that promises no stop, with the policy's own explanation // kept — on js-debug a pause can land under the flag, and #678's @@ -1090,12 +1106,13 @@ export class ExecutionController { * (issue #678), or undefined when it has none. A throwing hook only costs * the explanation. */ - private async describePendingStop( + private describePendingStop( session: ManagedSession, sessionId: string, operation: 'pause' | 'step', - fromFrame?: StackFrame - ): Promise { + fromFrame?: StackFrame, + stepLeftStack?: boolean + ): string | undefined { const policy = this.ctx.selectPolicy(session.language); if (!policy.describePendingStop) { return undefined; @@ -1114,7 +1131,8 @@ export class ExecutionController { operation, attachMode: session.attachMode === true, launch, - ...(fromFrame ? { fromFrame } : {}) + ...(fromFrame ? { fromFrame } : {}), + ...(stepLeftStack ? { stepLeftStack } : {}) }) || undefined; } catch (error) { this.ctx.logger.debug(`[SM ${operation} ${sessionId}] Pending-stop explanation failed:`, error); diff --git a/src/utils/error-messages.ts b/src/utils/error-messages.ts index 97566d2be..741f45b0b 100644 --- a/src/utils/error-messages.ts +++ b/src/utils/error-messages.ts @@ -308,22 +308,27 @@ export const ErrorMessages = { /** * The sentence on a step_into that reached no code of the program (issue #1130) * Occurs when: the proxy's JavaScript stepper walked into the call on the - * line, stayed in skipped code for its whole budget, stepped back out and - * landed in the frame the step started in. It says what is known: how far - * the walk went. Not that the call reaches nothing of the program's: a - * module the line loads, a late callback, ran during the step out. The - * remedy is worded for a launch and an attach alike. + * line, was still in skipped code when the walk reached one of its bounds + * (engine steps taken in skipped code, or time), stepped out and landed in + * the frame the step started in: usually where the call returned to (on + * the same line, when the line goes on), further down when V8 lost the + * step out (a `require` line, issue #1161). It says what is known: how far the walk + * went and which bound ended it. Not that the call reaches nothing of the + * program's: code the call runs further in, or only schedules, ran during + * the step out. The remedy is worded for a launch and an attach alike. * Used in: src/proxy/js-stepper.ts (the `text` of the step's stopped * event), appended to the step's message by * src/session/execution/execution-controller.ts - * @param stepIns - How many engine step-ins the walk took before it stepped out + * @param steps - How many engine steps the walk took in skipped code before it stepped out + * @param endedBy - Which bound ended the walk + * @param limit - That bound: engine steps, or milliseconds */ - stepIntoReachedNoProgramCode: (stepIns: number) => - `step_into walked ${stepIns} engine steps into the call on that line and was still in skipped code ` + - '(Node internals, node_modules, or files on skipFiles), so it stepped back out and the rest of the line ran ' + - 'as a step over runs it. Code of yours that the call runs further in (a module it loads) or only schedules ' + - '(a timer or promise callback) does not stop the step: a breakpoint there stops in it. To stop inside the ' + - 'skipped code instead, turn ' + + stepIntoReachedNoProgramCode: (steps: number, endedBy: 'steps' | 'time', limit: number) => + `step_into walked ${steps} engine steps into the call and was still in skipped code ` + + '(Node internals, node_modules, or files on skipFiles) when the walk reached its ' + + `${endedBy === 'time' ? `${limit / 1000} s` : `${limit}-step`} limit, and stepped out. Code of yours that the ` + + 'call runs further in, or only schedules (a timer or promise callback), did not stop the step: a breakpoint ' + + 'there stops in it. To stop inside the skipped code instead, turn ' + 'stepping through it off: justMyCode: false on a launch, smartStep: false on a launch or an attach.', /** diff --git a/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts b/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts index b6a0a7adb..9750baf73 100644 --- a/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts +++ b/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts @@ -6,17 +6,25 @@ * where a step ends. What that has to hold, as measured: * * - a step_into on a line that calls only Node's own code lands on the - * next line, at once. js-debug's stepper lost that step on the first - * console.log of a process (the session ended), and took about 6 s on a - * Linux host for a later one; + * next line, inside the window after which a step answers `pending`. + * js-debug's stepper lost that step on the first console.log of a + * process (the session ended), and took about 6 s on a Linux host for a + * later one; * - a call through Node's code into a callback of the program's is - * followed; a call that only starts a later task is not; + * followed (an on() or once() listener); a call that only starts a later + * task is not; + * - a pause in the program's code is the landing, on the line the step + * started from too: a one-line loop stops at its header's next position; + * - in a bundle, js-debug's verdict is asked at each landing: a stop in a + * bundled dependency does not make the program's lines of the same + * script count as skipped; * - a step that leaves a function through `return` inside try...finally * is the engine's own. V8 loses it (issues #1161, #1174; Node 22, 24 * and 26), sync and async, and the server does not rescue it. Those * tests accept both a runtime that loses the step and one that lands it * in the caller, and fail on a stop anywhere else (another call of the - * same function); + * same function). Every one of them is lost on main too (measured: 3 of + * 3 runs each); every step main lands is asserted strictly; * - a breakpoint reached during a step stops as itself; * - a step off the last line of a callback Node called has no frame of the * program to return to: the program is resumed, not walked through the @@ -51,8 +59,29 @@ type StopAnswer = ToolAnswer & { snapshot?: { frames?: Array<{ name: string; line: number }> }; }; -/** A step that answered inside the grace window is not pending; this bound says it was prompt. */ -const PROMPT_MS = 4000; +/** + * Inside the 5 s window after which a step answers `pending` (the step + * grace window), with room for the answer's own stack reads: a step that + * answers under this bound landed by itself. + */ +const PROMPT_MS = 4500; + +/** + * The sentence a step_into carries when its walk through skipped code ended + * on one of its bounds (512 engine steps, or 3 s) and it stepped out. Which + * bound comes first depends on what an engine step costs on the host (about + * 2 ms through the server on Windows, 44 ms on Linux, issue #1163), so either is accepted, and + * the number of steps must fit the bound. + */ +function expectWalkEnded(message: string | undefined): void { + const walked = /^Stepped into\. step_into walked (\d+) engine steps into the call/.exec(message ?? ''); + expect(walked, message).not.toBeNull(); + const steps = Number(walked![1]); + expect([ + `Stepped into. ${ErrorMessages.stepIntoReachedNoProgramCode(512, 'steps', 512)}`, + ...(steps < 512 ? [`Stepped into. ${ErrorMessages.stepIntoReachedNoProgramCode(steps, 'time', 3000)}`] : []) + ], message).toContain(message); +} /** * A step V8 loses (issues #1161, #1174) is the engine's own, and the server @@ -122,13 +151,40 @@ describe('The server\'s JavaScript stepper against a real js-debug (issues #1130 } describe('step_into (issue #1130)', () => { - it('lands on the next line when the walk into the call stays in Node\'s own code, and says how far it went: the first console.log of the process', async () => { + it('lands on the next line when the walk into the call stays in Node\'s own code: the first console.log of the process', async () => { await pausedAt('the first console.log'); const answer = await step('step_into'); // js-debug's own stepper lost this step: "Step completed as session exited." expectLanding(answer, 'after the first console.log'); - // The first command and the whole budget, 25 step-ins, before it stepped out. - expect(answer.message).toBe(`Stepped into. ${ErrorMessages.stepIntoReachedNoProgramCode(25)}`); + // Measured through the server on Windows: 391 engine steps, back out by + // step-ins (a plain landing). On a slow inspector link the walk ends on + // its time bound first, steps out, and says so. + if (answer.message !== 'Stepped into') { + expectWalkEnded(answer.message); + } + }, 60000); + + it('lands on the next line of a later console.log, inside the window: issue #1130\'s own case', async () => { + await pausedAt('a later console.log'); + const answer = await step('step_into'); + expectLanding(answer, 'after a later console.log'); + // 130 engine steps through the server on Windows: walked back out by + // step-ins (a plain landing); stepped out after 3 s on a slow link. + if (answer.message !== 'Stepped into') { + expectWalkEnded(answer.message); + } + }, 60000); + + it('stays in the first iteration of a one-line loop: the header\'s next position on the same line is the landing', async () => { + await pausedAt('a one-line loop'); + const answer = await step('step_into'); + expectLanding(answer, 'a one-line loop'); + expect(answer.message).toBe('Stepped into'); + // The loop variable is not bound yet, or holds the first item. + const item = await server!.call('evaluate_expression', { + expression: "(() => { try { return String(item); } catch (e) { return 'TDZ'; } })()" + }); + expect(['\'TDZ\'', 'TDZ', '\'1\'', '1'], JSON.stringify(item)).toContain(item.result); }, 60000); it('enters a function of the program that a builtin calls', async () => { @@ -145,6 +201,13 @@ describe('The server\'s JavaScript stepper against a real js-debug (issues #1130 expect(answer.message).toBe('Stepped into'); }, 60000); + it('follows a call through Node\'s once-wrapper into the program\'s listener: a walk longer than 24 engine steps', async () => { + await pausedAt('emits to a once listener'); + const answer = await step('step_into'); + expectLanding(answer, 'in the once listener'); + expect(answer.message).toBe('Stepped into'); + }, 60000); + it('does not follow a call into a later task: the next line, not the timer\'s callback', async () => { await pausedAt('starts a later task'); expectLanding(await step('step_into'), 'after setTimeout'); @@ -243,6 +306,48 @@ describe('The server\'s JavaScript stepper against a real js-debug (issues #1130 }, 60000); }); + describe('a bundle: one script, a dependency\'s lines and the program\'s (C1)', () => { + const BUNDLE = path.resolve(here, '../../../fixtures/javascript/step-skipped-code/bundle'); + const SCRIPT = path.join(BUNDLE, 'out', 'bundle.js'); + const APP = path.join(BUNDLE, 'src', 'app.js'); + const LIB = path.join(BUNDLE, 'node_modules', 'blib', 'index.js'); + /** The 1-based line of `file` that carries `// `. */ + const markerLine = (file: string, marker: string): number => { + const index = fs.readFileSync(file, 'utf8').split('\n').findIndex((line) => new RegExp(`// ${marker}(?![A-Z-])`).test(line)); + if (index === -1) { + throw new Error(`no line marked "${marker}" in ${file}`); + } + return index + 1; + }; + + function expectInApp(answer: StopAnswer & { ms: number }, marker: string): void { + expect(answer, JSON.stringify(answer)).toMatchObject({ success: true, state: 'paused' }); + expect(answer.pending, JSON.stringify(answer)).toBeUndefined(); + expect(answer.stopReason, JSON.stringify(answer)).toBeUndefined(); + expect(answer.location?.file ?? '', JSON.stringify(answer)).toMatch(/app\.js$/); + expect(answer.location?.line, JSON.stringify(answer)).toBe(markerLine(APP, marker)); + expect(answer.ms, `took ${answer.ms} ms: ${JSON.stringify(answer)}`).toBeLessThan(PROMPT_MS); + } + + it('steps on through the program\'s lines after a stop inside the bundled dependency', async () => { + server = await startStdioClient({ name: 'js-stepper-bundle' }); + await server.createSession('javascript', 'js-stepper-bundle'); + const set = await server.call('set_breakpoint', { file: LIB, line: markerLine(LIB, 'BLIB-WORK') }); + expect(set.success, JSON.stringify(set)).toBe(true); + let stop = await server.call('start_debugging', { scriptPath: SCRIPT }); + if (stop.state !== 'paused') { + stop = await server.call('wait_for_stop', { timeout: 20000 }); + } + expect(stop, JSON.stringify(stop)).toMatchObject({ success: true, state: 'paused' }); + expect(stop.location?.file ?? '', JSON.stringify(stop)).toMatch(/blib[\\/]index\.js$/); + // The dependency's code is skipped: step_over comes back to the caller's next line. + expectInApp(await step('step_over'), 'B-AFTER-LIBWORK'); + // The program's lines of the same script are program code to the steps after it. + expectInApp(await step('step_over'), 'B-CALLS-MINE'); + expectInApp(await step('step_into'), 'B-IN-MINE'); + }, 60000); + }); + describe('a session that chose plain steps', () => { it('justMyCode: false lands in Node\'s own code, where V8 lands', async () => { await pausedAt('the first console.log', { justMyCode: false }); diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-true.json index 5f9da8feb..d3b002d58 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-true.json @@ -240,7 +240,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-unset.json index 3157a2450..599c62dde 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-unset.json @@ -240,7 +240,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-true.json index 0f7668313..4345309ba 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-true.json @@ -240,7 +240,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-unset.json index dc23b8756..ccf264e32 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-unset.json @@ -240,7 +240,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-true.json index 0f7668313..4345309ba 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-true.json @@ -240,7 +240,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-unset.json index dc23b8756..ccf264e32 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-unset.json @@ -240,7 +240,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-true.json index f224bcb08..0e01a607c 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-true.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-unset.json index 5b740732a..88966b5ee 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-unset.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-true.json index 6dfc4ffbd..06fdf3839 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-true.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-unset.json index 26ffcf8b4..2f4f22b88 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-unset.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-true.json index 6dfc4ffbd..06fdf3839 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-true.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-unset.json index 26ffcf8b4..2f4f22b88 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-unset.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-true.json index 873381aac..1046a0b2c 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-true.json @@ -236,7 +236,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-unset.json index 22127557d..f31b3823f 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-unset.json @@ -236,7 +236,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-true.json index c0950fcb2..a9f841e57 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-true.json @@ -236,7 +236,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-unset.json index fc6d2805d..2ed23104e 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-unset.json @@ -236,7 +236,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-true.json index c0950fcb2..a9f841e57 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-true.json @@ -236,7 +236,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-unset.json index fc6d2805d..2ed23104e 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-unset.json @@ -236,7 +236,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-true.json index f224bcb08..0e01a607c 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-true.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-unset.json index 5b740732a..88966b5ee 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-unset.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-true.json index 6dfc4ffbd..06fdf3839 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-true.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-unset.json index 26ffcf8b4..2f4f22b88 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-unset.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-true.json index 6dfc4ffbd..06fdf3839 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-true.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-unset.json index 26ffcf8b4..2f4f22b88 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-unset.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code, or lands on the next line and says how far it walked without reaching it); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps or 3 s, whichever comes first, or else steps out and says how far it walked); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/session/session-manager-dap.test.ts b/tests/core/unit/session/session-manager-dap.test.ts index 2d5b2ff38..03e8f07ea 100644 --- a/tests/core/unit/session/session-manager-dap.test.ts +++ b/tests/core/unit/session/session-manager-dap.test.ts @@ -25,6 +25,7 @@ import { threadStacksHandler } from '../../../test-utils/mocks/thread-stacks.js' import { ErrorMessages } from '../../../../src/utils/error-messages.js'; import { ProxyNotRunningError } from '../../../../src/errors/debug-errors.js'; import { DapResponseError } from '../../../../src/proxy/dap-response-error.js'; +import { PROXY_STEP_LEFT_STACK_EVENT } from '../../../../src/proxy/dap-proxy-interfaces.js'; /** * A `breakpoint` event body as the proxy delivers it for a CHILD session event. @@ -1745,6 +1746,69 @@ describe('SessionManager - DAP Operations', () => { expect(data.message).toMatch(/back at the line the step was issued from/); }); + // I3 (issue #1130): the JavaScript policy's "left the frame" sentence is + // true only for a step the proxy's stepper ended by resuming the program, + // which it records with an event of its own. A step still executing in + // its own frame (a step_over of a long call) gets the generic wording. + describe('the pending wording of a step the proxy stepper ended by leaving the stack (I3)', () => { + const LEFT = 'Left its frame, by the stepper\'s own record.'; + + function withLeftStackHook(manager: SessionManager): ReturnType { + const hook = vi.fn((info: { stepLeftStack?: boolean }) => (info.stepLeftStack ? LEFT : undefined)); + const original = (manager as unknown as { selectPolicy: (language: string) => AdapterPolicy }).selectPolicy.bind(manager); + vi.spyOn(manager as unknown as { selectPolicy: (language: string) => AdapterPolicy }, 'selectPolicy') + .mockImplementation((language: string) => ({ ...original(language), describePendingStop: hook })); + return hook; + } + + async function pendingStepOver(sessionId: string, events: Array<[string, unknown]>) { + dependencies.mockProxyManager.sendDapRequest = vi.fn().mockImplementation(async (command: string) => { + if (command === 'next') { + process.nextTick(() => { + for (const [event, body] of events) { + dependencies.mockProxyManager.emit('dap-event', event, body); + } + }); + } + if (command === 'stackTrace') { + const frame = { id: 1, name: 'main', source: { path: '/app/main.js' }, line: 12, column: 3 }; + return { success: true, body: { stackFrames: [frame], totalFrames: 1 } }; + } + return { success: true }; + }); + const stepPromise = sessionManager.stepOver(sessionId); + await vi.advanceTimersByTimeAsync(6000); + return (await stepPromise).data as { message?: string; pending?: boolean }; + } + + it('carries the sentence when the stepper recorded that the step left the stack', async () => { + const session = await createPausedSession(sessionManager, dependencies); + const hook = withLeftStackHook(sessionManager); + const data = await pendingStepOver(session.id, [[PROXY_STEP_LEFT_STACK_EVENT, { threadId: 1 }]]); + expect(data.pending).toBe(true); + expect(data.message).toBe(`${ErrorMessages.stepStillRunning(5)} ${LEFT}`); + expect(hook).toHaveBeenCalledWith(expect.objectContaining({ operation: 'step', stepLeftStack: true })); + }); + + it('carries the generic wording for a step with no such record: still executing, in its own frame or a call', async () => { + const session = await createPausedSession(sessionManager, dependencies); + withLeftStackHook(sessionManager); + // Another custom event is not the record. + const data = await pendingStepOver(session.id, [['flutter.appStarted', {}]]); + expect(data.pending).toBe(true); + expect(data.message).toBe(ErrorMessages.stepStillRunning(5)); + }); + + it('reads the record of this step only: the one a finished step left behind does not carry over', async () => { + const session = await createPausedSession(sessionManager, dependencies); + withLeftStackHook(sessionManager); + // The record arrives while no step is waiting (the last step had already answered). + dependencies.mockProxyManager.emit('dap-event', PROXY_STEP_LEFT_STACK_EVENT, { threadId: 1 }); + const data = await pendingStepOver(session.id, []); + expect(data.message).toBe(ErrorMessages.stepStillRunning(5)); + }); + }); + // Issue #879: the Dart SDK adapter's `next` stops once per token position // (measured: app.dart:29 took three step_overs, columns 16, 26, 32). describe('an adapter that steps by token position (issue #879)', () => { diff --git a/tests/fixtures/javascript/step-skipped-code/bundle/node_modules/blib/index.js b/tests/fixtures/javascript/step-skipped-code/bundle/node_modules/blib/index.js new file mode 100644 index 000000000..8e7cadad4 --- /dev/null +++ b/tests/fixtures/javascript/step-skipped-code/bundle/node_modules/blib/index.js @@ -0,0 +1,11 @@ +// A dependency bundled into the program's single script. +'use strict'; +function libWork(n) { + let t = n; // BLIB-WORK + t += 1; + return t; // BLIB-LAST +} +function libCall(fn) { + return fn(2); // BLIB-CALL +} +module.exports = { libWork, libCall }; diff --git a/tests/fixtures/javascript/step-skipped-code/bundle/out/bundle.js b/tests/fixtures/javascript/step-skipped-code/bundle/out/bundle.js new file mode 100644 index 000000000..236b3908e --- /dev/null +++ b/tests/fixtures/javascript/step-skipped-code/bundle/out/bundle.js @@ -0,0 +1,43 @@ +var __getOwnPropNames = Object.getOwnPropertyNames; +var __commonJS = (cb, mod) => function __require() { + try { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; + } catch (e) { + throw mod = 0, e; + } +}; + +// node_modules/blib/index.js +var require_blib = __commonJS({ + "node_modules/blib/index.js"(exports2, module2) { + "use strict"; + function libWork2(n) { + let t = n; + t += 1; + return t; + } + function libCall2(fn) { + return fn(2); + } + module2.exports = { libWork: libWork2, libCall: libCall2 }; + } +}); + +// src/app.js +var { libWork, libCall } = require_blib(); +function mine(v) { + const w = v * 3; + return w; +} +function run() { + const a = libWork(1); + const b = a + 1; + const c = mine(b); + const d = c + 1; + const e = libCall(mine); + const f = e + 1; + return f; +} +var out = run(); +console.log("bundle done", out); +//# sourceMappingURL=bundle.js.map diff --git a/tests/fixtures/javascript/step-skipped-code/bundle/out/bundle.js.map b/tests/fixtures/javascript/step-skipped-code/bundle/out/bundle.js.map new file mode 100644 index 000000000..fa5cddb28 --- /dev/null +++ b/tests/fixtures/javascript/step-skipped-code/bundle/out/bundle.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../node_modules/blib/index.js", "../src/app.js"], + "sourcesContent": ["// A dependency bundled into the program's single script.\n'use strict';\nfunction libWork(n) {\n let t = n; // BLIB-WORK\n t += 1;\n return t; // BLIB-LAST\n}\nfunction libCall(fn) {\n return fn(2); // BLIB-CALL\n}\nmodule.exports = { libWork, libCall };\n", "// The program, bundled with its dependency into out/bundle.js (one V8 script, one source map).\nconst { libWork, libCall } = require('blib');\nfunction mine(v) {\n const w = v * 3; // B-IN-MINE\n return w; // B-MINE-RETURN\n}\nfunction run() {\n const a = libWork(1); // B-CALLS-LIBWORK\n const b = a + 1; // B-AFTER-LIBWORK\n const c = mine(b); // B-CALLS-MINE\n const d = c + 1; // B-AFTER-MINE\n const e = libCall(mine); // B-CALLS-LIBCALL\n const f = e + 1; // B-AFTER-LIBCALL\n return f; // B-RUN-RETURN\n}\nconst out = run(); // B-CALLS-RUN\nconsole.log('bundle done', out); // B-END\n"], + "mappings": ";;;;;;;;;;AAAA;AAAA,+BAAAA,UAAAC,SAAA;AAAA;AAEA,aAASC,SAAQ,GAAG;AAClB,UAAI,IAAI;AACR,WAAK;AACL,aAAO;AAAA,IACT;AACA,aAASC,SAAQ,IAAI;AACnB,aAAO,GAAG,CAAC;AAAA,IACb;AACA,IAAAF,QAAO,UAAU,EAAE,SAAAC,UAAS,SAAAC,SAAQ;AAAA;AAAA;;;ACTpC,IAAM,EAAE,SAAS,QAAQ,IAAI;AAC7B,SAAS,KAAK,GAAG;AACf,QAAM,IAAI,IAAI;AACd,SAAO;AACT;AACA,SAAS,MAAM;AACb,QAAM,IAAI,QAAQ,CAAC;AACnB,QAAM,IAAI,IAAI;AACd,QAAM,IAAI,KAAK,CAAC;AAChB,QAAM,IAAI,IAAI;AACd,QAAM,IAAI,QAAQ,IAAI;AACtB,QAAM,IAAI,IAAI;AACd,SAAO;AACT;AACA,IAAM,MAAM,IAAI;AAChB,QAAQ,IAAI,eAAe,GAAG;", + "names": ["exports", "module", "libWork", "libCall"] +} diff --git a/tests/fixtures/javascript/step-skipped-code/bundle/src/app.js b/tests/fixtures/javascript/step-skipped-code/bundle/src/app.js new file mode 100644 index 000000000..f17e0d090 --- /dev/null +++ b/tests/fixtures/javascript/step-skipped-code/bundle/src/app.js @@ -0,0 +1,17 @@ +// The program, bundled with its dependency into out/bundle.js (one V8 script, one source map). +const { libWork, libCall } = require('blib'); +function mine(v) { + const w = v * 3; // B-IN-MINE + return w; // B-MINE-RETURN +} +function run() { + const a = libWork(1); // B-CALLS-LIBWORK + const b = a + 1; // B-AFTER-LIBWORK + const c = mine(b); // B-CALLS-MINE + const d = c + 1; // B-AFTER-MINE + const e = libCall(mine); // B-CALLS-LIBCALL + const f = e + 1; // B-AFTER-LIBCALL + return f; // B-RUN-RETURN +} +const out = run(); // B-CALLS-RUN +console.log('bundle done', out); // B-END diff --git a/tests/fixtures/javascript/step-skipped-code/steps.cjs b/tests/fixtures/javascript/step-skipped-code/steps.cjs index e3c4792bb..32627008f 100644 --- a/tests/fixtures/javascript/step-skipped-code/steps.cjs +++ b/tests/fixtures/javascript/step-skipped-code/steps.cjs @@ -13,6 +13,14 @@ function listener(value) { } emitter.on('x', listener); +// Node's once-wrapper calls this one: a longer walk through Node's code than on(). +const onceEmitter = new EventEmitter(); +function onceListener(value) { + const tripled = value * 3; // MARK: in the once listener + return tripled; +} +onceEmitter.once('y', onceListener); + function mapper(value) { return value + 1; // MARK: in the mapper } @@ -66,9 +74,13 @@ function syncPart() { async function main() { console.log('first line printed'); // MARK: the first console.log const afterLog = 1; // MARK: after the first console.log + console.log('a later line printed'); // MARK: a later console.log + const afterLaterLog = 1; // MARK: after a later console.log + for (const item of [1, 2, 3]) console.log('item', item); // MARK: a one-line loop const mapped = [1, 2].map(mapper); // MARK: a builtin calls the program emitter.emit('x', 1); // MARK: Node code calls the program const afterEmit = 2; // MARK: after emit + onceEmitter.emit('y', 1); // MARK: emits to a once listener setTimeout(() => {}, 0); // MARK: starts a later task const afterTimeout = 3; // MARK: after setTimeout const called = callee(); // MARK: calls a function with a breakpoint @@ -80,7 +92,7 @@ async function main() { setTimeout(timerCallback, 0); setTimeout(laterCallback, 30); await sleep(120); - return [afterLog, mapped, afterEmit, afterTimeout, called, fromSync, awaited, afterAwait, again, afterAgain]; + return [afterLog, afterLaterLog, mapped, afterEmit, afterTimeout, called, fromSync, awaited, afterAwait, again, afterAgain]; } main().then(() => { diff --git a/tests/proxy/dap-proxy-worker-live-update.test.ts b/tests/proxy/dap-proxy-worker-live-update.test.ts index fdfdbec04..81e829a9e 100644 --- a/tests/proxy/dap-proxy-worker-live-update.test.ts +++ b/tests/proxy/dap-proxy-worker-live-update.test.ts @@ -9,7 +9,7 @@ import path from 'path'; import { describe, it, expect, beforeEach, vi } from 'vitest'; import { DefaultAdapterPolicy, type AdapterPolicy } from '@debugmcp/shared'; import { DapProxyWorker } from '../../src/proxy/dap-proxy-worker.js'; -import type { DapProxyDependencies, ProxyInitPayload } from '../../src/proxy/dap-proxy-interfaces.js'; +import { PROXY_STEP_LEFT_STACK_EVENT, type DapProxyDependencies, type ProxyInitPayload } from '../../src/proxy/dap-proxy-interfaces.js'; import { createMockDapClient } from '../test-utils/mocks/dap-client.js'; import { createMockLogger } from '../test-utils/helpers/test-dependencies.js'; import { createMockFileSystem, createMockProcessSpawner } from '../test-utils/mocks/dap-proxy-doubles.js'; @@ -111,6 +111,16 @@ describe('DapProxyWorker live update events and resumes (issue #876)', () => { expect(forwardedEvents()).toEqual([]); }); + // Not a live-update event, forwarded the same way: the proxy stepper's + // record that it ended a step by resuming the program (issue #1130, I3), + // which the pending step's answer reads. + it("forwards the proxy stepper's left-stack record to the session, with its body", async () => { + await configure({ ...DefaultAdapterPolicy, name: 'plain' } as AdapterPolicy); + mockDapClient.emit(PROXY_STEP_LEFT_STACK_EVENT, { threadId: 1 }); + expect(forwardedEvents()).toEqual([PROXY_STEP_LEFT_STACK_EVENT]); + expect(sent().find((m) => m.event === PROXY_STEP_LEFT_STACK_EVENT)?.body).toEqual({ threadId: 1 }); + }); + it("clears the last stop when one of the feature's resume commands goes out", async () => { await configure(liveUpdatePolicy()); mockDapClient.emit('stopped', { reason: 'breakpoint', threadId: 1 }); diff --git a/tests/proxy/js-stepper.test.ts b/tests/proxy/js-stepper.test.ts index 9a7800802..e562152e9 100644 --- a/tests/proxy/js-stepper.test.ts +++ b/tests/proxy/js-stepper.test.ts @@ -13,7 +13,8 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; import { EventEmitter } from 'events'; import type { DebugProtocol } from '@vscode/debugprotocol'; -import { JsStepper, type JsStepperTunables } from '../../src/proxy/js-stepper.js'; +import { JsStepper, DEFAULT_JS_STEPPER_TUNABLES, type JsStepperTunables } from '../../src/proxy/js-stepper.js'; +import { PROXY_STEP_LEFT_STACK_EVENT } from '../../src/proxy/dap-proxy-interfaces.js'; import { ErrorMessages } from '../../src/utils/error-messages.js'; interface Frame { @@ -24,8 +25,14 @@ interface Frame { col?: number; /** js-debug marks it skipped code. */ skipped?: boolean; - /** The mark's wording; "Skipped by skipFiles" is a script-level verdict. */ + /** The mark's wording, js-debug's `source.origin`: "Skipped by skipFiles" (the default) or "Skipped by smartStep". */ origin?: string; + /** + * The source js-debug names for the frame. By default: `/…` + * for a `node:` script (with a sourceReference, as js-debug answers for + * Node's own modules), `/app/