Skip to content

Emit DCP session termination when stopping resources - #19125

Merged
Adam Ratzman (adamint) merged 24 commits into
microsoft:mainfrom
adamint:adamint/issue15426-vscode-session-terminated
Aug 12, 2026
Merged

Adam Ratzman (adamint) merged 24 commits into
microsoft:mainfrom
adamint:adamint/issue15426-vscode-session-terminated

Conversation

@adamint

@adamint Adam Ratzman (adamint) commented Aug 7, 2026 •

Copy link
Copy Markdown
Member

Description

Keeps DCP run-session lifecycle consistent when a VS Code-controlled resource is stopped from the Aspire dashboard.

  • Tracks run ownership and WebSocket routing by the stable DCP session prefix so reconnects keep control of their runs.
  • Emits exactly one terminal notification for requested stops, natural exits, and debugger_did_not_start.
  • Retains completed runs long enough for duplicate DELETE requests to remain idempotent.
  • Stops sessions that finish starting after a DELETE exactly once.
  • Prevents a stale WebSocket close handler from removing a newer replacement connection.
  • Suppresses logs, restarts, and duplicate completion after a run becomes terminal.

Fixes #15426

Security considerations

The existing authenticated DCP channel remains the trust boundary. Run control is limited to the stable owning DCP session prefix; this change adds no listener, credential flow, or network surface.

Validation

  • TypeScript compile and lint
  • 13 focused AspireDcpServer tests
  • 3 focused run-session registry tests

Checklist

  • Feature complete
  • Tests cover the changed lifecycle behavior
  • No public API added

Copilot AI balanced review requested due to automatic review settings August 7, 2026 12:02
@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.sh | bash -s -- 19125

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.ps1) } 19125"

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds reliable DCP run-session termination when dashboard-controlled resources stop.

Changes:

  • Tracks run lifecycle and ownership by execution ID.
  • Deduplicates terminal notifications and late adapter events.
  • Adds extensive lifecycle, ownership, telemetry, and adapter tests.
Show a summary per file
File Description
extension/src/dcp/AspireDcpServer.ts Implements lifecycle, ownership, teardown, and notification handling.
extension/src/dcp/types.ts Makes termination exit codes optional.
extension/src/debugger/adapterTracker.ts Routes callbacks through run-scoped handlers.
extension/src/test/aspireDcpServer.test.ts Tests DCP lifecycle and ownership scenarios.
extension/src/test/adapterTracker.test.ts Tests run-scoped adapter notifications.

Review details

  • Files reviewed: 5/5 changed files
  • Comments generated: 1
  • Review effort level: Balanced

Comment thread extension/src/dcp/AspireDcpServer.ts Resolved
Adam Ratzman (adamint) pushed a commit to adamint/aspire that referenced this pull request Aug 7, 2026
`SessionTerminatedNotification.exit_code` is now optional, so the run
telemetry summary can no longer assume a number is present. Treat an
absent exit code as its own `unknown` bucket instead of letting it fall
into `nonzero`, and omit the `exit_code` measurement entirely rather
than emitting a fabricated value.

This mirrors the bucket logic in microsoft#19125 verbatim so the two branches
compose without conflict.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: 0caf8437-4c5f-47a5-82da-9ecefb06e2fc
Copilot AI review requested due to automatic review settings August 7, 2026 15:50

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review details

Suppressed comments (1)

extension/src/dcp/AspireDcpServer.ts:819

  • If the adapter reports sessionTerminated without an exit code after a DELETE, this cancels the fallback timer and records the run as unknown, even though run.lifecycle proves it was a requested stop. The telemetry bucket therefore depends on whether the adapter's no-code callback arrives before the timeout. Preserve the omitted wire field, but record -1 for this requested-stop completion so it is consistently classified as canceled.
        this._recordRunSessionCompletion(run, sessionTerminated.exit_code);
  • Files reviewed: 5/5 changed files
  • Comments generated: 0 new
  • Review effort level: Balanced

Copilot AI review requested due to automatic review settings August 7, 2026 18:07

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review details

Suppressed comments (1)

extension/src/dcp/RunSessionRegistry.ts:202

  • undefined does not uniquely mean a requested stop: adapterTracker.onExit(undefined) now intentionally emits a natural sessionTerminated without exit_code. This branch therefore marks that natural adapter exit as stopRequested, waits for retention, and records it as canceled (-1) instead of completing it with an unknown exit code. Distinguish the stop source (for example, by checking the lifecycle set by requestStop) and add an integration test for an adapter termination with no exit code.
        if (exitCode === undefined && record.terminationTrigger.kind === 'adapterExit') {
            // A requested stop on an adapter-backed run. The notification stream is terminal
            // immediately, but telemetry is deferred: the adapter's later exit reports the
            // process's real exit code, and the retention deadline records a cancellation if
            // no exit ever arrives.
            record.lifecycle = 'stopRequested';
            this._scheduleRetention(record);
            return;
  • Files reviewed: 7/7 changed files
  • Comments generated: 1
  • Review effort level: Balanced

Comment thread extension/src/dcp/AspireDcpServer.ts Resolved
@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt.

@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt.

@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt.

Copilot AI review requested due to automatic review settings August 7, 2026 19:10

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review details

Suppressed comments (3)

extension/src/dcp/RunSessionRegistry.ts:215

  • A natural adapter exit now records completion and evicts the run after five seconds without ever invoking stopSession(). That method is also the per-run cleanup path (AspireDebugSession.ts:596-608); for example, Azure Functions registers killFuncProcess there explicitly for every session end (languages/azureFunctions.ts:107-109). The DELETE handler also skips teardown for completed records, and after eviction it returns 204, so an absent or delayed follow-up DELETE leaves auxiliary processes and cleanup registrations alive until the whole Aspire debug session is disposed. Trigger the memoized teardown/cleanup when an adapter-backed run completes, while retaining only the protocol record for idempotent DELETEs.
        if (record.terminationTrigger.kind === 'adapterExit') {
            // DCP usually follows a natural exit with its own DELETE. Retention keeps the
            // record addressable so that DELETE is still answered 200 rather than 204 for
            // the most common shutdown ordering.
            this._scheduleRetention(record);

extension/src/test/aspireDcpServer.test.ts:587

  • Repository comments should describe the current behavior without depending on within-PR review history. This discussion URL becomes stale context after merge and is not needed to understand the scenario; state the reconnect sequence directly instead.
        // Sequence from https://github.com/microsoft/aspire/pull/19125#discussion_r3735627366:
        // the first instance stops the run while its socket is unavailable, then a replacement
        // instance retries the DELETE and is answered 200 without a second notification.

extension/src/dcp/RunSessionRegistry.ts:22

  • This comment describes the implementation change rather than the current contract. Repository comments should remain valid without branch history; explain only that callers declare the termination model at registration.
 * This replaces per-call-site booleans: a caller declares the run's termination model once
 * at registration instead of each termination path re-deciding whether to send and dedupe.
  • Files reviewed: 7/7 changed files
  • Comments generated: 1
  • Review effort level: Balanced

Comment thread extension/src/dcp/AspireDcpServer.ts Resolved
Adam Ratzman and others added 9 commits August 7, 2026 16:13
Co-authored-by: Copilot <[email protected]>
Copilot-Session: ffeff87e-f284-434d-87d3-843e21a7aebb
Copilot-Session: ffeff87e-f284-434d-87d3-843e21a7aebb

Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>

Copilot-Session: ffeff87e-f284-434d-87d3-843e21a7aebb
Co-authored-by: Copilot <[email protected]>

Copilot-Session: ffeff87e-f284-434d-87d3-843e21a7aebb
Keep resource notifications run-scoped through bounded retention, preserve compatible DELETE routing and status semantics, replace stale sockets, and finalize telemetry during cleanup and disposal.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: ffeff87e-f284-434d-87d3-843e21a7aebb
Omit the wire exit code when startup fails before a process exit is available, while retaining -1 only for canceled telemetry.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: ffeff87e-f284-434d-87d3-843e21a7aebb
Co-authored-by: Copilot <[email protected]>
Copilot-Session: ffeff87e-f284-434d-87d3-843e21a7aebb
Co-authored-by: Copilot <[email protected]>
Copilot-Session: ffeff87e-f284-434d-87d3-843e21a7aebb
A `sessionTerminated` queued for the exact owner while its WebSocket was
already gone stayed under that owner's DCP instance ID. The pending queue is
only drained by a WebSocket upgrade for that exact ID, and a replaced DCP
execution never reconnects under it, so the notification was dropped for good.

When an open same-prefix replacement then retried DELETE, ownership moved but
the queue did not: the run was already `stopRequested` with
`terminalNotificationSent` set, so the replacement got a bare 200 and never
learned the session had ended — the original symptom of issue microsoft#15426.

Hand the run's queued notifications to the new owner during ownership transfer,
before the terminal-state early return. Only this run's notifications move;
other runs still owned by the previous instance keep their place in the queue
and transfer with their own DELETE.

Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>

Copilot-Session: c235246b-d021-4d8e-b041-cc4984674ebe
Copilot AI review requested due to automatic review settings August 11, 2026 01:33

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review details

Suppressed comments (3)

extension/src/dcp/AspireDcpServer.ts:592

  • A DELETE can set this record to stopRequested while prepareDebugSession (or another awaited startup step) is pending. If that operation then rejects before retention expires, the record still exists, so this guard misclassifies the acknowledged cancellation as launch_failed and returns 500; after retention expires the same race returns 409. Check that the lifecycle is still starting, not merely that the record exists.
                    if (!runSessions.get(runId)) {

extension/src/dcp/AspireDcpServer.ts:551

  • If DELETE arrives while startAndGetDebugSession is pending and startup then resolves undefined, this path reports debugger_did_not_start/500 instead of the cancellation 409 used for a late successful start. If the retention timer has already evicted the run, it also emits a second run-session end event after the canceled completion. Recheck the lifecycle before emitting failure telemetry.
                        runTelemetryById.delete(runId);
                        emitRunSessionFailureEnd('debugger_did_not_start');
                        runSessions.terminate(runId, -1);

extension/src/dcp/AspireDcpServer.ts:680

  • This early return skips debugger teardown when the run already became terminal through a natural adapter exit. stopSession is also the path that invokes cleanupRun, so resource-specific cleanup handlers remain registered (and processes such as Azure Functions can remain reachable) until the parent session is disposed. Schedule the memoized teardown for every known owned adapter run; teardownStarted already prevents duplicate stops.
                if (!runSessions.requestStop(runId)) {
                    res.status(200).end();
                    return;
  • Files reviewed: 7/7 changed files
  • Comments generated: 0 new
  • Review effort level: Balanced

Co-authored-by: Copilot <[email protected]>

Copilot-Session: 3253974d-4f18-486f-863c-281a607656d4
Copilot AI review requested due to automatic review settings August 11, 2026 04:54

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review details

Suppressed comments (2)

extension/src/test/aspireDcpServer.test.ts:640

  • This reconnect test connects the replacement socket before issuing DELETE, so it never exercises the pending-notification queue. A regression that keyed pendingNotificationQueueByDcpId by the old full instance ID would still pass even though a terminal queued while disconnected would be stranded. Add a case that closes the original socket, issues DELETE with no socket connected, then connects a same-prefix replacement and verifies the queued terminal is delivered exactly once.
    test('DELETE accepts a reconnected DCP instance with the same stable prefix', async () => {
        const originalClient = await openNotificationClient(harness);
        const stopSession = sinon.stub().resolves();
        const runId = await createRun(harness, 'node', stopSession);
        const reconnectedDcpId = 'aspire-extension-run-test-reconnected';
        const reconnectedClient = await openNotificationClient(harness, reconnectedDcpId);

extension/src/dcp/AspireDcpServer.ts:170

  • Pending-start cancellations now complete through this callback, but they never pass through either aggregate increment at the successful-start path or emitRunSessionFailureEnd. Consequently debug/apphost/end omits these accepted runs from total_child_sessions and distinct_resource_types even though a paired debug/runsession/start/end is emitted. Record the aggregate membership once when the run is accepted (and remove the later duplicate increments), or track whether it has already been recorded.
        const recordRunSessionCompletion = (runId: string, exitCode: number): void => {
            const entry = runTelemetryById.get(runId);
            if (!entry) {
                return;
            }
  • Files reviewed: 7/7 changed files
  • Comments generated: 0 new
  • Review effort level: Balanced

@adamint
Adam Ratzman (adamint) marked this pull request as ready for review August 11, 2026 05:26
@adamint
Adam Ratzman (adamint) marked this pull request as draft August 11, 2026 06:44
Record aggregate membership when a run session is accepted and cover queued terminal delivery after a disconnected DELETE.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: 3253974d-4f18-486f-863c-281a607656d4
Copilot AI review requested due to automatic review settings August 11, 2026 07:30

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review details

  • Files reviewed: 7/7 changed files
  • Comments generated: 0 new
  • Review effort level: Balanced

@adamint
Adam Ratzman (adamint) marked this pull request as ready for review August 11, 2026 08:18

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reviewed the DCP run-session lifecycle end to end, including startup and DELETE races, terminal-notification ordering, debugger teardown and retry behavior, reconnect routing, retention and telemetry, disposal, and the new unit coverage.

I found one wire-contract regression in the handling of unavailable exit codes.

Comment thread extension/src/dcp/AspireDcpServer.ts Resolved
Co-authored-by: Copilot <[email protected]>

Copilot-Session: 3e0243ed-7347-4ac1-848c-db9440abb139

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review details

  • Files reviewed: 7/7 changed files
  • Comments generated: 0 new
  • Review effort level: Balanced

@adamint
Adam Ratzman (adamint) merged commit 199a9f3 into microsoft:main Aug 12, 2026
341 checks passed
@github-actions github-actions Bot added this to the 13.6 milestone Aug 12, 2026
@github-actions

Copy link
Copy Markdown
Contributor

⚠️ CI Failure Analysis: Possible Flaky Test(s)

The CI build failed due to test failure(s) that appear unrelated to the PR changes. These may be flaky tests.

Suspected flaky test(s):

  • e2eShardMatrix.test.js (Extension host E2E test) in job Tests / Run VS Code extension unit tests (Windows)
    • Error: 1 test failed. Extension host test runner error 1 test failed. (exit code 1)
    • Stack Trace (first frames):
      at Context.<anonymous> (d:\a\aspire\aspire\extension\out\test\e2eShardMatrix.test.js:146:9)
      	at process.processImmediate (node:internal/timers:504:21)
      
    • Why likely flaky: This test file (e2eShardMatrix.test.js) is not part of the PR's changed files; the PR only modified DCP session/debugger source and their dedicated unit test files, all of which passed. The failure is isolated to an unrelated E2E VS Code extension host test on Windows, consistent with known environment-dependent flakiness in the Extension host test runner.

Suggested actions:

  • Re-run the failed CI jobs to confirm if the failure is intermittent
  • If the test continues to fail, consider quarantining it using /quarantine-test <test name> <issue URL>
  • Search existing issues to see if this test is already known to be flaky

You can re-run the failed jobs from the workflow run page.

@github-actions github-actions Bot locked and limited conversation to collaborators Oct 9, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[AspireE2E] When creating and running the Aspire Starter App (Express/React) in VS Code, the app resources fail to stop on the dashboard page.

3 participants