fix(lifecycle): reject session work once close has started (#6411)
* fix(lifecycle): reject session work once close has started Process shutdown closed the shared binary session without sealing it, so a stdio tool call could open a provider after that close and leave the child running. GDB ran a queued console command or a second close after the session had started closing because the queued turn did not repeat admission checks. Shutdown now refuses later target acquisition, and a queued GDB command or duplicate close fails as unavailable once its turn finds the session closing or gone. Co-authored-by: morluto <[email protected]> * fix(gdb): block console admission after cleanup starts --------- Co-authored-by: Cursor Agent <[email protected]> Co-authored-by: morluto <[email protected]>
This commit is contained in:
5 files changed
+436
-44
No files matched your search
@@ -154,6 +154,8 @@ export class BinarySession
|
||||
#transition: Promise<void> = Promise.resolve();
|
||||
#transitionGeneration = 0;
|
||||
#transitionPending = 0;
|
||||
/** Process shutdown has begun; later target acquisition must not outlive it. */
|
||||
#shutdownStarted = false;
|
||||
readonly #calls = new Map<Promise<unknown>, number>();
|
||||
readonly #promptCompletionControllers = new Set<AbortController>();
|
||||
readonly #providerRouter: SessionProviderRouter;
|
||||
@@ -182,6 +184,8 @@ export class BinarySession
|
||||
options: Pick<ExecutionOptions, "signal"> = {},
|
||||
): Promise<Result<ResolvedAppBundleResourceRoot, AnalysisError>> {
|
||||
return this.#serialize(async (admittedThrough) => {
|
||||
const refused = this.#targetAcquisitionRefused("open_bundle_resources");
|
||||
if (refused !== undefined) return refused;
|
||||
await this.#drainCalls(admittedThrough);
|
||||
if (isAborted(options.signal))
|
||||
return err(
|
||||
@@ -498,6 +502,8 @@ export class BinarySession
|
||||
options: BinarySessionOpenOptions,
|
||||
): Promise<Result<BinaryTarget, AnalysisError>> {
|
||||
return this.#serialize(async (admittedThrough) => {
|
||||
const refused = this.#targetAcquisitionRefused("open_binary");
|
||||
if (refused !== undefined) return refused;
|
||||
const admitted = await this.#withLoadedSnapshot(options);
|
||||
if (!admitted.ok) return admitted;
|
||||
return this.#openWithinTransition(
|
||||
@@ -757,6 +763,22 @@ export class BinarySession
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reject target acquisition once process shutdown has begun.
|
||||
* Acquisition already inside its transition still finishes; the shutdown
|
||||
* close queued behind that transition retires it.
|
||||
*/
|
||||
beginShutdown(): void {
|
||||
this.#shutdownStarted = true;
|
||||
}
|
||||
|
||||
#targetAcquisitionRefused(
|
||||
operation: "open_binary" | "open_bundle_resources",
|
||||
): Result<never, AnalysisCancelledError> | undefined {
|
||||
if (!this.#shutdownStarted) return undefined;
|
||||
return err(new AnalysisCancelledError(operation));
|
||||
}
|
||||
|
||||
/** Close the active target, if any. */
|
||||
close(
|
||||
options: Pick<ExecutionOptions, "progress"> & {
|
||||
|
||||
@@ -494,6 +494,8 @@ interface GdbSession {
|
||||
readonly settleStdout: () => void;
|
||||
inferiorTtyVerified: boolean;
|
||||
noInferiorVerified: boolean;
|
||||
/** Sticky admission seal once destructive cleanup starts, including failed stops. */
|
||||
cleanupStarted: boolean;
|
||||
stopAttempt: ReturnType<typeof stopOwnedDebuggerProcess> | undefined;
|
||||
readonly pending: Map<number, PendingCommand>;
|
||||
readonly cleanupFailures: Set<AnalysisError>;
|
||||
@@ -517,6 +519,18 @@ interface GdbSession {
|
||||
recentRecordsTruncated: boolean;
|
||||
}
|
||||
|
||||
const gdbConsoleUnavailable = (): AnalysisInputError =>
|
||||
new AnalysisInputError("gdb_console", undefined, [
|
||||
{
|
||||
path: ["session_id"],
|
||||
reason: "invalid_value",
|
||||
message: "GDB session is unavailable or closed.",
|
||||
},
|
||||
]);
|
||||
|
||||
const gdbCloseUnavailable = (): AnalysisInputError =>
|
||||
new AnalysisInputError("close_gdb_session");
|
||||
|
||||
/** Owns persistent GDB/MI sessions independently from the active binary target. */
|
||||
export class GdbSessionManager {
|
||||
readonly #sessions = new Map<string, GdbSession>();
|
||||
@@ -794,6 +808,7 @@ export class GdbSessionManager {
|
||||
// GDB is launched with --nx and receives no target-execution commands
|
||||
// during startup, so no inferior can exist until execute() is called.
|
||||
noInferiorVerified: true,
|
||||
cleanupStarted: false,
|
||||
stopAttempt: undefined,
|
||||
pending: new Map(),
|
||||
cleanupFailures: new Set(),
|
||||
@@ -1140,26 +1155,27 @@ export class GdbSessionManager {
|
||||
this.#closing ||
|
||||
session === undefined ||
|
||||
!session.ready ||
|
||||
session.cleanupStarted ||
|
||||
session.exited ||
|
||||
session.protocolError !== undefined
|
||||
)
|
||||
return err(
|
||||
new AnalysisInputError("gdb_console", undefined, [
|
||||
{
|
||||
path: ["session_id"],
|
||||
reason: "invalid_value",
|
||||
message: "GDB session is unavailable or closed.",
|
||||
},
|
||||
]),
|
||||
);
|
||||
return err(gdbConsoleUnavailable());
|
||||
if (signal?.aborted)
|
||||
return err(cancelledWithCallerReason("gdb_console", signal));
|
||||
try {
|
||||
const completed = await this.#serialize(
|
||||
session,
|
||||
async () => {
|
||||
if (session.exited || session.protocolError !== undefined)
|
||||
return err(new AnalysisInputError("gdb_console"));
|
||||
// Retained cleanup ownership and a delayed exit event do not imply
|
||||
// command readiness. Recheck admission when this queued turn starts.
|
||||
if (
|
||||
this.#closing ||
|
||||
this.#sessions.get(sessionId) !== session ||
|
||||
session.cleanupStarted ||
|
||||
session.exited ||
|
||||
session.protocolError !== undefined
|
||||
)
|
||||
return err(gdbConsoleUnavailable());
|
||||
session.noInferiorVerified = false;
|
||||
session.knownInferiorIdentities.clear();
|
||||
if (commandMayChangeInferiorOutput(command))
|
||||
@@ -1324,7 +1340,10 @@ export class GdbSessionManager {
|
||||
session_id: session.id,
|
||||
mi_version: session.miVersion,
|
||||
state:
|
||||
session.exited || session.protocolError !== undefined || !session.ready
|
||||
session.cleanupStarted ||
|
||||
session.exited ||
|
||||
session.protocolError !== undefined ||
|
||||
!session.ready
|
||||
? "closed"
|
||||
: "ready",
|
||||
recent_mi_records: [...session.lines],
|
||||
@@ -1352,38 +1371,17 @@ export class GdbSessionManager {
|
||||
if (this.#closing)
|
||||
return err(new AnalysisCancelledError("close_gdb_session"));
|
||||
const session = this.#sessions.get(sessionId);
|
||||
if (session === undefined)
|
||||
return err(new AnalysisInputError("close_gdb_session"));
|
||||
if (session.exited) {
|
||||
const stopped = await this.#stopDebuggerOnly(session);
|
||||
if (stopped.status === "incomplete")
|
||||
return err(
|
||||
this.#retainCleanupFailure(
|
||||
session,
|
||||
"close_gdb_session",
|
||||
stopped.reason,
|
||||
),
|
||||
);
|
||||
this.#sessions.delete(sessionId);
|
||||
return ok({ target_state: "unknown" });
|
||||
}
|
||||
if (session === undefined) return err(gdbCloseUnavailable());
|
||||
if (session.exited) return this.#finishSessionCleanup(session);
|
||||
try {
|
||||
return await this.#serialize(
|
||||
session,
|
||||
async () => {
|
||||
if (session.exited) {
|
||||
const stopped = await this.#stopDebuggerOnly(session);
|
||||
if (stopped.status === "incomplete")
|
||||
return err(
|
||||
this.#retainCleanupFailure(
|
||||
session,
|
||||
"close_gdb_session",
|
||||
stopped.reason,
|
||||
),
|
||||
);
|
||||
this.#sessions.delete(sessionId);
|
||||
return ok({ target_state: "unknown" });
|
||||
}
|
||||
// An earlier close can remove this session while this close waits.
|
||||
if (this.#sessions.get(sessionId) !== session)
|
||||
return err(gdbCloseUnavailable());
|
||||
if (session.exited || session.cleanupStarted)
|
||||
return this.#finishSessionCleanup(session);
|
||||
let targetState: "none_observed" | "unknown" = "unknown";
|
||||
try {
|
||||
const groups = await this.#request(
|
||||
@@ -1418,6 +1416,9 @@ export class GdbSessionManager {
|
||||
},
|
||||
),
|
||||
);
|
||||
// Refusing inferior disposition above leaves console remediation
|
||||
// available; from here onward only owned cleanup may be retried.
|
||||
session.cleanupStarted = true;
|
||||
if (groupCount === 0) {
|
||||
session.noInferiorVerified = true;
|
||||
targetState = "none_observed";
|
||||
@@ -1454,6 +1455,22 @@ export class GdbSessionManager {
|
||||
}
|
||||
}
|
||||
|
||||
async #finishSessionCleanup(
|
||||
session: GdbSession,
|
||||
): Promise<Result<{ readonly target_state: "unknown" }, AnalysisError>> {
|
||||
const stopped = await this.#stopDebuggerOnly(session);
|
||||
if (stopped.status === "incomplete")
|
||||
return err(
|
||||
this.#retainCleanupFailure(
|
||||
session,
|
||||
"close_gdb_session",
|
||||
stopped.reason,
|
||||
),
|
||||
);
|
||||
this.#sessions.delete(session.id);
|
||||
return ok({ target_state: "unknown" });
|
||||
}
|
||||
|
||||
async retryCleanupFailures(): Promise<Result<null, AnalysisError>> {
|
||||
for (const session of this.#sessions.values()) {
|
||||
if (session.cleanupFailures.size === 0) continue;
|
||||
@@ -1764,6 +1781,7 @@ export class GdbSessionManager {
|
||||
#stopDebuggerOnly(
|
||||
session: GdbSession,
|
||||
): ReturnType<typeof stopOwnedDebuggerProcess> {
|
||||
session.cleanupStarted = true;
|
||||
if (session.stopAttempt !== undefined) return session.stopAttempt;
|
||||
const attempt = this.#stopProcess(session, "GDB")
|
||||
.then((stopped) => {
|
||||
|
||||
@@ -47,8 +47,11 @@ export const createShutdown = (input: {
|
||||
if (shutdownAttempt !== undefined) return shutdownAttempt;
|
||||
const pending = cleanupOwners.filter(({ closed }) => !closed);
|
||||
const attempt = (async () => {
|
||||
// HTTP handlers can still own provider resources after cancellation.
|
||||
// A failed drain keeps every shared owner available for a later retry.
|
||||
// Seal before the drain and owner closes. A tool call admitted before
|
||||
// shutdown can reach session.open() after that close and would otherwise
|
||||
// start a provider the completed shutdown never retires. A failed drain
|
||||
// still keeps every shared owner available for a later cleanup retry.
|
||||
session.beginShutdown();
|
||||
await handle.prepareShutdown?.();
|
||||
const results = await Promise.allSettled(
|
||||
pending.map(async (owner) => {
|
||||
|
||||
Reference in new issue
Block a user