From 6654fdf45560aee7a704872dbaaa17d97d7e04af Mon Sep 17 00:00:00 2001 From: JF Date: Sat, 28 Nov 2026 22:48:15 -0500 Subject: [PATCH 1/9] fix(session): one record per stop, and each answer pinned to the stop it describes An answer that describes a stop could carry one stop's location and the next stop's reason: the stop was read after an awaited stack read, so a second stop that arrived during the read replaced it under the answer (#1348). The same happened in step_over, pause_execution and start_debugging, and inside the snapshot, which could carry one stop's frames with another's exception. A stop's identity used to be the identity of the `lastStop` object, compared by reference in a dozen places. Now: - Each stop the core applies gets a record with an id (`src/session/stop-record.ts`), which holds the only writers of `lastStop`. Every comparison of two stops is by that id: the step and pause bookkeeping, the snapshot's diff base, the exception-details merge, the frame-anchor resolver's gate and cache, the shadow table. - An answer that describes a stop takes the stop's id when its reads start and checks each dependent read against it (`src/session/inspection/pinned-stop-read.ts`). If the stop changed, the reads are made again once. If it changed again, the answer gives the current stop's reason and state, no landing, and says the stop changed while it was read. - Pinned: wait_for_stop, the steps (landing, snapshot, origin), pause_execution, start_debugging and a replayed restart, a launch's paused child, a hot restart, attach_to_process, a hot reload that stops the program, and get_stack_trace. Not changed: the worker, the IPC envelope, the proxy's forwarding, the adapter policy contract; no stop's reason; nothing is hidden or dropped. Two existing expectations changed and are stated in the tests: a step whose first landing read stalls now holds its answer for that read instead of being settled by a later stop's reader, and an answer whose stop was replaced during its reads now describes the newer stop, read again. Not covered yet: get_local_variables, get_variables, get_scopes and evaluate_expression take no pin. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn82vMcRzWFDD9aUbZs --- CLAUDE.md | 2 +- changelog.d/1348.fixed.md | 1 + docs/architecture/session-state-machine.md | 47 +- docs/tool-reference.md | 17 + packages/shared/src/utils/secret-redaction.ts | 5 +- src/server/handlers/inspection-tools.ts | 30 +- src/server/handlers/shared.ts | 7 +- src/session/attach/attach-controller.ts | 24 +- src/session/execution/execution-controller.ts | 391 +++++++++---- src/session/execution/pause-coordinator.ts | 2 +- src/session/execution/pause-intent.ts | 17 +- .../inspection/frame-anchor-resolver.ts | 43 +- src/session/inspection/pinned-stop-read.ts | 150 +++++ src/session/inspection/stop-location.ts | 11 +- src/session/inspection/stop-snapshot.ts | 30 +- src/session/launch/debug-launcher.ts | 55 +- .../live-update/live-update-controller.ts | 16 +- src/session/machine/shadow.ts | 14 +- src/session/machine/transition-table.ts | 8 +- src/session/session-manager-core.ts | 72 ++- src/session/session-store.ts | 31 +- src/session/stop-record.ts | 215 +++++++ src/utils/error-messages.ts | 11 + .../server/stop-pins-through-tools.test.ts | 159 ++++++ .../breakpoint-controller-armed-pause.test.ts | 8 +- .../session/inspection/stop-snapshot.test.ts | 30 +- .../unit/session/pause-coordinator.test.ts | 2 +- .../session-manager-attach-modes.test.ts | 42 ++ .../unit/session/session-manager-dap.test.ts | 18 +- .../session-manager-integration.test.ts | 2 +- .../session/session-manager-snapshot.test.ts | 11 +- .../session-manager-stop-pin-routes.test.ts | 526 ++++++++++++++++++ .../session/session-manager-stop-pins.test.ts | 294 ++++++++++ .../unit/session/session-state-shadow.test.ts | 6 +- .../unit/session/stop-record-writes.test.ts | 207 +++++++ tests/core/unit/session/stop-record.test.ts | 209 +++++++ tests/test-utils/helpers/stop-record.ts | 23 + ...ession-manager-operations-coverage.test.ts | 25 +- 38 files changed, 2482 insertions(+), 279 deletions(-) create mode 100644 changelog.d/1348.fixed.md create mode 100644 src/session/inspection/pinned-stop-read.ts create mode 100644 src/session/stop-record.ts create mode 100644 tests/core/unit/server/stop-pins-through-tools.test.ts create mode 100644 tests/core/unit/session/session-manager-stop-pin-routes.test.ts create mode 100644 tests/core/unit/session/session-manager-stop-pins.test.ts create mode 100644 tests/core/unit/session/stop-record-writes.test.ts create mode 100644 tests/core/unit/session/stop-record.test.ts create mode 100644 tests/test-utils/helpers/stop-record.ts diff --git a/CLAUDE.md b/CLAUDE.md index 92d6042b2..8b832581c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -310,7 +310,7 @@ The codebase follows a **layered architecture with dependency injection** and ** - `breakpoints/anchor-resolution.ts` (`reresolveAnchors`) and `breakpoints/launch-warnings.ts` (pure warning builders) - `execution/execution-controller.ts` (`ExecutionController`): stepping (table-driven over `STEP_KINDS`), continue, pause, thread list, `waitForStop`; `execution/session-state-wait.ts` (`waitForSessionState`): the one level-triggered wait on a session's state — it re-reads the state in a microtask after each change (`OperationsContext.onStateChange`, fed by `_updateSessionState`), so an entry stop the core auto-continues within one call stack is never reported (issue #849) - `inspection/stop-anchor.ts` (`selectStopAnchor`: the one verdict on which thread a stop is anchored on, shared by the attach controller and the frame-anchor resolver — a `pause` reported on a thread with no program frame moves to the first sibling whose stack reaches the program and says so; breakpoint/step/exception/entry stops never move; issues #904/#898), `inspection/stop-location.ts` (`describeStopLocation`: the one landing read behind the pause, step, wait_for_stop, attach and launch answers — a `start_debugging`/`restart_debugging` that is paused when it answers reads it too, issue #951 — `location`, and `threadId`/`note` when the answer is anchored off the reported thread or no frame is program code; the landing also carries its resolver read internally as `StopLanding.stackResult`, which `inspection/stop-snapshot.ts` (`composeStopSnapshot`, issue #982) turns into the bounded `snapshot` — exception from the redacted stop record, top ≤3 frames, locals via `extractLocalsFromResolved` under `snapshotLocalsLimits` and the `snapshotLocalsTimeoutMs` tunable — that every PAUSED arrival answer carries (entry stops, dry runs, pending answers and the pause "Already paused" fast path carry none; `DEBUG_MCP_NO_SNAPSHOT` opts out, explicit variable-access mode withholds locals); the handlers hoist the landing fields and the snapshot through `handlers/shared.ts` `hoistStopLanding` — attach included (issue #982 parity) — which also reads the line context and the stale-build sentence and dedupes the snapshot out of the embedded `data`), `inspection/expression-evaluator.ts` (`ExpressionEvaluator`), `jvm/redefine-classes-controller.ts` (`RedefineClassesController`), `mirror/mirror-controller.ts` (`MirrorController`) - - Collaborators see the facade through `OperationsContext` (`operations-context.ts`), whose members are late-bound arrows and getters — never captured references — so reassigning a facade method or writing a tunable on a live instance is visible to them; each takes the narrowest `Pick<>` slice it uses. Collaborator-to-collaborator dependencies are constructor arguments (`DebugLauncher(ctx, proxyLauncher, breakpoints, inFlight)`, `AttachController(ctx, proxyLauncher, breakpoints, pauseCoordinator, inFlight)`) held as captured instance references: their methods resolve at call time, so `vi.spyOn(internals(ops).proxyLauncher, 'start')` intercepts, but reassigning a collaborator field after construction is not observed. The facade owns one shared `InFlightGuard` (`in-flight-guard.ts`, issue #711) that the launcher and the attach controller both take: `startDebugging`, `restartDebugging`, `attachToProcess` and `detachFromProcess` each claim the session before their first await and release it in `finally`, so one launch-shaped call per session at a time; `restartDebugging` replays through the launcher's private `launch()` under its own claim, never through the facade's `startDebugging`. The guard also holds the session's ending in flight (issue #1325): `close_debug_session` goes through the facade's `closeDebugSession` → `AttachController.closeSession`, and a close or a plain detach that arrives while another close or detach of the session is in flight joins it (`InFlightGuard.runEnding`/`ending`), and no second `disconnect` goes out after a confirmed release, also after a detach whose cleanup failed once its release was confirmed (the detach's record keeps the release; the joined close passes a confirmed one, `released` or `program-ended`, to `closeSessionReporting` as `releaseSent` and stops the worker itself; after a detach whose release was not confirmed, which may never have reached the adapter, or that failed before its release, the close sends its own, as one that joined nothing does); a terminating detach is refused instead. While an ending is in flight `InFlightGuard.tryAcquire` refuses every launch, restart or attach, whoever holds the claim ("This session is being closed …"), so an attach that was in flight when the close came and answers meanwhile lets nothing in under it. The close also claims the session when nothing holds it, and is itself never refused: with a launch-shaped call in flight it goes ahead unclaimed. The server's exit and the idle policy call `closeSessionReporting` directly, outside the join. Shared per-request DAP helpers live in `dap-request-helpers.ts` + - Collaborators see the facade through `OperationsContext` (`operations-context.ts`), whose members are late-bound arrows and getters — never captured references — so reassigning a facade method or writing a tunable on a live instance is visible to them; each takes the narrowest `Pick<>` slice it uses. Collaborator-to-collaborator dependencies are constructor arguments (`DebugLauncher(ctx, proxyLauncher, breakpoints, inFlight)`, `AttachController(ctx, proxyLauncher, breakpoints, pauseCoordinator, inFlight)`) held as captured instance references: their methods resolve at call time, so `vi.spyOn(internals(ops).proxyLauncher, 'start')` intercepts, but reassigning a collaborator field after construction is not observed. The facade owns one shared `InFlightGuard` (`in-flight-guard.ts`, issue #711) that the launcher and the attach controller both take: `startDebugging`, `restartDebugging`, `attachToProcess` and `detachFromProcess` each claim the session before their first await and release it in `finally`, so one launch-shaped call per session at a time; `restartDebugging` replays through the launcher's private `launch()` under its own claim, never through the facade's `startDebugging`. The guard also holds the session's ending in flight (issue #1325): `close_debug_session` goes through the facade's `closeDebugSession` → `AttachController.closeSession`, and a close or a plain detach that arrives while another close or detach of the session is in flight joins it (`InFlightGuard.runEnding`/`ending`), and no second `disconnect` goes out after a confirmed release, also after a detach whose cleanup failed once its release was confirmed (the detach's record keeps the release; the joined close passes a confirmed one, `released` or `program-ended`, to `closeSessionReporting` as `releaseSent` and stops the worker itself; after a detach whose release was not confirmed, which may never have reached the adapter, or that failed before its release, the close sends its own, as one that joined nothing does); a terminating detach is refused instead. While an ending is in flight `InFlightGuard.tryAcquire` refuses every launch, restart or attach, whoever holds the claim ("This session is being closed …"), so an attach that was in flight when the close came and answers meanwhile lets nothing in under it. The close also claims the session when nothing holds it, and is itself never refused: with a launch-shaped call in flight it goes ahead unclaimed. The server's exit and the idle policy call `closeSessionReporting` directly, outside the join. Shared per-request DAP helpers live in `dap-request-helpers.ts`. Each stop has a record (`stop-record.ts`, issue #1362: an id minted when the core applies it, its run, thread, reason, whether it is shown, and the step or pause it answers; `lastStop` is its `info`, written only by that module, and stops are compared by record id), and every answer that describes a stop reads under a pin of it (`inspection/pinned-stop-read.ts` `readPinnedStop`: pinned before the first await, every read checked, read again once if the stop changed, and answered with the current stop and no landing if it changed again; issue #1348) - Session state has one gate, `SessionManagerCore._updateSessionState`, and every call of it names its site and event (`{ site, event, facts? }`, paired by the compiler through `EVENT_OF_SITE`). `src/session/machine/` holds the transition table (`transition-table.ts`) and its shadow check (`shadow.ts`), which judges each write against the table and records a verdict without refusing anything (`MCP_STATE_SHADOW`: `record` by default, `strict` in the unit project, `off`). See `docs/architecture/session-state-machine.md` for the verdicts, the `legacy`/`future` marks, and how to add a site, an event or a row - Coordinates ProxyManager instances (one per session) - Handles breakpoint management and queuing diff --git a/changelog.d/1348.fixed.md b/changelog.d/1348.fixed.md new file mode 100644 index 000000000..f1bca2735 --- /dev/null +++ b/changelog.d/1348.fixed.md @@ -0,0 +1 @@ +**A stop answer describes one stop, also when the program stops again while the answer is being read** — `wait_for_stop`, `step_over`/`step_into`/`step_out`, `pause_execution`, a `start_debugging` or `restart_debugging` that answers paused (and its `pausedChild`), `attach_to_process`, a `hot_reload` that stops a running program, and `get_stack_trace` read where the program stopped with a request to the debugger, and took the stop they describe after that read returned. When a second stop arrived during the read, the answer carried the first stop's `location`, frames and snapshot with the second stop's reason, `lastStop`, exception and step note, and said nothing of it: a `wait_for_stop` could answer `Paused (exception) at app.py:11` for an exception raised at line 50, and a step could add "The program is back at the line the step was issued from" to a stop somewhere else. Each stop now gets a record with an id when the server applies it, and each of these answers takes that id before its first read and checks every read against it (the location, the frames, the snapshot's exception and locals, the step's provenance note; the source line and the stale-build note are read from the answer's own location). If the stop changed, all of the answer's reads are made again for the stop the program is at now; if it changed again during that second read, the answer gives that stop's reason and state with no location, frames or snapshot, and its `note` says that the program stopped again while the answer was being read and that `get_stack_trace` and `get_local_variables` read that stop (#1348, #1362) diff --git a/docs/architecture/session-state-machine.md b/docs/architecture/session-state-machine.md index 88d2e9940..6cafddfd8 100644 --- a/docs/architecture/session-state-machine.md +++ b/docs/architecture/session-state-machine.md @@ -82,6 +82,51 @@ which holds the test-only cast and runs no gate, shadow, timestamp update or listeners; a fake with a type of its own is a plain object and is written directly. +## The stop record and the pins + +The first part of the `stop-record` stage (issue #1362; it closes #1348). A stop gets a record +when the core applies it ([`stop-record.ts`](../../src/session/stop-record.ts)): an id that is +never reused in the process, the run it arrived on (the session's proxy generation), its session, +thread, reason, whether it is shown (`false` for the entry stop the core resumes unseen), and the +operation in flight that it answers (`cause`: a pause armed on this run's proxy, else the step +sent on its thread; the step in flight and the pause intent carry ids for this). The record's +`info` is the session's `lastStop`, the object every answer projects; the record itself is never +emitted. The field for the worker's receipt sequence number (`seq`) is in the type and empty: the +second part stamps it in the worker and applies no observation older than one already applied. + +What a session has recorded, the stop it is at and the last stop it showed are readings of these +records: `stopRecordOf` (the record behind `lastStop`, with today's lifetime: a hidden stop is +recorded while its resume is in flight and erased after it), `currentStopOf` (that record while +the session is paused; a reading of the state, so nothing is cleared on a resume or restored by a +refused one), and `lastShownStop` (kept across resumes and hidden stops, reset per run; nothing +reads it yet). Every write of `lastStop` in shipped code is one of the module's three functions, +and every comparison of two stops is by record id, which +[`stop-record-writes.test.ts`](../../tests/core/unit/session/stop-record-writes.test.ts) checks +by name across `src/` and the package sources (its header says what a scan of names cannot see). +Tests give a session a stop through +[`setStopForTest`](../../tests/test-utils/helpers/stop-record.ts); a `lastStop` written around +the module has no record. The shadow is handed the record ids as its stop identities. + +An answer that describes a stop pins it +([`pinned-stop-read.ts`](../../src/session/inspection/pinned-stop-read.ts)): it takes the +session's record before its first await, makes its reads under it (the landing, which reads the +pinned stop's reason and thread rather than the session's; the snapshot, whose exception, diff +base and locals check are the pinned stop's), and checks the pin when they end. If the session is +paused at another stop, all of the reads are made again once, under a pin of that stop; if it +changed again, the answer gives the current stop's reason and state, no landing, and +`ErrorMessages.stopChangedWhileRead`. A session that is not paused when the reads end is answered +by the rules it always had (ended as ended, running as pending), from the pinned stop. The answers +that pin: `wait_for_stop` (on the session the tree-aware selection names, its child releases +inside the pinned reads), the three steps (the first stopped event owns the answer; the snapshot, +composed once after any same-line repeats, is checked against the final landing's pin and reads +again if the landing's own re-read is unspent), `pause_execution`, the launch and hot-restart +answers and the launch's `pausedChild`, `attach_to_process`, a `hot_reload` of a running program +that stops it, and `get_stack_trace` (in the handler). The step's origin read before the step is +sent is pinned too: a stop that changes under it leaves the step without an origin. The probes are in +[`session-manager-stop-pins.test.ts`](../../tests/core/unit/session/session-manager-stop-pins.test.ts), +[`session-manager-stop-pin-routes.test.ts`](../../tests/core/unit/session/session-manager-stop-pin-routes.test.ts) +and [`stop-pins-through-tools.test.ts`](../../tests/core/unit/server/stop-pins-through-tools.test.ts). + ## The table A **phase** is a public state one to one (`created`, `starting`, `running`, `paused`, @@ -108,7 +153,7 @@ The stages a mark can name: | Stage | What it changes | |---|---| -| `stop-record` | One record per stop, stamped with a sequence number where the proxy receives it, which every answer reads; an event older than one already applied changes no phase. | +| `stop-record` | One record per stop, stamped with a sequence number where the proxy receives it, which every answer reads; an event older than one already applied changes no phase. The record and the answers' pins are in (above); the sequence number and the rule for an older event are the second part. | | `hidden-stop` | A stop the core resumes without showing it (an entry stop when `stopOnEntry` is off) never enters `paused`. | | `endings` | Every ending of a run is one record, which collects the evidence of every terminal event that reaches it (the program's exit, `terminated`, the worker's exit). | | `admission` | Which calls may run while another call or an ending is in flight on the session, and what a refused or unanswered request leaves behind. | diff --git a/docs/tool-reference.md b/docs/tool-reference.md index bd43c311a..55848a86f 100644 --- a/docs/tool-reference.md +++ b/docs/tool-reference.md @@ -15,6 +15,7 @@ This document provides a complete reference for all tools available in mcp-debug - [clear_breakpoints](#clear_breakpoints) 3. [Execution Control](#execution-control) - [The stop snapshot](#the-stop-snapshot) + - [One stop per answer](#one-stop-per-answer) - [start_debugging](#start_debugging) - [restart_debugging](#restart_debugging) - [step_over](#step_over) @@ -600,6 +601,22 @@ crashing state costs zero extra tool calls: landing read failed. Under `DEBUG_MCP_VARIABLE_ACCESS=explicit` the `locals` half is withheld (exception and frames stay). `DEBUG_MCP_NO_SNAPSHOT=1` turns the snapshot off entirely. +### One stop per answer + +An answer that describes a stop — the stop answers above, a `hot_reload` of a running program that +stops it, `pausedChild` on a launch, and `get_stack_trace` — reads where the program stopped with requests +to the debugger, and the program can stop again while they are in flight (a resumed thread that +hits a breakpoint at once, a second thread's exception). Each stop has a record of its own, and +the answer takes the stop's identity before its first read and checks every read against it +(issues #1348, #1362), so its `location`, frames, `snapshot`, reason, `lastStop` and step note +always describe the same stop. If the stop changed, the answer's reads are made again for the +stop the program is at now, and the answer describes that one. If it changed again during that +second read, the answer gives the stop the program is at now (its reason, and `lastStop` where the +answer carries one) and its state, with no `location`, frames or `snapshot`, and `note` says: "The +program stopped again while this answer was being read, twice, so where it is paused was not read: +the reason given is the stop it is at now. get_stack_trace and get_local_variables read that stop." +The source line (`context`) and the stale-build note are read from the answer's own `location`. + ### start_debugging Starts debugging a script. diff --git a/packages/shared/src/utils/secret-redaction.ts b/packages/shared/src/utils/secret-redaction.ts index a167086ed..328f24af5 100644 --- a/packages/shared/src/utils/secret-redaction.ts +++ b/packages/shared/src/utils/secret-redaction.ts @@ -357,9 +357,8 @@ function redactDeep(value: unknown, ancestors: WeakSet, totals: Map { // exceptionInfo enrichment merges in place and an answer built during the // fetch should include it. The emitted copy is redacted (issue #982); the // stored record is never mutated. - const storedStop = carriesLastStop(sessionBefore?.state) ? sessionBefore?.lastStop : undefined; - const stackTrace = await ctx.getStackTrace(args.sessionId, includeInternals, args.threadId); + let storedStop = carriesLastStop(sessionBefore?.state) ? sessionBefore?.lastStop : undefined; + // The stop the answer describes, pinned before the fetch by its record + // (tracking issue #1362): a stop that changes under the fetch is read + // again once, and a second change answers the stop now current with no + // frames, and says so. + let pin = sessionBefore?.state === SessionState.PAUSED ? pinStop(sessionBefore) : undefined; + let stackTrace = await ctx.getStackTrace(args.sessionId, includeInternals, args.threadId); + if (pin && pinBroken(ctx.sessionManager.getSession(args.sessionId), pin)) { + const now = ctx.sessionManager.getSession(args.sessionId)!; + pin = pinStop(now); + storedStop = pin.stop?.info; + stackTrace = await ctx.getStackTrace(args.sessionId, includeInternals, args.threadId); + const after = ctx.sessionManager.getSession(args.sessionId); + if (pinBroken(after, pin)) { + const current = stopRecordOf(after); + const currentStop = current ? emittableStopInfo(ctx, current.info) : undefined; + return jsonResult({ + success: true, + stackFrames: [], + count: 0, + includeInternals, + stopReason: currentStop?.reason, + lastStop: currentStop, + note: ErrorMessages.stopChangedWhileRead() + }); + } + } const lastStop = storedStop ? emittableStopInfo(ctx, storedStop) : undefined; const payload: Record = { success: true, diff --git a/src/server/handlers/shared.ts b/src/server/handlers/shared.ts index e37f74447..590a17662 100644 --- a/src/server/handlers/shared.ts +++ b/src/server/handlers/shared.ts @@ -412,9 +412,10 @@ export async function hoistStopLanding( /** * The stop record as an answer may carry it (issue #982): a deep redacted - * copy unless redaction is off. The stored record is never mutated — the - * exceptionInfo merge guard and `lastStop !== before` checks compare by - * identity. wait_for_stop redacts in the session layer (its snapshot is + * copy unless redaction is off. The stored record is never mutated: the + * exceptionInfo merge writes into it, and a copy would not be the stop the + * session records (src/session/stop-record.ts compares by the record's id, + * and the record holds this object). wait_for_stop redacts in the session layer (its snapshot is * built from the same copy); this helper serves the handlers that read * `session.lastStop` directly (get_stack_trace, list_debug_sessions). */ diff --git a/src/session/attach/attach-controller.ts b/src/session/attach/attach-controller.ts index d4906427b..9b07962af 100644 --- a/src/session/attach/attach-controller.ts +++ b/src/session/attach/attach-controller.ts @@ -41,8 +41,9 @@ import type { ProxyLauncher } from '../launch/proxy-launcher.js'; import { recordExceptionArming } from '../launch/launch-arming.js'; import { verifyAttachThreads } from './attach-verification.js'; import { ATTACH_ANCHOR_BOUNDS, selectStopAnchor } from '../inspection/stop-anchor.js'; -import { describeStopLocation, landingFields } from '../inspection/stop-location.js'; -import { composeStopSnapshot } from '../inspection/stop-snapshot.js'; +import { landingFields } from '../inspection/stop-location.js'; +import { describedStop, readPinnedStop } from '../inspection/pinned-stop-read.js'; +import { resetStops } from '../stop-record.js'; import type { PauseCoordinator } from '../execution/pause-coordinator.js'; import { refuseChildSession, type EndingRecord, type InFlightGuard, type SessionEnding } from '../in-flight-guard.js'; import { releaseAttachedTarget, type TargetRelease } from './target-release.js'; @@ -209,7 +210,7 @@ export class AttachController { // Same per-attempt reset as startDebugging: an attach that fails before a // proxy exists emits no stop, so a stop left over from a prior run would // be reported as this attempt's once the session lands in ERROR (#720). - session.lastStop = undefined; + resetStops(session); session.snapshotDiffBase = undefined; // The previous run's proxy error and exit are not this attempt's either // (issue #896): assertTargetPresent below reports lastProxyError. @@ -462,15 +463,15 @@ export class AttachController { // Where the attach's stop landed, when it has one (issue #904): the // resolver's verdict on the reported thread. An idle js-debug target // pauses on a sourceless frame (issue #900), and only a note can say - // that the frame is not the program's. - const landing = session.state === SessionState.PAUSED - ? await describeStopLocation(this.ctx, sessionId, 'attach') - : undefined; - // The snapshot behind the landing (issue #982): attach parity with the - // other stop answers — same resolver result, bounded locals. - const snapshot = landing - ? await composeStopSnapshot(this.ctx, sessionId, landing.stackResult, 'attach') + // that the frame is not the program's. And the snapshot behind the + // landing (issue #982): attach parity with the other stop answers — + // same resolver result, bounded locals. Both under a pin of the stop + // taken before the read's first await (tracking issue #1362). + const described = session.state === SessionState.PAUSED + ? describedStop(await readPinnedStop(this.ctx, sessionId, 'attach')) : undefined; + const landing = described?.landing; + const snapshot = described?.snapshot; assertTargetPresent(); // Named the way the request addressed it: a PID, a host:port, or a @@ -498,6 +499,7 @@ export class AttachController { : attachedTo, ...(attachPausePending ? { pending: true } : {}), ...(landing ? landingFields(landing) : {}), + ...(described?.note ? { note: described.note } : {}), ...(snapshot ? { snapshot } : {}), ...(session.run.attachFootprint ? { attachFootprint: session.run.attachFootprint } : {}) }; diff --git a/src/session/execution/execution-controller.ts b/src/session/execution/execution-controller.ts index 143512d4d..61f4946b1 100644 --- a/src/session/execution/execution-controller.ts +++ b/src/session/execution/execution-controller.ts @@ -80,8 +80,19 @@ import { debuggerOffWhy, isDebuggerOff, type DebuggerOffView } from '../debugger import { samePath } from '../breakpoints/hit-verification.js'; import type { ExecutionContext } from '../operations-context.js'; import { runFactsOf, type RunFacts } from '../run-facts.js'; -import { describeStopLocation, landingFields, type StopLanding } from '../inspection/stop-location.js'; +import { landingFields, type StopLanding } from '../inspection/stop-location.js'; import { composeStopSnapshot } from '../inspection/stop-snapshot.js'; +import { readPinnedStop, type PinnedStopRead } from '../inspection/pinned-stop-read.js'; +import { + nextOperationId, + pinBroken, + pinStop, + stopIdOf, + stopRecordOf, + type StopId, + type StopPin, + type StopRecord +} from '../stop-record.js'; import type { PauseCoordinator } from './pause-coordinator.js'; import { waitForSubtreeSettle } from './session-state-wait.js'; import { describeReleasedChildren, describeTreeAnswer, withReleasedChildren } from './tree-settle.js'; @@ -179,9 +190,33 @@ export interface StepOperationOptions { * Hands each landing read to the caller (issue #983). A same-line-repeating * step (Dart, issue #879) reads a landing per attempt; the step snapshot * must be composed ONCE, from the final one — so `step()` sinks them here - * and composes after the repeat loop, never inside it. + * and composes after the repeat loop, never inside it, under the pin the + * landing was read with (tracking issue #1362). */ - onLanding?: (landing: StopLanding) => void; + onLanding?: (read: StepLandingRead) => void; +} + +/** One attempt's answer for a pinned landing, and the hint delivery it carries. */ +interface StepAnswer { + result: DebugResult; + /** Marks the step-in filter hint delivered, for the answer that is returned (issue #1328). */ + deliver?: () => void; +} + +/** + * What one attempt of a step read (issue #983; tracking issue #1362): the + * landing and the pin it was read and checked under (both absent when the stop + * changed twice, which leaves no landing), whether the one re-read is spent, + * and the attempt's own answer builders, which step() uses when the stop + * changes under the snapshot it composes afterwards. + */ +export interface StepLandingRead { + landing?: StopLanding; + pin?: StopPin; + reread: boolean; + answerAgain: (pin: StopPin, landing: StopLanding) => StepAnswer; + changedAnswer: (current: StopRecord | undefined) => DebugResult; + endedAnswer: () => DebugResult; } /** One record of the proxy's JavaScript stepper (issue #1130): the event's name and body. */ @@ -309,8 +344,9 @@ export class ExecutionController { let landed = false; try { // The last landing read, whatever attempt made it (issue #983): the - // snapshot is composed once per ANSWER, after any same-line repeats. - let finalLanding: StopLanding | undefined; + // snapshot is composed once per ANSWER, after any same-line repeats, + // under the pin that landing was read with. + let finalRead: StepLandingRead | undefined; const stepOptions: StepOperationOptions = { command, flavor: kind, @@ -322,25 +358,23 @@ export class ExecutionController { ...(origin ? { stepOrigin: origin } : {}), ...(stepFilterHint ? { stepFilterHint } : {}), ...(fromFrame ? { origin: { file: fromFrame.file, line: fromFrame.line, column: fromFrame.column } } : {}), - onLanding: (landing) => { finalLanding = landing; }, + onLanding: (read) => { finalRead = read; }, }; const first = await this.executeStep(session, sessionId, stepOptions); const result = repeatsOnSameLine && origin?.rawTop ? await this.repeatWhileOnOriginLine(session, sessionId, stepOptions, origin, first) : first; landed = true; + const read = finalRead; if ( result.success && result.data !== undefined && !result.data.pending && - session.state === SessionState.PAUSED + session.state === SessionState.PAUSED && + read?.pin !== undefined && + read.landing !== undefined ) { - const snapshot = await composeStopSnapshot( - this.ctx, sessionId, finalLanding?.stackResult, logTag - ); - if (snapshot) { - return { ...result, data: { ...result.data, snapshot } }; - } + return await this.withStepSnapshot(session, sessionId, logTag, result, { ...read, pin: read.pin, landing: read.landing }); } return result; } catch (error) { @@ -381,14 +415,16 @@ export class ExecutionController { const endedDuringReadMessage = `${options.successMessage.replace(/\.$/, '')}; the session ended before the stack could be read`; - // The stop recorded before this step was sent; a different object in - // onStopped is THIS step's stop, whose reason says whether the step ended - // it or something else did (issue #678) — the same discipline pause uses. - const lastStopBefore = session.lastStop; + // The stop recorded before this step was sent, by its record's id; a + // stop with another id in onStopped is THIS step's stop, whose reason says + // whether the step ended it or something else did (issue #678) — the same + // discipline pause uses. + const stopBeforeId = stopIdOf(session); const flavor: StepFlavor = options.flavor ?? (options.command === 'stepIn' ? 'stepInto' : options.command === 'stepOut' ? 'stepOut' : 'stepOver'); const inFlightRecord: InFlightStep = { + id: nextOperationId(), kind: options.toolName ?? (options.command === 'stepIn' ? 'step_into' : options.command === 'stepOut' ? 'step_out' : 'step_over'), flavor, command: options.command, @@ -436,7 +472,7 @@ export class ExecutionController { }; const settle = (result: DebugResult) => { - if (!result.data?.pending && session.inFlightStep === inFlightRecord) { + if (!result.data?.pending && session.inFlightStep?.id === inFlightRecord.id) { session.inFlightStep = undefined; } if (settled) { @@ -447,18 +483,23 @@ export class ExecutionController { resolve(result); }; + const resultFor = ( + message: string, + landing?: StopLanding, + extra?: Pick + ): DebugResult => ({ + success: true, + state: session.state, + data: { message, ...extra, ...(landing ? landingFields(landing) : {}) } + }); + const success = ( message: string, landing?: StopLanding, extra?: Pick ) => { this.ctx.logger.info(`[SM ${options.logTag} ${sessionId}] ${message} Current state: ${session.state}`); - const data: StepResultData = { message, ...extra, ...(landing ? landingFields(landing) : {}) }; - settle({ - success: true, - state: session.state, - data, - }); + settle(resultFor(message, landing, extra)); }; const endedFields = (): Pick => { @@ -481,32 +522,22 @@ export class ExecutionController { const sessionEnded = () => isTerminalSessionState(session.state); - const onStopped = async () => { - stopSeen = true; - clearTimeout(timeout); - // Where the step landed, through the resolver (issue #904): a failed - // read answers no location and never fails the step. - const landing = await describeStopLocation(this.ctx, sessionId, options.logTag); - options.onLanding?.(landing); + // The answer for one landing read under a pin (pinned-stop-read.ts): + // every field of it is the pinned stop's, never the session's stop read + // after the landing. Also what step() rebuilds the answer with when the + // stop changes under its snapshot. + const answerFor = (pin: StopPin, landing: StopLanding): StepAnswer => { const location = landing.location; - // Rule 2. An ended event that reached the listeners below has already - // settled with its own wording; this covers the endings that did not - // (handlers torn down by the core, an exit mapped straight to ERROR). - if (sessionEnded()) { - const extra = endedFields(); - success(withOutputTailClause(endedDuringReadMessage, extra.outputTail), undefined, extra); - return; - } // A stop recorded for THIS step whose reason is not the step: name it, // and for a breakpoint or exception say so in the wording too — with // the lost-step signature when it is on the line the step left from. - const ownStop = session.lastStop && session.lastStop !== lastStopBefore ? session.lastStop : undefined; + const ownStop = pin.stop && pin.stop.id !== stopBeforeId ? pin.stop : undefined; const stoppedOnRequestedThread = ownStop?.threadId === undefined || ownStop.threadId === options.threadId; const landedOnRequestedThread = landing.stackResult?.threadId === undefined || landing.stackResult.threadId === options.threadId; - if (ownStop && stoppedOnRequestedThread && session.lastStepProvenance?.stopRef !== ownStop) { + if (ownStop && stoppedOnRequestedThread && session.lastStepProvenance?.stopId !== ownStop.id) { session.lastStepProvenance = { - stopRef: ownStop, + stopId: ownStop.id, flavor, origin: options.stepOrigin }; @@ -514,7 +545,7 @@ export class ExecutionController { if (ownStop && ownStop.reason !== 'step') { const stop = { stopReason: ownStop.reason, - ...(ownStop.rawReason ? { rawStopReason: ownStop.rawReason } : {}) + ...(ownStop.info.rawReason ? { rawStopReason: ownStop.info.rawReason } : {}) }; const backAtOrigin = !options.suppressBackAtOrigin && @@ -524,17 +555,17 @@ export class ExecutionController { const message = USER_BREAK_REASONS.has(ownStop.reason) ? ErrorMessages.stepStoppedOn(options.successMessage, ownStop.reason, { backAtOrigin }) : options.successMessage; - success(message, landing, stop); - return; + return { result: resultFor(message, landing, stop) }; } // 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 every command it may send was spent there; issue #1130). - const stepNote = ownStop?.reason === 'step' ? ownStop.text : undefined; + const stepNote = ownStop?.reason === 'step' ? ownStop.info.text : undefined; let enrichedLanding = landing; + let deliver: (() => void) | undefined; if (ownStop?.reason === 'step') { const rawDescription = - this.ctx.redactionEnabled() ? redactStopInfo(ownStop).description : ownStop.description; + this.ctx.redactionEnabled() ? redactStopInfo(ownStop.info).description : ownStop.info.description; const adapterDescription = meaningfulStepStopDescription(rawDescription); const candidateHint = this.undeliveredStepFilterHint(session, options.stepFilterHint); const provenanceNote = compareStepOriginAndLanding( @@ -547,9 +578,7 @@ export class ExecutionController { noProgramFrame: landing.noProgramFrame === true } ); - if (!settled) { - this.recordDeliveredStepFilterHint(session, candidateHint, provenanceNote); - } + deliver = () => this.recordDeliveredStepFilterHint(session, candidateHint, provenanceNote); const mergedNotes = [adapterDescription, landing.note, provenanceNote].filter( (part): part is string => typeof part === 'string' && part.length > 0 ); @@ -557,7 +586,68 @@ export class ExecutionController { enrichedLanding = { ...landing, note: mergedNotes.join(' ') }; } } - success(stepNote ? `${options.successMessage}. ${stepNote}` : options.successMessage, enrichedLanding); + return { + result: resultFor(stepNote ? `${options.successMessage}. ${stepNote}` : options.successMessage, enrichedLanding), + ...(deliver ? { deliver } : {}) + }; + }; + + // Rule 2's answer when the stop was seen: the step landed, and the + // session ended before the stack that would say where could be read. + const endedAnswer = (): DebugResult => { + const extra = endedFields(); + return resultFor(withOutputTailClause(endedDuringReadMessage, extra.outputTail), undefined, extra); + }; + + // The stop changed while the landing was read, and again while it was + // read a second time: the stop the session is at now, no landing, and why. + const changedAnswer = (current: StopRecord | undefined): DebugResult => { + const ownReason = current && current.id !== stopBeforeId && current.reason !== 'step' ? current : undefined; + const message = ownReason && USER_BREAK_REASONS.has(ownReason.reason) + ? ErrorMessages.stepStoppedOn(options.successMessage, ownReason.reason) + : options.successMessage; + return resultFor(message, undefined, { + ...(ownReason + ? { stopReason: ownReason.reason, ...(ownReason.info.rawReason ? { rawStopReason: ownReason.info.rawReason } : {}) } + : {}), + note: ErrorMessages.stopChangedWhileRead() + }); + }; + + const onStopped = async () => { + // Rule 1's owner: the first stopped event. A stop that lands while it + // is being read is the pin's to find (and the reads are made again for + // it), never a second reader racing this one to the answer. + if (stopSeen) { + return; + } + stopSeen = true; + clearTimeout(timeout); + // Where the step landed, through the resolver (issue #904), under a + // pin of the stop taken here, before the read's first await: a failed + // read answers no location and never fails the step. + const read = await readPinnedStop(this.ctx, sessionId, options.logTag, { snapshot: false }); + const builders = { answerAgain: answerFor, changedAnswer, endedAnswer }; + options.onLanding?.(read.status === 'pinned' + ? { landing: read.landing, pin: read.pin, reread: read.reread, ...builders } + : { reread: true, ...builders }); + // Rule 2. An ended event that reached the listeners below has already + // settled with its own wording; this covers the endings that did not + // (handlers torn down by the core, an exit mapped straight to ERROR). + if (sessionEnded()) { + settle(endedAnswer()); + return; + } + if (read.status === 'changed') { + settle(changedAnswer(read.current)); + return; + } + const answer = answerFor(read.pin, read.landing); + if (!settled) { + answer.deliver?.(); + } + this.ctx.logger.info(`[SM ${options.logTag} ${sessionId}] ${answer.result.data?.message} Current state: ${session.state}`); + settle(answer.result); }; const onTerminated = () => settleEnded(options.terminatedMessage); @@ -632,7 +722,7 @@ export class ExecutionController { // recorded another stop/resume or replaced the proxy on relaunch; // a rejection of the old request must not roll back that newer run. if (settled && ( - session.inFlightStep !== inFlightRecord || session.proxyManager !== proxyManager + session.inFlightStep?.id !== inFlightRecord.id || session.proxyManager !== proxyManager )) { return; } @@ -827,14 +917,14 @@ export class ExecutionController { this.ctx.logger.debug(`[SessionManager] pauseExecution: sending DAP pause for session=${sessionId} currentState=${session.state}`); - // Snapshot the current lastStop so result paths can tell whether the stop - // they observe belongs to THIS pause (handleStopped replaces the object) - // rather than reporting a stale earlier stop. Taken BEFORE the - // threads-discovery await below: a stop delivered during that await has - // already replaced session.lastStop, so a snapshot taken afterwards would - // compare this pause's own stop against itself and report no reason at - // all — the very case the post-response race branch exists for (#574). - const lastStopBefore = session.lastStop; + // The id of the stop recorded before this pause, so result paths can tell + // whether the stop they describe belongs to THIS pause (each stop gets a + // record of its own) rather than reporting a stale earlier stop. Taken + // BEFORE the threads-discovery await below: a stop delivered during that + // await already has its record, so an id taken afterwards would compare + // this pause's own stop against itself and report no reason at all — the + // very case the post-response race branch exists for (#574). + const stopBeforeId = stopIdOf(session); // DAP pause request: threadId 0 should pause all threads per DAP spec, // but some adapters (e.g. netcoredbg) reject threadId=0 with E_INVALIDARG. // When no explicit threadId is provided, discover one via a threads request. @@ -890,14 +980,14 @@ export class ExecutionController { const sessionEnded = () => isTerminalSessionState(session.state); - /** The stop reason, but only when core recorded a NEW stop for this pause. */ - const ownStopReason = (): Pick => { - if (!session.lastStop || session.lastStop === lastStopBefore) { + /** The stop's reason, but only when it is a NEW stop, recorded for this pause. */ + const ownStopReason = (stop: StopRecord | undefined): Pick => { + if (!stop || stop.id === stopBeforeId) { return {}; } return { - stopReason: session.lastStop.reason, - ...(session.lastStop.rawReason ? { rawStopReason: session.lastStop.rawReason } : {}) + stopReason: stop.reason, + ...(stop.info.rawReason ? { rawStopReason: stop.info.rawReason } : {}) }; }; @@ -905,27 +995,26 @@ export class ExecutionController { // Where the pause landed, through the resolver (issue #904): a pause // reported on a thread with no program frame shows the sibling in the // program's code (issue #898), or says that no program frame is - // active (issue #900), in note. - const landing = await describeStopLocation(this.ctx, sessionId, 'pause'); - + // active (issue #900), in note. And the snapshot behind the landing + // (issue #982): same resolver result, bounded locals. Both under a pin + // of the stop taken before the read's first await (tracking issue + // #1362): a stop that changes under them is read again, once. + const read = await readPinnedStop(this.ctx, sessionId, 'pause', { skipSnapshotWhenEnded: true }); + + // The reads are real waits: a debuggee that ended under them gets the + // ended wording (#574's rule 2), with the stop recorded for this pause. if (sessionEnded()) { return { success: true, state: session.state, - data: { message: PAUSED_THEN_ENDED_MESSAGE, ...ownStopReason() } + data: { message: PAUSED_THEN_ENDED_MESSAGE, ...ownStopReason(stopRecordOf(session)) } }; } - // The snapshot behind the landing (issue #982): same resolver result, - // bounded locals; a session that moved on under the read answers none. - const snapshot = await composeStopSnapshot(this.ctx, sessionId, landing.stackResult, 'pause'); - // The compose is a real wait (locals read, bounded by its tunable): a - // debuggee that ended under it must get the ended wording, exactly as - // one that ended under the landing read does (#574's rule 2). - if (sessionEnded()) { + if (read.status === 'changed') { return { success: true, state: session.state, - data: { message: PAUSED_THEN_ENDED_MESSAGE, ...ownStopReason() } + data: { message: 'Paused', ...ownStopReason(read.current), note: ErrorMessages.stopChangedWhileRead() } }; } this.ctx.logger.info( @@ -936,9 +1025,9 @@ export class ExecutionController { state: session.state, data: { message: 'Paused', - ...ownStopReason(), - ...landingFields(landing), - ...(snapshot ? { snapshot } : {}) + ...ownStopReason(read.pin.stop), + ...landingFields(read.landing), + ...(read.snapshot ? { snapshot: read.snapshot } : {}) } }; } @@ -1051,14 +1140,14 @@ export class ExecutionController { } const waitMs = timeoutCheck.timeoutMs ?? this.ctx.tunables.waitForStopDefaultMs; - // The stop on record before this wait began, per session of the tree. A - // different record afterwards is a stop that landed during it — the - // discipline step and pause use to tell their own stop from an earlier - // one. A descendant adopted during the wait has no entry: whatever it - // recorded is this wait's. - const lastStopBefore = new Map([ - [session.id, session.lastStop], - ...this.ctx.descendantsOf(sessionId).map((d): [string, SessionStopInfo | undefined] => [d.id, d.lastStop]) + // The stop on record before this wait began, per session of the tree, by + // its record's id. A different id afterwards is a stop that landed during + // it — the discipline step and pause use to tell their own stop from an + // earlier one. A descendant adopted during the wait has no entry: whatever + // it recorded is this wait's. + const stopBefore = new Map([ + [session.id, stopIdOf(session)], + ...this.ctx.descendantsOf(sessionId).map((d): [string, StopId | undefined] => [d.id, stopIdOf(d)]) ]); const deadline = Date.now() + waitMs; @@ -1067,9 +1156,9 @@ export class ExecutionController { }); let settled = await wait(); let target = session; - let landing: StopLanding; - let stopAtLanding: SessionStopInfo | undefined; - let snapshot: Awaited>; + // The answer's reads, made under a pin of the target's stop when it is + // paused (pinned-stop-read.ts); undefined when it was not. + let read: PinnedStopRead | undefined; for (;;) { if (settled.outcome === 'gone') { return { @@ -1082,28 +1171,28 @@ export class ExecutionController { // the one asked for. target = settled.outcome === 'matched' ? settled.value : session; - // Where it stopped, best effort: the same short settle and stack read - // a step or a pause does. Re-read state after the DAP round trip. - landing = target.state === SessionState.PAUSED - ? await describeStopLocation(this.ctx, target.id, 'waitForStop') - : {}; - // Pin this answer's stop before the snapshot's locals read: a new stop - // under that read belongs to the next answer, never a mixed snapshot. - stopAtLanding = target.lastStop; - // lastStop already carries the exception, so do not repeat it in the - // snapshot. Its own identity gate rejects a changed stop's locals. - snapshot = await composeStopSnapshot( - this.ctx, target.id, landing.stackResult, 'waitForStop', { omitException: true } - ); - // Settle any in-flight child releases (bounded to min(1.5 s, remaining // deadline) and cancelled on abort) BEFORE the loop's final re-check so // a child that resumed or closed during the wait never returns a stale - // landing (issue #1221). - await this.ctx.settleInFlightChildReleases(sessionId, { + // landing (issue #1221). Made with the reads, so a stop that changes + // while the releases settle is caught by the same pin. + const settleReleases = () => this.ctx.settleInFlightChildReleases(sessionId, { timeoutMs: Math.max(0, deadline - Date.now()), signal }); + if (target.state === SessionState.PAUSED) { + // Where it stopped, best effort: the same short settle and stack read + // a step or a pause does, and the snapshot behind it, both under a + // pin of the stop taken here. lastStop already carries the + // exception, so the snapshot does not repeat it. + read = await readPinnedStop(this.ctx, target.id, 'waitForStop', { + snapshot: { omitException: true }, + alsoAwait: settleReleases + }); + } else { + read = undefined; + await settleReleases(); + } try { this.ctx.getSession(sessionId); @@ -1130,14 +1219,12 @@ export class ExecutionController { } break; } - const location = landing.location; const tree = () => describeTreeAnswer(session, this.ctx.descendantsOf(sessionId)); // Every answer that carries the run's `childrenReleased` says what it means // (issue #1137): read from the session asked about, as the count is. const explained = (message: string): string => withReleasedChildren(message, describeReleasedChildren(session)); // Emit a redacted copy of the stop record (issue #982); the stored record - // keeps its identity — the exceptionInfo merge and `lastStop !== before` - // guards depend on it. + // is never mutated. const emitStop = (stop: SessionStopInfo): SessionStopInfo => this.ctx.redactionEnabled() ? redactStopInfo(stop) : stop; @@ -1148,11 +1235,36 @@ export class ExecutionController { // from before the wait is not this wait's to report: the program was // resumed past it. const stopDuringWait = - target.lastStop && target.lastStop !== lastStopBefore.get(target.id) ? { lastStop: emitStop(target.lastStop) } : {}; + target.lastStop && stopIdOf(target) !== stopBefore.get(target.id) ? { lastStop: emitStop(target.lastStop) } : {}; + if (state === SessionState.PAUSED && read?.status === 'changed') { + // The stop changed while the answer was read, and again while it was + // read a second time: the stop it is at now, no landing, and why. + const current = read.current; + return { + success: true, + state, + data: { + sessionId: target.id, + message: explained(`Paused (${current?.reason ?? 'unknown'})`), + ...(current ? { lastStop: emitStop(current.info) } : {}), + note: ErrorMessages.stopChangedWhileRead(), + ...tree() + } + }; + } + // The stop this answer describes, and the reads made under its pin. A + // target that was not paused when it was read has no landing; if it is + // paused by now, its answer names the stop it is at and nothing more, as + // it always has (one synchronous read, nothing awaited after it). + const pinned = read?.status === 'pinned' ? read : undefined; + const stopAtLanding = pinned ? pinned.pin.stop : stopRecordOf(target); + const landing: StopLanding = pinned?.landing ?? {}; + const snapshot = pinned?.snapshot; + const location = landing.location; if (state === SessionState.PAUSED && stopAtLanding) { const where = location ? ` at ${location.file}:${location.line}` : ''; let waitLanding = landing; - if (stopAtLanding.reason === 'step' && target.lastStepProvenance?.stopRef === stopAtLanding) { + if (stopAtLanding.reason === 'step' && target.lastStepProvenance?.stopId === stopAtLanding.id) { const prov = target.lastStepProvenance; const landedOnOriginThread = landing.stackResult?.threadId === undefined || landing.stackResult.threadId === prov.origin?.threadId; @@ -1166,7 +1278,7 @@ export class ExecutionController { landing.stackResult?.frames ?? [], { stepFilterHint: candidateHint, - hasStepperWalkNote: stopAtLanding.text !== undefined, + hasStepperWalkNote: stopAtLanding.info.text !== undefined, noProgramFrame: landing.noProgramFrame === true } ); @@ -1184,7 +1296,7 @@ export class ExecutionController { data: { sessionId: target.id, message: explained(`Paused (${stopAtLanding.reason})${where}`), - lastStop: emitStop(stopAtLanding), + lastStop: emitStop(stopAtLanding.info), ...landingFields(waitLanding), ...(snapshot ? { snapshot } : {}), ...tree() @@ -1268,11 +1380,53 @@ export class ExecutionController { }; } + /** + * The step's snapshot (issue #982), composed once per answer from the final + * landing and under the pin that landing was read with (tracking issue + * #1362; issue #1348). If the stop changes under it, the answer is read + * again once for the stop now current — the landing, every field of the + * answer and the snapshot — unless the landing's own re-read is spent; + * then, or if the stop changes again, the answer names the stop the session + * is at with no landing. A session that ended under the re-read gets rule + * 2's answer. + */ + private async withStepSnapshot( + session: ManagedSession, + sessionId: string, + logTag: string, + result: DebugResult, + read: StepLandingRead & { pin: StopPin; landing: StopLanding } + ): Promise> { + let answer = result; + let snapshot = await composeStopSnapshot(this.ctx, sessionId, read.landing.stackResult, logTag, { pin: read.pin }); + if (pinBroken(session, read.pin)) { + if (read.reread) { + return read.changedAnswer(stopRecordOf(session)); + } + this.ctx.logger.info(`[SM ${logTag} ${sessionId}] The stop changed under the step's snapshot; reading the stop now current`); + const again = await readPinnedStop(this.ctx, sessionId, logTag, { rereads: 0 }); + if (isTerminalSessionState(session.state)) { + return read.endedAnswer(); + } + if (again.status === 'changed') { + return read.changedAnswer(again.current); + } + const rebuilt = read.answerAgain(again.pin, again.landing); + rebuilt.deliver?.(); + answer = rebuilt.result; + snapshot = again.snapshot; + } + return snapshot && answer.data ? { ...answer, data: { ...answer.data, snapshot } } : answer; + } + /** * Read the starting stack before sending a step (issues #678, #879, #1180): * one unfiltered `stackTrace` call, bounded to a fraction of `stepGraceMs` so * a wedged adapter never stalls the step for 30s. A failed, empty, or late - * read returns `undefined` and never blocks the step itself. + * read returns `undefined` and never blocks the step itself, and so does a + * read during which the session stopped somewhere else (tracking issue + * #1362): the origin is the stop it was pinned on, frames and reason, or + * none. */ private async readStepOrigin( session: ManagedSession, @@ -1280,6 +1434,7 @@ export class ExecutionController { threadId: number ): Promise { const boundMs = Math.max(1, Math.floor(this.ctx.tunables.stepGraceMs / 5)); + const pin = pinStop(session); let timer: ReturnType | undefined; const late = new Promise((resolve) => { timer = setTimeout(() => resolve(undefined), boundMs); @@ -1293,8 +1448,12 @@ export class ExecutionController { this.ctx.logger.debug(`[SM step ${sessionId}] Origin stack read exceeded ${boundMs}ms; stepping without it`); return undefined; } + if (pinBroken(session, pin)) { + this.ctx.logger.debug(`[SM step ${sessionId}] The stop changed while the origin stack was read; stepping without it`); + return undefined; + } const policy = this.ctx.selectPolicy(session.language); - return captureStepOrigin(detailed.frames, policy, threadId, session.lastStop?.reason); + return captureStepOrigin(detailed.frames, policy, threadId, pin.stop?.reason); } catch (error) { this.ctx.logger.debug(`[SM step ${sessionId}] Could not read the origin stack before stepping:`, error); return undefined; diff --git a/src/session/execution/pause-coordinator.ts b/src/session/execution/pause-coordinator.ts index ba85e4c48..23d684096 100644 --- a/src/session/execution/pause-coordinator.ts +++ b/src/session/execution/pause-coordinator.ts @@ -158,7 +158,7 @@ export class PauseCoordinator { }); } } - intent = armPauseIntent(session, source); + intent = armPauseIntent(session, source, threadId); const request = proxyManager .sendDapRequest('pause', { threadId }) diff --git a/src/session/execution/pause-intent.ts b/src/session/execution/pause-intent.ts index 504d7f791..99b63ca8d 100644 --- a/src/session/execution/pause-intent.ts +++ b/src/session/execution/pause-intent.ts @@ -1,8 +1,14 @@ +import { nextOperationId, type OperationId } from '../stop-record.js'; + /** A pause request scoped to the proxy generation that received it. */ export interface PauseIntent { + /** The pause's identity (tracking issue #1362): the `cause` its stop names. */ + id: OperationId; generation: number; source: 'user' | 'attach'; armedAt: number; + /** The thread the pause was sent for (0: every thread). */ + threadId?: number; } interface PauseIntentSession { @@ -21,12 +27,15 @@ export function beginProxyGeneration(session: PauseIntentSession): number { /** Arm a pause against the currently installed proxy only. */ export function armPauseIntent( session: PauseIntentSession, - source: PauseIntent['source'] + source: PauseIntent['source'], + threadId?: number ): PauseIntent { const intent: PauseIntent = { + id: nextOperationId(), generation: session.proxyGeneration ?? 0, source, - armedAt: Date.now() + armedAt: Date.now(), + ...(typeof threadId === 'number' ? { threadId } : {}) }; session.pauseIntent = intent; return intent; @@ -43,12 +52,12 @@ export function getCurrentPauseIntent(session: PauseIntentSession): PauseIntent return hasCurrentPauseIntent(session) ? session.pauseIntent : undefined; } -/** Clear one current intent, optionally only if it is the expected object. */ +/** Clear one current intent, optionally only if it is the expected one (by id). */ export function clearPauseIntent( session: PauseIntentSession, expected?: PauseIntent ): void { - if (!expected || session.pauseIntent === expected) { + if (!expected || session.pauseIntent?.id === expected.id) { session.pauseIntent = undefined; } } diff --git a/src/session/inspection/frame-anchor-resolver.ts b/src/session/inspection/frame-anchor-resolver.ts index 17b732232..478a22606 100644 --- a/src/session/inspection/frame-anchor-resolver.ts +++ b/src/session/inspection/frame-anchor-resolver.ts @@ -21,6 +21,7 @@ import type { DebugProtocol } from '@vscode/debugprotocol'; import path from 'path'; import type { IProxyManager } from '../../proxy/proxy-manager.js'; import type { ManagedSession } from '../session-store.js'; +import { stopIdOf, stopRecordOf, type StopRecord } from '../stop-record.js'; import { debuggerOffWhy } from '../debugger-off.js'; import { isDapRequestTimeout } from '../dap-request-helpers.js'; import { DapResponseError } from '../../proxy/dap-response-error.js'; @@ -190,7 +191,6 @@ function emptyResult(note?: string, threadId?: number): StackTraceResult { }; } -type StopRecord = NonNullable; interface SiblingStack { threadId: number; @@ -208,7 +208,7 @@ export class FrameAnchorResolver { * The verdict on an internal-only stop, once per stop: a stop that no * sibling can improve on (an idle js-debug pause) is scanned when first * resolved, not again by every locals or evaluate read that follows. Keyed - * by the stop record itself, which the core replaces on every stop. + * by the stop's record (src/session/stop-record.ts), one per stop. */ private readonly verdicts = new WeakMap(); @@ -247,8 +247,11 @@ export class FrameAnchorResolver { } // The stop this stack belongs to. A new stop landing while the stack is // in flight makes the frames stale; the paused-frame rule below and every - // adoption only apply when the stop they reason about is still current. + // adoption only apply when the stop they reason about is still current, + // by its record's id (stillAtGate). const stopAtGate = session.lastStop; + const gateRecord = stopRecordOf(session); + const stillAtGate = (): boolean => stopIdOf(session) === gateRecord?.id; const proxyManager = session.proxyManager; const policy = this.ctx.selectPolicy(session.language); @@ -264,6 +267,7 @@ export class FrameAnchorResolver { proxyManager, effectiveThreadId, stopAtGate, + stillAtGate, policy ); rawFrames = ready.frames; @@ -293,7 +297,8 @@ export class FrameAnchorResolver { proxyManager, effectiveThreadId, rawFrames, - stopAtGate, + gateRecord, + stillAtGate, policy ); if (adopted) { @@ -317,7 +322,7 @@ export class FrameAnchorResolver { } else if ( filtered.length > 0 && filtered[0].id !== rawTop.id && - session.lastStop === stopAtGate && + stillAtGate() && this.isStoppedThread(stopAtGate, currentThreadId, resultThreadId) ) { // The paused frame itself was filtered out while ancestors survived @@ -364,7 +369,7 @@ export class FrameAnchorResolver { opts?.ensureStackReady && typeof stopAtGate?.threadId === 'number' && resultThreadId !== stopAtGate.threadId && - session.lastStop === stopAtGate + stillAtGate() ) { note = `The stop was reported on thread ${stopAtGate.threadId}; inspection is anchored on thread ${resultThreadId}.`; } @@ -457,10 +462,11 @@ export class FrameAnchorResolver { private async waitForReadyStack( sessionId: string, - session: Pick, + session: Pick, proxyManager: IProxyManager, threadId: number, stopAtGate: ManagedSession['lastStop'], + stillAtGate: () => boolean, policy: AdapterPolicy ): Promise<{ frames: DebugProtocol.StackFrame[]; threadId: number; note?: string }> { const { pausedStackReadyTimeoutMs, pausedStackReadyIntervalMs } = this.ctx.tunables; @@ -490,7 +496,7 @@ export class FrameAnchorResolver { pausedStackReadyIntervalMs ); if (sibling) { - return this.adoptFramedSibling(sessionId, session, proxyManager, threadId, stopAtGate, sibling); + return this.adoptFramedSibling(sessionId, session, proxyManager, threadId, stillAtGate, sibling); } this.ctx.logger.info(`[FrameAnchor ${sessionId}] Thread ${threadId} is paused with no frames: ${empty.note}`); return { frames: [], threadId, note: empty.note }; @@ -552,7 +558,7 @@ export class FrameAnchorResolver { break; } if (scanned) { - return this.adoptFramedSibling(sessionId, session, proxyManager, threadId, stopAtGate, scanned); + return this.adoptFramedSibling(sessionId, session, proxyManager, threadId, stillAtGate, scanned); } } } finally { @@ -578,15 +584,15 @@ export class FrameAnchorResolver { /** Anchor the session on a sibling thread that has frames, unless the stop changed while it was being found. */ private adoptFramedSibling( sessionId: string, - session: Pick, + session: Pick, proxyManager: IProxyManager, threadId: number, - stopAtGate: ManagedSession['lastStop'], + stillAtGate: () => boolean, scanned: { threadId: number; frames: DebugProtocol.StackFrame[] } ): { frames: DebugProtocol.StackFrame[]; threadId: number; note: string } { // A stop that landed during the scan has re-anchored the session // itself; adopting now would clobber it with a stale verdict. - if (session.lastStop !== stopAtGate || session.state !== SessionState.PAUSED) { + if (!stillAtGate() || session.state !== SessionState.PAUSED) { this.ctx.logger.info( `[FrameAnchor ${sessionId}] The stop changed while scanning for a framed thread; not adopting thread ${scanned.threadId}.` ); @@ -617,14 +623,15 @@ export class FrameAnchorResolver { */ private async adoptProgramThread( sessionId: string, - session: Pick, + session: Pick, proxyManager: IProxyManager, stoppedThreadId: number, stoppedFrames: DebugProtocol.StackFrame[], - stopAtGate: ManagedSession['lastStop'], + gateRecord: StopRecord | undefined, + stillAtGate: () => boolean, policy: AdapterPolicy ): Promise<{ frames: DebugProtocol.StackFrame[]; threadId: number; note: string } | undefined> { - const remembered = stopAtGate ? this.verdicts.get(stopAtGate) : undefined; + const remembered = gateRecord ? this.verdicts.get(gateRecord) : undefined; const { verdict, threads } = remembered ?? await this.verdictFor( sessionId, proxyManager, @@ -633,11 +640,11 @@ export class FrameAnchorResolver { policy, this.ctx.tunables.pausedStackReadyTimeoutMs ); - if (!remembered && stopAtGate) { + if (!remembered && gateRecord) { // Kept whatever the outcome: a scan cut short by its budget or by // rejecting siblings is not retried by the locals and evaluate reads // that follow — one bounded scan per stop, by design. - this.verdicts.set(stopAtGate, { verdict, threads }); + this.verdicts.set(gateRecord, { verdict, threads }); } const programThreadId = verdict.programThreadId; if (programThreadId === undefined || programThreadId === stoppedThreadId) { @@ -647,7 +654,7 @@ export class FrameAnchorResolver { if (frames.length === 0) { return undefined; } - if (session.lastStop !== stopAtGate || session.state !== SessionState.PAUSED) { + if (!stillAtGate() || session.state !== SessionState.PAUSED) { this.ctx.logger.info( `[FrameAnchor ${sessionId}] The stop changed while scanning for the program thread; not adopting thread ${programThreadId}.` ); diff --git a/src/session/inspection/pinned-stop-read.ts b/src/session/inspection/pinned-stop-read.ts new file mode 100644 index 000000000..016a274ff --- /dev/null +++ b/src/session/inspection/pinned-stop-read.ts @@ -0,0 +1,150 @@ +/** + * Pins (tracking issue #1362, stage "stop record"; issue #1348): an answer + * that describes a stop takes that stop's identity before its first await and + * checks every read it makes against it, so no answer carries one stop's + * location and another's reason. + * + * The rule, in `readPinnedStop`: + * + * 1. The pin is the session's stop record, taken synchronously + * (`pinStop`, src/session/stop-record.ts). + * 2. The reads are made under it: the landing (`describeStopLocation`, which + * reads the stop it is handed, never the session's), the snapshot + * (`composeStopSnapshot`, whose exception, diff base and locals check are + * the pinned stop's), and whatever the caller adds (`alsoAwait`). + * 3. If the session is paused at another stop when they end (`pinBroken`), + * all of them are made again once, under a pin of that stop. + * 4. If it changed again, the read is `changed`: the stop the session is at + * now, and no landing. The caller gives that stop's reason and state and + * says that the stop changed while it was being read + * (`ErrorMessages.stopChangedWhileRead`). + * + * A session that is not paused when the reads end is the caller's to answer, + * as it always was (an ending reported as ended, a resumed program as + * running): the reads it gets back describe the pinned stop, and nothing else + * in its answer may be taken from the session's stop. "Changed" means another + * stop record, not a resume: a stop is never applied twice and an id is never + * reused, so equal ids are the same stop. + * + * The answer's own fields come from the pin (`read.pin.stop`), never from + * `session.lastStop` read after the reads. The tool handlers then read the + * source line and the stale-build note from the answer's `location` alone; + * they read nothing of the session's stop. + */ +import { SessionState } from '@debugmcp/shared'; +import type { ManagedSession } from '../session-store.js'; +import { pinBroken, pinStop, stopRecordOf, type StopPin, type StopRecord } from '../stop-record.js'; +import type { StopSnapshot } from '../session-manager-core.js'; +import { describeStopLocation, type StopLanding, type StopLandingContext } from './stop-location.js'; +import { composeStopSnapshot, type ComposeSnapshotOptions, type StopSnapshotContext } from './stop-snapshot.js'; +import { ErrorMessages } from '../../utils/error-messages.js'; + +export type PinnedStopReadContext = StopLandingContext & StopSnapshotContext; + +export interface PinnedStopReadOptions { + /** The pin, when the caller took it earlier (before an await of its own). */ + readonly pin?: StopPin; + /** Compose the snapshot behind the landing (the default); `false` reads the landing alone. */ + readonly snapshot?: Omit | false; + /** + * Skip the snapshot when the session has ended under the landing read (the + * pause answer's rule 2: there is no stack left to compose from). + */ + readonly skipSnapshotWhenEnded?: boolean; + /** Another wait of the answer's, made after the reads and again with them (wait_for_stop's child releases). */ + readonly alsoAwait?: () => Promise; + /** How many times the reads may be made again: 1 (the default), or 0 for a caller that has spent it. */ + readonly rereads?: 0 | 1; +} + +export type PinnedStopRead = + | { + readonly status: 'pinned'; + /** The pin every read was made and checked under. */ + readonly pin: StopPin; + readonly landing: StopLanding; + readonly snapshot: StopSnapshot | undefined; + /** The reads were made a second time, because the stop changed during the first. */ + readonly reread: boolean; + } + | { + readonly status: 'changed'; + /** The stop the session is at now, which no read describes. */ + readonly current: StopRecord | undefined; + }; + +function sessionOrUndefined(ctx: Pick, sessionId: string): ManagedSession | undefined { + try { + return ctx.getSession(sessionId); + } catch { + return undefined; + } +} + +/** Pin the session's stop now, or pin nothing for a session that is gone. */ +export function pinSession(ctx: Pick, sessionId: string): StopPin { + const session = sessionOrUndefined(ctx, sessionId); + return session ? pinStop(session) : { sessionId, stop: undefined }; +} + +/** Read a stop's landing and snapshot under a pin, by the rule in this module's header. */ +export async function readPinnedStop( + ctx: PinnedStopReadContext, + sessionId: string, + logTag: string, + opts: PinnedStopReadOptions = {} +): Promise { + // Taken before the first await, unless the caller took it earlier still. + let pin = opts.pin ?? pinSession(ctx, sessionId); + const readUnder = async (under: StopPin): Promise<{ landing: StopLanding; snapshot: StopSnapshot | undefined }> => { + const landing = await describeStopLocation(ctx, sessionId, logTag, under); + let snapshot: StopSnapshot | undefined; + const endedUnderLanding = opts.skipSnapshotWhenEnded === true && + isTerminal(sessionOrUndefined(ctx, sessionId)?.state); + if (opts.snapshot !== false && !endedUnderLanding) { + snapshot = await composeStopSnapshot(ctx, sessionId, landing.stackResult, logTag, { ...(opts.snapshot ?? {}), pin: under }); + } + await opts.alsoAwait?.(); + return { landing, snapshot }; + }; + let read = await readUnder(pin); + let reread = false; + if ((opts.rereads ?? 1) > 0 && pinBroken(sessionOrUndefined(ctx, sessionId), pin)) { + ctx.logger.info(`[SessionManager ${logTag} ${sessionId}] The stop changed while its answer was read; reading the stop now current`); + pin = pinSession(ctx, sessionId); + read = await readUnder(pin); + reread = true; + } + const session = sessionOrUndefined(ctx, sessionId); + if (pinBroken(session, pin)) { + ctx.logger.info(`[SessionManager ${logTag} ${sessionId}] The stop changed again while its answer was read; answering without a landing`); + return { status: 'changed', current: stopRecordOf(session) }; + } + return { status: 'pinned', pin, landing: read.landing, snapshot: read.snapshot, reread }; +} + +function isTerminal(state: SessionState | undefined): boolean { + return state === SessionState.STOPPED || state === SessionState.ERROR; +} + +/** What an answer takes from a pinned read (or from none, for a session that was not paused). */ +export interface DescribedStop { + /** The stop the answer names: the pin's, or, when the stop changed twice, the one current now. */ + readonly stop: StopRecord | undefined; + /** The landing read under the pin; empty when there was no read or the stop changed twice. */ + readonly landing: StopLanding; + readonly snapshot: StopSnapshot | undefined; + /** The sentence for a stop that changed twice while it was read; absent otherwise. */ + readonly note?: string; +} + +/** The fields a launch-shaped answer (launch, restart, attach, hot reload) takes from a pinned read. */ +export function describedStop(read: PinnedStopRead | undefined): DescribedStop { + if (!read) { + return { stop: undefined, landing: {}, snapshot: undefined }; + } + if (read.status === 'changed') { + return { stop: read.current, landing: {}, snapshot: undefined, note: ErrorMessages.stopChangedWhileRead() }; + } + return { stop: read.pin.stop, landing: read.landing, snapshot: read.snapshot }; +} diff --git a/src/session/inspection/stop-location.ts b/src/session/inspection/stop-location.ts index df4774b75..54d3b93e7 100644 --- a/src/session/inspection/stop-location.ts +++ b/src/session/inspection/stop-location.ts @@ -14,6 +14,7 @@ import type { StackTraceResult } from './frame-anchor-resolver.js'; import { hasPausingBreakpoint } from '../launch/launch-arming.js'; import { ErrorMessages } from '../../utils/error-messages.js'; import { isProgramNeutralStopReason } from './stop-anchor.js'; +import type { StopPin } from '../stop-record.js'; /** * The landing as read: the answer's fields (`StopLandingFields`) plus the @@ -40,16 +41,22 @@ export type StopLandingContext = Pick { try { // A brief settle after the stopped event, as every reader here always had. await new Promise((resolve) => setTimeout(resolve, 10)); - const stop = ctx.getSession(sessionId).lastStop; + const stop = pin ? pin.stop?.info : ctx.getSession(sessionId).lastStop; const result = isProgramNeutralStopReason(stop?.reason) ? await ctx.getStackTraceDetailed(sessionId, undefined, false, { ensureStackReady: true }) : await ctx.getStackTraceDetailed(sessionId); diff --git a/src/session/inspection/stop-snapshot.ts b/src/session/inspection/stop-snapshot.ts index 12a571692..be974f63c 100644 --- a/src/session/inspection/stop-snapshot.ts +++ b/src/session/inspection/stop-snapshot.ts @@ -20,6 +20,7 @@ import type { OperationsContext } from '../operations-context.js'; import type { ChangedVariable, SnapshotException, StopSnapshot } from '../session-manager-core.js'; import type { StackTraceResult } from './frame-anchor-resolver.js'; import { frameSummary } from './frame-anchor-resolver.js'; +import { pinHolds, pinStop, type StopPin } from '../stop-record.js'; import { applyVariableCaps, snapshotLocalsLimits } from '../variable-caps.js'; import { buildSnapshotFrameKey, @@ -47,6 +48,12 @@ export interface ComposeSnapshotOptions { * (redacted) `lastStop`, and the same message must never ship twice. */ omitException?: boolean; + /** + * The stop the answer describes (pinned-stop-read.ts): the exception, the diff + * base and the check after the locals read are this stop's. Without one, + * the session's stop when the compose begins is pinned. + */ + pin?: StopPin; } /** How many frames the snapshot shows, and how deep its locals read probes. */ @@ -165,7 +172,9 @@ export async function composeStopSnapshot( if (session.state !== SessionState.PAUSED) { return undefined; } - const stop = session.lastStop; + const pin = opts.pin ?? pinStop(session); + const stop = pin.stop?.info; + const stopId = pin.stop?.id; if (stop?.reason === 'entry') { // Locals at an entry stop are module scaffolding, not state worth paying for. return undefined; @@ -261,9 +270,10 @@ export async function composeStopSnapshot( ); } else if (raced === FAILED) { notes.push('locals omitted: the locals read failed; get_local_variables reads them'); - } else if (ctx.getSession(sessionId).lastStop !== stop) { - // The stop changed under the read: these locals belong to another - // stop's world. No snapshot beats a mixed one. + } else if (!pinHolds(ctx.getSession(sessionId), pin)) { + // The stop changed under the read (or has no record to tell): these + // locals may belong to another stop's world. No snapshot beats a + // mixed one. return undefined; } else { const cappedLocals = applyVariableCaps(raced.variables, snapshotLocalsLimits()); @@ -312,7 +322,7 @@ export async function composeStopSnapshot( const frameKey = buildSnapshotFrameKey(anchor, stackResult.frames, stackResult.threadId ?? stop?.threadId); const callerResolved = !hasUnresolvedCallerUnwind(stackResult.frames); const provenance = - session.lastStepProvenance && session.lastStepProvenance.stopRef === stop + session.lastStepProvenance && stopId !== undefined && session.lastStepProvenance.stopId === stopId ? session.lastStepProvenance : undefined; const stepOutSameFn = stepOutReenteredOriginFrame( @@ -324,15 +334,15 @@ export async function composeStopSnapshot( // An unresolved caller cannot establish call identity on either // side of the comparison, even on consecutive broken unwinds. const brokenCallerUnwind = !callerResolved || base?.callerResolved === false; - if (stop && base && base.stopRef === stop) { + if (stopId !== undefined && base && base.stopId === stopId) { snapshot.locals = flat; - } else if (stop && base && base.frameKey === frameKey && !stepOutSameFn && !brokenCallerUnwind) { + } else if (stopId !== undefined && base && base.frameKey === frameKey && !stepOutSameFn && !brokenCallerUnwind) { snapshot.changedVariables = diffLocals(base, flat, complete); - session.snapshotDiffBase = { stopRef: stop, frameKey, rendered: flat, complete, callerResolved }; + session.snapshotDiffBase = { stopId, frameKey, rendered: flat, complete, callerResolved }; } else { snapshot.locals = flat; - if (stop) { - session.snapshotDiffBase = { stopRef: stop, frameKey, rendered: flat, complete, callerResolved }; + if (stopId !== undefined) { + session.snapshotDiffBase = { stopId, frameKey, rendered: flat, complete, callerResolved }; } } } diff --git a/src/session/launch/debug-launcher.ts b/src/session/launch/debug-launcher.ts index b8baed2a9..cedb40136 100644 --- a/src/session/launch/debug-launcher.ts +++ b/src/session/launch/debug-launcher.ts @@ -34,9 +34,9 @@ import { setCuratedMessage } from '../breakpoints/hit-verification.js'; import type { CustomLaunchRequestArguments, DebugResult, LaunchResultData, PausedChildSummary } from '../session-manager-core.js'; import type { ManagedSession, ToolchainValidationState } from '../session-store.js'; import type { LaunchContext } from '../operations-context.js'; -import { describeStopLocation, landingFields, type StopLanding } from '../inspection/stop-location.js'; +import { landingFields } from '../inspection/stop-location.js'; +import { describedStop, readPinnedStop } from '../inspection/pinned-stop-read.js'; import { describeReleasedChildren, describeTreeAnswer, selectSettledInTree, withReleasedChildren } from '../execution/tree-settle.js'; -import { composeStopSnapshot } from '../inspection/stop-snapshot.js'; import type { BreakpointController, ResyncOutcome } from '../breakpoints/breakpoint-controller.js'; import { reresolveAnchors, type AnchorResolution } from '../breakpoints/anchor-resolution.js'; import { @@ -58,6 +58,7 @@ import { describeLaunchTarget, describeSpawnCommand } from './spawn-command.js'; import { classifyTestRunner, TEST_RUNNER_KEY } from './test-runner-gate.js'; import type { InFlightGuard } from '../in-flight-guard.js'; import { adapterVerifiedABreakpoint, debuggerOffWhy } from '../debugger-off.js'; +import { resetStops } from '../stop-record.js'; /** * A launch flag the way the adapter will see it. The proxy launcher merges @@ -507,7 +508,7 @@ export class DebugLauncher { session.lastProxyExit = undefined; session.lastProxyError = undefined; session.failureDiagnostics = undefined; - session.lastStop = undefined; + resetStops(session); session.snapshotDiffBase = undefined; session.run.launchConfigNotices = []; session.adapterNotices = []; @@ -744,13 +745,20 @@ export class DebugLauncher { // re-read (issue #849) sees the RUNNING the continue sets in the same // call stack. Best effort, like every landing read: a stack that cannot // be read leaves the answer as it was. - const landing: StopLanding = finalState === SessionState.PAUSED - ? await describeStopLocation(this.ctx, sessionId, 'launch') - : {}; // The bounded state snapshot the landing read pays for (issue #982): // frames and locals from the same resolver result. An entry stop and a - // launch that is not paused answer no snapshot (composer gates). - const snapshot = await composeStopSnapshot(this.ctx, sessionId, landing.stackResult, 'launch'); + // launch that is not paused answer no snapshot (composer gates). Both + // under a pin of the stop taken by the read itself, before its first + // await (tracking issue #1362), and the answer's reason is the pin's. + // The pin comes after the breakpoint re-send above, which reads nothing + // of the stop: one taken before it would spend the one re-read on a + // stop that changed before any of the answer's reads began (measured + // on the JDI bridge, which reports one stop per breakpoint request at + // a location, a millisecond apart). + const described = describedStop(finalState === SessionState.PAUSED + ? await readPinnedStop(this.ctx, sessionId, 'launch') + : undefined); + const { landing, snapshot } = described; // The policy's word is a static pin; a stop that arrived anyway is the // stronger evidence (an adapter build that ignores the flag after all): @@ -838,24 +846,23 @@ export class DebugLauncher { const descendants = this.ctx.descendantsOf(sessionId); const settledInTree = selectSettledInTree(finalSession, descendants); if (settledInTree && settledInTree !== finalSession && settledInTree.state === SessionState.PAUSED) { - const childLanding = await describeStopLocation(this.ctx, settledInTree.id, 'launch'); - const childSnapshot = await composeStopSnapshot( - this.ctx, - settledInTree.id, - childLanding.stackResult, - 'launch' - ); + // The child's stop, read through its root's answer: pinned on the + // child's own record before the child's landing read. + const child = describedStop(await readPinnedStop(this.ctx, settledInTree.id, 'launch')); + const childLanding = child.landing; + const childSnapshot = child.snapshot; if ( settledInTree.state === SessionState.PAUSED && this.ctx.descendantsOf(sessionId).includes(settledInTree) ) { - const childReason = settledInTree.lastStop?.reason ?? 'unknown'; + const childReason = child.stop?.reason ?? 'unknown'; pausedChild = { sessionId: settledInTree.id, name: settledInTree.name, state: SessionState.PAUSED, reason: childReason, ...landingFields(childLanding), + ...(child.note ? { note: child.note } : {}), ...(childSnapshot ? { snapshot: childSnapshot } : {}) }; stillRunning = ErrorMessages.launchRunningWithPausedChild( @@ -909,11 +916,12 @@ export class DebugLauncher { // otherwise — never a fabricated 'breakpoint' (issue #255). reason: finalState === SessionState.PAUSED - ? finalSession.lastStop?.reason ?? + ? described.stop?.reason ?? (effectiveLaunchArgs?.stopOnEntry ? 'entry' : 'unknown') : undefined, stopOnEntrySuccessful: !!effectiveLaunchArgs?.stopOnEntry && finalState === SessionState.PAUSED, ...landingFields(landing), + ...(described.note ? { note: described.note } : {}), ...(snapshot ? { snapshot } : {}), // The session tree (issue #1081): the children adopted during the // hold, the run's released count, any already-paused child snapshot @@ -1180,10 +1188,12 @@ export class DebugLauncher { }); const finalSession = this.ctx.getSession(sessionId); const finalState = finalSession.state; - const landing: StopLanding = finalState === SessionState.PAUSED - ? await describeStopLocation(this.ctx, sessionId, 'launch') - : {}; - const snapshot = await composeStopSnapshot(this.ctx, sessionId, landing.stackResult, 'launch'); + // The landing and snapshot of a paused restart, under a pin of its stop + // taken before the read's first await (tracking issue #1362). + const described = describedStop(finalState === SessionState.PAUSED + ? await readPinnedStop(this.ctx, sessionId, 'launch') + : undefined); + const { landing, snapshot } = described; const runToCompletion = finalState === SessionState.STOPPED ? buildRunToCompletionSummary(finalSession) : undefined; @@ -1218,8 +1228,9 @@ export class DebugLauncher { ...(warning ? { warning } : {}), ...(stillRunning ? { pending: true } : {}), ...(runToCompletion?.data ?? {}), - reason: finalState === SessionState.PAUSED ? finalSession.lastStop?.reason ?? 'unknown' : undefined, + reason: finalState === SessionState.PAUSED ? described.stop?.reason ?? 'unknown' : undefined, ...landingFields(landing), + ...(described.note ? { note: described.note } : {}), ...(snapshot ? { snapshot } : {}), // A hot restart keeps the process and its children (issue #1081). ...describeTreeAnswer(finalSession, this.ctx.descendantsOf(sessionId)), diff --git a/src/session/live-update/live-update-controller.ts b/src/session/live-update/live-update-controller.ts index d495c1706..2c683ed3e 100644 --- a/src/session/live-update/live-update-controller.ts +++ b/src/session/live-update/live-update-controller.ts @@ -23,8 +23,8 @@ import type { BreakpointController } from '../breakpoints/breakpoint-controller. import type { ManagedSession } from '../session-store.js'; import type { LaunchContext } from '../operations-context.js'; import { waitForSessionState } from '../execution/session-state-wait.js'; -import { describeStopLocation, landingFields, type StopLanding } from '../inspection/stop-location.js'; -import { composeStopSnapshot } from '../inspection/stop-snapshot.js'; +import { landingFields } from '../inspection/stop-location.js'; +import { describedStop, readPinnedStop } from '../inspection/pinned-stop-read.js'; /** What a live update touches: the adapter's answer, the anchors, the session's stop. */ export type LiveUpdateContext = LaunchContext; @@ -200,13 +200,15 @@ export class LiveUpdateController { private async describeState(session: ManagedSession, raced: boolean): Promise> { const state = session.state; if (state === SessionState.PAUSED) { - const landing: StopLanding = await describeStopLocation(this.ctx, session.id, 'launch'); - const snapshot = await composeStopSnapshot(this.ctx, session.id, landing.stackResult, 'launch'); + // Under a pin of the stop taken before the read's first await (tracking + // issue #1362): the reason is the stop the landing was read for. + const described = describedStop(await readPinnedStop(this.ctx, session.id, 'launch')); return { state, - reason: session.lastStop?.reason ?? 'unknown', - ...landingFields(landing), - ...(snapshot ? { snapshot } : {}), + reason: described.stop?.reason ?? 'unknown', + ...landingFields(described.landing), + ...(described.note ? { note: described.note } : {}), + ...(described.snapshot ? { snapshot: described.snapshot } : {}), }; } if (state === SessionState.RUNNING && raced) { diff --git a/src/session/machine/shadow.ts b/src/session/machine/shadow.ts index 4756af7d6..49a612d01 100644 --- a/src/session/machine/shadow.ts +++ b/src/session/machine/shadow.ts @@ -235,6 +235,12 @@ export interface StateShadowOptions { rootOf?: (session: ShadowSession) => ShadowSession; /** How many descendants (live or retained rows) a session has. */ descendantsOf?: (session: ShadowSession) => number; + /** + * The identity of the stop a session records. The session manager passes + * its stop record's id (src/session/stop-record.ts); without it, the + * `lastStop` object itself is the identity. + */ + stopOf?: (session: ShadowSession) => StopIdentity | undefined; /** How many mismatches the ring keeps (default 64). */ ringSize?: number; } @@ -355,7 +361,7 @@ export class StateShadow implements StateShadowPort { token(session: ShadowSession): ResumeToken | undefined { try { - return { runId: this.runIdOf(session), continued: this.stateOf(session).continued, fromStop: session.lastStop }; + return { runId: this.runIdOf(session), continued: this.stateOf(session).continued, fromStop: this.stopOf(session) }; } catch { return undefined; } @@ -416,7 +422,7 @@ export class StateShadow implements StateShadowPort { state.seq += 1; return { seq: state.seq, - stop: session.lastStop, + stop: this.stopOf(session), lastShownStop: state.lastShownStop, continued: state.continued, runId: this.runIdOf(session), @@ -583,6 +589,10 @@ export class StateShadow implements StateShadowPort { state.lastShownStop = undefined; } + private stopOf(session: ShadowSession): StopIdentity | undefined { + return this.options.stopOf ? this.options.stopOf(session) : session.lastStop; + } + private stateOf(session: ShadowSession): SessionShadowState { let state = this.perSession.get(session); if (!state) { diff --git a/src/session/machine/transition-table.ts b/src/session/machine/transition-table.ts index 77eb9e1d9..0e39ecc5c 100644 --- a/src/session/machine/transition-table.ts +++ b/src/session/machine/transition-table.ts @@ -181,10 +181,12 @@ export const TRANSITIONS: readonly TransitionRow[] = [ ]; /** - * The stop identities the shadow compares, by reference. Opaque on purpose: - * only identity is ever read. + * The stop identities the shadow compares. Opaque on purpose: only equality + * is ever read. The session manager's shadow is handed its stop records' ids + * (src/session/stop-record.ts); a shadow given none compares the `lastStop` + * objects themselves. */ -export type StopIdentity = object; +export type StopIdentity = object | number; /** What a resume request started from, taken just before its command goes out. */ export interface ResumeToken { diff --git a/src/session/session-manager-core.ts b/src/session/session-manager-core.ts index 2510b8301..3827b0863 100644 --- a/src/session/session-manager-core.ts +++ b/src/session/session-manager-core.ts @@ -26,8 +26,17 @@ import { OutputRingBuffer } from './output-buffer.js'; import { beginProxyGeneration, clearPauseIntent, - getCurrentPauseIntent + getCurrentPauseIntent, + type PauseIntent } from './execution/pause-intent.js'; +import { + applyStop, + currentStopOf, + eraseHiddenStop, + resetStops, + stopIdOf, + type OperationRef +} from './stop-record.js'; import { describeTreeAnswer } from './execution/tree-settle.js'; import { DebugProtocol } from '@vscode/debugprotocol'; import path from 'path'; @@ -258,6 +267,36 @@ export type PauseResultData = DebugResultData & StopAnswerFields & { /** How much of the output's tail a policy reads the program's end from (issue #877). */ const PROGRAM_END_OUTPUT_TAIL_CHARS = 8000; +/** + * The operation in flight when a stop is applied, for its record (tracking + * issue #1362, stage "stop record"): a pause armed on this run's proxy, else + * the step sent on the stop's thread (or any step, when the stop names no + * thread). What was in flight, not what caused the stop (with both in flight, + * the pause is named). Recorded only: no reason, visibility or state is + * decided on it in this stage. `pauseIntent` is the intent the stop was read + * under, taken before `settleStop` clears it. + */ +function causeOf( + session: Pick, + threadId: number | undefined, + pauseIntent: PauseIntent | undefined +): { cause?: OperationRef } { + if (pauseIntent) { + return { + cause: { + id: pauseIntent.id, + kind: pauseIntent.source === 'attach' ? 'attach-pause' : 'pause', + ...(typeof pauseIntent.threadId === 'number' && pauseIntent.threadId !== 0 ? { threadId: pauseIntent.threadId } : {}) + } + }; + } + const step = session.inFlightStep; + if (step && (threadId === undefined || threadId === step.threadId)) { + return { cause: { id: step.id, kind: 'step', threadId: step.threadId } }; + } + return {}; +} + /** * Ceiling on the entire held-stop source lookup (issue #1097), including * the stack request and file read. If either stalls, keep the adapter's @@ -564,7 +603,9 @@ export abstract class SessionManagerCore extends EventEmitter { this.stateShadow = new StateShadow({ logger: () => this.logger, rootOf: (session) => this.rootOf(session as ManagedSession), - descendantsOf: (session) => this.descendantsDeepestFirst(session.id).length + descendantsOf: (session) => this.descendantsDeepestFirst(session.id).length, + // A stop's identity is its record's id (tracking issue #1362). + stopOf: (session) => stopIdOf(session as ManagedSession) }); this.fileSystem.ensureDirSync(this.logDirBase); @@ -2036,7 +2077,7 @@ export abstract class SessionManagerCore extends EventEmitter { // Reset first-stop tracking for this launch — a session may be re-launched. session.firstStopHandled = false; - session.lastStop = undefined; + resetStops(session); // A new run's first stop shows full locals, never a diff against the old // run (issue #983). The transient entry-stop erase below is NOT a launch // boundary: the cache deliberately survives ordinary resumes. @@ -2301,17 +2342,16 @@ export abstract class SessionManagerCore extends EventEmitter { this.logger.info(`[ProxyManager ${sessionId}] Auto-continuing (stopOnEntry=false) [reason=${reason}, firstStop=${isFirstStop}]`); // continue() requires PAUSED. Record the transient stop first so the // state invariant remains true even while auto-continue is in flight. - const autoContinuedStop = { + const autoContinuedStop = applyStop(session, { reason, ...(reason !== rawReason ? { rawReason } : {}), threadId, timestamp: Date.now(), ...(body?.description ? { description: body.description } : {}), ...(body?.text ? { text: body.text } : {}) - }; - session.lastStop = autoContinuedStop; + }, { shown: false, ...causeOf(session, threadId, pauseIntent) }); this._updateSessionState(session, SessionState.PAUSED, { site: 'settleStop.hidden', event: 'stop-hidden' }); - // Erase the transient stop however the continue settles. The identity + // Erase the transient stop however the continue settles. The record // check is what keeps it safe: a newer user-visible stop that raced // the continue replaced the record and must survive, and a continue // that failed with the session still PAUSED is genuinely at this stop. @@ -2322,8 +2362,8 @@ export abstract class SessionManagerCore extends EventEmitter { const clearTransientEntryStop = () => { const movedOn = session.state === SessionState.RUNNING || isTerminalSessionState(session.state); - if (movedOn && session.lastStop === autoContinuedStop) { - session.lastStop = undefined; + if (movedOn) { + eraseHiddenStop(session, autoContinuedStop); } }; this.handleAutoContinue(sessionId) @@ -2360,20 +2400,20 @@ export abstract class SessionManagerCore extends EventEmitter { // (list_debug_sessions / get_stack_trace, issue #214). Auto-continued // entry stops are deliberately not recorded — the user never saw them. // description/text carry e.g. the exception class/message (issue #220). - session.lastStop = { + const shownStop = applyStop(session, { reason, ...(reason !== rawReason ? { rawReason } : {}), threadId, timestamp: Date.now(), ...(body?.description ? { description: exceptionName(body.description) } : {}), ...(body?.text ? { text: exceptionName(body.text) } : {}) - }; + }, { shown: true, ...causeOf(session, threadId, pauseIntent) }); if (session.inFlightStep) { // Another thread may interrupt the step. Its stack cannot prove // anything about motion on the thread that received the command. if (threadId === undefined || threadId === session.inFlightStep.threadId) { session.lastStepProvenance = { - stopRef: session.lastStop, + stopId: shownStop.id, flavor: session.inFlightStep.flavor, origin: session.inFlightStep.origin }; @@ -2399,7 +2439,6 @@ export abstract class SessionManagerCore extends EventEmitter { typeof threadId === 'number' && session.adapterCapabilities?.supportsExceptionInfoRequest ) { - const stopRef = session.lastStop; proxyManager .sendDapRequest( 'exceptionInfo', @@ -2408,15 +2447,16 @@ export abstract class SessionManagerCore extends EventEmitter { ) .then((resp) => { const info = resp?.body; - // Stale-guard: only merge while this stop is still current. - if (!info || session.lastStop !== stopRef || session.state !== SessionState.PAUSED) { + // Stale-guard: only merge while this stop is still the one the + // session is at, by its record's id. + if (!info || currentStopOf(session)?.id !== shownStop.id) { return; } const details = info.details; // The same lens as the stop record above (issue #1047): the // type-name fields lose the adapter's decoration; message, // description and stackTrace are kept as reported. - stopRef.exceptionInfo = { + shownStop.info.exceptionInfo = { exceptionId: exceptionName(info.exceptionId), breakMode: info.breakMode, ...(info.description ? { description: info.description } : {}), diff --git a/src/session/session-store.ts b/src/session/session-store.ts index 48676c661..9dda25ac1 100644 --- a/src/session/session-store.ts +++ b/src/session/session-store.ts @@ -18,7 +18,7 @@ import { getPolicyForLanguage, isSettledSessionState } from '@debugmcp/shared'; -import type { AttachFootprint, AttachLocality, ExceptionBreakMode, ProgramEndExplanation, SessionStopInfo } from '@debugmcp/shared'; +import type { AttachFootprint, AttachLocality, ExceptionBreakMode, ProgramEndExplanation } from '@debugmcp/shared'; import { SessionNotFoundError } from '../errors/debug-errors.js'; import type { NoUncaughtStop } from '../utils/error-messages.js'; @@ -44,6 +44,7 @@ import { IProxyManager } from '../proxy/proxy-manager.js'; import { OutputRingBuffer } from './output-buffer.js'; import { isDebuggerOff } from './debugger-off.js'; import type { PauseIntent } from './execution/pause-intent.js'; +import type { OperationId, StopId, StopRecord } from './stop-record.js'; import type { StepFlavor, StepOrigin } from './execution/step-provenance.js'; import type { ProxyFailureDiagnostics } from './launch/proxy-failure-diagnostics.js'; import { isSessionHidden } from './session-scope.js'; @@ -123,6 +124,8 @@ export type ChildReleaseCause = 'adoption-off' | 'cap' | 'unsupported' | 'adopti * origin stack it started from (issues #1180, #1183). */ export interface InFlightStep { + /** The step's identity (tracking issue #1362): the `cause` a stop it ends names. */ + id: OperationId; kind: 'step_over' | 'step_into' | 'step_out'; flavor: StepFlavor; command: 'next' | 'stepIn' | 'stepOut'; @@ -132,12 +135,12 @@ export interface InFlightStep { } /** - * Provenance paired with the `SessionStopInfo` produced when an `InFlightStep` - * stops (issues #1180, #1183): compared by `stopRef` identity so stale steps - * never leak onto later stops. + * Provenance paired with the stop produced when an `InFlightStep` stops + * (issues #1180, #1183): keyed by the stop record's id so stale steps never + * leak onto later stops. */ export interface StepStopProvenance { - stopRef: SessionStopInfo; + stopId: StopId; flavor: StepFlavor; origin?: StepOrigin; } @@ -336,16 +339,24 @@ export interface ManagedSession extends DebugSessionInfo { // even when the adapter reports a non-'entry' reason (e.g., js-debug // emits 'pause' from its post-attach forced pause). firstStopHandled?: boolean; + /** + * The record behind `lastStop` (tracking issue #1362, stage "stop record"): + * written with it, only by src/session/stop-record.ts. Read through + * `stopRecordOf`, which answers none when `lastStop` was written around it. + */ + stopRecord?: StopRecord; + /** The last stop shown in this run (stop-record.ts); reset when a run starts. */ + lastShownStop?: StopRecord; /** * The last snapshot's rendered locals, for changedVariables diffs (issue * #983): a later stop in the same frame (frameKey = anchor name|file| - * visible depth) reports only what changed. `stopRef` is the lastStop the - * base was read at, compared by identity so the same stop answered twice - * never diffs against itself. Cleared at the launch/attach boundaries; - * survives ordinary resumes on purpose. + * visible depth) reports only what changed. `stopId` is the id of the stop + * record the base was read at, so the same stop answered twice never diffs + * against itself. Cleared at the launch/attach boundaries; survives + * ordinary resumes on purpose. */ snapshotDiffBase?: { - stopRef: SessionStopInfo; + stopId: StopId; frameKey: string; rendered: Record; /** diff --git a/src/session/stop-record.ts b/src/session/stop-record.ts new file mode 100644 index 000000000..576cde99f --- /dev/null +++ b/src/session/stop-record.ts @@ -0,0 +1,215 @@ +/** + * One record per stop (tracking issue #1362, stage "stop record"). + * + * A stop gets an id when the core applies it, and the record carries the run + * it arrived on, its session, its thread, its reason, whether it is shown, + * and the operation in flight that it answers. The session's `lastStop` is + * the record's public face, `info`: the object every answer projects (and + * redacts). The record itself never leaves the server, so nothing here adds + * a field to an answer. + * + * What a session has recorded, the stop it is at, and the last stop it showed + * are readings of these records: + * + * - `stopRecordOf(session)`: the record behind `session.lastStop`. It has + * today's lifetime: set at each stop (a shown one, or the entry stop the + * core resumes unseen, while that resume is in flight), erased with that + * hidden stop once it is resumed, kept across a resume of a shown stop, + * reset when a run starts. + * - `currentStopOf(session)`: the stop the session is at, the record while + * the session is paused. It is a reading of the state rather than a field, + * so a resume, an ending and a refused resume's rollback each give the + * answer the state gives, with nothing to clear or restore. + * - `session.lastShownStop`: the last stop shown in this run, kept across + * resumes and across a hidden stop. Nothing reads it yet: the stage that + * stops a hidden stop entering `paused` moves the readers that mean "a stop + * was shown in this run" onto it. + * + * Every write of `session.lastStop` in shipped code is one of the three + * functions below (`applyStop`, `eraseHiddenStop`, `resetStops`); a source + * scan in the unit suite (tests/core/unit/session/stop-record-writes.test.ts) + * fails on any other. A record whose `info` is not the session's `lastStop` + * (a stop written around this module, by a test) is no record: the reading + * answers none, the snapshot's locals check never holds on it, and an answer + * pinned on it names no stop. + * + * The comparisons that used to take a stop's identity from the identity of + * the `lastStop` object compare these ids instead. + */ +import { SessionState, type SessionStopInfo } from '@debugmcp/shared'; + +/** A stop's identity: minted when the core applies the stop, never reused in this process. */ +export type StopId = number; + +/** An operation's identity (a step or a pause), minted when it is armed. */ +export type OperationId = number; + +/** + * The operation a stop can answer: a step on its thread, a pause the user + * asked for, or the pause an attach sends. + */ +export type OperationKind = 'step' | 'pause' | 'attach-pause'; + +export interface OperationRef { + readonly id: OperationId; + readonly kind: OperationKind; + /** The thread the operation was sent for, when it names one. */ + readonly threadId?: number; +} + +export interface StopRecord { + readonly id: StopId; + /** The proxy generation the stop arrived on: the session's run of its connection (`proxyGeneration`). */ + readonly runId: number; + readonly sessionId: string; + readonly threadId?: number; + /** The reason as the core recorded it (after the policy's normalization). */ + readonly reason: string; + /** False for the entry stop the core resumes without showing it. */ + readonly shown: boolean; + /** + * The operation that was in flight when the stop was applied, when one was + * (a pause armed on this run's proxy before a step on the stop's thread). + * What was in flight, not a verdict on what caused the stop: that is the + * reducer's, in the stage after the next. + */ + readonly cause?: OperationRef; + /** + * The worker's receipt sequence number for the `stopped` event. Empty in + * this stage: the next part stamps it where the worker receives the event, + * and applies no observation older than one already applied. + */ + readonly seq?: number; + /** The stop as answers show it: the object `session.lastStop` holds. */ + readonly info: SessionStopInfo; +} + +/** The fields of a session this module reads and writes. A ManagedSession is one. */ +export interface StopHolder { + readonly id: string; + readonly state: SessionState; + lastStop?: SessionStopInfo; + stopRecord?: StopRecord; + lastShownStop?: StopRecord; + proxyGeneration?: number; +} + +/** The reading side only: what the comparisons need. */ +export type StopReader = Pick; + +let lastStopId = 0; +let lastOperationId = 0; + +/** A new operation's identity. */ +export function nextOperationId(): OperationId { + lastOperationId += 1; + return lastOperationId; +} + +/** + * Apply a stop the core has decided on: mint its record and make it the + * session's. `info` becomes `session.lastStop`. A shown stop also becomes the + * last stop shown in this run. + */ +export function applyStop( + session: StopHolder, + info: SessionStopInfo, + opts: { shown: boolean; cause?: OperationRef } +): StopRecord { + lastStopId += 1; + const record: StopRecord = { + id: lastStopId, + runId: session.proxyGeneration ?? 0, + sessionId: session.id, + ...(typeof info.threadId === 'number' ? { threadId: info.threadId } : {}), + reason: info.reason, + shown: opts.shown, + ...(opts.cause ? { cause: opts.cause } : {}), + info + }; + session.lastStop = info; + session.stopRecord = record; + if (opts.shown) { + session.lastShownStop = record; + } + return record; +} + +/** + * Erase the hidden stop the core resumed, if it is still the session's: a + * newer stop that raced the resume replaced it and is kept. True when erased. + */ +export function eraseHiddenStop(session: StopHolder, record: StopRecord): boolean { + if (stopRecordOf(session)?.id !== record.id) { + return false; + } + session.lastStop = undefined; + session.stopRecord = undefined; + return true; +} + +/** A run starts: nothing is recorded, nothing has been shown. */ +export function resetStops(session: StopHolder): void { + session.lastStop = undefined; + session.stopRecord = undefined; + session.lastShownStop = undefined; +} + +/** + * The record behind `session.lastStop`, or undefined when there is none or + * when `lastStop` was written around this module. + */ +export function stopRecordOf(session: StopReader | undefined): StopRecord | undefined { + const record = session?.stopRecord; + return record !== undefined && session?.lastStop !== undefined && record.info === session.lastStop + ? record + : undefined; +} + +/** The id of the record behind `session.lastStop`, or undefined (see `stopRecordOf`). */ +export function stopIdOf(session: StopReader | undefined): StopId | undefined { + return stopRecordOf(session)?.id; +} + +/** The stop the session is at: its record while it is paused. */ +export function currentStopOf(session: (StopReader & { readonly state: SessionState }) | undefined): StopRecord | undefined { + return session?.state === SessionState.PAUSED ? stopRecordOf(session) : undefined; +} + +/** + * The stop an answer describes, taken before the answer's first await + * (inspection/pinned-stop-read.ts has the rule every answer follows). + */ +export interface StopPin { + readonly sessionId: string; + /** The session's stop record when the pin was taken; undefined when it had none. */ + readonly stop: StopRecord | undefined; +} + +/** Pin the session's stop now. Synchronous: call it before the answer's first await. */ +export function pinStop(session: StopReader & { readonly id: string }): StopPin { + return { sessionId: session.id, stop: stopRecordOf(session) }; +} + +/** + * Whether the session still records the pinned stop, by the record's id: what + * a read that must belong to a recorded stop checks (the snapshot's locals). + * Fails closed: false when either side has no record. + */ +export function pinHolds(session: StopReader | undefined, pin: StopPin): boolean { + return pin.stop !== undefined && stopIdOf(session) === pin.stop.id; +} + +/** + * Whether an answer's reads must be made again: the session is paused, and + * the id of the stop it records is not the pin's. Having no record counts as + * a value of its own, so a session paused with none (the refused step's + * rollback with no stop recorded) and pinned with none is unchanged, and its + * answer names no stop, as before; one that has a record now, or has lost + * the pinned one, is changed. A session that is gone, not paused, or still at + * the pinned stop is not; how it is answered is the caller's rule (an ending + * as ended, a resume as running). + */ +export function pinBroken(session: (StopReader & { readonly state: SessionState }) | undefined, pin: StopPin): boolean { + return session !== undefined && session.state === SessionState.PAUSED && stopIdOf(session) !== pin.stop?.id; +} diff --git a/src/utils/error-messages.ts b/src/utils/error-messages.ts index 28ba25f97..75de518a4 100644 --- a/src/utils/error-messages.ts +++ b/src/utils/error-messages.ts @@ -678,6 +678,17 @@ export const ErrorMessages = { sessionClosedWhileWaiting: (sessionId: string) => `Session ${sessionId} was closed while waiting for a stop.`, + /** + * A stop answer whose stop changed while it was being read, and again while + * it was read a second time (tracking issue #1362, stage "stop record"; + * issue #1348): the answer names the stop the program is paused at now and + * carries no location, frames or locals, because none was read for that + * stop. Says where to read them. + */ + stopChangedWhileRead: () => + 'The program stopped again while this answer was being read, twice, so where it is paused was not read: ' + + 'the reason given is the stop it is at now. get_stack_trace and get_local_variables read that stop.', + /** * A launch answered while the program is still running (issues #815, #823, * #826): the short hold for its first stop elapsed with no stop and no diff --git a/tests/core/unit/server/stop-pins-through-tools.test.ts b/tests/core/unit/server/stop-pins-through-tools.test.ts new file mode 100644 index 000000000..589052d11 --- /dev/null +++ b/tests/core/unit/server/stop-pins-through-tools.test.ts @@ -0,0 +1,159 @@ +/** + * One answer, one stop, through the tools (tracking issue #1362, stage + * "stop record"; issue #1348): the same probes as the session layer's, made + * through the real dispatch over the real SessionManager (mock proxy), so the + * handlers' own reads (the source line and the stale-build note, read from + * the answer's location) and get_stack_trace, whose pin is the handler's, are + * covered too. The engine reports a new stop from inside the stack read. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { DebugLanguage, SessionState } from '@debugmcp/shared'; +import { DebugMcpServer } from '../../../../src/server.js'; +import { registerToolHandlers } from '../../../../src/server/tool-dispatch.js'; +import { createProductionDependencies, type Dependencies } from '../../../../src/container/dependencies.js'; +import { createMockDependencies } from '../session/session-manager-test-utils.js'; +import { ErrorMessages } from '../../../../src/utils/error-messages.js'; + +vi.mock('../../../../src/container/dependencies.js'); + +type Handler = (request: unknown, callCtx?: unknown) => Promise<{ content: Array<{ text: string }> }>; + +const FRAMES = { + A: { id: 1, name: 'main', source: { path: '/w/app.py' }, line: 11, column: 0 }, + B: { id: 2, name: 'callee', source: { path: '/w/app.py' }, line: 50, column: 0 }, + C: { id: 3, name: 'other', source: { path: '/w/app.py' }, line: 70, column: 0 } +} as const; +const STOPS = { + B: { threadId: 2, reason: 'exception', description: 'B: ValueError' }, + C: { threadId: 3, reason: 'breakpoint', description: 'C: hit' } +} as const; + +describe('one answer, one stop, through the tools', () => { + let core: DebugMcpServer; + let dependencies: ReturnType; + let callTool: Handler; + + beforeEach(() => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + dependencies = createMockDependencies(); + vi.mocked(createProductionDependencies).mockReturnValue(dependencies as unknown as Dependencies); + core = new DebugMcpServer(); + let handler: Handler | undefined; + registerToolHandlers({ + setRequestHandler: (method: string, registered: Handler) => { + if (method === 'tools/call') handler = registered; + } + } as never, core); + callTool = handler!; + }); + + afterEach(async () => { + await core?.sessionManager.closeAllSessions().catch(() => undefined); + vi.useRealTimers(); + vi.clearAllMocks(); + dependencies.mockProxyManager.reset(); + }); + + async function answer(name: string, args: Record): Promise> { + const raw = await callTool( + { method: 'tools/call', params: { name, arguments: args } }, + { mcpReq: { signal: new AbortController().signal } } + ); + return JSON.parse(raw.content[0].text) as Record; + } + + /** A session paused at A on thread 1; the engine reports each of `then` from inside one stack read. */ + async function pausedAtA(then: Array<'B' | 'C'>) { + const session = await core.sessionManager.createSession({ language: DebugLanguage.MOCK, executablePath: 'python' }); + const started = core.sessionManager.startDebugging(session.id, 'app.py', [], { stopOnEntry: false }); + await vi.runAllTimersAsync(); + expect((await started).state).toBe(SessionState.RUNNING); + const proxy = dependencies.mockProxyManager; + proxy.simulateStopped(1, 'breakpoint', { reason: 'breakpoint', threadId: 1 }); + await vi.advanceTimersByTimeAsync(20); + let current: 'A' | 'B' | 'C' = 'A'; + const queue = [...then]; + proxy.setDapRequestHandler(async (command: string) => { + if (command === 'stackTrace') { + const at = current; + const next = queue.shift(); + if (next) { + current = next; + const { threadId, reason, description } = STOPS[next]; + proxy.simulateStopped(threadId, reason, { reason, threadId, description }); + } + return { success: true, body: { stackFrames: [FRAMES[at]] } }; + } + if (command === 'scopes') return { success: true, body: { scopes: [] } }; + return { success: true }; + }); + return session.id; + } + + it('wait_for_stop: the hoisted location, its source line and lastStop are one stop\'s', async () => { + const sessionId = await pausedAtA(['B']); + + const response = await answer('wait_for_stop', { sessionId, timeout: 2000 }); + + expect(response.state).toBe(SessionState.PAUSED); + expect(response.location).toMatchObject({ line: 50 }); + expect(response.lastStop).toMatchObject({ reason: 'exception', threadId: 2 }); + expect(response.message).toBe('Paused (exception) at /w/app.py:50'); + }); + + it('step_over: the hoisted location and stopReason are one stop\'s', async () => { + const sessionId = await pausedAtA([]); + const proxy = dependencies.mockProxyManager; + let stepped = false; + let current: 'A' | 'S' | 'B' = 'A'; + proxy.setDapRequestHandler(async (command: string) => { + if (command === 'next') { + stepped = true; + process.nextTick(() => { + current = 'S'; + proxy.simulateStopped(1, 'step', { reason: 'step', threadId: 1 }); + }); + return { success: true }; + } + if (command === 'stackTrace') { + const at = current; + if (stepped && current === 'S') { + current = 'B'; + proxy.simulateStopped(2, 'exception', { reason: 'exception', threadId: 2, description: 'B: ValueError' }); + } + return { success: true, body: { stackFrames: [at === 'B' ? FRAMES.B : FRAMES.A] } }; + } + if (command === 'scopes') return { success: true, body: { scopes: [] } }; + return { success: true }; + }); + + const response = await answer('step_over', { sessionId }); + + expect(response.success).toBe(true); + expect(response.location).toMatchObject({ line: 50 }); + expect(response.stopReason).toBe('exception'); + }); + + it('get_stack_trace: a stop that lands during the fetch is fetched again, and its reason is the frames\' stop\'s', async () => { + const sessionId = await pausedAtA(['B']); + + const response = await answer('get_stack_trace', { sessionId }); + + expect(response.success).toBe(true); + expect(response.stackFrames?.[0]).toMatchObject({ line: 50 }); + expect(response.stopReason).toBe('exception'); + expect(response.lastStop).toMatchObject({ reason: 'exception', threadId: 2 }); + }); + + it('get_stack_trace: a stop that changes again during the second fetch is answered with no frames, the current stop and the sentence', async () => { + const sessionId = await pausedAtA(['B', 'C']); + + const response = await answer('get_stack_trace', { sessionId }); + + expect(response.success).toBe(true); + expect(response.stackFrames).toEqual([]); + expect(response.stopReason).toBe('breakpoint'); + expect(response.lastStop).toMatchObject({ reason: 'breakpoint', threadId: 3 }); + expect(response.note).toBe(ErrorMessages.stopChangedWhileRead()); + }); +}); diff --git a/tests/core/unit/session/breakpoints/breakpoint-controller-armed-pause.test.ts b/tests/core/unit/session/breakpoints/breakpoint-controller-armed-pause.test.ts index 01d57bad0..0ac5c0c88 100644 --- a/tests/core/unit/session/breakpoints/breakpoint-controller-armed-pause.test.ts +++ b/tests/core/unit/session/breakpoints/breakpoint-controller-armed-pause.test.ts @@ -71,7 +71,7 @@ function harness(policy: unknown = HOLDS) { for (const listener of [...listeners]) listener(); await new Promise((resolve) => setImmediate(resolve)); }; - const arm = () => { session.pauseIntent = { generation: 3, source: 'user', armedAt: Date.now() }; }; + const arm = () => { session.pauseIntent = { id: 9001, generation: 3, source: 'user', armedAt: Date.now() }; }; const land = async () => { session.pauseIntent = undefined; session.lastStop = { reason: 'pause' } as ManagedSession['lastStop']; @@ -282,13 +282,13 @@ describe('breakpoint requests wait for an armed pause (issue #1146)', () => { it.each([ ['no pause is armed', HOLDS, (session: ManagedSession) => { session.pauseIntent = undefined; }], ['the armed pause belongs to an earlier proxy generation', HOLDS, (session: ManagedSession) => { - session.pauseIntent = { generation: 2, source: 'user', armedAt: 1 }; + session.pauseIntent = { id: 9002, generation: 2, source: 'user', armedAt: 1 }; }], ['the policy does not declare the hold', {}, (session: ManagedSession) => { - session.pauseIntent = { generation: 3, source: 'user', armedAt: 1 }; + session.pauseIntent = { id: 9003, generation: 3, source: 'user', armedAt: 1 }; }], ['the policy cannot be selected', undefined, (session: ManagedSession) => { - session.pauseIntent = { generation: 3, source: 'user', armedAt: 1 }; + session.pauseIntent = { id: 9003, generation: 3, source: 'user', armedAt: 1 }; }] ] as const)('sends at once when %s', async (_name, policy, prepare) => { const { controller, session, ctx, sent } = harness(policy); diff --git a/tests/core/unit/session/inspection/stop-snapshot.test.ts b/tests/core/unit/session/inspection/stop-snapshot.test.ts index 4f156496a..fde484b6e 100644 --- a/tests/core/unit/session/inspection/stop-snapshot.test.ts +++ b/tests/core/unit/session/inspection/stop-snapshot.test.ts @@ -8,6 +8,7 @@ import { describe, it, expect, vi, afterEach } from 'vitest'; import { SessionState, PythonAdapterPolicy } from '@debugmcp/shared'; import type { StackTraceResult } from '../../../../../src/session/inspection/frame-anchor-resolver.js'; +import { setStopForTest } from '../../../../test-utils/helpers/stop-record.js'; import { composeStopSnapshot, type StopSnapshotContext @@ -61,12 +62,14 @@ function makeCtx(opts: { return Promise.resolve(locals.value); }); const logger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }; - // One stable session object: the diff cache (issue #983) lives on it and - // the stop-identity rule compares lastStop by reference. + // One stable session object: the diff cache (issue #983) lives on it, and + // its stop has a record the way the core applies one (tracking issue + // #1362), so the identity rules compare record ids. const session: Record = { - state: opts.state ?? SessionState.PAUSED, - lastStop: opts.lastStop ?? { reason: 'breakpoint', timestamp: 1, threadId: 1 } + id: 'sid', + state: opts.state ?? SessionState.PAUSED }; + setStopForTest(session as never, (opts.lastStop ?? { reason: 'breakpoint', timestamp: 1, threadId: 1 }) as never); const ctx = { logger, tunables: { snapshotLocalsTimeoutMs: opts.timeoutMs ?? 2000 }, @@ -497,7 +500,7 @@ describe('composeStopSnapshot diff cache (issue #983)', () => { scopeName: 'Locals' }); const newStop = (session: Record) => { - session.lastStop = { reason: 'breakpoint', timestamp: Date.now(), threadId: 1 }; + setStopForTest(session as never, { reason: 'breakpoint', timestamp: Date.now(), threadId: 1 } as never); }; it('first stop emits full locals and seeds the cache; the next stop in the same frame emits only what changed', async () => { @@ -617,7 +620,7 @@ describe('composeStopSnapshot diff vocabulary: changed, new, gone (issue #1140)' const numbered = (prefix: string, count: number): Array<[string, string]> => Array.from({ length: count }, (_, i): [string, string] => [`${prefix}${String(i).padStart(2, '0')}`, `${i}`]); const newStop = (session: Record) => { - session.lastStop = { reason: 'step', timestamp: Date.now(), threadId: 1 }; + setStopForTest(session as never, { reason: 'step', timestamp: Date.now(), threadId: 1 } as never); }; /** Compose once per read, each on a fresh stop, and answer the last snapshot. */ @@ -952,10 +955,9 @@ describe('review fixes: notes and truncation honesty', () => { expect(first?.locals).toEqual({ x: '11' }); // Second stop: a step_out from global.key landed in global.key again (#1196). - const stepStop = { reason: 'step', timestamp: 2, threadId: 1 }; - session.lastStop = stepStop; + const stepStop = setStopForTest(session as never, { reason: 'step', timestamp: 2, threadId: 1 }); session.lastStepProvenance = { - stopRef: stepStop, + stopId: stepStop.id, flavor: 'stepOut', origin: { rawTop: cbFrames[0], rawDepth: 2, visibleFrames: cbFrames as never, threadId: 1 } }; @@ -968,7 +970,7 @@ describe('review fixes: notes and truncation honesty', () => { cbFrames[0], { id: 9, name: '50000061', file: '', line: 0, column: 0, unresolvedSource: true } ]; - session.lastStop = { reason: 'step', timestamp: 3, threadId: 1 }; + setStopForTest(session as never, { reason: 'step', timestamp: 3, threadId: 1 } as never); const afterBrokenUnwind = await composeStopSnapshot(ctx, 'sid', stack({ frames: brokenFrames as never }), 'stepOver'); expect(afterBrokenUnwind?.locals).toEqual({ x: '99' }); expect(afterBrokenUnwind?.changedVariables).toBeUndefined(); @@ -986,7 +988,7 @@ describe('review fixes: notes and truncation honesty', () => { frame: FRAMES[0], scopeName: 'Local' }); - session.lastStop = { reason: 'step', timestamp: index + 1, threadId: 1 }; + setStopForTest(session as never, { reason: 'step', timestamp: index + 1, threadId: 1 } as never); const snapshot = await composeStopSnapshot(ctx, 'sid', stack({ frames: brokenFrames }), 'stepOver'); expect(snapshot?.locals).toEqual({ x: value }); expect(snapshot?.changedVariables).toBeUndefined(); @@ -1001,12 +1003,12 @@ describe('review fixes: notes and truncation honesty', () => { .mockResolvedValueOnce({ variables: [{ name: 'x', value: '22', variablesReference: 0 }], frame: FRAMES[0] }); await composeStopSnapshot(ctx, 'sid', stack(resolvedThread ? { threadId: 1 } : {}), 'test'); // A resolved inspection thread wins over the thread named by the stop. - session.lastStop = { reason: 'breakpoint', timestamp: 2, threadId: resolvedThread ? 1 : 2 }; + setStopForTest(session as never, { reason: 'breakpoint', timestamp: 2, threadId: resolvedThread ? 1 : 2 } as never); const second = await composeStopSnapshot(ctx, 'sid', stack(resolvedThread ? { threadId: 2 } : {}), 'test'); expect(second?.locals).toEqual({ x: '21' }); expect(second?.changedVariables).toBeUndefined(); - session.lastStop = { reason: 'step', timestamp: 3, threadId: resolvedThread ? 1 : 2 }; + setStopForTest(session as never, { reason: 'step', timestamp: 3, threadId: resolvedThread ? 1 : 2 } as never); const third = await composeStopSnapshot(ctx, 'sid', stack(resolvedThread ? { threadId: 2 } : {}), 'test'); expect(third?.changedVariables).toEqual({ x: { before: '21', after: '22' } }); }); @@ -1082,7 +1084,7 @@ describe('review fixes: stop identity across the locals read', () => { const { ctx, extractLocalsFromResolved, session } = makeCtx(); (extractLocalsFromResolved as ReturnType).mockImplementationOnce(async () => { // A different stop lands while the read is in flight. - session.lastStop = { reason: 'breakpoint', timestamp: 2, threadId: 1 }; + setStopForTest(session as never, { reason: 'breakpoint', timestamp: 2, threadId: 1 } as never); return { variables: [{ name: 'x', value: '1', type: 'int', variablesReference: 0 }], frame: null, diff --git a/tests/core/unit/session/pause-coordinator.test.ts b/tests/core/unit/session/pause-coordinator.test.ts index 150260188..76dd02e21 100644 --- a/tests/core/unit/session/pause-coordinator.test.ts +++ b/tests/core/unit/session/pause-coordinator.test.ts @@ -164,7 +164,7 @@ describe('PauseCoordinator', () => { it('evaluates again once the armed pause belongs to an earlier proxy generation', async () => { const { proxy, session, coordinator } = fixture({ pauseWakeExpression: WAKE }); - session.pauseIntent = { generation: 6, source: 'user', armedAt: 1 }; + session.pauseIntent = { id: 9004, generation: 6, source: 'user', armedAt: 1 }; proxy.sendDapRequest.mockImplementation((command: string) => { if (command === 'pause') proxy.emit('stopped', { reason: 'pause', threadId: 1 }); return Promise.resolve({ success: true }); diff --git a/tests/core/unit/session/session-manager-attach-modes.test.ts b/tests/core/unit/session/session-manager-attach-modes.test.ts index 54486a6ed..526bd7c3b 100644 --- a/tests/core/unit/session/session-manager-attach-modes.test.ts +++ b/tests/core/unit/session/session-manager-attach-modes.test.ts @@ -39,6 +39,7 @@ import type { LanguageSpecificLaunchConfig } from '@debugmcp/shared'; import { setSessionStateForTest } from '../../../test-utils/helpers/session-state.js'; +import { setStopForTest } from '../../../test-utils/helpers/stop-record.js'; class TestableSessionManagerOperations extends SessionManagerOperations { protected attachVerifyIntervalMs = 5; @@ -582,6 +583,47 @@ describe('SessionManagerOperations attach modes', () => { expect(result.data?.snapshot?.locals).toBeUndefined(); }); + it('describes one stop when the target stops again during the attach answer\'s landing read (tracking issue #1362)', async () => { + mockSession.language = DebugLanguage.CPP; + vi.mocked(mockDependencies.adapterRegistry.getFactoryMetadata).mockResolvedValue( + metadataWithModes({ launch: true, attach: 'direct-connect' }) + ); + vi.mocked(mockDependencies.adapterRegistry.create).mockResolvedValue( + new FakeDebugAdapter({ language: DebugLanguage.CPP }).withAttachSupport({ directConnect: true }) + ); + mockProxyManager.getCurrentThreadId.mockReturnValue(7); + const FRAME_A = { id: 1, name: 'main', line: 11, column: 0, source: { path: '/proj/app.cpp' } }; + const FRAME_B = { id: 2, name: 'callee', line: 50, column: 0, source: { path: '/proj/app.cpp' } }; + let current: 'A' | 'B' = 'A'; + mockProxyManager.sendDapRequest.mockImplementation(async (command: string, args?: unknown) => { + if (command === 'threads') { + setSessionStateForTest(mockSession, SessionState.PAUSED); + if (!mockSession.lastStop) setStopForTest(mockSession, { reason: 'breakpoint', threadId: 7, timestamp: Date.now() }); + return { success: true, body: { threads: [{ id: 7, name: 'main' }] } }; + } + if (command === 'stackTrace') { + const at = current; + // The resolver's read (no `levels`), not the attach's anchor unwind: the + // target reports an exception from inside it. + if (current === 'A' && (args as { levels?: number }).levels === undefined) { + current = 'B'; + setStopForTest(mockSession, { reason: 'exception', threadId: 7, timestamp: Date.now(), description: 'B: ValueError' }); + } + return { success: true, body: { stackFrames: [at === 'A' ? FRAME_A : FRAME_B] } }; + } + return {}; + }); + + const result = await operations.attachToProcess('test-session', { host: '127.0.0.1', port: 12345, stopOnEntry: true }); + + expect(result.success).toBe(true); + expect(current).toBe('B'); + // Read again for the stop the target is at now: B's location and B's frames, never A's. + expect(result.data?.location).toMatchObject({ line: 50 }); + expect(result.data?.snapshot?.frames?.[0]).toMatchObject({ line: 50 }); + expect(result.data?.snapshot?.exception).toMatchObject({ type: 'B: ValueError' }); + }); + it('falls back to the thread named main, else the first thread, when no stop was observed', async () => { mockSession.language = DebugLanguage.CPP; vi.mocked(mockDependencies.adapterRegistry.getFactoryMetadata).mockResolvedValue( diff --git a/tests/core/unit/session/session-manager-dap.test.ts b/tests/core/unit/session/session-manager-dap.test.ts index 8c35e5d76..6e2eaa118 100644 --- a/tests/core/unit/session/session-manager-dap.test.ts +++ b/tests/core/unit/session/session-manager-dap.test.ts @@ -2852,15 +2852,12 @@ describe('SessionManager - DAP Operations', () => { await vi.advanceTimersByTimeAsync(20); expect(releaseSupersededLanding).toBeDefined(); - // A superseding stop completes its landing read first (entering `callee`, with no hint), - // settling `executeStep` before the first `onStopped` finishes its same-depth landing read. + // A superseding stop lands while the first stop's same-depth landing + // read (which would carry the hint) is still in flight. The first stop + // owns the answer, and its pin (tracking issue #1362) finds the newer + // stop: the answer is read again for it (entering `callee`, no hint). dependencies.mockProxyManager.simulateStopped(1, 'step'); await vi.advanceTimersByTimeAsync(20); - const returned = await stepPromise; - expect(returned.success).toBe(true); - expect(returned.data?.location?.line).toBe(2); - expect(returned.data?.note).toBeUndefined(); - releaseSupersededLanding!({ success: true, body: { @@ -2869,7 +2866,12 @@ describe('SessionManager - DAP Operations', () => { } }); await vi.runAllTimersAsync(); + const returned = await stepPromise; + expect(returned.success).toBe(true); + expect(returned.data?.location?.line).toBe(2); + expect(returned.data?.note).toBeUndefined(); + // The superseded landing's hint was never in an answer that was returned. expect(sessionManager.getSession(session.id)?.run.deliveredStepFilterHints).toBeUndefined(); }); @@ -5570,6 +5572,7 @@ describe('SessionManager - DAP Operations', () => { const session = await createPausedRustSession(); const managed = sessionManager.getSession(session.id)!; managed.pauseIntent = { + id: 9005, generation: managed.proxyGeneration ?? 0, source: 'user', armedAt: Date.now() @@ -5590,6 +5593,7 @@ describe('SessionManager - DAP Operations', () => { const session = await createPausedRustSession(); const managed = sessionManager.getSession(session.id)!; managed.pauseIntent = { + id: 9006, generation: managed.proxyGeneration ?? 0, source: 'attach', armedAt: Date.now() diff --git a/tests/core/unit/session/session-manager-integration.test.ts b/tests/core/unit/session/session-manager-integration.test.ts index 5fb8347a7..94d654ae5 100644 --- a/tests/core/unit/session/session-manager-integration.test.ts +++ b/tests/core/unit/session/session-manager-integration.test.ts @@ -72,7 +72,7 @@ describe('SessionManager - Integration Tests', () => { await sessionManager.continue(session.id); const managed = sessionManager.getSession(session.id)!; expect(managed.state).toBe(SessionState.RUNNING); - const intent = { generation: managed.proxyGeneration ?? 0, source: 'user' as const, armedAt: Date.now() }; + const intent = { id: 9007, generation: managed.proxyGeneration ?? 0, source: 'user' as const, armedAt: Date.now() }; managed.pauseIntent = intent; const told = vi.fn(); (sessionManager as unknown as { diff --git a/tests/core/unit/session/session-manager-snapshot.test.ts b/tests/core/unit/session/session-manager-snapshot.test.ts index 9a5d8d8fd..9e81a2ecf 100644 --- a/tests/core/unit/session/session-manager-snapshot.test.ts +++ b/tests/core/unit/session/session-manager-snapshot.test.ts @@ -510,11 +510,12 @@ describe('review fixes: answers stay coherent across the locals read (issue #982 const result = await wait; expect(result.success).toBe(true); - // The wait settled on stop A: the whole answer speaks about A. - expect(result.data?.lastStop?.reason).toBe('breakpoint'); - expect(result.data?.message).toContain('(breakpoint)'); - // The snapshot never mixes stops: A's frames may ship (they are this - // answer's stop), but locals read under B's world may not. + // The stop changed under the answer's reads (tracking issue #1362): they + // are made again for stop B, and the whole answer speaks about B. + expect(result.data?.lastStop?.reason).toBe('exception'); + expect(result.data?.message).toContain('(exception)'); + // The snapshot never mixes stops: B's locals read hangs too, so it ships + // without locals, and nothing read under A's world rides along. expect(result.data?.snapshot?.locals).toBeUndefined(); expect(result.data?.snapshot?.changedVariables).toBeUndefined(); }); diff --git a/tests/core/unit/session/session-manager-stop-pin-routes.test.ts b/tests/core/unit/session/session-manager-stop-pin-routes.test.ts new file mode 100644 index 000000000..6eb1925d3 --- /dev/null +++ b/tests/core/unit/session/session-manager-stop-pin-routes.test.ts @@ -0,0 +1,526 @@ +/** + * The routes by which one answer could mix two stops, beyond the landing's + * stack read (tracking issue #1362, stage "stop record"; issue #1348). The + * stop changes because the engine reports it from inside a read the answer + * makes, never by timing: + * + * - other reads of the same answer: the snapshot's locals read (`variables`), + * the resolver's sibling scan for a pause (`threads`), the launch's + * breakpoint re-send (`setBreakpoints`), and the exceptionInfo enrichment + * that merges into a stop record after the stop is shown; + * - other handles on the same stop: a child's stop read through its root's + * launch answer (`pausedChild`), the tree-aware wait's choice of a + * descendant, and a hidden stop (the entry stop the core resumes unseen) + * that lands during a read and is gone when it ends. + * + * Mock proxy, fake timers. Stop A is a breakpoint on thread 1 at main:11; + * stop B an exception on thread 2 at callee:50. + */ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { SessionManager, SessionManagerConfig } from '../../../../src/session/session-manager.js'; +import { DartAdapterPolicy, DebugLanguage, MockAdapterPolicy, SessionState, type AdapterPolicy } from '@debugmcp/shared'; +import { createMockDependencies, overridePolicy } from './session-manager-test-utils.js'; +import type { MockProxyManager } from '../../../test-utils/mocks/mock-proxy-manager.js'; + +const FRAME_A = { id: 1, name: 'main', source: { path: '/w/app.py' }, line: 11, column: 0 }; +const FRAME_B = { id: 2, name: 'callee', source: { path: '/w/app.py' }, line: 50, column: 0 }; +/** A frame the debugger has no source for: no program code. */ +const FRAME_IDLE = { id: 3, name: 'idle', line: 0, column: 0 }; +const FRAME_WORKER = { id: 4, name: 'worker', source: { path: '/w/app.py' }, line: 30, column: 0 }; + +const report = (reportId: string, pid = 4242) => ({ + reportId, + targetId: String(pid), + name: `Subprocess ${pid}`, + configuration: { type: 'python', subProcessId: pid } +}); + +describe('Stop pins: the routes beyond the landing read', () => { + let sessionManager: SessionManager; + let dependencies: ReturnType; + + beforeEach(() => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + dependencies = createMockDependencies(); + const config: SessionManagerConfig = { + logDirBase: '/tmp/test-sessions', + defaultDapLaunchArgs: { stopOnEntry: false, justMyCode: true } + }; + sessionManager = new SessionManager(config, dependencies); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.clearAllMocks(); + dependencies.mockProxyManager.reset(); + }); + + async function runningSession(): Promise { + const session = await sessionManager.createSession({ language: DebugLanguage.MOCK, executablePath: 'python' }); + const started = sessionManager.startDebugging(session.id, 'app.py', [], { stopOnEntry: false }); + await vi.runAllTimersAsync(); + expect((await started).state).toBe(SessionState.RUNNING); + return session.id; + } + + const stopB = (proxy: MockProxyManager) => + proxy.simulateStopped(2, 'exception', { reason: 'exception', threadId: 2, description: 'B: ValueError' }); + + /** + * An engine whose stacks, scopes and locals are those of the stop current + * when each request arrives; stop B is reported from inside the first + * request of `command` made while `armed()` says so. `extra` answers the + * other commands a case needs. + */ + function engineChangingIn( + proxy: MockProxyManager, + command: string, + armed: () => boolean = () => true, + extra?: (name: string) => unknown + ) { + let current: 'A' | 'B' = 'A'; + let fired = false; + proxy.setDapRequestHandler(async (name: string) => { + const answered = extra?.(name); + if (answered !== undefined) return answered; + const at = current; + if (name === command && !fired && armed()) { + fired = true; + current = 'B'; + stopB(proxy); + } + switch (name) { + case 'stackTrace': + return { success: true, body: { stackFrames: [at === 'A' ? FRAME_A : FRAME_B] } }; + case 'scopes': + return { success: true, body: { scopes: [{ name: 'Locals', variablesReference: at === 'A' ? 100 : 200, expensive: false }] } }; + case 'variables': + return { success: true, body: { variables: [{ name: 'who', value: `'${at}'`, type: 'str', variablesReference: 0 }] } }; + case 'threads': + return { success: true, body: { threads: [{ id: 1, name: 'main' }, { id: 2, name: 'worker' }] } }; + case 'setBreakpoints': + return { success: true, body: { breakpoints: [{ id: 1, verified: true, line: 11 }] } }; + default: + return { success: true }; + } + }); + return { fired: () => fired }; + } + + it('wait_for_stop: a stop that lands during the snapshot\'s locals read is read again whole, its locals included', async () => { + const sessionId = await runningSession(); + const proxy = dependencies.mockProxyManager; + proxy.simulateStopped(1, 'breakpoint', { reason: 'breakpoint', threadId: 1 }); + const probe = engineChangingIn(proxy, 'variables'); + + const answer = await sessionManager.waitForStop(sessionId, 2000); + + expect(probe.fired()).toBe(true); + expect(answer.data?.lastStop).toMatchObject({ reason: 'exception', threadId: 2 }); + expect(answer.data?.location).toMatchObject({ line: 50 }); + expect(answer.data?.snapshot?.frames?.[0]).toMatchObject({ line: 50 }); + expect(answer.data?.snapshot?.locals).toEqual({ who: "'B'" }); + }); + + it('wait_for_stop: a stop that lands during the landing\'s short settle, before its stack request, is the one described', async () => { + const sessionId = await runningSession(); + const proxy = dependencies.mockProxyManager; + proxy.simulateStopped(1, 'breakpoint', { reason: 'breakpoint', threadId: 1 }); + await vi.advanceTimersByTimeAsync(20); + let current: 'A' | 'B' = 'A'; + proxy.setDapRequestHandler(async (name: string) => { + switch (name) { + case 'stackTrace': + return { success: true, body: { stackFrames: [current === 'A' ? FRAME_A : FRAME_B] } }; + case 'scopes': + return { success: true, body: { scopes: [] } }; + default: + return { success: true }; + } + }); + + const pending = sessionManager.waitForStop(sessionId, 2000); + // Inside the 10 ms settle the landing read waits before it asks for the stack. + await vi.advanceTimersByTimeAsync(4); + current = 'B'; + stopB(proxy); + await vi.advanceTimersByTimeAsync(100); + const answer = await pending; + + expect(answer.data?.lastStop).toMatchObject({ reason: 'exception', threadId: 2 }); + expect(answer.data?.location).toMatchObject({ line: 50 }); + expect(answer.data?.snapshot?.frames?.[0]).toMatchObject({ line: 50 }); + }); + + it('wait_for_stop: a stop that lands while the wait settles in-flight child releases is read again whole', async () => { + const sessionId = await runningSession(); + const proxy = dependencies.mockProxyManager; + proxy.simulateStopped(1, 'breakpoint', { reason: 'breakpoint', threadId: 1 }); + await vi.advanceTimersByTimeAsync(20); + let current: 'A' | 'B' = 'A'; + proxy.setDapRequestHandler(async (name: string) => { + switch (name) { + case 'stackTrace': + return { success: true, body: { stackFrames: [current === 'A' ? FRAME_A : FRAME_B] } }; + case 'scopes': + return { success: true, body: { scopes: [] } }; + default: + return { success: true }; + } + }); + // A child release still in flight (issue #1221): the wait settles it after + // its reads, and B lands while it does. + const session = sessionManager.getSession(sessionId)!; + let releaseStarted = false; + const release = new Promise((resolve) => { + setTimeout(() => { + releaseStarted = true; + current = 'B'; + stopB(proxy); + resolve(); + }, 30); + }); + session.run.inFlightChildReleases = new Set([release]); + + const pending = sessionManager.waitForStop(sessionId, 2000); + await vi.advanceTimersByTimeAsync(200); + const answer = await pending; + + expect(releaseStarted).toBe(true); + expect(answer.data?.lastStop).toMatchObject({ reason: 'exception', threadId: 2 }); + expect(answer.data?.location).toMatchObject({ line: 50 }); + }); + + it('step_over: a stop that lands during the step snapshot\'s locals read is read again whole, the step answer\'s fields included', async () => { + const sessionId = await runningSession(); + const proxy = dependencies.mockProxyManager; + proxy.simulateStopped(1, 'breakpoint', { reason: 'breakpoint', threadId: 1 }); + await vi.advanceTimersByTimeAsync(20); + let stepSent = false; + const probe = engineChangingIn(proxy, 'variables', () => stepSent, (name) => { + if (name !== 'next') return undefined; + stepSent = true; + process.nextTick(() => proxy.simulateStopped(1, 'step', { reason: 'step', threadId: 1 })); + return { success: true }; + }); + + const pending = sessionManager.stepOver(sessionId); + await vi.advanceTimersByTimeAsync(200); + const answer = await pending; + + expect(probe.fired()).toBe(true); + expect(answer.success).toBe(true); + expect(answer.data?.stopReason).toBe('exception'); + expect(answer.data?.location).toMatchObject({ line: 50 }); + expect(answer.data?.snapshot?.frames?.[0]).toMatchObject({ line: 50 }); + expect(answer.data?.snapshot?.locals).toEqual({ who: "'B'" }); + }); + + it('pause_execution: a stop that lands during the resolver\'s sibling scan is not adopted, and the answer is read again for it', async () => { + const sessionId = await runningSession(); + const proxy = dependencies.mockProxyManager; + let pauseSent = false; + let current: 'A' | 'B' = 'A'; + proxy.setDapRequestHandler(async (name: string, args?: { threadId?: number }) => { + switch (name) { + case 'pause': + pauseSent = true; + process.nextTick(() => proxy.simulateStopped(1, 'pause', { reason: 'pause', threadId: 1 })); + return { success: true }; + case 'threads': + if (pauseSent && current === 'A') { + current = 'B'; + stopB(proxy); + } + return { success: true, body: { threads: [{ id: 1, name: 'main' }, { id: 2, name: 'worker' }] } }; + case 'stackTrace': + if (args?.threadId === 1) return { success: true, body: { stackFrames: [FRAME_IDLE] } }; + return { success: true, body: { stackFrames: [current === 'A' ? FRAME_WORKER : FRAME_B] } }; + case 'scopes': + return { success: true, body: { scopes: [] } }; + default: + return { success: true }; + } + }); + + const pending = sessionManager.pause(sessionId, 1); + await vi.advanceTimersByTimeAsync(200); + const answer = await pending; + + expect(current).toBe('B'); + expect(answer.state).toBe(SessionState.PAUSED); + // The pause's own stop (A) was never adopted onto thread 2's worker frame + // under B: the answer is B's, landing and reason both. + expect(answer.data?.stopReason).toBe('exception'); + expect(answer.data?.location).toMatchObject({ line: 50 }); + expect(JSON.stringify(answer.data)).not.toContain('worker'); + }); + + it('start_debugging: a stop that lands while the launch re-sends its breakpoints is the stop the answer describes', async () => { + const session = await sessionManager.createSession({ language: DebugLanguage.MOCK, executablePath: 'python' }); + await sessionManager.setBreakpoint(session.id, { file: '/w/app.py', line: 11 }); + const proxy = dependencies.mockProxyManager; + let stopShown = false; + const probe = engineChangingIn(proxy, 'setBreakpoints', () => stopShown); + const started = sessionManager.startDebugging(session.id, 'app.py', [], { stopOnEntry: false }); + await vi.advanceTimersByTimeAsync(50); + stopShown = true; + proxy.simulateStopped(1, 'breakpoint', { reason: 'breakpoint', threadId: 1 }); + await vi.advanceTimersByTimeAsync(2000); + const answer = await started; + + expect(probe.fired()).toBe(true); + expect(answer.state).toBe(SessionState.PAUSED); + expect(answer.data?.reason).toBe('exception'); + expect(answer.data?.location).toMatchObject({ line: 50 }); + }); + + it('the exceptionInfo of one stop is never merged into the next stop\'s record, nor carried by its answer', async () => { + const sessionId = await runningSession(); + const proxy = dependencies.mockProxyManager; + proxy.simulateEvent('adapter-capabilities', { supportsExceptionInfoRequest: true }); + let answerA: ((value: unknown) => void) | undefined; + let current: 'A' | 'B' = 'A'; + proxy.setDapRequestHandler(async (name: string, args?: { threadId?: number }) => { + switch (name) { + case 'exceptionInfo': + if (args?.threadId === 1) { + // A's enrichment is held until stop B is current. + return new Promise((resolve) => { answerA = resolve; }); + } + return { success: true, body: { exceptionId: 'ValueError', breakMode: 'always', description: 'B details' } }; + case 'stackTrace': + return { success: true, body: { stackFrames: [current === 'A' ? FRAME_A : FRAME_B] } }; + case 'scopes': + return { success: true, body: { scopes: [] } }; + default: + return { success: true }; + } + }); + + proxy.simulateStopped(1, 'exception', { reason: 'exception', threadId: 1, description: 'A: KeyError' }); + await vi.advanceTimersByTimeAsync(5); + expect(answerA).toBeDefined(); + current = 'B'; + stopB(proxy); + await vi.advanceTimersByTimeAsync(5); + answerA!({ success: true, body: { exceptionId: 'KeyError', breakMode: 'always', description: 'A details' } }); + await vi.advanceTimersByTimeAsync(5); + + const answer = await sessionManager.waitForStop(sessionId, 2000); + expect(answer.data?.lastStop).toMatchObject({ reason: 'exception', threadId: 2, description: 'B: ValueError' }); + expect(answer.data?.lastStop?.exceptionInfo).toMatchObject({ exceptionId: 'ValueError', description: 'B details' }); + expect(JSON.stringify(answer.data)).not.toContain('A details'); + }); + + it('a hidden stop that lands during a read, after a resume, is never shown, and the pinned stop is not mixed with it', async () => { + const sessionId = await runningSession(); + const proxy = dependencies.mockProxyManager; + proxy.simulateStopped(1, 'breakpoint', { reason: 'breakpoint', threadId: 1 }); + await vi.advanceTimersByTimeAsync(20); + let fired = false; + proxy.setDapRequestHandler(async (name: string) => { + if (name === 'stackTrace' && !fired) { + fired = true; + // Another caller resumes the program, and the engine then reports an + // entry stop, which the core resumes without showing it. + void sessionManager.continue(sessionId); + proxy.simulateStopped(1, 'entry', { reason: 'entry', threadId: 1 }); + } + switch (name) { + case 'stackTrace': + return { success: true, body: { stackFrames: [FRAME_A] } }; + case 'scopes': + return { success: true, body: { scopes: [] } }; + default: + return { success: true }; + } + }); + + const answer = await sessionManager.waitForStop(sessionId, 200); + + expect(fired).toBe(true); + expect(answer.state).toBe(SessionState.RUNNING); + expect(answer.data?.pending).toBe(true); + expect(JSON.stringify(answer.data)).not.toContain('entry'); + // A's landing does not ride on the running answer. + expect(answer.data?.location).toBeUndefined(); + expect(answer.data?.lastStop).toBeUndefined(); + }); + + it('step_into: an origin read during which the program stopped somewhere else is not the step\'s origin', async () => { + const sessionId = await runningSession(); + const proxy = dependencies.mockProxyManager; + proxy.simulateStopped(1, 'breakpoint', { reason: 'breakpoint', threadId: 1 }); + await vi.advanceTimersByTimeAsync(20); + const FRAME_MAIN_12 = { ...FRAME_A, line: 12 }; + let originReads = 0; + let stepSent = false; + proxy.setDapRequestHandler(async (name: string) => { + switch (name) { + case 'stackTrace': + if (stepSent) return { success: true, body: { stackFrames: [FRAME_MAIN_12] } }; + originReads += 1; + if (originReads === 1) { + // The program stops in callee (thread 1) while A's stack is read. + proxy.simulateStopped(1, 'exception', { reason: 'exception', threadId: 1, description: 'B: ValueError' }); + return { success: true, body: { stackFrames: [FRAME_A] } }; + } + return { success: true, body: { stackFrames: [{ ...FRAME_B }, FRAME_A] } }; + case 'stepIn': + stepSent = true; + process.nextTick(() => proxy.simulateStopped(1, 'step', { reason: 'step', threadId: 1 })); + return { success: true }; + case 'scopes': + return { success: true, body: { scopes: [] } }; + default: + return { success: true }; + } + }); + + const pending = sessionManager.stepInto(sessionId); + await vi.advanceTimersByTimeAsync(100); + const answer = await pending; + + expect(originReads).toBe(1); + expect(answer.success).toBe(true); + expect(answer.data?.location).toMatchObject({ line: 12 }); + // A's frames, read before the step was sent from B, are not compared with + // the landing: no claim about the depth the step started from. + expect(answer.data?.note ?? '').not.toContain('same visible call-stack depth'); + }); + + describe('the answers of a restart and a reload in place', () => { + /** Both policy lookups: the facade's (the launcher and the live-update controller read it) and the store's (the core's). */ + function usePolicy(overrides: Partial) { + overridePolicy(sessionManager, overrides); + vi.spyOn(sessionManager as unknown as { selectPolicy: (l: string) => AdapterPolicy }, 'selectPolicy') + .mockReturnValue({ ...MockAdapterPolicy, ...overrides } as AdapterPolicy); + } + + it('restart_debugging as a hot restart: the stop the re-run lands on is described whole when it changes under the read', async () => { + usePolicy({ restartViaDapRequest: true }); + const sessionId = await runningSession(); + const proxy = dependencies.mockProxyManager; + proxy.simulateStopped(1, 'breakpoint', { reason: 'breakpoint', threadId: 1 }); + await vi.advanceTimersByTimeAsync(20); + proxy.emit('adapter-capabilities', { supportsRestartRequest: true }); + let restarted = false; + const probe = engineChangingIn(proxy, 'stackTrace', () => restarted, (name) => { + if (name !== 'restart') return undefined; + restarted = true; + return { success: true }; + }); + + const pending = sessionManager.restartDebugging(sessionId); + await vi.advanceTimersByTimeAsync(20); + expect(restarted).toBe(true); + // The re-run program reaches its breakpoint (A), and B lands during A's read. + proxy.simulateStopped(1, 'breakpoint', { reason: 'breakpoint', threadId: 1 }); + await vi.advanceTimersByTimeAsync(2000); + const answer = await pending; + + expect(probe.fired()).toBe(true); + expect(answer.state).toBe(SessionState.PAUSED); + const data = answer.data as Record; + expect(data.hotRestart).toBe(true); + expect(data.reason).toBe('exception'); + expect(data.location).toMatchObject({ line: 50 }); + expect(data.snapshot?.frames?.[0]).toMatchObject({ line: 50 }); + }); + + it('hot_reload: the stop the reassemble lands on is described whole when it changes under the read', async () => { + usePolicy({ liveUpdate: DartAdapterPolicy.liveUpdate }); + const sessionId = await runningSession(); + const proxy = dependencies.mockProxyManager; + proxy.emit('dap-event', 'flutter.appStart', { launchMode: 'run', supportsRestart: true }); + proxy.emit('dap-event', 'flutter.appStarted', {}); + let reloading = false; + const probe = engineChangingIn(proxy, 'stackTrace', () => reloading, (name) => { + if (name !== 'hotReload') return undefined; + reloading = true; + // Measured on web: the response waits for the paused isolate to resume. + return new Promise((resolve) => setTimeout(() => resolve({ success: true, body: {} }), 60_000)); + }); + + const pending = sessionManager.hotReload(sessionId, {}); + await vi.advanceTimersByTimeAsync(50); + proxy.simulateStopped(1, 'breakpoint', { reason: 'breakpoint', threadId: 1 }); + await vi.advanceTimersByTimeAsync(200); + const answer = await pending; + + expect(probe.fired()).toBe(true); + expect(answer.success).toBe(true); + expect(answer.state).toBe(SessionState.PAUSED); + const data = answer as unknown as Record; + expect(data.reason).toBe('exception'); + expect(data.location).toMatchObject({ line: 50 }); + await vi.runAllTimersAsync(); + }); + }); + + describe('a child\'s stop', () => { + function childEngine(view: MockProxyManager, armed: () => boolean) { + let current: 'A' | 'B' = 'A'; + let fired = false; + view.setDapRequestHandler(async (name: string) => { + const at = current; + if (name === 'stackTrace' && !fired && armed()) { + fired = true; + current = 'B'; + stopB(view); + } + switch (name) { + case 'stackTrace': + return { success: true, body: { stackFrames: [at === 'A' ? FRAME_A : FRAME_B] } }; + case 'scopes': + return { success: true, body: { scopes: [] } }; + default: + return { success: true, body: {} }; + } + }); + return { fired: () => fired }; + } + + it('read through its root\'s launch answer (pausedChild) describes one stop', async () => { + const root = await sessionManager.createSession({ language: DebugLanguage.MOCK }); + const starting = sessionManager.startDebugging(root.id, '/w/parent.py'); + await vi.advanceTimersByTimeAsync(20); + dependencies.mockProxyManager.simulateEvent('child-reported', report('r-paused', 5151)); + await vi.advanceTimersByTimeAsync(10); + const child = sessionManager.getAllSessions().find((s) => s.parentSessionId === root.id)!; + const view = dependencies.mockProxyManager.childViews.get(child.id)!; + let stopped = false; + const probe = childEngine(view, () => stopped); + stopped = true; + view.simulateStopped(1, 'breakpoint', { reason: 'breakpoint', threadId: 1 }); + await vi.runAllTimersAsync(); + const started = await starting; + + expect(probe.fired()).toBe(true); + expect(started.state).toBe(SessionState.RUNNING); + expect(started.data?.pausedChild).toMatchObject({ sessionId: child.id, reason: 'exception', location: { line: 50 } }); + expect(started.data?.message).toContain('is already paused (exception) at /w/app.py:50'); + }); + + it('chosen by the tree-aware wait describes one stop', async () => { + const root = await sessionManager.createSession({ language: DebugLanguage.MOCK }); + const started = sessionManager.startDebugging(root.id, 'test.py'); + await vi.runAllTimersAsync(); + await started; + dependencies.mockProxyManager.simulateEvent('child-reported', report('r1', 4242)); + await vi.runAllTimersAsync(); + const child = sessionManager.getAllSessions().find((s) => s.parentSessionId === root.id)!; + const view = dependencies.mockProxyManager.childViews.get(child.id)!; + const probe = childEngine(view, () => true); + view.simulateStopped(1, 'breakpoint', { reason: 'breakpoint', threadId: 1 }); + + const answer = await sessionManager.waitForStop(root.id, 2000); + + expect(probe.fired()).toBe(true); + expect(answer.data?.sessionId).toBe(child.id); + expect(answer.data?.lastStop).toMatchObject({ reason: 'exception', threadId: 2 }); + expect(answer.data?.location).toMatchObject({ line: 50 }); + }); + }); +}); diff --git a/tests/core/unit/session/session-manager-stop-pins.test.ts b/tests/core/unit/session/session-manager-stop-pins.test.ts new file mode 100644 index 000000000..3c1255df0 --- /dev/null +++ b/tests/core/unit/session/session-manager-stop-pins.test.ts @@ -0,0 +1,294 @@ +/** + * One answer, one stop (issue #1348 and its three siblings; tracking issue + * #1362, stage "stop record"). An answer that describes a stop pins that + * stop's identity before its first await and checks every read it makes + * against it. These cases make the stop change while the answer's landing + * read is in flight, by the engine reporting a second stop from inside that + * read, never by timing: + * + * - changed once: the answer's reads are made again for the stop now + * current, and every field of the answer describes that one stop; + * - changed twice: the answer gives the current stop's reason and state, no + * landing, and says that the stop changed while it was being read. + * + * Mock proxy, fake timers. Stop A is a breakpoint on thread 1 at main:11; + * stop B an exception on thread 2 at callee:50; stop C a breakpoint on + * thread 3 at other:70, so that each field of an answer names one of them. + */ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { SessionManager, SessionManagerConfig } from '../../../../src/session/session-manager.js'; +import { DebugLanguage, SessionState } from '@debugmcp/shared'; +import { createMockDependencies } from './session-manager-test-utils.js'; +import { ErrorMessages } from '../../../../src/utils/error-messages.js'; + +type StopName = 'A' | 'B' | 'C'; + +const FRAMES: Record = { + A: { id: 1, name: 'main', source: { path: '/w/app.py' }, line: 11, column: 0 }, + B: { id: 2, name: 'callee', source: { path: '/w/app.py' }, line: 50, column: 0 }, + C: { id: 3, name: 'other', source: { path: '/w/app.py' }, line: 70, column: 0 } +}; + +/** What the engine reports for each stop after A. */ +const NEXT_STOP: Record<'B' | 'C', { threadId: number; reason: string; description: string }> = { + B: { threadId: 2, reason: 'exception', description: 'B: ValueError' }, + C: { threadId: 3, reason: 'breakpoint', description: 'C: hit' } +}; + +describe('Stop pins: an answer read while the stop changes describes one stop', () => { + let sessionManager: SessionManager; + let dependencies: ReturnType; + + beforeEach(() => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + dependencies = createMockDependencies(); + const config: SessionManagerConfig = { + logDirBase: '/tmp/test-sessions', + defaultDapLaunchArgs: { stopOnEntry: false, justMyCode: true } + }; + sessionManager = new SessionManager(config, dependencies); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.clearAllMocks(); + dependencies.mockProxyManager.reset(); + }); + + async function runningSession(): Promise { + const session = await sessionManager.createSession({ language: DebugLanguage.MOCK, executablePath: 'python' }); + const started = sessionManager.startDebugging(session.id, 'app.py', [], { stopOnEntry: false }); + await vi.runAllTimersAsync(); + expect((await started).state).toBe(SessionState.RUNNING); + return session.id; + } + + /** + * The engine: a stackTrace answers with the frame of the stop that was + * current when the request arrived; while `armed()` says so, each of the + * stops in `then` is reported from inside one stackTrace request, in order + * (one per request). `extra` answers the other commands a case needs. + */ + function engine(armed: () => boolean, then: Array<'B' | 'C'>, extra?: (command: string) => unknown) { + let current: StopName = 'A'; + const queue = [...then]; + const reported: StopName[] = []; + let stackReads = 0; + const proxy = dependencies.mockProxyManager; + proxy.setDapRequestHandler(async (command: string) => { + const answered = extra?.(command); + if (answered !== undefined) return answered; + if (command === 'stackTrace') { + const at = current; + if (armed()) stackReads += 1; + if (armed() && queue.length > 0) { + const next = queue.shift()!; + current = next; + reported.push(next); + const { threadId, reason, description } = NEXT_STOP[next]; + proxy.simulateStopped(threadId, reason, { reason, threadId, description }); + } + return { success: true, body: { stackFrames: [FRAMES[at]] } }; + } + if (command === 'threads') { + return { success: true, body: { threads: [{ id: 1, name: 'main' }, { id: 2, name: 'worker' }, { id: 3, name: 'third' }] } }; + } + if (command === 'scopes') return { success: true, body: { scopes: [] } }; + return { success: true }; + }); + return { reported: () => [...reported], stackReads: () => stackReads }; + } + + /** + * The answer describes stop B and nothing else: its location, its reason + * (or record), and its snapshot: B's top frame and, where the answer + * carries the exception in the snapshot, B's exception. + */ + function expectDescribes( + data: Record | undefined, + stop: 'B', + reasonField: 'stopReason' | 'reason' | 'lastStop' + ): void { + expect(data?.location).toMatchObject({ line: FRAMES[stop].line }); + if (reasonField === 'lastStop') { + expect(data?.lastStop).toMatchObject({ reason: NEXT_STOP[stop].reason, threadId: NEXT_STOP[stop].threadId, description: NEXT_STOP[stop].description }); + expect(data?.snapshot?.exception).toBeUndefined(); + } else { + expect(data?.[reasonField]).toBe(NEXT_STOP[stop].reason); + expect(data?.snapshot?.exception).toMatchObject({ type: NEXT_STOP[stop].description }); + } + expect(data?.snapshot).toBeDefined(); + expect(data?.snapshot?.frames?.[0]).toMatchObject({ line: FRAMES[stop].line }); + } + + /** The current stop (C), no landing and no snapshot, and the sentence. */ + function expectChangedTwice(data: Record | undefined): void { + expect(data?.location).toBeUndefined(); + expect(data?.threadId).toBeUndefined(); + expect(data?.snapshot).toBeUndefined(); + expect(data?.note).toBe(ErrorMessages.stopChangedWhileRead()); + } + + describe('wait_for_stop (#1348)', () => { + it('changed once: location, record and message all describe the stop now current', async () => { + const sessionId = await runningSession(); + dependencies.mockProxyManager.simulateStopped(1, 'breakpoint', { reason: 'breakpoint', threadId: 1 }); + const probe = engine(() => true, ['B']); + + const answer = await sessionManager.waitForStop(sessionId, 2000); + + expect(probe.reported()).toEqual(['B']); + expect(answer.state).toBe(SessionState.PAUSED); + expectDescribes(answer.data as Record, 'B', 'lastStop'); + expect(answer.data?.message).toMatch(/Paused \(exception\) at \/w\/app\.py:50/); + }); + + it('changed twice: the current stop, no landing, and the sentence', async () => { + const sessionId = await runningSession(); + dependencies.mockProxyManager.simulateStopped(1, 'breakpoint', { reason: 'breakpoint', threadId: 1 }); + const probe = engine(() => true, ['B', 'C']); + + const answer = await sessionManager.waitForStop(sessionId, 2000); + + expect(probe.reported()).toEqual(['B', 'C']); + expect(answer.state).toBe(SessionState.PAUSED); + const data = answer.data as Record; + expectChangedTwice(data); + expect(data.lastStop).toMatchObject({ reason: 'breakpoint', threadId: 3, description: 'C: hit' }); + expect(data.message).toBe('Paused (breakpoint)'); + }); + }); + + describe('step_over', () => { + async function pausedAtA(): Promise { + const sessionId = await runningSession(); + dependencies.mockProxyManager.simulateStopped(1, 'breakpoint', { reason: 'breakpoint', threadId: 1 }); + await vi.advanceTimersByTimeAsync(20); + return sessionId; + } + + function stepEngine(then: Array<'B' | 'C'>) { + let stepSent = false; + const proxy = dependencies.mockProxyManager; + const probe = engine(() => stepSent, then, (command) => { + if (command === 'next') { + stepSent = true; + process.nextTick(() => proxy.simulateStopped(1, 'step', { reason: 'step', threadId: 1 })); + return { success: true }; + } + return undefined; + }); + return probe; + } + + it('changed once: the location and the reason are the same stop\'s', async () => { + const sessionId = await pausedAtA(); + const probe = stepEngine(['B']); + + const pending = sessionManager.stepOver(sessionId); + await vi.advanceTimersByTimeAsync(100); + const answer = await pending; + + expect(probe.reported()).toEqual(['B']); + expect(answer.success).toBe(true); + expectDescribes(answer.data as Record, 'B', 'stopReason'); + // One reader owns the answer: the landing read and its one re-read. B's + // own stopped event starts no second reader racing the first. + expect(probe.stackReads()).toBe(2); + // B is not on the line the step left from: no lost-step signature. + expect(answer.data?.message).toBe("Stepped over; stopped on 'exception' rather than on the step itself (see stopReason)."); + }); + + it('changed twice: the current stop, no landing, and the sentence', async () => { + const sessionId = await pausedAtA(); + const probe = stepEngine(['B', 'C']); + + const pending = sessionManager.stepOver(sessionId); + await vi.advanceTimersByTimeAsync(100); + const answer = await pending; + + expect(probe.reported()).toEqual(['B', 'C']); + expect(probe.stackReads()).toBe(2); + expect(answer.success).toBe(true); + expect(answer.state).toBe(SessionState.PAUSED); + expectChangedTwice(answer.data as Record); + expect(answer.data?.stopReason).toBe('breakpoint'); + expect(answer.data?.message).toBe("Stepped over; stopped on 'breakpoint' rather than on the step itself (see stopReason)."); + }); + }); + + describe('pause_execution', () => { + function pauseEngine(then: Array<'B' | 'C'>) { + let pauseSent = false; + const proxy = dependencies.mockProxyManager; + return engine(() => pauseSent, then, (command) => { + if (command === 'pause') { + pauseSent = true; + process.nextTick(() => proxy.simulateStopped(1, 'pause', { reason: 'pause', threadId: 1 })); + return { success: true }; + } + return undefined; + }); + } + + it('changed once: the location and the reason are the same stop\'s', async () => { + const sessionId = await runningSession(); + const probe = pauseEngine(['B']); + + const pending = sessionManager.pause(sessionId, 1); + await vi.advanceTimersByTimeAsync(100); + const answer = await pending; + + expect(probe.reported()).toEqual(['B']); + expect(answer.success).toBe(true); + expectDescribes(answer.data as Record, 'B', 'stopReason'); + }); + + it('changed twice: the current stop, no landing, and the sentence', async () => { + const sessionId = await runningSession(); + const probe = pauseEngine(['B', 'C']); + + const pending = sessionManager.pause(sessionId, 1); + await vi.advanceTimersByTimeAsync(100); + const answer = await pending; + + expect(probe.reported()).toEqual(['B', 'C']); + expect(answer.state).toBe(SessionState.PAUSED); + expectChangedTwice(answer.data as Record); + expect(answer.data?.stopReason).toBe('breakpoint'); + expect(answer.data?.message).toBe('Paused'); + }); + }); + + describe('start_debugging', () => { + async function launchStoppingAtA(then: Array<'B' | 'C'>) { + const session = await sessionManager.createSession({ language: DebugLanguage.MOCK, executablePath: 'python' }); + let stopShown = false; + const probe = engine(() => stopShown, then); + const started = sessionManager.startDebugging(session.id, 'app.py', [], { stopOnEntry: false }); + // The program reaches a breakpoint inside the launch hold. + await vi.advanceTimersByTimeAsync(50); + stopShown = true; + dependencies.mockProxyManager.simulateStopped(1, 'breakpoint', { reason: 'breakpoint', threadId: 1 }); + await vi.advanceTimersByTimeAsync(2000); + return { answer: await started, probe }; + } + + it('changed once: the location and the reason are the same stop\'s', async () => { + const { answer, probe } = await launchStoppingAtA(['B']); + + expect(probe.reported()).toEqual(['B']); + expect(answer.state).toBe(SessionState.PAUSED); + expectDescribes(answer.data as Record, 'B', 'reason'); + }); + + it('changed twice: the current stop, no landing, and the sentence', async () => { + const { answer, probe } = await launchStoppingAtA(['B', 'C']); + + expect(probe.reported()).toEqual(['B', 'C']); + expect(answer.state).toBe(SessionState.PAUSED); + expectChangedTwice(answer.data as Record); + expect((answer.data as Record).reason).toBe('breakpoint'); + }); + }); +}); diff --git a/tests/core/unit/session/session-state-shadow.test.ts b/tests/core/unit/session/session-state-shadow.test.ts index 88909a28d..f0ed1230a 100644 --- a/tests/core/unit/session/session-state-shadow.test.ts +++ b/tests/core/unit/session/session-state-shadow.test.ts @@ -14,6 +14,7 @@ import type { ManagedSession } from '../../../../src/session/session-store.js'; import { createMockDependencies } from './session-manager-test-utils.js'; import { internals } from '../../../test-utils/helpers/operations-internals.js'; import { setSessionStateForTest } from '../../../test-utils/helpers/session-state.js'; +import { setStopForTest } from '../../../test-utils/helpers/stop-record.js'; const CONFIG: SessionManagerConfig = { logDirBase: '/tmp/test-sessions', defaultDapLaunchArgs: { stopOnEntry: false, justMyCode: true } }; @@ -430,14 +431,13 @@ describe('the transition table shadow, through the session manager', () => { (sessionManager as unknown as { _updateSessionState: (s: ManagedSession, next: SessionState, write: StateWrite) => void }) ._updateSessionState(s, next, write); gate(SessionState.INITIALIZING, { site: 'launch', event: 'start' }); - const shown = { reason: 'breakpoint', threadId: 1, timestamp: 1 }; - s.lastStop = shown; + setStopForTest(s, { reason: 'breakpoint', threadId: 1, timestamp: 1 }); gate(SessionState.PAUSED, { site: 'settleStop.shown', event: 'stop-shown' }); const token = shadowOf(sessionManager).token(s); gate(SessionState.RUNNING, { site: 'executeStep.sent', event: 'resume' }); // When the refusal writes PAUSED, a listener moves the record to another stop. internals(sessionManager).opsContext.onStateChange(s.id, () => { - if (s.state === SessionState.PAUSED) s.lastStop = { reason: 'exception', threadId: 2, timestamp: 2 }; + if (s.state === SessionState.PAUSED) setStopForTest(s, { reason: 'exception', threadId: 2, timestamp: 2 }); }); const added = await delta(shadowOf(sessionManager), () => gate(SessionState.PAUSED, { site: 'executeStep.refused', event: 'resume-refused', facts: { since: token } })); diff --git a/tests/core/unit/session/stop-record-writes.test.ts b/tests/core/unit/session/stop-record-writes.test.ts new file mode 100644 index 000000000..e16c6e4e1 --- /dev/null +++ b/tests/core/unit/session/stop-record-writes.test.ts @@ -0,0 +1,207 @@ +/** + * One record per stop (tracking issue #1362, stage "stop record"): every + * write of a session's stop goes through src/session/stop-record.ts, which + * mints the record with it, and no shipped code compares two stops by the + * identity of their objects. Read from the sources of src/ and + * packages//src with the TypeScript parser. + * + * What the scan sees, by name: + * - a plain `=` assignment to `.lastStop`, `.stopRecord` or `.lastShownStop` + * on any receiver but `this` (the proxy worker keeps a `lastStop` of its + * own, the raw DAP body, on `this`). The writes of those names that are not + * a session's are listed below by file, receiver and field: an answer + * object carrying the emitted copy, and the transition shadow's own + * bookkeeping. A new one fails until it is named there; + * - a call of `update`/`updateSession` whose object literal has one of those + * keys; + * - an `===`/`!==` comparison with a `.lastStop` member access on either side + * (other than against `undefined` or `null`), and the same comparison of a + * `stopRef` (the provenance and diff-base field this stage removed); + * - a call of the two stop readers, `describeStopLocation` and + * `composeStopSnapshot`, whose `pin` is optional for their own tests: in + * shipped code they are called by the pinned read, and the step's snapshot + * with a `pin` key, and nowhere else, so an answer that reads a landing + * without a pin fails here. + * What it cannot see: a write through an alias, a bracket access + * (`s['lastStop'] = …`), a compound or destructuring assignment, an object + * spread or `Object.assign`, a write by key (`Reflect.set`), an identity + * comparison of a `lastStop` value first copied into a local (`const a = + * s.lastStop; … a === b`), `Object.is`, a `Map`/`WeakMap`/`Set` keyed by the + * object, a stop reader called through an alias or a re-export, a stack read + * that bypasses the two readers (`getStackTraceDetailed` called directly by + * a new answer), and anything outside the shipped sources (tests write + * around it: `setStopForTest` is their way in). + */ +import { describe, it, expect } from 'vitest'; +import { existsSync, readFileSync, readdirSync, statSync } from 'fs'; +import path from 'path'; +import ts from 'typescript'; + +const ROOT = path.resolve(__dirname, '../../../..'); +const STOP_FIELDS = new Set(['lastStop', 'stopRecord', 'lastShownStop']); +const OWNER = 'src/session/stop-record.ts'; + +/** Writes of those names whose receiver is not a session, as `file receiver.field`. */ +const NOT_A_SESSION = [ + 'src/server/handlers/execution-tools.ts response.lastStop', // the wait_for_stop answer's emitted copy + 'src/server/handlers/session-tools.ts mappedSession.lastStop', // a list_debug_sessions row's emitted copy + 'src/session/machine/shadow.ts state.lastShownStop' // the shadow's own record of the last shown stop (twice) +]; + +function sourceFiles(dir: string): string[] { + const out: string[] = []; + for (const name of readdirSync(dir)) { + const full = path.join(dir, name); + if (statSync(full).isDirectory()) { + if (name !== 'node_modules' && name !== 'dist') out.push(...sourceFiles(full)); + } else if (full.endsWith('.ts') && !full.endsWith('.d.ts')) { + out.push(full); + } + } + return out; +} + +function shippedSources(): string[] { + const files = sourceFiles(path.join(ROOT, 'src')); + for (const name of readdirSync(path.join(ROOT, 'packages'))) { + const src = path.join(ROOT, 'packages', name, 'src'); + if (statSync(path.join(ROOT, 'packages', name)).isDirectory() && existsSync(src)) { + files.push(...sourceFiles(src)); + } + } + return files; +} + +function isNullish(node: ts.Expression): boolean { + return node.kind === ts.SyntaxKind.NullKeyword || (ts.isIdentifier(node) && node.text === 'undefined'); +} + +function memberNamed(node: ts.Expression, names: ReadonlySet): boolean { + let inner: ts.Expression = node; + while (ts.isParenthesizedExpression(inner) || ts.isNonNullExpression(inner)) inner = inner.expression; + return ts.isPropertyAccessExpression(inner) && names.has(inner.name.text); +} + +interface Scan { + /** Calls of the stop readers, as `file name pin|no-pin`. */ + readerCalls: string[]; + writes: string[]; + /** The writes listed in NOT_A_SESSION, as found. */ + named: string[]; + patches: string[]; + identityComparisons: string[]; +} + +function scanSource(relative: string, text: string): Scan { + const scan: Scan = { readerCalls: [], writes: [], named: [], patches: [], identityComparisons: [] }; + const source = ts.createSourceFile(relative, text, ts.ScriptTarget.Latest, true); + const where = (node: ts.Node) => `${relative}:${source.getLineAndCharacterOfPosition(node.getStart()).line + 1}`; + const visit = (node: ts.Node): void => { + if ( + ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken && + ts.isPropertyAccessExpression(node.left) && STOP_FIELDS.has(node.left.name.text) && + node.left.expression.kind !== ts.SyntaxKind.ThisKeyword + ) { + const named = `${relative} ${node.left.expression.getText(source)}.${node.left.name.text}`; + if (!NOT_A_SESSION.includes(named)) { + scan.writes.push(where(node)); + } else { + scan.named.push(named); + } + } + if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && + ['describeStopLocation', 'composeStopSnapshot'].includes(node.expression.text)) { + const pinned = node.arguments.some((argument) => ts.isIdentifier(argument) && argument.text === 'under') || + node.arguments.some((argument) => ts.isObjectLiteralExpression(argument) && argument.properties.some((property) => + (ts.isPropertyAssignment(property) || ts.isShorthandPropertyAssignment(property)) && + ts.isIdentifier(property.name) && property.name.text === 'pin')); + scan.readerCalls.push(`${relative} ${node.expression.text} ${pinned ? 'pin' : 'no-pin'}`); + } + if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && + ['update', 'updateSession'].includes(node.expression.name.text) && + node.arguments.some((argument) => ts.isObjectLiteralExpression(argument) && argument.properties.some((property) => + (ts.isPropertyAssignment(property) || ts.isShorthandPropertyAssignment(property)) && + ts.isIdentifier(property.name) && STOP_FIELDS.has(property.name.text)))) { + scan.patches.push(where(node)); + } + if (ts.isBinaryExpression(node) && [ + ts.SyntaxKind.EqualsEqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsEqualsToken, + ts.SyntaxKind.EqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsToken + ].includes(node.operatorToken.kind)) { + const sides = [node.left, node.right]; + const compared = new Set(['lastStop', 'stopRef']); + if (sides.some((side) => memberNamed(side, compared)) && !sides.some(isNullish)) { + scan.identityComparisons.push(where(node)); + } + } + ts.forEachChild(node, visit); + }; + visit(source); + return scan; +} + +function scanAll(): Scan { + const all: Scan = { readerCalls: [], writes: [], named: [], patches: [], identityComparisons: [] }; + for (const file of shippedSources()) { + const relative = path.relative(ROOT, file).split(path.sep).join('/'); + const one = scanSource(relative, readFileSync(file, 'utf8')); + if (relative !== OWNER) { + all.writes.push(...one.writes); + all.patches.push(...one.patches); + } + all.named.push(...one.named); + all.readerCalls.push(...one.readerCalls); + all.identityComparisons.push(...one.identityComparisons); + } + return all; +} + +describe('the stop record is the one writer of a session\'s stop', () => { + const found = scanAll(); + + it('no shipped code outside stop-record.ts assigns lastStop, stopRecord or lastShownStop on a session', () => { + expect(found.writes).toEqual([]); + }); + + it('every write of those names that is not a session\'s is still where it is listed', () => { + expect([...new Set(found.named)].sort()).toEqual([...NOT_A_SESSION].sort()); + }); + + it('no shipped code patches them in through update or updateSession', () => { + expect(found.patches).toEqual([]); + }); + + it('compares stops by record id: the one object comparison is the record holding its own info', () => { + expect(found.identityComparisons.filter((at) => !at.startsWith(`${OWNER}:`))).toEqual([]); + expect(found.identityComparisons.filter((at) => at.startsWith(`${OWNER}:`))).toHaveLength(1); + }); + + it('the stop readers are called by the pinned read and the step\'s snapshot, each with its pin, and nowhere else', () => { + expect([...found.readerCalls].sort()).toEqual([ + 'src/session/execution/execution-controller.ts composeStopSnapshot pin', + 'src/session/inspection/pinned-stop-read.ts composeStopSnapshot pin', + 'src/session/inspection/pinned-stop-read.ts describeStopLocation pin' + ]); + }); + + it('sees the forms it claims to see', () => { + const probe = scanSource('probe.ts', [ + 'session.lastStop = x;', + 'other.stopRecord = y;', + 'a.b.lastShownStop = z;', + 'this.lastStop = w;', + 'store.update(id, { lastStop: v });', + 'if (s.lastStop === before) {}', + 'if (before !== s.lastStop) {}', + 'if (p.stopRef === q) {}', + 'if (s.lastStop !== undefined) {}', + 'if (s.lastStop === null) {}', + 'describeStopLocation(ctx, id, tag);', + 'composeStopSnapshot(ctx, id, stack, tag, { pin });' + ].join('\n')); + expect(probe.writes).toEqual(['probe.ts:1', 'probe.ts:2', 'probe.ts:3']); + expect(probe.patches).toEqual(['probe.ts:5']); + expect(probe.identityComparisons).toEqual(['probe.ts:6', 'probe.ts:7', 'probe.ts:8']); + expect(probe.readerCalls).toEqual(['probe.ts describeStopLocation no-pin', 'probe.ts composeStopSnapshot pin']); + }); +}); diff --git a/tests/core/unit/session/stop-record.test.ts b/tests/core/unit/session/stop-record.test.ts new file mode 100644 index 000000000..4c5b375d3 --- /dev/null +++ b/tests/core/unit/session/stop-record.test.ts @@ -0,0 +1,209 @@ +/** + * One record per stop (tracking issue #1362, stage "stop record"): the record + * a stop gets when the core applies it, the readings of it, the pin rules, + * and the operation in flight a stop names as its cause. + */ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { DebugLanguage, SessionState } from '@debugmcp/shared'; +import { + applyStop, + currentStopOf, + eraseHiddenStop, + pinBroken, + pinHolds, + pinStop, + resetStops, + stopIdOf, + stopRecordOf, + type StopHolder +} from '../../../../src/session/stop-record.js'; +import { SessionManager, SessionManagerConfig } from '../../../../src/session/session-manager.js'; +import { createMockDependencies } from './session-manager-test-utils.js'; + +function holder(state: SessionState = SessionState.PAUSED): StopHolder & { state: SessionState } { + return { id: 's1', state, proxyGeneration: 3 }; +} + +describe('the stop record', () => { + it('a stop gets a record with an id, its run, session, thread, reason and visibility; lastStop is its info', () => { + const session = holder(); + const info = { reason: 'breakpoint', threadId: 7, timestamp: 1 }; + const record = applyStop(session, info, { shown: true }); + + expect(record).toMatchObject({ runId: 3, sessionId: 's1', threadId: 7, reason: 'breakpoint', shown: true }); + expect(record.seq).toBeUndefined(); + expect(record.info).toBe(info); + expect(session.lastStop).toBe(info); + expect(stopRecordOf(session)).toBe(record); + expect(session.lastShownStop).toBe(record); + }); + + it('ids are never reused: every stop applied gets a new one, the same info applied twice included', () => { + const session = holder(); + const info = { reason: 'step', timestamp: 1 }; + const first = applyStop(session, info, { shown: true }); + const second = applyStop(session, info, { shown: true }); + expect(second.id).toBeGreaterThan(first.id); + expect(stopIdOf(session)).toBe(second.id); + }); + + it('a hidden stop is not the last shown, and erasing it keeps a newer stop that raced its resume', () => { + const session = holder(); + const shown = applyStop(session, { reason: 'breakpoint', timestamp: 1 }, { shown: true }); + const hidden = applyStop(session, { reason: 'entry', timestamp: 2 }, { shown: false }); + expect(session.lastShownStop).toBe(shown); + expect(stopRecordOf(session)).toBe(hidden); + + const newer = applyStop(session, { reason: 'exception', timestamp: 3 }, { shown: true }); + expect(eraseHiddenStop(session, hidden)).toBe(false); + expect(stopRecordOf(session)).toBe(newer); + + const again = applyStop(session, { reason: 'entry', timestamp: 4 }, { shown: false }); + expect(eraseHiddenStop(session, again)).toBe(true); + expect(session.lastStop).toBeUndefined(); + expect(stopRecordOf(session)).toBeUndefined(); + expect(session.lastShownStop).toBe(newer); + }); + + it('a run starts with nothing recorded and nothing shown', () => { + const session = holder(); + applyStop(session, { reason: 'breakpoint', timestamp: 1 }, { shown: true }); + resetStops(session); + expect(session.lastStop).toBeUndefined(); + expect(session.stopRecord).toBeUndefined(); + expect(session.lastShownStop).toBeUndefined(); + }); + + it('a lastStop written around the module has no record, and the record left behind is not read as its', () => { + const session = holder(); + applyStop(session, { reason: 'breakpoint', timestamp: 1 }, { shown: true }); + session.lastStop = { reason: 'exception', timestamp: 2 }; + expect(stopRecordOf(session)).toBeUndefined(); + expect(stopIdOf(session)).toBeUndefined(); + }); + + it('the stop the session is at is its record while paused, and none otherwise', () => { + const session = holder(SessionState.RUNNING); + const record = applyStop(session, { reason: 'breakpoint', timestamp: 1 }, { shown: true }); + expect(currentStopOf(session)).toBeUndefined(); + session.state = SessionState.PAUSED; + expect(currentStopOf(session)).toBe(record); + }); +}); + +describe('the pin rules', () => { + it('a pin holds while the session records the pinned stop, and breaks on another while paused', () => { + const session = holder(); + applyStop(session, { reason: 'breakpoint', timestamp: 1 }, { shown: true }); + const pin = pinStop(session); + expect(pinHolds(session, pin)).toBe(true); + expect(pinBroken(session, pin)).toBe(false); + + applyStop(session, { reason: 'exception', timestamp: 2 }, { shown: true }); + expect(pinHolds(session, pin)).toBe(false); + expect(pinBroken(session, pin)).toBe(true); + }); + + it('a session that is not paused, or gone, never asks for the reads to be made again', () => { + const session = holder(SessionState.RUNNING); + applyStop(session, { reason: 'breakpoint', timestamp: 1 }, { shown: true }); + const pin = pinStop(session); + applyStop(session, { reason: 'exception', timestamp: 2 }, { shown: true }); + expect(pinBroken(session, pin)).toBe(false); + expect(pinBroken(undefined, pin)).toBe(false); + }); + + it('holding fails closed without a record; breaking treats "no record" as a value of its own', () => { + const session = holder(); + const empty = pinStop(session); + expect(empty.stop).toBeUndefined(); + expect(pinHolds(session, empty)).toBe(false); + expect(pinBroken(session, empty)).toBe(false); + + applyStop(session, { reason: 'breakpoint', timestamp: 1 }, { shown: true }); + expect(pinBroken(session, empty)).toBe(true); + + const pinned = pinStop(session); + session.lastStop = { reason: 'written around', timestamp: 2 }; + expect(pinHolds(session, pinned)).toBe(false); + expect(pinBroken(session, pinned)).toBe(true); + }); +}); + +describe('a stop names the operation in flight that it answers', () => { + let sessionManager: SessionManager; + let dependencies: ReturnType; + + beforeEach(() => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + dependencies = createMockDependencies(); + const config: SessionManagerConfig = { + logDirBase: '/tmp/test-sessions', + defaultDapLaunchArgs: { stopOnEntry: false, justMyCode: true } + }; + sessionManager = new SessionManager(config, dependencies); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.clearAllMocks(); + dependencies.mockProxyManager.reset(); + }); + + async function runningSession(): Promise { + const session = await sessionManager.createSession({ language: DebugLanguage.MOCK, executablePath: 'python' }); + const started = sessionManager.startDebugging(session.id, 'test.py', [], { stopOnEntry: false }); + await vi.runAllTimersAsync(); + expect((await started).state).toBe(SessionState.RUNNING); + return session.id; + } + + it('a step\'s stop names the step, by the id the step was sent with', async () => { + const sessionId = await runningSession(); + dependencies.mockProxyManager.simulateStopped(1, 'breakpoint'); + await vi.advanceTimersByTimeAsync(20); + const session = sessionManager.getSession(sessionId)!; + expect(stopRecordOf(session)?.cause).toBeUndefined(); + + let stepId: number | undefined; + const proxy = dependencies.mockProxyManager; + const original = proxy.sendDapRequest.bind(proxy); + vi.spyOn(proxy, 'sendDapRequest').mockImplementation((command, args, options) => { + if (command === 'next') stepId = session.inFlightStep?.id; + return original(command, args, options); + }); + const stepped = sessionManager.stepOver(sessionId); + await vi.advanceTimersByTimeAsync(50); + await stepped; + + expect(stepId).toBeDefined(); + expect(stopRecordOf(session)).toMatchObject({ reason: 'step', shown: true, cause: { kind: 'step', id: stepId, threadId: 1 } }); + expect(session.lastStepProvenance?.stopId).toBe(stopIdOf(session)); + }); + + it('a pause\'s stop names the pause, and a later stop with nothing in flight names none', async () => { + const sessionId = await runningSession(); + const proxy = dependencies.mockProxyManager; + let intentId: number | undefined; + proxy.setDapRequestHandler(async (command: string) => { + if (command === 'pause') { + intentId = sessionManager.getSession(sessionId)?.pauseIntent?.id; + process.nextTick(() => proxy.simulateStopped(1, 'pause', { reason: 'pause', threadId: 1 })); + } + if (command === 'stackTrace') { + return { success: true, body: { stackFrames: [{ id: 1, name: 'main', source: { path: '/w/app.py' }, line: 3, column: 0 }] } }; + } + return { success: true }; + }); + const paused = sessionManager.pause(sessionId, 1); + await vi.advanceTimersByTimeAsync(50); + await paused; + const session = sessionManager.getSession(sessionId)!; + + expect(intentId).toBeDefined(); + expect(stopRecordOf(session)).toMatchObject({ reason: 'pause', cause: { kind: 'pause', id: intentId, threadId: 1 } }); + + proxy.simulateStopped(1, 'breakpoint', { reason: 'breakpoint', threadId: 1 }); + expect(stopRecordOf(session)?.cause).toBeUndefined(); + }); +}); diff --git a/tests/test-utils/helpers/stop-record.ts b/tests/test-utils/helpers/stop-record.ts new file mode 100644 index 000000000..979e301b5 --- /dev/null +++ b/tests/test-utils/helpers/stop-record.ts @@ -0,0 +1,23 @@ +import type { SessionStopInfo } from '@debugmcp/shared'; +import { applyStop, type OperationRef, type StopHolder, type StopRecord } from '../../../src/session/stop-record.js'; + +/** + * Gives a test session a stop the way the core applies one (tracking issue + * #1362, stage "stop record"): a record with an id of its own, and + * `lastStop` set to its info. A test that assigns `lastStop` itself writes + * around the record, and every comparison of stops (the pins, the snapshot's + * check, the resolver's gate, the shadow's guards) then reads that session + * as having no record. Runs no gate, shadow or listener, like + * `setSessionStateForTest`. + */ +export function setStopForTest( + session: StopHolder, + info: Partial & { reason: string }, + opts: { shown?: boolean; cause?: OperationRef } = {} +): StopRecord { + // A complete stop is recorded as the very object given, as the core records its own. + const complete: SessionStopInfo = typeof info.timestamp === 'number' + ? info as SessionStopInfo + : { timestamp: Date.now(), ...info }; + return applyStop(session, complete, { shown: opts.shown ?? true, ...(opts.cause ? { cause: opts.cause } : {}) }); +} diff --git a/tests/unit/session-manager-operations-coverage.test.ts b/tests/unit/session-manager-operations-coverage.test.ts index 4fcc04be1..a00c6ef64 100644 --- a/tests/unit/session-manager-operations-coverage.test.ts +++ b/tests/unit/session-manager-operations-coverage.test.ts @@ -52,6 +52,7 @@ import { import { FakeDebugAdapter } from '../test-utils/fakes/fake-debug-adapter'; import { internals } from '../test-utils/helpers/operations-internals'; import { setSessionStateForTest } from '../test-utils/helpers/session-state.js'; +import { setStopForTest } from '../test-utils/helpers/stop-record.js'; /** * The landing read is the resolver's detailed result (issue #904); these @@ -209,7 +210,7 @@ describe('Session Manager Operations Coverage - Error Paths and Edge Cases', () */ function moveSessionTo(state: SessionState, lastStop?: ManagedSession['lastStop']): void { if (lastStop) { - mockSession.lastStop = lastStop; + setStopForTest(mockSession, lastStop); } internals(operations).opsContext.updateState(mockSession, state, TEST_SETUP_WRITE); } @@ -511,7 +512,7 @@ describe('Session Manager Operations Coverage - Error Paths and Edge Cases', () it('should handle continue request failure', async () => { setSessionStateForTest(mockSession, SessionState.PAUSED); - mockSession.lastStop = { reason: 'breakpoint', threadId: 1, timestamp: Date.now() }; + setStopForTest(mockSession, { reason: 'breakpoint', threadId: 1, timestamp: Date.now() }); mockProxyManager.sendDapRequest.mockRejectedValue(new Error('Network error')); await expect(operations.continue('test-session')) @@ -2984,7 +2985,7 @@ describe('Session Manager Operations Coverage - Error Paths and Edge Cases', () const pausedSession = () => { mockSession.proxyManager = mockProxyManager; setSessionStateForTest(mockSession, SessionState.PAUSED); - mockSession.lastStop = { reason: 'pause' } as ManagedSession['lastStop']; + setStopForTest(mockSession, { reason: 'pause' }); mockProxyManager.getCurrentThreadId.mockReturnValue(1); }; @@ -3129,7 +3130,7 @@ describe('Session Manager Operations Coverage - Error Paths and Edge Cases', () } if (command === 'pause') { // The core listener is registered before the coordinator listener. - mockSession.lastStop = { reason: 'pause', threadId: 1, timestamp: Date.now() }; + setStopForTest(mockSession, { reason: 'pause', threadId: 1, timestamp: Date.now() }); setSessionStateForTest(mockSession, SessionState.PAUSED); stopped?.(); } @@ -4399,7 +4400,7 @@ describe('Session Manager Operations Coverage - Error Paths and Edge Cases', () }); // Emulate core handleStopped recording a normalized stop before the // operations-level listener observes the event. - mockSession.lastStop = { reason: 'pause', rawReason: 'exception', threadId: 1, timestamp: Date.now() }; + setStopForTest(mockSession, { reason: 'pause', rawReason: 'exception', threadId: 1, timestamp: Date.now() }); emitStopped(); const result = await promise; @@ -4410,7 +4411,7 @@ describe('Session Manager Operations Coverage - Error Paths and Edge Cases', () it('does not echo a stale stop recorded before the pause was requested', async () => { setSessionStateForTest(mockSession, SessionState.RUNNING); - mockSession.lastStop = { reason: 'breakpoint', threadId: 1, timestamp: Date.now() - 1000 }; + setStopForTest(mockSession, { reason: 'breakpoint', threadId: 1, timestamp: Date.now() - 1000 }); mockProxyManager.sendDapRequest.mockResolvedValue({}); const promise = operations.pause('test-session', 1); @@ -4473,7 +4474,7 @@ describe('Session Manager Operations Coverage - Error Paths and Edge Cases', () it('includes the last stop reason when already paused', async () => { setSessionStateForTest(mockSession, SessionState.PAUSED); - mockSession.lastStop = { reason: 'breakpoint', threadId: 1, timestamp: Date.now() }; + setStopForTest(mockSession, { reason: 'breakpoint', threadId: 1, timestamp: Date.now() }); const result = await operations.pause('test-session'); @@ -4575,7 +4576,7 @@ describe('Session Manager Operations Coverage - Error Paths and Edge Cases', () mockProxyManager.sendDapRequest.mockImplementation((command: string) => { if (command === 'threads') { setSessionStateForTest(mockSession, SessionState.PAUSED); - mockSession.lastStop = raceStop; + setStopForTest(mockSession, raceStop); return Promise.resolve({ body: { threads: [{ id: 3, name: 'Main' }] } }); } return Promise.resolve({}); @@ -4603,7 +4604,7 @@ describe('Session Manager Operations Coverage - Error Paths and Edge Cases', () mockProxyManager.sendDapRequest.mockImplementation((command: string) => { if (command === 'threads') { setSessionStateForTest(mockSession, SessionState.PAUSED); - mockSession.lastStop = raceStop; + setStopForTest(mockSession, raceStop); return Promise.resolve({ body: { threads: [{ id: 3, name: 'Main' }] } }); } return Promise.reject(new Error('Cannot pause: process is already stopped')); @@ -4635,7 +4636,7 @@ describe('Session Manager Operations Coverage - Error Paths and Edge Cases', () // The stop lands during discovery: state flips and handleStopped // records it before the listeners below are ever registered. setSessionStateForTest(mockSession, SessionState.PAUSED); - mockSession.lastStop = raceStop; + setStopForTest(mockSession, raceStop); return Promise.resolve({ body: { threads: [{ id: 3, name: 'Main' }] } }); } return Promise.resolve({}); @@ -4729,7 +4730,7 @@ describe('Session Manager Operations Coverage - Error Paths and Edge Cases', () const promise = operations.pause('test-session', 1); await vi.advanceTimersByTimeAsync(0); - mockSession.lastStop = { reason: 'pause', threadId: 1, timestamp: Date.now() }; + setStopForTest(mockSession, { reason: 'pause', threadId: 1, timestamp: Date.now() }); emitStopped(); await vi.advanceTimersByTimeAsync(10); // into the held stack read @@ -4876,7 +4877,7 @@ describe('Session Manager Operations Coverage - Error Paths and Edge Cases', () const promise = operations.pause('test-session', 1); await vi.advanceTimersByTimeAsync(0); // let the pause response resolve - mockSession.lastStop = { reason: 'pause', threadId: 1, timestamp: Date.now() }; + setStopForTest(mockSession, { reason: 'pause', threadId: 1, timestamp: Date.now() }); emitStopped(); await vi.advanceTimersByTimeAsync(10); // the post-stop settle delay await vi.advanceTimersByTimeAsync(5000); // the grace window elapses From e1e6cf066c24105fbcc8a688c017ab2fc4ae6bfa Mon Sep 17 00:00:00 2001 From: JF Date: Sun, 29 Nov 2026 00:23:55 -0500 Subject: [PATCH 2/9] fix(session): a read belongs to the pinned stop only if the session held it throughout Two independent reviews of the stop record found the guarantee still broken on one route, and five related things. Written by a GPT model (the reviewer that had demonstrated each defect), tests first, from five principles; committed by the manager session. - A replacement stop that then resumed or ended passed for the pinned one: the check for a changed stop fired only while the session was paused, so an answer carried one stop's reason with the other's frames (shown through get_stack_trace and start_debugging). Identity is now checked independently of the state, where each read is made: after the landing's settle and after its stack read, in get_stack_trace's own handler, and in the frame-anchor resolver, which takes the caller's record as its gate instead of whatever stop is current when it starts. - An older read can no longer move a newer stop's thread (explicit stack inspection, attach adoption, the resolver's sibling scan). - A launch-shaped answer reads the session's state when it is built, so it no longer says "paused" with a landing for a session that has ended. - Nothing is recorded as shown until the answer that shows it is the one returned: the snapshot's diff base and the step filter hint's delivered mark are staged and published with the serialized answer. - One answer has one time budget: the re-read, the dependent reads and a step's grace share one deadline. Two 34 s landing reads used to take 68 s against a stated 35 s ceiling. - The note for a stop that changed while it was read no longer promises a reason that attach answers do not carry, nor that get_local_variables reads "that stop". - Source and stale-build enrichment are part of the pinned read. Tests: 24 of the new regression and boundary tests fail on the previous head; the seven mutants the first builder called equivalent are told apart; four tests that passed with their behaviour removed now fail under it; 23 ordinary answers are frozen and match main, the previous head and this one. Not covered, and said so in the documents: get_local_variables, evaluate_expression, get_scopes, get_variables and the thread a step resumes (#1374). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn82vMcRzWFDD9aUbZs --- CLAUDE.md | 2 +- changelog.d/1348.fixed.md | 2 +- docs/architecture/session-state-machine.md | 51 +- docs/tool-reference.md | 38 +- src/server.ts | 24 +- src/server/handlers/debuggee-tools.ts | 3 +- src/server/handlers/inspection-tools.ts | 55 +- src/server/handlers/shared.ts | 34 +- src/server/tool-context.ts | 4 +- src/server/tool-dispatch.ts | 14 +- src/server/tool-result.ts | 11 +- src/session/attach/attach-controller.ts | 15 +- src/session/execution/execution-controller.ts | 744 ++++++++++-------- .../inspection/frame-anchor-resolver.ts | 44 +- src/session/inspection/pinned-stop-read.ts | 123 ++- src/session/inspection/stop-answer-effects.ts | 145 ++++ src/session/inspection/stop-location.ts | 31 +- src/session/inspection/stop-snapshot.ts | 61 +- src/session/launch/debug-launcher.ts | 28 +- .../live-update/live-update-controller.ts | 11 +- src/session/operations-context.ts | 7 +- src/session/session-manager-data.ts | 33 +- src/session/stop-record.ts | 20 +- src/utils/error-messages.ts | 16 +- .../unit/server/server-control-tools.test.ts | 9 +- .../server/server-inspection-tools.test.ts | 2 +- .../unit/server/stop-pin-boundaries.test.ts | 188 +++++ .../unit/server/stop-pin-ordinary.test.ts | 130 +++ .../unit/server/stop-pin-regressions.test.ts | 305 +++++++ .../server/stop-pins-through-tools.test.ts | 8 + .../inspection/stop-answer-effects.test.ts | 43 + .../session/inspection/stop-location.test.ts | 36 + .../session/inspection/stop-snapshot.test.ts | 11 +- .../session-manager-attach-modes.test.ts | 37 + .../session-manager-stop-pin-routes.test.ts | 46 +- ...session-manager-wait-for-stop-tree.test.ts | 22 +- tests/core/unit/session/stop-record.test.ts | 6 +- tests/fixtures/stop-pin-ordinary.json | 614 +++++++++++++++ tests/unit/server-coverage.test.ts | 8 +- ...ession-manager-operations-coverage.test.ts | 4 +- 40 files changed, 2346 insertions(+), 639 deletions(-) create mode 100644 src/session/inspection/stop-answer-effects.ts create mode 100644 tests/core/unit/server/stop-pin-boundaries.test.ts create mode 100644 tests/core/unit/server/stop-pin-ordinary.test.ts create mode 100644 tests/core/unit/server/stop-pin-regressions.test.ts create mode 100644 tests/core/unit/session/inspection/stop-answer-effects.test.ts create mode 100644 tests/fixtures/stop-pin-ordinary.json diff --git a/CLAUDE.md b/CLAUDE.md index 8b832581c..ac3d20fc7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -310,7 +310,7 @@ The codebase follows a **layered architecture with dependency injection** and ** - `breakpoints/anchor-resolution.ts` (`reresolveAnchors`) and `breakpoints/launch-warnings.ts` (pure warning builders) - `execution/execution-controller.ts` (`ExecutionController`): stepping (table-driven over `STEP_KINDS`), continue, pause, thread list, `waitForStop`; `execution/session-state-wait.ts` (`waitForSessionState`): the one level-triggered wait on a session's state — it re-reads the state in a microtask after each change (`OperationsContext.onStateChange`, fed by `_updateSessionState`), so an entry stop the core auto-continues within one call stack is never reported (issue #849) - `inspection/stop-anchor.ts` (`selectStopAnchor`: the one verdict on which thread a stop is anchored on, shared by the attach controller and the frame-anchor resolver — a `pause` reported on a thread with no program frame moves to the first sibling whose stack reaches the program and says so; breakpoint/step/exception/entry stops never move; issues #904/#898), `inspection/stop-location.ts` (`describeStopLocation`: the one landing read behind the pause, step, wait_for_stop, attach and launch answers — a `start_debugging`/`restart_debugging` that is paused when it answers reads it too, issue #951 — `location`, and `threadId`/`note` when the answer is anchored off the reported thread or no frame is program code; the landing also carries its resolver read internally as `StopLanding.stackResult`, which `inspection/stop-snapshot.ts` (`composeStopSnapshot`, issue #982) turns into the bounded `snapshot` — exception from the redacted stop record, top ≤3 frames, locals via `extractLocalsFromResolved` under `snapshotLocalsLimits` and the `snapshotLocalsTimeoutMs` tunable — that every PAUSED arrival answer carries (entry stops, dry runs, pending answers and the pause "Already paused" fast path carry none; `DEBUG_MCP_NO_SNAPSHOT` opts out, explicit variable-access mode withholds locals); the handlers hoist the landing fields and the snapshot through `handlers/shared.ts` `hoistStopLanding` — attach included (issue #982 parity) — which also reads the line context and the stale-build sentence and dedupes the snapshot out of the embedded `data`), `inspection/expression-evaluator.ts` (`ExpressionEvaluator`), `jvm/redefine-classes-controller.ts` (`RedefineClassesController`), `mirror/mirror-controller.ts` (`MirrorController`) - - Collaborators see the facade through `OperationsContext` (`operations-context.ts`), whose members are late-bound arrows and getters — never captured references — so reassigning a facade method or writing a tunable on a live instance is visible to them; each takes the narrowest `Pick<>` slice it uses. Collaborator-to-collaborator dependencies are constructor arguments (`DebugLauncher(ctx, proxyLauncher, breakpoints, inFlight)`, `AttachController(ctx, proxyLauncher, breakpoints, pauseCoordinator, inFlight)`) held as captured instance references: their methods resolve at call time, so `vi.spyOn(internals(ops).proxyLauncher, 'start')` intercepts, but reassigning a collaborator field after construction is not observed. The facade owns one shared `InFlightGuard` (`in-flight-guard.ts`, issue #711) that the launcher and the attach controller both take: `startDebugging`, `restartDebugging`, `attachToProcess` and `detachFromProcess` each claim the session before their first await and release it in `finally`, so one launch-shaped call per session at a time; `restartDebugging` replays through the launcher's private `launch()` under its own claim, never through the facade's `startDebugging`. The guard also holds the session's ending in flight (issue #1325): `close_debug_session` goes through the facade's `closeDebugSession` → `AttachController.closeSession`, and a close or a plain detach that arrives while another close or detach of the session is in flight joins it (`InFlightGuard.runEnding`/`ending`), and no second `disconnect` goes out after a confirmed release, also after a detach whose cleanup failed once its release was confirmed (the detach's record keeps the release; the joined close passes a confirmed one, `released` or `program-ended`, to `closeSessionReporting` as `releaseSent` and stops the worker itself; after a detach whose release was not confirmed, which may never have reached the adapter, or that failed before its release, the close sends its own, as one that joined nothing does); a terminating detach is refused instead. While an ending is in flight `InFlightGuard.tryAcquire` refuses every launch, restart or attach, whoever holds the claim ("This session is being closed …"), so an attach that was in flight when the close came and answers meanwhile lets nothing in under it. The close also claims the session when nothing holds it, and is itself never refused: with a launch-shaped call in flight it goes ahead unclaimed. The server's exit and the idle policy call `closeSessionReporting` directly, outside the join. Shared per-request DAP helpers live in `dap-request-helpers.ts`. Each stop has a record (`stop-record.ts`, issue #1362: an id minted when the core applies it, its run, thread, reason, whether it is shown, and the step or pause it answers; `lastStop` is its `info`, written only by that module, and stops are compared by record id), and every answer that describes a stop reads under a pin of it (`inspection/pinned-stop-read.ts` `readPinnedStop`: pinned before the first await, every read checked, read again once if the stop changed, and answered with the current stop and no landing if it changed again; issue #1348) +Each stop has a record (`stop-record.ts`, issue #1362): an id minted when the core applies it, its run, thread, reason, visibility and operation cause. The pinned stop-answer paths use `inspection/pinned-stop-read.ts` (get_stack_trace pins in its handler). They check identity independently of state, retry once within the same Deadline, sample state at answer assembly, and publish snapshot diff baselines and step hints only with the returned answer. Launch pins after breakpoint re-send, before its dependent reads. This change does not pin get_local_variables, evaluate_expression, get_scopes or get_variables, or change which thread a step resumes; those are issue #1374. - Session state has one gate, `SessionManagerCore._updateSessionState`, and every call of it names its site and event (`{ site, event, facts? }`, paired by the compiler through `EVENT_OF_SITE`). `src/session/machine/` holds the transition table (`transition-table.ts`) and its shadow check (`shadow.ts`), which judges each write against the table and records a verdict without refusing anything (`MCP_STATE_SHADOW`: `record` by default, `strict` in the unit project, `off`). See `docs/architecture/session-state-machine.md` for the verdicts, the `legacy`/`future` marks, and how to add a site, an event or a row - Coordinates ProxyManager instances (one per session) - Handles breakpoint management and queuing diff --git a/changelog.d/1348.fixed.md b/changelog.d/1348.fixed.md index f1bca2735..a8a38dd2b 100644 --- a/changelog.d/1348.fixed.md +++ b/changelog.d/1348.fixed.md @@ -1 +1 @@ -**A stop answer describes one stop, also when the program stops again while the answer is being read** — `wait_for_stop`, `step_over`/`step_into`/`step_out`, `pause_execution`, a `start_debugging` or `restart_debugging` that answers paused (and its `pausedChild`), `attach_to_process`, a `hot_reload` that stops a running program, and `get_stack_trace` read where the program stopped with a request to the debugger, and took the stop they describe after that read returned. When a second stop arrived during the read, the answer carried the first stop's `location`, frames and snapshot with the second stop's reason, `lastStop`, exception and step note, and said nothing of it: a `wait_for_stop` could answer `Paused (exception) at app.py:11` for an exception raised at line 50, and a step could add "The program is back at the line the step was issued from" to a stop somewhere else. Each stop now gets a record with an id when the server applies it, and each of these answers takes that id before its first read and checks every read against it (the location, the frames, the snapshot's exception and locals, the step's provenance note; the source line and the stale-build note are read from the answer's own location). If the stop changed, all of the answer's reads are made again for the stop the program is at now; if it changed again during that second read, the answer gives that stop's reason and state with no location, frames or snapshot, and its `note` says that the program stopped again while the answer was being read and that `get_stack_trace` and `get_local_variables` read that stop (#1348, #1362) +**Keep stop answers coherent when another stop arrives during their reads.** A wait or step could report one stop's location with another's reason or exception. The stop-answer paths now pin the record before their dependent debugger reads, reject replacement reads even after resume or exit, and guard thread adoption with that same identity. Launch, restart, attach and reload answers use the state at assembly and omit a landing after resume or exit. A retry shares the first read's deadline; expiry names the budget, and a second change omits the landing and asks the caller to call get_stack_trace again. Snapshot diff baselines and step filter hints are published only with the answer that shows them. The note does not promise a reason field on attach or claim that unpinned locals inspect the same stop. This change does not pin get_local_variables, evaluate_expression, get_scopes or get_variables, or change which thread a step resumes; those are issue #1374. (#1348, #1362) diff --git a/docs/architecture/session-state-machine.md b/docs/architecture/session-state-machine.md index 6cafddfd8..17ee2d266 100644 --- a/docs/architecture/session-state-machine.md +++ b/docs/architecture/session-state-machine.md @@ -107,25 +107,38 @@ Tests give a session a stop through [`setStopForTest`](../../tests/test-utils/helpers/stop-record.ts); a `lastStop` written around the module has no record. The shadow is handed the record ids as its stop identities. -An answer that describes a stop pins it -([`pinned-stop-read.ts`](../../src/session/inspection/pinned-stop-read.ts)): it takes the -session's record before its first await, makes its reads under it (the landing, which reads the -pinned stop's reason and thread rather than the session's; the snapshot, whose exception, diff -base and locals check are the pinned stop's), and checks the pin when they end. If the session is -paused at another stop, all of the reads are made again once, under a pin of that stop; if it -changed again, the answer gives the current stop's reason and state, no landing, and -`ErrorMessages.stopChangedWhileRead`. A session that is not paused when the reads end is answered -by the rules it always had (ended as ended, running as pending), from the pinned stop. The answers -that pin: `wait_for_stop` (on the session the tree-aware selection names, its child releases -inside the pinned reads), the three steps (the first stopped event owns the answer; the snapshot, -composed once after any same-line repeats, is checked against the final landing's pin and reads -again if the landing's own re-read is unspent), `pause_execution`, the launch and hot-restart -answers and the launch's `pausedChild`, `attach_to_process`, a `hot_reload` of a running program -that stops it, and `get_stack_trace` (in the handler). The step's origin read before the step is -sent is pinned too: a stop that changes under it leaves the step without an origin. The probes are in -[`session-manager-stop-pins.test.ts`](../../tests/core/unit/session/session-manager-stop-pins.test.ts), -[`session-manager-stop-pin-routes.test.ts`](../../tests/core/unit/session/session-manager-stop-pin-routes.test.ts) -and [`stop-pins-through-tools.test.ts`](../../tests/core/unit/server/stop-pins-through-tools.test.ts). +The pinned answer paths are `wait_for_stop` (including descendant selection), the three +steps, `pause_execution`, paused launch/restart and attach answers, `pausedChild`, a running +program stopped by `hot_reload`, and `get_stack_trace`. They pin before the first dependent +read. Launch pins after breakpoint re-send, which reads no stack or stop payload. + +Identity validation is independent of session state: `pinBroken` compares the recorded id, +including when the session has resumed, ended or disappeared. `describeStopLocation` checks +after its settle and after its stack read. The resolver receives the caller's pin and uses it +as the adoption gate; it cannot acquire a newer stop's permission to move threads. The current +inspection anchor may already differ from the reported thread; the landing discloses that +choice rather than claiming that every stack request targets the reported thread. + +`readPinnedStop` re-reads once if another stop is paused, using the same `Deadline`. Step +origin, landing and snapshot reads share the step answer budget; waits use the caller's +original deadline. The default read budget is 35,000 ms, plus up to 250 ms for a request already +sent. No new read is admitted after expiry. An expired budget and a changed stop have distinct, +truthful notes. The latter directs the caller to call `get_stack_trace` again and makes no +promise about unpinned inspection tools or a reason field absent from an attach answer. + +Callers sample state when assembling the answer. A resumed/ended session has no paused landing +or snapshot; tool serialization checks state again after source/footprint enrichment. Snapshot +composition stages its diff baseline. Only the snapshot actually returned publishes that +baseline. Step hint delivery likewise follows the final selected answer, not an earlier attempt. +The per-call publication scope keeps concurrent answers separate and publishes no effects if +serialization fails; direct SessionManager callers publish at their own return boundary. + +This change does not pin get_local_variables, evaluate_expression, get_scopes or get_variables, or change which thread a step resumes; those are issue #1374. + +Regression probes live in `stop-pin-regressions.test.ts`, `stop-pin-boundaries.test.ts`, +`stop-pin-ordinary.test.ts`, `session-manager-stop-pin-routes.test.ts`, the landing and attach +tests, and `stop-pins-through-tools.test.ts`. The ordinary-answer fixture also matches +`51d5886c`; it excludes only generated ids and timestamps. ## The table diff --git a/docs/tool-reference.md b/docs/tool-reference.md index 55848a86f..7403e1571 100644 --- a/docs/tool-reference.md +++ b/docs/tool-reference.md @@ -603,19 +603,31 @@ crashing state costs zero extra tool calls: ### One stop per answer -An answer that describes a stop — the stop answers above, a `hot_reload` of a running program that -stops it, `pausedChild` on a launch, and `get_stack_trace` — reads where the program stopped with requests -to the debugger, and the program can stop again while they are in flight (a resumed thread that -hits a breakpoint at once, a second thread's exception). Each stop has a record of its own, and -the answer takes the stop's identity before its first read and checks every read against it -(issues #1348, #1362), so its `location`, frames, `snapshot`, reason, `lastStop` and step note -always describe the same stop. If the stop changed, the answer's reads are made again for the -stop the program is at now, and the answer describes that one. If it changed again during that -second read, the answer gives the stop the program is at now (its reason, and `lastStop` where the -answer carries one) and its state, with no `location`, frames or `snapshot`, and `note` says: "The -program stopped again while this answer was being read, twice, so where it is paused was not read: -the reason given is the stop it is at now. get_stack_trace and get_local_variables read that stop." -The source line (`context`) and the stale-build note are read from the answer's own `location`. +The stop answers from `wait_for_stop`, the three step tools, `pause_execution`, paused launch, +restart and attach answers, a launch's `pausedChild`, a `hot_reload` that stops a running program, +and `get_stack_trace` pin a stop record before reading its stack. The record is checked where +reads begin and return, including after the landing's settle. A replacement invalidates the +read even if the session has subsequently resumed or ended. Thread adoption is allowed only +while the same record remains current. Each caller reads the answer's state when building it; +a session that resumed or ended receives no paused landing or snapshot. + +If the stop changes, these answers re-read it once under the remaining answer budget. If it +changes again, they omit the landing, frames and snapshot. They retain the reason or `lastStop` +only on answer shapes that carry those fields. The note says: "The stop changed while this +answer was being read; its stack and snapshot were omitted. Call get_stack_trace again to read +the current stop." Attach has no reason field; the note makes no claim that it has one. + +The debugger reads and their retry share a 35,000 ms deadline; `wait_for_stop` instead uses its +requested timeout for the wait and answer reads together. Requests already sent have up to +250 ms of deadline grace. A budget-expired answer names the budget and omits its landing and +snapshot. Source/build enrichment uses the same remaining budget. A locals diff baseline and +a step filter hint are recorded as shown only when the returned answer includes them. + +Source context and the stale-build note use the captured location. `get_stack_trace` checks +stale builds using its captured top frame; `hot_reload` adds neither source context nor a +stale-build note. + +This change does not pin get_local_variables, evaluate_expression, get_scopes or get_variables, or change which thread a step resumes; those are issue #1374. ### start_debugging diff --git a/src/server.ts b/src/server.ts index 56d82407d..69bbc945c 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1,3 +1,5 @@ +import { pinBroken, pinStop, type StopPin } from './session/stop-record.js'; +import type { Deadline } from '@debugmcp/shared'; /** * Debug MCP Server - Main Server Implementation * @@ -622,13 +624,18 @@ export class DebugMcpServer implements ToolContext { public async getStackTrace( sessionId: string, includeInternals: boolean = false, - threadId?: number + threadId?: number, + readOptions?: { pin?: StopPin; deadline?: Deadline } ): Promise { this.validateSession(sessionId); const session = this.sessionManager.getSession(sessionId); if (!session || !session.proxyManager) { throw new ProxyNotRunningError(sessionId || 'unknown', 'get stack trace'); } + const pin = readOptions?.pin ?? pinStop(session); + const options = { ...readOptions, pin }; + const changed = (): StackTraceResult => ({ frames: [], totalFrameCount: 0, hiddenFrameCount: 0, allFramesInternal: false }); + if (pinBroken(session, pin)) return changed(); // An explicit threadId (issue #465) targets that thread AND adopts it as // current when it reports frames, so follow-up scopes/locals/evaluate // anchor to it — this is the escape hatch when the session anchored to a @@ -639,9 +646,9 @@ export class DebugMcpServer implements ToolContext { // at sibling threads to *suggest* an alternative in `note` (issue // #553), but never silently re-anchors to one. const result = await this.sessionManager.getStackTraceDetailed( - sessionId, threadId, includeInternals + sessionId, threadId, includeInternals, options ); - if (result.frames.length > 0) { + if (result.frames.length > 0 && !pinBroken(session, pin) && session.state === SessionState.PAUSED) { session.proxyManager.setCurrentThreadId(threadId); } return result; @@ -654,14 +661,17 @@ export class DebugMcpServer implements ToolContext { // is not available") — a wasted round trip at best, the DAP timeout on // a wedged adapter at worst. if (session.state !== SessionState.PAUSED) { - return this.sessionManager.getStackTraceDetailed(sessionId, undefined, includeInternals); + return this.sessionManager.getStackTraceDetailed(sessionId, undefined, includeInternals, options); } let currentThreadId = session.proxyManager.getCurrentThreadId(); // If no thread ID is known (e.g. adapter omitted threadId from stopped event), // try to discover one via a 'threads' DAP request. if (typeof currentThreadId !== 'number') { try { - const threadsResp = await session.proxyManager.sendDapRequest('threads', {}); + const threadsResp = readOptions?.deadline + ? await session.proxyManager.sendDapRequest('threads', {}, { deadline: readOptions.deadline }) + : await session.proxyManager.sendDapRequest('threads', {}); + if (pinBroken(session, pin)) return changed(); const threads = threadsResp?.body?.threads; if (Array.isArray(threads) && threads.length > 0 && typeof threads[0]?.id === 'number') { currentThreadId = threads[0].id; @@ -674,13 +684,13 @@ export class DebugMcpServer implements ToolContext { // Paused, no thread known, and the adapter named none: the proxy is // alive, so "no active proxy" would be false. The session layer says // what is true — no stopped thread is known for this session. - return this.sessionManager.getStackTraceDetailed(sessionId, undefined, includeInternals); + return this.sessionManager.getStackTraceDetailed(sessionId, undefined, includeInternals, options); } // ensureStackReady: the thread above was resolved implicitly (the MCP tool // has no threadId argument), so a paused session answering with zero // frames gets the bounded readiness retry + thread scan instead of a // confusing empty success. - return this.sessionManager.getStackTraceDetailed(sessionId, currentThreadId, includeInternals, { ensureStackReady: true }); + return this.sessionManager.getStackTraceDetailed(sessionId, currentThreadId, includeInternals, { ...options, ensureStackReady: true }); } public async getScopes(sessionId: string, frameId: number): Promise { diff --git a/src/server/handlers/debuggee-tools.ts b/src/server/handlers/debuggee-tools.ts index 70fcaa26d..753bc2a09 100644 --- a/src/server/handlers/debuggee-tools.ts +++ b/src/server/handlers/debuggee-tools.ts @@ -1,3 +1,4 @@ +import { trackStopAnswerState } from '../../session/inspection/stop-answer-effects.js'; /** * Debuggee lifecycle tools: start_debugging, restart_debugging, * attach_to_process, detach_from_process, hot_reload. @@ -243,7 +244,7 @@ export const hotReloadTool: ToolHandler = async (ctx, args, toolName) => { ...(args.sinceTimestamp !== undefined ? { sinceTimestamp: args.sinceTimestamp } : {}), }; const result = await ctx.sessionManager.hotReload(args.sessionId as string, request, args.timeout); - const payload: Record = { ...result }; + const payload: Record = trackStopAnswerState({ ...result }, () => ctx.sessionManager.getSession(args.sessionId)?.state); if (toolName === 'redefine_classes') { payload.warning = result.warning ? `${result.warning}; ${REDEFINE_CLASSES_ALIAS_WARNING}` : REDEFINE_CLASSES_ALIAS_WARNING; } diff --git a/src/server/handlers/inspection-tools.ts b/src/server/handlers/inspection-tools.ts index 61428aee8..6bf29e616 100644 --- a/src/server/handlers/inspection-tools.ts +++ b/src/server/handlers/inspection-tools.ts @@ -3,9 +3,11 @@ * evaluate_expression, get_source_context, get_local_variables. */ import { ProtocolError, ProtocolErrorCode } from '@modelcontextprotocol/server'; -import { SessionState } from '@debugmcp/shared'; +import { deadline, SessionState } from '@debugmcp/shared'; import { hasPausingBreakpoint } from '../../session/launch/launch-arming.js'; -import { pinBroken, pinStop, stopRecordOf } from '../../session/stop-record.js'; +import { pinBroken, pinStop, stopRecordOf, type StopPin } from '../../session/stop-record.js'; +import { retainStopAnswerDeadline } from '../../session/inspection/stop-answer-effects.js'; +import { STOP_READ_BUDGET_MS } from '../../session/inspection/pinned-stop-read.js'; import { ErrorMessages } from '../../utils/error-messages.js'; import type { ToolContext, ToolHandler } from '../tool-context.js'; import { enforceExplicitNames, requireSessionId } from '../tool-validation.js'; @@ -83,6 +85,14 @@ export const getStackTraceTool: ToolHandler = async (ctx, args) => { const failureDiagnostics = () => ctx.sessionManager.getSession(args.sessionId)?.failureDiagnostics; + const budget = deadline(STOP_READ_BUDGET_MS, { label: 'stack trace answer' }); + const retained = retainStopAnswerDeadline(budget); + const changed = (note: string) => { + const after = ctx.sessionManager.getSession(args.sessionId); + const current = carriesLastStop(after?.state) ? stopRecordOf(after)?.info : undefined; + const lastStop = current ? emittableStopInfo(ctx, current) : undefined; + return jsonResult({ success: true, stackFrames: [], count: 0, includeInternals: args.includeInternals ?? false, stopReason: lastStop?.reason, lastStop, note }); + }; try { // Default to false for cleaner output const includeInternals = args.includeInternals ?? false; @@ -104,26 +114,24 @@ export const getStackTraceTool: ToolHandler = async (ctx, args) => { // again once, and a second change answers the stop now current with no // frames, and says so. let pin = sessionBefore?.state === SessionState.PAUSED ? pinStop(sessionBefore) : undefined; - let stackTrace = await ctx.getStackTrace(args.sessionId, includeInternals, args.threadId); + const fetch = async (under: StopPin | undefined) => { + const stackTrace = await budget.request(() => ctx.getStackTrace(args.sessionId!, includeInternals, args.threadId, { pin: under, deadline: budget })); + if (under && pinBroken(ctx.sessionManager.getSession(args.sessionId), under)) return { stackTrace, staleBuild: undefined }; + const top = stackTrace.frames[0]; + const staleBuild = top && !top.unresolvedSource && hasOpenableSourcePath(top.file) + ? await budget.request(() => describeStaleBuild(ctx, args.sessionId!, top.file, 'stack trace')) + : undefined; + return { stackTrace, staleBuild }; + }; + let { stackTrace, staleBuild } = await fetch(pin); if (pin && pinBroken(ctx.sessionManager.getSession(args.sessionId), pin)) { - const now = ctx.sessionManager.getSession(args.sessionId)!; + const now = ctx.sessionManager.getSession(args.sessionId); + if (!now || now.state !== SessionState.PAUSED) return changed(ErrorMessages.stopChangedWhileRead()); pin = pinStop(now); storedStop = pin.stop?.info; - stackTrace = await ctx.getStackTrace(args.sessionId, includeInternals, args.threadId); + ({ stackTrace, staleBuild } = await fetch(pin)); const after = ctx.sessionManager.getSession(args.sessionId); - if (pinBroken(after, pin)) { - const current = stopRecordOf(after); - const currentStop = current ? emittableStopInfo(ctx, current.info) : undefined; - return jsonResult({ - success: true, - stackFrames: [], - count: 0, - includeInternals, - stopReason: currentStop?.reason, - lastStop: currentStop, - note: ErrorMessages.stopChangedWhileRead() - }); - } + if (pinBroken(after, pin)) return changed(ErrorMessages.stopChangedWhileRead()); } const lastStop = storedStop ? emittableStopInfo(ctx, storedStop) : undefined; const payload: Record = { @@ -215,18 +223,13 @@ export const getStackTraceTool: ToolHandler = async (ctx, args) => { // #951). The top frame only, and only one with an openable path — a // `<…>` label, a relative spelling or an unresolvedSource frame names no // file on this host (the same rule the stop answers apply). - const top = stackTrace.frames[0]; - if (top && !top.unresolvedSource && hasOpenableSourcePath(top.file)) { - const staleBuild = await describeStaleBuild(ctx, args.sessionId, top.file, 'stack trace'); - if (staleBuild) { - notes.push(staleBuild); - } - } + if (staleBuild) notes.push(staleBuild); if (notes.length > 0) { payload.note = notes.join(' '); } return jsonResult(payload); } catch (error) { + if (budget.expired) return changed(ErrorMessages.stopReadBudgetExpired(budget.budgetMs)); const sessionResult = sessionErrorToResult(error); if (sessionResult) { // An ended session gets the sentence get_local_variables always gave @@ -246,6 +249,8 @@ export const getStackTraceTool: ToolHandler = async (ctx, args) => { } // Re-throw unexpected errors throw error; + } finally { + if (!retained) budget.dispose(); } }; diff --git a/src/server/handlers/shared.ts b/src/server/handlers/shared.ts index 590a17662..a8b7133c3 100644 --- a/src/server/handlers/shared.ts +++ b/src/server/handlers/shared.ts @@ -1,3 +1,4 @@ +import { beforeStopAnswerReturn, isTrackedStopAnswer, readStopEnrichment, stopAnswerDeadline, stopEnrichmentFor, trackStopAnswerState } from '../../session/inspection/stop-answer-effects.js'; /** * Helpers shared by more than one tool handler: the best-effort line-context * read, the redaction notice, the get_variables / get_local_variables payload @@ -323,18 +324,35 @@ export async function hoistPausedChild( return; } const pausedChild: Record = { ...data.pausedChild }; + if (isTrackedStopAnswer(data) || stopAnswerDeadline() || ctx.sessionManager.getSession(data.pausedChild.sessionId)?.state !== undefined) { + trackStopAnswerState(pausedChild, () => ctx.sessionManager.getSession(data.pausedChild!.sessionId)?.state); + } const location = data.pausedChild.location; if (location && !location.unresolvedSource && hasOpenableSourcePath(location.file)) { - const [context, staleBuild] = await Promise.all([ + const cached = stopEnrichmentFor(location); + const enriched = cached ? [cached.context, cached.staleBuild] as const : await readStopEnrichment(() => Promise.all([ readLineContext(ctx, location.file, location.line, logLabel), - describeStaleBuild(ctx, data.pausedChild.sessionId, location.file, logLabel) - ]); + describeStaleBuild(ctx, data.pausedChild!.sessionId, location.file, logLabel) + ]), pausedChild); + const [context, staleBuild] = enriched ?? []; if (context) { pausedChild.context = context; } appendNote(pausedChild, staleBuild); } response.pausedChild = pausedChild; + if (ctx.sessionManager.getSession(data.pausedChild.sessionId)?.state !== undefined) { + beforeStopAnswerReturn(response, () => { + const state = ctx.sessionManager.getSession(data.pausedChild!.sessionId)?.state; + if (state === SessionState.PAUSED) return; + delete response.pausedChild; + const embedded = response.data as Record | undefined; + if (embedded) delete embedded.pausedChild; + const message = `The selected child is ${state ?? 'closed'}; its paused landing was omitted.`; + response.message = message; + if (embedded) embedded.message = message; + }); + } if (data.pausedChild.snapshot) { const embedded = response.data; if (embedded && typeof embedded === 'object' && 'pausedChild' in embedded) { @@ -372,6 +390,9 @@ export async function hoistStopLanding( sessionId: string, logLabel: string ): Promise { + if (isTrackedStopAnswer(data) || stopAnswerDeadline() || ctx.sessionManager.getSession(sessionId)?.state !== undefined) { + trackStopAnswerState(response, () => ctx.sessionManager.getSession(sessionId)?.state); + } if (typeof data?.threadId === 'number') { response.threadId = data.threadId; } @@ -400,10 +421,13 @@ export async function hoistStopLanding( if (location.unresolvedSource || !hasOpenableSourcePath(location.file)) { return; } - const [context, staleBuild] = await Promise.all([ + const cached = stopEnrichmentFor(location); + const enriched = cached ? [cached.context, cached.staleBuild] as const : await readStopEnrichment(() => Promise.all([ readLineContext(ctx, location.file, location.line, logLabel), describeStaleBuild(ctx, sessionId, location.file, logLabel) - ]); + ]), response); + if (!enriched) return; + const [context, staleBuild] = enriched; if (context) { response.context = context; } diff --git a/src/server/tool-context.ts b/src/server/tool-context.ts index 4561da923..bb8b2d912 100644 --- a/src/server/tool-context.ts +++ b/src/server/tool-context.ts @@ -1,3 +1,5 @@ +import type { Deadline } from '@debugmcp/shared'; +import type { StopPin } from '../session/stop-record.js'; /** * The contract every tool handler in src/server/handlers/ programs against. * @@ -112,7 +114,7 @@ export interface ToolContext { variables: Variable[]; truncation?: VariableTruncationSummary; }>; - getStackTrace(sessionId: string, includeInternals?: boolean, threadId?: number): Promise; + getStackTrace(sessionId: string, includeInternals?: boolean, threadId?: number, opts?: { pin?: StopPin; deadline?: Deadline }): Promise; getScopes(sessionId: string, frameId: number): Promise; getLocalVariables(sessionId: string, includeSpecial?: boolean, names?: string[]): Promise; continueExecution(sessionId: string): Promise; diff --git a/src/server/tool-dispatch.ts b/src/server/tool-dispatch.ts index 51862f712..59c40c856 100644 --- a/src/server/tool-dispatch.ts +++ b/src/server/tool-dispatch.ts @@ -15,6 +15,8 @@ import { buildToolDefinitions, isToolName, TOOL_ALIASES, type ToolDefinition } f import { assertRequiredToolArguments } from './tool-validation.js'; import type { ToolContext } from './tool-context.js'; import { TOOL_HANDLERS } from './handlers/index.js'; +import { withStopAnswerEffects } from '../session/inspection/stop-answer-effects.js'; +import { describeStaleBuild, hasOpenableSourcePath, readLineContext } from './handlers/shared.js'; /** * The owner-key gate (issue #1025, step 2). For a caller, a session outside @@ -181,7 +183,17 @@ export function registerToolHandlers(server: Pick, releaseIdleHold = await holdForTheCall(ctx, definition, args.sessionId, outOfScope, callerKey); const result = idleExpiryResult(ctx, definition, args.sessionId, callerKey) ?? - await TOOL_HANDLERS[toolName](ctx, args, requestedName, { signal: callCtx?.mcpReq.signal, callerKey }); + await withStopAnswerEffects( + () => TOOL_HANDLERS[toolName](ctx, args, requestedName, { signal: callCtx?.mcpReq.signal, callerKey }), + async (sessionId, location) => { + if (toolName === 'hot_reload' || location.unresolvedSource || !hasOpenableSourcePath(location.file)) return {}; + const [context, staleBuild] = await Promise.all([ + readLineContext(ctx, location.file, location.line, toolName), + describeStaleBuild(ctx, sessionId, location.file, toolName) + ]); + return { context, staleBuild }; + } + ); // Log tool response; success mirrors the payload's own success flag (issue #397) ctx.logger.info('tool:response', { diff --git a/src/server/tool-result.ts b/src/server/tool-result.ts index 15284c3c2..c207c0913 100644 --- a/src/server/tool-result.ts +++ b/src/server/tool-result.ts @@ -7,6 +7,7 @@ */ import { ProtocolError, ServerResult, ProtocolErrorCode } from '@modelcontextprotocol/server'; import path from 'path'; +import { publishReturnedStopEffects, refreshStopAnswer } from '../session/inspection/stop-answer-effects.js'; import { getErrorMessage, SessionNotFoundError, @@ -19,12 +20,18 @@ export type ToolResult = { content: [{ type: 'text'; text: string }] }; /** Wrap a JSON-serializable payload as a tool result. */ export function jsonResult(payload: unknown): ToolResult { - return { content: [{ type: 'text', text: JSON.stringify(payload) }] }; + refreshStopAnswer(payload); + const text = JSON.stringify(payload); + publishReturnedStopEffects(payload); + return { content: [{ type: 'text', text }] }; } /** Wrap a JSON-serializable payload as a pretty-printed (2-space) tool result. */ export function prettyJsonResult(payload: unknown): ToolResult { - return { content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }] }; + refreshStopAnswer(payload); + const text = JSON.stringify(payload, null, 2); + publishReturnedStopEffects(payload); + return { content: [{ type: 'text', text }] }; } /** diff --git a/src/session/attach/attach-controller.ts b/src/session/attach/attach-controller.ts index 9b07962af..82c45024b 100644 --- a/src/session/attach/attach-controller.ts +++ b/src/session/attach/attach-controller.ts @@ -42,8 +42,8 @@ import { recordExceptionArming } from '../launch/launch-arming.js'; import { verifyAttachThreads } from './attach-verification.js'; import { ATTACH_ANCHOR_BOUNDS, selectStopAnchor } from '../inspection/stop-anchor.js'; import { landingFields } from '../inspection/stop-location.js'; -import { describedStop, readPinnedStop } from '../inspection/pinned-stop-read.js'; -import { resetStops } from '../stop-record.js'; +import { completeStopAnswer, describedStop, readPinnedStop } from '../inspection/pinned-stop-read.js'; +import { pinBroken, pinStop, resetStops } from '../stop-record.js'; import type { PauseCoordinator } from '../execution/pause-coordinator.js'; import { refuseChildSession, type EndingRecord, type InFlightGuard, type SessionEnding } from '../in-flight-guard.js'; import { releaseAttachedTarget, type TargetRelease } from './target-release.js'; @@ -345,6 +345,7 @@ export class AttachController { // thread is routinely a thread-pool worker. Only without such a stop does // the name heuristic apply: a thread named "main" (common in JVM // debugging), else the first thread. + const anchorPin = pinStop(session); const stoppedThreadId = observedAttachStopThread(session); const stoppedThread = typeof stoppedThreadId === 'number' ? threads.find(t => t.id === stoppedThreadId) : undefined; // The reported stop thread is not always the program's: CodeLLDB reports the @@ -371,7 +372,7 @@ export class AttachController { this.ctx.logger.info( `[SessionManager] Discovered ${threads.length} threads. Using threadId=${discoveredThreadId} (name=${chosen.name}, ${rule})` ); - proxyManager.setCurrentThreadId(discoveredThreadId); + if (!pinBroken(session, anchorPin)) proxyManager.setCurrentThreadId(discoveredThreadId); this.ctx.logger.info(`[SessionManager] Set threadId=${discoveredThreadId} for attach mode`); assertTargetPresent(); @@ -470,8 +471,8 @@ export class AttachController { const described = session.state === SessionState.PAUSED ? describedStop(await readPinnedStop(this.ctx, sessionId, 'attach')) : undefined; - const landing = described?.landing; - const snapshot = described?.snapshot; + const landing = session.state === SessionState.PAUSED ? described?.landing : undefined; + const snapshot = session.state === SessionState.PAUSED ? described?.snapshot : undefined; assertTargetPresent(); // Named the way the request addressed it: a PID, a host:port, or a @@ -538,11 +539,11 @@ export class AttachController { attachData.warning = warningParts.join('; '); } - return { + return completeStopAnswer({ success: true, state: session.state, data: attachData - }; + }, () => session.state); } catch (error) { this.ctx.logger.error(`[SessionManager] Failed to attach to process for session ${sessionId}:`, error); // Never leave a live proxy chain behind a failed attach — e.g. diff --git a/src/session/execution/execution-controller.ts b/src/session/execution/execution-controller.ts index 61f4946b1..f0d6b8a02 100644 --- a/src/session/execution/execution-controller.ts +++ b/src/session/execution/execution-controller.ts @@ -1,3 +1,4 @@ +import { containsStopNote, publishStopEffect, retainStopAnswerDeadline, trackStopAnswerState } from '../inspection/stop-answer-effects.js'; /** * Execution control: stepping, continue, pause, waiting for a stop, and the * thread list. @@ -42,6 +43,8 @@ */ import { getErrorMessage } from '../../errors/debug-errors.js'; import { + deadline, + type Deadline, isSessionTerminated, isTerminalSessionState, NO_DEBUG_TARGET_MARKER, @@ -81,8 +84,8 @@ import { samePath } from '../breakpoints/hit-verification.js'; import type { ExecutionContext } from '../operations-context.js'; import { runFactsOf, type RunFacts } from '../run-facts.js'; import { landingFields, type StopLanding } from '../inspection/stop-location.js'; -import { composeStopSnapshot } from '../inspection/stop-snapshot.js'; -import { readPinnedStop, type PinnedStopRead } from '../inspection/pinned-stop-read.js'; +import { commitStopSnapshot, composeStopSnapshot } from '../inspection/stop-snapshot.js'; +import { readPinnedStop, STOP_READ_BUDGET_MS, type PinnedStopRead } from '../inspection/pinned-stop-read.js'; import { nextOperationId, pinBroken, @@ -153,6 +156,7 @@ const PAUSED_THEN_ENDED_MESSAGE = 'Paused; the session ended before the stack co /** The per-step options `executeStep` waits on. */ export interface StepOperationOptions { + deadline?: Deadline; command: 'next' | 'stepIn' | 'stepOut'; threadId: number; logTag: string; @@ -211,6 +215,7 @@ interface StepAnswer { * changes under the snapshot it composes afterwards. */ export interface StepLandingRead { + deliver?: () => void; landing?: StopLanding; pin?: StopPin; reread: boolean; @@ -283,111 +288,120 @@ export class ExecutionController { * checks, the current thread, and the error handling around the wait. */ private async step(sessionId: string, kind: StepKindName): Promise> { - const { command, toolName, operation, logTag, successMessage } = STEP_KINDS[kind]; - const session = this.ctx.getSession(sessionId); + const stopBudget = deadline(STOP_READ_BUDGET_MS, { label: 'step answer' }); + const retained = retainStopAnswerDeadline(stopBudget); + try { + const { command, toolName, operation, logTag, successMessage } = STEP_KINDS[kind]; + const session = this.ctx.getSession(sessionId); - // Check if session is terminated - if (isSessionTerminated(session)) { - throw new SessionTerminatedError(sessionId); - } + // Check if session is terminated + if (isSessionTerminated(session)) { + throw new SessionTerminatedError(sessionId); + } - const threadId = session.proxyManager?.getCurrentThreadId(); - this.ctx.logger.info( - `[SM ${logTag} ${sessionId}] Entered. Current state: ${session.state}, ThreadID: ${threadId}` - ); + const threadId = session.proxyManager?.getCurrentThreadId(); + this.ctx.logger.info( + `[SM ${logTag} ${sessionId}] Entered. Current state: ${session.state}, ThreadID: ${threadId}` + ); - if (!session.proxyManager || !session.proxyManager.isRunning()) { - throw new ProxyNotRunningError(sessionId, operation); - } - if (session.state !== SessionState.PAUSED) { - this.ctx.logger.warn(`[SM ${logTag} ${sessionId}] Not paused. State: ${session.state}`); - return { success: false, error: notPausedError(session), state: session.state }; - } - if (typeof threadId !== 'number') { - this.ctx.logger.warn(`[SM ${logTag} ${sessionId}] No current thread ID.`); - return { success: false, error: 'No current thread ID', state: session.state }; - } + if (!session.proxyManager || !session.proxyManager.isRunning()) { + throw new ProxyNotRunningError(sessionId, operation); + } + if (session.state !== SessionState.PAUSED) { + this.ctx.logger.warn(`[SM ${logTag} ${sessionId}] Not paused. State: ${session.state}`); + return { success: false, error: notPausedError(session), state: session.state }; + } + if (typeof threadId !== 'number') { + this.ctx.logger.warn(`[SM ${logTag} ${sessionId}] No current thread ID.`); + return { success: false, error: 'No current thread ID', state: session.state }; + } - // Read the starting stack for every adapter (issue #1180): one bounded - // stackTrace supplies the raw top frame (JS pending hints and Dart - // same-line repeats) and the policy-filtered stack (landing provenance and - // changedVariables call identity, issues #1183/#1184). - const repeatsOnSameLine = - kind === 'stepOver' && this.ctx.selectPolicy(session.language).stepsByTokenPosition === true; - const origin = await this.readStepOrigin(session, sessionId, threadId); - const fromFrame = origin?.rawTop; - const stepFilterHint = kind === 'stepInto' ? this.describeStepInFilter(session, sessionId) : undefined; - const describePending = (record: StepperRecord | undefined): string | undefined => - this.describePendingStop(session, sessionId, 'step', fromFrame, record); - - // 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 - // continue_execution or a second step can have resumed the thread, or - // the session can have ended, in the meantime. Without this the step - // would go to a running thread and its rejection would flip a healthy - // session to ERROR. - if (isSessionTerminated(session)) { - throw new SessionTerminatedError(sessionId); - } - if (!session.proxyManager || !session.proxyManager.isRunning()) { - throw new ProxyNotRunningError(sessionId, operation); - } - if (session.state !== SessionState.PAUSED) { - this.ctx.logger.warn(`[SM ${logTag} ${sessionId}] No longer paused after the origin read. State: ${session.state}`); - return { success: false, error: notPausedError(session), state: session.state }; - } + // Read the starting stack for every adapter (issue #1180): one bounded + // stackTrace supplies the raw top frame (JS pending hints and Dart + // same-line repeats) and the policy-filtered stack (landing provenance and + // changedVariables call identity, issues #1183/#1184). + const repeatsOnSameLine = + kind === 'stepOver' && this.ctx.selectPolicy(session.language).stepsByTokenPosition === true; + const origin = await this.readStepOrigin(session, sessionId, threadId, stopBudget); + const fromFrame = origin?.rawTop; + const stepFilterHint = kind === 'stepInto' ? this.describeStepInFilter(session, sessionId) : undefined; + const describePending = (record: StepperRecord | undefined): string | undefined => + this.describePendingStop(session, sessionId, 'step', fromFrame, record); + + if (stopBudget.expired) return { success: false, state: session.state, error: ErrorMessages.stopReadBudgetExpired(stopBudget.budgetMs) }; + + // 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 + // continue_execution or a second step can have resumed the thread, or + // the session can have ended, in the meantime. Without this the step + // would go to a running thread and its rejection would flip a healthy + // session to ERROR. + if (isSessionTerminated(session)) { + throw new SessionTerminatedError(sessionId); + } + if (!session.proxyManager || !session.proxyManager.isRunning()) { + throw new ProxyNotRunningError(sessionId, operation); + } + if (session.state !== SessionState.PAUSED) { + this.ctx.logger.warn(`[SM ${logTag} ${sessionId}] No longer paused after the origin read. State: ${session.state}`); + return { success: false, error: notPausedError(session), state: session.state }; + } - this.ctx.logger.info(`[SM ${logTag} ${sessionId}] Sending DAP '${command}' for threadId ${threadId}`); + this.ctx.logger.info(`[SM ${logTag} ${sessionId}] Sending DAP '${command}' for threadId ${threadId}`); - // Set once the step (and any same-line repeats) has landed: a failure - // after that is in reading the answer, not in the resume. - let landed = false; - try { - // The last landing read, whatever attempt made it (issue #983): the - // snapshot is composed once per ANSWER, after any same-line repeats, - // under the pin that landing was read with. - let finalRead: StepLandingRead | undefined; - const stepOptions: StepOperationOptions = { - command, - flavor: kind, - toolName, - threadId, - logTag, - successMessage, - describePending, - ...(origin ? { stepOrigin: origin } : {}), - ...(stepFilterHint ? { stepFilterHint } : {}), - ...(fromFrame ? { origin: { file: fromFrame.file, line: fromFrame.line, column: fromFrame.column } } : {}), - onLanding: (read) => { finalRead = read; }, - }; - const first = await this.executeStep(session, sessionId, stepOptions); - const result = repeatsOnSameLine && origin?.rawTop - ? await this.repeatWhileOnOriginLine(session, sessionId, stepOptions, origin, first) - : first; - landed = true; - const read = finalRead; - if ( - result.success && - result.data !== undefined && - !result.data.pending && - session.state === SessionState.PAUSED && - read?.pin !== undefined && - read.landing !== undefined - ) { - return await this.withStepSnapshot(session, sessionId, logTag, result, { ...read, pin: read.pin, landing: read.landing }); - } - return result; - } catch (error) { - const errorMessage = getErrorMessage(error); - this.ctx.logger.error(`[SM ${logTag} ${sessionId}] Error during step:`, error); - if (!(error instanceof DapResponseError) && !isTerminalSessionState(session.state)) { - this.ctx.updateState( - session, - SessionState.ERROR, - landed ? { site: 'step.failed', event: 'answer-failed' } : { site: 'step.failed', event: 'resume-failed' } - ); + // Set once the step (and any same-line repeats) has landed: a failure + // after that is in reading the answer, not in the resume. + let landed = false; + try { + // The last landing read, whatever attempt made it (issue #983): the + // snapshot is composed once per ANSWER, after any same-line repeats, + // under the pin that landing was read with. + let finalRead: StepLandingRead | undefined; + const stepOptions: StepOperationOptions = { + deadline: stopBudget, + command, + flavor: kind, + toolName, + threadId, + logTag, + successMessage, + describePending, + ...(origin ? { stepOrigin: origin } : {}), + ...(stepFilterHint ? { stepFilterHint } : {}), + ...(fromFrame ? { origin: { file: fromFrame.file, line: fromFrame.line, column: fromFrame.column } } : {}), + onLanding: (read) => { finalRead = read; }, + }; + const first = await this.executeStep(session, sessionId, stepOptions); + const result = repeatsOnSameLine && origin?.rawTop + ? await this.repeatWhileOnOriginLine(session, sessionId, stepOptions, origin, first) + : first; + landed = true; + const read = finalRead; + if ( + result.success && + result.data !== undefined && + !result.data.pending && + session.state === SessionState.PAUSED && + read?.pin !== undefined && + read.landing !== undefined + ) { + return await this.withStepSnapshot(session, sessionId, logTag, result, { ...read, pin: read.pin, landing: read.landing }, stopBudget); + } + return trackStopAnswerState(result, () => session.state); + } catch (error) { + const errorMessage = getErrorMessage(error); + this.ctx.logger.error(`[SM ${logTag} ${sessionId}] Error during step:`, error); + if (!(error instanceof DapResponseError) && !isTerminalSessionState(session.state)) { + this.ctx.updateState( + session, + SessionState.ERROR, + landed ? { site: 'step.failed', event: 'answer-failed' } : { site: 'step.failed', event: 'resume-failed' } + ); + } + return { success: false, error: errorMessage, state: session.state }; } - return { success: false, error: errorMessage, state: session.state }; + } finally { + if (!retained) stopBudget.dispose(); } } @@ -447,6 +461,7 @@ export class ExecutionController { return new Promise((resolve) => { let settled = false; + const graceBudget = deadline(this.ctx.tunables.stepGraceMs, { parent: options.deadline, label: 'step grace' }); // Rule 1's flag: "a stop has been observed, the stop path owns the // settle". Set as the first statement of onStopped, so every other path // can tell "nothing stopped" from "stopped, still resolving where". @@ -468,7 +483,7 @@ export class ExecutionController { proxyManager.off('exited', onExited); proxyManager.off('exit', onExit); proxyManager.off('dap-event', onDapEvent); - clearTimeout(timeout); + graceBudget.dispose(); }; const settle = (result: DebugResult) => { @@ -622,15 +637,12 @@ export class ExecutionController { return; } stopSeen = true; - clearTimeout(timeout); + graceBudget.dispose(); // Where the step landed, through the resolver (issue #904), under a // pin of the stop taken here, before the read's first await: a failed // read answers no location and never fails the step. - const read = await readPinnedStop(this.ctx, sessionId, options.logTag, { snapshot: false }); + const read = await readPinnedStop(this.ctx, sessionId, options.logTag, { snapshot: false, deadline: options.deadline }); const builders = { answerAgain: answerFor, changedAnswer, endedAnswer }; - options.onLanding?.(read.status === 'pinned' - ? { landing: read.landing, pin: read.pin, reread: read.reread, ...builders } - : { reread: true, ...builders }); // Rule 2. An ended event that reached the listeners below has already // settled with its own wording; this covers the endings that did not // (handlers torn down by the core, an exit mapped straight to ERROR). @@ -639,13 +651,19 @@ export class ExecutionController { return; } if (read.status === 'changed') { - settle(changedAnswer(read.current)); + options.onLanding?.({ reread: true, ...builders }); + const changed = changedAnswer(read.current); + changed.data!.note = read.note; + settle(changed); return; } - const answer = answerFor(read.pin, read.landing); - if (!settled) { - answer.deliver?.(); + if (session.state !== SessionState.PAUSED) { + settle(resultFor('The program resumed while this answer was being read.')); + return; } + const answer = answerFor(read.pin, read.landing); + options.onLanding?.({ landing: read.landing, pin: read.pin, reread: read.reread, ...builders, deliver: answer.deliver }); + if (!settled && !options.onLanding) answer.deliver?.(); this.ctx.logger.info(`[SM ${options.logTag} ${sessionId}] ${answer.result.data?.message} Current state: ${session.state}`); settle(answer.result); }; @@ -654,21 +672,27 @@ export class ExecutionController { const onExited = () => settleEnded(options.exitedMessage); const onExit = () => settleEnded(options.exitedMessage); - const timeout = setTimeout(() => { + void graceBudget.sleep(this.ctx.tunables.stepGraceMs).then(() => { + if (settled) return; // Rule 1: the stop already arrived, so onStopped owns the settle and // will report where it landed. "Still executing" from here would be a // lie the caller has no way to correct. - // Trade-off: past this point the answer is bounded by the stackTrace - // round trip (a 30s DAP request timeout plus the proxy's 5s parent - // margin) rather than by this 5s window. Worth it — a slow truthful - // answer beats a fast wrong one — but it IS the ceiling, which is why - // the stand-down is logged. + // The stop reader owns settlement now, within the shared answer + // Deadline. Its retry receives only the time still available. if (stopSeen) { this.ctx.logger.debug( `[SM ${options.logTag} ${sessionId}] Grace window elapsed but the stop is already being resolved; standing down` ); return; } + if (options.deadline?.expired) { + settle({ success: true, state: session.state, data: { + pending: true, + message: 'The step is still executing; the answer budget expired.', + note: ErrorMessages.stopReadBudgetExpired(options.deadline.budgetMs) + } }); + return; + } this.ctx.logger.info( `[SM ${options.logTag} ${sessionId}] Step still running after ${this.ctx.tunables.stepGraceMs}ms grace window; completing asynchronously` ); @@ -691,7 +715,7 @@ export class ExecutionController { pending: true, }, }); - }, this.ctx.tunables.stepGraceMs); + }); proxyManager.on('stopped', onStopped); proxyManager.on('continued', onContinued); @@ -1010,13 +1034,17 @@ export class ExecutionController { data: { message: PAUSED_THEN_ENDED_MESSAGE, ...ownStopReason(stopRecordOf(session)) } }; } + if (this.ctx.getSession(sessionId).state !== SessionState.PAUSED) { + return { success: true, state: session.state, data: { message: 'The program resumed while this answer was being read.', pending: true } }; + } if (read.status === 'changed') { return { success: true, state: session.state, - data: { message: 'Paused', ...ownStopReason(read.current), note: ErrorMessages.stopChangedWhileRead() } + data: { message: 'Paused', ...ownStopReason(read.current), note: read.note } }; } + commitStopSnapshot(read.snapshot); this.ctx.logger.info( `[SessionManager pause] Paused session ${sessionId}. Current state: ${session.state}` ); @@ -1150,234 +1178,241 @@ export class ExecutionController { ...this.ctx.descendantsOf(sessionId).map((d): [string, StopId | undefined] => [d.id, stopIdOf(d)]) ]); - const deadline = Date.now() + waitMs; - const wait = () => waitForSubtreeSettle(this.ctx, sessionId, { - timeoutMs: Math.max(0, deadline - Date.now()), signal - }); - let settled = await wait(); - let target = session; - // The answer's reads, made under a pin of the target's stop when it is - // paused (pinned-stop-read.ts); undefined when it was not. - let read: PinnedStopRead | undefined; - for (;;) { - if (settled.outcome === 'gone') { - return { - success: false, - error: ErrorMessages.sessionClosedWhileWaiting(sessionId), - state: SessionState.STOPPED - }; - } - // The session this answer is about: the selection's, or — pending — - // the one asked for. - target = settled.outcome === 'matched' ? settled.value : session; - - // Settle any in-flight child releases (bounded to min(1.5 s, remaining - // deadline) and cancelled on abort) BEFORE the loop's final re-check so - // a child that resumed or closed during the wait never returns a stale - // landing (issue #1221). Made with the reads, so a stop that changes - // while the releases settle is caught by the same pin. - const settleReleases = () => this.ctx.settleInFlightChildReleases(sessionId, { - timeoutMs: Math.max(0, deadline - Date.now()), - signal + const waitBudget = deadline(waitMs, { parent: signal, label: 'wait_for_stop answer' }); + const retained = retainStopAnswerDeadline(waitBudget); + try { + const wait = () => waitForSubtreeSettle(this.ctx, sessionId, { + timeoutMs: waitBudget.remaining(), signal }); - if (target.state === SessionState.PAUSED) { - // Where it stopped, best effort: the same short settle and stack read - // a step or a pause does, and the snapshot behind it, both under a - // pin of the stop taken here. lastStop already carries the - // exception, so the snapshot does not repeat it. - read = await readPinnedStop(this.ctx, target.id, 'waitForStop', { - snapshot: { omitException: true }, - alsoAwait: settleReleases + let settled = await wait(); + let target = session; + // The answer's reads, made under a pin of the target's stop when it is + // paused (pinned-stop-read.ts); undefined when it was not. + let read: PinnedStopRead | undefined; + for (;;) { + if (settled.outcome === 'gone') { + return { + success: false, + error: ErrorMessages.sessionClosedWhileWaiting(sessionId), + state: SessionState.STOPPED + }; + } + // The session this answer is about: the selection's, or — pending — + // the one asked for. + target = settled.outcome === 'matched' ? settled.value : session; + + // Settle any in-flight child releases (bounded to min(1.5 s, remaining + // deadline) and cancelled on abort) BEFORE the loop's final re-check so + // a child that resumed or closed during the wait never returns a stale + // landing (issue #1221). Made with the reads, so a stop that changes + // while the releases settle is caught by the same pin. + const settleReleases = () => this.ctx.settleInFlightChildReleases(sessionId, { + timeoutMs: waitBudget.remaining(), + signal }); - } else { - read = undefined; - await settleReleases(); - } + if (target.state === SessionState.PAUSED) { + // Where it stopped, best effort: the same short settle and stack read + // a step or a pause does, and the snapshot behind it, both under a + // pin of the stop taken here. lastStop already carries the + // exception, so the snapshot does not repeat it. + read = await readPinnedStop(this.ctx, target.id, 'waitForStop', { + snapshot: { omitException: true }, + deadline: waitBudget, + alsoAwait: settleReleases + }); + } else { + read = undefined; + await settleReleases(); + } - try { - this.ctx.getSession(sessionId); - } catch { - settled = { outcome: 'gone' }; - continue; + try { + this.ctx.getSession(sessionId); + } catch { + settled = { outcome: 'gone' }; + continue; + } + if (target !== session && ( + !this.ctx.descendantsOf(sessionId).includes(target) || + (target.state !== SessionState.PAUSED && !isTerminalSessionState(target.state)) + )) { + // A selected child may be closed or resumed by another caller while + // the answer is assembled. Re-select the tree under the ORIGINAL + // deadline: never return a removed id, or a pending root answer with + // the child's state. A still-present child that naturally ended keeps + // the ordinary ended-at-settle contract, including its recorded stop. + // waitForSubtreeSettle intentionally checks current state even with + // a zero timeout. That is useful for an initial read, but retries + // must not keep selecting alternating children past this deadline. + settled = waitBudget.expired + ? { outcome: signal?.aborted ? 'aborted' : 'timeout' } + : await wait(); + continue; + } + break; } - if (target !== session && ( - !this.ctx.descendantsOf(sessionId).includes(target) || - (target.state !== SessionState.PAUSED && !isTerminalSessionState(target.state)) - )) { - // A selected child may be closed or resumed by another caller while - // the answer is assembled. Re-select the tree under the ORIGINAL - // deadline: never return a removed id, or a pending root answer with - // the child's state. A still-present child that naturally ended keeps - // the ordinary ended-at-settle contract, including its recorded stop. - // waitForSubtreeSettle intentionally checks current state even with - // a zero timeout. That is useful for an initial read, but retries - // must not keep selecting alternating children past this deadline. - settled = Date.now() >= deadline - ? { outcome: signal?.aborted ? 'aborted' : 'timeout' } - : await wait(); - continue; + const tree = () => describeTreeAnswer(session, this.ctx.descendantsOf(sessionId)); + // Every answer that carries the run's `childrenReleased` says what it means + // (issue #1137): read from the session asked about, as the count is. + const explained = (message: string): string => withReleasedChildren(message, describeReleasedChildren(session)); + // Emit a redacted copy of the stop record (issue #982); the stored record + // is never mutated. + const emitStop = (stop: SessionStopInfo): SessionStopInfo => + this.ctx.redactionEnabled() ? redactStopInfo(stop) : stop; + + const state = target.state; + // Rule 2 of the settle contract: a session that is over by now is + // reported as ended, with the stop that landed during this wait if there + // was one — an exception stop and the exit can arrive in one tick. A stop + // from before the wait is not this wait's to report: the program was + // resumed past it. + const stopDuringWait = + target.lastStop && stopIdOf(target) !== stopBefore.get(target.id) ? { lastStop: emitStop(target.lastStop) } : {}; + if (state === SessionState.PAUSED && read?.status === 'changed') { + // The stop changed while the answer was read, and again while it was + // read a second time: the stop it is at now, no landing, and why. + const current = read.current; + return { + success: true, + state, + data: { + sessionId: target.id, + message: explained(`Paused (${current?.reason ?? 'unknown'})`), + ...(current ? { lastStop: emitStop(current.info) } : {}), + note: read.note, + ...tree() + } + }; } - break; - } - const tree = () => describeTreeAnswer(session, this.ctx.descendantsOf(sessionId)); - // Every answer that carries the run's `childrenReleased` says what it means - // (issue #1137): read from the session asked about, as the count is. - const explained = (message: string): string => withReleasedChildren(message, describeReleasedChildren(session)); - // Emit a redacted copy of the stop record (issue #982); the stored record - // is never mutated. - const emitStop = (stop: SessionStopInfo): SessionStopInfo => - this.ctx.redactionEnabled() ? redactStopInfo(stop) : stop; - - const state = target.state; - // Rule 2 of the settle contract: a session that is over by now is - // reported as ended, with the stop that landed during this wait if there - // was one — an exception stop and the exit can arrive in one tick. A stop - // from before the wait is not this wait's to report: the program was - // resumed past it. - const stopDuringWait = - target.lastStop && stopIdOf(target) !== stopBefore.get(target.id) ? { lastStop: emitStop(target.lastStop) } : {}; - if (state === SessionState.PAUSED && read?.status === 'changed') { - // The stop changed while the answer was read, and again while it was - // read a second time: the stop it is at now, no landing, and why. - const current = read.current; - return { - success: true, - state, - data: { - sessionId: target.id, - message: explained(`Paused (${current?.reason ?? 'unknown'})`), - ...(current ? { lastStop: emitStop(current.info) } : {}), - note: ErrorMessages.stopChangedWhileRead(), - ...tree() - } - }; - } - // The stop this answer describes, and the reads made under its pin. A - // target that was not paused when it was read has no landing; if it is - // paused by now, its answer names the stop it is at and nothing more, as - // it always has (one synchronous read, nothing awaited after it). - const pinned = read?.status === 'pinned' ? read : undefined; - const stopAtLanding = pinned ? pinned.pin.stop : stopRecordOf(target); - const landing: StopLanding = pinned?.landing ?? {}; - const snapshot = pinned?.snapshot; - const location = landing.location; - if (state === SessionState.PAUSED && stopAtLanding) { - const where = location ? ` at ${location.file}:${location.line}` : ''; - let waitLanding = landing; - if (stopAtLanding.reason === 'step' && target.lastStepProvenance?.stopId === stopAtLanding.id) { - const prov = target.lastStepProvenance; - const landedOnOriginThread = - landing.stackResult?.threadId === undefined || landing.stackResult.threadId === prov.origin?.threadId; - const candidateHint = - prov.flavor === 'stepInto' - ? this.undeliveredStepFilterHint(target, this.describeStepInFilter(target, target.id)) - : undefined; - const provenanceNote = compareStepOriginAndLanding( - prov.flavor, - landedOnOriginThread ? prov.origin : undefined, - landing.stackResult?.frames ?? [], - { - stepFilterHint: candidateHint, - hasStepperWalkNote: stopAtLanding.info.text !== undefined, - noProgramFrame: landing.noProgramFrame === true + // The stop this answer describes, and the reads made under its pin. A + // target that was not paused when it was read has no landing; if it is + // paused by now, its answer names the stop it is at and nothing more, as + // it always has (one synchronous read, nothing awaited after it). + const pinned = read?.status === 'pinned' ? read : undefined; + const stopAtLanding = pinned ? pinned.pin.stop : stopRecordOf(target); + const landing: StopLanding = pinned?.landing ?? {}; + const snapshot = pinned?.snapshot; + const location = landing.location; + if (state === SessionState.PAUSED && stopAtLanding) { + commitStopSnapshot(snapshot); + const where = location ? ` at ${location.file}:${location.line}` : ''; + let waitLanding = landing; + if (stopAtLanding.reason === 'step' && target.lastStepProvenance?.stopId === stopAtLanding.id) { + const prov = target.lastStepProvenance; + const landedOnOriginThread = + landing.stackResult?.threadId === undefined || landing.stackResult.threadId === prov.origin?.threadId; + const candidateHint = + prov.flavor === 'stepInto' + ? this.undeliveredStepFilterHint(target, this.describeStepInFilter(target, target.id)) + : undefined; + const provenanceNote = compareStepOriginAndLanding( + prov.flavor, + landedOnOriginThread ? prov.origin : undefined, + landing.stackResult?.frames ?? [], + { + stepFilterHint: candidateHint, + hasStepperWalkNote: stopAtLanding.info.text !== undefined, + noProgramFrame: landing.noProgramFrame === true + } + ); + if (provenanceNote) { + this.recordDeliveredStepFilterHint(target, candidateHint, provenanceNote); + waitLanding = { + ...landing, + note: landing.note ? `${landing.note} ${provenanceNote}` : provenanceNote + }; } - ); - if (provenanceNote) { - this.recordDeliveredStepFilterHint(target, candidateHint, provenanceNote); - waitLanding = { - ...landing, - note: landing.note ? `${landing.note} ${provenanceNote}` : provenanceNote - }; } + return { + success: true, + state, + data: { + sessionId: target.id, + message: explained(`Paused (${stopAtLanding.reason})${where}`), + lastStop: emitStop(stopAtLanding.info), + ...landingFields(waitLanding), + ...(snapshot ? { snapshot } : {}), + ...tree() + } + }; } + if (state === SessionState.ERROR) { + const detail = target.lastProxyError ? `: ${target.lastProxyError}` : ''; + const which = target === session ? 'The debug session' : `Child session ${target.id}`; + return { + success: true, + state, + data: { sessionId: target.id, message: explained(`${which} ended in an error state${detail}`), ...stopDuringWait, ...tree() } + }; + } + if (state === SessionState.STOPPED) { + // Only the session itself can be selected already ended (rule 3); a + // selected descendant can also end while its answer is assembled. + // No stop was recorded in this launch: + // the program ran past every breakpoint, and the answer says which — + // the same run-to-completion summary the launch gives when the program + // ends inside its hold (issues #701, #1033); it already joins the + // adapter's reading of the end (issue #877). A program resumed past a + // stop keeps the plain message: its breakpoints were not all missed. + const ranPast = target.lastStop ? undefined : buildRunToCompletionSummary(target); + const outputTail = ranPast ? ranPast.data.outputTail : exitOutputTail(target); + return { + success: true, + state, + data: { + sessionId: target.id, + message: explained(ranPast + ? ranPast.summary + : `${withOutputTailClause(`${describeProgramEnd(target.exitCode)}.`, outputTail)}${target.programEndExplanation?.note ? ` ${target.programEndExplanation.note}` : ''}`), + ...(typeof target.exitCode === 'number' ? { exitCode: target.exitCode } : {}), + ...(outputTail ? { outputTail } : {}), + ...(ranPast?.data ?? {}), + ...(target.programEndExplanation ? { programEnd: target.programEndExplanation } : {}), + ...stopDuringWait, + ...tree() + } + }; + } + this.ctx.logger.info( + `[SessionManager waitForStop] Session ${sessionId} still ${state} after ${waitMs}ms (${settled.outcome}); answering with pending` + ); + // What is armed now words the answer: with something armed, that it stays + // armed; with nothing, no pause is promised. An entry stop is not part of + // it — that belongs to the launch, which is behind a running program. + const arming = describeLaunchArming(session, false); + const pendingClause = state === SessionState.RUNNING + ? buildPendingAttachBreakpointClause(arming, this.runOf(session)) + : undefined; + const inFlightStep = + state === SessionState.RUNNING && session.inFlightStep + ? { + kind: session.inFlightStep.kind, + ageSeconds: Math.max(1, Math.round((Date.now() - session.inFlightStep.sentAt) / 1000)) + } + : undefined; return { success: true, state, data: { - sessionId: target.id, - message: explained(`Paused (${stopAtLanding.reason})${where}`), - lastStop: emitStop(stopAtLanding.info), - ...landingFields(waitLanding), - ...(snapshot ? { snapshot } : {}), - ...tree() - } - }; - } - if (state === SessionState.ERROR) { - const detail = target.lastProxyError ? `: ${target.lastProxyError}` : ''; - const which = target === session ? 'The debug session' : `Child session ${target.id}`; - return { - success: true, - state, - data: { sessionId: target.id, message: explained(`${which} ended in an error state${detail}`), ...stopDuringWait, ...tree() } - }; - } - if (state === SessionState.STOPPED) { - // Only the session itself can be selected already ended (rule 3); a - // selected descendant can also end while its answer is assembled. - // No stop was recorded in this launch: - // the program ran past every breakpoint, and the answer says which — - // the same run-to-completion summary the launch gives when the program - // ends inside its hold (issues #701, #1033); it already joins the - // adapter's reading of the end (issue #877). A program resumed past a - // stop keeps the plain message: its breakpoints were not all missed. - const ranPast = target.lastStop ? undefined : buildRunToCompletionSummary(target); - const outputTail = ranPast ? ranPast.data.outputTail : exitOutputTail(target); - return { - success: true, - state, - data: { - sessionId: target.id, - message: explained(ranPast - ? ranPast.summary - : `${withOutputTailClause(`${describeProgramEnd(target.exitCode)}.`, outputTail)}${target.programEndExplanation?.note ? ` ${target.programEndExplanation.note}` : ''}`), - ...(typeof target.exitCode === 'number' ? { exitCode: target.exitCode } : {}), - ...(outputTail ? { outputTail } : {}), - ...(ranPast?.data ?? {}), - ...(target.programEndExplanation ? { programEnd: target.programEndExplanation } : {}), - ...stopDuringWait, + sessionId: session.id, + message: explained(ErrorMessages.waitForStopPending( + waitMs / 1000, + state === SessionState.INITIALIZING ? 'initializing' : 'running', + { + ...(arming.armed ? { armedSummary: arming.summary } : {}), + ...(arming.loggingSummary ? { loggingSummary: arming.loggingSummary } : {}), + ...(debuggerOffWhy(session) ? { debuggerOffWhy: debuggerOffWhy(session) } : {}), + ...(inFlightStep ? { inFlightStep } : {}), + attachBreakpointClause: pendingClause, + noUncaughtStop: arming.noUncaughtStop + } + )), + pending: true, ...tree() } }; + } finally { + if (!retained) waitBudget.dispose(); } - this.ctx.logger.info( - `[SessionManager waitForStop] Session ${sessionId} still ${state} after ${waitMs}ms (${settled.outcome}); answering with pending` - ); - // What is armed now words the answer: with something armed, that it stays - // armed; with nothing, no pause is promised. An entry stop is not part of - // it — that belongs to the launch, which is behind a running program. - const arming = describeLaunchArming(session, false); - const pendingClause = state === SessionState.RUNNING - ? buildPendingAttachBreakpointClause(arming, this.runOf(session)) - : undefined; - const inFlightStep = - state === SessionState.RUNNING && session.inFlightStep - ? { - kind: session.inFlightStep.kind, - ageSeconds: Math.max(1, Math.round((Date.now() - session.inFlightStep.sentAt) / 1000)) - } - : undefined; - return { - success: true, - state, - data: { - sessionId: session.id, - message: explained(ErrorMessages.waitForStopPending( - waitMs / 1000, - state === SessionState.INITIALIZING ? 'initializing' : 'running', - { - ...(arming.armed ? { armedSummary: arming.summary } : {}), - ...(arming.loggingSummary ? { loggingSummary: arming.loggingSummary } : {}), - ...(debuggerOffWhy(session) ? { debuggerOffWhy: debuggerOffWhy(session) } : {}), - ...(inFlightStep ? { inFlightStep } : {}), - attachBreakpointClause: pendingClause, - noUncaughtStop: arming.noUncaughtStop - } - )), - pending: true, - ...tree() - } - }; } /** @@ -1395,28 +1430,41 @@ export class ExecutionController { sessionId: string, logTag: string, result: DebugResult, - read: StepLandingRead & { pin: StopPin; landing: StopLanding } + read: StepLandingRead & { pin: StopPin; landing: StopLanding }, + budget: Deadline ): Promise> { let answer = result; - let snapshot = await composeStopSnapshot(this.ctx, sessionId, read.landing.stackResult, logTag, { pin: read.pin }); + let deliver = read.deliver; + let snapshot = await composeStopSnapshot(this.ctx, sessionId, read.landing.stackResult, logTag, { pin: read.pin, deadline: budget }); + if (isTerminalSessionState(session.state)) return read.endedAnswer(); + if (session.state !== SessionState.PAUSED) return trackStopAnswerState(result, () => session.state); + if (budget.expired) { + const expired = read.changedAnswer(stopRecordOf(session)); + expired.data!.note = ErrorMessages.stopReadBudgetExpired(budget.budgetMs); + return expired; + } if (pinBroken(session, read.pin)) { if (read.reread) { return read.changedAnswer(stopRecordOf(session)); } this.ctx.logger.info(`[SM ${logTag} ${sessionId}] The stop changed under the step's snapshot; reading the stop now current`); - const again = await readPinnedStop(this.ctx, sessionId, logTag, { rereads: 0 }); + const again = await readPinnedStop(this.ctx, sessionId, logTag, { rereads: 0, deadline: budget }); if (isTerminalSessionState(session.state)) { return read.endedAnswer(); } if (again.status === 'changed') { - return read.changedAnswer(again.current); + const changed = read.changedAnswer(again.current); + changed.data!.note = again.note; + return changed; } const rebuilt = read.answerAgain(again.pin, again.landing); - rebuilt.deliver?.(); + deliver = rebuilt.deliver; answer = rebuilt.result; snapshot = again.snapshot; } - return snapshot && answer.data ? { ...answer, data: { ...answer.data, snapshot } } : answer; + const completed = trackStopAnswerState(snapshot && answer.data ? { ...answer, data: { ...answer.data, snapshot } } : answer, () => session.state); + if (completed.state === SessionState.PAUSED) { commitStopSnapshot(snapshot); deliver?.(); } + return completed; } /** @@ -1431,19 +1479,14 @@ export class ExecutionController { private async readStepOrigin( session: ManagedSession, sessionId: string, - threadId: number + threadId: number, + parent?: Deadline ): Promise { const boundMs = Math.max(1, Math.floor(this.ctx.tunables.stepGraceMs / 5)); const pin = pinStop(session); - let timer: ReturnType | undefined; - const late = new Promise((resolve) => { - timer = setTimeout(() => resolve(undefined), boundMs); - }); + const budget = deadline(boundMs, { parent, label: 'step origin' }); try { - const detailed = await Promise.race([ - this.ctx.getStackTraceDetailed(sessionId, threadId, true, { ensureStackReady: false }), - late - ]); + const detailed = await budget.race(this.ctx.getStackTraceDetailed(sessionId, threadId, true, { ensureStackReady: false, pin, deadline: budget })); if (!detailed) { this.ctx.logger.debug(`[SM step ${sessionId}] Origin stack read exceeded ${boundMs}ms; stepping without it`); return undefined; @@ -1458,9 +1501,7 @@ export class ExecutionController { this.ctx.logger.debug(`[SM step ${sessionId}] Could not read the origin stack before stepping:`, error); return undefined; } finally { - if (timer !== undefined) { - clearTimeout(timer); - } + budget.dispose(); } } @@ -1510,7 +1551,7 @@ export class ExecutionController { rereadFailedOnSameLine = true; break; } - const here = await this.readStepOrigin(session, sessionId, threadId); + const here = await this.readStepOrigin(session, sessionId, threadId, stepOptions.deadline); // Re-check after the read, as the step preamble does: a continue or // another step may have resumed the thread meanwhile. if (session.state !== SessionState.PAUSED) { @@ -1632,7 +1673,10 @@ export class ExecutionController { provenanceNote: string | undefined ): void { if (hint && provenanceNote?.endsWith(hint)) { - (session.run.deliveredStepFilterHints ??= new Set()).add(hint); + const run = session.run; + publishStopEffect(() => { + if (session.run === run) (run.deliveredStepFilterHints ??= new Set()).add(hint); + }, payload => containsStopNote(payload, provenanceNote)); } } diff --git a/src/session/inspection/frame-anchor-resolver.ts b/src/session/inspection/frame-anchor-resolver.ts index 478a22606..de71329c6 100644 --- a/src/session/inspection/frame-anchor-resolver.ts +++ b/src/session/inspection/frame-anchor-resolver.ts @@ -21,7 +21,7 @@ import type { DebugProtocol } from '@vscode/debugprotocol'; import path from 'path'; import type { IProxyManager } from '../../proxy/proxy-manager.js'; import type { ManagedSession } from '../session-store.js'; -import { stopIdOf, stopRecordOf, type StopRecord } from '../stop-record.js'; +import { pinBroken, stopIdOf, stopRecordOf, type StopPin, type StopRecord } from '../stop-record.js'; import { debuggerOffWhy } from '../debugger-off.js'; import { isDapRequestTimeout } from '../dap-request-helpers.js'; import { DapResponseError } from '../../proxy/dap-response-error.js'; @@ -169,6 +169,9 @@ export interface FrameAnchorContext { } export interface ResolveFrameAnchorOptions { + /** The caller's stop owns permission to read and to move its thread anchor. */ + pin?: StopPin; + deadline?: Deadline; /** * The caller's permission to re-anchor, passed by the implicit reads * (the server facade's default stack, locals, evaluate) and never with @@ -221,6 +224,8 @@ export class FrameAnchorResolver { opts?: ResolveFrameAnchorOptions ): Promise { const session = this.ctx.getSession(sessionId); + if (opts?.pin && pinBroken(session, opts.pin)) return emptyResult(); + if (opts?.deadline?.expired) return emptyResult(); const currentThreadId = session.proxyManager?.getCurrentThreadId(); this.ctx.logger.info( `[FrameAnchor ${sessionId}] Requested threadId=${threadId}, currentThreadId=${currentThreadId}, state=${session.state}, includeInternals=${includeInternals}` @@ -250,13 +255,14 @@ export class FrameAnchorResolver { // adoption only apply when the stop they reason about is still current, // by its record's id (stillAtGate). const stopAtGate = session.lastStop; - const gateRecord = stopRecordOf(session); - const stillAtGate = (): boolean => stopIdOf(session) === gateRecord?.id; + const gateRecord = opts?.pin ? opts.pin.stop : stopRecordOf(session); + const stillAtGate = (): boolean => stopIdOf(session) === gateRecord?.id && !opts?.deadline?.expired; const proxyManager = session.proxyManager; const policy = this.ctx.selectPolicy(session.language); try { - let rawFrames = await this.requestRawStackFrames(sessionId, proxyManager, effectiveThreadId); + let rawFrames = await this.requestRawStackFrames(sessionId, proxyManager, effectiveThreadId, { within: opts?.deadline }); + if (opts?.pin && !stillAtGate()) return emptyResult(); let note: string | undefined; let resultThreadId = effectiveThreadId; @@ -268,13 +274,14 @@ export class FrameAnchorResolver { effectiveThreadId, stopAtGate, stillAtGate, - policy + policy, + opts?.deadline ); rawFrames = ready.frames; note = ready.note; resultThreadId = ready.threadId; } else if (rawFrames.length === 0 && typeof threadId === 'number') { - note = await this.describeFramelessThread(sessionId, proxyManager, threadId, policy, stopAtGate?.reason); + note = await this.describeFramelessThread(sessionId, proxyManager, threadId, policy, stopAtGate?.reason, opts?.deadline); } else if ( rawFrames.length > 0 && opts?.ensureStackReady && @@ -299,7 +306,8 @@ export class FrameAnchorResolver { rawFrames, gateRecord, stillAtGate, - policy + policy, + opts?.deadline ); if (adopted) { rawFrames = adopted.frames; @@ -308,6 +316,7 @@ export class FrameAnchorResolver { } } + if (opts?.pin && !stillAtGate()) return emptyResult(); let frames: StackFrame[] = framesOf(rawFrames, policy); const totalFrameCount = frames.length; let allFramesInternal = false; @@ -467,7 +476,8 @@ export class FrameAnchorResolver { threadId: number, stopAtGate: ManagedSession['lastStop'], stillAtGate: () => boolean, - policy: AdapterPolicy + policy: AdapterPolicy, + parent?: Deadline ): Promise<{ frames: DebugProtocol.StackFrame[]; threadId: number; note?: string }> { const { pausedStackReadyTimeoutMs, pausedStackReadyIntervalMs } = this.ctx.tunables; // What an empty paused stack means under this adapter (issue #1132). Where @@ -493,7 +503,8 @@ export class FrameAnchorResolver { policy, pausedStackReadyTimeoutMs, undefined, - pausedStackReadyIntervalMs + pausedStackReadyIntervalMs, + parent ); if (sibling) { return this.adoptFramedSibling(sessionId, session, proxyManager, threadId, stillAtGate, sibling); @@ -506,7 +517,7 @@ export class FrameAnchorResolver { // answered by the window's backstop, the window plus PARENT_GRACE_MS, if // the proxy never answers), and no read or scan starts once it has // closed. So the sentence below that names the window is true. - const readiness = deadline(pausedStackReadyTimeoutMs, { label: `paused stack readiness for session ${sessionId}` }); + const readiness = deadline(pausedStackReadyTimeoutMs, { parent, label: `paused stack readiness for session ${sessionId}` }); try { for (;;) { const slept = await readiness.sleep(pausedStackReadyIntervalMs); @@ -629,7 +640,8 @@ export class FrameAnchorResolver { stoppedFrames: DebugProtocol.StackFrame[], gateRecord: StopRecord | undefined, stillAtGate: () => boolean, - policy: AdapterPolicy + policy: AdapterPolicy, + parent?: Deadline ): Promise<{ frames: DebugProtocol.StackFrame[]; threadId: number; note: string } | undefined> { const remembered = gateRecord ? this.verdicts.get(gateRecord) : undefined; const { verdict, threads } = remembered ?? await this.verdictFor( @@ -638,7 +650,8 @@ export class FrameAnchorResolver { stoppedThreadId, stoppedFrames, policy, - this.ctx.tunables.pausedStackReadyTimeoutMs + this.ctx.tunables.pausedStackReadyTimeoutMs, + undefined, undefined, parent ); if (!remembered && gateRecord) { // Kept whatever the outcome: a scan cut short by its budget or by @@ -752,9 +765,10 @@ export class FrameAnchorResolver { proxyManager: IProxyManager, threadId: number, policy: AdapterPolicy, - stopReason: string | undefined + stopReason: string | undefined, + within?: Deadline ): Promise { - const threads = await this.listThreadsForScan(sessionId, proxyManager) ?? []; + const threads = await this.listThreadsForScan(sessionId, proxyManager, within) ?? []; const label = (id: number, name?: string): string => name ? `${id} (${name})` : String(id); const requested = label(threadId, threads.find((thread) => thread?.id === threadId)?.name); const alternative = await this.scanSiblings( @@ -763,7 +777,7 @@ export class FrameAnchorResolver { threadId, policy, this.ctx.tunables.pausedStackReadyTimeoutMs, - threads + threads, undefined, within ); if (alternative) { return ( diff --git a/src/session/inspection/pinned-stop-read.ts b/src/session/inspection/pinned-stop-read.ts index 016a274ff..585bc6085 100644 --- a/src/session/inspection/pinned-stop-read.ts +++ b/src/session/inspection/pinned-stop-read.ts @@ -1,47 +1,20 @@ -/** - * Pins (tracking issue #1362, stage "stop record"; issue #1348): an answer - * that describes a stop takes that stop's identity before its first await and - * checks every read it makes against it, so no answer carries one stop's - * location and another's reason. - * - * The rule, in `readPinnedStop`: - * - * 1. The pin is the session's stop record, taken synchronously - * (`pinStop`, src/session/stop-record.ts). - * 2. The reads are made under it: the landing (`describeStopLocation`, which - * reads the stop it is handed, never the session's), the snapshot - * (`composeStopSnapshot`, whose exception, diff base and locals check are - * the pinned stop's), and whatever the caller adds (`alsoAwait`). - * 3. If the session is paused at another stop when they end (`pinBroken`), - * all of them are made again once, under a pin of that stop. - * 4. If it changed again, the read is `changed`: the stop the session is at - * now, and no landing. The caller gives that stop's reason and state and - * says that the stop changed while it was being read - * (`ErrorMessages.stopChangedWhileRead`). - * - * A session that is not paused when the reads end is the caller's to answer, - * as it always was (an ending reported as ended, a resumed program as - * running): the reads it gets back describe the pinned stop, and nothing else - * in its answer may be taken from the session's stop. "Changed" means another - * stop record, not a resume: a stop is never applied twice and an id is never - * reused, so equal ids are the same stop. - * - * The answer's own fields come from the pin (`read.pin.stop`), never from - * `session.lastStop` read after the reads. The tool handlers then read the - * source line and the stale-build note from the answer's `location` alone; - * they read nothing of the session's stop. - */ -import { SessionState } from '@debugmcp/shared'; +/** Read a stop under one identity and one deadline, with at most one re-read. */ +import { deadline, SessionState, type Deadline } from '@debugmcp/shared'; import type { ManagedSession } from '../session-store.js'; import { pinBroken, pinStop, stopRecordOf, type StopPin, type StopRecord } from '../stop-record.js'; import type { StopSnapshot } from '../session-manager-core.js'; import { describeStopLocation, type StopLanding, type StopLandingContext } from './stop-location.js'; -import { composeStopSnapshot, type ComposeSnapshotOptions, type StopSnapshotContext } from './stop-snapshot.js'; +import { commitStopSnapshot, composeStopSnapshot, type ComposeSnapshotOptions, type StopSnapshotContext } from './stop-snapshot.js'; +import { enrichPinnedStop, retainStopAnswerDeadline, trackStopAnswerState } from './stop-answer-effects.js'; import { ErrorMessages } from '../../utils/error-messages.js'; export type PinnedStopReadContext = StopLandingContext & StopSnapshotContext; +/** The old landing ceiling (30s DAP plus the proxy margin), shared by all reads and the retry. */ +export const STOP_READ_BUDGET_MS = 35_000; + export interface PinnedStopReadOptions { + readonly deadline?: Deadline; /** The pin, when the caller took it earlier (before an await of its own). */ readonly pin?: StopPin; /** Compose the snapshot behind the landing (the default); `false` reads the landing alone. */ @@ -71,6 +44,7 @@ export type PinnedStopRead = readonly status: 'changed'; /** The stop the session is at now, which no read describes. */ readonly current: StopRecord | undefined; + readonly note: string; }; function sessionOrUndefined(ctx: Pick, sessionId: string): ManagedSession | undefined { @@ -94,47 +68,61 @@ export async function readPinnedStop( logTag: string, opts: PinnedStopReadOptions = {} ): Promise { - // Taken before the first await, unless the caller took it earlier still. let pin = opts.pin ?? pinSession(ctx, sessionId); - const readUnder = async (under: StopPin): Promise<{ landing: StopLanding; snapshot: StopSnapshot | undefined }> => { - const landing = await describeStopLocation(ctx, sessionId, logTag, under); + const budget = opts.deadline ?? deadline(STOP_READ_BUDGET_MS, { label: 'stop answer' }); + const retained = !opts.deadline && retainStopAnswerDeadline(budget); + const changed = (expired = false): PinnedStopRead => ({ + status: 'changed', current: stopRecordOf(sessionOrUndefined(ctx, sessionId)), + note: expired ? ErrorMessages.stopReadBudgetExpired(budget.budgetMs) : ErrorMessages.stopChangedWhileRead() + }); + const readUnder = async (under: StopPin) => { + const landing = await describeStopLocation(ctx, sessionId, logTag, under, budget); let snapshot: StopSnapshot | undefined; - const endedUnderLanding = opts.skipSnapshotWhenEnded === true && - isTerminal(sessionOrUndefined(ctx, sessionId)?.state); - if (opts.snapshot !== false && !endedUnderLanding) { - snapshot = await composeStopSnapshot(ctx, sessionId, landing.stackResult, logTag, { ...(opts.snapshot ?? {}), pin: under }); + const session = sessionOrUndefined(ctx, sessionId); + if (!pinBroken(session, under) && session?.state === SessionState.PAUSED && opts.snapshot !== false && !budget.expired) { + snapshot = await composeStopSnapshot(ctx, sessionId, landing.stackResult, logTag, { + ...(opts.snapshot ?? {}), pin: under, deadline: budget + }); + } + if (landing.location && !pinBroken(sessionOrUndefined(ctx, sessionId), under) && !budget.expired) { + await enrichPinnedStop(sessionId, landing.location, budget); } - await opts.alsoAwait?.(); + if (opts.alsoAwait && !budget.expired) await budget.race(opts.alsoAwait()); return { landing, snapshot }; }; - let read = await readUnder(pin); - let reread = false; - if ((opts.rereads ?? 1) > 0 && pinBroken(sessionOrUndefined(ctx, sessionId), pin)) { - ctx.logger.info(`[SessionManager ${logTag} ${sessionId}] The stop changed while its answer was read; reading the stop now current`); - pin = pinSession(ctx, sessionId); - read = await readUnder(pin); - reread = true; - } - const session = sessionOrUndefined(ctx, sessionId); - if (pinBroken(session, pin)) { - ctx.logger.info(`[SessionManager ${logTag} ${sessionId}] The stop changed again while its answer was read; answering without a landing`); - return { status: 'changed', current: stopRecordOf(session) }; + try { + if (budget.expired) return changed(true); + let read = await readUnder(pin); + let reread = false; + if (budget.expired) return changed(true); + if (pinBroken(sessionOrUndefined(ctx, sessionId), pin)) { + if ((opts.rereads ?? 1) === 0 || sessionOrUndefined(ctx, sessionId)?.state !== SessionState.PAUSED) return changed(); + ctx.logger.info(`[SessionManager ${logTag} ${sessionId}] The stop changed while its answer was read; reading the stop now current`); + pin = pinSession(ctx, sessionId); + if (budget.expired) return changed(true); + read = await readUnder(pin); + reread = true; + } + if (budget.expired) return changed(true); + if (pinBroken(sessionOrUndefined(ctx, sessionId), pin)) return changed(); + return { status: 'pinned', pin, landing: read.landing, snapshot: read.snapshot, reread }; + } catch (error) { + if (budget.expired) return changed(true); + throw error; + } finally { + if (!opts.deadline && !retained) budget.dispose(); } - return { status: 'pinned', pin, landing: read.landing, snapshot: read.snapshot, reread }; } -function isTerminal(state: SessionState | undefined): boolean { - return state === SessionState.STOPPED || state === SessionState.ERROR; -} /** What an answer takes from a pinned read (or from none, for a session that was not paused). */ export interface DescribedStop { - /** The stop the answer names: the pin's, or, when the stop changed twice, the one current now. */ + /** The stop the answer names: the accepted pin's, or the current record when reads were omitted. */ readonly stop: StopRecord | undefined; - /** The landing read under the pin; empty when there was no read or the stop changed twice. */ + /** The accepted landing; empty when there was no read, identity failed or the budget expired. */ readonly landing: StopLanding; readonly snapshot: StopSnapshot | undefined; - /** The sentence for a stop that changed twice while it was read; absent otherwise. */ + /** Why the landing and snapshot were omitted after an invalid or expired read. */ readonly note?: string; } @@ -144,7 +132,16 @@ export function describedStop(read: PinnedStopRead | undefined): DescribedStop { return { stop: undefined, landing: {}, snapshot: undefined }; } if (read.status === 'changed') { - return { stop: read.current, landing: {}, snapshot: undefined, note: ErrorMessages.stopChangedWhileRead() }; + return { stop: read.current, landing: {}, snapshot: undefined, note: read.note }; } return { stop: read.pin.stop, landing: read.landing, snapshot: read.snapshot }; } + +/** Select the caller's final state before publishing any snapshot in its answer. */ +export function completeStopAnswer(answer: T, state: () => SessionState | undefined): T { + trackStopAnswerState(answer, state); + const root = answer as { snapshot?: StopSnapshot; data?: { snapshot?: StopSnapshot; pausedChild?: { snapshot?: StopSnapshot } } }; + commitStopSnapshot(root.snapshot ?? root.data?.snapshot); + commitStopSnapshot(root.data?.pausedChild?.snapshot); + return answer; +} diff --git a/src/session/inspection/stop-answer-effects.ts b/src/session/inspection/stop-answer-effects.ts new file mode 100644 index 000000000..bd525f6c2 --- /dev/null +++ b/src/session/inspection/stop-answer-effects.ts @@ -0,0 +1,145 @@ +/** + * An observation is published only with the answer that contains it. The MCP + * scope spans source/footprint enrichment too; direct SessionManager callers + * publish at their return boundary. Scopes are per async call, never per session. + */ +import { AsyncLocalStorage } from 'node:async_hooks'; +import { SessionState, type Deadline } from '@debugmcp/shared'; +import { ErrorMessages } from '../../utils/error-messages.js'; + +interface Publication { shown: (payload: unknown) => boolean; commit: () => void } +interface EnrichmentLocation { file: string; line: number; unresolvedSource?: boolean } +export interface StopEnrichment { + context?: { lineContent: string; surrounding: Array<{ line: number; content: string }> }; + staleBuild?: string; +} +type EnrichStop = (sessionId: string, location: EnrichmentLocation) => Promise; +interface AnswerScope { publications: Publication[]; deadlines: Deadline[]; enrich?: EnrichStop } +const scopes = new AsyncLocalStorage(); +const refreshers = new WeakMap void>(); +const managerAnswers = new WeakSet(); +const enrichments = new WeakMap(); + +/** Lets handlers recognize manager answers even after the session was removed. */ +export function isTrackedStopAnswer(value: unknown): boolean { + return typeof value === 'object' && value !== null && managerAnswers.has(value); +} + +export async function withStopAnswerEffects(work: () => Promise, enrich?: EnrichStop): Promise { + const scope: AnswerScope = { publications: [], deadlines: [], enrich }; + return scopes.run(scope, async () => { + try { return await work(); } + finally { for (const budget of scope.deadlines) budget.dispose(); } + }); +} + +/** True when the tool scope owns disposal; otherwise the reader uses finally. */ +export function retainStopAnswerDeadline(budget: Deadline): boolean { + const scope = scopes.getStore(); + if (!scope) return false; + if (!scope.deadlines.includes(budget)) scope.deadlines.push(budget); + return true; +} + +export function stopAnswerDeadline(): Deadline | undefined { return scopes.getStore()?.deadlines[0]; } + +/** Called inside the pinned transaction, so its caller checks identity afterwards. */ +export async function enrichPinnedStop(sessionId: string, location: EnrichmentLocation, budget: Deadline): Promise { + const enrich = scopes.getStore()?.enrich; + if (!enrich || budget.expired) return; + const result = await budget.race(enrich(sessionId, location)); + enrichments.set(location, result); +} + +export function stopEnrichmentFor(location: object): StopEnrichment | undefined { return enrichments.get(location); } + +/** Source/build reads belong to the same answer budget as its debugger reads. */ +export async function readStopEnrichment(work: () => Promise, answer: Record): Promise { + const budget = stopAnswerDeadline(); + try { return budget ? await budget.request(work) : await work(); } + catch (error) { + if (!budget?.expired) throw error; + const data = answer.data && typeof answer.data === 'object' ? answer.data as Record : undefined; + for (const part of [answer, data]) { + if (!part) continue; + for (const field of ['location', 'context', 'snapshot', 'threadId']) delete part[field]; + part.note = ErrorMessages.stopReadBudgetExpired(budget.budgetMs); + } + return undefined; + } +} + +function visit(value: unknown, action: (value: object) => void, seen = new Set()): void { + if (!value || typeof value !== 'object' || seen.has(value)) return; + seen.add(value); + action(value); + for (const child of Object.values(value)) visit(child, action, seen); +} + +export function publishStopEffect(commit: () => void, shown: (payload: unknown) => boolean): void { + const scope = scopes.getStore(); + if (scope) scope.publications.push({ commit, shown }); + else commit(); +} + +export function containsStopValue(payload: unknown, value: object): boolean { + let found = false; + visit(payload, item => { found ||= item === value; }); + return found; +} + +export function containsStopNote(payload: unknown, note: string): boolean { + let found = false; + visit(payload, item => { + const text = (item as { note?: unknown }).note; + found ||= typeof text === 'string' && text.includes(note); + }); + return found; +} + +/** Re-read state after the handler's own awaits, immediately before serialization. */ +export function refreshStopAnswer(payload: unknown): void { + visit(payload, item => refreshers.get(item)?.()); +} + +export function beforeStopAnswerReturn(answer: object, refresh: () => void): void { + const previous = refreshers.get(answer); + refreshers.set(answer, () => { previous?.(); refresh(); }); +} + +export function publishReturnedStopEffects(payload: unknown): void { + const scope = scopes.getStore(); + if (!scope) return; + for (const publication of scope.publications.splice(0)) if (publication.shown(payload)) publication.commit(); +} + +const STOP_FIELDS = ['location', 'context', 'snapshot', 'threadId', 'note', 'reason', 'stopReason', 'rawStopReason', 'lastStop']; +export function trackStopAnswerState(answer: T, state: () => SessionState | undefined): T { + managerAnswers.add(answer); + const data = (answer as { data?: unknown }).data; + if (data && typeof data === 'object') managerAnswers.add(data); + const refresh = () => { + const record = answer as Record; + const current = state() ?? SessionState.STOPPED; + if (record.state === undefined) return; + const data = record.data && typeof record.data === 'object' ? record.data as Record : undefined; + const invalidLanding = current !== SessionState.PAUSED && [record, data].some(part => part && (part.location || part.snapshot || part.context)); + if (record.state === current && !invalidLanding) return; + // This is an outbound projection, never a ManagedSession state write. + Object.assign(record, { state: current }); + for (const part of [record, data]) { + if (!part) continue; + for (const field of STOP_FIELDS) delete part[field]; + part.message = current === SessionState.RUNNING + ? 'The program resumed while this answer was being read.' + : current === SessionState.PAUSED + ? 'The program paused while this answer was being read. Call get_stack_trace to read the stop.' + : 'The session ended while this answer was being read.'; + if (current !== SessionState.RUNNING) delete part.pending; + if ('stopOnEntrySuccessful' in part && current !== SessionState.PAUSED) part.stopOnEntrySuccessful = false; + } + }; + refresh(); + refreshers.set(answer, refresh); + return answer; +} diff --git a/src/session/inspection/stop-location.ts b/src/session/inspection/stop-location.ts index 54d3b93e7..7c6d4c457 100644 --- a/src/session/inspection/stop-location.ts +++ b/src/session/inspection/stop-location.ts @@ -7,14 +7,14 @@ * that explains a switch — instead of the top frame alone, which used to be * copied three times and knew nothing (issues #898/#900). */ -import { SessionState } from '@debugmcp/shared'; +import { SessionState, type Deadline } from '@debugmcp/shared'; import type { OperationsContext } from '../operations-context.js'; import type { StopLandingFields } from '../session-manager-core.js'; import type { StackTraceResult } from './frame-anchor-resolver.js'; import { hasPausingBreakpoint } from '../launch/launch-arming.js'; import { ErrorMessages } from '../../utils/error-messages.js'; import { isProgramNeutralStopReason } from './stop-anchor.js'; -import type { StopPin } from '../stop-record.js'; +import { pinBroken, type StopPin } from '../stop-record.js'; /** * The landing as read: the answer's fields (`StopLandingFields`) plus the @@ -42,24 +42,35 @@ export type StopLandingContext = Pick { try { // A brief settle after the stopped event, as every reader here always had. - await new Promise((resolve) => setTimeout(resolve, 10)); + if (budget) { + if (await budget.sleep(10) === 'expired') return {}; + } else { + await new Promise((resolve) => setTimeout(resolve, 10)); + } + if (pin && pinBroken(ctx.getSession(sessionId), pin)) return {}; const stop = pin ? pin.stop?.info : ctx.getSession(sessionId).lastStop; + const options = { ...(pin ? { pin } : {}), ...(budget ? { deadline: budget } : {}) }; const result = isProgramNeutralStopReason(stop?.reason) - ? await ctx.getStackTraceDetailed(sessionId, undefined, false, { ensureStackReady: true }) - : await ctx.getStackTraceDetailed(sessionId); + ? await ctx.getStackTraceDetailed(sessionId, undefined, false, { ...options, ensureStackReady: true }) + : pin || budget + ? await ctx.getStackTraceDetailed(sessionId, undefined, false, options) + : await ctx.getStackTraceDetailed(sessionId); + if (pin && pinBroken(ctx.getSession(sessionId), pin)) return {}; + if (budget?.expired) return {}; const top = result.frames[0]; const landing: StopLanding = { stackResult: result }; // The frames read are the landing even if the session left PAUSED under diff --git a/src/session/inspection/stop-snapshot.ts b/src/session/inspection/stop-snapshot.ts index be974f63c..3be882cef 100644 --- a/src/session/inspection/stop-snapshot.ts +++ b/src/session/inspection/stop-snapshot.ts @@ -15,12 +15,13 @@ * - never fail the answer: any throw degrades to no snapshot, debug-logged * (the describeStopLocation pattern). */ -import { SessionState, redactStopInfo } from '@debugmcp/shared'; +import { deadline, SessionState, redactStopInfo, type Deadline } from '@debugmcp/shared'; +import { containsStopValue, publishStopEffect } from './stop-answer-effects.js'; import type { OperationsContext } from '../operations-context.js'; import type { ChangedVariable, SnapshotException, StopSnapshot } from '../session-manager-core.js'; import type { StackTraceResult } from './frame-anchor-resolver.js'; import { frameSummary } from './frame-anchor-resolver.js'; -import { pinHolds, pinStop, type StopPin } from '../stop-record.js'; +import { pinBroken, pinHolds, pinStop, type StopPin } from '../stop-record.js'; import { applyVariableCaps, snapshotLocalsLimits } from '../variable-caps.js'; import { buildSnapshotFrameKey, @@ -54,6 +55,18 @@ export interface ComposeSnapshotOptions { * the session's stop when the compose begins is pinned. */ pin?: StopPin; + deadline?: Deadline; +} + +const pendingBaselines = new WeakMap void>(); + +/** Called only for the snapshot selected for return, never a discarded attempt. */ +export function commitStopSnapshot(snapshot: StopSnapshot | undefined): void { + if (!snapshot) return; + const commit = pendingBaselines.get(snapshot); + if (!commit) return; + pendingBaselines.delete(snapshot); + publishStopEffect(commit, payload => containsStopValue(payload, snapshot)); } /** How many frames the snapshot shows, and how deep its locals read probes. */ @@ -173,8 +186,11 @@ export async function composeStopSnapshot( return undefined; } const pin = opts.pin ?? pinStop(session); + if (pinBroken(session, pin) || opts.deadline?.expired) return undefined; const stop = pin.stop?.info; const stopId = pin.stop?.id; + const run = session.run; + const generation = session.proxyGeneration; if (stop?.reason === 'entry') { // Locals at an entry stop are module scaffolding, not state worth paying for. return undefined; @@ -248,22 +264,18 @@ export async function composeStopSnapshot( // and the walk-down (#468) exists exactly for that. A stack with no // program frame at all is caught by noProgramFrame above. const timeoutMs = ctx.tunables.snapshotLocalsTimeoutMs; - let timer: NodeJS.Timeout | undefined; + const localsBudget = deadline(timeoutMs, { parent: opts.deadline, label: 'stop snapshot locals' }); try { // Failure folds into a sentinel so a read that loses the race can // never surface later as an unhandled rejection. - const guardedRead = ctx - .extractLocalsFromResolved(sessionId, stackResult, { maxFrames: SNAPSHOT_FRAMES }) - .catch((error: unknown): typeof FAILED => { - ctx.logger.debug(`[SessionManager ${logTag} ${sessionId}] Snapshot locals read failed:`, error); - return FAILED; - }); - const raced = await Promise.race([ - guardedRead, - new Promise((resolve) => { - timer = setTimeout(() => resolve(TIMED_OUT), timeoutMs); - }) - ]); + const raced = await localsBudget.race(ctx.extractLocalsFromResolved( + sessionId, stackResult, { maxFrames: SNAPSHOT_FRAMES, deadline: localsBudget, pin } + )).catch((error: unknown): typeof FAILED | typeof TIMED_OUT => { + if (localsBudget.expired) return TIMED_OUT; + ctx.logger.debug(`[SessionManager ${logTag} ${sessionId}] Snapshot locals read failed:`, error); + return FAILED; + }); + if (pinBroken(ctx.getSession(sessionId), pin) || ctx.getSession(sessionId).state !== SessionState.PAUSED) return undefined; if (raced === TIMED_OUT) { notes.push( `locals omitted: the locals read exceeded ${timeoutMs}ms; get_local_variables reads them` @@ -336,13 +348,18 @@ export async function composeStopSnapshot( const brokenCallerUnwind = !callerResolved || base?.callerResolved === false; if (stopId !== undefined && base && base.stopId === stopId) { snapshot.locals = flat; - } else if (stopId !== undefined && base && base.frameKey === frameKey && !stepOutSameFn && !brokenCallerUnwind) { - snapshot.changedVariables = diffLocals(base, flat, complete); - session.snapshotDiffBase = { stopId, frameKey, rendered: flat, complete, callerResolved }; } else { - snapshot.locals = flat; + if (stopId !== undefined && base && base.frameKey === frameKey && !stepOutSameFn && !brokenCallerUnwind) { + snapshot.changedVariables = diffLocals(base, flat, complete); + } else { + snapshot.locals = flat; + } if (stopId !== undefined) { - session.snapshotDiffBase = { stopId, frameKey, rendered: flat, complete, callerResolved }; + pendingBaselines.set(snapshot, () => { + if (session.run === run && session.proxyGeneration === generation) { + session.snapshotDiffBase = { stopId, frameKey, rendered: flat, complete, callerResolved }; + } + }); } } } @@ -364,9 +381,7 @@ export async function composeStopSnapshot( } } } finally { - if (timer !== undefined) { - clearTimeout(timer); - } + localsBudget.dispose(); } } diff --git a/src/session/launch/debug-launcher.ts b/src/session/launch/debug-launcher.ts index cedb40136..fabb43246 100644 --- a/src/session/launch/debug-launcher.ts +++ b/src/session/launch/debug-launcher.ts @@ -35,7 +35,7 @@ import type { CustomLaunchRequestArguments, DebugResult, LaunchResultData, Pause import type { ManagedSession, ToolchainValidationState } from '../session-store.js'; import type { LaunchContext } from '../operations-context.js'; import { landingFields } from '../inspection/stop-location.js'; -import { describedStop, readPinnedStop } from '../inspection/pinned-stop-read.js'; +import { completeStopAnswer, describedStop, readPinnedStop } from '../inspection/pinned-stop-read.js'; import { describeReleasedChildren, describeTreeAnswer, selectSettledInTree, withReleasedChildren } from '../execution/tree-settle.js'; import type { BreakpointController, ResyncOutcome } from '../breakpoints/breakpoint-controller.js'; import { reresolveAnchors, type AnchorResolution } from '../breakpoints/anchor-resolution.js'; @@ -669,7 +669,7 @@ export class DebugLauncher { // Re-fetch session to get the most up-to-date state const finalSession = this.ctx.getSession(sessionId); - const finalState = finalSession.state; + let finalState = finalSession.state; // Readiness resolves on terminal events as well as a usable debugger. // Do not turn an adapter/proxy crash into a successful start merely @@ -755,10 +755,11 @@ export class DebugLauncher { // stop that changed before any of the answer's reads began (measured // on the JDI bridge, which reports one stop per breakpoint request at // a location, a millisecond apart). - const described = describedStop(finalState === SessionState.PAUSED + const described = describedStop(finalSession.state === SessionState.PAUSED ? await readPinnedStop(this.ctx, sessionId, 'launch') : undefined); - const { landing, snapshot } = described; + finalState = finalSession.state; + const { landing, snapshot } = finalState === SessionState.PAUSED ? described : describedStop(undefined); // The policy's word is a static pin; a stop that arrived anyway is the // stronger evidence (an adapter build that ignores the flag after all): @@ -892,7 +893,7 @@ export class DebugLauncher { } } - return { + return completeStopAnswer({ success: true, state: finalState, data: { @@ -921,7 +922,7 @@ export class DebugLauncher { : undefined, stopOnEntrySuccessful: !!effectiveLaunchArgs?.stopOnEntry && finalState === SessionState.PAUSED, ...landingFields(landing), - ...(described.note ? { note: described.note } : {}), + ...(finalState === SessionState.PAUSED && described.note ? { note: described.note } : {}), ...(snapshot ? { snapshot } : {}), // The session tree (issue #1081): the children adopted during the // hold, the run's released count, any already-paused child snapshot @@ -930,7 +931,7 @@ export class DebugLauncher { ...(pausedChild ? { pausedChild } : {}), ...(childrenClosed > 0 ? { childrenClosed } : {}), }, - }; + }, () => finalSession.state); } catch (error) { const diagnosticData = await failProxySetup(this.ctx, session, error, 'startDebugging'); session.failureDiagnostics = Object.keys(diagnosticData).length > 0 @@ -1187,13 +1188,14 @@ export class DebugLauncher { holdMs: this.ctx.tunables.launchHoldMs, }); const finalSession = this.ctx.getSession(sessionId); - const finalState = finalSession.state; + let finalState = finalSession.state; // The landing and snapshot of a paused restart, under a pin of its stop // taken before the read's first await (tracking issue #1362). - const described = describedStop(finalState === SessionState.PAUSED + const described = describedStop(finalSession.state === SessionState.PAUSED ? await readPinnedStop(this.ctx, sessionId, 'launch') : undefined); - const { landing, snapshot } = described; + finalState = finalSession.state; + const { landing, snapshot } = finalState === SessionState.PAUSED ? described : describedStop(undefined); const runToCompletion = finalState === SessionState.STOPPED ? buildRunToCompletionSummary(finalSession) : undefined; @@ -1212,7 +1214,7 @@ export class DebugLauncher { const warning = anchorWarnings(anchorResolution); this.ctx.logger.info(`[SessionManager] Hot restart of session ${sessionId} answered. State: ${finalState}`); - return { + return completeStopAnswer({ success: true, state: finalState, data: { @@ -1230,12 +1232,12 @@ export class DebugLauncher { ...(runToCompletion?.data ?? {}), reason: finalState === SessionState.PAUSED ? described.stop?.reason ?? 'unknown' : undefined, ...landingFields(landing), - ...(described.note ? { note: described.note } : {}), + ...(finalState === SessionState.PAUSED && described.note ? { note: described.note } : {}), ...(snapshot ? { snapshot } : {}), // A hot restart keeps the process and its children (issue #1081). ...describeTreeAnswer(finalSession, this.ctx.descendantsOf(sessionId)), }, - }; + }, () => finalSession.state); } /** diff --git a/src/session/live-update/live-update-controller.ts b/src/session/live-update/live-update-controller.ts index 2c683ed3e..864ffe7bf 100644 --- a/src/session/live-update/live-update-controller.ts +++ b/src/session/live-update/live-update-controller.ts @@ -24,7 +24,7 @@ import type { ManagedSession } from '../session-store.js'; import type { LaunchContext } from '../operations-context.js'; import { waitForSessionState } from '../execution/session-state-wait.js'; import { landingFields } from '../inspection/stop-location.js'; -import { describedStop, readPinnedStop } from '../inspection/pinned-stop-read.js'; +import { completeStopAnswer, describedStop, readPinnedStop } from '../inspection/pinned-stop-read.js'; /** What a live update touches: the adapter's answer, the anchors, the session's stop. */ export type LiveUpdateContext = LaunchContext; @@ -120,12 +120,13 @@ export class LiveUpdateController { const current = this.ctx.getSession(sessionId); const after = await this.afterUpdate(current, live, first.kind === 'response' ? first.response : undefined); const body = first.kind === 'response' ? ((first.response?.body ?? {}) as Record) : {}; - return { + const observed = await this.describeState(current, first.kind !== 'response'); + return completeStopAnswer({ success: true, ...body, ...after, - ...(await this.describeState(current, first.kind !== 'response')), - }; + ...observed, + }, () => current.state); } /** The plain path: await the response and answer it, with the anchor pass when code changed. */ @@ -149,7 +150,7 @@ export class LiveUpdateController { ...body, ...after, state: this.ctx.getSession(sessionId).state, - ...(reloadWhilePaused + ...(reloadWhilePaused && this.ctx.getSession(sessionId).state === SessionState.PAUSED ? { note: 'The program is paused: the reloaded code runs when it resumes (continue_execution). A breakpoint the reassemble reaches is then reported as a stop.' } : {}), }; diff --git a/src/session/operations-context.ts b/src/session/operations-context.ts index 23881a394..7b087e173 100644 --- a/src/session/operations-context.ts +++ b/src/session/operations-context.ts @@ -1,3 +1,6 @@ +import type { StopPin } from './stop-record.js'; +import type { Deadline } from '@debugmcp/shared'; +import type { ResolveFrameAnchorOptions } from './inspection/frame-anchor-resolver.js'; /** * The seam between `SessionManagerOperations` and the collaborators the debug * operations are split across. @@ -173,7 +176,7 @@ export interface OperationsContext { sessionId: string, threadId?: number, includeInternals?: boolean, - opts?: { ensureStackReady?: boolean } + opts?: ResolveFrameAnchorOptions ): Promise; /** * The locals pipeline behind an already-resolved stack (issue #982): the @@ -182,7 +185,7 @@ export interface OperationsContext { extractLocalsFromResolved( sessionId: string, stackResult: StackTraceResult, - opts?: { includeSpecial?: boolean; names?: string[]; maxFrames?: number } + opts?: { includeSpecial?: boolean; names?: string[]; maxFrames?: number; deadline?: Deadline; pin?: StopPin } ): Promise; redactionEnabled(): boolean; /** Stop-snapshot switch (issue #982): DEBUG_MCP_NO_SNAPSHOT opts out. */ diff --git a/src/session/session-manager-data.ts b/src/session/session-manager-data.ts index 176cc03c9..93a8d3727 100644 --- a/src/session/session-manager-data.ts +++ b/src/session/session-manager-data.ts @@ -1,3 +1,6 @@ +import { pinBroken, type StopPin } from './stop-record.js'; +import type { Deadline } from '@debugmcp/shared'; +import type { ResolveFrameAnchorOptions } from './inspection/frame-anchor-resolver.js'; /** * Data retrieval operations for session management including variables, * stack traces, and scopes. @@ -168,13 +171,14 @@ export abstract class SessionManagerData extends SessionManagerCore { * `truncation` reports what was cut, so the tool layer can annotate the * response instead of blowing a client's per-result size limit. */ - async getVariablesDetailed(sessionId: string, variablesReference: number, names?: string[]): Promise<{ + async getVariablesDetailed(sessionId: string, variablesReference: number, names?: string[], budget?: Deadline, pin?: StopPin): Promise<{ variables: Variable[]; truncation?: VariableTruncationSummary; /** Internal observation status: a failed read is not an empty scope. */ readFailed?: true; }> { const session = this._getSessionById(sessionId); + if ((pin && pinBroken(session, pin)) || budget?.expired) return { variables: [], readFailed: true }; this.logger.info(`[SM getVariables ${sessionId}] Entered. variablesReference: ${variablesReference}, Current state: ${session.state}`); if (!session.proxyManager || !session.proxyManager.isRunning()) { @@ -188,7 +192,10 @@ export abstract class SessionManagerData extends SessionManagerCore { try { this.logger.info(`[SM getVariables ${sessionId}] Sending DAP 'variables' for variablesReference ${variablesReference}.`); - const response = await session.proxyManager.sendDapRequest('variables', { variablesReference }); + const response = budget + ? await session.proxyManager.sendDapRequest('variables', { variablesReference }, { deadline: budget }) + : await session.proxyManager.sendDapRequest('variables', { variablesReference }); + if (pin && pinBroken(session, pin)) return { variables: [], readFailed: true }; // Count only — the raw body carries unredacted values (issue #237); the // parsed (post-redaction) values are logged below. this.logger.info(`[SM getVariables ${sessionId}] DAP 'variables' response received. ${response?.body?.variables?.length ?? 0} variable(s).`); @@ -258,7 +265,7 @@ export abstract class SessionManagerData extends SessionManagerCore { sessionId: string, threadId?: number, includeInternals: boolean = false, - opts?: { ensureStackReady?: boolean } + opts?: ResolveFrameAnchorOptions ): Promise { return this.frameAnchorResolver.resolve(sessionId, threadId, includeInternals, opts); } @@ -268,19 +275,22 @@ export abstract class SessionManagerData extends SessionManagerCore { } /** Internal frame-walk probe: an unsupported/frameless candidate is expected. */ - private async probeScopes(sessionId: string, frameId: number): Promise<{ + private async probeScopes(sessionId: string, frameId: number, budget?: Deadline, pin?: StopPin): Promise<{ scopes: DebugProtocol.Scope[]; readFailed?: true; }> { - return this.readScopes(sessionId, frameId, 'probe'); + return this.readScopes(sessionId, frameId, 'probe', budget, pin); } private async readScopes( sessionId: string, frameId: number, - purpose: 'public' | 'probe' + purpose: 'public' | 'probe', + budget?: Deadline, + pin?: StopPin ): Promise<{ scopes: DebugProtocol.Scope[]; readFailed?: true }> { const session = this._getSessionById(sessionId); + if ((pin && pinBroken(session, pin)) || budget?.expired) return { scopes: [], readFailed: true }; const prefix = purpose === 'public' ? 'getScopes' : 'scopeProbe'; this.logger.info(`[SM ${prefix} ${sessionId}] Entered. frameId: ${frameId}, Current state: ${session.state}`); @@ -295,7 +305,10 @@ export abstract class SessionManagerData extends SessionManagerCore { try { this.logger.info(`[SM ${prefix} ${sessionId}] Sending DAP 'scopes' for frameId ${frameId}.`); - const response = await session.proxyManager.sendDapRequest('scopes', { frameId }); + const response = budget + ? await session.proxyManager.sendDapRequest('scopes', { frameId }, { deadline: budget }) + : await session.proxyManager.sendDapRequest('scopes', { frameId }); + if (pin && pinBroken(session, pin)) return { scopes: [], readFailed: true }; this.logger.info(`[SM ${prefix} ${sessionId}] DAP 'scopes' response received. Body:`, response?.body); if (response?.success === false) { throw new Error(response.message || `DAP 'scopes' request failed`); @@ -371,7 +384,7 @@ export abstract class SessionManagerData extends SessionManagerCore { protected async extractLocalsFromResolved( sessionId: string, stackResult: StackTraceResult, - opts: { includeSpecial?: boolean; names?: string[]; maxFrames?: number } = {} + opts: { includeSpecial?: boolean; names?: string[]; maxFrames?: number; deadline?: Deadline; pin?: StopPin } = {} ): Promise { const session = this._getSessionById(sessionId); const includeSpecial = opts.includeSpecial ?? false; @@ -400,7 +413,7 @@ export abstract class SessionManagerData extends SessionManagerCore { const scopesMap: Record = {}; const failedScopeFrames = new Set(); for (const frame of stackFrames) { - const scopeResult = await this.probeScopes(sessionId, frame.id); + const scopeResult = await this.probeScopes(sessionId, frame.id, opts.deadline, opts.pin); if (scopeResult.readFailed) failedScopeFrames.add(frame.id); const scopes = scopeResult.scopes; if (scopes && scopes.length > 0) { @@ -436,7 +449,7 @@ export abstract class SessionManagerData extends SessionManagerCore { scopeFetchesSkipped++; continue; } - const detailed = await this.getVariablesDetailed(sessionId, scope.variablesReference, names); + const detailed = await this.getVariablesDetailed(sessionId, scope.variablesReference, names, opts.deadline, opts.pin); // An empty failed scope may be absent from the policy's selected // refs (e.g. a JS Block beside a readable Local). Keep this status // independently of truncation attributed to contributing scopes. diff --git a/src/session/stop-record.ts b/src/session/stop-record.ts index 576cde99f..036d0c54b 100644 --- a/src/session/stop-record.ts +++ b/src/session/stop-record.ts @@ -177,8 +177,8 @@ export function currentStopOf(session: (StopReader & { readonly state: SessionSt } /** - * The stop an answer describes, taken before the answer's first await - * (inspection/pinned-stop-read.ts has the rule every answer follows). + * The stop a pinned answer describes, taken before its first dependent read + * (inspection/pinned-stop-read.ts lists the scoped callers). */ export interface StopPin { readonly sessionId: string; @@ -186,7 +186,7 @@ export interface StopPin { readonly stop: StopRecord | undefined; } -/** Pin the session's stop now. Synchronous: call it before the answer's first await. */ +/** Pin the session's stop now. Synchronous: call it before the first dependent read. */ export function pinStop(session: StopReader & { readonly id: string }): StopPin { return { sessionId: session.id, stop: stopRecordOf(session) }; } @@ -201,15 +201,11 @@ export function pinHolds(session: StopReader | undefined, pin: StopPin): boolean } /** - * Whether an answer's reads must be made again: the session is paused, and - * the id of the stop it records is not the pin's. Having no record counts as - * a value of its own, so a session paused with none (the refused step's - * rollback with no stop recorded) and pinned with none is unchanged, and its - * answer names no stop, as before; one that has a record now, or has lost - * the pinned one, is changed. A session that is gone, not paused, or still at - * the pinned stop is not; how it is answered is the caller's rule (an ending - * as ended, a resume as running). + * Identity validation is independent of state. A replacement remains a + * replacement after it resumes or ends. Callers separately decide whether + * another read is possible and how to report the current state. Two missing + * records compare equal (the refused-step rollback); a removed session fails. */ export function pinBroken(session: (StopReader & { readonly state: SessionState }) | undefined, pin: StopPin): boolean { - return session !== undefined && session.state === SessionState.PAUSED && stopIdOf(session) !== pin.stop?.id; + return session === undefined || stopIdOf(session) !== pin.stop?.id; } diff --git a/src/utils/error-messages.ts b/src/utils/error-messages.ts index 75de518a4..1f59f6d29 100644 --- a/src/utils/error-messages.ts +++ b/src/utils/error-messages.ts @@ -679,15 +679,17 @@ export const ErrorMessages = { `Session ${sessionId} was closed while waiting for a stop.`, /** - * A stop answer whose stop changed while it was being read, and again while - * it was read a second time (tracking issue #1362, stage "stop record"; - * issue #1348): the answer names the stop the program is paused at now and - * carries no location, frames or locals, because none was read for that - * stop. Says where to read them. + * An invalid stop read with no retry left, or no paused stop to retry. + * Answer shapes differ, so this makes no promise about a reason field or + * about unpinned locals inspection. The next stack call takes a new pin. */ stopChangedWhileRead: () => - 'The program stopped again while this answer was being read, twice, so where it is paused was not read: ' + - 'the reason given is the stop it is at now. get_stack_trace and get_local_variables read that stop.', + 'The stop changed while this answer was being read; its stack and snapshot were omitted. ' + + 'Call get_stack_trace again to read the current stop.', + + stopReadBudgetExpired: (budgetMs: number) => + `Reading this stop exceeded the ${budgetMs} ms answer budget; its location, stack and snapshot were omitted. ` + + 'Call get_stack_trace again to read the current stop.', /** * A launch answered while the program is still running (issues #815, #823, diff --git a/tests/core/unit/server/server-control-tools.test.ts b/tests/core/unit/server/server-control-tools.test.ts index 5b7ffd93f..2b0f6cb0a 100644 --- a/tests/core/unit/server/server-control-tools.test.ts +++ b/tests/core/unit/server/server-control-tools.test.ts @@ -340,10 +340,9 @@ describe('Server Control Tools Tests', () => { state: 'stopped', sessionLifecycle: SessionLifecycleState.TERMINATED }); - mockSessionManager.startDebugging.mockResolvedValue({ - success: true, - state: 'paused', - data: { reason: 'breakpoint' } + mockSessionManager.startDebugging.mockImplementation(async () => { + mockSessionManager.getSession.mockReturnValue({ run: {}, id: 'test-session', state: 'paused', sessionLifecycle: SessionLifecycleState.ACTIVE }); + return { success: true, state: 'paused', data: { reason: 'breakpoint' } }; }); const result = await callToolHandler({ @@ -1112,7 +1111,7 @@ describe('Server Control Tools Tests', () => { mockSessionManager.getSession.mockReturnValue({ run: {}, id: 'test-session', - state: 'running', + state: 'paused', sessionLifecycle: 'ACTIVE' }); mockSessionManager.waitForStop.mockResolvedValue({ diff --git a/tests/core/unit/server/server-inspection-tools.test.ts b/tests/core/unit/server/server-inspection-tools.test.ts index fa6a3d9f1..dc2cf2514 100644 --- a/tests/core/unit/server/server-inspection-tools.test.ts +++ b/tests/core/unit/server/server-inspection-tools.test.ts @@ -300,7 +300,7 @@ describe('Server Inspection Tools Tests', () => { expect(content.note).toMatch(/Signal Dispatcher/); expect(content.diagnostics).toEqual({ proxyLogPath: '/logs/proxy-test-session.log' }); expect(mockSessionManager.getStackTraceDetailed).toHaveBeenCalledWith( - 'test-session', 4, false + 'test-session', 4, false, expect.objectContaining({ deadline: expect.any(Object) }) ); expect(mockSession.proxyManager.setCurrentThreadId).not.toHaveBeenCalled(); }); diff --git a/tests/core/unit/server/stop-pin-boundaries.test.ts b/tests/core/unit/server/stop-pin-boundaries.test.ts new file mode 100644 index 000000000..e640c85ee --- /dev/null +++ b/tests/core/unit/server/stop-pin-boundaries.test.ts @@ -0,0 +1,188 @@ +/** Regression probes from the two reviews of #1362's stop-record stage. */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { DartAdapterPolicy, DebugLanguage, MockAdapterPolicy, SessionState, type AdapterPolicy } from '@debugmcp/shared'; +import { DebugMcpServer } from '../../../../src/server.js'; +import { registerToolHandlers } from '../../../../src/server/tool-dispatch.js'; +import { createProductionDependencies, type Dependencies } from '../../../../src/container/dependencies.js'; +import { createMockDependencies, overridePolicy } from '../session/session-manager-test-utils.js'; +import { type OperationsContext } from '../../../../src/session/operations-context.js'; +import { readPinnedStop } from '../../../../src/session/inspection/pinned-stop-read.js'; +import { pinStop } from '../../../../src/session/stop-record.js'; + +vi.mock('../../../../src/container/dependencies.js'); + +type Payload = Record; +type Handler = (request: unknown, context: unknown) => Promise<{ content: Array<{ text: string }> }>; +const frame = (name: string, line: number) => ({ id: 1, name, source: { path: '/w/app.py' }, line, column: 0 }); + +describe('stop pins: async boundaries', () => { + let core: DebugMcpServer; + let deps: ReturnType; + let handler: Handler; + + beforeEach(() => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + deps = createMockDependencies(); + vi.mocked(createProductionDependencies).mockReturnValue(deps as unknown as Dependencies); + core = new DebugMcpServer(); + registerToolHandlers({ setRequestHandler: (method: string, registered: Handler) => { + if (method === 'tools/call') handler = registered; + } } as never, core); + }); + afterEach(async () => { + await core.sessionManager.closeAllSessions().catch(() => undefined); + vi.useRealTimers(); + vi.restoreAllMocks(); + deps.mockProxyManager.reset(); + }); + const ctx = () => (core.sessionManager as unknown as { opsContext: OperationsContext }).opsContext; + const stop = (name: string, reason = 'breakpoint', threadId = 1) => + deps.mockProxyManager.simulateStopped(threadId, reason, { threadId, reason, description: name }); + const call = async (name: string, args: Payload): Promise => JSON.parse((await handler( + { method: 'tools/call', params: { name, arguments: args } }, + { mcpReq: { signal: new AbortController().signal } } + )).content[0].text) as Payload; + const policy = (overrides: Partial) => { + overridePolicy(core.sessionManager, overrides); + vi.spyOn(core.sessionManager as unknown as { selectPolicy: () => AdapterPolicy }, 'selectPolicy') + .mockReturnValue({ ...MockAdapterPolicy, ...overrides }); + }; + async function running() { + const s = await core.sessionManager.createSession({ language: DebugLanguage.MOCK }); + const pending = core.sessionManager.startDebugging(s.id, 'app.py', [], { stopOnEntry: false }); + await vi.runAllTimersAsync(); + expect((await pending).state).toBe(SessionState.RUNNING); + return s.id; + } + + + it.each(['wait_for_stop', 'pause_execution', 'start_debugging'])('M12/M13/M15 %s keeps its pin across the helper-to-caller microtask', async tool => { + const s = tool === 'start_debugging' + ? (await core.sessionManager.createSession({ language: DebugLanguage.MOCK })).id : await running(); + if (tool === 'wait_for_stop') stop('A'); + let current = 'A', fired = false; + deps.mockProxyManager.setDapRequestHandler(async command => { + if (command === 'pause') { process.nextTick(() => stop('A')); return { success: true }; } + if (command === 'stackTrace') return { success: true, body: { stackFrames: [frame(current, current === 'A' ? 11 : 50)] } }; + if (command === 'scopes') return { success: true, body: { scopes: [] } }; + if (command === 'threads') return { success: true, body: { threads: [{ id: 1, name: 'main' }] } }; + return { success: true }; + }); + const session = core.sessionManager.getSession(s)!; + let record = session.stopRecord; + Object.defineProperty(session, 'stopRecord', { configurable: true, get() { + const stack = new Error().stack ?? ''; + if (!fired && stack.includes('pinBroken') && stack.includes('readPinnedStop') && !stack.includes('readUnder')) { + fired = true; queueMicrotask(() => { current = 'B'; stop('B', 'exception'); }); + } + return record; + }, set(value) { record = value; } }); + let pending: Promise; + if (tool === 'start_debugging') { + pending = core.sessionManager.startDebugging(s, 'app.py', [], { stopOnEntry: false }); + await vi.advanceTimersByTimeAsync(50); stop('A'); + } else pending = call(tool, { sessionId: s, timeout: 2000 }); + await vi.advanceTimersByTimeAsync(3000); + const raw = await pending as Payload, a = { ...raw.data, ...raw }; + expect(fired).toBe(true); + expect(a.reason ?? a.stopReason ?? a.lastStop?.reason).toBe('breakpoint'); + expect(a.location.line).toBe(11); + }); + + it('M11 the final step retry keeps B fields when C arrives before the answer is rebuilt', async () => { + const s = await running(); stop('origin'); + let current = 'origin', changed = false, gap = false; + deps.mockProxyManager.setDapRequestHandler(async command => { + const at = current; + if (command === 'next') { process.nextTick(() => { current = 'A'; stop('A', 'step'); }); return { success: true }; } + if (command === 'stackTrace') return { success: true, body: { stackFrames: [frame(at, at === 'origin' ? 1 : at === 'A' ? 11 : at === 'B' ? 50 : 70)] } }; + if (command === 'scopes') return { success: true, body: { scopes: [{ name: 'Locals', variablesReference: 100, expensive: false }] } }; + if (command === 'variables') { if (!changed) { changed = true; current = 'B'; stop('B'); } return { success: true, body: { variables: [{ name: 'who', value: at, variablesReference: 0 }] } }; } + return { success: true }; + }); + const session = core.sessionManager.getSession(s)!; let record = session.stopRecord; + Object.defineProperty(session, 'stopRecord', { configurable: true, get() { + const stack = new Error().stack ?? ''; + if (!gap && current === 'B' && stack.includes('pinBroken') && stack.includes('readPinnedStop') && !stack.includes('readUnder')) { + gap = true; queueMicrotask(() => { current = 'C'; stop('C', 'exception'); }); + } + return record; + }, set(value) { record = value; } }); + const a = await call('step_over', { sessionId: s }); + expect(gap).toBe(true); expect(a.stopReason).toBe('breakpoint'); expect(a.location.line).toBe(50); + }); + + it('M19 an invalid landing cannot acquire the replacement exception during a locals timeout', async () => { + const s = await running(); stop('A'); + vi.spyOn(ctx(), 'getStackTraceDetailed').mockImplementation(async () => { + stop('B', 'exception'); + return { frames: [{ id: 1, name: 'A', file: '/w/app.py', line: 11, column: 0 }], threadId: 1, totalFrameCount: 1, hiddenFrameCount: 0, allFramesInternal: false }; + }); + vi.spyOn(ctx(), 'extractLocalsFromResolved').mockImplementation(async () => { + deps.mockProxyManager.simulateExited(0); return new Promise(() => {}); + }); + const pending = readPinnedStop(ctx(), s, 'review', { pin: pinStop(core.sessionManager.getSession(s)!) }); + await vi.advanceTimersByTimeAsync(2000); const a = await pending; + if (a.status === 'pinned') expect(a.snapshot?.exception).toBeUndefined(); + else { + expect(a.current?.reason).toBe('exception'); + expect(a.note).toMatch(/stop changed/i); + } + }); + + it('M14 the origin reader rejects a replacement before using the old frames for provenance', async () => { + const s = await running(); stop('A'); + vi.spyOn(ctx(), 'getStackTraceDetailed').mockImplementation(async () => { + stop('B', 'exception'); + return { frames: [{ id: 1, name: 'A', file: '/w/app.py', line: 11, column: 0 }], totalFrameCount: 1, hiddenFrameCount: 0, allFramesInternal: false }; + }); + const execution = (core.sessionManager as unknown as { execution: { readStepOrigin: (session: unknown, id: string, thread: number) => Promise } }).execution; + expect(await execution.readStepOrigin(core.sessionManager.getSession(s), s, 1)).toBeUndefined(); + }); + + it('M20 a replacement during the settle cannot borrow the pinned pause thread disclosure', async () => { + const s = await running(); stop('A', 'pause'); + vi.spyOn(ctx(), 'getStackTraceDetailed').mockImplementation(async () => { + deps.mockProxyManager.simulateExited(0); + return { frames: [{ id: 1, name: 'B', file: '/w/app.py', line: 50, column: 0 }], threadId: 2, totalFrameCount: 1, hiddenFrameCount: 0, allFramesInternal: false }; + }); + const schedule = globalThis.setTimeout; + let changed = false; + vi.spyOn(globalThis, 'setTimeout').mockImplementation((callback, ms, ...args) => { + const atSettle = !changed && (new Error().stack ?? '').includes('describeStopLocation'); + if (atSettle) changed = true; + return schedule(atSettle ? (() => { stop('B', 'exception', 2); (callback as () => void)(); }) : callback, ms, ...args); + }); + const pending = readPinnedStop(ctx(), s, 'review'); + await vi.advanceTimersByTimeAsync(2000); const a = await pending; + expect(changed).toBe(true); + expect(a.status).toBe('pinned'); + if (a.status === 'pinned') { + expect(a.landing.location?.line).toBe(50); + // The reviewed head retained A; the fixed reader retries under B. In + // either case a thread disclosure must be relative to that actual pin. + expect(a.landing.threadId).toBe(a.pin.stop?.threadId === 2 ? undefined : 2); + } + }); + + it('M22 stale exceptionInfo cannot mutate the historical stop emitted by get_stack_trace', async () => { + const s = await running(), p = deps.mockProxyManager; + p.emit('adapter-capabilities', { supportsExceptionInfoRequest: true }); + let exception!: (value: unknown) => void, stack!: (value: unknown) => void; + p.setDapRequestHandler(async command => { + if (command === 'exceptionInfo') return new Promise(resolve => { exception = resolve; }); + if (command === 'stackTrace') return new Promise(resolve => { stack = resolve; }); + return { success: true }; + }); + stop('A', 'exception'); await vi.advanceTimersByTimeAsync(1); expect(exception).toBeDefined(); + const original = core.sessionManager.getSession(s)!.stopRecord!; + const pending = call('get_stack_trace', { sessionId: s }); await vi.advanceTimersByTimeAsync(1); expect(stack).toBeDefined(); + stop('B'); await core.sessionManager.continue(s); + exception({ success: true, body: { exceptionId: 'BException', breakMode: 'always', description: 'B details' } }); + await vi.advanceTimersByTimeAsync(1); + stack({ success: true, body: { stackFrames: [frame('A', 11)] } }); + const a = await pending; + if (a.lastStop?.description === 'A') expect(a.lastStop.exceptionInfo).toBeUndefined(); + expect(original.info.exceptionInfo).toBeUndefined(); + }); +}); diff --git a/tests/core/unit/server/stop-pin-ordinary.test.ts b/tests/core/unit/server/stop-pin-ordinary.test.ts new file mode 100644 index 000000000..6355ce255 --- /dev/null +++ b/tests/core/unit/server/stop-pin-ordinary.test.ts @@ -0,0 +1,130 @@ +import { readFileSync, writeFileSync } from 'node:fs'; +/** Regression probes from the two reviews of #1362's stop-record stage. */ +import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { DartAdapterPolicy, DebugLanguage, MockAdapterPolicy, SessionState, type AdapterPolicy } from '@debugmcp/shared'; +import { DebugMcpServer } from '../../../../src/server.js'; +import { registerToolHandlers } from '../../../../src/server/tool-dispatch.js'; +import { createProductionDependencies, type Dependencies } from '../../../../src/container/dependencies.js'; +import { createMockDependencies, overridePolicy } from '../session/session-manager-test-utils.js'; +import { type OperationsContext } from '../../../../src/session/operations-context.js'; +import { pinStop } from '../../../../src/session/stop-record.js'; + +vi.mock('../../../../src/container/dependencies.js'); + +type Payload = Record; +type Handler = (request: unknown, context: unknown) => Promise<{ content: Array<{ text: string }> }>; +const frame = (name: string, line: number) => ({ id: 1, name, source: { path: '/w/app.py' }, line, column: 0 }); + +describe('stop pins: ordinary answer compatibility', () => { + let core: DebugMcpServer; + let deps: ReturnType; + let handler: Handler; + + beforeEach(() => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + deps = createMockDependencies(); + vi.mocked(createProductionDependencies).mockReturnValue(deps as unknown as Dependencies); + core = new DebugMcpServer(); + registerToolHandlers({ setRequestHandler: (method: string, registered: Handler) => { + if (method === 'tools/call') handler = registered; + } } as never, core); + }); + afterEach(async () => { + await core.sessionManager.closeAllSessions().catch(() => undefined); + vi.useRealTimers(); + vi.restoreAllMocks(); + deps.mockProxyManager.reset(); + }); + const ctx = () => (core.sessionManager as unknown as { opsContext: OperationsContext }).opsContext; + const stop = (name: string, reason = 'breakpoint', threadId = 1) => + deps.mockProxyManager.simulateStopped(threadId, reason, { threadId, reason, description: name }); + const call = async (name: string, args: Payload): Promise => JSON.parse((await handler( + { method: 'tools/call', params: { name, arguments: args } }, + { mcpReq: { signal: new AbortController().signal } } + )).content[0].text) as Payload; + const policy = (overrides: Partial) => { + overridePolicy(core.sessionManager, overrides); + vi.spyOn(core.sessionManager as unknown as { selectPolicy: () => AdapterPolicy }, 'selectPolicy') + .mockReturnValue({ ...MockAdapterPolicy, ...overrides }); + }; + async function running() { + const s = await core.sessionManager.createSession({ language: DebugLanguage.MOCK }); + const pending = core.sessionManager.startDebugging(s.id, 'app.py', [], { stopOnEntry: false }); + await vi.runAllTimersAsync(); + expect((await pending).state).toBe(SessionState.RUNNING); + return s.id; + } + + + const expectedFile = new URL('../../../fixtures/stop-pin-ordinary.json', import.meta.url); + const recorded: Record = {}; + function normalized(value: unknown): unknown { + const ids = new Map(); + const visit = (v: unknown): unknown => { + if (typeof v === 'string') return v.replace(/[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}/gi, id => { + if (!ids.has(id)) ids.set(id, 'session-' + ids.size); + return ids.get(id)!; + }); + if (Array.isArray(v)) return v.map(visit); + if (v && typeof v === 'object') return Object.fromEntries(Object.keys(v).sort().filter(k => k !== 'timestamp').map(k => [k, visit((v as Payload)[k])])); + return v; + }; + return visit(JSON.parse(JSON.stringify(value))); + } + function check(name: string, value: unknown) { + recorded[name] = normalized(value); + if (!process.env.RECORD_STOP_ANSWERS) expect(recorded[name]).toEqual(JSON.parse(readFileSync(expectedFile, 'utf8'))[name]); + } + afterAll(() => { if (process.env.RECORD_STOP_ANSWERS) writeFileSync(process.env.RECORD_STOP_ANSWERS, JSON.stringify(recorded, null, 2) + '\n'); }); + it.each(['wait_for_stop','step_over','step_into','step_out','pause_execution','start_debugging'].flatMap(tool => ['stackTrace','scopes','variables'].map(read => ({tool,read}))))('ordinary $tool / $read', async ({tool,read}) => { + const s = tool === 'start_debugging' ? (await core.sessionManager.createSession({language:DebugLanguage.MOCK})).id : await running(); + if (tool !== 'start_debugging' && tool !== 'pause_execution') stop('A'); + const p=deps.mockProxyManager; + p.setDapRequestHandler(async command=>{ + if(['next','stepIn','stepOut','pause'].includes(command)){process.nextTick(()=>stop('A',command==='pause'?'pause':'step'));return {success:true};} + if(command==='stackTrace')return {success:true,body:{stackFrames:[frame('A',11)]}}; + if(command==='threads')return {success:true,body:{threads:[{id:1,name:'main'}]}}; + if(command==='scopes')return {success:true,body:{scopes:[{name:'Locals',variablesReference:100,expensive:false}]}}; + if(command==='variables')return {success:true,body:{variables:[{name:'who',value:'A',variablesReference:0}]}}; + return {success:true}; + }); + let pending:Promise; + if(tool==='start_debugging'){pending=core.sessionManager.startDebugging(s,'app.py',[],{stopOnEntry:false});await vi.advanceTimersByTimeAsync(50);stop('A');} + else pending=call(tool,{sessionId:s,timeout:2000}); + await vi.advanceTimersByTimeAsync(3000);check(tool+'/'+read,await pending); + }); + it.each(['tree wait','paused child'])('ordinary %s',async kind=>{ + const s=await core.sessionManager.createSession({language:DebugLanguage.MOCK}); + const launch=core.sessionManager.startDebugging(s.id,'app.py',[],{stopOnEntry:false}); + if(kind==='tree wait'){await vi.runAllTimersAsync();await launch;}else await vi.advanceTimersByTimeAsync(20); + deps.mockProxyManager.simulateEvent('child-reported',{reportId:'ordinary-child',targetId:'4242',name:'Child',configuration:{type:'python',subProcessId:4242}}); + await vi.advanceTimersByTimeAsync(30); + const child=core.sessionManager.getAllSessions().find(item=>item.parentSessionId===s.id)!; + const p=deps.mockProxyManager.childViews.get(child.id)!; + p.setDapRequestHandler(async command=>command==='stackTrace'?{success:true,body:{stackFrames:[frame('A',11)]}}:command==='scopes'?{success:true,body:{scopes:[]}}:{success:true}); + p.simulateStopped(1,'breakpoint',{threadId:1,reason:'breakpoint',description:'A'}); + const pending=kind==='tree wait'?core.sessionManager.waitForStop(s.id,2000):launch; + await vi.runAllTimersAsync();check(kind,await pending); + }); + it('ordinary hidden entry and shown exception',async()=>{ + const s=await running(),p=deps.mockProxyManager;stop('entry','entry');await vi.advanceTimersByTimeAsync(30); + const hidden=core.sessionManager.getSession(s)!;const stateAfterHidden={state:hidden.state,lastStop:hidden.lastStop}; + p.setDapRequestHandler(async command=>command==='stackTrace'?{success:true,body:{stackFrames:[frame('exception',50)]}}:command==='scopes'?{success:true,body:{scopes:[]}}:{success:true}); + stop('ShownException','exception');check('hidden',{stateAfterHidden,answer:await core.sessionManager.waitForStop(s,2000)}); + }); + it.each(['restart','reload'])('ordinary %s',async kind=>{ + policy(kind==='restart'?{restartViaDapRequest:true}:{liveUpdate:DartAdapterPolicy.liveUpdate}); + const s=await running(),p=deps.mockProxyManager; + if(kind==='restart'){stop('origin');p.emit('adapter-capabilities',{supportsRestartRequest:true});} + else {p.emit('dap-event','flutter.appStart',{launchMode:'run',supportsRestart:true});p.emit('dap-event','flutter.appStarted',{});} + p.setDapRequestHandler(async command=>{ + if(command==='stackTrace')return {success:true,body:{stackFrames:[frame('A',11)]}}; + if(command==='scopes')return {success:true,body:{scopes:[]}}; + if(command==='hotReload')return new Promise(resolve=>setTimeout(()=>resolve({success:true,body:{}}),60000)); + return {success:true}; + }); + const pending=kind==='restart'?core.sessionManager.restartDebugging(s):core.sessionManager.hotReload(s,{}); + await vi.advanceTimersByTimeAsync(50);stop('A');await vi.advanceTimersByTimeAsync(2000);check(kind,await pending); + if(kind==='reload')await vi.runAllTimersAsync(); + }); +}); diff --git a/tests/core/unit/server/stop-pin-regressions.test.ts b/tests/core/unit/server/stop-pin-regressions.test.ts new file mode 100644 index 000000000..12824a195 --- /dev/null +++ b/tests/core/unit/server/stop-pin-regressions.test.ts @@ -0,0 +1,305 @@ +/** Regression probes from the two reviews of #1362's stop-record stage. */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { DartAdapterPolicy, DebugLanguage, MockAdapterPolicy, SessionState, type AdapterPolicy } from '@debugmcp/shared'; +import { DebugMcpServer } from '../../../../src/server.js'; +import { registerToolHandlers } from '../../../../src/server/tool-dispatch.js'; +import { createProductionDependencies, type Dependencies } from '../../../../src/container/dependencies.js'; +import { createMockDependencies, overridePolicy } from '../session/session-manager-test-utils.js'; +import { type OperationsContext } from '../../../../src/session/operations-context.js'; +import { pinStop } from '../../../../src/session/stop-record.js'; + +vi.mock('../../../../src/container/dependencies.js'); + +type Payload = Record; +type Handler = (request: unknown, context: unknown) => Promise<{ content: Array<{ text: string }> }>; +const frame = (name: string, line: number) => ({ id: 1, name, source: { path: '/w/app.py' }, line, column: 0 }); + +describe('stop pins: review regressions', () => { + let core: DebugMcpServer; + let deps: ReturnType; + let handler: Handler; + + beforeEach(() => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + deps = createMockDependencies(); + vi.mocked(createProductionDependencies).mockReturnValue(deps as unknown as Dependencies); + core = new DebugMcpServer(); + registerToolHandlers({ setRequestHandler: (method: string, registered: Handler) => { + if (method === 'tools/call') handler = registered; + } } as never, core); + }); + afterEach(async () => { + await core.sessionManager.closeAllSessions().catch(() => undefined); + vi.useRealTimers(); + vi.restoreAllMocks(); + deps.mockProxyManager.reset(); + }); + const ctx = () => (core.sessionManager as unknown as { opsContext: OperationsContext }).opsContext; + const stop = (name: string, reason = 'breakpoint', threadId = 1) => + deps.mockProxyManager.simulateStopped(threadId, reason, { threadId, reason, description: name }); + const call = async (name: string, args: Payload): Promise => JSON.parse((await handler( + { method: 'tools/call', params: { name, arguments: args } }, + { mcpReq: { signal: new AbortController().signal } } + )).content[0].text) as Payload; + const policy = (overrides: Partial) => { + overridePolicy(core.sessionManager, overrides); + vi.spyOn(core.sessionManager as unknown as { selectPolicy: () => AdapterPolicy }, 'selectPolicy') + .mockReturnValue({ ...MockAdapterPolicy, ...overrides }); + }; + async function running() { + const s = await core.sessionManager.createSession({ language: DebugLanguage.MOCK }); + const pending = core.sessionManager.startDebugging(s.id, 'app.py', [], { stopOnEntry: false }); + await vi.runAllTimersAsync(); + expect((await pending).state).toBe(SessionState.RUNNING); + return s.id; + } + + const families = ['get_stack_trace', 'start_debugging', 'restart', 'hot_reload', 'step_over', 'step_into', 'step_out', 'pause_execution', 'wait_for_stop']; + it.each(families.flatMap(tool => ['ended', 'resumed'].map(ending => ({ tool, ending }))))( + 'F1 $tool: discards B frames read under A when B $ending', async ({ tool, ending }) => { + if (tool === 'restart') policy({ restartViaDapRequest: true }); + if (tool === 'hot_reload') policy({ liveUpdate: DartAdapterPolicy.liveUpdate }); + const s = tool === 'start_debugging' + ? (await core.sessionManager.createSession({ language: DebugLanguage.MOCK })).id : await running(); + const proxy = deps.mockProxyManager; + if (tool === 'restart') proxy.emit('adapter-capabilities', { supportsRestartRequest: true }); + if (tool === 'hot_reload') { + proxy.emit('dap-event', 'flutter.appStart', { launchMode: 'run', supportsRestart: true }); + proxy.emit('dap-event', 'flutter.appStarted', {}); + } + let armed = ['get_stack_trace', 'wait_for_stop'].includes(tool), fired = false; + if (armed || tool === 'restart' || tool.startsWith('step_')) stop('origin'); + proxy.setDapRequestHandler(async (command: string) => { + if (['next', 'stepIn', 'stepOut', 'pause'].includes(command)) { + armed = true; + process.nextTick(() => stop('A')); + return { success: true }; + } + if (command === 'stackTrace') { + if (armed && !fired) { + fired = true; + stop('B', 'exception'); + if (ending === 'ended') proxy.simulateExited(0); + else void core.sessionManager.continue(s); + return { success: true, body: { stackFrames: [frame('B', 50)] } }; + } + return { success: true, body: { stackFrames: [frame('origin', 1)] } }; + } + if (command === 'threads') return { success: true, body: { threads: [{ id: 1, name: 'main' }] } }; + if (command === 'scopes') return { success: true, body: { scopes: [] } }; + if (command === 'hotReload') return new Promise(resolve => setTimeout(() => resolve({ success: true, body: {} }), 60_000)); + return { success: true }; + }); + let pending: Promise; + if (tool === 'start_debugging') pending = core.sessionManager.startDebugging(s, 'app.py', [], { stopOnEntry: false }); + else if (tool === 'restart') pending = core.sessionManager.restartDebugging(s); + else if (tool === 'hot_reload') pending = core.sessionManager.hotReload(s, {}); + else pending = call(tool, { sessionId: s, timeout: 2000 }); + if (['start_debugging', 'restart', 'hot_reload'].includes(tool)) { + await vi.advanceTimersByTimeAsync(50); armed = true; stop('A'); + } + await vi.advanceTimersByTimeAsync(3000); + const raw = await pending as Payload; + const a = { ...raw.data, ...raw }; + expect(fired).toBe(true); + expect(a.location).toBeUndefined(); + expect(a.snapshot).toBeUndefined(); + if (tool === 'get_stack_trace') expect(a.stackFrames).toEqual([]); + else expect(a.state).toBe(ending === 'ended' ? SessionState.STOPPED : SessionState.RUNNING); + if (tool === 'hot_reload') await vi.runAllTimersAsync(); + } + ); + + it('F2 explicit get_stack_trace cannot adopt a thread after its stop changed', async () => { + const s = await running(); stop('A'); + deps.mockProxyManager.setDapRequestHandler(async command => { + if (command === 'stackTrace') { stop('B', 'exception', 2); return { success: true, body: { stackFrames: [frame('A', 11)] } }; } + return { success: true }; + }); + await core.getStackTrace(s, false, 7); + expect(deps.mockProxyManager.getCurrentThreadId()).toBe(2); + }); + it('F2 the resolver rejects an older pin before borrowing its re-anchor permission', async () => { + const s = await running(); stop('A', 'pause'); + const pin = pinStop(core.sessionManager.getSession(s)!); + stop('B', 'breakpoint', 2); + const reads: string[] = []; + deps.mockProxyManager.setDapRequestHandler(async (command, args) => { + reads.push(command); + if (command === 'threads') return { success: true, body: { threads: [{ id: 2, name: 'stopped' }, { id: 3, name: 'worker' }] } }; + if (command === 'stackTrace') return { success: true, body: { stackFrames: args?.threadId === 3 ? [frame('worker', 70)] : [] } }; + return { success: true }; + }); + const options = { ensureStackReady: true, pin }; + const a = await core.sessionManager.getStackTraceDetailed(s, undefined, false, options); + expect(a.frames).toEqual([]); + expect(reads).toEqual([]); + expect(deps.mockProxyManager.getCurrentThreadId()).toBe(2); + }); + it('F1/F6 a stop ending during source enrichment discards its landing and unshown baseline', async () => { + const s = await running(); stop('A'); + deps.mockProxyManager.setDapRequestHandler(async command => { + if (command === 'stackTrace') return { success: true, body: { stackFrames: [frame('A', 11)] } }; + if (command === 'scopes') return { success: true, body: { scopes: [{ name: 'Locals', variablesReference: 100, expensive: false }] } }; + if (command === 'variables') return { success: true, body: { variables: [{ name: 'who', value: 'A', variablesReference: 0 }] } }; + return { success: true }; + }); + const lineReader = (core as unknown as { lineReader: { getLineContext: () => Promise } }).lineReader; + vi.spyOn(lineReader, 'getLineContext').mockImplementation(async () => { + deps.mockProxyManager.simulateExited(0); + return { lineContent: 'A source', surrounding: [] }; + }); + const a = await call('wait_for_stop', { sessionId: s }); + expect(a.state).toBe(SessionState.STOPPED); + expect(a.location).toBeUndefined(); expect(a.snapshot).toBeUndefined(); + expect(core.sessionManager.getSession(s)!.snapshotDiffBase).toBeUndefined(); + }); + + it('source context is part of the pinned read: a replacement retries the entire answer', async () => { + const s = await running(); stop('A'); let current = 'A'; + deps.mockProxyManager.setDapRequestHandler(async command => { + if (command === 'stackTrace') return { success: true, body: { stackFrames: [frame(current, current === 'A' ? 11 : 50)] } }; + if (command === 'scopes') return { success: true, body: { scopes: [] } }; + return { success: true }; + }); + const lineReader = (core as unknown as { lineReader: { getLineContext: (file: string, line: number) => Promise } }).lineReader; + const lines: number[] = []; + vi.spyOn(lineReader, 'getLineContext').mockImplementation(async (_file, line) => { + lines.push(line); + if (line === 11) { current = 'B'; stop('B', 'exception'); } + return { lineContent: line === 11 ? 'A source' : 'B source', surrounding: [] }; + }); + const a = await call('wait_for_stop', { sessionId: s, timeout: 2000 }); + expect(a.location.line).toBe(50); + expect(a.lastStop.description).toBe('B'); + expect(a.context.lineContent).toBe('B source'); + expect(lines).toEqual([11, 50]); + }); + + it('get_stack_trace validates the pin after its stale-build read', async () => { + const s = await running(); stop('A'); let current = 'A'; + deps.mockProxyManager.setDapRequestHandler(async command => command === 'stackTrace' + ? { success: true, body: { stackFrames: [frame(current, current === 'A' ? 11 : 50)] } } + : { success: true }); + const checker = (core as unknown as { buildStaleness: { check: () => Promise } }).buildStaleness; + vi.spyOn(checker, 'check').mockImplementation(async () => { + if (current === 'A') { current = 'B'; stop('B', 'exception'); } + return undefined; + }); + const a = await call('get_stack_trace', { sessionId: s }); + expect(a.stackFrames[0].line).toBe(50); + expect(a.lastStop.description).toBe('B'); + }); + + it.each(['replaced', 'ended'])('a child %s during source enrichment cannot leave a stale pausedChild', async change => { + const checker = (core as unknown as { fileChecker: { checkExists: (file: string) => Promise } }).fileChecker; + vi.spyOn(checker, 'checkExists').mockResolvedValue({ exists: true, effectivePath: '/w/app.py' }); + const s = await core.sessionManager.createSession({ language: DebugLanguage.MOCK }); + const pending = call('start_debugging', { sessionId: s.id, scriptPath: 'app.py', stopOnEntry: false }); + await vi.advanceTimersByTimeAsync(20); + deps.mockProxyManager.simulateEvent('child-reported', { reportId: 'review-child', targetId: '4242', name: 'Child', configuration: { type: 'python', subProcessId: 4242 } }); + await vi.advanceTimersByTimeAsync(30); + const child = core.sessionManager.getAllSessions().find(item => item.parentSessionId === s.id)!; + const proxy = deps.mockProxyManager.childViews.get(child.id)!; + let current = 'A'; + proxy.setDapRequestHandler(async command => command === 'stackTrace' + ? { success: true, body: { stackFrames: [frame(current, current === 'A' ? 11 : 50)] } } + : command === 'scopes' ? { success: true, body: { scopes: [] } } : { success: true }); + const reader = (core as unknown as { lineReader: { getLineContext: (file: string, line: number) => Promise } }).lineReader; + vi.spyOn(reader, 'getLineContext').mockImplementation(async (_file, line) => { + if (line === 11) { + current = 'B'; + if (change === 'ended') proxy.simulateExited(0); + else proxy.simulateStopped(1, 'exception', { threadId: 1, reason: 'exception', description: 'B' }); + } + return { lineContent: current, surrounding: [] }; + }); + proxy.simulateStopped(1, 'breakpoint', { threadId: 1, reason: 'breakpoint', description: 'A' }); + await vi.runAllTimersAsync(); + const a = await pending; + if (change === 'ended') { + expect(a.pausedChild).toBeUndefined(); + expect(a.data?.pausedChild).toBeUndefined(); + expect(a.message).not.toContain('already paused'); + } else { + expect(a.pausedChild.location.line).toBe(50); + expect(a.pausedChild.context.lineContent).toBe('B'); + } + }); + + it('F6 a discarded snapshot cannot consume the last emitted locals baseline', async () => { + const s = await running(); let current = 'P'; + deps.mockProxyManager.setDapRequestHandler(async command => { + if (command === 'stackTrace') return { success: true, body: { stackFrames: [frame('main', current === 'P' ? 1 : current === 'A' ? 11 : 50)] } }; + if (command === 'scopes') return { success: true, body: { scopes: [{ name: 'Locals', variablesReference: 100, expensive: false }] } }; + if (command === 'variables') return { success: true, body: { variables: [{ name: 'who', value: current === 'P' ? 'P' : 'A', variablesReference: 0 }] } }; + return { success: true }; + }); + stop('P'); + expect((await call('wait_for_stop', { sessionId: s })).snapshot.locals).toEqual({ who: 'P' }); + await core.sessionManager.continue(s); current = 'A'; stop('A'); + let release!: () => void; + core.sessionManager.getSession(s)!.run.inFlightChildReleases = new Set([new Promise(resolve => { release = resolve; })]); + const pending = call('wait_for_stop', { sessionId: s, timeout: 2000 }); + await vi.advanceTimersByTimeAsync(20); + current = 'B'; stop('B'); release(); + const a = await pending; + expect(a.location.line).toBe(50); + expect(a.snapshot.changedVariables).toEqual({ who: { before: 'P', after: 'A' } }); + }); + + it('F5 a hint in a snapshot-superseded step answer remains undelivered', async () => { + policy({ describeStepInFilter: () => 'Run hint.' }); + const s = await running(); stop('origin'); let stepped = false, changed = false; + deps.mockProxyManager.setDapRequestHandler(async command => { + if (command === 'stepIn') { stepped = true; process.nextTick(() => stop('A', 'step')); return { success: true }; } + if (command === 'stackTrace') return { success: true, body: { stackFrames: [frame('main', stepped ? 11 : 1)] } }; + if (command === 'scopes') return { success: true, body: { scopes: [{ name: 'Locals', variablesReference: 100, expensive: false }] } }; + if (command === 'variables') { if (!changed) { changed = true; stop('B', 'exception'); } return { success: true, body: { variables: [] } }; } + return { success: true }; + }); + const a = await call('step_into', { sessionId: s }); + expect(a.stopReason).toBe('exception'); + expect(a.note ?? '').not.toContain('Run hint.'); + expect(core.sessionManager.getSession(s)!.run.deliveredStepFilterHints?.has('Run hint.')).not.toBe(true); + }); + + it.each(['step_over', 'pause_execution', 'wait_for_stop'])('budget %s: retry shares the first landing budget', async tool => { + const s = await running(); if (tool !== 'pause_execution') stop('A'); + let armed = tool === 'wait_for_stop', reads = 0; + deps.mockProxyManager.setDapRequestHandler(async command => { + if (command === 'next' || command === 'pause') { armed = true; process.nextTick(() => stop('A')); return { success: true }; } + if (command === 'stackTrace') { + if (!armed) return { success: true, body: { stackFrames: [frame('origin', 1)] } }; + const read = ++reads; + await new Promise(resolve => setTimeout(() => { if (read === 1) stop('B'); resolve(); }, 34_000)); + return { success: true, body: { stackFrames: [frame(read === 1 ? 'A' : 'B', read === 1 ? 11 : 50)] } }; + } + if (command === 'threads') return { success: true, body: { threads: [{ id: 1, name: 'main' }] } }; + if (command === 'scopes') return { success: true, body: { scopes: [] } }; + return { success: true }; + }); + let a: Payload | undefined; + const pending = call(tool, { sessionId: s, timeout: 35_000 }).then(result => { a = result; }); + await vi.advanceTimersByTimeAsync(35_300); + expect(a, 'one 35s budget plus the deadline grace').toBeDefined(); + expect(a?.location).toBeUndefined(); + expect(a?.note ?? a?.data?.note).toMatch(/budget|time|exceed/i); + await vi.advanceTimersByTimeAsync(35_000); await pending; + }); + + it('budget step grace cannot outlive the answer budget after the origin read', async () => { + const s = await running(); stop('A'); + vi.spyOn(ctx().tunables, 'stepGraceMs', 'get').mockReturnValue(60_000); + deps.mockProxyManager.setDapRequestHandler(async command => command === 'stackTrace' + ? { success: true, body: { stackFrames: [frame('A', 11)] } } + : { success: true }); + let answer: Payload | undefined; + const pending = call('step_over', { sessionId: s }).then(value => { answer = value; }); + await vi.advanceTimersByTimeAsync(35_300); + expect(answer).toBeDefined(); + expect(answer?.state).toBe(SessionState.RUNNING); + expect(answer?.note).toMatch(/35000 ms answer budget/); + await vi.runAllTimersAsync(); await pending; + }); +}); diff --git a/tests/core/unit/server/stop-pins-through-tools.test.ts b/tests/core/unit/server/stop-pins-through-tools.test.ts index 589052d11..2ed213428 100644 --- a/tests/core/unit/server/stop-pins-through-tools.test.ts +++ b/tests/core/unit/server/stop-pins-through-tools.test.ts @@ -13,6 +13,7 @@ import { registerToolHandlers } from '../../../../src/server/tool-dispatch.js'; import { createProductionDependencies, type Dependencies } from '../../../../src/container/dependencies.js'; import { createMockDependencies } from '../session/session-manager-test-utils.js'; import { ErrorMessages } from '../../../../src/utils/error-messages.js'; +import type { ToolContext } from '../../../../src/server/tool-context.js'; vi.mock('../../../../src/container/dependencies.js'); @@ -92,6 +93,10 @@ describe('one answer, one stop, through the tools', () => { it('wait_for_stop: the hoisted location, its source line and lastStop are one stop\'s', async () => { const sessionId = await pausedAtA(['B']); + const context = core as unknown as ToolContext; + vi.spyOn(context.lineReader, 'getLineContext').mockResolvedValue({ lineContent: 'raise ValueError("B")', surrounding: [] }); + const evidence = { sourceFile: '/w/app.py', sourceMtimeMs: 2000, generatedFile: '/w/app.pyc', generatedMtimeMs: 1000, linkedBy: 'launch' as const }; + vi.spyOn(context.buildStaleness, 'check').mockResolvedValue(evidence); const response = await answer('wait_for_stop', { sessionId, timeout: 2000 }); @@ -99,6 +104,9 @@ describe('one answer, one stop, through the tools', () => { expect(response.location).toMatchObject({ line: 50 }); expect(response.lastStop).toMatchObject({ reason: 'exception', threadId: 2 }); expect(response.message).toBe('Paused (exception) at /w/app.py:50'); + expect(context.lineReader.getLineContext).toHaveBeenCalledWith('/w/app.py', 50, { contextLines: 2 }); + expect(response.context).toEqual({ lineContent: 'raise ValueError("B")', surrounding: [] }); + expect(response.note).toBe(ErrorMessages.staleGeneratedFile(evidence)); }); it('step_over: the hoisted location and stopReason are one stop\'s', async () => { diff --git a/tests/core/unit/session/inspection/stop-answer-effects.test.ts b/tests/core/unit/session/inspection/stop-answer-effects.test.ts new file mode 100644 index 000000000..4806e9ea0 --- /dev/null +++ b/tests/core/unit/session/inspection/stop-answer-effects.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from 'vitest'; +import { containsStopValue, publishStopEffect, withStopAnswerEffects } from '../../../../../src/session/inspection/stop-answer-effects.js'; +import { jsonResult } from '../../../../../src/server/tool-result.js'; + +describe('stop answer publication boundary', () => { + it('publishes only an observation contained in the serialized answer', async () => { + const shown = {}, discarded = {}, published: string[] = []; + await withStopAnswerEffects(async () => { + publishStopEffect(() => published.push('shown'), payload => containsStopValue(payload, shown)); + publishStopEffect(() => published.push('discarded'), payload => containsStopValue(payload, discarded)); + expect(published).toEqual([]); + jsonResult({ snapshot: shown }); + }); + expect(published).toEqual(['shown']); + }); + + it('publishes nothing when serialization fails', async () => { + let published = false; + await expect(withStopAnswerEffects(async () => { + publishStopEffect(() => { published = true; }, () => true); + return jsonResult({ invalid: 1n }); + })).rejects.toThrow(); + expect(published).toBe(false); + }); + + it('keeps two concurrent answers in separate publication scopes', async () => { + const published: string[] = []; + let release!: () => void; + const gate = new Promise(resolve => { release = resolve; }); + const first = withStopAnswerEffects(async () => { + publishStopEffect(() => published.push('first'), () => true); + await gate; + return jsonResult({ answer: 'first' }); + }); + await withStopAnswerEffects(async () => { + publishStopEffect(() => published.push('second'), () => true); + return jsonResult({ answer: 'second' }); + }); + expect(published).toEqual(['second']); + release(); await first; + expect(published).toEqual(['second', 'first']); + }); +}); diff --git a/tests/core/unit/session/inspection/stop-location.test.ts b/tests/core/unit/session/inspection/stop-location.test.ts index 08a896bd1..c27e5368e 100644 --- a/tests/core/unit/session/inspection/stop-location.test.ts +++ b/tests/core/unit/session/inspection/stop-location.test.ts @@ -4,6 +4,7 @@ */ import { describe, it, expect, vi } from 'vitest'; import { SessionState } from '@debugmcp/shared'; +import { applyStop, pinStop } from '../../../../../src/session/stop-record.js'; import type { StackTraceResult } from '../../../../../src/session/inspection/frame-anchor-resolver.js'; import { describeStopLocation, @@ -208,3 +209,38 @@ it.each([ const landing = await describeStopLocation(ctx, 'sid', 'pause'); expect(landing.note?.includes('or set a breakpoint')).toBe(!opts.pauses); }); + + +describe('pinned landing boundaries (#1362 review F1/F2)', () => { + it('rejects a replacement after the settle before requesting its stack', async () => { + const { ctx, getStackTraceDetailed } = context({ reason: 'pause' }); + const session = ctx.getSession('sid'); + applyStop(session, { reason: 'pause', threadId: 1, timestamp: 1 }, { shown: true }); + vi.spyOn(ctx, 'getSession').mockReturnValue(session); + const pin = pinStop(session); + let settle!: () => void; + const timer = setTimeout(() => undefined, 60_000); + const spy = vi.spyOn(globalThis, 'setTimeout').mockImplementationOnce((callback) => { settle = () => (callback as () => void)(); return timer; }); + try { + const pending = describeStopLocation(ctx, 'sid', 'review', pin); + expect(settle).toBeDefined(); + applyStop(session, { reason: 'exception', threadId: 2, timestamp: 2 }, { shown: true }); + settle(); + expect(await pending).toEqual({}); expect(getStackTraceDetailed).not.toHaveBeenCalled(); + } finally { spy.mockRestore(); clearTimeout(timer); } + }); + it.each([SessionState.RUNNING, SessionState.STOPPED])('rejects B frames under pin A even when the session is %s on return', async state => { + const { ctx, getStackTraceDetailed } = context({ reason: 'breakpoint' }); + const session = ctx.getSession('sid'); + applyStop(session, { reason: 'breakpoint', threadId: 1, timestamp: 1 }, { shown: true }); + vi.spyOn(ctx, 'getSession').mockReturnValue(session); + const pin = pinStop(session); + getStackTraceDetailed.mockImplementation(async () => { + applyStop(session, { reason: 'exception', threadId: 2, timestamp: 2 }, { shown: true }); + // This reader unit test has no transition machine; the session is a plain fixture. + Object.assign(session, { state }); + return result(); + }); + expect(await describeStopLocation(ctx, 'sid', 'review', pin)).toEqual({}); + }); +}); diff --git a/tests/core/unit/session/inspection/stop-snapshot.test.ts b/tests/core/unit/session/inspection/stop-snapshot.test.ts index fde484b6e..5f70d615d 100644 --- a/tests/core/unit/session/inspection/stop-snapshot.test.ts +++ b/tests/core/unit/session/inspection/stop-snapshot.test.ts @@ -10,10 +10,17 @@ import { SessionState, PythonAdapterPolicy } from '@debugmcp/shared'; import type { StackTraceResult } from '../../../../../src/session/inspection/frame-anchor-resolver.js'; import { setStopForTest } from '../../../../test-utils/helpers/stop-record.js'; import { - composeStopSnapshot, + composeStopSnapshot as readSnapshot, + commitStopSnapshot, type StopSnapshotContext } from '../../../../../src/session/inspection/stop-snapshot.js'; +async function composeStopSnapshot(...args: Parameters) { + const snapshot = await readSnapshot(...args); + commitStopSnapshot(snapshot); + return snapshot; +} + const FRAMES = [ { id: 1, name: 'compute', file: '/proj/app.py', line: 44, column: 0 }, { id: 2, name: 'bill', file: '/proj/billing.py', line: 12, column: 0 }, @@ -142,7 +149,7 @@ describe('composeStopSnapshot frames and locals', () => { ]); expect(snapshot?.locals).toEqual({ subtotal: '125.0', user: "'ada'" }); expect(snapshot?.exception).toBeUndefined(); - expect(extractLocalsFromResolved).toHaveBeenCalledWith('sid', read, { maxFrames: 3 }); + expect(extractLocalsFromResolved).toHaveBeenCalledWith('sid', read, expect.objectContaining({ maxFrames: 3, deadline: expect.any(Object) })); }); it('keeps the first value when a name repeats, and stores exotic names safely', async () => { diff --git a/tests/core/unit/session/session-manager-attach-modes.test.ts b/tests/core/unit/session/session-manager-attach-modes.test.ts index 526bd7c3b..9337d2e9a 100644 --- a/tests/core/unit/session/session-manager-attach-modes.test.ts +++ b/tests/core/unit/session/session-manager-attach-modes.test.ts @@ -583,6 +583,43 @@ describe('SessionManagerOperations attach modes', () => { expect(result.data?.snapshot?.locals).toBeUndefined(); }); + it.each(['resumed', 'twice', 'anchor'])('review attach %s keeps the answer and thread on a valid stop', async route => { + mockSession.language = DebugLanguage.CPP; + vi.mocked(mockDependencies.adapterRegistry.getFactoryMetadata).mockResolvedValue(metadataWithModes({ launch: true, attach: 'direct-connect' })); + vi.mocked(mockDependencies.adapterRegistry.create).mockResolvedValue(new FakeDebugAdapter({ language: DebugLanguage.CPP }).withAttachSupport({ directConnect: true })); + mockProxyManager.getCurrentThreadId.mockReturnValue(7); + let landingReads = 0, anchorChanged = false; + mockProxyManager.sendDapRequest.mockImplementation(async (command: string, args?: any) => { + if (command === 'threads') { + setSessionStateForTest(mockSession, SessionState.PAUSED); + if (!mockSession.lastStop) setStopForTest(mockSession, { reason: 'breakpoint', threadId: 7, timestamp: Date.now() }); + return { success: true, body: { threads: [{ id: 7, name: 'main' }, { id: 8, name: 'worker' }] } }; + } + if (command === 'stackTrace') { + if (route === 'anchor' && args?.levels === 32 && !anchorChanged) { + anchorChanged = true; setStopForTest(mockSession, { reason: 'breakpoint', threadId: 8, timestamp: Date.now() }); + mockProxyManager.getCurrentThreadId.mockReturnValue(8); + } + if (args?.levels === undefined) { + landingReads++; + if (route === 'resumed' && landingReads === 1) { + setStopForTest(mockSession, { reason: 'exception', threadId: 8, timestamp: Date.now() }); + setSessionStateForTest(mockSession, SessionState.RUNNING); + } + if (route === 'twice' && landingReads <= 2) setStopForTest(mockSession, { reason: landingReads === 1 ? 'exception' : 'breakpoint', threadId: 7, timestamp: Date.now() }); + } + return { success: true, body: { stackFrames: [{ id: 1, name: 'main', line: 50, column: 0, source: { path: '/proj/app.cpp' } }] } }; + } + return { success: true }; + }); + const result = await operations.attachToProcess('test-session', { host: '127.0.0.1', port: 12345, stopOnEntry: false }); + expect(result.success).toBe(true); + if (route === 'anchor') { expect(anchorChanged).toBe(true); expect(mockProxyManager.setCurrentThreadId).not.toHaveBeenCalledWith(7); } + else { expect(result.data?.location).toBeUndefined(); expect(result.data?.snapshot).toBeUndefined(); } + if (route === 'resumed') expect(result.state).toBe(SessionState.RUNNING); + if (route === 'twice') { expect(landingReads).toBe(2); expect(result.data?.note).not.toMatch(/reason given|get_local_variables/); expect(result.data?.note).toMatch(/call get_stack_trace again/i); } + }); + it('describes one stop when the target stops again during the attach answer\'s landing read (tracking issue #1362)', async () => { mockSession.language = DebugLanguage.CPP; vi.mocked(mockDependencies.adapterRegistry.getFactoryMetadata).mockResolvedValue( diff --git a/tests/core/unit/session/session-manager-stop-pin-routes.test.ts b/tests/core/unit/session/session-manager-stop-pin-routes.test.ts index 6eb1925d3..ac77307fc 100644 --- a/tests/core/unit/session/session-manager-stop-pin-routes.test.ts +++ b/tests/core/unit/session/session-manager-stop-pin-routes.test.ts @@ -139,13 +139,21 @@ describe('Stop pins: the routes beyond the landing read', () => { } }); + const owner = sessionManager as unknown as { getStackTraceDetailed: (...args: unknown[]) => Promise }; + const stackRead = vi.spyOn(owner, 'getStackTraceDetailed'); + const schedule = globalThis.setTimeout; + let changed = false; + const timer = vi.spyOn(globalThis, 'setTimeout').mockImplementation((callback, ms, ...args) => { + const atSettle = !changed && (new Error().stack ?? '').includes('describeStopLocation'); + if (atSettle) changed = true; + return schedule(atSettle ? (() => { current = 'B'; stopB(proxy); (callback as () => void)(); }) : callback, ms, ...args); + }); const pending = sessionManager.waitForStop(sessionId, 2000); - // Inside the 10 ms settle the landing read waits before it asks for the stack. - await vi.advanceTimersByTimeAsync(4); - current = 'B'; - stopB(proxy); await vi.advanceTimersByTimeAsync(100); const answer = await pending; + timer.mockRestore(); + expect(changed).toBe(true); + expect(stackRead).toHaveBeenCalledTimes(1); expect(answer.data?.lastStop).toMatchObject({ reason: 'exception', threadId: 2 }); expect(answer.data?.location).toMatchObject({ line: 50 }); @@ -256,12 +264,19 @@ describe('Stop pins: the routes beyond the landing read', () => { expect(JSON.stringify(answer.data)).not.toContain('worker'); }); - it('start_debugging: a stop that lands while the launch re-sends its breakpoints is the stop the answer describes', async () => { + it('start_debugging: a stop during breakpoint re-send leaves the retry available for a replacement during landing', async () => { const session = await sessionManager.createSession({ language: DebugLanguage.MOCK, executablePath: 'python' }); await sessionManager.setBreakpoint(session.id, { file: '/w/app.py', line: 11 }); const proxy = dependencies.mockProxyManager; let stopShown = false; - const probe = engineChangingIn(proxy, 'setBreakpoints', () => stopShown); + let third = false, landingReads = 0; + const probe = engineChangingIn(proxy, 'setBreakpoints', () => stopShown, (command) => { + if (command === 'scopes' && third) return { success: true, body: { scopes: [] } }; + if (command !== 'stackTrace' || !probe.fired()) return undefined; + landingReads++; + if (!third) { third = true; proxy.simulateStopped(3, 'breakpoint', { reason: 'breakpoint', threadId: 3 }); return { success: true, body: { stackFrames: [FRAME_B] } }; } + return { success: true, body: { stackFrames: [FRAME_WORKER] } }; + }); const started = sessionManager.startDebugging(session.id, 'app.py', [], { stopOnEntry: false }); await vi.advanceTimersByTimeAsync(50); stopShown = true; @@ -271,8 +286,9 @@ describe('Stop pins: the routes beyond the landing read', () => { expect(probe.fired()).toBe(true); expect(answer.state).toBe(SessionState.PAUSED); - expect(answer.data?.reason).toBe('exception'); - expect(answer.data?.location).toMatchObject({ line: 50 }); + expect(answer.data?.reason).toBe('breakpoint'); + expect(landingReads).toBe(2); + expect(answer.data?.location).toMatchObject({ line: 30 }); }); it('the exceptionInfo of one stop is never merged into the next stop\'s record, nor carried by its answer', async () => { @@ -319,6 +335,8 @@ describe('Stop pins: the routes beyond the landing read', () => { proxy.simulateStopped(1, 'breakpoint', { reason: 'breakpoint', threadId: 1 }); await vi.advanceTimersByTimeAsync(20); let fired = false; + let stackReads = 0; + const commandReadFrame = () => ++stackReads === 1 ? FRAME_A : FRAME_B; proxy.setDapRequestHandler(async (name: string) => { if (name === 'stackTrace' && !fired) { fired = true; @@ -326,10 +344,11 @@ describe('Stop pins: the routes beyond the landing read', () => { // entry stop, which the core resumes without showing it. void sessionManager.continue(sessionId); proxy.simulateStopped(1, 'entry', { reason: 'entry', threadId: 1 }); + stopB(proxy); } switch (name) { case 'stackTrace': - return { success: true, body: { stackFrames: [FRAME_A] } }; + return { success: true, body: { stackFrames: [commandReadFrame()] } }; case 'scopes': return { success: true, body: { scopes: [] } }; default: @@ -340,12 +359,11 @@ describe('Stop pins: the routes beyond the landing read', () => { const answer = await sessionManager.waitForStop(sessionId, 200); expect(fired).toBe(true); - expect(answer.state).toBe(SessionState.RUNNING); - expect(answer.data?.pending).toBe(true); + expect(answer.state).toBe(SessionState.PAUSED); + expect(answer.data?.lastStop).toMatchObject({ reason: 'exception', threadId: 2 }); + expect(answer.data?.location).toMatchObject({ line: 50 }); + expect(answer.data?.snapshot?.frames?.[0]).toMatchObject({ line: 50 }); expect(JSON.stringify(answer.data)).not.toContain('entry'); - // A's landing does not ride on the running answer. - expect(answer.data?.location).toBeUndefined(); - expect(answer.data?.lastStop).toBeUndefined(); }); it('step_into: an origin read during which the program stopped somewhere else is not the step\'s origin', async () => { diff --git a/tests/core/unit/session/session-manager-wait-for-stop-tree.test.ts b/tests/core/unit/session/session-manager-wait-for-stop-tree.test.ts index af796b481..e95e16f0b 100644 --- a/tests/core/unit/session/session-manager-wait-for-stop-tree.test.ts +++ b/tests/core/unit/session/session-manager-wait-for-stop-tree.test.ts @@ -336,24 +336,16 @@ describe('SessionManager - the tree-aware waitForStop (issue #1081)', () => { await vi.advanceTimersByTimeAsync(5); await sessionManager.continue(first.id); await vi.advanceTimersByTimeAsync(10); - // The second landing finishes at 20 ms. The first child is paused again, - // but another selection now would restart work beyond the 15 ms budget. + // The answer budget expires at 15 ms, before the second settle can + // finish. Report that still-paused child without a landing, rather than + // waiting until 20 ms to observe a later resume or reselecting another. + expect(wait.result()).toMatchObject({ success: true, state: SessionState.PAUSED, data: { sessionId: second.id } }); + expect(wait.result()?.data?.location).toBeUndefined(); + expect(wait.result()?.data?.note).toMatch(/15 ms answer budget/); first.view.simulateStopped(1, 'breakpoint', { reason: 'breakpoint', threadId: 1, allThreadsStopped: true }); await sessionManager.continue(second.id); await vi.advanceTimersByTimeAsync(5); - - expect(wait.result()).toMatchObject({ - success: true, - state: SessionState.RUNNING, - data: { - sessionId: rootId, - pending: true, - children: [ - expect.objectContaining({ sessionId: first.id, state: SessionState.PAUSED }), - expect.objectContaining({ sessionId: second.id, state: SessionState.RUNNING }) - ] - } - }); + expect(wait.result()?.data?.sessionId).toBe(second.id); }); it('preserves ended-at-settle for a selected child that naturally ends during the landing read', async () => { diff --git a/tests/core/unit/session/stop-record.test.ts b/tests/core/unit/session/stop-record.test.ts index 4c5b375d3..66ee99f72 100644 --- a/tests/core/unit/session/stop-record.test.ts +++ b/tests/core/unit/session/stop-record.test.ts @@ -104,13 +104,13 @@ describe('the pin rules', () => { expect(pinBroken(session, pin)).toBe(true); }); - it('a session that is not paused, or gone, never asks for the reads to be made again', () => { + it('identity changes remain invalid after resume or removal', () => { const session = holder(SessionState.RUNNING); applyStop(session, { reason: 'breakpoint', timestamp: 1 }, { shown: true }); const pin = pinStop(session); applyStop(session, { reason: 'exception', timestamp: 2 }, { shown: true }); - expect(pinBroken(session, pin)).toBe(false); - expect(pinBroken(undefined, pin)).toBe(false); + expect(pinBroken(session, pin)).toBe(true); + expect(pinBroken(undefined, pin)).toBe(true); }); it('holding fails closed without a record; breaking treats "no record" as a value of its own', () => { diff --git a/tests/fixtures/stop-pin-ordinary.json b/tests/fixtures/stop-pin-ordinary.json new file mode 100644 index 000000000..bf1423532 --- /dev/null +++ b/tests/fixtures/stop-pin-ordinary.json @@ -0,0 +1,614 @@ +{ + "wait_for_stop/stackTrace": { + "lastStop": { + "description": "A", + "reason": "breakpoint", + "threadId": 1 + }, + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "message": "Paused (breakpoint) at /w/app.py:11", + "sessionId": "session-0", + "snapshot": { + "frames": [ + { + "file": "/w/app.py", + "line": 11, + "name": "A" + } + ], + "locals": { + "who": "A" + } + }, + "state": "paused", + "success": true + }, + "wait_for_stop/scopes": { + "lastStop": { + "description": "A", + "reason": "breakpoint", + "threadId": 1 + }, + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "message": "Paused (breakpoint) at /w/app.py:11", + "sessionId": "session-0", + "snapshot": { + "frames": [ + { + "file": "/w/app.py", + "line": 11, + "name": "A" + } + ], + "locals": { + "who": "A" + } + }, + "state": "paused", + "success": true + }, + "wait_for_stop/variables": { + "lastStop": { + "description": "A", + "reason": "breakpoint", + "threadId": 1 + }, + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "message": "Paused (breakpoint) at /w/app.py:11", + "sessionId": "session-0", + "snapshot": { + "frames": [ + { + "file": "/w/app.py", + "line": 11, + "name": "A" + } + ], + "locals": { + "who": "A" + } + }, + "state": "paused", + "success": true + }, + "step_over/stackTrace": { + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "message": "Stepped over", + "note": "A", + "snapshot": { + "frames": [ + { + "file": "/w/app.py", + "line": 11, + "name": "A" + } + ], + "locals": { + "who": "A" + } + }, + "state": "paused", + "success": true + }, + "step_over/scopes": { + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "message": "Stepped over", + "note": "A", + "snapshot": { + "frames": [ + { + "file": "/w/app.py", + "line": 11, + "name": "A" + } + ], + "locals": { + "who": "A" + } + }, + "state": "paused", + "success": true + }, + "step_over/variables": { + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "message": "Stepped over", + "note": "A", + "snapshot": { + "frames": [ + { + "file": "/w/app.py", + "line": 11, + "name": "A" + } + ], + "locals": { + "who": "A" + } + }, + "state": "paused", + "success": true + }, + "step_into/stackTrace": { + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "message": "Stepped into", + "note": "A The stop is in 'A' at the same visible call-stack depth as before step_into. It is on the starting source line.", + "snapshot": { + "frames": [ + { + "file": "/w/app.py", + "line": 11, + "name": "A" + } + ], + "locals": { + "who": "A" + } + }, + "state": "paused", + "success": true + }, + "step_into/scopes": { + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "message": "Stepped into", + "note": "A The stop is in 'A' at the same visible call-stack depth as before step_into. It is on the starting source line.", + "snapshot": { + "frames": [ + { + "file": "/w/app.py", + "line": 11, + "name": "A" + } + ], + "locals": { + "who": "A" + } + }, + "state": "paused", + "success": true + }, + "step_into/variables": { + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "message": "Stepped into", + "note": "A The stop is in 'A' at the same visible call-stack depth as before step_into. It is on the starting source line.", + "snapshot": { + "frames": [ + { + "file": "/w/app.py", + "line": 11, + "name": "A" + } + ], + "locals": { + "who": "A" + } + }, + "state": "paused", + "success": true + }, + "step_out/stackTrace": { + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "message": "Stepped out", + "note": "A The stop is in 'A' at the same visible call-stack depth as before step_out (the same call, or another call of 'A').", + "snapshot": { + "frames": [ + { + "file": "/w/app.py", + "line": 11, + "name": "A" + } + ], + "locals": { + "who": "A" + } + }, + "state": "paused", + "success": true + }, + "step_out/scopes": { + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "message": "Stepped out", + "note": "A The stop is in 'A' at the same visible call-stack depth as before step_out (the same call, or another call of 'A').", + "snapshot": { + "frames": [ + { + "file": "/w/app.py", + "line": 11, + "name": "A" + } + ], + "locals": { + "who": "A" + } + }, + "state": "paused", + "success": true + }, + "step_out/variables": { + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "message": "Stepped out", + "note": "A The stop is in 'A' at the same visible call-stack depth as before step_out (the same call, or another call of 'A').", + "snapshot": { + "frames": [ + { + "file": "/w/app.py", + "line": 11, + "name": "A" + } + ], + "locals": { + "who": "A" + } + }, + "state": "paused", + "success": true + }, + "pause_execution/stackTrace": { + "data": { + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "message": "Paused", + "stopReason": "pause" + }, + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "message": "Paused", + "snapshot": { + "frames": [ + { + "file": "/w/app.py", + "line": 11, + "name": "A" + } + ], + "locals": { + "who": "A" + } + }, + "state": "paused", + "stopReason": "pause", + "success": true + }, + "pause_execution/scopes": { + "data": { + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "message": "Paused", + "stopReason": "pause" + }, + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "message": "Paused", + "snapshot": { + "frames": [ + { + "file": "/w/app.py", + "line": 11, + "name": "A" + } + ], + "locals": { + "who": "A" + } + }, + "state": "paused", + "stopReason": "pause", + "success": true + }, + "pause_execution/variables": { + "data": { + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "message": "Paused", + "stopReason": "pause" + }, + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "message": "Paused", + "snapshot": { + "frames": [ + { + "file": "/w/app.py", + "line": 11, + "name": "A" + } + ], + "locals": { + "who": "A" + } + }, + "state": "paused", + "stopReason": "pause", + "success": true + }, + "start_debugging/stackTrace": { + "data": { + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "message": "Debugging started for app.py. Current state: paused", + "reason": "breakpoint", + "snapshot": { + "frames": [ + { + "file": "/w/app.py", + "line": 11, + "name": "A" + } + ], + "locals": { + "who": "A" + } + }, + "stopOnEntrySuccessful": false + }, + "state": "paused", + "success": true + }, + "start_debugging/scopes": { + "data": { + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "message": "Debugging started for app.py. Current state: paused", + "reason": "breakpoint", + "snapshot": { + "frames": [ + { + "file": "/w/app.py", + "line": 11, + "name": "A" + } + ], + "locals": { + "who": "A" + } + }, + "stopOnEntrySuccessful": false + }, + "state": "paused", + "success": true + }, + "start_debugging/variables": { + "data": { + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "message": "Debugging started for app.py. Current state: paused", + "reason": "breakpoint", + "snapshot": { + "frames": [ + { + "file": "/w/app.py", + "line": 11, + "name": "A" + } + ], + "locals": { + "who": "A" + } + }, + "stopOnEntrySuccessful": false + }, + "state": "paused", + "success": true + }, + "tree wait": { + "data": { + "children": [ + { + "name": "Child", + "parentSessionId": "session-0", + "sessionId": "session-1", + "state": "paused" + } + ], + "lastStop": { + "description": "A", + "reason": "breakpoint", + "threadId": 1 + }, + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "message": "Paused (breakpoint) at /w/app.py:11", + "sessionId": "session-1", + "snapshot": { + "frames": [ + { + "file": "/w/app.py", + "line": 11, + "name": "A" + } + ] + } + }, + "state": "paused", + "success": true + }, + "paused child": { + "data": { + "children": [ + { + "name": "Child", + "parentSessionId": "session-0", + "sessionId": "session-1", + "state": "paused" + } + ], + "message": "Debugging started for app.py. Current state: running. The launched process is running, and child session 'Child' (session-1) is already paused (breakpoint) at /w/app.py:11. Inspect, step, or continue session session-1 directly (pausedChild carries its stop snapshot).", + "pausedChild": { + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "name": "Child", + "reason": "breakpoint", + "sessionId": "session-1", + "snapshot": { + "frames": [ + { + "file": "/w/app.py", + "line": 11, + "name": "A" + } + ] + }, + "state": "paused" + }, + "pending": true, + "stopOnEntrySuccessful": false + }, + "state": "running", + "success": true + }, + "hidden": { + "answer": { + "data": { + "lastStop": { + "description": "ShownException", + "reason": "exception", + "threadId": 1 + }, + "location": { + "column": 0, + "file": "/w/app.py", + "line": 50 + }, + "message": "Paused (exception) at /w/app.py:50", + "sessionId": "session-0", + "snapshot": { + "frames": [ + { + "file": "/w/app.py", + "line": 50, + "name": "exception" + } + ] + } + }, + "state": "paused", + "success": true + }, + "stateAfterHidden": { + "state": "running" + } + }, + "restart": { + "data": { + "breakpointsReapplied": 0, + "hotRestart": true, + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "message": "Restarted app.py in place (the adapter's hot restart). Current state: paused", + "reason": "breakpoint", + "snapshot": { + "frames": [ + { + "file": "/w/app.py", + "line": 11, + "name": "A" + } + ] + } + }, + "state": "paused", + "success": true + }, + "reload": { + "location": { + "column": 0, + "file": "/w/app.py", + "line": 11 + }, + "reason": "breakpoint", + "snapshot": { + "frames": [ + { + "file": "/w/app.py", + "line": 11, + "name": "A" + } + ] + }, + "state": "paused", + "success": true + } +} diff --git a/tests/unit/server-coverage.test.ts b/tests/unit/server-coverage.test.ts index da1098825..60bd78d51 100644 --- a/tests/unit/server-coverage.test.ts +++ b/tests/unit/server-coverage.test.ts @@ -228,7 +228,7 @@ describe('Server Coverage - Error Paths and Edge Cases', () => { const result = await server.getStackTrace('test-session'); expect(mockProxy.sendDapRequest).toHaveBeenCalledWith('threads', {}); - expect(mockSessionManager.getStackTraceDetailed).toHaveBeenCalledWith('test-session', 5, false, { ensureStackReady: true }); + expect(mockSessionManager.getStackTraceDetailed).toHaveBeenCalledWith('test-session', 5, false, expect.objectContaining({ ensureStackReady: true, pin: expect.any(Object) })); expect(result.frames).toHaveLength(1); }); @@ -259,7 +259,7 @@ describe('Server Coverage - Error Paths and Edge Cases', () => { await expect(server.getStackTrace('test-session')).resolves.toBe(noThread); expect(mockProxy.sendDapRequest).toHaveBeenCalledWith('threads', {}); - expect(mockSessionManager.getStackTraceDetailed).toHaveBeenCalledWith('test-session', undefined, false); + expect(mockSessionManager.getStackTraceDetailed).toHaveBeenCalledWith('test-session', undefined, false, expect.objectContaining({ pin: expect.any(Object) })); }); it('hands a paused session with no thread to the session layer when the threads response is empty', async () => { @@ -283,7 +283,7 @@ describe('Server Coverage - Error Paths and Edge Cases', () => { await expect(server.getStackTrace('test-session')).resolves.toBe(noThread); - expect(mockSessionManager.getStackTraceDetailed).toHaveBeenCalledWith('test-session', undefined, false); + expect(mockSessionManager.getStackTraceDetailed).toHaveBeenCalledWith('test-session', undefined, false, expect.objectContaining({ pin: expect.any(Object) })); }); it('answers a session that is not paused without asking the adapter for threads (issue #749)', async () => { @@ -314,7 +314,7 @@ describe('Server Coverage - Error Paths and Edge Cases', () => { await expect(server.getStackTrace('test-session')).resolves.toBe(notPaused); expect(mockProxy.sendDapRequest).not.toHaveBeenCalled(); - expect(mockSessionManager.getStackTraceDetailed).toHaveBeenCalledWith('test-session', undefined, false); + expect(mockSessionManager.getStackTraceDetailed).toHaveBeenCalledWith('test-session', undefined, false, expect.objectContaining({ pin: expect.any(Object) })); }); }); diff --git a/tests/unit/session-manager-operations-coverage.test.ts b/tests/unit/session-manager-operations-coverage.test.ts index a00c6ef64..47c6b6448 100644 --- a/tests/unit/session-manager-operations-coverage.test.ts +++ b/tests/unit/session-manager-operations-coverage.test.ts @@ -590,7 +590,7 @@ describe('Session Manager Operations Coverage - Error Paths and Edge Cases', () expect(result.data?.pending).toBe(true); expect(result.data?.message).toBe(`${ErrorMessages.stepStillRunning(5)} Explained by the policy.`); // The raw paused frame, not the filtered display: internals included, no readiness wait - expect(detailed).toHaveBeenCalledWith('test-session', 1, true, { ensureStackReady: false }); + expect(detailed).toHaveBeenCalledWith('test-session', 1, true, expect.objectContaining({ ensureStackReady: false, pin: expect.any(Object), deadline: expect.any(Object) })); expect(describePendingStop).toHaveBeenCalledWith({ operation: 'step', attachMode: false, @@ -618,7 +618,7 @@ describe('Session Manager Operations Coverage - Error Paths and Edge Cases', () expect(result.data?.pending).toBe(true); expect(result.data?.message).toBe(ErrorMessages.stepStillRunning(5)); - expect(detailed).toHaveBeenCalledWith('test-session', 1, true, { ensureStackReady: false }); + expect(detailed).toHaveBeenCalledWith('test-session', 1, true, expect.objectContaining({ ensureStackReady: false, pin: expect.any(Object), deadline: expect.any(Object) })); } finally { vi.useRealTimers(); } From 7977ad218a3e111cd826e69e2119156abb79a90a Mon Sep 17 00:00:00 2001 From: JF Date: Sun, 29 Nov 2026 01:26:53 -0500 Subject: [PATCH 3/9] fix(session): the stop record's guarantee is consistency; the per-call machinery comes out The previous commit closed the route by which an answer could mix two stops, and added a mechanism to keep an answer fresh up to serialization: a per-call AsyncLocalStorage scope, answers refreshed and effects published by the result path, source reads moved inside the pinned read, one deadline shared by a wait and its read. A second reviewer read it and found it could not be made tight (an event listener runs in its emitter's context, not the call's) and that it reached answers it had no business with: a dry run's or a refusal's message rewritten, a 120 s wait stalling two minutes on a wedged read, a late stop returned with no location, and budget sentences for things that had not happened. The guarantee is now stated as what it is: an answer describes one stop, as that stop was when the answer's reads completed. It may be out of date by the time it is read; no answer can promise otherwise. - Removed: stop-answer-effects.ts and its tests; the dispatch, the result path, the handlers' enrichment and the launch handlers are byte for byte what they were before the previous commit. - Kept: the identity check independent of the session's state, the checks where each read is made, the resolver gated on the caller's pin, the guarded thread writes, the corrected sentences, and their tests. - State is read where each pinned answer is built, in the session layer, after its pinned read has returned. - The snapshot's diff base and a step hint's delivered mark are committed when the session layer selects the answer it returns, never when one is merely composed, and a base never moves back to an older stop. - Only a re-read gets a bound: what is left of 35 s counted from when the answer's reads began. An answer whose stop does not change takes exactly as long as before; a wait's timeout bounds the waiting only. Written by a GPT model from the second review and a narrowing brief; committed by the manager session. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn82vMcRzWFDD9aUbZs --- CLAUDE.md | 2 +- changelog.d/1348.fixed.md | 2 +- docs/architecture/session-state-machine.md | 67 +- docs/tool-reference.md | 50 +- src/server.ts | 2 +- src/server/handlers/debuggee-tools.ts | 3 +- src/server/handlers/inspection-tools.ts | 49 +- src/server/handlers/shared.ts | 34 +- src/server/tool-dispatch.ts | 14 +- src/server/tool-result.ts | 11 +- src/session/attach/attach-controller.ts | 10 +- src/session/execution/execution-controller.ts | 775 +++++++++--------- .../inspection/frame-anchor-resolver.ts | 4 +- src/session/inspection/pinned-stop-read.ts | 144 ++-- src/session/inspection/stop-answer-effects.ts | 145 ---- src/session/inspection/stop-snapshot.ts | 32 +- src/session/launch/debug-launcher.ts | 33 +- .../live-update/live-update-controller.ts | 19 +- src/session/session-manager-data.ts | 4 +- src/utils/error-messages.ts | 6 +- .../unit/server/server-control-tools.test.ts | 9 +- .../server/server-inspection-tools.test.ts | 2 +- .../unit/server/stop-pin-boundaries.test.ts | 56 +- .../unit/server/stop-pin-consistency.test.ts | 251 ++++++ .../unit/server/stop-pin-ordinary.test.ts | 7 + .../unit/server/stop-pin-regressions.test.ts | 107 +-- .../inspection/stop-answer-effects.test.ts | 43 - .../session/inspection/stop-snapshot.test.ts | 14 +- .../session-manager-attach-modes.test.ts | 37 + ...session-manager-wait-for-stop-tree.test.ts | 22 +- ...ession-manager-operations-coverage.test.ts | 4 +- 31 files changed, 982 insertions(+), 976 deletions(-) delete mode 100644 src/session/inspection/stop-answer-effects.ts create mode 100644 tests/core/unit/server/stop-pin-consistency.test.ts delete mode 100644 tests/core/unit/session/inspection/stop-answer-effects.test.ts diff --git a/CLAUDE.md b/CLAUDE.md index ac3d20fc7..08e4267bb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -310,7 +310,7 @@ The codebase follows a **layered architecture with dependency injection** and ** - `breakpoints/anchor-resolution.ts` (`reresolveAnchors`) and `breakpoints/launch-warnings.ts` (pure warning builders) - `execution/execution-controller.ts` (`ExecutionController`): stepping (table-driven over `STEP_KINDS`), continue, pause, thread list, `waitForStop`; `execution/session-state-wait.ts` (`waitForSessionState`): the one level-triggered wait on a session's state — it re-reads the state in a microtask after each change (`OperationsContext.onStateChange`, fed by `_updateSessionState`), so an entry stop the core auto-continues within one call stack is never reported (issue #849) - `inspection/stop-anchor.ts` (`selectStopAnchor`: the one verdict on which thread a stop is anchored on, shared by the attach controller and the frame-anchor resolver — a `pause` reported on a thread with no program frame moves to the first sibling whose stack reaches the program and says so; breakpoint/step/exception/entry stops never move; issues #904/#898), `inspection/stop-location.ts` (`describeStopLocation`: the one landing read behind the pause, step, wait_for_stop, attach and launch answers — a `start_debugging`/`restart_debugging` that is paused when it answers reads it too, issue #951 — `location`, and `threadId`/`note` when the answer is anchored off the reported thread or no frame is program code; the landing also carries its resolver read internally as `StopLanding.stackResult`, which `inspection/stop-snapshot.ts` (`composeStopSnapshot`, issue #982) turns into the bounded `snapshot` — exception from the redacted stop record, top ≤3 frames, locals via `extractLocalsFromResolved` under `snapshotLocalsLimits` and the `snapshotLocalsTimeoutMs` tunable — that every PAUSED arrival answer carries (entry stops, dry runs, pending answers and the pause "Already paused" fast path carry none; `DEBUG_MCP_NO_SNAPSHOT` opts out, explicit variable-access mode withholds locals); the handlers hoist the landing fields and the snapshot through `handlers/shared.ts` `hoistStopLanding` — attach included (issue #982 parity) — which also reads the line context and the stale-build sentence and dedupes the snapshot out of the embedded `data`), `inspection/expression-evaluator.ts` (`ExpressionEvaluator`), `jvm/redefine-classes-controller.ts` (`RedefineClassesController`), `mirror/mirror-controller.ts` (`MirrorController`) -Each stop has a record (`stop-record.ts`, issue #1362): an id minted when the core applies it, its run, thread, reason, visibility and operation cause. The pinned stop-answer paths use `inspection/pinned-stop-read.ts` (get_stack_trace pins in its handler). They check identity independently of state, retry once within the same Deadline, sample state at answer assembly, and publish snapshot diff baselines and step hints only with the returned answer. Launch pins after breakpoint re-send, before its dependent reads. This change does not pin get_local_variables, evaluate_expression, get_scopes or get_variables, or change which thread a step resumes; those are issue #1374. +Each stop has a record (`stop-record.ts`, issue #1362): an id minted when the core applies it, its run, thread, reason, visibility and operation cause. An answer describes one stop, as that stop was when the answer's reads completed. It may be out of date by the time it is serialized or read. The pinned paths check identity independently of state and sample state in the session layer after their reads; no handler refreshes an answer. First reads keep their existing bounds. A re-read gets what remains of 35 s measured from the first landing read; wait_for_stop's timeout bounds waiting only, so reading an arriving stop can take the answer past that timeout. A changed answer omits the landing and snapshot and says why; if the window expired before a retry, it says the stop changed and was not read again. Snapshot diff bases and step hints are staged during composition and committed synchronously when the session layer selects its returned answer; bases never move to an older stop. Launch pins after breakpoint re-send, before dependent reads. This change does not pin get_local_variables, evaluate_expression, get_scopes or get_variables, or change which thread a step resumes; those are issue #1374. - Session state has one gate, `SessionManagerCore._updateSessionState`, and every call of it names its site and event (`{ site, event, facts? }`, paired by the compiler through `EVENT_OF_SITE`). `src/session/machine/` holds the transition table (`transition-table.ts`) and its shadow check (`shadow.ts`), which judges each write against the table and records a verdict without refusing anything (`MCP_STATE_SHADOW`: `record` by default, `strict` in the unit project, `off`). See `docs/architecture/session-state-machine.md` for the verdicts, the `legacy`/`future` marks, and how to add a site, an event or a row - Coordinates ProxyManager instances (one per session) - Handles breakpoint management and queuing diff --git a/changelog.d/1348.fixed.md b/changelog.d/1348.fixed.md index a8a38dd2b..069fd42b8 100644 --- a/changelog.d/1348.fixed.md +++ b/changelog.d/1348.fixed.md @@ -1 +1 @@ -**Keep stop answers coherent when another stop arrives during their reads.** A wait or step could report one stop's location with another's reason or exception. The stop-answer paths now pin the record before their dependent debugger reads, reject replacement reads even after resume or exit, and guard thread adoption with that same identity. Launch, restart, attach and reload answers use the state at assembly and omit a landing after resume or exit. A retry shares the first read's deadline; expiry names the budget, and a second change omits the landing and asks the caller to call get_stack_trace again. Snapshot diff baselines and step filter hints are published only with the answer that shows them. The note does not promise a reason field on attach or claim that unpinned locals inspect the same stop. This change does not pin get_local_variables, evaluate_expression, get_scopes or get_variables, or change which thread a step resumes; those are issue #1374. (#1348, #1362) +**Keep stop answers coherent across replacement stops.** An answer describes one stop, as that stop was when the answer's reads completed. It may be out of date by the time it is serialized or read. Identity checks work independently of state, gate thread adoption, and each session-layer caller samples state after its reads. First reads retain their existing timing; a replacement is read once with what remains of 35 s from the first landing read. A changed answer omits its landing and snapshot and says why; an exhausted retry window says the stop changed and was not read again, or that its re-read did not complete. wait_for_stop's timeout bounds waiting only, so reading a stop that arrived inside it can take the answer past that timeout. Source/build enrichment uses the accepted location without refreshing the answer. Snapshot diff bases and step hints are committed synchronously only for the selected session-layer answer; bases never move backwards. A later handler failure or cancellation does not roll back that selection. This change does not pin get_local_variables, evaluate_expression, get_scopes or get_variables, or change which thread a step resumes; those are issue #1374. (#1348, #1362) diff --git a/docs/architecture/session-state-machine.md b/docs/architecture/session-state-machine.md index 17ee2d266..3b024b96b 100644 --- a/docs/architecture/session-state-machine.md +++ b/docs/architecture/session-state-machine.md @@ -107,38 +107,47 @@ Tests give a session a stop through [`setStopForTest`](../../tests/test-utils/helpers/stop-record.ts); a `lastStop` written around the module has no record. The shadow is handed the record ids as its stop identities. -The pinned answer paths are `wait_for_stop` (including descendant selection), the three -steps, `pause_execution`, paused launch/restart and attach answers, `pausedChild`, a running -program stopped by `hot_reload`, and `get_stack_trace`. They pin before the first dependent -read. Launch pins after breakpoint re-send, which reads no stack or stop payload. - -Identity validation is independent of session state: `pinBroken` compares the recorded id, -including when the session has resumed, ended or disappeared. `describeStopLocation` checks -after its settle and after its stack read. The resolver receives the caller's pin and uses it -as the adoption gate; it cannot acquire a newer stop's permission to move threads. The current -inspection anchor may already differ from the reported thread; the landing discloses that -choice rather than claiming that every stack request targets the reported thread. - -`readPinnedStop` re-reads once if another stop is paused, using the same `Deadline`. Step -origin, landing and snapshot reads share the step answer budget; waits use the caller's -original deadline. The default read budget is 35,000 ms, plus up to 250 ms for a request already -sent. No new read is admitted after expiry. An expired budget and a changed stop have distinct, -truthful notes. The latter directs the caller to call `get_stack_trace` again and makes no -promise about unpinned inspection tools or a reason field absent from an attach answer. - -Callers sample state when assembling the answer. A resumed/ended session has no paused landing -or snapshot; tool serialization checks state again after source/footprint enrichment. Snapshot -composition stages its diff baseline. Only the snapshot actually returned publishes that -baseline. Step hint delivery likewise follows the final selected answer, not an earlier attempt. -The per-call publication scope keeps concurrent answers separate and publishes no effects if -serialization fails; direct SessionManager callers publish at their own return boundary. +**An answer describes one stop, as that stop was when the answer's reads completed.** +It may be out of date by the time it is serialized or read. This is consistency, not +freshness; nothing rewrites an answer after the session layer returns it. + +The pinned paths are wait_for_stop (including descendant selection), the three steps, +pause_execution, paused launch/restart and attach answers, pausedChild, a running program +stopped by hot_reload, and get_stack_trace. Each pins before its dependent reads; launch +pins after breakpoint re-send. The landing reads the current inspection anchor, which may +already differ from the reported thread, and discloses that choice. It does not promise +that every request targets the reported thread. Identity checks are independent of state: +the landing checks after its settle and stack read, and the resolver uses the caller's +pin to gate adoption. The session layer samples the root's and selected child's own state +after their reads and selects a paused, running or ended answer there. + +First reads retain their existing bounds: the ordinary DAP timeout and proxy margin, +readiness probes, the locals timer, the step-origin bound and the step's stop-wait grace. +There is no new overall deadline on a first read. Only a replacement read takes a Deadline, +with what remains of 35,000 ms measured from the first landing read. The outer retry race +ends at that boundary and disposes its requests. If there is no time left, no retry starts. +wait_for_stop's timeout bounds waiting and tree re-selection, not the landing/snapshot of +a stop that arrived inside it; the answer can therefore arrive after that timeout by the +time those reads take. Cancellation is not reported as expiry of a stop-read budget. + +A broken pin is re-read once if another stop is paused and time remains. If that read +changes too, the changed answer omits the landing/frames/snapshot and says the stop changed; +it asks the caller to call get_stack_trace again. If the retry window expires, the note +says either that the stop was not read again or that the re-read did not complete, as +applicable. It does not promise a reason field on attach or same-stop unpinned locals. + +Source/build enrichment stays in the handlers, using the accepted location. Those file +reads do not pin a stop or renew its transaction. Snapshot diff bases and step hints are +staged during composition and committed synchronously when the session layer selects the +answer it returns. An older snapshot cannot move the base backwards to an older stop. +A later handler error, serialization failure or cancellation does not undo that selection. +There is no per-call publication scope or serialization-time state refresh. This change does not pin get_local_variables, evaluate_expression, get_scopes or get_variables, or change which thread a step resumes; those are issue #1374. -Regression probes live in `stop-pin-regressions.test.ts`, `stop-pin-boundaries.test.ts`, -`stop-pin-ordinary.test.ts`, `session-manager-stop-pin-routes.test.ts`, the landing and attach -tests, and `stop-pins-through-tools.test.ts`. The ordinary-answer fixture also matches -`51d5886c`; it excludes only generated ids and timestamps. +Regression tests include stop-pin-regressions, stop-pin-consistency, stop-pin-boundaries, +stop-pin-ordinary, the landing/attach tests and stop-pins-through-tools. The ordinary +fixture also matches 51d5886c and d511ae79, excluding generated ids and timestamps. ## The table diff --git a/docs/tool-reference.md b/docs/tool-reference.md index 7403e1571..9aed025bf 100644 --- a/docs/tool-reference.md +++ b/docs/tool-reference.md @@ -603,29 +603,33 @@ crashing state costs zero extra tool calls: ### One stop per answer -The stop answers from `wait_for_stop`, the three step tools, `pause_execution`, paused launch, -restart and attach answers, a launch's `pausedChild`, a `hot_reload` that stops a running program, -and `get_stack_trace` pin a stop record before reading its stack. The record is checked where -reads begin and return, including after the landing's settle. A replacement invalidates the -read even if the session has subsequently resumed or ended. Thread adoption is allowed only -while the same record remains current. Each caller reads the answer's state when building it; -a session that resumed or ended receives no paused landing or snapshot. - -If the stop changes, these answers re-read it once under the remaining answer budget. If it -changes again, they omit the landing, frames and snapshot. They retain the reason or `lastStop` -only on answer shapes that carry those fields. The note says: "The stop changed while this -answer was being read; its stack and snapshot were omitted. Call get_stack_trace again to read -the current stop." Attach has no reason field; the note makes no claim that it has one. - -The debugger reads and their retry share a 35,000 ms deadline; `wait_for_stop` instead uses its -requested timeout for the wait and answer reads together. Requests already sent have up to -250 ms of deadline grace. A budget-expired answer names the budget and omits its landing and -snapshot. Source/build enrichment uses the same remaining budget. A locals diff baseline and -a step filter hint are recorded as shown only when the returned answer includes them. - -Source context and the stale-build note use the captured location. `get_stack_trace` checks -stale builds using its captured top frame; `hot_reload` adds neither source context nor a -stale-build note. +**An answer describes one stop, as that stop was when the answer's reads completed.** +It may be out of date by the time it is serialized or read. The pinned paths are +wait_for_stop, the three step tools, pause_execution, paused launch/restart and attach +answers, pausedChild, hot_reload when it stops a running program, and get_stack_trace. +Their identity checks work even after resume or exit. Each session-layer caller samples +state after the read and builds the answer there; handlers do not refresh its state later. + +If the stop changes, the answer re-reads it once while another stop is paused and time +remains. A second change omits the landing, frames and snapshot. The note says: "The stop +changed while this answer was being read; its stack and snapshot were omitted. Call +get_stack_trace again to read the current stop." Only shapes that carry a reason/lastStop +retain those fields; attach has no reason field. + +First reads keep their existing request/readiness/locals bounds. Only a re-read is bounded +by what remains of 35,000 ms from the first landing read. If none remains, the changed +answer says the stop changed and was not read again; if the retry began but could not +finish, it says so. A first stack-trace timeout remains a failure, not an empty success. +The step's wait for a stop keeps its original grace. wait_for_stop's timeout bounds waiting +only: a stop arriving inside it is read normally, so the answer can arrive after the timeout +by the time it takes to read that stop. Cancellation is not a stop-read-budget expiry. + +Source context and stale-build enrichment stay in handlers and describe the answer's own +location, whatever the session does meanwhile. get_stack_trace checks its captured top +frame; hot_reload adds neither source context nor a stale-build note. Snapshot diff bases +and hint delivery are committed when the session layer selects its returned answer, not +when composing an attempt. An older stop cannot replace a newer diff base. Later handler +failure or cancellation is accepted and does not roll back that commit. This change does not pin get_local_variables, evaluate_expression, get_scopes or get_variables, or change which thread a step resumes; those are issue #1374. diff --git a/src/server.ts b/src/server.ts index 13bac0a10..2fd40f294 100644 --- a/src/server.ts +++ b/src/server.ts @@ -676,7 +676,7 @@ export class DebugMcpServer implements ToolContext { if (typeof currentThreadId !== 'number') { try { const threadsResp = readOptions?.deadline - ? await session.proxyManager.sendDapRequest('threads', {}, { deadline: readOptions.deadline }) + ? await session.proxyManager.sendDapRequest('threads', {}, { deadline: readOptions.deadline, timeoutMs: 30_000 }) : await session.proxyManager.sendDapRequest('threads', {}); if (pinBroken(session, pin)) return changed(); const threads = threadsResp?.body?.threads; diff --git a/src/server/handlers/debuggee-tools.ts b/src/server/handlers/debuggee-tools.ts index 753bc2a09..70fcaa26d 100644 --- a/src/server/handlers/debuggee-tools.ts +++ b/src/server/handlers/debuggee-tools.ts @@ -1,4 +1,3 @@ -import { trackStopAnswerState } from '../../session/inspection/stop-answer-effects.js'; /** * Debuggee lifecycle tools: start_debugging, restart_debugging, * attach_to_process, detach_from_process, hot_reload. @@ -244,7 +243,7 @@ export const hotReloadTool: ToolHandler = async (ctx, args, toolName) => { ...(args.sinceTimestamp !== undefined ? { sinceTimestamp: args.sinceTimestamp } : {}), }; const result = await ctx.sessionManager.hotReload(args.sessionId as string, request, args.timeout); - const payload: Record = trackStopAnswerState({ ...result }, () => ctx.sessionManager.getSession(args.sessionId)?.state); + const payload: Record = { ...result }; if (toolName === 'redefine_classes') { payload.warning = result.warning ? `${result.warning}; ${REDEFINE_CLASSES_ALIAS_WARNING}` : REDEFINE_CLASSES_ALIAS_WARNING; } diff --git a/src/server/handlers/inspection-tools.ts b/src/server/handlers/inspection-tools.ts index 6bf29e616..4c5f24e7b 100644 --- a/src/server/handlers/inspection-tools.ts +++ b/src/server/handlers/inspection-tools.ts @@ -3,11 +3,10 @@ * evaluate_expression, get_source_context, get_local_variables. */ import { ProtocolError, ProtocolErrorCode } from '@modelcontextprotocol/server'; -import { deadline, SessionState } from '@debugmcp/shared'; +import { SessionState } from '@debugmcp/shared'; import { hasPausingBreakpoint } from '../../session/launch/launch-arming.js'; -import { pinBroken, pinStop, stopRecordOf, type StopPin } from '../../session/stop-record.js'; -import { retainStopAnswerDeadline } from '../../session/inspection/stop-answer-effects.js'; -import { STOP_READ_BUDGET_MS } from '../../session/inspection/pinned-stop-read.js'; +import { pinBroken, pinStop, stopRecordOf } from '../../session/stop-record.js'; +import { rereadStop, startStopRead } from '../../session/inspection/pinned-stop-read.js'; import { ErrorMessages } from '../../utils/error-messages.js'; import type { ToolContext, ToolHandler } from '../tool-context.js'; import { enforceExplicitNames, requireSessionId } from '../tool-validation.js'; @@ -84,15 +83,14 @@ export const getStackTraceTool: ToolHandler = async (ctx, args) => { const failureDiagnostics = () => ctx.sessionManager.getSession(args.sessionId)?.failureDiagnostics; - - const budget = deadline(STOP_READ_BUDGET_MS, { label: 'stack trace answer' }); - const retained = retainStopAnswerDeadline(budget); const changed = (note: string) => { const after = ctx.sessionManager.getSession(args.sessionId); - const current = carriesLastStop(after?.state) ? stopRecordOf(after)?.info : undefined; - const lastStop = current ? emittableStopInfo(ctx, current) : undefined; - return jsonResult({ success: true, stackFrames: [], count: 0, includeInternals: args.includeInternals ?? false, stopReason: lastStop?.reason, lastStop, note }); + const current = carriesLastStop(after?.state) ? stopRecordOf(after) : undefined; + const lastStop = current ? emittableStopInfo(ctx, current.info) : undefined; + return jsonResult({ success: true, stackFrames: [], count: 0, includeInternals: args.includeInternals ?? false, + stopReason: lastStop?.reason, lastStop, note }); }; + try { // Default to false for cleaner output const includeInternals = args.includeInternals ?? false; @@ -114,24 +112,20 @@ export const getStackTraceTool: ToolHandler = async (ctx, args) => { // again once, and a second change answers the stop now current with no // frames, and says so. let pin = sessionBefore?.state === SessionState.PAUSED ? pinStop(sessionBefore) : undefined; - const fetch = async (under: StopPin | undefined) => { - const stackTrace = await budget.request(() => ctx.getStackTrace(args.sessionId!, includeInternals, args.threadId, { pin: under, deadline: budget })); - if (under && pinBroken(ctx.sessionManager.getSession(args.sessionId), under)) return { stackTrace, staleBuild: undefined }; - const top = stackTrace.frames[0]; - const staleBuild = top && !top.unresolvedSource && hasOpenableSourcePath(top.file) - ? await budget.request(() => describeStaleBuild(ctx, args.sessionId!, top.file, 'stack trace')) - : undefined; - return { stackTrace, staleBuild }; - }; - let { stackTrace, staleBuild } = await fetch(pin); + const startedAt = startStopRead(); + let stackTrace = await ctx.getStackTrace(args.sessionId, includeInternals, args.threadId, { pin }); if (pin && pinBroken(ctx.sessionManager.getSession(args.sessionId), pin)) { const now = ctx.sessionManager.getSession(args.sessionId); if (!now || now.state !== SessionState.PAUSED) return changed(ErrorMessages.stopChangedWhileRead()); pin = pinStop(now); storedStop = pin.stop?.info; - ({ stackTrace, staleBuild } = await fetch(pin)); + const retry = await rereadStop(startedAt, budget => ctx.getStackTrace(args.sessionId!, includeInternals, args.threadId, { pin, deadline: budget })); + if (retry.status === 'expired') return changed(retry.note); + stackTrace = retry.value; const after = ctx.sessionManager.getSession(args.sessionId); - if (pinBroken(after, pin)) return changed(ErrorMessages.stopChangedWhileRead()); + if (pinBroken(after, pin)) { + return changed(ErrorMessages.stopChangedWhileRead()); + } } const lastStop = storedStop ? emittableStopInfo(ctx, storedStop) : undefined; const payload: Record = { @@ -223,13 +217,18 @@ export const getStackTraceTool: ToolHandler = async (ctx, args) => { // #951). The top frame only, and only one with an openable path — a // `<…>` label, a relative spelling or an unresolvedSource frame names no // file on this host (the same rule the stop answers apply). - if (staleBuild) notes.push(staleBuild); + const top = stackTrace.frames[0]; + if (top && !top.unresolvedSource && hasOpenableSourcePath(top.file)) { + const staleBuild = await describeStaleBuild(ctx, args.sessionId, top.file, 'stack trace'); + if (staleBuild) { + notes.push(staleBuild); + } + } if (notes.length > 0) { payload.note = notes.join(' '); } return jsonResult(payload); } catch (error) { - if (budget.expired) return changed(ErrorMessages.stopReadBudgetExpired(budget.budgetMs)); const sessionResult = sessionErrorToResult(error); if (sessionResult) { // An ended session gets the sentence get_local_variables always gave @@ -249,8 +248,6 @@ export const getStackTraceTool: ToolHandler = async (ctx, args) => { } // Re-throw unexpected errors throw error; - } finally { - if (!retained) budget.dispose(); } }; diff --git a/src/server/handlers/shared.ts b/src/server/handlers/shared.ts index a8b7133c3..590a17662 100644 --- a/src/server/handlers/shared.ts +++ b/src/server/handlers/shared.ts @@ -1,4 +1,3 @@ -import { beforeStopAnswerReturn, isTrackedStopAnswer, readStopEnrichment, stopAnswerDeadline, stopEnrichmentFor, trackStopAnswerState } from '../../session/inspection/stop-answer-effects.js'; /** * Helpers shared by more than one tool handler: the best-effort line-context * read, the redaction notice, the get_variables / get_local_variables payload @@ -324,35 +323,18 @@ export async function hoistPausedChild( return; } const pausedChild: Record = { ...data.pausedChild }; - if (isTrackedStopAnswer(data) || stopAnswerDeadline() || ctx.sessionManager.getSession(data.pausedChild.sessionId)?.state !== undefined) { - trackStopAnswerState(pausedChild, () => ctx.sessionManager.getSession(data.pausedChild!.sessionId)?.state); - } const location = data.pausedChild.location; if (location && !location.unresolvedSource && hasOpenableSourcePath(location.file)) { - const cached = stopEnrichmentFor(location); - const enriched = cached ? [cached.context, cached.staleBuild] as const : await readStopEnrichment(() => Promise.all([ + const [context, staleBuild] = await Promise.all([ readLineContext(ctx, location.file, location.line, logLabel), - describeStaleBuild(ctx, data.pausedChild!.sessionId, location.file, logLabel) - ]), pausedChild); - const [context, staleBuild] = enriched ?? []; + describeStaleBuild(ctx, data.pausedChild.sessionId, location.file, logLabel) + ]); if (context) { pausedChild.context = context; } appendNote(pausedChild, staleBuild); } response.pausedChild = pausedChild; - if (ctx.sessionManager.getSession(data.pausedChild.sessionId)?.state !== undefined) { - beforeStopAnswerReturn(response, () => { - const state = ctx.sessionManager.getSession(data.pausedChild!.sessionId)?.state; - if (state === SessionState.PAUSED) return; - delete response.pausedChild; - const embedded = response.data as Record | undefined; - if (embedded) delete embedded.pausedChild; - const message = `The selected child is ${state ?? 'closed'}; its paused landing was omitted.`; - response.message = message; - if (embedded) embedded.message = message; - }); - } if (data.pausedChild.snapshot) { const embedded = response.data; if (embedded && typeof embedded === 'object' && 'pausedChild' in embedded) { @@ -390,9 +372,6 @@ export async function hoistStopLanding( sessionId: string, logLabel: string ): Promise { - if (isTrackedStopAnswer(data) || stopAnswerDeadline() || ctx.sessionManager.getSession(sessionId)?.state !== undefined) { - trackStopAnswerState(response, () => ctx.sessionManager.getSession(sessionId)?.state); - } if (typeof data?.threadId === 'number') { response.threadId = data.threadId; } @@ -421,13 +400,10 @@ export async function hoistStopLanding( if (location.unresolvedSource || !hasOpenableSourcePath(location.file)) { return; } - const cached = stopEnrichmentFor(location); - const enriched = cached ? [cached.context, cached.staleBuild] as const : await readStopEnrichment(() => Promise.all([ + const [context, staleBuild] = await Promise.all([ readLineContext(ctx, location.file, location.line, logLabel), describeStaleBuild(ctx, sessionId, location.file, logLabel) - ]), response); - if (!enriched) return; - const [context, staleBuild] = enriched; + ]); if (context) { response.context = context; } diff --git a/src/server/tool-dispatch.ts b/src/server/tool-dispatch.ts index 59c40c856..51862f712 100644 --- a/src/server/tool-dispatch.ts +++ b/src/server/tool-dispatch.ts @@ -15,8 +15,6 @@ import { buildToolDefinitions, isToolName, TOOL_ALIASES, type ToolDefinition } f import { assertRequiredToolArguments } from './tool-validation.js'; import type { ToolContext } from './tool-context.js'; import { TOOL_HANDLERS } from './handlers/index.js'; -import { withStopAnswerEffects } from '../session/inspection/stop-answer-effects.js'; -import { describeStaleBuild, hasOpenableSourcePath, readLineContext } from './handlers/shared.js'; /** * The owner-key gate (issue #1025, step 2). For a caller, a session outside @@ -183,17 +181,7 @@ export function registerToolHandlers(server: Pick, releaseIdleHold = await holdForTheCall(ctx, definition, args.sessionId, outOfScope, callerKey); const result = idleExpiryResult(ctx, definition, args.sessionId, callerKey) ?? - await withStopAnswerEffects( - () => TOOL_HANDLERS[toolName](ctx, args, requestedName, { signal: callCtx?.mcpReq.signal, callerKey }), - async (sessionId, location) => { - if (toolName === 'hot_reload' || location.unresolvedSource || !hasOpenableSourcePath(location.file)) return {}; - const [context, staleBuild] = await Promise.all([ - readLineContext(ctx, location.file, location.line, toolName), - describeStaleBuild(ctx, sessionId, location.file, toolName) - ]); - return { context, staleBuild }; - } - ); + await TOOL_HANDLERS[toolName](ctx, args, requestedName, { signal: callCtx?.mcpReq.signal, callerKey }); // Log tool response; success mirrors the payload's own success flag (issue #397) ctx.logger.info('tool:response', { diff --git a/src/server/tool-result.ts b/src/server/tool-result.ts index c207c0913..15284c3c2 100644 --- a/src/server/tool-result.ts +++ b/src/server/tool-result.ts @@ -7,7 +7,6 @@ */ import { ProtocolError, ServerResult, ProtocolErrorCode } from '@modelcontextprotocol/server'; import path from 'path'; -import { publishReturnedStopEffects, refreshStopAnswer } from '../session/inspection/stop-answer-effects.js'; import { getErrorMessage, SessionNotFoundError, @@ -20,18 +19,12 @@ export type ToolResult = { content: [{ type: 'text'; text: string }] }; /** Wrap a JSON-serializable payload as a tool result. */ export function jsonResult(payload: unknown): ToolResult { - refreshStopAnswer(payload); - const text = JSON.stringify(payload); - publishReturnedStopEffects(payload); - return { content: [{ type: 'text', text }] }; + return { content: [{ type: 'text', text: JSON.stringify(payload) }] }; } /** Wrap a JSON-serializable payload as a pretty-printed (2-space) tool result. */ export function prettyJsonResult(payload: unknown): ToolResult { - refreshStopAnswer(payload); - const text = JSON.stringify(payload, null, 2); - publishReturnedStopEffects(payload); - return { content: [{ type: 'text', text }] }; + return { content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }] }; } /** diff --git a/src/session/attach/attach-controller.ts b/src/session/attach/attach-controller.ts index e2fc86b1c..8041395b7 100644 --- a/src/session/attach/attach-controller.ts +++ b/src/session/attach/attach-controller.ts @@ -42,8 +42,9 @@ import type { ProxyLauncher } from '../launch/proxy-launcher.js'; import { recordExceptionArming } from '../launch/launch-arming.js'; import { verifyAttachThreads } from './attach-verification.js'; import { ATTACH_ANCHOR_BOUNDS, selectStopAnchor } from '../inspection/stop-anchor.js'; +import { commitStopSnapshot } from '../inspection/stop-snapshot.js'; import { landingFields } from '../inspection/stop-location.js'; -import { completeStopAnswer, describedStop, readPinnedStop } from '../inspection/pinned-stop-read.js'; +import { describedStop, readPinnedStop } from '../inspection/pinned-stop-read.js'; import { pinBroken, pinStop, resetStops } from '../stop-record.js'; import type { PauseCoordinator } from '../execution/pause-coordinator.js'; import { refuseChildSession, type EndingRecord, type InFlightGuard, type SessionEnding } from '../in-flight-guard.js'; @@ -501,7 +502,7 @@ export class AttachController { : attachedTo, ...(attachPausePending ? { pending: true } : {}), ...(landing ? landingFields(landing) : {}), - ...(described?.note ? { note: described.note } : {}), + ...(session.state === SessionState.PAUSED && described?.note ? { note: described.note } : {}), ...(snapshot ? { snapshot } : {}), ...(session.run.attachFootprint ? { attachFootprint: session.run.attachFootprint } : {}), // What the attach's logpoint check said (issue #1334): not checked, and why. @@ -542,11 +543,12 @@ export class AttachController { attachData.warning = warningParts.join('; '); } - return completeStopAnswer({ + commitStopSnapshot(snapshot); + return { success: true, state: session.state, data: attachData - }, () => session.state); + }; } catch (error) { this.ctx.logger.error(`[SessionManager] Failed to attach to process for session ${sessionId}:`, error); // Never leave a live proxy chain behind a failed attach — e.g. diff --git a/src/session/execution/execution-controller.ts b/src/session/execution/execution-controller.ts index f0d6b8a02..49cff660e 100644 --- a/src/session/execution/execution-controller.ts +++ b/src/session/execution/execution-controller.ts @@ -1,4 +1,3 @@ -import { containsStopNote, publishStopEffect, retainStopAnswerDeadline, trackStopAnswerState } from '../inspection/stop-answer-effects.js'; /** * Execution control: stepping, continue, pause, waiting for a stop, and the * thread list. @@ -43,14 +42,13 @@ import { containsStopNote, publishStopEffect, retainStopAnswerDeadline, trackSto */ import { getErrorMessage } from '../../errors/debug-errors.js'; import { - deadline, - type Deadline, isSessionTerminated, isTerminalSessionState, NO_DEBUG_TARGET_MARKER, redactStopInfo, SessionState, USER_BREAK_REASONS, + type Deadline, type SessionStopInfo, type StackFrame } from '@debugmcp/shared'; @@ -85,7 +83,7 @@ import type { ExecutionContext } from '../operations-context.js'; import { runFactsOf, type RunFacts } from '../run-facts.js'; import { landingFields, type StopLanding } from '../inspection/stop-location.js'; import { commitStopSnapshot, composeStopSnapshot } from '../inspection/stop-snapshot.js'; -import { readPinnedStop, STOP_READ_BUDGET_MS, type PinnedStopRead } from '../inspection/pinned-stop-read.js'; +import { readPinnedStop, rereadStop, startStopRead, type PinnedStopRead } from '../inspection/pinned-stop-read.js'; import { nextOperationId, pinBroken, @@ -156,7 +154,6 @@ const PAUSED_THEN_ENDED_MESSAGE = 'Paused; the session ended before the stack co /** The per-step options `executeStep` waits on. */ export interface StepOperationOptions { - deadline?: Deadline; command: 'next' | 'stepIn' | 'stepOut'; threadId: number; logTag: string; @@ -215,10 +212,11 @@ interface StepAnswer { * changes under the snapshot it composes afterwards. */ export interface StepLandingRead { - deliver?: () => void; landing?: StopLanding; pin?: StopPin; reread: boolean; + startedAt?: number; + deliver?: () => void; answerAgain: (pin: StopPin, landing: StopLanding) => StepAnswer; changedAnswer: (current: StopRecord | undefined) => DebugResult; endedAnswer: () => DebugResult; @@ -288,120 +286,115 @@ export class ExecutionController { * checks, the current thread, and the error handling around the wait. */ private async step(sessionId: string, kind: StepKindName): Promise> { - const stopBudget = deadline(STOP_READ_BUDGET_MS, { label: 'step answer' }); - const retained = retainStopAnswerDeadline(stopBudget); - try { - const { command, toolName, operation, logTag, successMessage } = STEP_KINDS[kind]; - const session = this.ctx.getSession(sessionId); + const { command, toolName, operation, logTag, successMessage } = STEP_KINDS[kind]; + const session = this.ctx.getSession(sessionId); - // Check if session is terminated - if (isSessionTerminated(session)) { - throw new SessionTerminatedError(sessionId); - } + // Check if session is terminated + if (isSessionTerminated(session)) { + throw new SessionTerminatedError(sessionId); + } - const threadId = session.proxyManager?.getCurrentThreadId(); - this.ctx.logger.info( - `[SM ${logTag} ${sessionId}] Entered. Current state: ${session.state}, ThreadID: ${threadId}` - ); + const threadId = session.proxyManager?.getCurrentThreadId(); + this.ctx.logger.info( + `[SM ${logTag} ${sessionId}] Entered. Current state: ${session.state}, ThreadID: ${threadId}` + ); - if (!session.proxyManager || !session.proxyManager.isRunning()) { - throw new ProxyNotRunningError(sessionId, operation); - } - if (session.state !== SessionState.PAUSED) { - this.ctx.logger.warn(`[SM ${logTag} ${sessionId}] Not paused. State: ${session.state}`); - return { success: false, error: notPausedError(session), state: session.state }; - } - if (typeof threadId !== 'number') { - this.ctx.logger.warn(`[SM ${logTag} ${sessionId}] No current thread ID.`); - return { success: false, error: 'No current thread ID', state: session.state }; - } + if (!session.proxyManager || !session.proxyManager.isRunning()) { + throw new ProxyNotRunningError(sessionId, operation); + } + if (session.state !== SessionState.PAUSED) { + this.ctx.logger.warn(`[SM ${logTag} ${sessionId}] Not paused. State: ${session.state}`); + return { success: false, error: notPausedError(session), state: session.state }; + } + if (typeof threadId !== 'number') { + this.ctx.logger.warn(`[SM ${logTag} ${sessionId}] No current thread ID.`); + return { success: false, error: 'No current thread ID', state: session.state }; + } - // Read the starting stack for every adapter (issue #1180): one bounded - // stackTrace supplies the raw top frame (JS pending hints and Dart - // same-line repeats) and the policy-filtered stack (landing provenance and - // changedVariables call identity, issues #1183/#1184). - const repeatsOnSameLine = - kind === 'stepOver' && this.ctx.selectPolicy(session.language).stepsByTokenPosition === true; - const origin = await this.readStepOrigin(session, sessionId, threadId, stopBudget); - const fromFrame = origin?.rawTop; - const stepFilterHint = kind === 'stepInto' ? this.describeStepInFilter(session, sessionId) : undefined; - const describePending = (record: StepperRecord | undefined): string | undefined => - this.describePendingStop(session, sessionId, 'step', fromFrame, record); - - if (stopBudget.expired) return { success: false, state: session.state, error: ErrorMessages.stopReadBudgetExpired(stopBudget.budgetMs) }; - - // 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 - // continue_execution or a second step can have resumed the thread, or - // the session can have ended, in the meantime. Without this the step - // would go to a running thread and its rejection would flip a healthy - // session to ERROR. - if (isSessionTerminated(session)) { - throw new SessionTerminatedError(sessionId); - } - if (!session.proxyManager || !session.proxyManager.isRunning()) { - throw new ProxyNotRunningError(sessionId, operation); - } - if (session.state !== SessionState.PAUSED) { - this.ctx.logger.warn(`[SM ${logTag} ${sessionId}] No longer paused after the origin read. State: ${session.state}`); - return { success: false, error: notPausedError(session), state: session.state }; - } + // Read the starting stack for every adapter (issue #1180): one bounded + // stackTrace supplies the raw top frame (JS pending hints and Dart + // same-line repeats) and the policy-filtered stack (landing provenance and + // changedVariables call identity, issues #1183/#1184). + const repeatsOnSameLine = + kind === 'stepOver' && this.ctx.selectPolicy(session.language).stepsByTokenPosition === true; + const origin = await this.readStepOrigin(session, sessionId, threadId); + const fromFrame = origin?.rawTop; + const stepFilterHint = kind === 'stepInto' ? this.describeStepInFilter(session, sessionId) : undefined; + const describePending = (record: StepperRecord | undefined): string | undefined => + this.describePendingStop(session, sessionId, 'step', fromFrame, record); + + // 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 + // continue_execution or a second step can have resumed the thread, or + // the session can have ended, in the meantime. Without this the step + // would go to a running thread and its rejection would flip a healthy + // session to ERROR. + if (isSessionTerminated(session)) { + throw new SessionTerminatedError(sessionId); + } + if (!session.proxyManager || !session.proxyManager.isRunning()) { + throw new ProxyNotRunningError(sessionId, operation); + } + if (session.state !== SessionState.PAUSED) { + this.ctx.logger.warn(`[SM ${logTag} ${sessionId}] No longer paused after the origin read. State: ${session.state}`); + return { success: false, error: notPausedError(session), state: session.state }; + } - this.ctx.logger.info(`[SM ${logTag} ${sessionId}] Sending DAP '${command}' for threadId ${threadId}`); + this.ctx.logger.info(`[SM ${logTag} ${sessionId}] Sending DAP '${command}' for threadId ${threadId}`); - // Set once the step (and any same-line repeats) has landed: a failure - // after that is in reading the answer, not in the resume. - let landed = false; - try { - // The last landing read, whatever attempt made it (issue #983): the - // snapshot is composed once per ANSWER, after any same-line repeats, - // under the pin that landing was read with. - let finalRead: StepLandingRead | undefined; - const stepOptions: StepOperationOptions = { - deadline: stopBudget, - command, - flavor: kind, - toolName, - threadId, - logTag, - successMessage, - describePending, - ...(origin ? { stepOrigin: origin } : {}), - ...(stepFilterHint ? { stepFilterHint } : {}), - ...(fromFrame ? { origin: { file: fromFrame.file, line: fromFrame.line, column: fromFrame.column } } : {}), - onLanding: (read) => { finalRead = read; }, - }; - const first = await this.executeStep(session, sessionId, stepOptions); - const result = repeatsOnSameLine && origin?.rawTop - ? await this.repeatWhileOnOriginLine(session, sessionId, stepOptions, origin, first) - : first; - landed = true; - const read = finalRead; - if ( - result.success && - result.data !== undefined && - !result.data.pending && - session.state === SessionState.PAUSED && - read?.pin !== undefined && - read.landing !== undefined - ) { - return await this.withStepSnapshot(session, sessionId, logTag, result, { ...read, pin: read.pin, landing: read.landing }, stopBudget); - } - return trackStopAnswerState(result, () => session.state); - } catch (error) { - const errorMessage = getErrorMessage(error); - this.ctx.logger.error(`[SM ${logTag} ${sessionId}] Error during step:`, error); - if (!(error instanceof DapResponseError) && !isTerminalSessionState(session.state)) { - this.ctx.updateState( - session, - SessionState.ERROR, - landed ? { site: 'step.failed', event: 'answer-failed' } : { site: 'step.failed', event: 'resume-failed' } - ); - } - return { success: false, error: errorMessage, state: session.state }; + // Set once the step (and any same-line repeats) has landed: a failure + // after that is in reading the answer, not in the resume. + let landed = false; + try { + // The last landing read, whatever attempt made it (issue #983): the + // snapshot is composed once per ANSWER, after any same-line repeats, + // under the pin that landing was read with. + let finalRead: StepLandingRead | undefined; + const stepOptions: StepOperationOptions = { + command, + flavor: kind, + toolName, + threadId, + logTag, + successMessage, + describePending, + ...(origin ? { stepOrigin: origin } : {}), + ...(stepFilterHint ? { stepFilterHint } : {}), + ...(fromFrame ? { origin: { file: fromFrame.file, line: fromFrame.line, column: fromFrame.column } } : {}), + onLanding: (read) => { finalRead = read; }, + }; + const first = await this.executeStep(session, sessionId, stepOptions); + const result = repeatsOnSameLine && origin?.rawTop + ? await this.repeatWhileOnOriginLine(session, sessionId, stepOptions, origin, first) + : first; + landed = true; + const read = finalRead; + if ( + result.success && + result.data !== undefined && + !result.data.pending && + session.state === SessionState.PAUSED && + read?.pin !== undefined && + read.landing !== undefined + ) { + return await this.withStepSnapshot(session, sessionId, logTag, result, { ...read, pin: read.pin, landing: read.landing }); } - } finally { - if (!retained) stopBudget.dispose(); + if (session.state !== SessionState.PAUSED && result.state === SessionState.PAUSED) { + if (isTerminalSessionState(session.state) && finalRead) return finalRead.endedAnswer(); + return { success: true, state: session.state, data: { message: 'The program resumed while this answer was being read.', pending: true } }; + } + return result; + } catch (error) { + const errorMessage = getErrorMessage(error); + this.ctx.logger.error(`[SM ${logTag} ${sessionId}] Error during step:`, error); + if (!(error instanceof DapResponseError) && !isTerminalSessionState(session.state)) { + this.ctx.updateState( + session, + SessionState.ERROR, + landed ? { site: 'step.failed', event: 'answer-failed' } : { site: 'step.failed', event: 'resume-failed' } + ); + } + return { success: false, error: errorMessage, state: session.state }; } } @@ -461,7 +454,6 @@ export class ExecutionController { return new Promise((resolve) => { let settled = false; - const graceBudget = deadline(this.ctx.tunables.stepGraceMs, { parent: options.deadline, label: 'step grace' }); // Rule 1's flag: "a stop has been observed, the stop path owns the // settle". Set as the first statement of onStopped, so every other path // can tell "nothing stopped" from "stopped, still resolving where". @@ -483,7 +475,7 @@ export class ExecutionController { proxyManager.off('exited', onExited); proxyManager.off('exit', onExit); proxyManager.off('dap-event', onDapEvent); - graceBudget.dispose(); + clearTimeout(timeout); }; const settle = (result: DebugResult) => { @@ -593,7 +585,8 @@ export class ExecutionController { noProgramFrame: landing.noProgramFrame === true } ); - deliver = () => this.recordDeliveredStepFilterHint(session, candidateHint, provenanceNote); + const run = session.run; + deliver = () => { if (session.run === run) this.recordDeliveredStepFilterHint(session, candidateHint, provenanceNote); }; const mergedNotes = [adapterDescription, landing.note, provenanceNote].filter( (part): part is string => typeof part === 'string' && part.length > 0 ); @@ -637,11 +630,11 @@ export class ExecutionController { return; } stopSeen = true; - graceBudget.dispose(); + clearTimeout(timeout); // Where the step landed, through the resolver (issue #904), under a // pin of the stop taken here, before the read's first await: a failed // read answers no location and never fails the step. - const read = await readPinnedStop(this.ctx, sessionId, options.logTag, { snapshot: false, deadline: options.deadline }); + const read = await readPinnedStop(this.ctx, sessionId, options.logTag, { snapshot: false }); const builders = { answerAgain: answerFor, changedAnswer, endedAnswer }; // Rule 2. An ended event that reached the listeners below has already // settled with its own wording; this covers the endings that did not @@ -650,6 +643,10 @@ export class ExecutionController { settle(endedAnswer()); return; } + if (session.state !== SessionState.PAUSED) { + settle({ success: true, state: session.state, data: { message: 'The program resumed while this answer was being read.', pending: true } }); + return; + } if (read.status === 'changed') { options.onLanding?.({ reread: true, ...builders }); const changed = changedAnswer(read.current); @@ -657,12 +654,8 @@ export class ExecutionController { settle(changed); return; } - if (session.state !== SessionState.PAUSED) { - settle(resultFor('The program resumed while this answer was being read.')); - return; - } const answer = answerFor(read.pin, read.landing); - options.onLanding?.({ landing: read.landing, pin: read.pin, reread: read.reread, ...builders, deliver: answer.deliver }); + options.onLanding?.({ landing: read.landing, pin: read.pin, reread: read.reread, startedAt: read.startedAt, deliver: answer.deliver, ...builders }); if (!settled && !options.onLanding) answer.deliver?.(); this.ctx.logger.info(`[SM ${options.logTag} ${sessionId}] ${answer.result.data?.message} Current state: ${session.state}`); settle(answer.result); @@ -672,27 +665,19 @@ export class ExecutionController { const onExited = () => settleEnded(options.exitedMessage); const onExit = () => settleEnded(options.exitedMessage); - void graceBudget.sleep(this.ctx.tunables.stepGraceMs).then(() => { - if (settled) return; + const timeout = setTimeout(() => { // Rule 1: the stop already arrived, so onStopped owns the settle and // will report where it landed. "Still executing" from here would be a // lie the caller has no way to correct. - // The stop reader owns settlement now, within the shared answer - // Deadline. Its retry receives only the time still available. + // Once stopped, the landing and locals keep their existing request + // bounds. Only a replacement read gets what remains of 35s measured + // from the first landing read; the step's grace does not limit it. if (stopSeen) { this.ctx.logger.debug( `[SM ${options.logTag} ${sessionId}] Grace window elapsed but the stop is already being resolved; standing down` ); return; } - if (options.deadline?.expired) { - settle({ success: true, state: session.state, data: { - pending: true, - message: 'The step is still executing; the answer budget expired.', - note: ErrorMessages.stopReadBudgetExpired(options.deadline.budgetMs) - } }); - return; - } this.ctx.logger.info( `[SM ${options.logTag} ${sessionId}] Step still running after ${this.ctx.tunables.stepGraceMs}ms grace window; completing asynchronously` ); @@ -715,7 +700,7 @@ export class ExecutionController { pending: true, }, }); - }); + }, this.ctx.tunables.stepGraceMs); proxyManager.on('stopped', onStopped); proxyManager.on('continued', onContinued); @@ -1044,10 +1029,10 @@ export class ExecutionController { data: { message: 'Paused', ...ownStopReason(read.current), note: read.note } }; } - commitStopSnapshot(read.snapshot); this.ctx.logger.info( `[SessionManager pause] Paused session ${sessionId}. Current state: ${session.state}` ); + commitStopSnapshot(read.snapshot); return { success: true, state: session.state, @@ -1178,241 +1163,235 @@ export class ExecutionController { ...this.ctx.descendantsOf(sessionId).map((d): [string, StopId | undefined] => [d.id, stopIdOf(d)]) ]); - const waitBudget = deadline(waitMs, { parent: signal, label: 'wait_for_stop answer' }); - const retained = retainStopAnswerDeadline(waitBudget); - try { - const wait = () => waitForSubtreeSettle(this.ctx, sessionId, { - timeoutMs: waitBudget.remaining(), signal + const deadline = Date.now() + waitMs; + const wait = () => waitForSubtreeSettle(this.ctx, sessionId, { + timeoutMs: Math.max(0, deadline - Date.now()), signal + }); + let settled = await wait(); + let target = session; + // The answer's reads, made under a pin of the target's stop when it is + // paused (pinned-stop-read.ts); undefined when it was not. + let read: PinnedStopRead | undefined; + for (;;) { + if (settled.outcome === 'gone') { + return { + success: false, + error: ErrorMessages.sessionClosedWhileWaiting(sessionId), + state: SessionState.STOPPED + }; + } + // The session this answer is about: the selection's, or — pending — + // the one asked for. + target = settled.outcome === 'matched' ? settled.value : session; + + // Settle any in-flight child releases (bounded to min(1.5 s, remaining + // deadline) and cancelled on abort) BEFORE the loop's final re-check so + // a child that resumed or closed during the wait never returns a stale + // landing (issue #1221). Made with the reads, so a stop that changes + // while the releases settle is caught by the same pin. + const settleReleases = () => this.ctx.settleInFlightChildReleases(sessionId, { + timeoutMs: Math.max(0, deadline - Date.now()), + signal }); - let settled = await wait(); - let target = session; - // The answer's reads, made under a pin of the target's stop when it is - // paused (pinned-stop-read.ts); undefined when it was not. - let read: PinnedStopRead | undefined; - for (;;) { - if (settled.outcome === 'gone') { - return { - success: false, - error: ErrorMessages.sessionClosedWhileWaiting(sessionId), - state: SessionState.STOPPED - }; - } - // The session this answer is about: the selection's, or — pending — - // the one asked for. - target = settled.outcome === 'matched' ? settled.value : session; - - // Settle any in-flight child releases (bounded to min(1.5 s, remaining - // deadline) and cancelled on abort) BEFORE the loop's final re-check so - // a child that resumed or closed during the wait never returns a stale - // landing (issue #1221). Made with the reads, so a stop that changes - // while the releases settle is caught by the same pin. - const settleReleases = () => this.ctx.settleInFlightChildReleases(sessionId, { - timeoutMs: waitBudget.remaining(), - signal + if (target.state === SessionState.PAUSED) { + // Where it stopped, best effort: the same short settle and stack read + // a step or a pause does, and the snapshot behind it, both under a + // pin of the stop taken here. lastStop already carries the + // exception, so the snapshot does not repeat it. + read = await readPinnedStop(this.ctx, target.id, 'waitForStop', { + snapshot: { omitException: true }, + alsoAwait: settleReleases }); - if (target.state === SessionState.PAUSED) { - // Where it stopped, best effort: the same short settle and stack read - // a step or a pause does, and the snapshot behind it, both under a - // pin of the stop taken here. lastStop already carries the - // exception, so the snapshot does not repeat it. - read = await readPinnedStop(this.ctx, target.id, 'waitForStop', { - snapshot: { omitException: true }, - deadline: waitBudget, - alsoAwait: settleReleases - }); - } else { - read = undefined; - await settleReleases(); - } + } else { + read = undefined; + await settleReleases(); + } - try { - this.ctx.getSession(sessionId); - } catch { - settled = { outcome: 'gone' }; - continue; - } - if (target !== session && ( - !this.ctx.descendantsOf(sessionId).includes(target) || - (target.state !== SessionState.PAUSED && !isTerminalSessionState(target.state)) - )) { - // A selected child may be closed or resumed by another caller while - // the answer is assembled. Re-select the tree under the ORIGINAL - // deadline: never return a removed id, or a pending root answer with - // the child's state. A still-present child that naturally ended keeps - // the ordinary ended-at-settle contract, including its recorded stop. - // waitForSubtreeSettle intentionally checks current state even with - // a zero timeout. That is useful for an initial read, but retries - // must not keep selecting alternating children past this deadline. - settled = waitBudget.expired - ? { outcome: signal?.aborted ? 'aborted' : 'timeout' } - : await wait(); - continue; - } - break; + try { + this.ctx.getSession(sessionId); + } catch { + settled = { outcome: 'gone' }; + continue; } - const tree = () => describeTreeAnswer(session, this.ctx.descendantsOf(sessionId)); - // Every answer that carries the run's `childrenReleased` says what it means - // (issue #1137): read from the session asked about, as the count is. - const explained = (message: string): string => withReleasedChildren(message, describeReleasedChildren(session)); - // Emit a redacted copy of the stop record (issue #982); the stored record - // is never mutated. - const emitStop = (stop: SessionStopInfo): SessionStopInfo => - this.ctx.redactionEnabled() ? redactStopInfo(stop) : stop; - - const state = target.state; - // Rule 2 of the settle contract: a session that is over by now is - // reported as ended, with the stop that landed during this wait if there - // was one — an exception stop and the exit can arrive in one tick. A stop - // from before the wait is not this wait's to report: the program was - // resumed past it. - const stopDuringWait = - target.lastStop && stopIdOf(target) !== stopBefore.get(target.id) ? { lastStop: emitStop(target.lastStop) } : {}; - if (state === SessionState.PAUSED && read?.status === 'changed') { - // The stop changed while the answer was read, and again while it was - // read a second time: the stop it is at now, no landing, and why. - const current = read.current; - return { - success: true, - state, - data: { - sessionId: target.id, - message: explained(`Paused (${current?.reason ?? 'unknown'})`), - ...(current ? { lastStop: emitStop(current.info) } : {}), - note: read.note, - ...tree() - } - }; + if (target !== session && ( + !this.ctx.descendantsOf(sessionId).includes(target) || + (target.state !== SessionState.PAUSED && !isTerminalSessionState(target.state)) + )) { + // A selected child may be closed or resumed by another caller while + // the answer is assembled. Re-select the tree under the ORIGINAL + // deadline: never return a removed id, or a pending root answer with + // the child's state. A still-present child that naturally ended keeps + // the ordinary ended-at-settle contract, including its recorded stop. + // waitForSubtreeSettle intentionally checks current state even with + // a zero timeout. That is useful for an initial read, but retries + // must not keep selecting alternating children past this deadline. + settled = Date.now() >= deadline + ? { outcome: signal?.aborted ? 'aborted' : 'timeout' } + : await wait(); + continue; } - // The stop this answer describes, and the reads made under its pin. A - // target that was not paused when it was read has no landing; if it is - // paused by now, its answer names the stop it is at and nothing more, as - // it always has (one synchronous read, nothing awaited after it). - const pinned = read?.status === 'pinned' ? read : undefined; - const stopAtLanding = pinned ? pinned.pin.stop : stopRecordOf(target); - const landing: StopLanding = pinned?.landing ?? {}; - const snapshot = pinned?.snapshot; - const location = landing.location; - if (state === SessionState.PAUSED && stopAtLanding) { - commitStopSnapshot(snapshot); - const where = location ? ` at ${location.file}:${location.line}` : ''; - let waitLanding = landing; - if (stopAtLanding.reason === 'step' && target.lastStepProvenance?.stopId === stopAtLanding.id) { - const prov = target.lastStepProvenance; - const landedOnOriginThread = - landing.stackResult?.threadId === undefined || landing.stackResult.threadId === prov.origin?.threadId; - const candidateHint = - prov.flavor === 'stepInto' - ? this.undeliveredStepFilterHint(target, this.describeStepInFilter(target, target.id)) - : undefined; - const provenanceNote = compareStepOriginAndLanding( - prov.flavor, - landedOnOriginThread ? prov.origin : undefined, - landing.stackResult?.frames ?? [], - { - stepFilterHint: candidateHint, - hasStepperWalkNote: stopAtLanding.info.text !== undefined, - noProgramFrame: landing.noProgramFrame === true - } - ); - if (provenanceNote) { - this.recordDeliveredStepFilterHint(target, candidateHint, provenanceNote); - waitLanding = { - ...landing, - note: landing.note ? `${landing.note} ${provenanceNote}` : provenanceNote - }; - } + break; + } + const tree = () => describeTreeAnswer(session, this.ctx.descendantsOf(sessionId)); + // Every answer that carries the run's `childrenReleased` says what it means + // (issue #1137): read from the session asked about, as the count is. + const explained = (message: string): string => withReleasedChildren(message, describeReleasedChildren(session)); + // Emit a redacted copy of the stop record (issue #982); the stored record + // is never mutated. + const emitStop = (stop: SessionStopInfo): SessionStopInfo => + this.ctx.redactionEnabled() ? redactStopInfo(stop) : stop; + + const state = target.state; + // Rule 2 of the settle contract: a session that is over by now is + // reported as ended, with the stop that landed during this wait if there + // was one — an exception stop and the exit can arrive in one tick. A stop + // from before the wait is not this wait's to report: the program was + // resumed past it. + const stopDuringWait = + target.lastStop && stopIdOf(target) !== stopBefore.get(target.id) ? { lastStop: emitStop(target.lastStop) } : {}; + if (state === SessionState.PAUSED && read?.status === 'changed') { + // The stop changed while the answer was read, and again while it was + // read a second time: the stop it is at now, no landing, and why. + const current = read.current; + return { + success: true, + state, + data: { + sessionId: target.id, + message: explained(`Paused (${current?.reason ?? 'unknown'})`), + ...(current ? { lastStop: emitStop(current.info) } : {}), + note: read.note, + ...tree() } - return { - success: true, - state, - data: { - sessionId: target.id, - message: explained(`Paused (${stopAtLanding.reason})${where}`), - lastStop: emitStop(stopAtLanding.info), - ...landingFields(waitLanding), - ...(snapshot ? { snapshot } : {}), - ...tree() - } - }; - } - if (state === SessionState.ERROR) { - const detail = target.lastProxyError ? `: ${target.lastProxyError}` : ''; - const which = target === session ? 'The debug session' : `Child session ${target.id}`; - return { - success: true, - state, - data: { sessionId: target.id, message: explained(`${which} ended in an error state${detail}`), ...stopDuringWait, ...tree() } - }; - } - if (state === SessionState.STOPPED) { - // Only the session itself can be selected already ended (rule 3); a - // selected descendant can also end while its answer is assembled. - // No stop was recorded in this launch: - // the program ran past every breakpoint, and the answer says which — - // the same run-to-completion summary the launch gives when the program - // ends inside its hold (issues #701, #1033); it already joins the - // adapter's reading of the end (issue #877). A program resumed past a - // stop keeps the plain message: its breakpoints were not all missed. - const ranPast = target.lastStop ? undefined : buildRunToCompletionSummary(target); - const outputTail = ranPast ? ranPast.data.outputTail : exitOutputTail(target); - return { - success: true, - state, - data: { - sessionId: target.id, - message: explained(ranPast - ? ranPast.summary - : `${withOutputTailClause(`${describeProgramEnd(target.exitCode)}.`, outputTail)}${target.programEndExplanation?.note ? ` ${target.programEndExplanation.note}` : ''}`), - ...(typeof target.exitCode === 'number' ? { exitCode: target.exitCode } : {}), - ...(outputTail ? { outputTail } : {}), - ...(ranPast?.data ?? {}), - ...(target.programEndExplanation ? { programEnd: target.programEndExplanation } : {}), - ...stopDuringWait, - ...tree() + }; + } + // The stop this answer describes, and the reads made under its pin. A + // target that was not paused when it was read has no landing; if it is + // paused by now, its answer names the stop it is at and nothing more, as + // it always has (one synchronous read, nothing awaited after it). + const pinned = read?.status === 'pinned' ? read : undefined; + const stopAtLanding = pinned ? pinned.pin.stop : stopRecordOf(target); + const landing: StopLanding = pinned?.landing ?? {}; + const snapshot = pinned?.snapshot; + const location = landing.location; + if (state === SessionState.PAUSED && stopAtLanding) { + commitStopSnapshot(snapshot); + const where = location ? ` at ${location.file}:${location.line}` : ''; + let waitLanding = landing; + if (stopAtLanding.reason === 'step' && target.lastStepProvenance?.stopId === stopAtLanding.id) { + const prov = target.lastStepProvenance; + const landedOnOriginThread = + landing.stackResult?.threadId === undefined || landing.stackResult.threadId === prov.origin?.threadId; + const candidateHint = + prov.flavor === 'stepInto' + ? this.undeliveredStepFilterHint(target, this.describeStepInFilter(target, target.id)) + : undefined; + const provenanceNote = compareStepOriginAndLanding( + prov.flavor, + landedOnOriginThread ? prov.origin : undefined, + landing.stackResult?.frames ?? [], + { + stepFilterHint: candidateHint, + hasStepperWalkNote: stopAtLanding.info.text !== undefined, + noProgramFrame: landing.noProgramFrame === true } - }; + ); + if (provenanceNote) { + this.recordDeliveredStepFilterHint(target, candidateHint, provenanceNote); + waitLanding = { + ...landing, + note: landing.note ? `${landing.note} ${provenanceNote}` : provenanceNote + }; + } } - this.ctx.logger.info( - `[SessionManager waitForStop] Session ${sessionId} still ${state} after ${waitMs}ms (${settled.outcome}); answering with pending` - ); - // What is armed now words the answer: with something armed, that it stays - // armed; with nothing, no pause is promised. An entry stop is not part of - // it — that belongs to the launch, which is behind a running program. - const arming = describeLaunchArming(session, false); - const pendingClause = state === SessionState.RUNNING - ? buildPendingAttachBreakpointClause(arming, this.runOf(session)) - : undefined; - const inFlightStep = - state === SessionState.RUNNING && session.inFlightStep - ? { - kind: session.inFlightStep.kind, - ageSeconds: Math.max(1, Math.round((Date.now() - session.inFlightStep.sentAt) / 1000)) - } - : undefined; return { success: true, state, data: { - sessionId: session.id, - message: explained(ErrorMessages.waitForStopPending( - waitMs / 1000, - state === SessionState.INITIALIZING ? 'initializing' : 'running', - { - ...(arming.armed ? { armedSummary: arming.summary } : {}), - ...(arming.loggingSummary ? { loggingSummary: arming.loggingSummary } : {}), - ...(debuggerOffWhy(session) ? { debuggerOffWhy: debuggerOffWhy(session) } : {}), - ...(inFlightStep ? { inFlightStep } : {}), - attachBreakpointClause: pendingClause, - noUncaughtStop: arming.noUncaughtStop - } - )), - pending: true, + sessionId: target.id, + message: explained(`Paused (${stopAtLanding.reason})${where}`), + lastStop: emitStop(stopAtLanding.info), + ...landingFields(waitLanding), + ...(snapshot ? { snapshot } : {}), + ...tree() + } + }; + } + if (state === SessionState.ERROR) { + const detail = target.lastProxyError ? `: ${target.lastProxyError}` : ''; + const which = target === session ? 'The debug session' : `Child session ${target.id}`; + return { + success: true, + state, + data: { sessionId: target.id, message: explained(`${which} ended in an error state${detail}`), ...stopDuringWait, ...tree() } + }; + } + if (state === SessionState.STOPPED) { + // Only the session itself can be selected already ended (rule 3); a + // selected descendant can also end while its answer is assembled. + // No stop was recorded in this launch: + // the program ran past every breakpoint, and the answer says which — + // the same run-to-completion summary the launch gives when the program + // ends inside its hold (issues #701, #1033); it already joins the + // adapter's reading of the end (issue #877). A program resumed past a + // stop keeps the plain message: its breakpoints were not all missed. + const ranPast = target.lastStop ? undefined : buildRunToCompletionSummary(target); + const outputTail = ranPast ? ranPast.data.outputTail : exitOutputTail(target); + return { + success: true, + state, + data: { + sessionId: target.id, + message: explained(ranPast + ? ranPast.summary + : `${withOutputTailClause(`${describeProgramEnd(target.exitCode)}.`, outputTail)}${target.programEndExplanation?.note ? ` ${target.programEndExplanation.note}` : ''}`), + ...(typeof target.exitCode === 'number' ? { exitCode: target.exitCode } : {}), + ...(outputTail ? { outputTail } : {}), + ...(ranPast?.data ?? {}), + ...(target.programEndExplanation ? { programEnd: target.programEndExplanation } : {}), + ...stopDuringWait, ...tree() } }; - } finally { - if (!retained) waitBudget.dispose(); } + this.ctx.logger.info( + `[SessionManager waitForStop] Session ${sessionId} still ${state} after ${waitMs}ms (${settled.outcome}); answering with pending` + ); + // What is armed now words the answer: with something armed, that it stays + // armed; with nothing, no pause is promised. An entry stop is not part of + // it — that belongs to the launch, which is behind a running program. + const arming = describeLaunchArming(session, false); + const pendingClause = state === SessionState.RUNNING + ? buildPendingAttachBreakpointClause(arming, this.runOf(session)) + : undefined; + const inFlightStep = + state === SessionState.RUNNING && session.inFlightStep + ? { + kind: session.inFlightStep.kind, + ageSeconds: Math.max(1, Math.round((Date.now() - session.inFlightStep.sentAt) / 1000)) + } + : undefined; + return { + success: true, + state, + data: { + sessionId: session.id, + message: explained(ErrorMessages.waitForStopPending( + waitMs / 1000, + state === SessionState.INITIALIZING ? 'initializing' : 'running', + { + ...(arming.armed ? { armedSummary: arming.summary } : {}), + ...(arming.loggingSummary ? { loggingSummary: arming.loggingSummary } : {}), + ...(debuggerOffWhy(session) ? { debuggerOffWhy: debuggerOffWhy(session) } : {}), + ...(inFlightStep ? { inFlightStep } : {}), + attachBreakpointClause: pendingClause, + noUncaughtStop: arming.noUncaughtStop + } + )), + pending: true, + ...tree() + } + }; } /** @@ -1430,41 +1409,51 @@ export class ExecutionController { sessionId: string, logTag: string, result: DebugResult, - read: StepLandingRead & { pin: StopPin; landing: StopLanding }, - budget: Deadline + read: StepLandingRead & { pin: StopPin; landing: StopLanding } ): Promise> { + const startedAt = read.startedAt ?? startStopRead(); + const changed = (note: string, current = stopRecordOf(session)) => { + const answer = read.changedAnswer(current); + answer.data!.note = note; + return answer; + }; + const resumed = (): DebugResult => ({ success: true, state: session.state, + data: { message: 'The program resumed while this answer was being read.', pending: true } }); let answer = result; let deliver = read.deliver; - let snapshot = await composeStopSnapshot(this.ctx, sessionId, read.landing.stackResult, logTag, { pin: read.pin, deadline: budget }); - if (isTerminalSessionState(session.state)) return read.endedAnswer(); - if (session.state !== SessionState.PAUSED) return trackStopAnswerState(result, () => session.state); - if (budget.expired) { - const expired = read.changedAnswer(stopRecordOf(session)); - expired.data!.note = ErrorMessages.stopReadBudgetExpired(budget.budgetMs); - return expired; + let snapshot; + const compose = (budget?: Deadline) => composeStopSnapshot(this.ctx, sessionId, read.landing.stackResult, logTag, { + pin: read.pin, ...(budget ? { deadline: budget } : {}) + }); + if (read.reread) { + const completion = await rereadStop(startedAt, compose); + if (isTerminalSessionState(session.state)) return read.endedAnswer(); + if (session.state !== SessionState.PAUSED) return resumed(); + if (completion.status === 'expired') return changed(completion.note); + snapshot = completion.value; + } else { + snapshot = await compose(); } + if (isTerminalSessionState(session.state)) return read.endedAnswer(); + if (session.state !== SessionState.PAUSED) return resumed(); if (pinBroken(session, read.pin)) { - if (read.reread) { - return read.changedAnswer(stopRecordOf(session)); - } - this.ctx.logger.info(`[SM ${logTag} ${sessionId}] The stop changed under the step's snapshot; reading the stop now current`); - const again = await readPinnedStop(this.ctx, sessionId, logTag, { rereads: 0, deadline: budget }); - if (isTerminalSessionState(session.state)) { - return read.endedAnswer(); - } - if (again.status === 'changed') { - const changed = read.changedAnswer(again.current); - changed.data!.note = again.note; - return changed; - } + if (read.reread) return read.changedAnswer(stopRecordOf(session)); + const retry = await rereadStop(startedAt, budget => readPinnedStop(this.ctx, sessionId, logTag, { rereads: 0, deadline: budget, startedAt })); + if (isTerminalSessionState(session.state)) return read.endedAnswer(); + if (session.state !== SessionState.PAUSED) return resumed(); + if (retry.status === 'expired') return changed(retry.note); + const again = retry.value; + if (again.status === 'changed') return changed(again.note, again.current); const rebuilt = read.answerAgain(again.pin, again.landing); deliver = rebuilt.deliver; answer = rebuilt.result; snapshot = again.snapshot; } - const completed = trackStopAnswerState(snapshot && answer.data ? { ...answer, data: { ...answer.data, snapshot } } : answer, () => session.state); - if (completed.state === SessionState.PAUSED) { commitStopSnapshot(snapshot); deliver?.(); } - return completed; + // Commit only the selected answer. Handler failure/cancellation after this + // session-layer return does not undo what it selected. + commitStopSnapshot(snapshot); + deliver?.(); + return snapshot && answer.data ? { ...answer, state: session.state, data: { ...answer.data, snapshot } } : { ...answer, state: session.state }; } /** @@ -1479,14 +1468,19 @@ export class ExecutionController { private async readStepOrigin( session: ManagedSession, sessionId: string, - threadId: number, - parent?: Deadline + threadId: number ): Promise { const boundMs = Math.max(1, Math.floor(this.ctx.tunables.stepGraceMs / 5)); const pin = pinStop(session); - const budget = deadline(boundMs, { parent, label: 'step origin' }); + let timer: ReturnType | undefined; + const late = new Promise((resolve) => { + timer = setTimeout(() => resolve(undefined), boundMs); + }); try { - const detailed = await budget.race(this.ctx.getStackTraceDetailed(sessionId, threadId, true, { ensureStackReady: false, pin, deadline: budget })); + const detailed = await Promise.race([ + this.ctx.getStackTraceDetailed(sessionId, threadId, true, { ensureStackReady: false, pin }), + late + ]); if (!detailed) { this.ctx.logger.debug(`[SM step ${sessionId}] Origin stack read exceeded ${boundMs}ms; stepping without it`); return undefined; @@ -1501,7 +1495,9 @@ export class ExecutionController { this.ctx.logger.debug(`[SM step ${sessionId}] Could not read the origin stack before stepping:`, error); return undefined; } finally { - budget.dispose(); + if (timer !== undefined) { + clearTimeout(timer); + } } } @@ -1551,7 +1547,7 @@ export class ExecutionController { rereadFailedOnSameLine = true; break; } - const here = await this.readStepOrigin(session, sessionId, threadId, stepOptions.deadline); + const here = await this.readStepOrigin(session, sessionId, threadId); // Re-check after the read, as the step preamble does: a continue or // another step may have resumed the thread meanwhile. if (session.state !== SessionState.PAUSED) { @@ -1673,10 +1669,7 @@ export class ExecutionController { provenanceNote: string | undefined ): void { if (hint && provenanceNote?.endsWith(hint)) { - const run = session.run; - publishStopEffect(() => { - if (session.run === run) (run.deliveredStepFilterHints ??= new Set()).add(hint); - }, payload => containsStopNote(payload, provenanceNote)); + (session.run.deliveredStepFilterHints ??= new Set()).add(hint); } } diff --git a/src/session/inspection/frame-anchor-resolver.ts b/src/session/inspection/frame-anchor-resolver.ts index de71329c6..d1f528a1a 100644 --- a/src/session/inspection/frame-anchor-resolver.ts +++ b/src/session/inspection/frame-anchor-resolver.ts @@ -261,7 +261,9 @@ export class FrameAnchorResolver { const proxyManager = session.proxyManager; const policy = this.ctx.selectPolicy(session.language); try { - let rawFrames = await this.requestRawStackFrames(sessionId, proxyManager, effectiveThreadId, { within: opts?.deadline }); + let rawFrames = await this.requestRawStackFrames(sessionId, proxyManager, effectiveThreadId, { + within: opts?.deadline, ...(opts?.deadline ? { timeoutMs: 30_000 } : {}) + }); if (opts?.pin && !stillAtGate()) return emptyResult(); let note: string | undefined; let resultThreadId = effectiveThreadId; diff --git a/src/session/inspection/pinned-stop-read.ts b/src/session/inspection/pinned-stop-read.ts index 585bc6085..be355f583 100644 --- a/src/session/inspection/pinned-stop-read.ts +++ b/src/session/inspection/pinned-stop-read.ts @@ -1,147 +1,109 @@ -/** Read a stop under one identity and one deadline, with at most one re-read. */ +/** + * An answer describes one stop, as that stop was when its reads completed. + * Files are enriched afterwards; freshness at serialization is not promised. + * First reads retain their existing timing. Only a re-read gets a deadline. + */ import { deadline, SessionState, type Deadline } from '@debugmcp/shared'; import type { ManagedSession } from '../session-store.js'; import { pinBroken, pinStop, stopRecordOf, type StopPin, type StopRecord } from '../stop-record.js'; import type { StopSnapshot } from '../session-manager-core.js'; import { describeStopLocation, type StopLanding, type StopLandingContext } from './stop-location.js'; -import { commitStopSnapshot, composeStopSnapshot, type ComposeSnapshotOptions, type StopSnapshotContext } from './stop-snapshot.js'; -import { enrichPinnedStop, retainStopAnswerDeadline, trackStopAnswerState } from './stop-answer-effects.js'; +import { composeStopSnapshot, type ComposeSnapshotOptions, type StopSnapshotContext } from './stop-snapshot.js'; import { ErrorMessages } from '../../utils/error-messages.js'; export type PinnedStopReadContext = StopLandingContext & StopSnapshotContext; - -/** The old landing ceiling (30s DAP plus the proxy margin), shared by all reads and the retry. */ export const STOP_READ_BUDGET_MS = 35_000; +/** Starts no timer and changes no first-read timeout. */ +export function startStopRead(): number { return performance.now(); } + +/** The re-read has only what remains of 35s from the first read. */ +export async function rereadStop(startedAt: number, work: (budget: Deadline) => Promise): Promise< + { status: 'read'; value: T } | { status: 'expired'; note: string } +> { + const remaining = STOP_READ_BUDGET_MS - (performance.now() - startedAt); + if (remaining <= 0) return { status: 'expired', note: ErrorMessages.stopRereadBudgetExpired(false) }; + const budget = deadline(remaining, { label: 'stop re-read' }); + try { return { status: 'read', value: await budget.race(work(budget)) }; } + catch (error) { + if (budget.expired) return { status: 'expired', note: ErrorMessages.stopRereadBudgetExpired(true) }; + throw error; + } finally { budget.dispose(); } +} + export interface PinnedStopReadOptions { + /** Present only when this call is already the bounded re-read (the step snapshot path). */ readonly deadline?: Deadline; - /** The pin, when the caller took it earlier (before an await of its own). */ + readonly startedAt?: number; readonly pin?: StopPin; - /** Compose the snapshot behind the landing (the default); `false` reads the landing alone. */ readonly snapshot?: Omit | false; - /** - * Skip the snapshot when the session has ended under the landing read (the - * pause answer's rule 2: there is no stack left to compose from). - */ readonly skipSnapshotWhenEnded?: boolean; - /** Another wait of the answer's, made after the reads and again with them (wait_for_stop's child releases). */ readonly alsoAwait?: () => Promise; - /** How many times the reads may be made again: 1 (the default), or 0 for a caller that has spent it. */ readonly rereads?: 0 | 1; } export type PinnedStopRead = - | { - readonly status: 'pinned'; - /** The pin every read was made and checked under. */ - readonly pin: StopPin; - readonly landing: StopLanding; - readonly snapshot: StopSnapshot | undefined; - /** The reads were made a second time, because the stop changed during the first. */ - readonly reread: boolean; - } - | { - readonly status: 'changed'; - /** The stop the session is at now, which no read describes. */ - readonly current: StopRecord | undefined; - readonly note: string; - }; + | { readonly status: 'pinned'; readonly pin: StopPin; readonly landing: StopLanding; + readonly snapshot: StopSnapshot | undefined; readonly reread: boolean; readonly startedAt: number } + | { readonly status: 'changed'; readonly current: StopRecord | undefined; readonly note: string }; function sessionOrUndefined(ctx: Pick, sessionId: string): ManagedSession | undefined { - try { - return ctx.getSession(sessionId); - } catch { - return undefined; - } + try { return ctx.getSession(sessionId); } catch { return undefined; } } -/** Pin the session's stop now, or pin nothing for a session that is gone. */ export function pinSession(ctx: Pick, sessionId: string): StopPin { const session = sessionOrUndefined(ctx, sessionId); return session ? pinStop(session) : { sessionId, stop: undefined }; } -/** Read a stop's landing and snapshot under a pin, by the rule in this module's header. */ export async function readPinnedStop( - ctx: PinnedStopReadContext, - sessionId: string, - logTag: string, - opts: PinnedStopReadOptions = {} + ctx: PinnedStopReadContext, sessionId: string, logTag: string, opts: PinnedStopReadOptions = {} ): Promise { let pin = opts.pin ?? pinSession(ctx, sessionId); - const budget = opts.deadline ?? deadline(STOP_READ_BUDGET_MS, { label: 'stop answer' }); - const retained = !opts.deadline && retainStopAnswerDeadline(budget); - const changed = (expired = false): PinnedStopRead => ({ - status: 'changed', current: stopRecordOf(sessionOrUndefined(ctx, sessionId)), - note: expired ? ErrorMessages.stopReadBudgetExpired(budget.budgetMs) : ErrorMessages.stopChangedWhileRead() + const startedAt = opts.startedAt ?? startStopRead(); + const changed = (note = ErrorMessages.stopChangedWhileRead()): PinnedStopRead => ({ + status: 'changed', current: stopRecordOf(sessionOrUndefined(ctx, sessionId)), note }); - const readUnder = async (under: StopPin) => { + const readUnder = async (under: StopPin, budget?: Deadline) => { const landing = await describeStopLocation(ctx, sessionId, logTag, under, budget); let snapshot: StopSnapshot | undefined; const session = sessionOrUndefined(ctx, sessionId); - if (!pinBroken(session, under) && session?.state === SessionState.PAUSED && opts.snapshot !== false && !budget.expired) { + if (!pinBroken(session, under) && session?.state === SessionState.PAUSED && opts.snapshot !== false && !budget?.expired) { snapshot = await composeStopSnapshot(ctx, sessionId, landing.stackResult, logTag, { - ...(opts.snapshot ?? {}), pin: under, deadline: budget + ...(opts.snapshot ?? {}), pin: under, ...(budget ? { deadline: budget } : {}) }); } - if (landing.location && !pinBroken(sessionOrUndefined(ctx, sessionId), under) && !budget.expired) { - await enrichPinnedStop(sessionId, landing.location, budget); + if (opts.alsoAwait && !budget?.expired) { + if (budget) await budget.race(opts.alsoAwait()); + else await opts.alsoAwait(); } - if (opts.alsoAwait && !budget.expired) await budget.race(opts.alsoAwait()); return { landing, snapshot }; }; - try { - if (budget.expired) return changed(true); - let read = await readUnder(pin); - let reread = false; - if (budget.expired) return changed(true); - if (pinBroken(sessionOrUndefined(ctx, sessionId), pin)) { - if ((opts.rereads ?? 1) === 0 || sessionOrUndefined(ctx, sessionId)?.state !== SessionState.PAUSED) return changed(); - ctx.logger.info(`[SessionManager ${logTag} ${sessionId}] The stop changed while its answer was read; reading the stop now current`); + let read = await readUnder(pin, opts.deadline); + let reread = false; + if (pinBroken(sessionOrUndefined(ctx, sessionId), pin)) { + if ((opts.rereads ?? 1) === 0 || sessionOrUndefined(ctx, sessionId)?.state !== SessionState.PAUSED) return changed(); + const again = await rereadStop(startedAt, budget => { pin = pinSession(ctx, sessionId); - if (budget.expired) return changed(true); - read = await readUnder(pin); - reread = true; - } - if (budget.expired) return changed(true); - if (pinBroken(sessionOrUndefined(ctx, sessionId), pin)) return changed(); - return { status: 'pinned', pin, landing: read.landing, snapshot: read.snapshot, reread }; - } catch (error) { - if (budget.expired) return changed(true); - throw error; - } finally { - if (!opts.deadline && !retained) budget.dispose(); + return readUnder(pin, budget); + }); + if (again.status === 'expired') return changed(again.note); + read = again.value; + reread = true; } + if (pinBroken(sessionOrUndefined(ctx, sessionId), pin)) return changed(); + return { status: 'pinned', pin, landing: read.landing, snapshot: read.snapshot, reread, startedAt }; } - -/** What an answer takes from a pinned read (or from none, for a session that was not paused). */ export interface DescribedStop { - /** The stop the answer names: the accepted pin's, or the current record when reads were omitted. */ readonly stop: StopRecord | undefined; - /** The accepted landing; empty when there was no read, identity failed or the budget expired. */ readonly landing: StopLanding; readonly snapshot: StopSnapshot | undefined; - /** Why the landing and snapshot were omitted after an invalid or expired read. */ readonly note?: string; } -/** The fields a launch-shaped answer (launch, restart, attach, hot reload) takes from a pinned read. */ export function describedStop(read: PinnedStopRead | undefined): DescribedStop { - if (!read) { - return { stop: undefined, landing: {}, snapshot: undefined }; - } - if (read.status === 'changed') { - return { stop: read.current, landing: {}, snapshot: undefined, note: read.note }; - } + if (!read) return { stop: undefined, landing: {}, snapshot: undefined }; + if (read.status === 'changed') return { stop: read.current, landing: {}, snapshot: undefined, note: read.note }; return { stop: read.pin.stop, landing: read.landing, snapshot: read.snapshot }; } - -/** Select the caller's final state before publishing any snapshot in its answer. */ -export function completeStopAnswer(answer: T, state: () => SessionState | undefined): T { - trackStopAnswerState(answer, state); - const root = answer as { snapshot?: StopSnapshot; data?: { snapshot?: StopSnapshot; pausedChild?: { snapshot?: StopSnapshot } } }; - commitStopSnapshot(root.snapshot ?? root.data?.snapshot); - commitStopSnapshot(root.data?.pausedChild?.snapshot); - return answer; -} diff --git a/src/session/inspection/stop-answer-effects.ts b/src/session/inspection/stop-answer-effects.ts deleted file mode 100644 index bd525f6c2..000000000 --- a/src/session/inspection/stop-answer-effects.ts +++ /dev/null @@ -1,145 +0,0 @@ -/** - * An observation is published only with the answer that contains it. The MCP - * scope spans source/footprint enrichment too; direct SessionManager callers - * publish at their return boundary. Scopes are per async call, never per session. - */ -import { AsyncLocalStorage } from 'node:async_hooks'; -import { SessionState, type Deadline } from '@debugmcp/shared'; -import { ErrorMessages } from '../../utils/error-messages.js'; - -interface Publication { shown: (payload: unknown) => boolean; commit: () => void } -interface EnrichmentLocation { file: string; line: number; unresolvedSource?: boolean } -export interface StopEnrichment { - context?: { lineContent: string; surrounding: Array<{ line: number; content: string }> }; - staleBuild?: string; -} -type EnrichStop = (sessionId: string, location: EnrichmentLocation) => Promise; -interface AnswerScope { publications: Publication[]; deadlines: Deadline[]; enrich?: EnrichStop } -const scopes = new AsyncLocalStorage(); -const refreshers = new WeakMap void>(); -const managerAnswers = new WeakSet(); -const enrichments = new WeakMap(); - -/** Lets handlers recognize manager answers even after the session was removed. */ -export function isTrackedStopAnswer(value: unknown): boolean { - return typeof value === 'object' && value !== null && managerAnswers.has(value); -} - -export async function withStopAnswerEffects(work: () => Promise, enrich?: EnrichStop): Promise { - const scope: AnswerScope = { publications: [], deadlines: [], enrich }; - return scopes.run(scope, async () => { - try { return await work(); } - finally { for (const budget of scope.deadlines) budget.dispose(); } - }); -} - -/** True when the tool scope owns disposal; otherwise the reader uses finally. */ -export function retainStopAnswerDeadline(budget: Deadline): boolean { - const scope = scopes.getStore(); - if (!scope) return false; - if (!scope.deadlines.includes(budget)) scope.deadlines.push(budget); - return true; -} - -export function stopAnswerDeadline(): Deadline | undefined { return scopes.getStore()?.deadlines[0]; } - -/** Called inside the pinned transaction, so its caller checks identity afterwards. */ -export async function enrichPinnedStop(sessionId: string, location: EnrichmentLocation, budget: Deadline): Promise { - const enrich = scopes.getStore()?.enrich; - if (!enrich || budget.expired) return; - const result = await budget.race(enrich(sessionId, location)); - enrichments.set(location, result); -} - -export function stopEnrichmentFor(location: object): StopEnrichment | undefined { return enrichments.get(location); } - -/** Source/build reads belong to the same answer budget as its debugger reads. */ -export async function readStopEnrichment(work: () => Promise, answer: Record): Promise { - const budget = stopAnswerDeadline(); - try { return budget ? await budget.request(work) : await work(); } - catch (error) { - if (!budget?.expired) throw error; - const data = answer.data && typeof answer.data === 'object' ? answer.data as Record : undefined; - for (const part of [answer, data]) { - if (!part) continue; - for (const field of ['location', 'context', 'snapshot', 'threadId']) delete part[field]; - part.note = ErrorMessages.stopReadBudgetExpired(budget.budgetMs); - } - return undefined; - } -} - -function visit(value: unknown, action: (value: object) => void, seen = new Set()): void { - if (!value || typeof value !== 'object' || seen.has(value)) return; - seen.add(value); - action(value); - for (const child of Object.values(value)) visit(child, action, seen); -} - -export function publishStopEffect(commit: () => void, shown: (payload: unknown) => boolean): void { - const scope = scopes.getStore(); - if (scope) scope.publications.push({ commit, shown }); - else commit(); -} - -export function containsStopValue(payload: unknown, value: object): boolean { - let found = false; - visit(payload, item => { found ||= item === value; }); - return found; -} - -export function containsStopNote(payload: unknown, note: string): boolean { - let found = false; - visit(payload, item => { - const text = (item as { note?: unknown }).note; - found ||= typeof text === 'string' && text.includes(note); - }); - return found; -} - -/** Re-read state after the handler's own awaits, immediately before serialization. */ -export function refreshStopAnswer(payload: unknown): void { - visit(payload, item => refreshers.get(item)?.()); -} - -export function beforeStopAnswerReturn(answer: object, refresh: () => void): void { - const previous = refreshers.get(answer); - refreshers.set(answer, () => { previous?.(); refresh(); }); -} - -export function publishReturnedStopEffects(payload: unknown): void { - const scope = scopes.getStore(); - if (!scope) return; - for (const publication of scope.publications.splice(0)) if (publication.shown(payload)) publication.commit(); -} - -const STOP_FIELDS = ['location', 'context', 'snapshot', 'threadId', 'note', 'reason', 'stopReason', 'rawStopReason', 'lastStop']; -export function trackStopAnswerState(answer: T, state: () => SessionState | undefined): T { - managerAnswers.add(answer); - const data = (answer as { data?: unknown }).data; - if (data && typeof data === 'object') managerAnswers.add(data); - const refresh = () => { - const record = answer as Record; - const current = state() ?? SessionState.STOPPED; - if (record.state === undefined) return; - const data = record.data && typeof record.data === 'object' ? record.data as Record : undefined; - const invalidLanding = current !== SessionState.PAUSED && [record, data].some(part => part && (part.location || part.snapshot || part.context)); - if (record.state === current && !invalidLanding) return; - // This is an outbound projection, never a ManagedSession state write. - Object.assign(record, { state: current }); - for (const part of [record, data]) { - if (!part) continue; - for (const field of STOP_FIELDS) delete part[field]; - part.message = current === SessionState.RUNNING - ? 'The program resumed while this answer was being read.' - : current === SessionState.PAUSED - ? 'The program paused while this answer was being read. Call get_stack_trace to read the stop.' - : 'The session ended while this answer was being read.'; - if (current !== SessionState.RUNNING) delete part.pending; - if ('stopOnEntrySuccessful' in part && current !== SessionState.PAUSED) part.stopOnEntrySuccessful = false; - } - }; - refresh(); - refreshers.set(answer, refresh); - return answer; -} diff --git a/src/session/inspection/stop-snapshot.ts b/src/session/inspection/stop-snapshot.ts index 3be882cef..507dcbb39 100644 --- a/src/session/inspection/stop-snapshot.ts +++ b/src/session/inspection/stop-snapshot.ts @@ -16,7 +16,6 @@ * (the describeStopLocation pattern). */ import { deadline, SessionState, redactStopInfo, type Deadline } from '@debugmcp/shared'; -import { containsStopValue, publishStopEffect } from './stop-answer-effects.js'; import type { OperationsContext } from '../operations-context.js'; import type { ChangedVariable, SnapshotException, StopSnapshot } from '../session-manager-core.js'; import type { StackTraceResult } from './frame-anchor-resolver.js'; @@ -66,7 +65,9 @@ export function commitStopSnapshot(snapshot: StopSnapshot | undefined): void { const commit = pendingBaselines.get(snapshot); if (!commit) return; pendingBaselines.delete(snapshot); - publishStopEffect(commit, payload => containsStopValue(payload, snapshot)); + // Session-layer return boundary: a later handler failure or cancellation + // does not roll back an answer selected here. + commit(); } /** How many frames the snapshot shows, and how deep its locals read probes. */ @@ -264,17 +265,28 @@ export async function composeStopSnapshot( // and the walk-down (#468) exists exactly for that. A stack with no // program frame at all is caught by noProgramFrame above. const timeoutMs = ctx.tunables.snapshotLocalsTimeoutMs; - const localsBudget = deadline(timeoutMs, { parent: opts.deadline, label: 'stop snapshot locals' }); + const localsBudget = opts.deadline + ? deadline(timeoutMs, { parent: opts.deadline, label: 'stop snapshot locals re-read' }) + : undefined; + let timer: NodeJS.Timeout | undefined; try { // Failure folds into a sentinel so a read that loses the race can // never surface later as an unhandled rejection. - const raced = await localsBudget.race(ctx.extractLocalsFromResolved( - sessionId, stackResult, { maxFrames: SNAPSHOT_FRAMES, deadline: localsBudget, pin } - )).catch((error: unknown): typeof FAILED | typeof TIMED_OUT => { - if (localsBudget.expired) return TIMED_OUT; + const guardedRead = ctx.extractLocalsFromResolved( + sessionId, stackResult, { maxFrames: SNAPSHOT_FRAMES, pin, ...(localsBudget ? { deadline: localsBudget } : {}) } + ).catch((error: unknown): typeof FAILED => { ctx.logger.debug(`[SessionManager ${logTag} ${sessionId}] Snapshot locals read failed:`, error); return FAILED; }); + const raced = localsBudget + ? await localsBudget.race(guardedRead).catch((error: unknown): typeof TIMED_OUT => { + if (localsBudget.expired) return TIMED_OUT; + throw error; + }) + : await Promise.race([ + guardedRead, + new Promise(resolve => { timer = setTimeout(() => resolve(TIMED_OUT), timeoutMs); }) + ]); if (pinBroken(ctx.getSession(sessionId), pin) || ctx.getSession(sessionId).state !== SessionState.PAUSED) return undefined; if (raced === TIMED_OUT) { notes.push( @@ -356,7 +368,8 @@ export async function composeStopSnapshot( } if (stopId !== undefined) { pendingBaselines.set(snapshot, () => { - if (session.run === run && session.proxyGeneration === generation) { + if (session.run === run && session.proxyGeneration === generation && + (!session.snapshotDiffBase || stopId >= session.snapshotDiffBase.stopId)) { session.snapshotDiffBase = { stopId, frameKey, rendered: flat, complete, callerResolved }; } }); @@ -381,7 +394,8 @@ export async function composeStopSnapshot( } } } finally { - localsBudget.dispose(); + localsBudget?.dispose(); + if (timer !== undefined) clearTimeout(timer); } } diff --git a/src/session/launch/debug-launcher.ts b/src/session/launch/debug-launcher.ts index f75e25ad9..9e262a50b 100644 --- a/src/session/launch/debug-launcher.ts +++ b/src/session/launch/debug-launcher.ts @@ -34,8 +34,9 @@ import { setCuratedMessage } from '../breakpoints/hit-verification.js'; import type { CustomLaunchRequestArguments, DebugResult, LaunchResultData, PausedChildSummary } from '../session-manager-core.js'; import type { ManagedSession, ToolchainValidationState } from '../session-store.js'; import type { LaunchContext } from '../operations-context.js'; +import { commitStopSnapshot } from '../inspection/stop-snapshot.js'; import { landingFields } from '../inspection/stop-location.js'; -import { completeStopAnswer, describedStop, readPinnedStop } from '../inspection/pinned-stop-read.js'; +import { describedStop, readPinnedStop } from '../inspection/pinned-stop-read.js'; import { describeReleasedChildren, describeTreeAnswer, selectSettledInTree, withReleasedChildren } from '../execution/tree-settle.js'; import type { BreakpointController, ResyncOutcome } from '../breakpoints/breakpoint-controller.js'; import { reresolveAnchors, type AnchorResolution } from '../breakpoints/anchor-resolution.js'; @@ -59,7 +60,7 @@ import { describeLaunchTarget, describeSpawnCommand } from './spawn-command.js'; import { classifyTestRunner, TEST_RUNNER_KEY } from './test-runner-gate.js'; import type { InFlightGuard } from '../in-flight-guard.js'; import { adapterVerifiedABreakpoint, debuggerOffWhy } from '../debugger-off.js'; -import { resetStops } from '../stop-record.js'; +import { resetStops, stopRecordOf } from '../stop-record.js'; /** * A launch flag the way the adapter will see it. The proxy launcher merges @@ -756,11 +757,11 @@ export class DebugLauncher { // stop that changed before any of the answer's reads began (measured // on the JDI bridge, which reports one stop per breakpoint request at // a location, a millisecond apart). - const described = describedStop(finalSession.state === SessionState.PAUSED + let described = describedStop(finalSession.state === SessionState.PAUSED ? await readPinnedStop(this.ctx, sessionId, 'launch') : undefined); finalState = finalSession.state; - const { landing, snapshot } = finalState === SessionState.PAUSED ? described : describedStop(undefined); + let { landing, snapshot } = finalState === SessionState.PAUSED ? described : describedStop(undefined); // The policy's word is a static pin; a stop that arrived anyway is the // stronger evidence (an adapter build that ignores the flag after all): @@ -831,7 +832,7 @@ export class DebugLauncher { // Ended before the launch could report a pause (issue #701): say how // the program ended, with its exit code and the breakpoints it ran past. - const runToCompletion = + let runToCompletion = finalState === SessionState.STOPPED ? buildRunToCompletionSummary(finalSession) : undefined; @@ -894,7 +895,20 @@ export class DebugLauncher { } } - return completeStopAnswer({ + // The child read may have changed the root's state. Select this answer + // here, never by rewriting it in the handler or at serialization. + if (finalState !== finalSession.state) { + finalState = finalSession.state; + described = { ...describedStop(undefined), stop: stopRecordOf(finalSession) }; + landing = {}; + snapshot = undefined; + pausedChild = undefined; + stillRunning = undefined; + runToCompletion = finalState === SessionState.STOPPED ? buildRunToCompletionSummary(finalSession) : undefined; + } + commitStopSnapshot(snapshot); + commitStopSnapshot(pausedChild?.snapshot); + return { success: true, state: finalState, data: { @@ -934,7 +948,7 @@ export class DebugLauncher { // What this run's logpoint check found, when it found something to say (issue #1334). ...logpointChecksField(finalSession.breakpoints.values()), }, - }, () => finalSession.state); + }; } catch (error) { const diagnosticData = await failProxySetup(this.ctx, session, error, 'startDebugging'); session.failureDiagnostics = Object.keys(diagnosticData).length > 0 @@ -1217,7 +1231,8 @@ export class DebugLauncher { const warning = anchorWarnings(anchorResolution); this.ctx.logger.info(`[SessionManager] Hot restart of session ${sessionId} answered. State: ${finalState}`); - return completeStopAnswer({ + commitStopSnapshot(snapshot); + return { success: true, state: finalState, data: { @@ -1240,7 +1255,7 @@ export class DebugLauncher { // A hot restart keeps the process and its children (issue #1081). ...describeTreeAnswer(finalSession, this.ctx.descendantsOf(sessionId)), }, - }, () => finalSession.state); + }; } /** diff --git a/src/session/live-update/live-update-controller.ts b/src/session/live-update/live-update-controller.ts index 864ffe7bf..171f750a0 100644 --- a/src/session/live-update/live-update-controller.ts +++ b/src/session/live-update/live-update-controller.ts @@ -23,8 +23,10 @@ import type { BreakpointController } from '../breakpoints/breakpoint-controller. import type { ManagedSession } from '../session-store.js'; import type { LaunchContext } from '../operations-context.js'; import { waitForSessionState } from '../execution/session-state-wait.js'; +import { commitStopSnapshot } from '../inspection/stop-snapshot.js'; import { landingFields } from '../inspection/stop-location.js'; -import { completeStopAnswer, describedStop, readPinnedStop } from '../inspection/pinned-stop-read.js'; +import { describedStop, readPinnedStop } from '../inspection/pinned-stop-read.js'; +import type { StopSnapshot } from '../session-manager-core.js'; /** What a live update touches: the adapter's answer, the anchors, the session's stop. */ export type LiveUpdateContext = LaunchContext; @@ -49,6 +51,7 @@ export interface HotReloadResult { /** Statement-anchored breakpoints re-resolved against the new source (issue #464). */ anchorResolution?: AnchorResolution; warning?: string; + snapshot?: StopSnapshot; [key: string]: unknown; } @@ -121,12 +124,13 @@ export class LiveUpdateController { const after = await this.afterUpdate(current, live, first.kind === 'response' ? first.response : undefined); const body = first.kind === 'response' ? ((first.response?.body ?? {}) as Record) : {}; const observed = await this.describeState(current, first.kind !== 'response'); - return completeStopAnswer({ + commitStopSnapshot(observed.snapshot); + return { success: true, ...body, ...after, ...observed, - }, () => current.state); + }; } /** The plain path: await the response and answer it, with the anchor pass when code changed. */ @@ -199,11 +203,14 @@ export class LiveUpdateController { /** The session's state for the answer: the landing and snapshot of a stop, or `pending` while running. */ private async describeState(session: ManagedSession, raced: boolean): Promise> { - const state = session.state; - if (state === SessionState.PAUSED) { + let described; + if (session.state === SessionState.PAUSED) { // Under a pin of the stop taken before the read's first await (tracking // issue #1362): the reason is the stop the landing was read for. - const described = describedStop(await readPinnedStop(this.ctx, session.id, 'launch')); + described = describedStop(await readPinnedStop(this.ctx, session.id, 'launch')); + } + const state = session.state; + if (state === SessionState.PAUSED && described) { return { state, reason: described.stop?.reason ?? 'unknown', diff --git a/src/session/session-manager-data.ts b/src/session/session-manager-data.ts index 93a8d3727..877ddc219 100644 --- a/src/session/session-manager-data.ts +++ b/src/session/session-manager-data.ts @@ -193,7 +193,7 @@ export abstract class SessionManagerData extends SessionManagerCore { try { this.logger.info(`[SM getVariables ${sessionId}] Sending DAP 'variables' for variablesReference ${variablesReference}.`); const response = budget - ? await session.proxyManager.sendDapRequest('variables', { variablesReference }, { deadline: budget }) + ? await session.proxyManager.sendDapRequest('variables', { variablesReference }, { deadline: budget, timeoutMs: 30_000 }) : await session.proxyManager.sendDapRequest('variables', { variablesReference }); if (pin && pinBroken(session, pin)) return { variables: [], readFailed: true }; // Count only — the raw body carries unredacted values (issue #237); the @@ -306,7 +306,7 @@ export abstract class SessionManagerData extends SessionManagerCore { try { this.logger.info(`[SM ${prefix} ${sessionId}] Sending DAP 'scopes' for frameId ${frameId}.`); const response = budget - ? await session.proxyManager.sendDapRequest('scopes', { frameId }, { deadline: budget }) + ? await session.proxyManager.sendDapRequest('scopes', { frameId }, { deadline: budget, timeoutMs: 30_000 }) : await session.proxyManager.sendDapRequest('scopes', { frameId }); if (pin && pinBroken(session, pin)) return { scopes: [], readFailed: true }; this.logger.info(`[SM ${prefix} ${sessionId}] DAP 'scopes' response received. Body:`, response?.body); diff --git a/src/utils/error-messages.ts b/src/utils/error-messages.ts index 1f59f6d29..98129bd34 100644 --- a/src/utils/error-messages.ts +++ b/src/utils/error-messages.ts @@ -687,8 +687,10 @@ export const ErrorMessages = { 'The stop changed while this answer was being read; its stack and snapshot were omitted. ' + 'Call get_stack_trace again to read the current stop.', - stopReadBudgetExpired: (budgetMs: number) => - `Reading this stop exceeded the ${budgetMs} ms answer budget; its location, stack and snapshot were omitted. ` + + stopRereadBudgetExpired: (attempted: boolean) => + 'The stop changed while this answer was being read; ' + + (attempted ? 'its re-read did not complete' : 'it was not read again') + + ' within the 35000 ms window measured from the first read. Its stack and snapshot were omitted. ' + 'Call get_stack_trace again to read the current stop.', /** diff --git a/tests/core/unit/server/server-control-tools.test.ts b/tests/core/unit/server/server-control-tools.test.ts index 2b0f6cb0a..5b7ffd93f 100644 --- a/tests/core/unit/server/server-control-tools.test.ts +++ b/tests/core/unit/server/server-control-tools.test.ts @@ -340,9 +340,10 @@ describe('Server Control Tools Tests', () => { state: 'stopped', sessionLifecycle: SessionLifecycleState.TERMINATED }); - mockSessionManager.startDebugging.mockImplementation(async () => { - mockSessionManager.getSession.mockReturnValue({ run: {}, id: 'test-session', state: 'paused', sessionLifecycle: SessionLifecycleState.ACTIVE }); - return { success: true, state: 'paused', data: { reason: 'breakpoint' } }; + mockSessionManager.startDebugging.mockResolvedValue({ + success: true, + state: 'paused', + data: { reason: 'breakpoint' } }); const result = await callToolHandler({ @@ -1111,7 +1112,7 @@ describe('Server Control Tools Tests', () => { mockSessionManager.getSession.mockReturnValue({ run: {}, id: 'test-session', - state: 'paused', + state: 'running', sessionLifecycle: 'ACTIVE' }); mockSessionManager.waitForStop.mockResolvedValue({ diff --git a/tests/core/unit/server/server-inspection-tools.test.ts b/tests/core/unit/server/server-inspection-tools.test.ts index dc2cf2514..230465405 100644 --- a/tests/core/unit/server/server-inspection-tools.test.ts +++ b/tests/core/unit/server/server-inspection-tools.test.ts @@ -300,7 +300,7 @@ describe('Server Inspection Tools Tests', () => { expect(content.note).toMatch(/Signal Dispatcher/); expect(content.diagnostics).toEqual({ proxyLogPath: '/logs/proxy-test-session.log' }); expect(mockSessionManager.getStackTraceDetailed).toHaveBeenCalledWith( - 'test-session', 4, false, expect.objectContaining({ deadline: expect.any(Object) }) + 'test-session', 4, false, expect.objectContaining({ pin: expect.any(Object) }) ); expect(mockSession.proxyManager.setCurrentThreadId).not.toHaveBeenCalled(); }); diff --git a/tests/core/unit/server/stop-pin-boundaries.test.ts b/tests/core/unit/server/stop-pin-boundaries.test.ts index e640c85ee..0a83daf67 100644 --- a/tests/core/unit/server/stop-pin-boundaries.test.ts +++ b/tests/core/unit/server/stop-pin-boundaries.test.ts @@ -112,22 +112,28 @@ describe('stop pins: async boundaries', () => { expect(gap).toBe(true); expect(a.stopReason).toBe('breakpoint'); expect(a.location.line).toBe(50); }); - it('M19 an invalid landing cannot acquire the replacement exception during a locals timeout', async () => { + it('M19 replacement reaches the snapshot and its locals timeout under B alone', async () => { const s = await running(); stop('A'); + let reads = 0; vi.spyOn(ctx(), 'getStackTraceDetailed').mockImplementation(async () => { - stop('B', 'exception'); - return { frames: [{ id: 1, name: 'A', file: '/w/app.py', line: 11, column: 0 }], threadId: 1, totalFrameCount: 1, hiddenFrameCount: 0, allFramesInternal: false }; - }); - vi.spyOn(ctx(), 'extractLocalsFromResolved').mockImplementation(async () => { - deps.mockProxyManager.simulateExited(0); return new Promise(() => {}); + reads++; + if (reads === 1) stop('B', 'exception'); + return { frames: [{ id: 1, name: reads === 1 ? 'A' : 'B', file: '/w/app.py', line: reads === 1 ? 11 : 50, column: 0 }], threadId: 1, totalFrameCount: 1, hiddenFrameCount: 0, allFramesInternal: false }; }); - const pending = readPinnedStop(ctx(), s, 'review', { pin: pinStop(core.sessionManager.getSession(s)!) }); - await vi.advanceTimersByTimeAsync(2000); const a = await pending; - if (a.status === 'pinned') expect(a.snapshot?.exception).toBeUndefined(); - else { - expect(a.current?.reason).toBe('exception'); - expect(a.note).toMatch(/stop changed/i); - } + const locals = vi.spyOn(ctx(), 'extractLocalsFromResolved').mockImplementation(() => new Promise(() => {})); + let answer: Awaited> | undefined; + const pending = readPinnedStop(ctx(), s, 'review', { pin: pinStop(core.sessionManager.getSession(s)!) }).then(value => { answer = value; }); + await vi.advanceTimersByTimeAsync(3000); + expect(answer, 'the reachable locals timeout settles the accepted B snapshot').toBeDefined(); + await pending; + const a = answer!; + expect(reads).toBe(2); + expect(locals).toHaveBeenCalledTimes(1); + expect(a.status).toBe('pinned'); + if (a.status !== 'pinned') throw new Error('Expected the accepted B read'); + expect(a.landing.location?.line).toBe(50); + expect(a.snapshot?.exception?.type).toBe('B'); + expect(a.snapshot?.note).toMatch(/locals read exceeded/); }); it('M14 the origin reader rejects a replacement before using the old frames for provenance', async () => { @@ -140,11 +146,26 @@ describe('stop pins: async boundaries', () => { expect(await execution.readStepOrigin(core.sessionManager.getSession(s), s, 1)).toBeUndefined(); }); + it('an exhausted re-read window does not start another read or claim it did', async () => { + const s = await running(); stop('A'); + const stack = vi.spyOn(ctx(), 'getStackTraceDetailed').mockImplementation(async () => { + await new Promise(resolve => setTimeout(resolve, 36_000)); + stop('B', 'exception'); + return { frames: [{ id: 1, name: 'A', file: '/w/app.py', line: 11, column: 0 }], totalFrameCount: 1, hiddenFrameCount: 0, allFramesInternal: false }; + }); + const pending = readPinnedStop(ctx(), s, 'window'); + await vi.advanceTimersByTimeAsync(36_020); const answer = await pending; + expect(stack).toHaveBeenCalledTimes(1); + expect(answer.status).toBe('changed'); + if (answer.status !== 'changed') throw new Error('Expected an omitted re-read'); + expect(answer.note).toMatch(/stop changed.*was not read again.*35000 ms window/i); + }); + it('M20 a replacement during the settle cannot borrow the pinned pause thread disclosure', async () => { const s = await running(); stop('A', 'pause'); vi.spyOn(ctx(), 'getStackTraceDetailed').mockImplementation(async () => { deps.mockProxyManager.simulateExited(0); - return { frames: [{ id: 1, name: 'B', file: '/w/app.py', line: 50, column: 0 }], threadId: 2, totalFrameCount: 1, hiddenFrameCount: 0, allFramesInternal: false }; + return { frames: [{ id: 1, name: 'B', file: '/w/app.py', line: 50, column: 0 }], threadId: 3, totalFrameCount: 1, hiddenFrameCount: 0, allFramesInternal: false }; }); const schedule = globalThis.setTimeout; let changed = false; @@ -159,9 +180,8 @@ describe('stop pins: async boundaries', () => { expect(a.status).toBe('pinned'); if (a.status === 'pinned') { expect(a.landing.location?.line).toBe(50); - // The reviewed head retained A; the fixed reader retries under B. In - // either case a thread disclosure must be relative to that actual pin. - expect(a.landing.threadId).toBe(a.pin.stop?.threadId === 2 ? undefined : 2); + expect(a.pin.stop?.threadId).toBe(2); + expect(a.landing.threadId).toBe(3); } }); @@ -182,7 +202,7 @@ describe('stop pins: async boundaries', () => { await vi.advanceTimersByTimeAsync(1); stack({ success: true, body: { stackFrames: [frame('A', 11)] } }); const a = await pending; - if (a.lastStop?.description === 'A') expect(a.lastStop.exceptionInfo).toBeUndefined(); + expect(a.stackFrames).toEqual([]); expect(original.info.exceptionInfo).toBeUndefined(); }); }); diff --git a/tests/core/unit/server/stop-pin-consistency.test.ts b/tests/core/unit/server/stop-pin-consistency.test.ts new file mode 100644 index 000000000..1ddd8e9b2 --- /dev/null +++ b/tests/core/unit/server/stop-pin-consistency.test.ts @@ -0,0 +1,251 @@ +/** Regression probes from the two reviews of #1362's stop-record stage. */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { DartAdapterPolicy, DebugLanguage, MockAdapterPolicy, SessionState, type AdapterPolicy } from '@debugmcp/shared'; +import { DebugMcpServer } from '../../../../src/server.js'; +import { registerToolHandlers } from '../../../../src/server/tool-dispatch.js'; +import { createProductionDependencies, type Dependencies } from '../../../../src/container/dependencies.js'; +import { createMockDependencies, overridePolicy } from '../session/session-manager-test-utils.js'; +import { type OperationsContext } from '../../../../src/session/operations-context.js'; +import { pinStop } from '../../../../src/session/stop-record.js'; + +vi.mock('../../../../src/container/dependencies.js'); + +type Payload = Record; +type Handler = (request: unknown, context: unknown) => Promise<{ content: Array<{ text: string }> }>; +const frame = (name: string, line: number) => ({ id: 1, name, source: { path: '/w/app.py' }, line, column: 0 }); + +describe('stop pins: consistency and unchanged timing', () => { + let core: DebugMcpServer; + let deps: ReturnType; + let handler: Handler; + + beforeEach(() => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + deps = createMockDependencies(); + vi.mocked(createProductionDependencies).mockReturnValue(deps as unknown as Dependencies); + core = new DebugMcpServer(); + registerToolHandlers({ setRequestHandler: (method: string, registered: Handler) => { + if (method === 'tools/call') handler = registered; + } } as never, core); + }); + afterEach(async () => { + await core.sessionManager.closeAllSessions().catch(() => undefined); + vi.useRealTimers(); + vi.restoreAllMocks(); + deps.mockProxyManager.reset(); + }); + const ctx = () => (core.sessionManager as unknown as { opsContext: OperationsContext }).opsContext; + const stop = (name: string, reason = 'breakpoint', threadId = 1) => + deps.mockProxyManager.simulateStopped(threadId, reason, { threadId, reason, description: name }); + const call = async (name: string, args: Payload): Promise => JSON.parse((await handler( + { method: 'tools/call', params: { name, arguments: args } }, + { mcpReq: { signal: new AbortController().signal } } + )).content[0].text) as Payload; + const policy = (overrides: Partial) => { + overridePolicy(core.sessionManager, overrides); + vi.spyOn(core.sessionManager as unknown as { selectPolicy: () => AdapterPolicy }, 'selectPolicy') + .mockReturnValue({ ...MockAdapterPolicy, ...overrides }); + }; + async function running() { + const s = await core.sessionManager.createSession({ language: DebugLanguage.MOCK }); + const pending = core.sessionManager.startDebugging(s.id, 'app.py', [], { stopOnEntry: false }); + await vi.runAllTimersAsync(); + expect((await pending).state).toBe(SessionState.RUNNING); + return s.id; + } + + + it.each(['get_stack_trace', 'wait_for_stop', 'pause_execution', 'step_over', 'start_debugging', 'restart', 'hot_reload'])( + 'B3 %s keeps the first stack request timeout and failure shape', async tool => { + if (tool === 'restart') policy({ restartViaDapRequest: true }); + if (tool === 'hot_reload') policy({ liveUpdate: DartAdapterPolicy.liveUpdate }); + const s = tool === 'start_debugging' ? (await core.sessionManager.createSession({ language: DebugLanguage.MOCK })).id : await running(); + const proxy = deps.mockProxyManager; + if (tool === 'restart') proxy.emit('adapter-capabilities', { supportsRestartRequest: true }); + if (tool === 'hot_reload') { + proxy.emit('dap-event', 'flutter.appStart', { launchMode: 'run', supportsRestart: true }); + proxy.emit('dap-event', 'flutter.appStarted', {}); + } + let armed = ['get_stack_trace', 'wait_for_stop'].includes(tool); + if (armed || tool === 'restart' || tool === 'step_over') stop('origin'); + const requests = vi.spyOn(proxy, 'sendDapRequest'); + let timeout: number | undefined; + let began = 0, completedAt = 0; + proxy.setDapRequestHandler(async command => { + if (command === 'next' || command === 'pause') { armed = true; process.nextTick(() => stop('A')); return { success: true }; } + if (command === 'stackTrace') { + if (!armed) return { success: true, body: { stackFrames: [frame('origin', 1)] } }; + const options = requests.mock.calls.at(-1)?.[2]; + timeout = options?.timeoutMs; + began = performance.now(); + return new Promise((_resolve, reject) => setTimeout(() => reject(new Error('DAP stackTrace timeout')), timeout ?? 30_000)); + } + if (command === 'hotReload') return new Promise(resolve => setTimeout(() => resolve({ success: true, body: {} }), 120_000)); + return { success: true }; + }); + let pending: Promise; + if (tool === 'start_debugging') pending = core.sessionManager.startDebugging(s, 'app.py', [], { stopOnEntry: false }); + else if (tool === 'restart') pending = core.sessionManager.restartDebugging(s); + else if (tool === 'hot_reload') pending = core.sessionManager.hotReload(s, {}); + else pending = call(tool, { sessionId: s, timeout: 120_000 }); + let answer: Payload | undefined; + const completed = pending.then(value => { answer = value as Payload; completedAt = performance.now(); }); + if (['start_debugging', 'restart', 'hot_reload'].includes(tool)) { await vi.advanceTimersByTimeAsync(50); armed = true; stop('A'); } + await vi.advanceTimersByTimeAsync(31_000); + const at31s = answer; + await vi.runAllTimersAsync(); await completed; + expect(timeout).toBeUndefined(); + expect(at31s).toBeDefined(); + expect(completedAt - began).toBe(30_000); + if (tool === 'get_stack_trace') { expect(at31s?.success).toBe(false); expect(at31s?.error).toMatch(/timeout/); } + else expect(at31s?.note ?? at31s?.data?.note ?? '').not.toMatch(/budget|window/); + } + ); + + it.each([false, true])('B2/B4 a late stop gets a full first read even if cancellation follows: %s', async cancel => { + const s = await running(); + deps.mockProxyManager.setDapRequestHandler(async command => command === 'stackTrace' + ? { success: true, body: { stackFrames: [frame('A', 11)] } } + : command === 'scopes' ? { success: true, body: { scopes: [] } } : { success: true }); + const controller = new AbortController(); + const pending = core.sessionManager.waitForStop(s, 30_000, controller.signal); + await vi.advanceTimersByTimeAsync(29_995); stop('A'); + await vi.advanceTimersByTimeAsync(1); if (cancel) controller.abort(); + await vi.advanceTimersByTimeAsync(30); + const answer = await pending; + expect(answer.state).toBe(SessionState.PAUSED); + expect(answer.data?.location?.line).toBe(11); + expect(answer.data?.note ?? '').not.toMatch(/budget|window/); + }); + + it('B1 a step with no stop keeps its original grace and pending wording', async () => { + const s = await running(); stop('A'); + vi.spyOn(ctx().tunables, 'stepGraceMs', 'get').mockReturnValue(60_000); + deps.mockProxyManager.setDapRequestHandler(async command => command === 'stackTrace' + ? { success: true, body: { stackFrames: [frame('A', 11)] } } : { success: true }); + let answer: Payload | undefined; + const pending = call('step_over', { sessionId: s }).then(value => { answer = value; }); + await vi.advanceTimersByTimeAsync(35_300); const early = answer; + await vi.runAllTimersAsync(); await pending; + expect(early).toBeUndefined(); + expect(answer?.pending).toBe(true); + expect(answer?.note ?? answer?.error ?? '').not.toMatch(/budget|window/); + }); + + it('B1 origin preflight is not turned into a refusal by a stop-read window', async () => { + const s = await running(); stop('A'); + vi.spyOn(ctx().tunables, 'stepGraceMs', 'get').mockReturnValue(300_000); + vi.spyOn(ctx(), 'getStackTraceDetailed').mockImplementationOnce(async () => { + await new Promise(resolve => setTimeout(resolve, 40_000)); + return { frames: [{ id: 1, name: 'A', file: '/w/app.py', line: 11, column: 0 }], totalFrameCount: 1, hiddenFrameCount: 0, allFramesInternal: false }; + }); + deps.mockProxyManager.setDapRequestHandler(async command => command === 'stackTrace' + ? { success: true, body: { stackFrames: [frame('A', 11)] } } + : command === 'scopes' ? { success: true, body: { scopes: [] } } : { success: true }); + const requests = vi.spyOn(deps.mockProxyManager, 'sendDapRequest'); + let answer: Payload | undefined; + const pending = call('step_over', { sessionId: s }).then(value => { answer = value; }); + await vi.advanceTimersByTimeAsync(35_300); + expect(answer).toBeUndefined(); + expect(requests.mock.calls.some(([command]) => command === 'next')).toBe(false); + await vi.advanceTimersByTimeAsync(5000); + expect(requests.mock.calls.some(([command]) => command === 'next')).toBe(true); + stop('landed', 'step'); await vi.advanceTimersByTimeAsync(1000); await pending; + expect(answer?.success).toBe(true); + expect(answer?.note ?? answer?.error ?? '').not.toMatch(/budget|window/); + }); + + it.each(['refusal', 'dry run'])('C1 a non-stop %s survives a state change during handler assembly', async kind => { + const s = await running(); + vi.spyOn(core, 'startDebugging').mockImplementation(async () => { + stop('unrelated'); + return kind === 'refusal' + ? { success: false, state: SessionState.RUNNING, error: 'Launch refused: original explanation' } + : { success: true, state: SessionState.RUNNING, data: { message: 'Dry run: nothing was started.', dryRun: true } }; + }); + const answer = await call('start_debugging', { sessionId: s, scriptPath: 'app.py' }); + expect(answer.success).toBe(kind === 'dry run'); + expect(answer.state).toBe(SessionState.RUNNING); + expect(answer.message).toBe(kind === 'refusal' ? 'Launch refused: original explanation' : 'Dry run: nothing was started.'); + }); + + it('source enrichment describes the accepted location even after the session ends', async () => { + const s = await running(); stop('A'); + deps.mockProxyManager.setDapRequestHandler(async command => command === 'stackTrace' + ? { success: true, body: { stackFrames: [frame('A', 11)] } } + : command === 'scopes' ? { success: true, body: { scopes: [{ name: 'Locals', variablesReference: 100, expensive: false }] } } + : command === 'variables' ? { success: true, body: { variables: [{ name: 'who', value: 'A', variablesReference: 0 }] } } : { success: true }); + const reader = (core as unknown as { lineReader: { getLineContext: (file: string, line: number) => Promise } }).lineReader; + vi.spyOn(reader, 'getLineContext').mockImplementation(async (_file, line) => { + expect(line).toBe(11); + expect(core.sessionManager.getSession(s)!.snapshotDiffBase).toBeDefined(); + stop('B', 'exception'); deps.mockProxyManager.simulateExited(0); + return { lineContent: 'A source', surrounding: [] }; + }); + const answer = await call('wait_for_stop', { sessionId: s }); + expect(answer.state).toBe(SessionState.PAUSED); + expect(answer.location.line).toBe(11); + expect(answer.lastStop.description).toBe('A'); + expect(answer.context.lineContent).toBe('A source'); + expect(answer.snapshot.locals).toEqual({ who: 'A' }); + }); + + it('get_stack_trace keeps its accepted stop when stale-build enrichment sees a later stop', async () => { + const s = await running(); stop('A'); + deps.mockProxyManager.setDapRequestHandler(async command => command === 'stackTrace' + ? { success: true, body: { stackFrames: [frame('A', 11)] } } : { success: true }); + const checker = (core as unknown as { buildStaleness: { check: () => Promise } }).buildStaleness; + vi.spyOn(checker, 'check').mockImplementation(async () => { stop('B', 'exception'); return undefined; }); + const answer = await call('get_stack_trace', { sessionId: s }); + expect(answer.stackFrames[0].line).toBe(11); + expect(answer.lastStop.description).toBe('A'); + }); + + it.each(['paused', 'ended'])('E4 root %s during a child landing is sampled at session-layer assembly', async state => { + const root = await core.sessionManager.createSession({ language: DebugLanguage.MOCK }); + const pending = core.sessionManager.startDebugging(root.id, 'app.py', [], { stopOnEntry: false }); + await vi.advanceTimersByTimeAsync(20); + deps.mockProxyManager.simulateEvent('child-reported', { reportId: 'consistency-child', targetId: '4242', name: 'Child', configuration: { type: 'python', subProcessId: 4242 } }); + await vi.advanceTimersByTimeAsync(30); + const child = core.sessionManager.getAllSessions().find(item => item.parentSessionId === root.id)!; + const proxy = deps.mockProxyManager.childViews.get(child.id)!; + proxy.setDapRequestHandler(async command => { + if (command === 'stackTrace') { + if (state === 'paused') stop('root', 'exception'); + else deps.mockProxyManager.simulateExited(0); + return { success: true, body: { stackFrames: [frame('child', 11)] } }; + } + return { success: true, body: { scopes: [] } }; + }); + proxy.simulateStopped(1, 'breakpoint', { threadId: 1, reason: 'breakpoint' }); + await vi.runAllTimersAsync(); const answer = await pending; + expect(answer.state).toBe(state === 'paused' ? SessionState.PAUSED : SessionState.STOPPED); + expect(answer.data?.pausedChild).toBeUndefined(); + expect(answer.data?.location).toBeUndefined(); + if (state === 'paused') expect(answer.data?.reason).toBe('exception'); + }); + + it.each(['resumed', 'ended', 'removed'])('E4 a child %s during its landing is absent from the selected launch summary', async state => { + const root = await core.sessionManager.createSession({ language: DebugLanguage.MOCK }); + const pending = core.sessionManager.startDebugging(root.id, 'app.py', [], { stopOnEntry: false }); + await vi.advanceTimersByTimeAsync(20); + deps.mockProxyManager.simulateEvent('child-reported', { reportId: 'child-state', targetId: '4242', name: 'Child', configuration: { type: 'python', subProcessId: 4242 } }); + await vi.advanceTimersByTimeAsync(30); + const child = core.sessionManager.getAllSessions().find(item => item.parentSessionId === root.id)!; + const proxy = deps.mockProxyManager.childViews.get(child.id)!; + proxy.setDapRequestHandler(async command => { + if (command === 'stackTrace') { + if (state === 'resumed') await core.sessionManager.continue(child.id); + else if (state === 'removed') await core.sessionManager.closeSession(child.id); + else proxy.simulateExited(0); + return { success: true, body: { stackFrames: [frame('child', 11)] } }; + } + return { success: true, body: { scopes: [] } }; + }); + proxy.simulateStopped(1, 'breakpoint', { threadId: 1, reason: 'breakpoint' }); + await vi.runAllTimersAsync(); const answer = await pending; + expect(answer.state).toBe(SessionState.RUNNING); + expect(answer.data?.pausedChild).toBeUndefined(); + expect(answer.data?.pending).toBe(true); + }); +}); diff --git a/tests/core/unit/server/stop-pin-ordinary.test.ts b/tests/core/unit/server/stop-pin-ordinary.test.ts index 6355ce255..cc5f83f41 100644 --- a/tests/core/unit/server/stop-pin-ordinary.test.ts +++ b/tests/core/unit/server/stop-pin-ordinary.test.ts @@ -80,7 +80,11 @@ describe('stop pins: ordinary answer compatibility', () => { const s = tool === 'start_debugging' ? (await core.sessionManager.createSession({language:DebugLanguage.MOCK})).id : await running(); if (tool !== 'start_debugging' && tool !== 'pause_execution') stop('A'); const p=deps.mockProxyManager; + let release!: () => void; + const gate = new Promise(resolve => { release = resolve; }); + let reached = false; p.setDapRequestHandler(async command=>{ + if (command === read && !reached) { reached = true; await gate; } if(['next','stepIn','stepOut','pause'].includes(command)){process.nextTick(()=>stop('A',command==='pause'?'pause':'step'));return {success:true};} if(command==='stackTrace')return {success:true,body:{stackFrames:[frame('A',11)]}}; if(command==='threads')return {success:true,body:{threads:[{id:1,name:'main'}]}}; @@ -91,6 +95,9 @@ describe('stop pins: ordinary answer compatibility', () => { let pending:Promise; if(tool==='start_debugging'){pending=core.sessionManager.startDebugging(s,'app.py',[],{stopOnEntry:false});await vi.advanceTimersByTimeAsync(50);stop('A');} else pending=call(tool,{sessionId:s,timeout:2000}); + await vi.advanceTimersByTimeAsync(20); + expect(reached, `ordinary ${tool}: gate at ${read}`).toBe(true); + release(); await vi.advanceTimersByTimeAsync(3000);check(tool+'/'+read,await pending); }); it.each(['tree wait','paused child'])('ordinary %s',async kind=>{ diff --git a/tests/core/unit/server/stop-pin-regressions.test.ts b/tests/core/unit/server/stop-pin-regressions.test.ts index 12824a195..c86320607 100644 --- a/tests/core/unit/server/stop-pin-regressions.test.ts +++ b/tests/core/unit/server/stop-pin-regressions.test.ts @@ -136,97 +136,6 @@ describe('stop pins: review regressions', () => { expect(reads).toEqual([]); expect(deps.mockProxyManager.getCurrentThreadId()).toBe(2); }); - it('F1/F6 a stop ending during source enrichment discards its landing and unshown baseline', async () => { - const s = await running(); stop('A'); - deps.mockProxyManager.setDapRequestHandler(async command => { - if (command === 'stackTrace') return { success: true, body: { stackFrames: [frame('A', 11)] } }; - if (command === 'scopes') return { success: true, body: { scopes: [{ name: 'Locals', variablesReference: 100, expensive: false }] } }; - if (command === 'variables') return { success: true, body: { variables: [{ name: 'who', value: 'A', variablesReference: 0 }] } }; - return { success: true }; - }); - const lineReader = (core as unknown as { lineReader: { getLineContext: () => Promise } }).lineReader; - vi.spyOn(lineReader, 'getLineContext').mockImplementation(async () => { - deps.mockProxyManager.simulateExited(0); - return { lineContent: 'A source', surrounding: [] }; - }); - const a = await call('wait_for_stop', { sessionId: s }); - expect(a.state).toBe(SessionState.STOPPED); - expect(a.location).toBeUndefined(); expect(a.snapshot).toBeUndefined(); - expect(core.sessionManager.getSession(s)!.snapshotDiffBase).toBeUndefined(); - }); - - it('source context is part of the pinned read: a replacement retries the entire answer', async () => { - const s = await running(); stop('A'); let current = 'A'; - deps.mockProxyManager.setDapRequestHandler(async command => { - if (command === 'stackTrace') return { success: true, body: { stackFrames: [frame(current, current === 'A' ? 11 : 50)] } }; - if (command === 'scopes') return { success: true, body: { scopes: [] } }; - return { success: true }; - }); - const lineReader = (core as unknown as { lineReader: { getLineContext: (file: string, line: number) => Promise } }).lineReader; - const lines: number[] = []; - vi.spyOn(lineReader, 'getLineContext').mockImplementation(async (_file, line) => { - lines.push(line); - if (line === 11) { current = 'B'; stop('B', 'exception'); } - return { lineContent: line === 11 ? 'A source' : 'B source', surrounding: [] }; - }); - const a = await call('wait_for_stop', { sessionId: s, timeout: 2000 }); - expect(a.location.line).toBe(50); - expect(a.lastStop.description).toBe('B'); - expect(a.context.lineContent).toBe('B source'); - expect(lines).toEqual([11, 50]); - }); - - it('get_stack_trace validates the pin after its stale-build read', async () => { - const s = await running(); stop('A'); let current = 'A'; - deps.mockProxyManager.setDapRequestHandler(async command => command === 'stackTrace' - ? { success: true, body: { stackFrames: [frame(current, current === 'A' ? 11 : 50)] } } - : { success: true }); - const checker = (core as unknown as { buildStaleness: { check: () => Promise } }).buildStaleness; - vi.spyOn(checker, 'check').mockImplementation(async () => { - if (current === 'A') { current = 'B'; stop('B', 'exception'); } - return undefined; - }); - const a = await call('get_stack_trace', { sessionId: s }); - expect(a.stackFrames[0].line).toBe(50); - expect(a.lastStop.description).toBe('B'); - }); - - it.each(['replaced', 'ended'])('a child %s during source enrichment cannot leave a stale pausedChild', async change => { - const checker = (core as unknown as { fileChecker: { checkExists: (file: string) => Promise } }).fileChecker; - vi.spyOn(checker, 'checkExists').mockResolvedValue({ exists: true, effectivePath: '/w/app.py' }); - const s = await core.sessionManager.createSession({ language: DebugLanguage.MOCK }); - const pending = call('start_debugging', { sessionId: s.id, scriptPath: 'app.py', stopOnEntry: false }); - await vi.advanceTimersByTimeAsync(20); - deps.mockProxyManager.simulateEvent('child-reported', { reportId: 'review-child', targetId: '4242', name: 'Child', configuration: { type: 'python', subProcessId: 4242 } }); - await vi.advanceTimersByTimeAsync(30); - const child = core.sessionManager.getAllSessions().find(item => item.parentSessionId === s.id)!; - const proxy = deps.mockProxyManager.childViews.get(child.id)!; - let current = 'A'; - proxy.setDapRequestHandler(async command => command === 'stackTrace' - ? { success: true, body: { stackFrames: [frame(current, current === 'A' ? 11 : 50)] } } - : command === 'scopes' ? { success: true, body: { scopes: [] } } : { success: true }); - const reader = (core as unknown as { lineReader: { getLineContext: (file: string, line: number) => Promise } }).lineReader; - vi.spyOn(reader, 'getLineContext').mockImplementation(async (_file, line) => { - if (line === 11) { - current = 'B'; - if (change === 'ended') proxy.simulateExited(0); - else proxy.simulateStopped(1, 'exception', { threadId: 1, reason: 'exception', description: 'B' }); - } - return { lineContent: current, surrounding: [] }; - }); - proxy.simulateStopped(1, 'breakpoint', { threadId: 1, reason: 'breakpoint', description: 'A' }); - await vi.runAllTimersAsync(); - const a = await pending; - if (change === 'ended') { - expect(a.pausedChild).toBeUndefined(); - expect(a.data?.pausedChild).toBeUndefined(); - expect(a.message).not.toContain('already paused'); - } else { - expect(a.pausedChild.location.line).toBe(50); - expect(a.pausedChild.context.lineContent).toBe('B'); - } - }); - it('F6 a discarded snapshot cannot consume the last emitted locals baseline', async () => { const s = await running(); let current = 'P'; deps.mockProxyManager.setDapRequestHandler(async command => { @@ -284,22 +193,8 @@ describe('stop pins: review regressions', () => { await vi.advanceTimersByTimeAsync(35_300); expect(a, 'one 35s budget plus the deadline grace').toBeDefined(); expect(a?.location).toBeUndefined(); - expect(a?.note ?? a?.data?.note).toMatch(/budget|time|exceed/i); + expect(a?.note ?? a?.data?.note).toMatch(/stop changed.*re-read did not complete.*35000 ms window/i); await vi.advanceTimersByTimeAsync(35_000); await pending; }); - it('budget step grace cannot outlive the answer budget after the origin read', async () => { - const s = await running(); stop('A'); - vi.spyOn(ctx().tunables, 'stepGraceMs', 'get').mockReturnValue(60_000); - deps.mockProxyManager.setDapRequestHandler(async command => command === 'stackTrace' - ? { success: true, body: { stackFrames: [frame('A', 11)] } } - : { success: true }); - let answer: Payload | undefined; - const pending = call('step_over', { sessionId: s }).then(value => { answer = value; }); - await vi.advanceTimersByTimeAsync(35_300); - expect(answer).toBeDefined(); - expect(answer?.state).toBe(SessionState.RUNNING); - expect(answer?.note).toMatch(/35000 ms answer budget/); - await vi.runAllTimersAsync(); await pending; - }); }); diff --git a/tests/core/unit/session/inspection/stop-answer-effects.test.ts b/tests/core/unit/session/inspection/stop-answer-effects.test.ts deleted file mode 100644 index 4806e9ea0..000000000 --- a/tests/core/unit/session/inspection/stop-answer-effects.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { containsStopValue, publishStopEffect, withStopAnswerEffects } from '../../../../../src/session/inspection/stop-answer-effects.js'; -import { jsonResult } from '../../../../../src/server/tool-result.js'; - -describe('stop answer publication boundary', () => { - it('publishes only an observation contained in the serialized answer', async () => { - const shown = {}, discarded = {}, published: string[] = []; - await withStopAnswerEffects(async () => { - publishStopEffect(() => published.push('shown'), payload => containsStopValue(payload, shown)); - publishStopEffect(() => published.push('discarded'), payload => containsStopValue(payload, discarded)); - expect(published).toEqual([]); - jsonResult({ snapshot: shown }); - }); - expect(published).toEqual(['shown']); - }); - - it('publishes nothing when serialization fails', async () => { - let published = false; - await expect(withStopAnswerEffects(async () => { - publishStopEffect(() => { published = true; }, () => true); - return jsonResult({ invalid: 1n }); - })).rejects.toThrow(); - expect(published).toBe(false); - }); - - it('keeps two concurrent answers in separate publication scopes', async () => { - const published: string[] = []; - let release!: () => void; - const gate = new Promise(resolve => { release = resolve; }); - const first = withStopAnswerEffects(async () => { - publishStopEffect(() => published.push('first'), () => true); - await gate; - return jsonResult({ answer: 'first' }); - }); - await withStopAnswerEffects(async () => { - publishStopEffect(() => published.push('second'), () => true); - return jsonResult({ answer: 'second' }); - }); - expect(published).toEqual(['second']); - release(); await first; - expect(published).toEqual(['second', 'first']); - }); -}); diff --git a/tests/core/unit/session/inspection/stop-snapshot.test.ts b/tests/core/unit/session/inspection/stop-snapshot.test.ts index 5f70d615d..6ab213826 100644 --- a/tests/core/unit/session/inspection/stop-snapshot.test.ts +++ b/tests/core/unit/session/inspection/stop-snapshot.test.ts @@ -94,6 +94,18 @@ afterEach(() => { vi.clearAllMocks(); }); +it('E2 committing an older selected snapshot cannot move the baseline backwards', async () => { + const { ctx, session } = makeCtx(); + const older = await readSnapshot(ctx, 'sid', stack(), 'older'); + setStopForTest(session as never, { reason: 'breakpoint', threadId: 1, timestamp: 2 }); + const newer = await readSnapshot(ctx, 'sid', stack(), 'newer'); + commitStopSnapshot(newer); + const base = session.snapshotDiffBase; + commitStopSnapshot(older); + expect(base).toBeDefined(); + expect(session.snapshotDiffBase).toBe(base); +}); + describe('composeStopSnapshot gates (issue #982)', () => { it('answers nothing when the snapshot is disabled, and never reads locals', async () => { const { ctx, extractLocalsFromResolved } = makeCtx({ snapshot: false }); @@ -149,7 +161,7 @@ describe('composeStopSnapshot frames and locals', () => { ]); expect(snapshot?.locals).toEqual({ subtotal: '125.0', user: "'ada'" }); expect(snapshot?.exception).toBeUndefined(); - expect(extractLocalsFromResolved).toHaveBeenCalledWith('sid', read, expect.objectContaining({ maxFrames: 3, deadline: expect.any(Object) })); + expect(extractLocalsFromResolved).toHaveBeenCalledWith('sid', read, expect.objectContaining({ maxFrames: 3, pin: expect.any(Object) })); }); it('keeps the first value when a name repeats, and stores exotic names safely', async () => { diff --git a/tests/core/unit/session/session-manager-attach-modes.test.ts b/tests/core/unit/session/session-manager-attach-modes.test.ts index 9337d2e9a..84e7d1be5 100644 --- a/tests/core/unit/session/session-manager-attach-modes.test.ts +++ b/tests/core/unit/session/session-manager-attach-modes.test.ts @@ -583,6 +583,43 @@ describe('SessionManagerOperations attach modes', () => { expect(result.data?.snapshot?.locals).toBeUndefined(); }); + it('B3 attach keeps the first landing timeout and advisory failure shape', async () => { + vi.useFakeTimers(); + try { + mockSession.language = DebugLanguage.CPP; + vi.mocked(mockDependencies.adapterRegistry.getFactoryMetadata).mockResolvedValue(metadataWithModes({ launch: true, attach: 'direct-connect' })); + vi.mocked(mockDependencies.adapterRegistry.create).mockResolvedValue(new FakeDebugAdapter({ language: DebugLanguage.CPP }).withAttachSupport({ directConnect: true })); + mockProxyManager.getCurrentThreadId.mockReturnValue(7); + let landingTimeout: number | undefined; + let landingReads = 0; + mockProxyManager.sendDapRequest.mockImplementation(async (command: string, args?: { levels?: number }, options?: { timeoutMs?: number }) => { + if (command === 'threads') { + setSessionStateForTest(mockSession, SessionState.PAUSED); + setStopForTest(mockSession, { reason: 'breakpoint', threadId: 7, timestamp: Date.now() }); + return { success: true, body: { threads: [{ id: 7, name: 'main' }] } }; + } + if (command === 'stackTrace') { + if (args?.levels === undefined) { + landingReads++; + landingTimeout = options?.timeoutMs; + return new Promise((_resolve, reject) => setTimeout(() => reject(new Error('DAP stackTrace timeout')), landingTimeout ?? 30_000)); + } + return { success: true, body: { stackFrames: [{ id: 1, name: 'main', line: 50, column: 0, source: { path: '/proj/app.cpp' } }] } }; + } + return { success: true }; + }); + let answer: Awaited> | undefined; + const pending = operations.attachToProcess('test-session', { host: '127.0.0.1', port: 12345, stopOnEntry: false }).then(value => { answer = value; }); + await vi.advanceTimersByTimeAsync(31_000); + expect(landingReads).toBe(1); + expect(landingTimeout).toBeUndefined(); + expect(answer).toMatchObject({ success: true, state: SessionState.PAUSED }); + expect(answer?.data?.location).toBeUndefined(); + expect(answer?.data?.note ?? '').not.toMatch(/budget|window/); + await pending; + } finally { vi.useRealTimers(); } + }); + it.each(['resumed', 'twice', 'anchor'])('review attach %s keeps the answer and thread on a valid stop', async route => { mockSession.language = DebugLanguage.CPP; vi.mocked(mockDependencies.adapterRegistry.getFactoryMetadata).mockResolvedValue(metadataWithModes({ launch: true, attach: 'direct-connect' })); diff --git a/tests/core/unit/session/session-manager-wait-for-stop-tree.test.ts b/tests/core/unit/session/session-manager-wait-for-stop-tree.test.ts index e95e16f0b..af796b481 100644 --- a/tests/core/unit/session/session-manager-wait-for-stop-tree.test.ts +++ b/tests/core/unit/session/session-manager-wait-for-stop-tree.test.ts @@ -336,16 +336,24 @@ describe('SessionManager - the tree-aware waitForStop (issue #1081)', () => { await vi.advanceTimersByTimeAsync(5); await sessionManager.continue(first.id); await vi.advanceTimersByTimeAsync(10); - // The answer budget expires at 15 ms, before the second settle can - // finish. Report that still-paused child without a landing, rather than - // waiting until 20 ms to observe a later resume or reselecting another. - expect(wait.result()).toMatchObject({ success: true, state: SessionState.PAUSED, data: { sessionId: second.id } }); - expect(wait.result()?.data?.location).toBeUndefined(); - expect(wait.result()?.data?.note).toMatch(/15 ms answer budget/); + // The second landing finishes at 20 ms. The first child is paused again, + // but another selection now would restart work beyond the 15 ms budget. first.view.simulateStopped(1, 'breakpoint', { reason: 'breakpoint', threadId: 1, allThreadsStopped: true }); await sessionManager.continue(second.id); await vi.advanceTimersByTimeAsync(5); - expect(wait.result()?.data?.sessionId).toBe(second.id); + + expect(wait.result()).toMatchObject({ + success: true, + state: SessionState.RUNNING, + data: { + sessionId: rootId, + pending: true, + children: [ + expect.objectContaining({ sessionId: first.id, state: SessionState.PAUSED }), + expect.objectContaining({ sessionId: second.id, state: SessionState.RUNNING }) + ] + } + }); }); it('preserves ended-at-settle for a selected child that naturally ends during the landing read', async () => { diff --git a/tests/unit/session-manager-operations-coverage.test.ts b/tests/unit/session-manager-operations-coverage.test.ts index 47c6b6448..52fca2658 100644 --- a/tests/unit/session-manager-operations-coverage.test.ts +++ b/tests/unit/session-manager-operations-coverage.test.ts @@ -590,7 +590,7 @@ describe('Session Manager Operations Coverage - Error Paths and Edge Cases', () expect(result.data?.pending).toBe(true); expect(result.data?.message).toBe(`${ErrorMessages.stepStillRunning(5)} Explained by the policy.`); // The raw paused frame, not the filtered display: internals included, no readiness wait - expect(detailed).toHaveBeenCalledWith('test-session', 1, true, expect.objectContaining({ ensureStackReady: false, pin: expect.any(Object), deadline: expect.any(Object) })); + expect(detailed).toHaveBeenCalledWith('test-session', 1, true, expect.objectContaining({ ensureStackReady: false, pin: expect.any(Object) })); expect(describePendingStop).toHaveBeenCalledWith({ operation: 'step', attachMode: false, @@ -618,7 +618,7 @@ describe('Session Manager Operations Coverage - Error Paths and Edge Cases', () expect(result.data?.pending).toBe(true); expect(result.data?.message).toBe(ErrorMessages.stepStillRunning(5)); - expect(detailed).toHaveBeenCalledWith('test-session', 1, true, expect.objectContaining({ ensureStackReady: false, pin: expect.any(Object), deadline: expect.any(Object) })); + expect(detailed).toHaveBeenCalledWith('test-session', 1, true, expect.objectContaining({ ensureStackReady: false, pin: expect.any(Object) })); } finally { vi.useRealTimers(); } From bf56fc0aaca9f9f7f989f88846e6dcff4175ee28 Mon Sep 17 00:00:00 2001 From: JF Date: Sun, 29 Nov 2026 02:03:23 -0500 Subject: [PATCH 4/9] refactor(session): three small items from the review of the stop record's narrowing An option nothing read any more is removed; the thread list read for a sibling scan takes the same 30 s per-request cap during a re-read as the other reads (a first read keeps its timeout); the probe for one mutant gives the first stop a thread of its own, so borrowing it would fail the test (shown by mutation). Written by a GPT model from the reviewer's optional list. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn82vMcRzWFDD9aUbZs --- src/session/execution/execution-controller.ts | 2 +- src/session/inspection/frame-anchor-resolver.ts | 2 +- src/session/inspection/pinned-stop-read.ts | 1 - tests/core/unit/server/stop-pin-boundaries.test.ts | 2 +- 4 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/session/execution/execution-controller.ts b/src/session/execution/execution-controller.ts index 49cff660e..50b8eb2ce 100644 --- a/src/session/execution/execution-controller.ts +++ b/src/session/execution/execution-controller.ts @@ -1008,7 +1008,7 @@ export class ExecutionController { // (issue #982): same resolver result, bounded locals. Both under a pin // of the stop taken before the read's first await (tracking issue // #1362): a stop that changes under them is read again, once. - const read = await readPinnedStop(this.ctx, sessionId, 'pause', { skipSnapshotWhenEnded: true }); + const read = await readPinnedStop(this.ctx, sessionId, 'pause'); // The reads are real waits: a debuggee that ended under them gets the // ended wording (#574's rule 2), with the stop recorded for this pause. diff --git a/src/session/inspection/frame-anchor-resolver.ts b/src/session/inspection/frame-anchor-resolver.ts index d1f528a1a..415e2ba19 100644 --- a/src/session/inspection/frame-anchor-resolver.ts +++ b/src/session/inspection/frame-anchor-resolver.ts @@ -809,7 +809,7 @@ export class FrameAnchorResolver { ? await within.request((remainingMs) => proxyManager.sendDapRequest( 'threads', {}, - { timeoutMs: remainingMs, deadline: within } + { timeoutMs: Math.min(30_000, remainingMs), deadline: within } )) : await proxyManager.sendDapRequest('threads', {}); const threads = response?.body?.threads; diff --git a/src/session/inspection/pinned-stop-read.ts b/src/session/inspection/pinned-stop-read.ts index be355f583..7532b0612 100644 --- a/src/session/inspection/pinned-stop-read.ts +++ b/src/session/inspection/pinned-stop-read.ts @@ -37,7 +37,6 @@ export interface PinnedStopReadOptions { readonly startedAt?: number; readonly pin?: StopPin; readonly snapshot?: Omit | false; - readonly skipSnapshotWhenEnded?: boolean; readonly alsoAwait?: () => Promise; readonly rereads?: 0 | 1; } diff --git a/tests/core/unit/server/stop-pin-boundaries.test.ts b/tests/core/unit/server/stop-pin-boundaries.test.ts index 0a83daf67..105a518f0 100644 --- a/tests/core/unit/server/stop-pin-boundaries.test.ts +++ b/tests/core/unit/server/stop-pin-boundaries.test.ts @@ -162,7 +162,7 @@ describe('stop pins: async boundaries', () => { }); it('M20 a replacement during the settle cannot borrow the pinned pause thread disclosure', async () => { - const s = await running(); stop('A', 'pause'); + const s = await running(); stop('A', 'pause', 3); vi.spyOn(ctx(), 'getStackTraceDetailed').mockImplementation(async () => { deps.mockProxyManager.simulateExited(0); return { frames: [{ id: 1, name: 'B', file: '/w/app.py', line: 50, column: 0 }], threadId: 3, totalFrameCount: 1, hiddenFrameCount: 0, allFramesInternal: false }; From dacc1e72256c1e99402b2007d83e9faaec7893a1 Mon Sep 17 00:00:00 2001 From: JF Date: Sun, 29 Nov 2026 03:16:33 -0500 Subject: [PATCH 5/9] docs(changelog): the stop record's entry says what a caller sees The entry listed the mechanism (identity checks, where state is sampled, when a diff base is committed). It now says what was wrong, which answers are covered, what an answer does when its stop changes, and what is not covered. Same facts as the tool reference; nothing else changes. Mine (the manager session). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn82vMcRzWFDD9aUbZs --- changelog.d/1348.fixed.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/changelog.d/1348.fixed.md b/changelog.d/1348.fixed.md index 069fd42b8..dc6709429 100644 --- a/changelog.d/1348.fixed.md +++ b/changelog.d/1348.fixed.md @@ -1 +1 @@ -**Keep stop answers coherent across replacement stops.** An answer describes one stop, as that stop was when the answer's reads completed. It may be out of date by the time it is serialized or read. Identity checks work independently of state, gate thread adoption, and each session-layer caller samples state after its reads. First reads retain their existing timing; a replacement is read once with what remains of 35 s from the first landing read. A changed answer omits its landing and snapshot and says why; an exhausted retry window says the stop changed and was not read again, or that its re-read did not complete. wait_for_stop's timeout bounds waiting only, so reading a stop that arrived inside it can take the answer past that timeout. Source/build enrichment uses the accepted location without refreshing the answer. Snapshot diff bases and step hints are committed synchronously only for the selected session-layer answer; bases never move backwards. A later handler failure or cancellation does not roll back that selection. This change does not pin get_local_variables, evaluate_expression, get_scopes or get_variables, or change which thread a step resumes; those are issue #1374. (#1348, #1362) +**An answer that describes a stop describes one stop** — `wait_for_stop`, the three step tools, `pause_execution`, a launch, restart or attach that answers paused, `hot_reload` when it stops the program, and `get_stack_trace` each read a stop in several requests to the adapter, and a stop that was replaced by another while those ran could leave the answer with one stop's reason beside the other's location, frames or snapshot. Each stop now has a record with an id, and an answer is pinned to one record and checked against it as it is read. When the stop changes during the reads, the answer reads the new stop once, if the program is paused at one and time remains (35 s from the first read); when it changes again, or the time is used up, the answer leaves out the location, frames and snapshot and says which, in a note that begins "The stop changed while this answer was being read" and ends "Call get_stack_trace again to read the current stop." An answer is the stop as it was when its reads completed, and the program can still move before the answer is read. `wait_for_stop`'s timeout bounds the waiting only: a stop that arrives just inside it is read in full, so the answer can come after the timeout by the time that read takes. `get_local_variables`, `evaluate_expression`, `get_scopes` and `get_variables` are not pinned by this change, and which thread a step resumes is unchanged; both are #1374. (#1348, #1362) From b0879a2438659c65fa26152897a695ebd77368d9 Mon Sep 17 00:00:00 2001 From: JF Date: Sun, 29 Nov 2026 04:42:09 -0500 Subject: [PATCH 6/9] test(session): eight behaviours of the stop record that no test held A reviewer that did not write the fix executed 23 mutants on it: 15 were killed and 8 survived the session and server unit folders. These are the eight tests. Four hold what an answer says (a step whose program resumed while its locals were read; a step that has used its one re-read and meets a third stop; a paused child's snapshot as the next step's diff base; a stack answer naming a last stop the session has left), four hold that nothing more is asked of the adapter once a pin is broken. Each mutant is saved as a patch and killed by its test in the manager's own run; the unmutated code passes all eight. No source change. Tests written by a GPT model; mutants found by a Gemini model. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn82vMcRzWFDD9aUbZs --- .../unit/server/stop-pin-boundaries.test.ts | 41 ++++++ .../unit/server/stop-pin-consistency.test.ts | 34 +++++ .../unit/server/stop-pin-regressions.test.ts | 119 ++++++++++++++++++ .../session/session-manager-stop-pins.test.ts | 43 +++++++ 4 files changed, 237 insertions(+) diff --git a/tests/core/unit/server/stop-pin-boundaries.test.ts b/tests/core/unit/server/stop-pin-boundaries.test.ts index 105a518f0..839985f9e 100644 --- a/tests/core/unit/server/stop-pin-boundaries.test.ts +++ b/tests/core/unit/server/stop-pin-boundaries.test.ts @@ -8,6 +8,7 @@ import { createMockDependencies, overridePolicy } from '../session/session-manag import { type OperationsContext } from '../../../../src/session/operations-context.js'; import { readPinnedStop } from '../../../../src/session/inspection/pinned-stop-read.js'; import { pinStop } from '../../../../src/session/stop-record.js'; +import { DapResponseError } from '../../../../src/proxy/dap-response-error.js'; vi.mock('../../../../src/container/dependencies.js'); @@ -55,6 +56,46 @@ describe('stop pins: async boundaries', () => { return s.id; } + it('does not restart a stop read while a refused concurrent step is still running', async () => { + const s = await running(); stop('A'); + const requests: string[] = []; + let step!: Promise; + let sent!: () => void; + const stepSent = new Promise(resolve => { sent = resolve; }); + let stackReads = 0; + deps.mockProxyManager.setDapRequestHandler(async command => { + requests.push(command); + if (command === 'stackTrace') { + stackReads++; + if (stackReads === 1) { + stop('B'); + step = core.sessionManager.stepOver(s); + await stepSent; + } + return { success: true, body: { stackFrames: [frame('main', 11)] } }; + } + if (command === 'next') { + sent(); + return new Promise((_resolve, reject) => setTimeout(() => reject(new DapResponseError({ + seq: 1, type: 'response', request_seq: 1, command: 'next', success: false, message: 'Step refused before resume' + })), 5)); + } + return { success: true }; + }); + const alsoAwait = vi.fn(async () => undefined); + const pending = readPinnedStop(ctx(), s, 'concurrent-refusal', { snapshot: false, alsoAwait }); + await vi.advanceTimersByTimeAsync(100); + const answer = await pending; + await step; + // A's landing, B's concurrent step origin, then the refused resume. + // A retry admitted while B was running would send a third stack request + // after the refusal restores B to paused without applying a new stop. + expect(requests).toEqual(['stackTrace', 'stackTrace', 'next']); + expect(alsoAwait).toHaveBeenCalledTimes(1); + expect(answer.status).toBe('changed'); + expect(core.sessionManager.getSession(s)?.state).toBe(SessionState.PAUSED); + }); + it.each(['wait_for_stop', 'pause_execution', 'start_debugging'])('M12/M13/M15 %s keeps its pin across the helper-to-caller microtask', async tool => { const s = tool === 'start_debugging' diff --git a/tests/core/unit/server/stop-pin-consistency.test.ts b/tests/core/unit/server/stop-pin-consistency.test.ts index 1ddd8e9b2..b4926a145 100644 --- a/tests/core/unit/server/stop-pin-consistency.test.ts +++ b/tests/core/unit/server/stop-pin-consistency.test.ts @@ -54,6 +54,40 @@ describe('stop pins: consistency and unchanged timing', () => { return s.id; } + it('uses the paused child snapshot as the next child step diff base', async () => { + const root = await core.sessionManager.createSession({ language: DebugLanguage.MOCK }); + const launch = core.sessionManager.startDebugging(root.id, 'app.py', [], { stopOnEntry: false }); + await vi.advanceTimersByTimeAsync(20); + deps.mockProxyManager.simulateEvent('child-reported', { reportId: 'diff-child', targetId: '4242', name: 'Child', configuration: { type: 'python', subProcessId: 4242 } }); + await vi.advanceTimersByTimeAsync(30); + const child = core.sessionManager.getAllSessions().find(item => item.parentSessionId === root.id)!; + const proxy = deps.mockProxyManager.childViews.get(child.id)!; + let stepped = false; + proxy.setDapRequestHandler(async command => { + if (command === 'next') { + stepped = true; + process.nextTick(() => proxy.simulateStopped(1, 'step', { threadId: 1, reason: 'step' })); + return { success: true }; + } + if (command === 'stackTrace') return { success: true, body: { stackFrames: [frame('main', stepped ? 12 : 11)] } }; + if (command === 'scopes') return { success: true, body: { scopes: [{ name: 'Locals', variablesReference: 101, expensive: false }] } }; + if (command === 'variables') return { success: true, body: { variables: [{ name: 'x', value: stepped ? '2' : '1', variablesReference: 0 }] } }; + return { success: true }; + }); + proxy.simulateStopped(1, 'breakpoint', { threadId: 1, reason: 'breakpoint' }); + await vi.runAllTimersAsync(); + const launched = await launch; + expect(launched.state).toBe(SessionState.RUNNING); + expect(launched.data?.pausedChild?.sessionId).toBe(child.id); + expect(launched.data?.pausedChild?.snapshot?.locals).toEqual({ x: '1' }); + const pending = core.sessionManager.stepOver(child.id); + await vi.advanceTimersByTimeAsync(100); + const answer = await pending; + expect(answer.state).toBe(SessionState.PAUSED); + expect(answer.data?.snapshot?.locals).toBeUndefined(); + expect(answer.data?.snapshot?.changedVariables).toEqual({ x: { before: '1', after: '2' } }); + }); + it.each(['get_stack_trace', 'wait_for_stop', 'pause_execution', 'step_over', 'start_debugging', 'restart', 'hot_reload'])( 'B3 %s keeps the first stack request timeout and failure shape', async tool => { diff --git a/tests/core/unit/server/stop-pin-regressions.test.ts b/tests/core/unit/server/stop-pin-regressions.test.ts index c86320607..3df4fb0fc 100644 --- a/tests/core/unit/server/stop-pin-regressions.test.ts +++ b/tests/core/unit/server/stop-pin-regressions.test.ts @@ -7,6 +7,8 @@ import { createProductionDependencies, type Dependencies } from '../../../../src import { createMockDependencies, overridePolicy } from '../session/session-manager-test-utils.js'; import { type OperationsContext } from '../../../../src/session/operations-context.js'; import { pinStop } from '../../../../src/session/stop-record.js'; +import { composeStopSnapshot } from '../../../../src/session/inspection/stop-snapshot.js'; +import { ErrorMessages } from '../../../../src/utils/error-messages.js'; vi.mock('../../../../src/container/dependencies.js'); @@ -136,6 +138,123 @@ describe('stop pins: review regressions', () => { expect(reads).toEqual([]); expect(deps.mockProxyManager.getCurrentThreadId()).toBe(2); }); + + it('discards the pinned runtime stack when a sibling unwind observes a replacement stop', async () => { + policy({ isInternalFrame: item => item.name === 'runtime' }); + const s = await running(); stop('A', 'pause'); + const pin = pinStop(core.sessionManager.getSession(s)!); + const requests: string[] = []; + deps.mockProxyManager.setDapRequestHandler(async (command, args) => { + if (command === 'threads') { + requests.push('threads'); + return { success: true, body: { threads: [{ id: 1, name: 'runtime' }, { id: 3, name: 'worker' }] } }; + } + if (command === 'stackTrace') { + requests.push(`stackTrace:${args?.threadId}`); + if (args?.threadId === 3) { + stop('B', 'exception', 2); + return { success: true, body: { stackFrames: [frame('worker', 50)] } }; + } + return { success: true, body: { stackFrames: [frame('runtime', 11)] } }; + } + return { success: true }; + }); + const answer = await core.sessionManager.getStackTraceDetailed(s, undefined, false, { ensureStackReady: true, pin }); + expect(requests).toEqual(['stackTrace:1', 'threads', 'stackTrace:3']); + expect(answer.frames).toEqual([]); + expect(answer.note).toBeUndefined(); + expect(deps.mockProxyManager.getCurrentThreadId()).toBe(2); + }); + + it('does not poll or scan after the initial stack read loses its pin', async () => { + const s = await running(); stop('A', 'pause'); + const pin = pinStop(core.sessionManager.getSession(s)!); + const requests: string[] = []; + deps.mockProxyManager.setDapRequestHandler(async command => { + requests.push(command); + if (command === 'stackTrace') { + stop('B', 'breakpoint', 2); + return { success: true, body: { stackFrames: [] } }; + } + return { success: true, body: { threads: [] } }; + }); + const pending = core.sessionManager.getStackTraceDetailed(s, undefined, false, { ensureStackReady: true, pin }); + await vi.advanceTimersByTimeAsync(4000); + const answer = await pending; + expect(requests).toEqual(['stackTrace']); + expect(answer.frames).toEqual([]); + }); + + it('returns a pending step without landing or hint when locals reading resumes the program', async () => { + policy({ describeStepInFilter: () => 'Run hint.' }); + const s = await running(); stop('origin'); + let stepped = false, resumed = false; + deps.mockProxyManager.setDapRequestHandler(async command => { + if (command === 'stepIn') { stepped = true; process.nextTick(() => stop('A', 'step')); return { success: true }; } + if (command === 'stackTrace') return { success: true, body: { stackFrames: [frame('main', stepped ? 11 : 1)] } }; + if (command === 'scopes') return { success: true, body: { scopes: [{ name: 'Locals', variablesReference: 101, expensive: false }] } }; + if (command === 'variables') { + resumed = true; + await core.sessionManager.continue(s); + return { success: true, body: { variables: [{ name: 'x', value: '1', variablesReference: 0 }] } }; + } + return { success: true }; + }); + const answer = await call('step_into', { sessionId: s }); + expect(resumed).toBe(true); + expect(answer.state).toBe(SessionState.RUNNING); + expect(answer.pending).toBe(true); + expect(answer.location).toBeUndefined(); + expect(answer.snapshot).toBeUndefined(); + expect(answer.note ?? '').not.toContain('Run hint.'); + expect(core.sessionManager.getSession(s)!.snapshotDiffBase).toBeUndefined(); + expect(core.sessionManager.getSession(s)!.run.deliveredStepFilterHints?.has('Run hint.')).not.toBe(true); + }); + + it('does not request variables from a second scope after the stop is replaced', async () => { + const s = await running(); stop('A'); + const pin = pinStop(core.sessionManager.getSession(s)!); + const references: number[] = []; + deps.mockProxyManager.setDapRequestHandler(async (command, args) => { + if (command === 'stackTrace') return { success: true, body: { stackFrames: [frame('main', 11)] } }; + if (command === 'scopes') return { success: true, body: { scopes: [ + { name: 'Locals', variablesReference: 101, expensive: false }, + { name: 'Closure', variablesReference: 102, expensive: false } + ] } }; + if (command === 'variables') { + references.push(args?.variablesReference as number); + if (args?.variablesReference === 101) stop('B', 'exception'); + return { success: true, body: { variables: [{ name: 'x', value: '1', variablesReference: 0 }] } }; + } + return { success: true }; + }); + const stack = await core.sessionManager.getStackTraceDetailed(s, undefined, false, { pin }); + const snapshot = await composeStopSnapshot(ctx(), s, stack, 'scope-replacement', { pin }); + expect(references).toEqual([101]); + expect(snapshot).toBeUndefined(); + }); + + it('omits the last stop from a stack answer after the replacement resumes', async () => { + const s = await running(); stop('A'); + const requests: string[] = []; + deps.mockProxyManager.setDapRequestHandler(async command => { + requests.push(command); + if (command === 'stackTrace') { + stop('B', 'exception'); + await core.sessionManager.continue(s); + return { success: true, body: { stackFrames: [frame('B', 50)] } }; + } + return { success: true }; + }); + const answer = await call('get_stack_trace', { sessionId: s }); + expect(requests).toEqual(['stackTrace', 'continue']); + expect(core.sessionManager.getSession(s)?.lastStop?.description).toBe('B'); + expect(core.sessionManager.getSession(s)?.state).toBe(SessionState.RUNNING); + expect(answer.stackFrames).toEqual([]); + expect(answer.lastStop).toBeUndefined(); + expect(answer.stopReason).toBeUndefined(); + expect(answer.note).toBe(ErrorMessages.stopChangedWhileRead()); + }); it('F6 a discarded snapshot cannot consume the last emitted locals baseline', async () => { const s = await running(); let current = 'P'; deps.mockProxyManager.setDapRequestHandler(async command => { diff --git a/tests/core/unit/session/session-manager-stop-pins.test.ts b/tests/core/unit/session/session-manager-stop-pins.test.ts index 3c1255df0..895b0d34c 100644 --- a/tests/core/unit/session/session-manager-stop-pins.test.ts +++ b/tests/core/unit/session/session-manager-stop-pins.test.ts @@ -215,6 +215,49 @@ describe('Stop pins: an answer read while the stop changes describes one stop', expect(answer.data?.stopReason).toBe('breakpoint'); expect(answer.data?.message).toBe("Stepped over; stopped on 'breakpoint' rather than on the step itself (see stopReason)."); }); + + it('omits the step landing when a third stop replaces the already retried snapshot', async () => { + const sessionId = await pausedAtA(); + const proxy = dependencies.mockProxyManager; + let stepped = false, landingReads = 0, snapshotReads = 0; + let current: StopName = 'A'; + proxy.setDapRequestHandler(async command => { + if (command === 'next') { + stepped = true; + process.nextTick(() => proxy.simulateStopped(1, 'step', { reason: 'step', threadId: 1 })); + return { success: true }; + } + if (command === 'stackTrace') { + const at = current; + if (stepped && ++landingReads === 1) { + current = 'B'; + proxy.simulateStopped(2, 'exception', { ...NEXT_STOP.B }); + } + return { success: true, body: { stackFrames: [FRAMES[at]] } }; + } + if (command === 'scopes') return { success: true, body: { scopes: [{ name: 'Locals', variablesReference: 101, expensive: false }] } }; + if (command === 'variables') { + snapshotReads++; + if (current === 'B') { + current = 'C'; + proxy.simulateStopped(3, 'breakpoint', { ...NEXT_STOP.C }); + } + return { success: true, body: { variables: [{ name: 'x', value: '1', variablesReference: 0 }] } }; + } + return { success: true }; + }); + const pending = sessionManager.stepOver(sessionId); + await vi.advanceTimersByTimeAsync(200); + const answer = await pending; + expect(current).toBe('C'); + expect(landingReads).toBe(2); + expect(snapshotReads).toBe(1); + expect(answer.state).toBe(SessionState.PAUSED); + expect(answer.data?.stopReason).toBe('breakpoint'); + expect(answer.data?.note).toBe(ErrorMessages.stopChangedWhileRead()); + expect(answer.data?.location).toBeUndefined(); + expect(answer.data?.snapshot).toBeUndefined(); + }); }); describe('pause_execution', () => { From 5c06af014e5389d7905d0bb078db90297d6020f9 Mon Sep 17 00:00:00 2001 From: JF Date: Sun, 29 Nov 2026 04:43:06 -0500 Subject: [PATCH 7/9] docs(session): what a stop answer says when the program has moved on, and that the record is internal From the reviewer's sentence-by-sentence check of the changelog entry: a caller could look for a new id field (there is none), 'leaves out' the frames meant an empty list on get_stack_trace, and the note is given only while the session-layer answer is still about a paused program; otherwise that answer says running or ended, and get_stack_trace keeps the note. Mine (the manager session). No code changes. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn82vMcRzWFDD9aUbZs --- changelog.d/1348.fixed.md | 2 +- docs/tool-reference.md | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/changelog.d/1348.fixed.md b/changelog.d/1348.fixed.md index dc6709429..a8f374de8 100644 --- a/changelog.d/1348.fixed.md +++ b/changelog.d/1348.fixed.md @@ -1 +1 @@ -**An answer that describes a stop describes one stop** — `wait_for_stop`, the three step tools, `pause_execution`, a launch, restart or attach that answers paused, `hot_reload` when it stops the program, and `get_stack_trace` each read a stop in several requests to the adapter, and a stop that was replaced by another while those ran could leave the answer with one stop's reason beside the other's location, frames or snapshot. Each stop now has a record with an id, and an answer is pinned to one record and checked against it as it is read. When the stop changes during the reads, the answer reads the new stop once, if the program is paused at one and time remains (35 s from the first read); when it changes again, or the time is used up, the answer leaves out the location, frames and snapshot and says which, in a note that begins "The stop changed while this answer was being read" and ends "Call get_stack_trace again to read the current stop." An answer is the stop as it was when its reads completed, and the program can still move before the answer is read. `wait_for_stop`'s timeout bounds the waiting only: a stop that arrives just inside it is read in full, so the answer can come after the timeout by the time that read takes. `get_local_variables`, `evaluate_expression`, `get_scopes` and `get_variables` are not pinned by this change, and which thread a step resumes is unchanged; both are #1374. (#1348, #1362) +**An answer that describes a stop describes one stop** — `wait_for_stop`, the three step tools, `pause_execution`, a launch, restart or attach that answers paused, `hot_reload` when it stops the program, and `get_stack_trace` each read a stop in several requests to the adapter, and a stop that was replaced by another while those ran could leave the answer with one stop's reason beside the other's location, frames or snapshot. The server now keeps a record of each stop, and an answer is pinned to one record and checked against it as it is read (the record is internal: answers gain no field). When the stop changes during the reads, the answer reads the new stop once, if the program is paused at one and time remains (35 s from the first read); when it changes again, or the time is used up, the answer carries no location, frames or snapshot and says which, in a note that begins "The stop changed while this answer was being read" and ends "Call get_stack_trace again to read the current stop." If the program has resumed or ended by then, a wait, step, pause, launch, attach or hot-reload answer says that instead, and `get_stack_trace` keeps the note (and names no last stop while the program is running again). An answer is the stop as it was when its reads completed, and the program can still move before the answer is read. `wait_for_stop`'s timeout bounds the waiting only: a stop that arrives just inside it is read in full, so the answer can come after the timeout by the time that read takes. `get_local_variables`, `evaluate_expression`, `get_scopes` and `get_variables` are not pinned by this change, and which thread a step resumes is unchanged; both are #1374. (#1348, #1362) diff --git a/docs/tool-reference.md b/docs/tool-reference.md index 9aed025bf..1c34effe0 100644 --- a/docs/tool-reference.md +++ b/docs/tool-reference.md @@ -614,7 +614,10 @@ If the stop changes, the answer re-reads it once while another stop is paused an remains. A second change omits the landing, frames and snapshot. The note says: "The stop changed while this answer was being read; its stack and snapshot were omitted. Call get_stack_trace again to read the current stop." Only shapes that carry a reason/lastStop -retain those fields; attach has no reason field. +retain those fields; attach has no reason field. If the program has resumed or ended by the +time the answer is built, a wait, step, pause, launch, attach or hot_reload answer says that +(running, or the end) and carries no such note; get_stack_trace keeps the note, returns an +empty `stackFrames` list, and names a last stop only when the session is paused or has ended. First reads keep their existing request/readiness/locals bounds. Only a re-read is bounded by what remains of 35,000 ms from the first landing read. If none remains, the changed From 13babd3edc981a860056fea75884d2cf812d85db Mon Sep 17 00:00:00 2001 From: JF Date: Sun, 29 Nov 2026 05:42:32 -0500 Subject: [PATCH 8/9] test(session): five more behaviours of the stop record that no test held The reviewer's read of the eight tests found a ninth mutant that survived when run, and named four more by reading. All five survived the session and server unit folders. These are their tests: a step whose program resumes during the snapshot's re-read, and one whose retried landing resumes while the snapshot uses up the window, each answer pending; no scopes asked of a caller frame once the stop is replaced; the attach answer's and the hot reload answer's snapshot as the next step's diff base. Each mutant is saved as a patch and killed by its test in the manager's own run, with the first eight; the unmutated code passes all thirteen. No source change. Tests written by a GPT model; mutants found by a Gemini model. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn82vMcRzWFDD9aUbZs --- .../unit/server/stop-pin-consistency.test.ts | 70 ++++++++++++ .../unit/server/stop-pin-regressions.test.ts | 100 ++++++++++++++++++ 2 files changed, 170 insertions(+) diff --git a/tests/core/unit/server/stop-pin-consistency.test.ts b/tests/core/unit/server/stop-pin-consistency.test.ts index b4926a145..c42eccbf7 100644 --- a/tests/core/unit/server/stop-pin-consistency.test.ts +++ b/tests/core/unit/server/stop-pin-consistency.test.ts @@ -7,6 +7,7 @@ import { createProductionDependencies, type Dependencies } from '../../../../src import { createMockDependencies, overridePolicy } from '../session/session-manager-test-utils.js'; import { type OperationsContext } from '../../../../src/session/operations-context.js'; import { pinStop } from '../../../../src/session/stop-record.js'; +import { FakeDebugAdapter } from '../../../test-utils/fakes/fake-debug-adapter.js'; vi.mock('../../../../src/container/dependencies.js'); @@ -89,6 +90,75 @@ describe('stop pins: consistency and unchanged timing', () => { }); + it('uses the attach snapshot as the next step diff base', async () => { + vi.mocked(deps.adapterRegistry.create).mockResolvedValue( + new FakeDebugAdapter({ language: DebugLanguage.MOCK }).withAttachSupport({ directConnect: true }) + ); + const session = await core.sessionManager.createSession({ language: DebugLanguage.MOCK }); + let attachedStop = false, stepped = false; + deps.mockProxyManager.setDapRequestHandler(async command => { + if (command === 'threads') { + if (!attachedStop) { attachedStop = true; stop('attached'); } + return { success: true, body: { threads: [{ id: 1, name: 'main' }] } }; + } + if (command === 'next') { + stepped = true; + process.nextTick(() => stop('stepped', 'step')); + return { success: true }; + } + if (command === 'stackTrace') return { success: true, body: { stackFrames: [frame('main', stepped ? 12 : 11)] } }; + if (command === 'scopes') return { success: true, body: { scopes: [{ name: 'Locals', variablesReference: 101, expensive: false }] } }; + if (command === 'variables') return { success: true, body: { variables: [{ name: 'x', value: stepped ? '2' : '1', variablesReference: 0 }] } }; + return { success: true }; + }); + const attaching = core.sessionManager.attachToProcess(session.id, { host: '127.0.0.1', port: 12345, stopOnEntry: false }); + await vi.advanceTimersByTimeAsync(100); + const attached = await attaching; + expect(attachedStop).toBe(true); + expect(attached).toMatchObject({ success: true, state: SessionState.PAUSED }); + expect(attached.data?.snapshot?.locals).toEqual({ x: '1' }); + const pending = core.sessionManager.stepOver(session.id); + await vi.advanceTimersByTimeAsync(100); + const answer = await pending; + expect(answer.state).toBe(SessionState.PAUSED); + expect(answer.data?.snapshot?.locals).toBeUndefined(); + expect(answer.data?.snapshot?.changedVariables).toEqual({ x: { before: '1', after: '2' } }); + }); + + it('uses the hot reload snapshot as the next step diff base', async () => { + policy({ liveUpdate: DartAdapterPolicy.liveUpdate }); + const s = await running(); + const proxy = deps.mockProxyManager; + proxy.emit('dap-event', 'flutter.appStart', { launchMode: 'run', supportsRestart: true }); + proxy.emit('dap-event', 'flutter.appStarted', {}); + let stepped = false; + proxy.setDapRequestHandler(async command => { + if (command === 'hotReload') return new Promise(resolve => setTimeout(() => resolve({ success: true, body: {} }), 60_000)); + if (command === 'next') { + stepped = true; + process.nextTick(() => stop('stepped', 'step')); + return { success: true }; + } + if (command === 'stackTrace') return { success: true, body: { stackFrames: [frame('main', stepped ? 12 : 11)] } }; + if (command === 'scopes') return { success: true, body: { scopes: [{ name: 'Locals', variablesReference: 101, expensive: false }] } }; + if (command === 'variables') return { success: true, body: { variables: [{ name: 'x', value: stepped ? '2' : '1', variablesReference: 0 }] } }; + return { success: true }; + }); + const reloading = core.sessionManager.hotReload(s, {}); + await vi.advanceTimersByTimeAsync(50); stop('reloaded'); + await vi.advanceTimersByTimeAsync(100); + const reloaded = await reloading; + expect(reloaded).toMatchObject({ success: true, state: SessionState.PAUSED }); + expect(reloaded.snapshot?.locals).toEqual({ x: '1' }); + const pending = core.sessionManager.stepOver(s); + await vi.advanceTimersByTimeAsync(100); + const answer = await pending; + expect(answer.state).toBe(SessionState.PAUSED); + expect(answer.data?.snapshot?.locals).toBeUndefined(); + expect(answer.data?.snapshot?.changedVariables).toEqual({ x: { before: '1', after: '2' } }); + await vi.runAllTimersAsync(); + }); + it.each(['get_stack_trace', 'wait_for_stop', 'pause_execution', 'step_over', 'start_debugging', 'restart', 'hot_reload'])( 'B3 %s keeps the first stack request timeout and failure shape', async tool => { if (tool === 'restart') policy({ restartViaDapRequest: true }); diff --git a/tests/core/unit/server/stop-pin-regressions.test.ts b/tests/core/unit/server/stop-pin-regressions.test.ts index 3df4fb0fc..cfdb46108 100644 --- a/tests/core/unit/server/stop-pin-regressions.test.ts +++ b/tests/core/unit/server/stop-pin-regressions.test.ts @@ -211,6 +211,106 @@ describe('stop pins: review regressions', () => { expect(core.sessionManager.getSession(s)!.run.deliveredStepFilterHints?.has('Run hint.')).not.toBe(true); }); + it('returns a pending step when the snapshot re-read resumes the program', async () => { + policy({ describeStepInFilter: () => 'Run hint.' }); + const s = await running(); stop('origin'); + let stepped = false, localsReads = 0; + const landings: number[] = []; + deps.mockProxyManager.setDapRequestHandler(async command => { + if (command === 'stepIn') { stepped = true; process.nextTick(() => stop('A', 'step')); return { success: true }; } + if (command === 'stackTrace') { + const line = !stepped ? 1 : localsReads === 0 ? 11 : 50; + if (stepped) landings.push(line); + return { success: true, body: { stackFrames: [frame('main', line)] } }; + } + if (command === 'scopes') return { success: true, body: { scopes: [{ name: 'Locals', variablesReference: 101, expensive: false }] } }; + if (command === 'variables') { + if (++localsReads === 1) stop('B', 'step'); + else await core.sessionManager.continue(s); + return { success: true, body: { variables: [{ name: 'x', value: '1', variablesReference: 0 }] } }; + } + return { success: true }; + }); + const answer = await call('step_into', { sessionId: s }); + expect(landings).toEqual([11, 50]); + expect(localsReads).toBe(2); + expect(answer.state).toBe(SessionState.RUNNING); + expect(answer.pending).toBe(true); + expect(answer.message).toBe('The program resumed while this answer was being read.'); + expect(answer.location).toBeUndefined(); + expect(answer.snapshot).toBeUndefined(); + expect(answer.note ?? '').not.toContain('Run hint.'); + expect(core.sessionManager.getSession(s)!.snapshotDiffBase).toBeUndefined(); + expect(core.sessionManager.getSession(s)!.run.deliveredStepFilterHints?.has('Run hint.')).not.toBe(true); + }); + + it('returns a pending step when a retried landing resumes during a snapshot that exhausts the window', async () => { + vi.useFakeTimers({ shouldAdvanceTime: false }); + const s = await running(); stop('origin'); + let stepped = false, landingReads = 0, resumedAt = 0, firstReadAt = 0; + deps.mockProxyManager.setDapRequestHandler(async command => { + if (command === 'next') { stepped = true; process.nextTick(() => stop('A', 'step')); return { success: true }; } + if (command === 'stackTrace') { + if (!stepped) return { success: true, body: { stackFrames: [frame('main', 1)] } }; + const read = ++landingReads; + if (read === 1) firstReadAt = performance.now(); + // Both requests finish inside their adapter caps. Together they leave + // less than the normal 2s locals cap in the 35s re-read window. + await new Promise(resolve => setTimeout(resolve, read === 1 ? 29_500 : 4_900)); + if (read === 1) stop('B', 'step'); + return { success: true, body: { stackFrames: [frame('main', read === 1 ? 11 : 50)] } }; + } + if (command === 'scopes') return { success: true, body: { scopes: [{ name: 'Locals', variablesReference: 101, expensive: false }] } }; + if (command === 'variables') { + await core.sessionManager.continue(s); + resumedAt = performance.now(); + // A real in-flight adapter read: it ignores its timeout, so the + // snapshot's parent deadline, rather than this response, settles it. + return new Promise(() => {}); + } + return { success: true }; + }); + let answer: Payload | undefined; + const pending = call('step_over', { sessionId: s }).then(value => { answer = value; }); + await vi.advanceTimersByTimeAsync(34_800); + expect(landingReads).toBe(2); + expect(resumedAt - firstReadAt).toBeGreaterThanOrEqual(34_400); + expect(resumedAt - firstReadAt).toBeLessThan(35_000); + expect(core.sessionManager.getSession(s)!.state).toBe(SessionState.RUNNING); + expect(answer).toBeUndefined(); + await vi.advanceTimersByTimeAsync(600); + await pending; + expect(answer?.state).toBe(SessionState.RUNNING); + expect(answer?.pending).toBe(true); + expect(answer?.message).toBe('The program resumed while this answer was being read.'); + expect(answer?.location).toBeUndefined(); + expect(answer?.snapshot).toBeUndefined(); + expect(answer?.note).toBeUndefined(); + expect(core.sessionManager.getSession(s)!.snapshotDiffBase).toBeUndefined(); + }); + + it('does not request scopes from a caller frame after the stop is replaced', async () => { + const s = await running(); stop('A'); + const pin = pinStop(core.sessionManager.getSession(s)!); + const frames: number[] = []; + deps.mockProxyManager.setDapRequestHandler(async (command, args) => { + if (command === 'stackTrace') return { success: true, body: { stackFrames: [ + frame('main', 11), { ...frame('caller', 5), id: 2 } + ] } }; + if (command === 'scopes') { + frames.push(args?.frameId as number); + if (args?.frameId === 1) stop('B', 'exception'); + return { success: true, body: { scopes: [{ name: 'Locals', variablesReference: 101, expensive: false }] } }; + } + return { success: true }; + }); + const stack = await core.sessionManager.getStackTraceDetailed(s, undefined, false, { pin }); + expect(stack.frames.map(item => item.id)).toEqual([1, 2]); + const snapshot = await composeStopSnapshot(ctx(), s, stack, 'frame-scope-replacement', { pin }); + expect(frames).toEqual([1]); + expect(snapshot).toBeUndefined(); + }); + it('does not request variables from a second scope after the stop is replaced', async () => { const s = await running(); stop('A'); const pin = pinStop(core.sessionManager.getSession(s)!); From 452cd0400e287b9495fd967ef870c9bb2a419bf8 Mon Sep 17 00:00:00 2001 From: JF Date: Sun, 29 Nov 2026 06:50:07 -0500 Subject: [PATCH 9/9] test(session): seven more guards of the stop record that no test held A third pass by the reviewer ran seven more mutants beside the last ones and all survived: the three snapshot commits still without a test (hot restart, the launch's root, pause), the three checks that a step whose program ended during the snapshot read says it ended and not that it resumed, and the snapshot's guard after a locals read that timed out or failed while the stop was replaced. These are their tests. Twenty mutants in all are saved as patches; each is killed by its test in the manager's own run, and the unmutated code passes all twenty. No source change. Tests written by a GPT model; mutants found by a Gemini model. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn82vMcRzWFDD9aUbZs --- .../unit/server/stop-pin-consistency.test.ts | 98 ++++++++++++++ .../unit/server/stop-pin-regressions.test.ts | 124 ++++++++++++++++++ 2 files changed, 222 insertions(+) diff --git a/tests/core/unit/server/stop-pin-consistency.test.ts b/tests/core/unit/server/stop-pin-consistency.test.ts index c42eccbf7..a65d7e393 100644 --- a/tests/core/unit/server/stop-pin-consistency.test.ts +++ b/tests/core/unit/server/stop-pin-consistency.test.ts @@ -159,6 +159,104 @@ describe('stop pins: consistency and unchanged timing', () => { await vi.runAllTimersAsync(); }); + it('uses the hot restart snapshot as the next step diff base', async () => { + policy({ restartViaDapRequest: true }); + const s = await running(); stop('origin'); + const proxy = deps.mockProxyManager; + proxy.emit('adapter-capabilities', { supportsRestartRequest: true }); + let restarted = false, stepped = false; + proxy.setDapRequestHandler(async command => { + if (command === 'restart') { + restarted = true; + process.nextTick(() => stop('restarted')); + return { success: true }; + } + if (command === 'next') { + stepped = true; + process.nextTick(() => stop('stepped', 'step')); + return { success: true }; + } + if (command === 'stackTrace') return { success: true, body: { stackFrames: [frame('main', stepped ? 12 : 11)] } }; + if (command === 'scopes') return { success: true, body: { scopes: [{ name: 'Locals', variablesReference: 101, expensive: false }] } }; + if (command === 'variables') return { success: true, body: { variables: [{ name: 'x', value: stepped ? '2' : '1', variablesReference: 0 }] } }; + return { success: true }; + }); + const restarting = core.sessionManager.restartDebugging(s); + await vi.advanceTimersByTimeAsync(100); + const restartedAnswer = await restarting; + expect(restarted).toBe(true); + expect(restartedAnswer).toMatchObject({ success: true, state: SessionState.PAUSED, data: { hotRestart: true } }); + expect(restartedAnswer.data?.snapshot?.locals).toEqual({ x: '1' }); + const pending = core.sessionManager.stepOver(s); + await vi.advanceTimersByTimeAsync(100); + const answer = await pending; + expect(answer.state).toBe(SessionState.PAUSED); + expect(answer.data?.snapshot?.locals).toBeUndefined(); + expect(answer.data?.snapshot?.changedVariables).toEqual({ x: { before: '1', after: '2' } }); + }); + + it('uses the root launch snapshot as the next step diff base', async () => { + const session = await core.sessionManager.createSession({ language: DebugLanguage.MOCK }); + let stepped = false; + deps.mockProxyManager.setDapRequestHandler(async command => { + if (command === 'next') { + stepped = true; + process.nextTick(() => stop('stepped', 'step')); + return { success: true }; + } + if (command === 'stackTrace') return { success: true, body: { stackFrames: [frame('main', stepped ? 12 : 11)] } }; + if (command === 'scopes') return { success: true, body: { scopes: [{ name: 'Locals', variablesReference: 101, expensive: false }] } }; + if (command === 'variables') return { success: true, body: { variables: [{ name: 'x', value: stepped ? '2' : '1', variablesReference: 0 }] } }; + return { success: true }; + }); + const launching = core.sessionManager.startDebugging(session.id, 'app.py', [], { stopOnEntry: false }); + await vi.advanceTimersByTimeAsync(50); stop('launched'); + await vi.advanceTimersByTimeAsync(100); + const launched = await launching; + expect(launched).toMatchObject({ success: true, state: SessionState.PAUSED }); + expect(launched.data?.pausedChild).toBeUndefined(); + expect(launched.data?.snapshot?.locals).toEqual({ x: '1' }); + const pending = core.sessionManager.stepOver(session.id); + await vi.advanceTimersByTimeAsync(100); + const answer = await pending; + expect(answer.state).toBe(SessionState.PAUSED); + expect(answer.data?.snapshot?.locals).toBeUndefined(); + expect(answer.data?.snapshot?.changedVariables).toEqual({ x: { before: '1', after: '2' } }); + }); + + it('uses the pause snapshot as the next step diff base', async () => { + const s = await running(); + let paused = false, stepped = false; + deps.mockProxyManager.setDapRequestHandler(async command => { + if (command === 'pause') { + paused = true; + process.nextTick(() => stop('paused', 'pause')); + return { success: true }; + } + if (command === 'next') { + stepped = true; + process.nextTick(() => stop('stepped', 'step')); + return { success: true }; + } + if (command === 'stackTrace') return { success: true, body: { stackFrames: [frame('main', stepped ? 12 : 11)] } }; + if (command === 'scopes') return { success: true, body: { scopes: [{ name: 'Locals', variablesReference: 101, expensive: false }] } }; + if (command === 'variables') return { success: true, body: { variables: [{ name: 'x', value: stepped ? '2' : '1', variablesReference: 0 }] } }; + return { success: true }; + }); + const pausing = core.sessionManager.pause(s); + await vi.advanceTimersByTimeAsync(100); + const pausedAnswer = await pausing; + expect(paused).toBe(true); + expect(pausedAnswer).toMatchObject({ success: true, state: SessionState.PAUSED }); + expect(pausedAnswer.data?.snapshot?.locals).toEqual({ x: '1' }); + const pending = core.sessionManager.stepOver(s); + await vi.advanceTimersByTimeAsync(100); + const answer = await pending; + expect(answer.state).toBe(SessionState.PAUSED); + expect(answer.data?.snapshot?.locals).toBeUndefined(); + expect(answer.data?.snapshot?.changedVariables).toEqual({ x: { before: '1', after: '2' } }); + }); + it.each(['get_stack_trace', 'wait_for_stop', 'pause_execution', 'step_over', 'start_debugging', 'restart', 'hot_reload'])( 'B3 %s keeps the first stack request timeout and failure shape', async tool => { if (tool === 'restart') policy({ restartViaDapRequest: true }); diff --git a/tests/core/unit/server/stop-pin-regressions.test.ts b/tests/core/unit/server/stop-pin-regressions.test.ts index cfdb46108..f9b681ed0 100644 --- a/tests/core/unit/server/stop-pin-regressions.test.ts +++ b/tests/core/unit/server/stop-pin-regressions.test.ts @@ -289,6 +289,130 @@ describe('stop pins: review regressions', () => { expect(core.sessionManager.getSession(s)!.snapshotDiffBase).toBeUndefined(); }); + it('reports the program ended when the first step snapshot outlives it', async () => { + const s = await running(); stop('origin'); + let stepped = false, localsReads = 0; + deps.mockProxyManager.setDapRequestHandler(async command => { + if (command === 'stepIn') { stepped = true; process.nextTick(() => stop('A', 'step')); return { success: true }; } + if (command === 'stackTrace') return { success: true, body: { stackFrames: [frame('main', stepped ? 11 : 1)] } }; + if (command === 'scopes') return { success: true, body: { scopes: [{ name: 'Locals', variablesReference: 101, expensive: false }] } }; + if (command === 'variables') { + localsReads++; + deps.mockProxyManager.simulateExited(17); + return { success: true, body: { variables: [{ name: 'x', value: '1', variablesReference: 0 }] } }; + } + return { success: true }; + }); + const answer = await call('step_into', { sessionId: s }); + expect(stepped).toBe(true); + expect(localsReads).toBe(1); + expect(answer.state).toBe(SessionState.STOPPED); + expect(answer.message).toContain('the session ended before the stack could be read'); + expect(answer.exitCode).toBe(17); + expect(answer.pending).toBeUndefined(); + expect(answer.location).toBeUndefined(); + expect(answer.snapshot).toBeUndefined(); + expect(core.sessionManager.getSession(s)!.snapshotDiffBase).toBeUndefined(); + }); + + it('reports the program ended when the step snapshot re-read outlives it', async () => { + const s = await running(); stop('origin'); + let stepped = false, localsReads = 0; + const landings: number[] = []; + deps.mockProxyManager.setDapRequestHandler(async command => { + if (command === 'stepIn') { stepped = true; process.nextTick(() => stop('A', 'step')); return { success: true }; } + if (command === 'stackTrace') { + const line = !stepped ? 1 : localsReads === 0 ? 11 : 50; + if (stepped) landings.push(line); + return { success: true, body: { stackFrames: [frame('main', line)] } }; + } + if (command === 'scopes') return { success: true, body: { scopes: [{ name: 'Locals', variablesReference: 101, expensive: false }] } }; + if (command === 'variables') { + if (++localsReads === 1) stop('B', 'step'); + else deps.mockProxyManager.simulateExited(23); + return { success: true, body: { variables: [{ name: 'x', value: '1', variablesReference: 0 }] } }; + } + return { success: true }; + }); + const answer = await call('step_into', { sessionId: s }); + expect(landings).toEqual([11, 50]); + expect(localsReads).toBe(2); + expect(answer.state).toBe(SessionState.STOPPED); + expect(answer.message).toContain('the session ended before the stack could be read'); + expect(answer.exitCode).toBe(23); + expect(answer.pending).toBeUndefined(); + expect(answer.location).toBeUndefined(); + expect(answer.snapshot).toBeUndefined(); + expect(core.sessionManager.getSession(s)!.snapshotDiffBase).toBeUndefined(); + }); + + it('reports the program ended when a retried landing snapshot exhausts the window after exit', async () => { + vi.useFakeTimers({ shouldAdvanceTime: false }); + const s = await running(); stop('origin'); + let stepped = false, landingReads = 0, exitedAt = 0, firstReadAt = 0; + deps.mockProxyManager.setDapRequestHandler(async command => { + if (command === 'next') { stepped = true; process.nextTick(() => stop('A', 'step')); return { success: true }; } + if (command === 'stackTrace') { + if (!stepped) return { success: true, body: { stackFrames: [frame('main', 1)] } }; + const read = ++landingReads; + if (read === 1) firstReadAt = performance.now(); + await new Promise(resolve => setTimeout(resolve, read === 1 ? 29_500 : 4_900)); + if (read === 1) stop('B', 'step'); + return { success: true, body: { stackFrames: [frame('main', read === 1 ? 11 : 50)] } }; + } + if (command === 'scopes') return { success: true, body: { scopes: [{ name: 'Locals', variablesReference: 101, expensive: false }] } }; + if (command === 'variables') { + deps.mockProxyManager.simulateExited(29); + exitedAt = performance.now(); + // Keep the real locals request pending until the re-read expires: + // ended must win over both resumed and budget-expiry wording. + return new Promise(() => {}); + } + return { success: true }; + }); + let answer: Payload | undefined; + const pending = call('step_over', { sessionId: s }).then(value => { answer = value; }); + await vi.advanceTimersByTimeAsync(34_800); + expect(landingReads).toBe(2); + expect(exitedAt - firstReadAt).toBeGreaterThanOrEqual(34_400); + expect(exitedAt - firstReadAt).toBeLessThan(35_000); + expect(core.sessionManager.getSession(s)!.state).toBe(SessionState.STOPPED); + expect(answer).toBeUndefined(); + await vi.advanceTimersByTimeAsync(600); + await pending; + expect(answer?.state).toBe(SessionState.STOPPED); + expect(answer?.message).toContain('the session ended before the stack could be read'); + expect(answer?.exitCode).toBe(29); + expect(answer?.pending).toBeUndefined(); + expect(answer?.location).toBeUndefined(); + expect(answer?.snapshot).toBeUndefined(); + expect(answer?.note).toBeUndefined(); + expect(core.sessionManager.getSession(s)!.snapshotDiffBase).toBeUndefined(); + }); + + it('discards a timed out snapshot after its stop is replaced', async () => { + vi.useFakeTimers({ shouldAdvanceTime: false }); + const s = await running(); stop('A', 'exception'); + const pin = pinStop(core.sessionManager.getSession(s)!); + let localsReads = 0; + deps.mockProxyManager.setDapRequestHandler(async command => { + if (command === 'stackTrace') return { success: true, body: { stackFrames: [frame('A', 11)] } }; + if (command === 'scopes') return { success: true, body: { scopes: [{ name: 'Locals', variablesReference: 101, expensive: false }] } }; + if (command === 'variables') { + localsReads++; + stop('B', 'breakpoint', 2); + return new Promise(() => {}); + } + return { success: true }; + }); + const stack = await core.sessionManager.getStackTraceDetailed(s, undefined, false, { pin }); + const pending = composeStopSnapshot(ctx(), s, stack, 'snapshot-timeout-replacement', { pin }); + await vi.advanceTimersByTimeAsync(2100); + expect(localsReads).toBe(1); + expect(core.sessionManager.getSession(s)!.lastStop?.description).toBe('B'); + expect(await pending).toBeUndefined(); + }); + it('does not request scopes from a caller frame after the stop is replaced', async () => { const s = await running(); stop('A'); const pin = pinStop(core.sessionManager.getSession(s)!);