diff --git a/scripts/verify/advertised-schemas/tools/close_gdb_session.json b/scripts/verify/advertised-schemas/tools/close_gdb_session.json index 37b917e0d6d..07589826f59 100644 --- a/scripts/verify/advertised-schemas/tools/close_gdb_session.json +++ b/scripts/verify/advertised-schemas/tools/close_gdb_session.json @@ -1,7 +1,7 @@ { "schemas": { "input compact": "d5defc56611ce19d", - "output compact": "377e3b6f9b0db8e3" + "output compact": "eed7b3ff8d51990e" }, "patterns": { "input": [ diff --git a/scripts/verify/advertised-schemas/tools/close_rizin_debug_session.json b/scripts/verify/advertised-schemas/tools/close_rizin_debug_session.json index 2ce87e5105d..07589826f59 100644 --- a/scripts/verify/advertised-schemas/tools/close_rizin_debug_session.json +++ b/scripts/verify/advertised-schemas/tools/close_rizin_debug_session.json @@ -1,7 +1,7 @@ { "schemas": { "input compact": "d5defc56611ce19d", - "output compact": "9ca208e0b4a3ca6f" + "output compact": "eed7b3ff8d51990e" }, "patterns": { "input": [ diff --git a/src/contracts/gdbToolContracts.ts b/src/contracts/gdbToolContracts.ts index a6fade438d8..b5cabbf9a2f 100644 --- a/src/contracts/gdbToolContracts.ts +++ b/src/contracts/gdbToolContracts.ts @@ -1,5 +1,8 @@ import { z } from "zod"; -import { DEBUGGER_SESSION_STOP_CODES } from "../domain/debuggerSessionErrors.js"; +import { + DEBUGGER_SESSION_STOP_CODES, + INFERIOR_DISPOSITIONS, +} from "../domain/debuggerSessionErrors.js"; import { absoluteLocalPathStringSchema } from "../domain/localPath.js"; import { @@ -139,10 +142,10 @@ export const GDB_TOOL_CONTRACTS = [ ), kind: "native-provider", description: - "Close the owned GDB process after verifying the inferior state. When one live thread group has a verified durable output TTY, REA automatically detaches it, which may resume target execution; otherwise close reports that a disposition is required. REA never kills attached or remote targets as part of debugger cleanup. In a shared MCP server, this admitted close retires any active binary-analysis session; after target effects have settled, call open_binary before further analysis. Close an active Ghidra session explicitly first.", + "Close the owned GDB process after verifying the inferior state. When one live thread group has a verified durable output TTY, REA automatically detaches it, which may resume target execution; otherwise close reports that a disposition is required. REA never kills attached or remote targets as part of debugger cleanup. target_state reports what cleanup established: none_observed, detached, exited, or unknown when the debugger was terminated without a verified detach. In a shared MCP server, this admitted close retires any active binary-analysis session; after target effects have settled, call open_binary before further analysis. Close an active Ghidra session explicitly first.", inputSchema: z.strictObject({ session_id: sessionId }), outputSchema: z.strictObject({ - target_state: z.enum(["none_observed", "unknown"]), + target_state: z.enum(INFERIOR_DISPOSITIONS), }), examples: [ { diff --git a/src/contracts/rizinDebugToolContracts.ts b/src/contracts/rizinDebugToolContracts.ts index dcd9839bc05..ef9caad2c47 100644 --- a/src/contracts/rizinDebugToolContracts.ts +++ b/src/contracts/rizinDebugToolContracts.ts @@ -1,5 +1,8 @@ import { z } from "zod"; -import { DEBUGGER_SESSION_STOP_CODES } from "../domain/debuggerSessionErrors.js"; +import { + DEBUGGER_SESSION_STOP_CODES, + INFERIOR_DISPOSITIONS, +} from "../domain/debuggerSessionErrors.js"; import { absoluteLocalPathStringSchema } from "../domain/localPath.js"; import type { ToolContract } from "./toolContractTypes.js"; @@ -145,9 +148,11 @@ export const RIZIN_DEBUG_TOOL_CONTRACTS = [ ), kind: "native-provider", description: - "Close the REA-owned Rizin debugger after verifying no inferior remains, detaching one with a verified caller-selected TTY output sink, or terminating the debugger when a desynchronized command transport cannot resynchronize. A detached target may continue running, read from and write to that TTY; a target whose detach was not verified may keep running with unknown state and output route. REA never signals an inferior based on PID or path. In a shared MCP server, this admitted close retires any active binary-analysis session; after target effects have settled, call open_binary before further analysis. Close an active Ghidra session explicitly first.", + "Close the REA-owned Rizin debugger after verifying no inferior remains, detaching one with a verified caller-selected TTY output sink, or terminating the debugger when a desynchronized command transport cannot resynchronize. A detached target may continue running, read from and write to that TTY; a target whose detach was not verified may keep running with unknown state and output route. REA never signals an inferior based on PID or path. target_state reports what cleanup established: none_observed, detached, exited, or unknown when the debugger was terminated without a verified detach. In a shared MCP server, this admitted close retires any active binary-analysis session; after target effects have settled, call open_binary before further analysis. Close an active Ghidra session explicitly first.", inputSchema: z.strictObject({ session_id: sessionId }), - outputSchema: z.strictObject({ target_state: z.literal("unknown") }), + outputSchema: z.strictObject({ + target_state: z.enum(INFERIOR_DISPOSITIONS), + }), examples: [ { title: "Close Rizin debugger", diff --git a/src/domain/debuggerSessionErrors.ts b/src/domain/debuggerSessionErrors.ts index 24d8a382e38..f961d41b42c 100644 --- a/src/domain/debuggerSessionErrors.ts +++ b/src/domain/debuggerSessionErrors.ts @@ -128,6 +128,24 @@ export const DEBUGGER_CLEANUP_INCOMPLETE_CODES = [ export type DebuggerCleanupIncompleteCode = (typeof DEBUGGER_CLEANUP_INCOMPLETE_CODES)[number]; +/** + * What a completed debugger stop established about the inferior, as close + * tools report it. + * - `none_observed`: the debugger reported no inferior. + * - `detached`: the debugger confirmed detaching its one inferior, which may + * keep running. + * - `exited`: every identified inferior process ended after detach or debugger exit. + * - `unknown`: the debugger was terminated without a verified detach, so the + * inferior may still be running. + */ +export const INFERIOR_DISPOSITIONS = [ + "none_observed", + "detached", + "exited", + "unknown", +] as const; +export type InferiorDispositionState = (typeof INFERIOR_DISPOSITIONS)[number]; + /** A debugger stop REA could not confirm: its code and explanation. */ export interface DebuggerCleanupIncomplete { readonly code: DebuggerCleanupIncompleteCode; diff --git a/src/gdb/GdbSessionManager.ts b/src/gdb/GdbSessionManager.ts index 98850b5068b..09b740c6df6 100644 --- a/src/gdb/GdbSessionManager.ts +++ b/src/gdb/GdbSessionManager.ts @@ -55,6 +55,7 @@ import { type DebuggerCleanupIncompleteCode, type DebuggerSessionStop, type DebuggerSessionStopCode, + type InferiorDispositionState, stoppedDebuggerSessionError, unknownDebuggerSessionError, } from "../domain/debuggerSessionErrors.js"; @@ -98,6 +99,7 @@ import { stopOwnedDebuggerProcess, type OwnedDebuggerDetachResult, type OwnedInferiorIdentity, + type VerifiedInferiorDisposition, type ProcessStartTimeReader, verifyOwnedInferiorsEnded, } from "../process/ownedDebuggerSession.js"; @@ -276,14 +278,15 @@ interface GdbSession { readonly supervisor: ProviderProcessSupervisor; /** Confirms target disposition and any durable sink before process cleanup. */ readonly detachInferior: () => Promise; - readonly inferiorStateUnknown: () => boolean; + readonly verifiedInferior: () => VerifiedInferiorDisposition | undefined; readonly verifyInferiorsEndedAfterExit: () => Promise; readonly knownInferiorIdentities: Map; readonly inferiorTty: string | undefined; readonly stdoutSettled: Promise; readonly settleStdout: () => void; inferiorTtyVerified: boolean; - noInferiorVerified: boolean; + /** Inferior state verified since the last target command, if any. */ + inferiorDisposition: "none_observed" | "detached" | undefined; /** Sticky admission seal once destructive cleanup starts, including failed stops. */ cleanupStarted: boolean; /** close_gdb_session started cleanup, so a successful retry releases the ID. */ @@ -365,6 +368,15 @@ const gdbCloseUnavailable = (): AnalysisInputError => unknownDebuggerSessionError(GDB_SESSION_TOOLS, "close_gdb_session"); /** Owns persistent GDB/MI sessions independently from the active binary target. */ +/** The detach result a GDB-verified inferior state already establishes. */ +const verifiedDetachResult = { + none_observed: { status: "no-inferior" }, + detached: { status: "detached", outputSink: "durable" }, +} as const satisfies Record< + NonNullable, + OwnedDebuggerDetachResult +>; + export class GdbSessionManager { readonly #startupResources = new ArtifactResourceScope(); readonly #sessions: OwnedDebuggerSessionRegistry; @@ -651,7 +663,7 @@ export class GdbSessionManager { launched, supervisor, detachInferior: () => this.#detachInferior(session), - inferiorStateUnknown: () => !session.noInferiorVerified, + verifiedInferior: () => session.inferiorDisposition, verifyInferiorsEndedAfterExit: async () => { const ended = await verifyOwnedInferiorsEnded( session.knownInferiorIdentities.values(), @@ -667,7 +679,7 @@ export class GdbSessionManager { inferiorTtyVerified: false, // GDB is launched with --nx and receives no target-execution commands // during startup, so no inferior can exist until execute() is called. - noInferiorVerified: true, + inferiorDisposition: "none_observed", cleanupStarted: false, closeRequested: false, closeQueued: false, @@ -864,7 +876,7 @@ export class GdbSessionManager { session.ready = true; // Before publication no target command can run. Once usable, the // inferior state is no longer inferred from startup phase. - session.noInferiorVerified = false; + session.inferiorDisposition = undefined; this.#sessions.add(session); releaseReservation(); return ok({ session_id: id, mi_version: miVersion }); @@ -1089,7 +1101,7 @@ export class GdbSessionManager { stoppedWhileQueued, ), ); - session.noInferiorVerified = false; + session.inferiorDisposition = undefined; session.knownInferiorIdentities.clear(); if (commandMayChangeInferiorOutput(command)) session.inferiorTtyVerified = false; @@ -1295,10 +1307,7 @@ export class GdbSessionManager { async close( sessionId: string, ): Promise< - Result< - { readonly target_state: "none_observed" | "unknown" }, - AnalysisError - > + Result<{ readonly target_state: InferiorDispositionState }, AnalysisError> > { if (this.#closing) return err( @@ -1316,7 +1325,6 @@ export class GdbSessionManager { return err(gdbCloseUnavailable()); if (session.exited || session.cleanupStarted) return this.#finishSessionCleanup(session); - let targetState: "none_observed" | "unknown" = "unknown"; try { const groups = await this.#request( session, @@ -1373,16 +1381,11 @@ export class GdbSessionManager { session.cleanupStarted = true; session.closeRequested = true; if (groupCount === 0) { - session.noInferiorVerified = true; - targetState = "none_observed"; + session.inferiorDisposition = "none_observed"; await this.#request(session, "-gdb-exit"); } else { - session.noInferiorVerified = false; - const disposition = await this.#detachInferior(session); - targetState = - disposition.status === "no-inferior" - ? "none_observed" - : "unknown"; + session.inferiorDisposition = undefined; + await this.#detachInferior(session); } } catch { // If MI synchronization is lost, stop only the owned debugger process. @@ -1391,18 +1394,7 @@ export class GdbSessionManager { // first so an incomplete stop is retried as owned cleanup rather // than kept as a live, ready session. session.cleanupStarted = true; - session.closeRequested = true; - const stopped = await this.#stopDebuggerOnly(session); - if (stopped.status === "incomplete") - return err( - this.#sessions.retainCleanupFailure( - session, - "close_gdb_session", - stopped, - ), - ); - this.#sessions.remove(session); - return ok({ target_state: targetState }); + return this.#finishSessionCleanup(session); }, undefined, "close_gdb_session", @@ -1413,9 +1405,12 @@ export class GdbSessionManager { } } + /** Stop the owned debugger and report the inferior state it established. */ async #finishSessionCleanup( session: GdbSession, - ): Promise> { + ): Promise< + Result<{ readonly target_state: InferiorDispositionState }, AnalysisError> + > { session.closeRequested = true; const stopped = await this.#stopDebuggerOnly(session); if (stopped.status === "incomplete") @@ -1427,7 +1422,7 @@ export class GdbSessionManager { ), ); this.#sessions.remove(session); - return ok({ target_state: "unknown" }); + return ok({ target_state: stopped.inferior.state }); } async retryCleanupFailures(): Promise> { @@ -1857,7 +1852,10 @@ export class GdbSessionManager { async #detachInferior( session: GdbSession, ): Promise { - if (session.noInferiorVerified) return { status: "no-inferior" }; + // A verified state stands until a target command clears it, so owned + // cleanup reports the detach close already performed, not a bare absence. + if (session.inferiorDisposition !== undefined) + return verifiedDetachResult[session.inferiorDisposition]; if (session.exited) throw new OwnedDebuggerDetachFailure( "inferior-state-unknown", @@ -1889,10 +1887,10 @@ export class GdbSessionManager { const inferiorPids = gdbThreadGroupPids(groups.mi); if (inferiorPids?.length === 0) { session.knownInferiorIdentities.clear(); - session.noInferiorVerified = true; + session.inferiorDisposition = "none_observed"; return { status: "no-inferior" }; } - session.noInferiorVerified = false; + session.inferiorDisposition = undefined; if (inferiorPids?.length !== 1) throw inferiorPids === undefined ? new OwnedDebuggerDetachFailure( @@ -1942,7 +1940,7 @@ export class GdbSessionManager { session.knownInferiorIdentities.clear(); // The sole recursively inventoried inferior is now detached. Retain this // fact for owned shutdown even if the MI transport becomes unavailable. - session.noInferiorVerified = true; + session.inferiorDisposition = "detached"; return { status: "detached", outputSink: "durable" }; } diff --git a/src/process/ownedDebuggerSession.ts b/src/process/ownedDebuggerSession.ts index 1ede3a5105e..1e426513820 100644 --- a/src/process/ownedDebuggerSession.ts +++ b/src/process/ownedDebuggerSession.ts @@ -23,6 +23,7 @@ import type { JsonValue } from "../domain/jsonValue.js"; import type { DebuggerCleanupIncomplete, DebuggerCleanupIncompleteCode, + InferiorDispositionState, } from "../domain/debuggerSessionErrors.js"; import { parseLinuxProcessStat } from "./LinuxProcessStat.js"; import { @@ -31,19 +32,31 @@ import { } from "./ownedDebuggerCleanupError.js"; import { errorMessage } from "../kernel/errorMessage.js"; +/** + * What a completed stop established about the inferior. An unknown + * disposition carries the provider's reason and is never inferred from a PID + * or path. + */ +export type InferiorDisposition = + | { readonly state: Exclude } + | { readonly state: "unknown"; readonly reason: string }; + /** Result of terminating one debugger process owned by this application. */ export type OwnedDebuggerStopResult = - | { readonly status: "stopped" | "already_exited" } | { - /** - * The owned process stopped, but its provider declared inferior detach - * unavailable, so the inferior's state and output route remain unknown. - */ - readonly status: "stopped_inferior_unknown"; - readonly reason: string; + readonly status: "stopped" | "already_exited"; + readonly inferior: InferiorDisposition; } | ({ readonly status: "incomplete" } & DebuggerCleanupIncomplete); +/** The reason a completed stop left the inferior's state unknown, if it did. */ +export const inferiorUnknownReason = ( + stopped: OwnedDebuggerStopResult, +): string | undefined => + stopped.status !== "incomplete" && stopped.inferior.state === "unknown" + ? stopped.inferior.reason + : undefined; + /** * A provider's refusal or failure to detach its inferior, naming why. Other * detach errors are reported as `detach-failed`. @@ -235,6 +248,8 @@ const MAX_LATE_DEBUGGER_OUTPUT_BYTES = 64 * 1024; export type OwnedDebuggerDetachResult = | { readonly status: "no-inferior" } | { readonly status: "detached"; readonly outputSink: "durable" } + /** Detach was confirmed and every identified inferior process then ended. */ + | { readonly status: "inferior-ended" } | { /** * Serialized detach cannot be performed or verified because the @@ -297,15 +312,23 @@ const detachAttempts = new WeakMap< object, Promise >(); +/** Inferior states an owned debugger can verify before its process stops. */ +export type VerifiedInferiorDisposition = Exclude< + InferiorDispositionState, + "unknown" +>; + type DetachOutcome = - | { readonly kind: "confirmed" } + | { + readonly kind: "confirmed"; + readonly inferior: VerifiedInferiorDisposition; + } | { readonly kind: "unconfirmed" } - | { readonly kind: "inferior-ended" } | { readonly kind: "unavailable"; readonly reason: string }; const detachOutcomes = new WeakMap(); type VerifiedDetachResult = - | { readonly status: "no-inferior" } + | { readonly status: "no-inferior" | "inferior-ended" } | { readonly status: "detached"; readonly outputSink: "durable" }; const isVerifiedDetachResult = ( @@ -313,16 +336,32 @@ const isVerifiedDetachResult = ( ): result is VerifiedDetachResult => typeof result === "object" && result !== null && - (("status" in result && result.status === "no-inferior") || + (("status" in result && + (result.status === "no-inferior" || result.status === "inferior-ended")) || ("status" in result && result.status === "detached" && "outputSink" in result && result.outputSink === "durable")); +const verifiedDisposition = ( + result: VerifiedDetachResult, +): VerifiedInferiorDisposition => { + switch (result.status) { + case "no-inferior": + return "none_observed"; + case "detached": + return "detached"; + case "inferior-ended": + return "exited"; + default: + return result satisfies never; + } +}; + /** Preserve a provider's declaration that only termination remains. */ const detachOutcomeFor = (result: OwnedDebuggerDetachResult): DetachOutcome => isVerifiedDetachResult(result) - ? { kind: "confirmed" } + ? { kind: "confirmed", inferior: verifiedDisposition(result) } : result.status === "unavailable" ? { kind: "unavailable", reason: result.reason } : { kind: "unconfirmed" }; @@ -366,7 +405,12 @@ const waitForInferiorDetach = async ( interface OwnedDebuggerProcess { readonly id: string; readonly exited: boolean; - readonly inferiorStateUnknown?: () => boolean; + /** + * The inferior state the provider verified outside an owned detach attempt, + * or undefined while it is unverified. A provider that verifies its inferior + * only through `detachInferior` omits it. + */ + readonly verifiedInferior?: () => VerifiedInferiorDisposition | undefined; readonly verifyInferiorsEndedAfterExit?: () => Promise; readonly launched: { readonly process: { kill(signal: NodeJS.Signals): boolean }; @@ -389,8 +433,8 @@ const finishExitedDebuggerSession = async ( session: OwnedDebuggerProcess, debuggerName: string, platform: NodeJS.Platform, - status: "stopped" | "already_exited" | "stopped_inferior_unknown", - reason?: string, + status: "stopped" | "already_exited", + inferior: InferiorDisposition, ): Promise => { try { session.supervisor.limitAdditionalOutputBytes( @@ -418,14 +462,24 @@ const finishExitedDebuggerSession = async ( } if (platform !== "win32") session.supervisor.unrefOutputStreams(); session.supervisor.dispose(); - return status === "stopped_inferior_unknown" - ? { - status, - reason: - reason ?? - `Owned ${debuggerName} was terminated without a verified inferior detach.`, - } - : { status }; + return { status, inferior }; +}; + +/** The disposition a recorded detach outcome establishes, if it settled one. */ +const recordedDisposition = ( + outcome: DetachOutcome | undefined, +): InferiorDisposition | undefined => { + switch (outcome?.kind) { + case "confirmed": + return { state: outcome.inferior }; + case "unavailable": + return { state: "unknown", reason: outcome.reason }; + case "unconfirmed": + case undefined: + return undefined; + default: + return outcome satisfies never; + } }; /** @@ -450,10 +504,14 @@ export const stopOwnedDebuggerProcess = async ( reason: `Owned ${debuggerName} inferior detach is still pending after the process exited.`, }; const detachOutcome = detachOutcomes.get(session); - if ( - detachOutcome?.kind === "unconfirmed" || - (detachOutcome === undefined && session.inferiorStateUnknown?.() === true) - ) { + // A recorded provider declaration that serialized detach is impossible + // stays unknown; process exit cannot turn it into a verified one. + let inferior = recordedDisposition(detachOutcome); + if (inferior === undefined && detachOutcome === undefined) { + const verified = session.verifiedInferior?.(); + if (verified !== undefined) inferior = { state: verified }; + } + if (inferior === undefined) { try { if ((await session.verifyInferiorsEndedAfterExit?.()) !== true) return { @@ -461,7 +519,8 @@ export const stopOwnedDebuggerProcess = async ( code: "inferior-disposition-unverified", reason: `Owned ${debuggerName} inferior disposition was not verified before the debugger exited, and no owner proof confirms the identified inferior processes have ended.`, }; - detachOutcomes.set(session, { kind: "inferior-ended" }); + detachOutcomes.set(session, { kind: "confirmed", inferior: "exited" }); + inferior = { state: "exited" }; } catch (cause: unknown) { return { status: "incomplete", @@ -470,16 +529,12 @@ export const stopOwnedDebuggerProcess = async ( }; } } - // A recorded provider declaration already established that serialized - // detach is impossible; process exit cannot turn that into a verified one. return finishExitedDebuggerSession( session, debuggerName, platform, - detachOutcome?.kind === "unavailable" - ? "stopped_inferior_unknown" - : "already_exited", - detachOutcome?.kind === "unavailable" ? detachOutcome.reason : undefined, + "already_exited", + inferior, ); } if (platform === "win32") @@ -495,51 +550,46 @@ export const stopOwnedDebuggerProcess = async ( // An `unavailable` declaration is equally final: serialized detach cannot // be performed now, so only terminating the owned process completes // cleanup, with the inferior's disposition left unknown. - let unverifiedTerminationReason: string | undefined; const detachOutcome = detachOutcomes.get(session); - if (detachOutcome?.kind !== "confirmed") { - if (detachOutcome?.kind === "unavailable") { - unverifiedTerminationReason = detachOutcome.reason; - } else { - try { - if (session.detachInferior === undefined) { - detachOutcomes.set(session, { kind: "unconfirmed" }); - return { - status: "incomplete", - code: "detach-unsupported", - reason: `Owned ${debuggerName} inferior detach cannot be verified because the provider has no detach capability.`, - }; - } - const detached = await waitForInferiorDetach( - session, - session.detachInferior, - ); - if (detached === undefined) - return { - status: "incomplete", - code: "detach-timeout", - reason: `Owned ${debuggerName} inferior detach was not verified within ${String(DETACH_TIMEOUT_MS)} ms. This release has no runtime override.`, - }; - if (detached.status === "unavailable") { - unverifiedTerminationReason = detached.reason; - } else if (!isVerifiedDetachResult(detached)) { - detachOutcomes.set(session, { kind: "unconfirmed" }); - return { - status: "incomplete", - code: "detach-unconfirmed", - reason: `Owned ${debuggerName} provider did not confirm no inferior or detachment with a durable output sink.`, - }; - } else detachOutcomes.set(session, { kind: "confirmed" }); - } catch (cause: unknown) { + let inferior = recordedDisposition(detachOutcome); + if (inferior === undefined) { + try { + if (session.detachInferior === undefined) { + detachOutcomes.set(session, { kind: "unconfirmed" }); return { status: "incomplete", - code: - cause instanceof OwnedDebuggerDetachFailure - ? cause.code - : "detach-failed", - reason: `Owned ${debuggerName} inferior detach could not be verified: ${errorMessage(cause)}`, + code: "detach-unsupported", + reason: `Owned ${debuggerName} inferior detach cannot be verified because the provider has no detach capability.`, }; } + const detached = await waitForInferiorDetach( + session, + session.detachInferior, + ); + if (detached === undefined) + return { + status: "incomplete", + code: "detach-timeout", + reason: `Owned ${debuggerName} inferior detach was not verified within ${String(DETACH_TIMEOUT_MS)} ms. This release has no runtime override.`, + }; + if (detached.status === "unavailable") { + inferior = { state: "unknown", reason: detached.reason }; + } else if (!isVerifiedDetachResult(detached)) { + return { + status: "incomplete", + code: "detach-unconfirmed", + reason: `Owned ${debuggerName} provider did not confirm no inferior or detachment with a durable output sink.`, + }; + } else inferior = { state: verifiedDisposition(detached) }; + } catch (cause: unknown) { + return { + status: "incomplete", + code: + cause instanceof OwnedDebuggerDetachFailure + ? cause.code + : "detach-failed", + reason: `Owned ${debuggerName} inferior detach could not be verified: ${errorMessage(cause)}`, + }; } } session.launched.process.kill("SIGTERM"); @@ -551,10 +601,8 @@ export const stopOwnedDebuggerProcess = async ( session, debuggerName, platform, - unverifiedTerminationReason === undefined - ? "stopped" - : "stopped_inferior_unknown", - unverifiedTerminationReason, + "stopped", + inferior, ); return { status: "incomplete", @@ -566,10 +614,8 @@ export const stopOwnedDebuggerProcess = async ( session, debuggerName, platform, - unverifiedTerminationReason === undefined - ? "stopped" - : "stopped_inferior_unknown", - unverifiedTerminationReason, + "stopped", + inferior, ); }; diff --git a/src/rizin/RizinDebugSessionManager.ts b/src/rizin/RizinDebugSessionManager.ts index f98de1914ac..74d689d9d2e 100644 --- a/src/rizin/RizinDebugSessionManager.ts +++ b/src/rizin/RizinDebugSessionManager.ts @@ -59,6 +59,7 @@ import { RIZIN_DEBUG_SESSION_TOOLS, type DebuggerSessionStop, type DebuggerSessionStopCode, + type InferiorDispositionState, stoppedDebuggerSessionError, unknownDebuggerSessionError, } from "../domain/debuggerSessionErrors.js"; @@ -94,6 +95,8 @@ import { type OwnedInferiorIdentity, OwnedDebuggerDetachFailure, type OwnedDebuggerDetachResult, + type OwnedDebuggerStopResult, + inferiorUnknownReason, } from "../process/ownedDebuggerSession.js"; import { OwnedDebuggerSessionRegistry } from "../process/OwnedDebuggerSessionRegistry.js"; import { absoluteCallerPath } from "../filesystem/callerPath.js"; @@ -133,7 +136,6 @@ interface RizinDebugSession { readonly inferiorTtyInode: number; readonly knownInferiorIdentities: Map; inferiorInventoryComplete: boolean; - inferiorStateUnknown: () => boolean; verifyInferiorsEndedAfterExit: () => Promise; readonly detachInferior: () => Promise; cleanupCommandTurnHeld: boolean; @@ -511,7 +513,6 @@ export class RizinDebugSessionManager { inferiorTtyInode: ttyInode, knownInferiorIdentities: new Map(), inferiorInventoryComplete: false, - inferiorStateUnknown: () => !session.inferiorInventoryComplete, verifyInferiorsEndedAfterExit: async () => { if (!session.inferiorInventoryComplete) return false; const ended = await verifyOwnedInferiorsEnded( @@ -615,7 +616,7 @@ export class RizinDebugSessionManager { // Cancellation stays the reported reason. The session is removed // after the stop, so this is the caller's only record that the // target may still be running. - if (stopped.status === "stopped_inferior_unknown") + if (inferiorUnknownReason(stopped) !== undefined) primary.retainSecondaryFailure( new AnalysisCapabilityUnavailableError( "rizin", @@ -636,7 +637,7 @@ export class RizinDebugSessionManager { primary = new AnalysisCapabilityUnavailableError( "rizin", "start_rizin_debug_session", - stopped.status === "stopped_inferior_unknown" + inferiorUnknownReason(stopped) !== undefined ? `${protocolFailure.reason} ${RIZIN_TERMINATED_WITHOUT_VERIFIED_DETACH_LIMITATION}` : protocolFailure.reason, { @@ -667,7 +668,7 @@ export class RizinDebugSessionManager { ); // The protocol error can race with the startup deadline while stop // waits for the command transport. Preserve that late uncertainty. - if (stopped.status === "stopped_inferior_unknown") + if (inferiorUnknownReason(stopped) !== undefined) primary.retainSecondaryFailure( new AnalysisCapabilityUnavailableError( "rizin", @@ -856,9 +857,8 @@ export class RizinDebugSessionManager { } const captured = received.value; if (signal?.aborted) throw cancelledBy("rizin_debug_command", signal); - let stopped: Awaited> = { - status: "stopped", - }; + // Only a truncated capture stops the session here. + let stopped: OwnedDebuggerStopResult | undefined; let cleanupFailure: string | undefined; if (captured.outputTruncated) { stopped = await this.#stopDebuggerOnly(session, true); @@ -884,7 +884,8 @@ export class RizinDebugSessionManager { captured.outputLimit, acceptedOutput, cleanupFailure, - stopped.status === "stopped_inferior_unknown", + stopped !== undefined && + inferiorUnknownReason(stopped) !== undefined, ), ] : []), @@ -942,7 +943,7 @@ export class RizinDebugSessionManager { const stopped = await this.#stopDebuggerOnly(session, true); const evidence = partialEvidence([ "The Rizin command was cancelled; collected frame output is partial and command completion is unknown.", - stopped.status === "stopped_inferior_unknown" + inferiorUnknownReason(stopped) !== undefined ? RIZIN_TERMINATED_WITHOUT_VERIFIED_DETACH_LIMITATION : "The owned debugger session was stopped because command output can no longer be correlated safely.", "The command is unrestricted and may access local files, the shell, network, or mutate the target.", @@ -977,7 +978,7 @@ export class RizinDebugSessionManager { ? [ `The owned debugger session remains retained because cleanup could not be verified: ${stopped.reason}`, ] - : stopped.status === "stopped_inferior_unknown" + : inferiorUnknownReason(stopped) !== undefined ? [RIZIN_TERMINATED_WITHOUT_VERIFIED_DETACH_LIMITATION] : []), "The command is unrestricted and may access local files, the shell, network, or mutate the target.", @@ -1017,7 +1018,7 @@ export class RizinDebugSessionManager { cleanupFailure: stopped.status === "incomplete" ? stopped.reason : undefined, inferiorDetachUnverified: - stopped.status === "stopped_inferior_unknown", + inferiorUnknownReason(stopped) !== undefined, launchProvenance: session.launchProvenance, launchTarget: session.launchTarget, }); @@ -1046,7 +1047,7 @@ export class RizinDebugSessionManager { ? [ `The owned debugger session remains retained because cleanup could not be verified: ${stopped.reason}`, ] - : stopped.status === "stopped_inferior_unknown" + : inferiorUnknownReason(stopped) !== undefined ? [RIZIN_TERMINATED_WITHOUT_VERIFIED_DETACH_LIMITATION] : []), "The command is unrestricted and may access local files, the shell, network, or mutate the target.", @@ -1074,7 +1075,7 @@ export class RizinDebugSessionManager { ? [ `The owned debugger session remains retained because cleanup could not be verified: ${stopped.reason}`, ] - : stopped.status === "stopped_inferior_unknown" + : inferiorUnknownReason(stopped) !== undefined ? [RIZIN_TERMINATED_WITHOUT_VERIFIED_DETACH_LIMITATION] : []), "The command is unrestricted and may access local files, the shell, network, or mutate the target.", @@ -1179,7 +1180,9 @@ export class RizinDebugSessionManager { async close( sessionId: string, - ): Promise> { + ): Promise< + Result<{ readonly target_state: InferiorDispositionState }, AnalysisError> + > { if (this.#closingAll) return err(new AnalysisInputError("close_rizin_debug_session")); const session = this.#sessions.get(sessionId); @@ -1202,7 +1205,7 @@ export class RizinDebugSessionManager { ), ); this.#sessions.remove(session); - return ok({ target_state: "unknown" }); + return ok({ target_state: stopped.inferior.state }); } async retryCleanupFailures(): Promise> { @@ -1520,7 +1523,7 @@ export class RizinDebugSessionManager { // before readback; only a previously identified process can prove its end. if (!(await verifyOwnedInferiorsEnded([identity]))) throw cause; session.knownInferiorIdentities.clear(); - return { status: "no-inferior" }; + return { status: "inferior-ended" }; } return { status: "detached", outputSink: "durable" }; } @@ -1679,7 +1682,8 @@ export class RizinDebugSessionManager { readonly result: RizinDebugCommandResult; readonly evidence: Evidence; }, - stopped: Awaited>, + /** Undefined when the command completed without stopping the session. */ + stopped: OwnedDebuggerStopResult | undefined, signal?: AbortSignal, ): Result { if (signal?.aborted) { @@ -1705,7 +1709,7 @@ export class RizinDebugSessionManager { ), ); } - if (stopped.status !== "incomplete") return ok(observation); + if (stopped?.status !== "incomplete") return ok(observation); // The retained failure names why the session stopped, as a refusal does. const stop = this.#stopReason(session); return err( @@ -1727,14 +1731,14 @@ export class RizinDebugSessionManager { session: RizinDebugSession, operation: string, primary: AnalysisError, - stopped: Awaited>, + stopped: OwnedDebuggerStopResult | undefined, signal?: AbortSignal, ): AnalysisError { if (signal?.aborted && !(primary instanceof AnalysisCancelledError)) primary.retainSecondaryFailure(cancelledBy(operation, signal), { finalization_cancelled: true, }); - if (stopped.status !== "incomplete") return primary; + if (stopped?.status !== "incomplete") return primary; if (primary instanceof AnalysisCancelledError) return this.#sessions.retainCleanupFailure(session, operation, stopped, { cause: primary, @@ -1761,7 +1765,7 @@ export class RizinDebugSessionManager { readonly commandTurnHeld?: boolean; readonly partialObservation?: Evidence; readonly signal?: AbortSignal | undefined; - readonly stopped?: Awaited>; + readonly stopped?: OwnedDebuggerStopResult; } = {}, ): Promise { const stopped = @@ -1776,7 +1780,7 @@ export class RizinDebugSessionManager { const primary = new AnalysisCapabilityUnavailableError( "rizin", "rizin_debug_command", - stopped.status === "stopped_inferior_unknown" + inferiorUnknownReason(stopped) !== undefined ? `${protocolFailure.reason} ${RIZIN_TERMINATED_WITHOUT_VERIFIED_DETACH_LIMITATION}` : protocolFailure.reason, { ...errorOptions, diagnostics: { session_stop: protocolFailure.code } }, diff --git a/tests/boundary/cli/gdbStartupCleanupCli.test.ts b/tests/boundary/cli/gdbStartupCleanupCli.test.ts index ee2a9bdad45..949dc523c57 100644 --- a/tests/boundary/cli/gdbStartupCleanupCli.test.ts +++ b/tests/boundary/cli/gdbStartupCleanupCli.test.ts @@ -255,7 +255,7 @@ it.each(["incomplete", "interrupt", "control"] as const)( reason: "synthetic stop remains pending", }; child.kill("SIGTERM"); - return { status: "stopped" }; + return { status: "stopped", inferior: { state: "none_observed" } }; }, }); const originalStart = manager.start.bind(manager); diff --git a/tests/boundary/mcp/debuggerExternalMutationLifecycleMcp.test.ts b/tests/boundary/mcp/debuggerExternalMutationLifecycleMcp.test.ts index 700ca3b70f9..2894b655ce0 100644 --- a/tests/boundary/mcp/debuggerExternalMutationLifecycleMcp.test.ts +++ b/tests/boundary/mcp/debuggerExternalMutationLifecycleMcp.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it, onTestFinished, vi } from "vitest"; import { AnalysisOutputError } from "../../../src/domain/analysisErrorCore.js"; import type { AnalysisError } from "../../../src/domain/analysisErrorBase.js"; +import type { InferiorDispositionState } from "../../../src/domain/debuggerSessionErrors.js"; import { createEvidence, type Evidence } from "../../../src/domain/evidence.js"; import type { JsonValue } from "../../../src/domain/jsonValue.js"; import { err, ok, type Result } from "../../../src/domain/result.js"; @@ -37,7 +38,7 @@ interface Operations { readonly start: () => Promise>; readonly execute: () => Promise>; readonly close: () => Promise< - Result<{ readonly target_state: "unknown" }, AnalysisError> + Result<{ readonly target_state: InferiorDispositionState }, AnalysisError> >; readonly retryCleanup: () => Promise>; } @@ -412,13 +413,28 @@ describe.each([RIZIN, GDB, CUTTER])( const retryCleanup = vi.fn(async () => err(detach.error), ); - const { client } = await connect({ close, retryCleanup }); + const execute = vi.fn(async () => + ok(debuggerTools.evidence()), + ); + const { client } = await connect({ close, retryCleanup, execute }); expect((await client.callTool(closeCall)).isError).toBe(true); // Another command is refused while the failed close stays owned. const command = await client.callTool(debuggerTools.command); - expect(command.isError).toBe(true); + // The refusal is the retained close blocker, not another failure. + expect(parseMcpToolError(command)).toMatchObject({ + error: { + code: "cleanup_incomplete", + details: { + operation: closeCall.name, + cleanup: "incomplete", + resources: [SESSION_ID], + cleanup_reason: "fixture detach failed", + }, + }, + }); expect(retryCleanup).toHaveBeenCalledOnce(); + expect(execute).not.toHaveBeenCalled(); const retried = await client.callTool(closeCall); expect(retried.isError ?? false, JSON.stringify(retried)).toBe(false); diff --git a/tests/boundary/mcp/rizinStoppedSessionMcp.test.ts b/tests/boundary/mcp/rizinStoppedSessionMcp.test.ts index 2d48b869822..209b55de2e3 100644 --- a/tests/boundary/mcp/rizinStoppedSessionMcp.test.ts +++ b/tests/boundary/mcp/rizinStoppedSessionMcp.test.ts @@ -58,10 +58,14 @@ test.each([ code: "stop-failed", reason: "injected stop pending", }; - if (session.exited) return { status: "already_exited" }; + if (session.exited) + return { + status: "already_exited", + inferior: { state: "none_observed" }, + }; await session.detachInferior?.(); injected.control.exit(); - return { status: "stopped" }; + return { status: "stopped", inferior: { state: "none_observed" } }; }, }, ); diff --git a/tests/boundary/process/ownedDebuggerSession.test.ts b/tests/boundary/process/ownedDebuggerSession.test.ts index 89fc2c84053..25295c4e60b 100644 --- a/tests/boundary/process/ownedDebuggerSession.test.ts +++ b/tests/boundary/process/ownedDebuggerSession.test.ts @@ -118,7 +118,10 @@ it("preserves the session receiver when invoking the provider detach callback", await expect( stopOwnedDebuggerProcess(session, "GDB", { platform: "linux" }), - ).resolves.toEqual({ status: "stopped" }); + ).resolves.toEqual({ + status: "stopped", + inferior: { state: "none_observed" }, + }); expect(session.supervisor.limitAdditionalOutputBytes).toHaveBeenCalledWith( 64 * 1024, ); @@ -137,7 +140,10 @@ it("clears the detach timeout when provider detachment settles immediately", asy await expect( stopOwnedDebuggerProcess(session, "GDB", { platform: "linux" }), - ).resolves.toEqual({ status: "stopped" }); + ).resolves.toEqual({ + status: "stopped", + inferior: { state: "none_observed" }, + }); expect(vi.getTimerCount()).toBe(0); } finally { vi.useRealTimers(); @@ -162,7 +168,10 @@ it("retries provider detachment after a rejected attempt", async () => { ).resolves.toMatchObject({ status: "incomplete" }); await expect( stopOwnedDebuggerProcess(session, "GDB", { platform: "linux" }), - ).resolves.toEqual({ status: "stopped" }); + ).resolves.toEqual({ + status: "stopped", + inferior: { state: "none_observed" }, + }); expect(detachInferior).toHaveBeenCalledTimes(2); }); @@ -199,7 +208,10 @@ it("retains ownership after stop until inherited output writers close", async () outputClosed = true; await expect( stopOwnedDebuggerProcess(session, "GDB", { platform: "linux" }), - ).resolves.toEqual({ status: "already_exited" }); + ).resolves.toEqual({ + status: "already_exited", + inferior: { state: "none_observed" }, + }); expect(supervisor.unrefOutputStreams).toHaveBeenCalledOnce(); expect(supervisor.dispose).toHaveBeenCalledOnce(); }); @@ -263,7 +275,7 @@ it("retains process supervision after an incomplete stop and disposes after a re const retry = await stopOwnedDebuggerProcess(session, "GDB", { platform: "linux", }); - expect(retry).toEqual({ status: "stopped" }); + expect(retry).toEqual({ status: "stopped", inferior: { state: "detached" } }); expect(disposals).toBe(1); expect(waits).toBe(3); expect(detachInferior).toHaveBeenCalledOnce(); @@ -314,6 +326,7 @@ it("retains an already-exited Windows session while its job has descendants", as { id: "windows-already-exited", exited: true, + verifiedInferior: () => "none_observed" as const, launched: { process: { kill: () => true } }, supervisor: { waitForExit: async () => false, @@ -349,6 +362,7 @@ it("retains an exited POSIX session while descendants still hold its output stre { id: "posix-already-exited-with-descendant", exited: true, + verifiedInferior: () => "none_observed" as const, launched: { process: { kill: () => true } }, supervisor: { waitForExit: async () => true, @@ -410,6 +424,7 @@ it.each([ { id: "output-settlement-error", exited: true, + verifiedInferior: () => "none_observed" as const, launched: { process: { kill: () => true } }, supervisor: { waitForExit: async () => true, @@ -545,8 +560,11 @@ it("terminates the owned debugger when the provider declares detach unavailable" ); expect(result).toEqual({ - status: "stopped_inferior_unknown", - reason: "Rizin did not resynchronize cleanup within 500 ms", + status: "stopped", + inferior: { + state: "unknown", + reason: "Rizin did not resynchronize cleanup within 500 ms", + }, }); expect(signals).toEqual(["SIGTERM"]); expect(supervisor.dispose).toHaveBeenCalledOnce(); @@ -578,8 +596,8 @@ it("escalates an unavailable-detach termination that ignores SIGTERM", async () ); expect(result).toEqual({ - status: "stopped_inferior_unknown", - reason: "transport desynchronized", + status: "stopped", + inferior: { state: "unknown", reason: "transport desynchronized" }, }); expect(signals).toEqual(["SIGTERM", "SIGKILL"]); }); @@ -610,8 +628,8 @@ it("retains an unavailable-detach session until its output streams settle", asyn await expect( stopOwnedDebuggerProcess(session, "Rizin", { platform: "linux" }), ).resolves.toEqual({ - status: "stopped_inferior_unknown", - reason: "transport desynchronized", + status: "stopped", + inferior: { state: "unknown", reason: "transport desynchronized" }, }); }); @@ -623,7 +641,6 @@ it("skips inferior-ended proof for a recorded unavailable detach after exit", as get exited() { return exited; }, - inferiorStateUnknown: () => true, verifyInferiorsEndedAfterExit: async () => { inferiorProofs += 1; return false; @@ -649,8 +666,8 @@ it("skips inferior-ended proof for a recorded unavailable detach after exit", as await expect( stopOwnedDebuggerProcess(session, "Rizin", { platform: "linux" }), ).resolves.toEqual({ - status: "stopped_inferior_unknown", - reason: "transport desynchronized", + status: "already_exited", + inferior: { state: "unknown", reason: "transport desynchronized" }, }); expect(inferiorProofs).toBe(0); }); @@ -763,6 +780,44 @@ it("preserves unknown identity reads and rejects empty proof", async () => { expect(read).not.toHaveBeenCalled(); }); +it.each([ + [{ status: "no-inferior" } as const, "none_observed"], + [{ status: "detached", outputSink: "durable" } as const, "detached"], + [{ status: "inferior-ended" } as const, "exited"], +])( + "reports the inferior state the provider's detach observed (%j)", + async (detachResult, state) => { + const session = { + id: `detach-${detachResult.status}`, + exited: false, + launched: { process: { kill: () => true } }, + detachInferior: async () => detachResult, + supervisor: createFakeSupervisor(), + }; + await expect( + stopOwnedDebuggerProcess(session, "GDB", { platform: "linux" }), + ).resolves.toEqual({ status: "stopped", inferior: { state } }); + }, +); + +it("keeps a provider-verified detach when the debugger exits before owned cleanup", async () => { + const session = { + id: "detached-then-exited", + exited: true, + verifiedInferior: () => "detached" as const, + verifyInferiorsEndedAfterExit: vi.fn(async () => false), + launched: { process: { kill: () => true } }, + supervisor: createFakeSupervisor(), + }; + await expect( + stopOwnedDebuggerProcess(session, "GDB", { platform: "linux" }), + ).resolves.toEqual({ + status: "already_exited", + inferior: { state: "detached" }, + }); + expect(session.verifyInferiorsEndedAfterExit).not.toHaveBeenCalled(); +}); + it("allows closing when the provider confirms no inferior is attached", async () => { const signals: NodeJS.Signals[] = []; const result = await stopOwnedDebuggerProcess( @@ -783,7 +838,10 @@ it("allows closing when the provider confirms no inferior is attached", async () { platform: "linux" }, ); - expect(result).toEqual({ status: "stopped" }); + expect(result).toEqual({ + status: "stopped", + inferior: { state: "none_observed" }, + }); expect(signals).toEqual(["SIGTERM"]); }); @@ -885,7 +943,7 @@ it("retains an owned debugger when inferior detach does not settle", async () => await vi.advanceTimersByTimeAsync(0); expect( await stopOwnedDebuggerProcess(session, "GDB", { platform: "linux" }), - ).toEqual({ status: "stopped" }); + ).toEqual({ status: "stopped", inferior: { state: "detached" } }); expect(detachCalls).toBe(1); expect(signals).toEqual(["SIGTERM"]); expect(disposals).toBe(1); @@ -968,6 +1026,7 @@ it("requires the Windows Job Object to close before releasing an exited session" const session = { id: "windows-job-settlement", exited: true, + verifiedInferior: () => "none_observed" as const, launched: { process: { kill: () => true } }, supervisor: { waitForExit: async () => true, @@ -986,7 +1045,7 @@ it("requires the Windows Job Object to close before releasing an exited session" expect(disposals).toBe(0); expect( await stopOwnedDebuggerProcess(session, "GDB", { platform: "win32" }), - ).toEqual({ status: "already_exited" }); + ).toEqual({ status: "already_exited", inferior: { state: "none_observed" } }); expect(closeWaits).toBe(2); expect(disposals).toBe(1); }); @@ -999,6 +1058,7 @@ it("disposes supervision when a process had already exited", async () => { { id: "already-exited", exited: true, + verifiedInferior: () => "none_observed" as const, launched: { process: { kill: () => true } }, supervisor: { waitForExit: async () => false, @@ -1018,7 +1078,10 @@ it("disposes supervision when a process had already exited", async () => { { platform: "linux" }, ); - expect(result).toEqual({ status: "already_exited" }); + expect(result).toEqual({ + status: "already_exited", + inferior: { state: "none_observed" }, + }); expect(disposals).toBe(1); expect(outputUnrefs).toBe(1); expect(lifecycle).toEqual(["unref", "dispose"]); @@ -1031,6 +1094,7 @@ it("uses the host platform when an exited debugger is stopped without options", { id: "already-exited-default-platform", exited: true, + verifiedInferior: () => "none_observed" as const, launched: { process: { kill: () => true } }, supervisor: { waitForExit: async () => true, @@ -1049,7 +1113,10 @@ it("uses the host platform when an exited debugger is stopped without options", "GDB", ); - expect(result).toEqual({ status: "already_exited" }); + expect(result).toEqual({ + status: "already_exited", + inferior: { state: "none_observed" }, + }); expect(outputCloseWaits).toBe(1); expect(outputUnrefs).toBe(process.platform === "win32" ? 0 : 1); }); @@ -1087,6 +1154,7 @@ it.skipIf(process.platform === "win32")( { id: "leader-exited-with-inferior", exited: true, + verifiedInferior: () => "none_observed" as const, launched: { process: child }, supervisor, }, @@ -1094,7 +1162,10 @@ it.skipIf(process.platform === "win32")( { platform: "linux" }, ); - expect(result).toEqual({ status: "already_exited" }); + expect(result).toEqual({ + status: "already_exited", + inferior: { state: "none_observed" }, + }); expect(supervisor.snapshot().stdout.text).toContain( "late-stdout-sentinel", ); @@ -1132,6 +1203,7 @@ it.skipIf(process.platform === "win32")( const session = { id: "leader-exited-retrying-inferior", exited: true, + verifiedInferior: () => "none_observed" as const, launched: { process: child }, supervisor, }; @@ -1161,7 +1233,10 @@ it.skipIf(process.platform === "win32")( const second = await stopOwnedDebuggerProcess(session, "GDB", { platform: "linux", }); - expect(second).toEqual({ status: "already_exited" }); + expect(second).toEqual({ + status: "already_exited", + inferior: { state: "none_observed" }, + }); const snapshot = supervisor.snapshot(); expect(snapshot.stdout.observedBytes).toBe( initialStdoutBytes + 80 * 1024, @@ -1219,7 +1294,10 @@ it("does not escalate when the debugger exits after SIGTERM", async () => { { platform: "linux" }, ); - expect(result).toEqual({ status: "stopped" }); + expect(result).toEqual({ + status: "stopped", + inferior: { state: "detached" }, + }); expect(signals).toEqual(["SIGTERM"]); expect(disposals).toBe(1); expect(lifecycle).toEqual(["unref", "dispose"]); @@ -1265,7 +1343,10 @@ it("disposes supervision when the debugger exits after SIGKILL", async () => { { platform: "linux" }, ); - expect(result).toEqual({ status: "stopped" }); + expect(result).toEqual({ + status: "stopped", + inferior: { state: "detached" }, + }); expect(signals).toEqual(["SIGTERM", "SIGKILL"]); expect(disposals).toBe(1); expect(lifecycle).toEqual(["unref", "dispose"]); @@ -1340,7 +1421,7 @@ it.skipIf(process.platform === "win32")( expect(probe.exitCode, stopProbe.output).toBe(0); await waitFor(() => expect(stopProbe.output).toContain( - '{"retried":{"status":"already_exited"}}\n', + '{"retried":{"status":"already_exited","inferior":{"state":"none_observed"}}}\n', ), ); }, @@ -1400,7 +1481,9 @@ it.skipIf(process.platform === "win32")( ); expect(probe.exitCode, stopProbe.output).toBe(0); await waitFor(() => - expect(stopProbe.output).toContain('probe-result={"status":"stopped"}'), + expect(stopProbe.output).toContain( + 'probe-result={"status":"stopped","inferior":{"state":"detached"}}', + ), ); expect(terminalExited).toBe(false); @@ -1429,7 +1512,7 @@ it("removes stopped sessions and retains incomplete sessions when closing all", code: "stop-failed", reason: "process remains alive", } - : { status: "stopped" }, + : { status: "stopped", inferior: { state: "none_observed" } }, "GDB", ), ).rejects.toMatchObject({ @@ -1447,8 +1530,8 @@ it("does not remove a replacement session installed under the same key while sto const original = closableSession("shared-key"); const replacement = closableSession("shared-key"); const sessions = new Map([["shared-key", original]]); - let finishStop!: (result: { readonly status: "stopped" }) => void; - const stopping = new Promise<{ readonly status: "stopped" }>((resolve) => { + let finishStop!: (result: OwnedDebuggerStopResult) => void; + const stopping = new Promise((resolve) => { finishStop = resolve; }); @@ -1459,7 +1542,7 @@ it("does not remove a replacement session installed under the same key while sto ); await Promise.resolve(); sessions.set("shared-key", replacement); - finishStop({ status: "stopped" }); + finishStop({ status: "stopped", inferior: { state: "none_observed" } }); await closing; expect(sessions.get("shared-key")).toBe(replacement); @@ -1470,7 +1553,7 @@ it("closes an empty owned-session collection", async () => { await expect( closeOwnedDebuggerSessions( sessions, - async () => ({ status: "stopped" }), + async () => ({ status: "stopped", inferior: { state: "none_observed" } }), "GDB", ), ).resolves.toBeUndefined(); @@ -1498,7 +1581,7 @@ it("settles every stop and retains rejected sessions while removing successful o code: "stop-failed", reason: "still alive", }; - return { status: "stopped" }; + return { status: "stopped", inferior: { state: "none_observed" } }; }, "GDB", ), @@ -1534,7 +1617,8 @@ it("stops retained sessions holding the host and names them, leaving stopped pee const failure: unknown = await closeOwnedDebuggerSessions( sessions, async (session) => { - if (session === stopped) return { status: "stopped" }; + if (session === stopped) + return { status: "stopped", inferior: { state: "none_observed" } }; if (session === rejected) throw new Error("signal failed"); return { status: "incomplete", @@ -1582,7 +1666,7 @@ it("holds the host again while retrying a retained session and leaves it held on expect(order).toEqual(["ref", "stop", "unref"]); order.length = 0; - stopResult = { status: "stopped" }; + stopResult = { status: "stopped", inferior: { state: "none_observed" } }; await closeOwnedDebuggerSessions(sessions, stop, "GDB"); expect(order).toEqual(["ref", "stop"]); expect(sessions.size).toBe(0); diff --git a/tests/boundary/providers/GdbSessionManagerCoverage.test.ts b/tests/boundary/providers/GdbSessionManagerCoverage.test.ts index f7b67c70a34..269a07b320c 100644 --- a/tests/boundary/providers/GdbSessionManagerCoverage.test.ts +++ b/tests/boundary/providers/GdbSessionManagerCoverage.test.ts @@ -399,7 +399,7 @@ it("keeps a consumed startup failure primary when caller abort arrives during cl const manager = managerWithFakeSpawner(fake.spawnProcess, { stopProcess: async () => { controller.abort(reason); - return { status: "stopped" }; + return { status: "stopped", inferior: { state: "none_observed" } }; }, }); @@ -643,7 +643,7 @@ it("rejects GDB commands queued before closeAll when their turn arrives", async const manager = managerWithFakeSpawner(fake.spawnProcess, { stopProcess: async () => { fake.children[0]?.exit(null, "SIGTERM"); - return { status: "stopped" }; + return { status: "stopped", inferior: { state: "none_observed" } }; }, }); const started = await expectGdbSessionStarted(manager); @@ -680,7 +680,10 @@ it("rejects GDB commands queued behind a session close", async () => { }); const manager = managerWithFakeSpawner(fake.spawnProcess, { // The child exit event can arrive after stop reports success. - stopProcess: async () => ({ status: "stopped" }), + stopProcess: async () => ({ + status: "stopped", + inferior: { state: "none_observed" }, + }), }); const started = await expectGdbSessionStarted(manager); const active = manager.execute(started.value.session_id, "held command"); @@ -732,7 +735,7 @@ it.each(["close", "retryCleanupFailures"] as const)( reason: "simulated cleanup uncertainty", }; } - return { status: "stopped" }; + return { status: "stopped", inferior: { state: "none_observed" } }; }, }); const started = await expectGdbSessionStarted(manager); @@ -826,7 +829,7 @@ it.each([ stopProcess: async () => { stopCalls += 1; return remainingInferiors.size === 0 - ? { status: "stopped" } + ? { status: "stopped", inferior: { state: "none_observed" } } : { status: "incomplete", code: "stop-failed", @@ -890,7 +893,7 @@ it("rejects a duplicate GDB close queued behind a session close", async () => { const manager = managerWithFakeSpawner(fake.spawnProcess, { stopProcess: async () => { stopCalls += 1; - return { status: "stopped" }; + return { status: "stopped", inferior: { state: "none_observed" } }; }, }); const started = await expectGdbSessionStarted(manager); @@ -1010,7 +1013,7 @@ it("reports process exit rather than protocol failure when stdin closes afterwar const manager = managerWithFakeSpawner(fake.spawnProcess, { stopProcess: async () => { stopCalls += 1; - return { status: "stopped" }; + return { status: "stopped", inferior: { state: "none_observed" } }; }, }); const started = await expectGdbSessionStarted(manager); @@ -2134,7 +2137,10 @@ it("keeps the stop code on a startup stream failure whose cleanup is incomplete" it("preserves the protocol failure when owned-process stop is confirmed", async () => { const fake = createFakeSpawner(); const manager = managerWithFakeSpawner(fake.spawnProcess, { - stopProcess: async () => ({ status: "stopped" }), + stopProcess: async () => ({ + status: "stopped", + inferior: { state: "none_observed" }, + }), }); const started = await expectGdbSessionStarted(manager); const stdin = fake.children[0]?.stdin; @@ -2163,7 +2169,10 @@ it("converts a closed stdin guard failure without partial MI records", async () Object.defineProperty(child.stdin, "destroyed", { value: true }); }); const manager = managerWithFakeSpawner(fake.spawnProcess, { - stopProcess: async () => ({ status: "stopped" }), + stopProcess: async () => ({ + status: "stopped", + inferior: { state: "none_observed" }, + }), }); const started = await expectGdbSessionStarted(manager); expect(fake.children[0]?.stdin?.destroyed).toBe(true); @@ -2463,7 +2472,10 @@ it("retains unknown completion and partial Evidence when the completion query fa else child.stdout.write(`${token}^done\n`); }); const manager = managerWithFakeSpawner(fake.spawnProcess, { - stopProcess: async () => ({ status: "stopped" }), + stopProcess: async () => ({ + status: "stopped", + inferior: { state: "none_observed" }, + }), }); const started = await expectGdbSessionStarted(manager); const result = await manager.execute( @@ -2624,7 +2636,7 @@ it.each([false, true])( expect(closed).toMatchObject({ ok: true, - value: { target_state: "unknown" }, + value: { target_state: "detached" }, }); expect( commands.filter((command) => command.includes("list-thread-groups")), @@ -2808,7 +2820,7 @@ it.each([ manager.close(started.value.session_id), ).resolves.toMatchObject({ ok: true, - value: { target_state: "unknown" }, + value: { target_state: "exited" }, }); expect(manager.status(started.value.session_id)).toBeUndefined(); } finally { @@ -2877,7 +2889,7 @@ it("keeps the verified sink across the read-only show inferior-tty inspection", expect(closed).toMatchObject({ ok: true, - value: { target_state: "unknown" }, + value: { target_state: "detached" }, }); expect(commands).toContain("-target-detach"); expect(fake.children[0]?.killSignals).toEqual(["SIGTERM"]); @@ -3438,7 +3450,10 @@ it.each(["tagged", "unexpected"] as const)( stopProcess: () => { if (recovered) { fake.children[0]?.exit(0, null); - return Promise.resolve({ status: "stopped" }); + return Promise.resolve({ + status: "stopped", + inferior: { state: "none_observed" }, + }); } // Include synchronous throws at this injected provider boundary. throw failureKind === "tagged" @@ -3479,7 +3494,10 @@ it("returns partial command evidence when the active MI request times out after }); const manager = managerWithFakeSpawner(fake.spawnProcess, { environment: { REA_DEBUGGER_COMMAND_DEADLINE_MS: "20" }, - stopProcess: async () => ({ status: "stopped" }), + stopProcess: async () => ({ + status: "stopped", + inferior: { state: "none_observed" }, + }), }); const started = await expectGdbSessionStarted(manager); @@ -3508,7 +3526,10 @@ it("preserves cancellation without cleanup details when stop is confirmed", asyn else _child.stdout.write(`${token}^done\n`); }); const manager = managerWithFakeSpawner(fake.spawnProcess, { - stopProcess: async () => ({ status: "stopped" }), + stopProcess: async () => ({ + status: "stopped", + inferior: { state: "none_observed" }, + }), }); const started = await expectGdbSessionStarted(manager); @@ -3553,7 +3574,10 @@ it("rechecks cancellation after registering the active MI request listener", asy child.stdout.write(`${token}^done\n`); }); const manager = managerWithFakeSpawner(fake.spawnProcess, { - stopProcess: async () => ({ status: "stopped" }), + stopProcess: async () => ({ + status: "stopped", + inferior: { state: "none_observed" }, + }), }); const started = await expectGdbSessionStarted(manager); @@ -3751,7 +3775,7 @@ it.each([false, true])( const manager = managerWithFakeSpawner(fake.spawnProcess, { stopProcess: async () => { for (const child of fake.children) child.exit(0, null); - return { status: "stopped" }; + return { status: "stopped", inferior: { state: "none_observed" } }; }, }); const started = await expectGdbSessionStarted(manager); @@ -3809,7 +3833,7 @@ it.each(["literal", "octal", "invalid-result", "invalid-stream"] as const)( const manager = managerWithFakeSpawner(fake.spawnProcess, { stopProcess: async () => { for (const child of fake.children) child.exit(0, null); - return { status: "stopped" }; + return { status: "stopped", inferior: { state: "none_observed" } }; }, }); const started = await manager.start(undefined, { inferiorTty: tty }); @@ -4078,10 +4102,14 @@ it.each(["incomplete", "rejected"] as const)( if (stopCalls === 3) { // Simulate later owner verification after recovery completed. fake.children[0]?.exit(0, null); - return { status: "stopped" }; + return { status: "stopped", inferior: { state: "none_observed" } }; } // That simulated verification stands for later stops of the session. - if (stopCalls > 3) return { status: "already_exited" }; + if (stopCalls > 3) + return { + status: "already_exited", + inferior: { state: "none_observed" }, + }; return stopOwnedDebuggerProcess(session, name); }, }); diff --git a/tests/boundary/providers/GdbSessionManagers.test.ts b/tests/boundary/providers/GdbSessionManagers.test.ts index 71afcfc6ccc..e1de526691b 100644 --- a/tests/boundary/providers/GdbSessionManagers.test.ts +++ b/tests/boundary/providers/GdbSessionManagers.test.ts @@ -88,9 +88,13 @@ describe("persistent debugger session managers", () => { version: FAKE_GDB_VERSION, }); + const [owned] = fixtureOwner.ownedProcesses(); + expect(owned?.observedExit()).toBeUndefined(); const closed = await manager.close(started.value.session_id); expect(closed.ok).toBe(true); expect(manager.status(started.value.session_id)).toBeUndefined(); + // The close itself stopped GDB, before the fixture owner's cleanup. + expect(owned?.observedExit()).toBeDefined(); }); it("recovers GDB commands after either runtime cap is reset to an invalid seed", async () => { diff --git a/tests/boundary/providers/GdbSessionReviewRegressions.test.ts b/tests/boundary/providers/GdbSessionReviewRegressions.test.ts index 65ee5adc5d6..4dc75b463a3 100644 --- a/tests/boundary/providers/GdbSessionReviewRegressions.test.ts +++ b/tests/boundary/providers/GdbSessionReviewRegressions.test.ts @@ -202,7 +202,7 @@ process.stdin.on("data", (chunk) => { stopProcess: async (session) => { detachChecked = true; await session.detachInferior?.(); - return { status: "stopped" }; + return { status: "stopped", inferior: { state: "none_observed" } }; }, }); managers.push(manager); diff --git a/tests/boundary/providers/RizinDebugSessionCoverage.part1.test.ts b/tests/boundary/providers/RizinDebugSessionCoverage.part1.test.ts index 55faf1bfa08..6965801bf19 100644 --- a/tests/boundary/providers/RizinDebugSessionCoverage.part1.test.ts +++ b/tests/boundary/providers/RizinDebugSessionCoverage.part1.test.ts @@ -113,7 +113,10 @@ it.skipIf(process.platform === "win32")( { REA_RIZIN_COMMAND: "injected-rizin" }, { spawnProcess: injected.spawnProcess, - stopProcess: async () => ({ status: "stopped" }), + stopProcess: async () => ({ + status: "stopped", + inferior: { state: "none_observed" }, + }), }, ); @@ -159,7 +162,7 @@ it.skipIf(process.platform === "win32")( }, stopProcess: async () => { stopCount += 1; - return { status: "stopped" }; + return { status: "stopped", inferior: { state: "none_observed" } }; }, }, ); @@ -284,7 +287,10 @@ it code: "stop-failed", reason: "injected stop uncertainty", }) - : async () => ({ status: "stopped" }); + : async () => ({ + status: "stopped", + inferior: { state: "none_observed" }, + }); const manager = createManager( { REA_RIZIN_COMMAND: provider }, { stopProcess }, diff --git a/tests/boundary/providers/RizinDebugSessionCoverage.part2.test.ts b/tests/boundary/providers/RizinDebugSessionCoverage.part2.test.ts index 9d32797eefe..c1ecad45b88 100644 --- a/tests/boundary/providers/RizinDebugSessionCoverage.part2.test.ts +++ b/tests/boundary/providers/RizinDebugSessionCoverage.part2.test.ts @@ -94,7 +94,10 @@ it.skipIf(process.platform === "win32").each([false, true])( const { manager, started } = await startInjected(injected.spawnProcess, { stopProcess: incomplete ? incompleteStop - : async () => ({ status: "stopped" }), + : async () => ({ + status: "stopped", + inferior: { state: "none_observed" }, + }), }); if (!started.ok) throw started.error; const sessionId = started.value.session_id; diff --git a/tests/boundary/providers/RizinDebugSessionCoverage.part3.test.ts b/tests/boundary/providers/RizinDebugSessionCoverage.part3.test.ts index 1db7cc9df25..4a8204dbd0b 100644 --- a/tests/boundary/providers/RizinDebugSessionCoverage.part3.test.ts +++ b/tests/boundary/providers/RizinDebugSessionCoverage.part3.test.ts @@ -26,7 +26,12 @@ it.skipIf(process.platform === "win32")( const injected = createInjectedProcess(); const { manager, started } = await startInjected( injected.spawnProcess, - { stopProcess: async () => ({ status: "stopped" }) }, + { + stopProcess: async () => ({ + status: "stopped", + inferior: { state: "none_observed" }, + }), + }, { REA_DEBUGGER_COMMAND_DEADLINE_MS: "10" }, ); if (!started.ok) throw started.error; @@ -77,7 +82,10 @@ it.skipIf(process.platform === "win32")( const { manager, started } = await startInjected( injected.spawnProcess, { - stopProcess: async () => ({ status: "stopped" }), + stopProcess: async () => ({ + status: "stopped", + inferior: { state: "none_observed" }, + }), }, { REA_DEBUGGER_COMMAND_DEADLINE_MS: "1000" }, ); @@ -151,7 +159,10 @@ it.skipIf(process.platform === "win32")( const { manager, started } = await startInjected( injected.spawnProcess, { - stopProcess: async () => ({ status: "stopped" }), + stopProcess: async () => ({ + status: "stopped", + inferior: { state: "none_observed" }, + }), }, { REA_DEBUGGER_COMMAND_DEADLINE_MS: "100" }, ); @@ -303,7 +314,10 @@ it.skipIf(process.platform === "win32")( }, }); const { manager, started } = await startInjected(injected.spawnProcess, { - stopProcess: async () => ({ status: "stopped" }), + stopProcess: async () => ({ + status: "stopped", + inferior: { state: "none_observed" }, + }), }); if (!started.ok) throw started.error; const signal = abortOnCheck(5, reason); @@ -333,7 +347,10 @@ it.skipIf(process.platform === "win32")( async () => { const injected = createInjectedProcess(); const { manager, started } = await startInjected(injected.spawnProcess, { - stopProcess: async () => ({ status: "stopped" }), + stopProcess: async () => ({ + status: "stopped", + inferior: { state: "none_observed" }, + }), }); if (!started.ok) throw started.error; const reason = { stage: "frame waiter installation" }; @@ -376,7 +393,7 @@ it.skipIf(process.platform === "win32").each([false, true])( code: "stop-failed", reason: "injected stop uncertainty", } - : { status: "stopped" }, + : { status: "stopped", inferior: { state: "none_observed" } }, }, { REA_DEBUGGER_COMMAND_DEADLINE_MS: "1000" }, ); @@ -530,7 +547,7 @@ it code: "stop-failed", reason: "owned stop pending", } - : { status: "stopped" }, + : { status: "stopped", inferior: { state: "none_observed" } }, }); if (!started.ok) throw started.error; const result = await manager.execute( @@ -574,11 +591,15 @@ it.skipIf(process.platform === "win32")( // The injected stream has no OS process identity. Exercise protocol detach // here; real debugger process ownership is covered by process boundaries. stopProcess: async (session) => { - if (session.exited) return { status: "already_exited" }; + if (session.exited) + return { + status: "already_exited", + inferior: { state: "none_observed" }, + }; try { await session.detachInferior?.(); injected.control.exit(); - return { status: "stopped" }; + return { status: "stopped", inferior: { state: "none_observed" } }; } catch (cause) { return { status: "incomplete", @@ -707,7 +728,7 @@ it.skipIf(process.platform === "win32").each([ code: "stop-failed", reason: "stop settlement pending", } - : { status: "stopped" }; + : { status: "stopped", inferior: { state: "none_observed" } }; }, }, { @@ -775,7 +796,7 @@ it.skipIf(process.platform === "win32")( try { await session.detachInferior?.(); injected.control.exit(); - return { status: "stopped" }; + return { status: "stopped", inferior: { state: "none_observed" } }; } catch (cause) { return { status: "incomplete", @@ -794,7 +815,7 @@ it.skipIf(process.platform === "win32")( expect(Buffer.byteLength(cleanupReadback, "utf8")).toBeGreaterThan(8); const closed = await manager.close(started.value.session_id); if (!closed.ok) throw closed.error; - expect(closed.value).toEqual({ target_state: "unknown" }); + expect(closed.value).toEqual({ target_state: "none_observed" }); }, ); @@ -845,7 +866,7 @@ it.skipIf(process.platform === "win32").each([false, true])( code: "stop-failed", reason: "stop settlement pending", } - : { status: "stopped" }; + : { status: "stopped", inferior: { state: "none_observed" } }; }, }, ); diff --git a/tests/boundary/providers/RizinDebugSessionCoverage.part4.test.ts b/tests/boundary/providers/RizinDebugSessionCoverage.part4.test.ts index cc06fcade01..ba11a5dae78 100644 --- a/tests/boundary/providers/RizinDebugSessionCoverage.part4.test.ts +++ b/tests/boundary/providers/RizinDebugSessionCoverage.part4.test.ts @@ -68,7 +68,10 @@ it.skipIf(process.platform === "win32")( const { manager, started } = await startInjected( injected.spawnProcess, { - stopProcess: async () => ({ status: "stopped" }), + stopProcess: async () => ({ + status: "stopped", + inferior: { state: "none_observed" }, + }), }, { REA_DEBUGGER_COMMAND_DEADLINE_MS: "1000" }, ); diff --git a/tests/boundary/providers/RizinDebugSessionInferiorStdin.test.ts b/tests/boundary/providers/RizinDebugSessionInferiorStdin.test.ts index 960f2e9b14b..1b320c84e41 100644 --- a/tests/boundary/providers/RizinDebugSessionInferiorStdin.test.ts +++ b/tests/boundary/providers/RizinDebugSessionInferiorStdin.test.ts @@ -363,7 +363,9 @@ linuxIt.each([ }); expect(closed.isError, JSON.stringify(closed)).not.toBe(true); - expect(closed.structuredContent).toEqual({ target_state: "unknown" }); + expect(closed.structuredContent).toEqual({ + target_state: staysRunning ? "detached" : "exited", + }); expect(manager.status(sessionId)).toBeUndefined(); expect(await current.commands()).toEqual(DETACH_COMMANDS); expect(current.terminal.output()).not.toContain("__REA_"); diff --git a/tests/boundary/providers/RizinTestInferiorTty.ts b/tests/boundary/providers/RizinTestInferiorTty.ts index 82d33260e9f..e7193ce1f7b 100644 --- a/tests/boundary/providers/RizinTestInferiorTty.ts +++ b/tests/boundary/providers/RizinTestInferiorTty.ts @@ -62,7 +62,7 @@ export const stopFakeNoInferior = async ( stopOwnedDebuggerProcess( { ...session, - inferiorStateUnknown: () => false, + verifiedInferior: () => "none_observed" as const, detachInferior: async () => ({ status: "no-inferior" }), }, debuggerName, diff --git a/tests/boundary/providers/RizinTtyCleanup.test.ts b/tests/boundary/providers/RizinTtyCleanup.test.ts index 9e227f4a23f..20eeabb0487 100644 --- a/tests/boundary/providers/RizinTtyCleanup.test.ts +++ b/tests/boundary/providers/RizinTtyCleanup.test.ts @@ -161,7 +161,7 @@ it.skipIf(process.platform === "win32")( stopProcess: async () => { stops++; injected.control.exit(); - return { status: "stopped" }; + return { status: "stopped", inferior: { state: "none_observed" } }; }, }, ); diff --git a/tests/boundary/providers/gdbTestHelpers.ts b/tests/boundary/providers/gdbTestHelpers.ts index 9b72479f747..43fbe5e2534 100644 --- a/tests/boundary/providers/gdbTestHelpers.ts +++ b/tests/boundary/providers/gdbTestHelpers.ts @@ -177,5 +177,9 @@ export const createGdbFixtureOwner = ( managers.length = 0; await removeFiles(); }; - return { spawnProcess, cleanup }; + /** Each still-owned fake GDB process, for asserting what a close stopped. */ + const ownedProcesses = (): readonly ProviderProcessSupervisor[] => [ + ...processes, + ]; + return { spawnProcess, cleanup, ownedProcesses }; };