Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions changelog.d/1231.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Starting or attaching again after a proxy worker crashes removes the previous run's child sessions. A root's `wait_for_stop` now waits for the new run instead of returning a child error from the crash (#1231).
1 change: 1 addition & 0 deletions changelog.d/1244.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Starting or attaching again on a session that was attached to an external program now releases its child processes so they can keep running. Previously, replacing the session asked the adapter to terminate them (#1244).
9 changes: 5 additions & 4 deletions docs/architecture/session-tree.md
Original file line number Diff line number Diff line change
Expand Up @@ -264,10 +264,11 @@ Two measured effects the answers name:
children's connections live in the parent's worker, so they cannot outlive the detach; the
parent-side order with several children is the one step here the spikes did not measure, and the
M1 suite does.
- `restart_debugging` on a parent ends the previous run's children with that run: they are closed
and removed (a relaunch is a new program, and children belong to a run), and the restart answer
says `childrenClosed: n`. Neither detach nor restart ever classifies children as `error`; that row
of the cascade table is for a worker that dies unexpectedly.
- When a launch or attach replaces a run on the same root, it removes the previous run's child
rows before starting the next one. This includes rows left for inspection after a worker crash.
The old run determines what happens to live child processes. Replacing an attached run releases
its children with `disconnect(terminateDebuggee: false)`. Replacing a launched run follows each
adapter's child-close semantics. A relaunch reports the number of rows it removed in `childrenClosed`.

### On by default, opt-out per launch

Expand Down
15 changes: 5 additions & 10 deletions src/session/attach/attach-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,17 +186,12 @@ export class AttachController {
attachLocality = attachLocalityOf(addressing);
}

if (session.proxyManager || session.pendingProxyStop || session.deferredWorkerStop) {
if (session.proxyManager) {
this.ctx.logger.warn(
`[SessionManager] Session ${sessionId} already has an active proxy. Terminating before attaching.`
);
}
// Session-preserving teardown (same landmine as startDebugging, #238);
// a stop() still in flight from a terminal event handler is awaited
// too, so the new worker never races the old one's exit (#502).
await this.ctx.stopProxyPreservingSession(session);
if (session.proxyManager) {
this.ctx.logger.warn(
`[SessionManager] Session ${sessionId} already has an active proxy. Terminating before attaching.`
);
}
await this.ctx.stopProxyPreservingSession(session);

// Update to INITIALIZING state and set lifecycle to ACTIVE
this.ctx.updateState(session, SessionState.INITIALIZING);
Expand Down
22 changes: 5 additions & 17 deletions src/session/launch/debug-launcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -482,24 +482,12 @@ export class DebugLauncher {
return this.dryRun(session, { scriptPath, scriptArgs, dapLaunchArgs, adapterLaunchConfig, breakOnExceptions });
}

// Children belong to a run (issue #1081): a relaunch closes the previous
// run's, and the answer says how many.
let childrenClosed = 0;
if (session.proxyManager || session.pendingProxyStop || session.deferredWorkerStop) {
if (session.proxyManager) {
this.ctx.logger.warn(
`[SessionManager] Session ${sessionId} already has an active proxy. Terminating before starting new.`
);
}
// Session-preserving teardown: closeSession here used to REMOVE the
// session from the store, so the state update below threw
// SessionNotFoundError and the session was silently destroyed (#238).
// Not gated on a live handle alone: a terminal event handler nulls
// proxyManager and leaves its stop() in flight as pendingProxyStop,
// which this awaits too (#502) — otherwise the relaunch races the old
// worker's exit (a debuggee port still bound, lastProxyPid overwritten).
childrenClosed = (await this.ctx.stopProxyPreservingSession(session)) ?? 0;
if (session.proxyManager) {
this.ctx.logger.warn(
`[SessionManager] Session ${sessionId} already has an active proxy. Terminating before starting new.`
);
}
const childrenClosed = await this.ctx.stopProxyPreservingSession(session);

// Update to INITIALIZING state and set lifecycle to ACTIVE
this.ctx.updateState(session, SessionState.INITIALIZING);
Expand Down
23 changes: 13 additions & 10 deletions src/session/session-manager-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1020,9 +1020,7 @@ export abstract class SessionManagerCore extends EventEmitter {
const finishClose = this.beginSubtreeClose(sessionId);
try {
for (const descendant of this.descendantsDeepestFirst(sessionId)) {
// A child whose adapter can only release it (js-debug, issue #1082)
// is closed with its target kept, whatever the cascade.
const releaseChild = releaseDescendants || (descendant.proxyManager !== undefined && this.childCloseSemantics(descendant) === 'release');
const releaseChild = this.shouldReleaseDescendant(descendant, releaseDescendants);
// Capture each outcome at its own close, not before the cascade: a
// later child can end naturally while an earlier close is awaited.
const released = releaseChild || descendant.programEndExplanation?.data?.released === true;
Expand Down Expand Up @@ -1129,6 +1127,11 @@ export abstract class SessionManagerCore extends EventEmitter {
}
}

/** A borrowed tree keeps its external targets. A release-only adapter keeps them on either kind of tree. */
private shouldReleaseDescendant(descendant: ManagedSession, preserveTargets: boolean): boolean {
return preserveTargets || (descendant.proxyManager !== undefined && this.childCloseSemantics(descendant) === 'release');
}

/**
* Where a child session's program output is read (issue #1082): the id of
* its tree's root when the adapter delivers the whole tree's stdout and
Expand Down Expand Up @@ -1276,12 +1279,10 @@ export abstract class SessionManagerCore extends EventEmitter {
}

/**
* Tear down the session's proxy (listeners, worker process, adapter slot)
* while PRESERVING the session record — breakpoints, output buffer, launch
* spec and lifecycle state survive for a relaunch. Contrast closeSession,
* which removes the session from the store entirely. stop() runs cleanup()
* even without a live proxy process, so the adapter registry slot is
* always released (issue #238).
* Close descendants and drain the previous worker while preserving the root
* session and its breakpoints (#238, #502). Launch and attach both call this
* before writing the new run. A worker exit can clear every proxy handle
* while its children's terminal rows are still available for inspection (#1231).
*/
protected async stopProxyPreservingSession(session: ManagedSession): Promise<number> {
const finishClose = this.beginSubtreeClose(session.id);
Expand All @@ -1297,9 +1298,11 @@ export abstract class SessionManagerCore extends EventEmitter {
clearPauseIntent(session);
// Children belong to a run (issue #1081): a relaunch, or the teardown of
// a launch that failed, closes the previous run's children first.
const preserveTargets = !session.parentSessionId && borrowsProgram(session);
let childrenClosed = 0;
for (const descendant of this.descendantsDeepestFirst(session.id)) {
if (await this.closeSingleSession(descendant.id)) {
const releaseChild = this.shouldReleaseDescendant(descendant, preserveTargets);
if (await this.closeSingleSession(descendant.id, { releaseChild })) {
childrenClosed += 1;
}
}
Expand Down
50 changes: 50 additions & 0 deletions tests/core/unit/session/session-manager-child-sessions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,33 @@ describe('SessionManager child sessions (issue #1081)', () => {
expect(dependencies.mockProxyManager.stopCalls).toBe(1);
});

it.each(['launch', 'attach'] as const)('a new %s retires the children of a crashed worker (#1231)', async (mode) => {
const { rootId, childId, view } = await rootWithChild();
const proxy = dependencies.mockProxyManager;
// A process exit reaches the child views first, then the root. An IPC
// termination status would also carry an 'expected' flag and schedule a reap.
view.onWorkerExit(1);
proxy.simulateExit(1);
expect(sessionManager.getSession(childId)!.state).toBe(SessionState.ERROR);
expect(sessionManager.getSession(rootId)!.state).toBe(SessionState.ERROR);

if (mode === 'launch') {
const started = await sessionManager.startDebugging(rootId, 'next.py', undefined, { stopOnEntry: false });
expect(started.success, started.error).toBe(true);
expect(started.data?.childrenClosed).toBe(1);
} else {
proxy.setDapRequestHandler(async (command) => command === 'threads'
? { success: true, body: { threads: [{ id: 1, name: 'main' }] } }
: { success: true, body: {} });
const attached = await sessionManager.attachToProcess(rootId, { port: 5678, stopOnEntry: false });
expect(attached.success, attached.error).toBe(true);
}

const wait = await sessionManager.waitForStop(rootId, 100);
expect(wait.data).toMatchObject({ sessionId: rootId, pending: true });
expect(sessionManager.getAllSessions().map((s) => s.id)).toEqual([rootId]);
});

it.each(['exit', 'error'] as const)("a child connection's failure (%s) points at its tree's one log, the root's, never a file named after the child (#1222)", async (event) => {
const { rootId, childId, view } = await rootWithChild();
const root = sessionManager.getSession(rootId)!;
Expand Down Expand Up @@ -751,6 +778,27 @@ describe('SessionManager child sessions (issue #1081)', () => {
expect(sessionManager.getAllSessions()).toHaveLength(0);
});

it.each(['launch', 'attach'] as const)('a new %s releases every child of the previous borrowed run (#1244)', async (mode) => {
const { rootId, childView, grandchildView } = await tree();
const previousRun = sessionManager.getSession(rootId)!.run;
previousRun.attachMode = true;
previousRun.programOwnership = 'borrowed';
// The mock reuses its proxy on the new run. Suppress the old worker's deferred exit.
vi.spyOn(dependencies.mockProxyManager, 'stop').mockResolvedValue();
dependencies.mockProxyManager.setDapRequestHandler(async (command) => command === 'threads'
? { success: true, body: { threads: [{ id: 1, name: 'main' }] } }
: { success: true, body: {} });

const result = mode === 'launch'
? await sessionManager.startDebugging(rootId, 'next.py', undefined, { stopOnEntry: false })
: await sessionManager.attachToProcess(rootId, { port: 5678, stopOnEntry: false });

expect(result.success, result.error).toBe(true);
expect(childView.stopOptions).toEqual([{ terminateDebuggee: false }]);
expect(grandchildView.stopOptions).toEqual([{ terminateDebuggee: false }]);
expect(sessionManager.getAllSessions().map((s) => s.id)).toEqual([rootId]);
});

it('a session with no tree answers the bare outcome, and a missing one closed: false', async () => {
const rootId = await startRoot();
expect(await sessionManager.closeSessionReporting(rootId)).toEqual({ closed: true, closedSessionIds: [rootId] });
Expand Down Expand Up @@ -1148,6 +1196,8 @@ describe('SessionManager child sessions (issue #1081)', () => {
expect(restarted.success).toBe(true);
expect(restarted.data?.childrenClosed).toBe(2);
expect(restarted.data?.children).toBeUndefined();
// The old launch owned this target. Its adapter's default close ends it.
expect(childView.stopOptions).toEqual([undefined]);
expect(removed).toHaveBeenCalledTimes(2);
expect(removed).not.toHaveBeenCalledWith(rootId);
});
Expand Down
14 changes: 8 additions & 6 deletions tests/core/unit/session/session-manager-state.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,17 @@ describe('SessionManager - State Machine Integrity', () => {
executablePath: 'python'
});

// CREATED → INITIALIZING. The transition is no longer synchronous: the
// issue-#360 launch gate awaits an availability probe first, so flush
// microtasks (not timers) before observing the state.
expect(sessionManager.getSession(session.id)?.state).toBe(SessionState.CREATED);
// Observe the state as the adapter finishes configuring, before the
// launcher's event handlers advance it to the entry stop.
let stateAtConfiguration: SessionState | undefined;
dependencies.mockProxyManager.once('adapter-configured', () => {
stateAtConfiguration = sessionManager.getSession(session.id)?.state;
});
const startPromise = sessionManager.startDebugging(session.id, 'test.py');
await Promise.resolve().then(() => {}).then(() => {}).then(() => {});
expect(sessionManager.getSession(session.id)?.state).toBe(SessionState.INITIALIZING);

await vi.runAllTimersAsync();
await startPromise;
expect(stateAtConfiguration).toBe(SessionState.INITIALIZING);

// INITIALIZING → PAUSED (because stopOnEntry=true by default)
expect(sessionManager.getSession(session.id)?.state).toBe(SessionState.PAUSED);
Expand Down
Loading