diff --git a/CLAUDE.md b/CLAUDE.md index 92d6042b2..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`) - - 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, 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 new file mode 100644 index 000000000..a8f374de8 --- /dev/null +++ b/changelog.d/1348.fixed.md @@ -0,0 +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. 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/architecture/session-state-machine.md b/docs/architecture/session-state-machine.md index 88d2e9940..3b024b96b 100644 --- a/docs/architecture/session-state-machine.md +++ b/docs/architecture/session-state-machine.md @@ -82,6 +82,73 @@ 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 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 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 A **phase** is a public state one to one (`created`, `starting`, `running`, `paused`, @@ -108,7 +175,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..1c34effe0 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,41 @@ 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 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. 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 +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. + ### 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 { 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 @@ -646,9 +653,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; @@ -661,14 +668,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, timeoutMs: 30_000 }) + : 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; @@ -681,13 +691,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/inspection-tools.ts b/src/server/handlers/inspection-tools.ts index 2d6e3f978..4c5f24e7b 100644 --- a/src/server/handlers/inspection-tools.ts +++ b/src/server/handlers/inspection-tools.ts @@ -5,6 +5,8 @@ import { ProtocolError, ProtocolErrorCode } from '@modelcontextprotocol/server'; import { SessionState } from '@debugmcp/shared'; import { hasPausingBreakpoint } from '../../session/launch/launch-arming.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'; @@ -81,6 +83,13 @@ export const getStackTraceTool: ToolHandler = async (ctx, args) => { const failureDiagnostics = () => ctx.sessionManager.getSession(args.sessionId)?.failureDiagnostics; + const changed = (note: string) => { + const after = ctx.sessionManager.getSession(args.sessionId); + 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 @@ -97,8 +106,27 @@ export const getStackTraceTool: ToolHandler = async (ctx, args) => { // 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; + 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; + 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()); + } + } 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/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/session/attach/attach-controller.ts b/src/session/attach/attach-controller.ts index cdf9e24a4..8041395b7 100644 --- a/src/session/attach/attach-controller.ts +++ b/src/session/attach/attach-controller.ts @@ -42,8 +42,10 @@ 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 { commitStopSnapshot } from '../inspection/stop-snapshot.js'; +import { landingFields } from '../inspection/stop-location.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'; import { releaseAttachedTarget, type TargetRelease } from './target-release.js'; @@ -210,7 +212,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. @@ -345,6 +347,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 +374,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(); @@ -463,15 +466,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 = 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 @@ -499,6 +502,7 @@ export class AttachController { : attachedTo, ...(attachPausePending ? { pending: true } : {}), ...(landing ? landingFields(landing) : {}), + ...(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. @@ -539,6 +543,7 @@ export class AttachController { attachData.warning = warningParts.join('; '); } + commitStopSnapshot(snapshot); return { success: true, state: session.state, diff --git a/src/session/execution/execution-controller.ts b/src/session/execution/execution-controller.ts index 143512d4d..50b8eb2ce 100644 --- a/src/session/execution/execution-controller.ts +++ b/src/session/execution/execution-controller.ts @@ -48,6 +48,7 @@ import { redactStopInfo, SessionState, USER_BREAK_REASONS, + type Deadline, type SessionStopInfo, type StackFrame } from '@debugmcp/shared'; @@ -80,8 +81,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 { composeStopSnapshot } from '../inspection/stop-snapshot.js'; +import { landingFields, type StopLanding } from '../inspection/stop-location.js'; +import { commitStopSnapshot, composeStopSnapshot } from '../inspection/stop-snapshot.js'; +import { readPinnedStop, rereadStop, startStopRead, 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 +191,35 @@ 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; + startedAt?: number; + deliver?: () => void; + 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 +347,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 +361,27 @@ 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 }); + } + 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) { @@ -381,14 +422,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 +479,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 +490,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 +529,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 +552,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 +562,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 +585,8 @@ export class ExecutionController { noProgramFrame: landing.noProgramFrame === true } ); - if (!settled) { - 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 ); @@ -557,7 +594,71 @@ 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 }; + // 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 (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); + changed.data!.note = read.note; + settle(changed); + return; + } + const answer = answerFor(read.pin, read.landing); + 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); }; const onTerminated = () => settleEnded(options.terminatedMessage); @@ -568,11 +669,9 @@ export class ExecutionController { // 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. + // 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` @@ -632,7 +731,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 +926,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 +989,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,40 +1004,43 @@ 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'); + + // 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 (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_THEN_ENDED_MESSAGE, ...ownStopReason() } + data: { message: 'Paused', ...ownStopReason(read.current), note: read.note } }; } this.ctx.logger.info( `[SessionManager pause] Paused session ${sessionId}. Current state: ${session.state}` ); + commitStopSnapshot(read.snapshot); return { success: true, 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 +1153,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 +1169,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 +1184,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 +1232,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 +1248,37 @@ 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: read.note, + ...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?.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 +1292,7 @@ export class ExecutionController { landing.stackResult?.frames ?? [], { stepFilterHint: candidateHint, - hasStepperWalkNote: stopAtLanding.text !== undefined, + hasStepperWalkNote: stopAtLanding.info.text !== undefined, noProgramFrame: landing.noProgramFrame === true } ); @@ -1184,7 +1310,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 +1394,76 @@ 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> { + 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; + 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)); + 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; + } + // 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 }; + } + /** * 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,21 +1471,26 @@ 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); }); try { const detailed = await Promise.race([ - this.ctx.getStackTraceDetailed(sessionId, threadId, true, { ensureStackReady: false }), + 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; } + 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..415e2ba19 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 { 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'; @@ -168,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 @@ -190,7 +194,6 @@ function emptyResult(note?: string, threadId?: number): StackTraceResult { }; } -type StopRecord = NonNullable; interface SiblingStack { threadId: number; @@ -208,7 +211,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(); @@ -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}` @@ -247,13 +252,19 @@ 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 = 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, ...(opts?.deadline ? { timeoutMs: 30_000 } : {}) + }); + if (opts?.pin && !stillAtGate()) return emptyResult(); let note: string | undefined; let resultThreadId = effectiveThreadId; @@ -264,13 +275,15 @@ export class FrameAnchorResolver { proxyManager, effectiveThreadId, stopAtGate, - policy + stillAtGate, + 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 && @@ -293,8 +306,10 @@ export class FrameAnchorResolver { proxyManager, effectiveThreadId, rawFrames, - stopAtGate, - policy + gateRecord, + stillAtGate, + policy, + opts?.deadline ); if (adopted) { rawFrames = adopted.frames; @@ -303,6 +318,7 @@ export class FrameAnchorResolver { } } + if (opts?.pin && !stillAtGate()) return emptyResult(); let frames: StackFrame[] = framesOf(rawFrames, policy); const totalFrameCount = frames.length; let allFramesInternal = false; @@ -317,7 +333,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 +380,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,11 +473,13 @@ export class FrameAnchorResolver { private async waitForReadyStack( sessionId: string, - session: Pick, + session: Pick, proxyManager: IProxyManager, threadId: number, stopAtGate: ManagedSession['lastStop'], - policy: AdapterPolicy + stillAtGate: () => boolean, + 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 @@ -487,10 +505,11 @@ export class FrameAnchorResolver { policy, pausedStackReadyTimeoutMs, undefined, - pausedStackReadyIntervalMs + pausedStackReadyIntervalMs, + parent ); 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 }; @@ -500,7 +519,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); @@ -552,7 +571,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 +597,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,27 +636,30 @@ export class FrameAnchorResolver { */ private async adoptProgramThread( sessionId: string, - session: Pick, + session: Pick, proxyManager: IProxyManager, stoppedThreadId: number, stoppedFrames: DebugProtocol.StackFrame[], - stopAtGate: ManagedSession['lastStop'], - policy: AdapterPolicy + gateRecord: StopRecord | undefined, + stillAtGate: () => boolean, + policy: AdapterPolicy, + parent?: Deadline ): 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, stoppedThreadId, stoppedFrames, policy, - this.ctx.tunables.pausedStackReadyTimeoutMs + this.ctx.tunables.pausedStackReadyTimeoutMs, + undefined, undefined, parent ); - 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 +669,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}.` ); @@ -745,9 +767,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( @@ -756,7 +779,7 @@ export class FrameAnchorResolver { threadId, policy, this.ctx.tunables.pausedStackReadyTimeoutMs, - threads + threads, undefined, within ); if (alternative) { return ( @@ -786,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 new file mode 100644 index 000000000..7532b0612 --- /dev/null +++ b/src/session/inspection/pinned-stop-read.ts @@ -0,0 +1,108 @@ +/** + * 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 { composeStopSnapshot, type ComposeSnapshotOptions, type StopSnapshotContext } from './stop-snapshot.js'; +import { ErrorMessages } from '../../utils/error-messages.js'; + +export type PinnedStopReadContext = StopLandingContext & StopSnapshotContext; +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; + readonly startedAt?: number; + readonly pin?: StopPin; + readonly snapshot?: Omit | false; + readonly alsoAwait?: () => Promise; + readonly rereads?: 0 | 1; +} + +export type PinnedStopRead = + | { 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; } +} + +export function pinSession(ctx: Pick, sessionId: string): StopPin { + const session = sessionOrUndefined(ctx, sessionId); + return session ? pinStop(session) : { sessionId, stop: undefined }; +} + +export async function readPinnedStop( + ctx: PinnedStopReadContext, sessionId: string, logTag: string, opts: PinnedStopReadOptions = {} +): Promise { + let pin = opts.pin ?? pinSession(ctx, sessionId); + const startedAt = opts.startedAt ?? startStopRead(); + const changed = (note = ErrorMessages.stopChangedWhileRead()): PinnedStopRead => ({ + status: 'changed', current: stopRecordOf(sessionOrUndefined(ctx, sessionId)), note + }); + 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) { + snapshot = await composeStopSnapshot(ctx, sessionId, landing.stackResult, logTag, { + ...(opts.snapshot ?? {}), pin: under, ...(budget ? { deadline: budget } : {}) + }); + } + if (opts.alsoAwait && !budget?.expired) { + if (budget) await budget.race(opts.alsoAwait()); + else await opts.alsoAwait(); + } + return { landing, snapshot }; + }; + 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); + 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 }; +} + +export interface DescribedStop { + readonly stop: StopRecord | undefined; + readonly landing: StopLanding; + readonly snapshot: StopSnapshot | undefined; + readonly note?: string; +} + +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 }; + 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..7c6d4c457 100644 --- a/src/session/inspection/stop-location.ts +++ b/src/session/inspection/stop-location.ts @@ -7,13 +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 { pinBroken, type StopPin } from '../stop-record.js'; /** * The landing as read: the answer's fields (`StopLandingFields`) plus the @@ -40,19 +41,36 @@ 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; + 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 12a571692..507dcbb39 100644 --- a/src/session/inspection/stop-snapshot.ts +++ b/src/session/inspection/stop-snapshot.ts @@ -15,11 +15,12 @@ * - 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 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 { pinBroken, pinHolds, pinStop, type StopPin } from '../stop-record.js'; import { applyVariableCaps, snapshotLocalsLimits } from '../variable-caps.js'; import { buildSnapshotFrameKey, @@ -47,6 +48,26 @@ 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; + 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); + // 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. */ @@ -165,7 +186,12 @@ export async function composeStopSnapshot( if (session.state !== SessionState.PAUSED) { return undefined; } - const stop = session.lastStop; + 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; @@ -239,31 +265,39 @@ 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 = 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 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 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( `locals omitted: the locals read exceeded ${timeoutMs}ms; get_local_variables reads them` ); } 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 +346,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 +358,21 @@ 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) { - snapshot.changedVariables = diffLocals(base, flat, complete); - session.snapshotDiffBase = { stopRef: stop, frameKey, rendered: flat, complete, callerResolved }; } else { - snapshot.locals = flat; - if (stop) { - session.snapshotDiffBase = { stopRef: stop, frameKey, rendered: flat, complete, callerResolved }; + if (stopId !== undefined && base && base.frameKey === frameKey && !stepOutSameFn && !brokenCallerUnwind) { + snapshot.changedVariables = diffLocals(base, flat, complete); + } else { + snapshot.locals = flat; + } + if (stopId !== undefined) { + pendingBaselines.set(snapshot, () => { + if (session.run === run && session.proxyGeneration === generation && + (!session.snapshotDiffBase || stopId >= session.snapshotDiffBase.stopId)) { + session.snapshotDiffBase = { stopId, frameKey, rendered: flat, complete, callerResolved }; + } + }); } } } @@ -354,9 +394,8 @@ export async function composeStopSnapshot( } } } finally { - if (timer !== undefined) { - clearTimeout(timer); - } + localsBudget?.dispose(); + if (timer !== undefined) clearTimeout(timer); } } diff --git a/src/session/launch/debug-launcher.ts b/src/session/launch/debug-launcher.ts index d69efb880..9e262a50b 100644 --- a/src/session/launch/debug-launcher.ts +++ b/src/session/launch/debug-launcher.ts @@ -34,9 +34,10 @@ 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 { commitStopSnapshot } from '../inspection/stop-snapshot.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 { logpointChecksField } from '../breakpoints/logpoint-checks.js'; @@ -59,6 +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, stopRecordOf } from '../stop-record.js'; /** * A launch flag the way the adapter will see it. The proxy launcher merges @@ -508,7 +510,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 = []; @@ -669,7 +671,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 @@ -745,13 +747,21 @@ 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). + let described = describedStop(finalSession.state === SessionState.PAUSED + ? await readPinnedStop(this.ctx, sessionId, 'launch') + : undefined); + finalState = finalSession.state; + 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): @@ -822,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; @@ -839,24 +849,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( @@ -886,6 +895,19 @@ export class DebugLauncher { } } + // 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, @@ -910,11 +932,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), + ...(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 @@ -1182,11 +1205,14 @@ export class DebugLauncher { holdMs: this.ctx.tunables.launchHoldMs, }); 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'); + 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(finalSession.state === SessionState.PAUSED + ? await readPinnedStop(this.ctx, sessionId, 'launch') + : undefined); + finalState = finalSession.state; + const { landing, snapshot } = finalState === SessionState.PAUSED ? described : describedStop(undefined); const runToCompletion = finalState === SessionState.STOPPED ? buildRunToCompletionSummary(finalSession) : undefined; @@ -1205,6 +1231,7 @@ export class DebugLauncher { const warning = anchorWarnings(anchorResolution); this.ctx.logger.info(`[SessionManager] Hot restart of session ${sessionId} answered. State: ${finalState}`); + commitStopSnapshot(snapshot); return { success: true, state: finalState, @@ -1221,8 +1248,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), + ...(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)), diff --git a/src/session/live-update/live-update-controller.ts b/src/session/live-update/live-update-controller.ts index d495c1706..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 { describeStopLocation, landingFields, type StopLanding } from '../inspection/stop-location.js'; -import { composeStopSnapshot } from '../inspection/stop-snapshot.js'; +import { commitStopSnapshot } from '../inspection/stop-snapshot.js'; +import { landingFields } from '../inspection/stop-location.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; } @@ -120,11 +123,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) : {}; + const observed = await this.describeState(current, first.kind !== 'response'); + commitStopSnapshot(observed.snapshot); return { success: true, ...body, ...after, - ...(await this.describeState(current, first.kind !== 'response')), + ...observed, }; } @@ -149,7 +154,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.' } : {}), }; @@ -198,15 +203,20 @@ 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> { + 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. + described = describedStop(await readPinnedStop(this.ctx, session.id, 'launch')); + } 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'); + if (state === SessionState.PAUSED && described) { 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/operations-context.ts b/src/session/operations-context.ts index 177e590b9..8a6d3b531 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. @@ -175,7 +178,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 @@ -184,7 +187,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-core.ts b/src/session/session-manager-core.ts index acda3fc5f..d76a129fc 100644 --- a/src/session/session-manager-core.ts +++ b/src/session/session-manager-core.ts @@ -27,8 +27,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'; @@ -263,6 +272,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 @@ -576,7 +615,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); @@ -2119,7 +2160,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. @@ -2384,17 +2425,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. @@ -2405,8 +2445,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) @@ -2443,20 +2483,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 }; @@ -2482,7 +2522,6 @@ export abstract class SessionManagerCore extends EventEmitter { typeof threadId === 'number' && session.adapterCapabilities?.supportsExceptionInfoRequest ) { - const stopRef = session.lastStop; proxyManager .sendDapRequest( 'exceptionInfo', @@ -2491,15 +2530,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-manager-data.ts b/src/session/session-manager-data.ts index 176cc03c9..877ddc219 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, 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 // 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, 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); 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/session-store.ts b/src/session/session-store.ts index fc5823865..17ac59834 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; } @@ -341,16 +344,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..036d0c54b --- /dev/null +++ b/src/session/stop-record.ts @@ -0,0 +1,211 @@ +/** + * 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 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; + /** 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 first dependent read. */ +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; +} + +/** + * 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 || stopIdOf(session) !== pin.stop?.id; +} diff --git a/src/utils/error-messages.ts b/src/utils/error-messages.ts index 28ba25f97..98129bd34 100644 --- a/src/utils/error-messages.ts +++ b/src/utils/error-messages.ts @@ -678,6 +678,21 @@ export const ErrorMessages = { sessionClosedWhileWaiting: (sessionId: string) => `Session ${sessionId} was closed while waiting for a stop.`, + /** + * 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 stop changed while this answer was being read; its stack and snapshot were omitted. ' + + 'Call get_stack_trace again to read the current stop.', + + 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.', + /** * 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/server-inspection-tools.test.ts b/tests/core/unit/server/server-inspection-tools.test.ts index fa6a3d9f1..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 + '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 new file mode 100644 index 000000000..839985f9e --- /dev/null +++ b/tests/core/unit/server/stop-pin-boundaries.test.ts @@ -0,0 +1,249 @@ +/** 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'; +import { DapResponseError } from '../../../../src/proxy/dap-response-error.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('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' + ? (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 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 () => { + 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 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 () => { + 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('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', 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 }; + }); + 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); + expect(a.pin.stop?.threadId).toBe(2); + expect(a.landing.threadId).toBe(3); + } + }); + + 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; + 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..a65d7e393 --- /dev/null +++ b/tests/core/unit/server/stop-pin-consistency.test.ts @@ -0,0 +1,453 @@ +/** 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'; +import { FakeDebugAdapter } from '../../../test-utils/fakes/fake-debug-adapter.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('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('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('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 }); + 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 new file mode 100644 index 000000000..cc5f83f41 --- /dev/null +++ b/tests/core/unit/server/stop-pin-ordinary.test.ts @@ -0,0 +1,137 @@ +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; + 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'}]}}; + 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(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=>{ + 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..f9b681ed0 --- /dev/null +++ b/tests/core/unit/server/stop-pin-regressions.test.ts @@ -0,0 +1,543 @@ +/** 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'; +import { composeStopSnapshot } from '../../../../src/session/inspection/stop-snapshot.js'; +import { ErrorMessages } from '../../../../src/utils/error-messages.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('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('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('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)!); + 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)!); + 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 => { + 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(/stop changed.*re-read did not complete.*35000 ms window/i); + await vi.advanceTimersByTimeAsync(35_000); 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 new file mode 100644 index 000000000..2ed213428 --- /dev/null +++ b/tests/core/unit/server/stop-pins-through-tools.test.ts @@ -0,0 +1,167 @@ +/** + * 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'; +import type { ToolContext } from '../../../../src/server/tool-context.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 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 }); + + 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'); + 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 () => { + 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 1a96d9c85..df239f62d 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 @@ -72,7 +72,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']; @@ -283,13 +283,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-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 4f156496a..6ab213826 100644 --- a/tests/core/unit/session/inspection/stop-snapshot.test.ts +++ b/tests/core/unit/session/inspection/stop-snapshot.test.ts @@ -8,11 +8,19 @@ 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, + 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 }, @@ -61,12 +69,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 }, @@ -84,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 }); @@ -139,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, { maxFrames: 3 }); + 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 () => { @@ -497,7 +519,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 +639,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 +974,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 +989,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 +1007,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 +1022,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 +1103,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..84e7d1be5 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,121 @@ 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' })); + 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( + 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..ac77307fc --- /dev/null +++ b/tests/core/unit/session/session-manager-stop-pin-routes.test.ts @@ -0,0 +1,544 @@ +/** + * 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 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); + 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 }); + 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 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; + 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; + 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('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 () => { + 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; + let stackReads = 0; + const commandReadFrame = () => ++stackReads === 1 ? FRAME_A : FRAME_B; + 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 }); + stopB(proxy); + } + switch (name) { + case 'stackTrace': + return { success: true, body: { stackFrames: [commandReadFrame()] } }; + 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.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'); + }); + + 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..895b0d34c --- /dev/null +++ b/tests/core/unit/session/session-manager-stop-pins.test.ts @@ -0,0 +1,337 @@ +/** + * 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)."); + }); + + 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', () => { + 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..66ee99f72 --- /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('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(true); + expect(pinBroken(undefined, pin)).toBe(true); + }); + + 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/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/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/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 4fcc04be1..52fca2658 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')) @@ -589,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) })); expect(describePendingStop).toHaveBeenCalledWith({ operation: 'step', attachMode: false, @@ -617,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) })); } finally { vi.useRealTimers(); } @@ -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