Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
ae46882
Stop the Aspire CLI and own RPC connections during deactivation
Aug 7, 2026
66aaa5d
Reject foreign absolute paths in getRelativePathToWorkspace
Aug 7, 2026
f7e616a
Reject foreign absolute paths before the workspace-membership check
Aug 7, 2026
938888d
Terminate the Aspire CLI process group when the cooperative stop does…
Aug 7, 2026
67519d5
Refuse debug sessions registered after teardown and never spawn into one
Aug 7, 2026
512c887
Collect the CLI process group on self-exit and force-kill on deactiva…
Aug 7, 2026
08ecfe2
Cover the Windows taskkill termination path
Aug 7, 2026
64bcad3
Fix Windows CLI shutdown ownership
Aug 8, 2026
eea96b2
Limit exited Windows sweep to force shutdown
Aug 8, 2026
05514e8
Stabilize Azure Functions tools install
Aug 8, 2026
380cdb3
Make CLI process tree termination idempotent
Aug 8, 2026
bdca042
Revert Azure Functions Core Tools workflow release-archive install
adamint Aug 8, 2026
1f67278
Complete CLI process tree termination idempotence
Aug 8, 2026
30bb845
Cover deactivation process-tree cleanup
adamint Aug 9, 2026
dec2a1e
Prevent CLI spawn during extension shutdown
adamint Aug 9, 2026
63711a9
Avoid stop requests after deactivation timeout
adamint Aug 9, 2026
fe64b61
Avoid stale Windows CLI PID sweeps
adamint Aug 9, 2026
73b6048
Retire the Windows CLI PID instead of only skipping the immediate sweep
Aug 10, 2026
9689a52
Pin the platform in the POSIX process-group test
Aug 10, 2026
072e412
Stop late shutdown sessions cooperatively
adamint Aug 10, 2026
40144fb
Avoid stale Windows taskkill after CLI exit
adamint Aug 10, 2026
488fc84
Wait for late CLI RPC stop during shutdown
adamint Aug 10, 2026
97e7cc8
Merge branch 'main' into adamint/extension-shutdown-lifecycle
adamint Aug 10, 2026
f744667
Keep extension deactivation change focused
Aug 10, 2026
c05edf6
Merge upstream main into extension shutdown lifecycle
Aug 12, 2026
8039a12
Test extension deactivation export wiring
Aug 12, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
161 changes: 157 additions & 4 deletions extension/src/AspireExtensionContext.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as vscode from 'vscode';
import { ErrorCodes, ResponseError } from 'vscode-jsonrpc';
import { AspireDebugSession } from './debugger/AspireDebugSession';
import { AspireDebugConfigurationProvider } from './debugger/AspireDebugConfigurationProvider';
import { debugSessionAlreadyExists, extensionContextNotInitialized } from './loc/strings';
Expand All @@ -7,8 +8,11 @@ import AspireDcpServer from './dcp/AspireDcpServer';
import { AspireTerminalProvider } from './utils/AspireTerminalProvider';
import { AspireEditorCommandProvider } from './editor/AspireEditorCommandProvider';
import type { AspireDebugConsoleOutputEvent } from './types/extensionApi';
import { extensionLogOutputChannel } from './utils/logging';

export class AspireExtensionContext implements vscode.Disposable {
private static readonly _cliStopTimeoutMs = 5_000;

private _rpcServer?: AspireRpcServer;
private _dcpServer?: AspireDcpServer;
private _extensionContext?: vscode.ExtensionContext;
Expand All @@ -21,6 +25,9 @@ export class AspireExtensionContext implements vscode.Disposable {
private readonly _debugSessionOutputSubscriptions = new Map<string, vscode.Disposable>();
private readonly _onDidChangeDebugSessions = new vscode.EventEmitter<void>();
private readonly _onDidReceiveDebugConsoleOutput = new vscode.EventEmitter<AspireDebugConsoleOutputEvent>();
private _shutdownPromise?: Promise<void>;
private _isShuttingDown = false;
private _isDisposed = false;
readonly onDidChangeDebugSessions = this._onDidChangeDebugSessions.event;
readonly onDidReceiveDebugConsoleOutput = this._onDidReceiveDebugConsoleOutput.event;

Expand Down Expand Up @@ -67,6 +74,17 @@ export class AspireExtensionContext implements vscode.Disposable {
}

addAspireDebugSession(debugSession: AspireDebugSession) {
if (this._isDisposed) {
// `_disposeCore` disposes exactly the sessions present when it takes its snapshot, and
// it never runs twice. Tracking a session that arrives afterwards would therefore mean
// never disposing it at all: its CLI would keep running with nothing left alive to stop
// it. Sessions arriving *before* teardown are still accepted — `_waitForCliStopRequests`
// re-scans for them, and `_disposeCore` then disposes them on the normal path.
extensionLogOutputChannel.warn(`Refusing Aspire debug session ${debugSession.debugSessionId} because the extension has already been torn down; disposing it immediately.`);
debugSession.dispose();
return;
}

if (this._aspireDebugSessions.find(session => session.debugSessionId === debugSession.debugSessionId)) {
throw new Error(debugSessionAlreadyExists(debugSession.debugSessionId));
}
Expand Down Expand Up @@ -94,14 +112,149 @@ export class AspireExtensionContext implements vscode.Disposable {
return this._debugConfigProvider;
}

dispose() {
this._rpcServer?.dispose();
this._dcpServer?.dispose();
deactivate(): Promise<void> {
if (this._isDisposed) {
return Promise.resolve();
}

if (this._shutdownPromise) {
return this._shutdownPromise;
}

this._isShuttingDown = true;
// Schedule the async work after storing the shared promise so a reentrant dispose/deactivate
// call cannot begin synchronous teardown between the stop request and the first await.
this._shutdownPromise = Promise.resolve().then(() => this._deactivateCore());
Comment thread
adamint marked this conversation as resolved.
Resolved
return this._shutdownPromise;
}

dispose(): void {
if (this._isDisposed || this._isShuttingDown) {
return;
}

this._disposeCore();
}

private async _deactivateCore(): Promise<void> {
try {
await this._waitForCliStopRequests();
}
finally {
// A timeout or failed RPC stop still has to run the established debug-session and
// terminal teardown path so extension deactivation cannot leave the CLI process alive.
this._disposeCore();
}
}

private async _waitForCliStopRequests(): Promise<void> {
const requested = new Map<string, Promise<void>>();
const deadline = Date.now() + AspireExtensionContext._cliStopTimeoutMs;

// Re-snapshot after every await. `_isShuttingDown` does not stop `addAspireDebugSession`
// from registering a session, so a debug-adapter descriptor or an RPC-triggered
// `startDebugSession` that lands mid-await would never be asked to stop if the array were
// captured only once. Requesting a stop is idempotent per session, so re-scanning is safe.
while (this._collectStopRequests(requested) && Date.now() < deadline) {
const timedOut = await this._settleStopRequests([...requested.values()], deadline);
if (timedOut) {
extensionLogOutputChannel.warn(`Timed out after ${AspireExtensionContext._cliStopTimeoutMs}ms waiting for Aspire CLI stop requests; continuing extension teardown.`);
break;
}
}

// A cooperative stop that resolved, rejected or timed out proves only what happened to the
// RPC request; the CLI process can still be running. Signal any that are, so deactivation
// cannot leave an AppHost and its resource processes orphaned.
for (const session of this._aspireDebugSessions) {
try {
// Force rather than signal-and-schedule: `terminateCliProcess` escalates to a hard
// kill on an `unref`'d timer, and `_deactivateCore` resolves immediately after this
// sweep, so the extension host can exit before that timer fires. The cooperative
// deadline above was this CLI's grace period; there is no second one.
session.terminateCliProcessTree({ force: true });
Comment thread
adamint marked this conversation as resolved.
Resolved
}
catch (error) {
extensionLogOutputChannel.warn(`Failed to terminate the Aspire CLI process during extension deactivation: ${error}`);
}
}
}

/**
* Requests a CLI stop for every registered session that has not been asked yet, returning
* whether any new session was found.
*/
private _collectStopRequests(requested: Map<string, Promise<void>>): boolean {
let addedRequest = false;
for (const session of this._aspireDebugSessions) {
if (requested.has(session.debugSessionId)) {
continue;
}

addedRequest = true;
try {
requested.set(session.debugSessionId, session.requestCliStopForExtensionShutdown());
}
catch (error) {
requested.set(session.debugSessionId, Promise.reject(error));
}
}

return addedRequest;
}

private async _settleStopRequests(stopRequests: Promise<void>[], deadline: number): Promise<boolean> {
const allStops = Promise.allSettled(stopRequests);
let timeout: ReturnType<typeof setTimeout> | undefined;
const outcome = await Promise.race([
allStops.then(results => ({ timedOut: false as const, results })),
new Promise<{ timedOut: true }>(resolve => {
timeout = setTimeout(() => {
timeout = undefined;
resolve({ timedOut: true });
}, Math.max(0, deadline - Date.now()));
}),
]);

if (timeout) {
clearTimeout(timeout);
}

if (outcome.timedOut) {
return true;
}

const failures = outcome.results
.filter((result): result is PromiseRejectedResult => result.status === 'rejected')
.map(result => result.reason);
for (const failure of failures) {
// Closing the RPC transport rejects its outstanding stop request even though the
// synchronous debug-session and terminal teardown below has completed successfully.
if (failure instanceof ResponseError && failure.code === ErrorCodes.PendingResponseRejected) {
extensionLogOutputChannel.info(`Aspire CLI stop request ended after the RPC transport closed: ${failure}`);
}
else {
extensionLogOutputChannel.warn(`Failed to stop Aspire CLI during extension deactivation: ${failure}`);
}
}

return false;
}

private _disposeCore(): void {
if (this._isDisposed) {
return;
}

this._isDisposed = true;
this._debugSessionStateSubscriptions.forEach(disposable => disposable.dispose());
this._debugSessionStateSubscriptions.clear();
this._debugSessionOutputSubscriptions.forEach(disposable => disposable.dispose());
this._debugSessionOutputSubscriptions.clear();
this._aspireDebugSessions.forEach(session => session.dispose());
const sessions = this._aspireDebugSessions.splice(0);
sessions.forEach(session => session.dispose());
this._rpcServer?.dispose();
this._dcpServer?.dispose();
this._terminalProvider?.dispose();
this._editorCommandProvider?.dispose();
this._onDidChangeDebugSessions.dispose();
Expand Down
100 changes: 95 additions & 5 deletions extension/src/debugger/AspireDebugSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { createDebugAdapterTracker, AppHostOutputHandler, AppHostRestartHandler
import { AspireResourceExtendedDebugConfiguration, AspireResourceDebugSession, EnvVar, AspireExtendedDebugConfiguration, NodeLaunchConfiguration, ProcessRestartedNotification, ProjectLaunchConfiguration, SessionTerminatedNotification, StartAppHostOptions } from "../dcp/types";
import { extensionLogOutputChannel } from "../utils/logging";
import AspireDcpServer, { generateDcpIdPrefix } from "../dcp/AspireDcpServer";
import { spawnCliProcess } from "./languages/cli";
import { spawnCliProcess, terminateCliProcess } from "./languages/cli";
import { disconnectingFromSession, launchingWithAppHost, launchingWithDirectory, processExceptionOccurred, processExitedWithCode, aspireDashboard, appHostSessionTerminated } from "../loc/strings";
import { projectDebuggerExtension } from "./languages/dotnet";
import { AnsiColors } from "../utils/AspireTerminalProvider";
Expand All @@ -20,6 +20,7 @@ import { ICliRpcClient } from "../server/rpcClient";
import path from "path";
import os from "os";
import { EnvironmentVariables } from "../utils/environment";
import type { ChildProcessWithoutNullStreams } from "child_process";
import { sendTelemetryEvent } from "../utils/telemetry";
import { classifyAppHostPath, classifyAppHostDirectory } from "../utils/appHostLanguage";
import { bucketAspireCommand } from "../utils/telemetryBuckets";
Expand Down Expand Up @@ -53,6 +54,12 @@ export function getLoggableDebugConfiguration(debugConfig: AspireResourceExtende
export class AspireDebugSession implements vscode.DebugAdapter {
private static readonly _mauiDebugStartMaxAttempts = 3;
private static readonly _mauiDebugStartRetryDelayMs = 5000;
/**
* How long the cooperative `stopCli` RPC has to bring the CLI down before its process group is
* signalled. Long enough for the CLI to stop containers and other resources cleanly, short
* enough that a wedged CLI does not keep the AppHost alive indefinitely.
*/
private static readonly _cliCooperativeStopGraceMs = 10_000;
private readonly _onDidSendMessage = new EventEmitter<any>();
private readonly _onDidSendDebugConsoleOutput = new EventEmitter<AspireDebugConsoleOutputEvent>();
private _messageSeq = 1;
Expand All @@ -74,6 +81,9 @@ export class AspireDebugSession implements vscode.DebugAdapter {
private readonly _disposables: vscode.Disposable[] = [];
private _disposed = false;
private _parentStopPromise: Thenable<void> | undefined;
private _cliStopPromise: Promise<void> | undefined;
private _cliProcess: ChildProcessWithoutNullStreams | undefined;
private _cliTerminationTimer: ReturnType<typeof setTimeout> | undefined;
// Timestamp for the `debug/apphost/end` duration measurement. Captured the first
// time we observe a `launch` request so it covers the actual user-visible session
// lifetime, not the moment the AspireDebugSession object was constructed.
Expand Down Expand Up @@ -135,6 +145,58 @@ export class AspireDebugSession implements vscode.DebugAdapter {
}
}

requestCliStopForExtensionShutdown(): Promise<void> {
if (!this._rpcClient) {
return Promise.resolve();
}

this._cliStopPromise ??= this._rpcClient.stopCli();
return this._cliStopPromise;
}

/**
* Signals the `aspire` CLI process group when the process is still alive.
*
* The cooperative `stopCli` RPC resolving proves only that the request was accepted, and on a
* closed transport it resolves having done nothing at all. Neither outcome terminates the CLI,
* so the process it owns — the AppHost and every resource process beneath it — has to be
* signalled directly whenever the cooperative path did not finish the job. No-ops when the CLI
* already exited, which is the normal case.
*/
terminateCliProcessTree(options?: { force?: boolean }): void {
this.cancelScheduledCliProcessTermination();
Comment thread
adamint marked this conversation as resolved.
Resolved
const cliProcess = this._cliProcess;
if (!cliProcess) {
return;
}

// Deliberately not skipped once the leader has exited. `terminateCliProcess` reaps the surviving
// members of a managed process group in that case, and that is the only path that collects
// AppHost and resource processes which outlived the CLI that owned them.
terminateCliProcess(cliProcess, `Aspire CLI for debug session ${this.debugSessionId}`, options);
}

private scheduleCliProcessTermination(): void {
if (!this._cliProcess || this._cliTerminationTimer) {
return;
}

// Give the cooperative stop the first chance so the CLI can shut its resources down cleanly;
// only a CLI that is still alive afterwards gets signalled.
this._cliTerminationTimer = setTimeout(() => {
this._cliTerminationTimer = undefined;
this.terminateCliProcessTree();
}, AspireDebugSession._cliCooperativeStopGraceMs);
this._cliTerminationTimer.unref?.();
}

private cancelScheduledCliProcessTermination(): void {
if (this._cliTerminationTimer) {
clearTimeout(this._cliTerminationTimer);
this._cliTerminationTimer = undefined;
}
}

private stopParentDebugSessionOnce(): Thenable<void> {
if (this._parentStopPromise) {
return this._parentStopPromise;
Expand Down Expand Up @@ -396,9 +458,20 @@ export class AspireDebugSession implements vscode.DebugAdapter {
return partial;
};

spawnCliProcess(
const cliPath = await this._terminalProvider.getAspireCliExecutablePath();
if (this._disposed) {
Comment thread
adamint marked this conversation as resolved.
Resolved
// Resolving the CLI path is asynchronous, so extension deactivation can complete between the
// launch request and this point. Spawning now would produce an `aspire run` that no teardown
// path is left to stop — and because it is spawned detached as a process-group leader, it
// would not even die with the extension host.
extensionLogOutputChannel.info(`Skipping Aspire CLI launch for disposed debug session ${this.debugSessionId}.`);
disposable.dispose();
return;
}

this._cliProcess = spawnCliProcess(
this._terminalProvider,
await this._terminalProvider.getAspireCliExecutablePath(),
cliPath,
args,
{
stdoutCallback: (data) => {
Expand All @@ -412,6 +485,12 @@ export class AspireDebugSession implements vscode.DebugAdapter {
vscode.window.showErrorMessage(processExceptionOccurred(error.message, commandLabel));
},
exitCallback: (code) => {
// The leader came down on its own, so the escalation timer has nothing left to signal —
// but a detached leader's descendants (the AppHost and every resource process beneath it)
// can outlive it, and this is the last moment they can be collected safely: once the
// leader's PID is released the operating system may recycle it as another group's id, and
// a later negative-PID signal would land on something unrelated.
this.terminateCliProcessTree();
Comment thread
adamint marked this conversation as resolved.
Resolved
this._dcpServer.recordAppHostProcessExit(this.debugSessionId, code);
// Flush any partial line left in either buffer so trailing output isn't lost.
if (stdoutBuffer.length > 0) {
Expand All @@ -429,16 +508,27 @@ export class AspireDebugSession implements vscode.DebugAdapter {
workingDirectory: workingDirectory,
debugSessionId: this.debugSessionId,
noDebug: noDebug,
env: env
env: env,
// `aspire run` owns the AppHost and every resource process beneath it. Spawning it as a
// process-group leader is what lets `terminateCliProcess` signal the whole tree by negative
// PID when the cooperative `stopCli` RPC does not finish the job. Every other CLI spawn
// site in the extension already does this; this one is the longest-lived of them.
createProcessGroup: true,
},
);

this._disposables.push({
dispose: () => {
this._rpcClient?.stopCli().catch((err) => {
void this.requestCliStopForExtensionShutdown().catch((err) => {
extensionLogOutputChannel.info(`stopCli failed (connection may already be closed): ${err}`);
});
extensionLogOutputChannel.info(`Requested Aspire CLI exit with args: ${args.join(' ')}`);
// `stopCli` is cooperative and cannot be the only stop mechanism: it resolves without
// effect when the transport is already closed, and never settles when the CLI has stopped
// servicing the connection. Escalate to signalling the process group once the CLI has had
// a chance to exit on its own, so a CLI that ignores the request cannot outlive the
// session and keep the AppHost and its resource processes alive.
this.scheduleCliProcessTermination();
Comment thread
adamint marked this conversation as resolved.
Resolved
}
});

Expand Down
12 changes: 11 additions & 1 deletion extension/src/debugger/languages/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ export function spawnCliProcess(terminalProvider: AspireTerminalProvider, comman
return child;
}

export function terminateCliProcess(childProcess: ChildProcessWithoutNullStreams, description: string, options?: { suppressTimeoutWarning?: boolean }): void {
export function terminateCliProcess(childProcess: ChildProcessWithoutNullStreams, description: string, options?: { suppressTimeoutWarning?: boolean; force?: boolean }): void {
const processGroupPid = process.platform !== 'win32' && managedPosixProcessGroups.has(childProcess)
? childProcess.pid
: undefined;
Expand Down Expand Up @@ -165,6 +165,16 @@ export function terminateCliProcess(childProcess: ChildProcessWithoutNullStreams
return;
}

if (options?.force) {
Comment thread
adamint marked this conversation as resolved.
Resolved
// Skip the graceful signal and its escalation timer entirely. The timer below is `unref`'d,
// so a caller that is itself shutting down — extension deactivation, which resolves as soon
// as this returns — can have its host exit before the timer ever fires, leaving a process
// that ignored SIGTERM alive along with its whole tree. Such callers have already spent
// their own cooperative window, so the only signal left that means anything is the hard one.
forceTermination();
return;
}

try {
if (!childProcess.killed) {
const signalSent = terminateCliProcessTree(childProcess, false);
Expand Down
Loading
Loading