Skip to content

Commit 95b13a2

Browse files
fix(mcp): release session slots independently (ENG-1554) (e2e-inc#2378)
* fix(mcp): release session slots independently (ENG-1554) * fix(core): guard abandoned process starts and concurrent stops * fix(core): stop a shared process when abort wins after start settled * test(core): rename a shadowed variable in the late abort case --------- Co-authored-by: michal-e2e <357875193+michal-e2e@users.noreply.github.com> Co-authored-by: Oskar Kwaśniewski <oskar@okwasniewski.com>
1 parent c2d656a commit 95b13a2

10 files changed

Lines changed: 414 additions & 48 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"@e2e-dev/core": patch
3+
"e2e": patch
4+
---
5+
6+
Closing an MCP session frees its slot even while another session's app is still stopping.

‎docs/reference/mcp.mdx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -171,8 +171,10 @@ call {tool: "tap", args: {target: "n42"}, session: "<id>"}
171171
#### `close_session`
172172

173173
Saves a recording still running, ends the attempt, and disposes the engine.
174-
It stops the app processes the session started once no other session uses
175-
them. Use it on an attachment to detach and leave the test held.
174+
It stops app processes and services when the session is their last user,
175+
with app processes stopping before services. The session frees its slot
176+
when its own cleanup finishes, even while another app is still stopping.
177+
Use it on an attachment to detach and leave the test held.
176178

177179
```txt
178180
close_session {session: "<id>"}

‎packages/core/src/run/managed-process.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@ export interface ManagedProcessHooks {
158158
*/
159159
export class ManagedProcess {
160160
private child: ChildProcess | null = null;
161+
private stopping: Promise<void> | undefined;
161162
private watching = false;
162163
private reusedExisting = false;
163164
private spawnedProcess = false;
@@ -430,16 +431,19 @@ export class ManagedProcess {
430431
/** Gracefully terminates the whole process group, then force-kills. A reused process was never ours to stop. */
431432
async stop(): Promise<void> {
432433
if (this.reusedExisting) return;
434+
if (this.stopping !== undefined) return this.stopping;
433435
this.watching = false;
434436
const child = this.child;
435437
this.child = null;
436438
if (child === null) return;
437439
const stopped = this.terminate(child);
440+
this.stopping = stopped;
438441
stopping.add(stopped);
439442
try {
440443
await stopped;
441444
} finally {
442445
stopping.delete(stopped);
446+
if (this.stopping === stopped) this.stopping = undefined;
443447
}
444448
}
445449

‎packages/core/src/run/process-pool.ts‎

Lines changed: 82 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ export const UNSHARED: ProcessPool = { acquire: (_key, start, signal) => start(s
2626

2727
interface SharedEntry<Held extends AppProcesses> {
2828
users: number;
29+
/** Set once `start` has actually been called after any earlier stop finished draining. */
30+
startedWork: boolean;
2931
/** Set once the start settled: from then on an attempt giving up abandons nothing. */
3032
settled: boolean;
3133
/** Attempts still waiting on the start whose own signal has not aborted. */
@@ -52,82 +54,125 @@ export class SharedProcesses<Held extends AppProcesses = AppProcesses> implement
5254
/** Stops still running, and starts abandoned, by key. */
5355
private readonly draining = new Map<string, Promise<unknown>>();
5456

57+
/** Wait on cancellation when the caller still holds dependencies of the process it abandons. */
58+
constructor(private readonly options: { readonly waitForAbandonedStart?: boolean } = {}) {}
59+
5560
async acquire(key: string, start: (signal: AbortSignal) => Promise<Held>, signal: AbortSignal): Promise<Held> {
5661
let entry = this.entries.get(key);
5762
if (entry === undefined) {
5863
// A stop that failed has still ended its process: the fresh start goes ahead.
5964
const drained = (this.draining.get(key) ?? Promise.resolve()).catch(() => undefined);
6065
const abandon = new AbortController();
61-
const created: SharedEntry<Held> = { users: 0, settled: false, waiting: 0, abandon, started: drained.then(() => start(abandon.signal)) };
62-
created.started.then(
63-
() => {
64-
created.settled = true;
65-
},
66-
() => {
67-
created.settled = true;
68-
this.forget(key, created);
69-
},
70-
);
66+
const created: SharedEntry<Held> = {
67+
users: 0,
68+
startedWork: false,
69+
settled: false,
70+
waiting: 0,
71+
abandon,
72+
started: drained.then(async () => {
73+
if (abandon.signal.aborted) {
74+
throw new InfrastructureError('CANCELLED', 'gave up waiting on a shared process start');
75+
}
76+
created.startedWork = true;
77+
try {
78+
const held = await start(abandon.signal);
79+
created.settled = true;
80+
return held;
81+
} catch (cause) {
82+
created.settled = true;
83+
this.forget(key, created);
84+
throw cause;
85+
}
86+
}),
87+
};
88+
// An abandoned start settles without callers; keep the rejection handled.
89+
created.started.catch(() => undefined);
7190
this.entries.set(key, created);
7291
entry = created;
7392
}
7493
const shared = entry;
7594
shared.users += 1;
7695
shared.waiting += 1;
96+
let abandoned: Promise<void> | undefined;
7797
const giveUp = (): void => {
7898
shared.waiting -= 1;
7999
if (shared.waiting > 0 || shared.settled) return;
80100
shared.abandon.abort();
81101
this.forget(key, shared);
102+
// Nothing was started yet while waiting on an earlier drain: keep the prior drain entry intact.
103+
if (!shared.startedWork) return;
82104
// A start that completes despite the abort has nobody left to stop it: it stops here.
83-
this.draining.set(
84-
key,
85-
shared.started.then(
86-
(started) => started.stop(() => undefined),
87-
() => undefined,
88-
),
105+
const cleanup = shared.started.then(
106+
(started) => started.stop(() => undefined),
107+
() => undefined,
89108
);
109+
const tracked = cleanup.finally(() => {
110+
if (this.draining.get(key) === tracked) {
111+
this.draining.delete(key);
112+
}
113+
});
114+
abandoned = tracked;
115+
this.draining.set(key, tracked);
90116
};
91117
if (signal.aborted) giveUp();
92118
else signal.addEventListener('abort', giveUp, { once: true });
93119

94120
let processes: Held;
95121

96122
try {
97-
// An attempt that gives up stops waiting at once, whether or not others still wait on the start.
98123
processes = await Promise.race([shared.started, cancelled(signal, shared.started)]);
124+
if (abandoned !== undefined || shared.abandon.signal.aborted) {
125+
throw new InfrastructureError('CANCELLED', 'gave up waiting on a shared process start');
126+
}
99127
} catch (cause) {
100-
shared.users -= 1;
128+
if (abandoned !== undefined) {
129+
shared.users -= 1;
130+
if (this.options.waitForAbandonedStart) {
131+
await abandoned.catch(() => undefined);
132+
}
133+
throw cause;
134+
}
135+
// The start can settle a tick before this attempt's abort wins the race: nothing was
136+
// abandoned then, so the attempt gives back its hold like any other, or nobody stops the process.
137+
const held = shared.settled && !shared.abandon.signal.aborted ? await shared.started.catch(() => undefined) : undefined;
138+
if (held === undefined) {
139+
shared.users -= 1;
140+
throw cause;
141+
}
142+
const released = this.release(key, shared, held, () => undefined).catch(() => undefined);
143+
if (this.options.waitForAbandonedStart) {
144+
await released;
145+
}
101146
throw cause;
102147
} finally {
103148
signal.removeEventListener('abort', giveUp);
104149
if (!signal.aborted) shared.waiting -= 1;
105150
}
106151

107-
return {
108-
...processes,
109-
stop: async (onFailure) => {
110-
shared.users -= 1;
152+
return { ...processes, stop: (onFailure) => this.release(key, shared, processes, onFailure) };
153+
}
111154

112-
if (shared.users > 0) {
113-
return;
114-
}
155+
/** Gives back one hold on `entry`; the last one stops the process and keeps the stop in `draining` until it is done. */
156+
private async release(key: string, entry: SharedEntry<Held>, processes: Held, onFailure: Parameters<Held['stop']>[0]): Promise<void> {
157+
entry.users -= 1;
115158

116-
this.forget(key, shared);
159+
if (entry.users > 0) {
160+
return;
161+
}
117162

118-
const stopping = processes.stop(onFailure);
163+
this.forget(key, entry);
119164

120-
this.draining.set(key, stopping);
165+
const stopping = processes.stop(onFailure);
121166

122-
try {
123-
await stopping;
124-
} finally {
125-
if (this.draining.get(key) === stopping) {
126-
this.draining.delete(key);
127-
}
128-
}
129-
},
130-
};
167+
this.draining.set(key, stopping);
168+
169+
try {
170+
await stopping;
171+
} finally {
172+
if (this.draining.get(key) === stopping) {
173+
this.draining.delete(key);
174+
}
175+
}
131176
}
132177

133178
/**

‎packages/e2e/src/mcp/session.ts‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -150,8 +150,8 @@ export interface SessionHostOptions {
150150
/** Owns the live sessions, up to the server's limit, and the fixed MCP tools that drive them. */
151151
export class SessionHost {
152152
private readonly sessions: SessionRegistry<Session>;
153-
/** Sessions on one app command share its process: the last one to close stops it. */
154-
private readonly apps = new SharedProcesses();
153+
/** Sessions share app commands and keep their services until an abandoned app start has stopped. */
154+
private readonly apps = new SharedProcesses({ waitForAbandonedStart: true });
155155
/**
156156
* Sessions on the same config file share its services, keyed by the file's
157157
* absolute path. The first session starts them, and the last one to close
@@ -280,11 +280,6 @@ export class SessionHost {
280280

281281
const cleanupErrors = attempt === undefined ? [] : [...await attempt.close()];
282282

283-
// An open that was cancelled while its app command was starting leaves
284-
// that start to stop in the background, so wait for it before the last
285-
// hold on the services can stop them under the app.
286-
await this.apps.drained();
287-
288283
await services.stop((cause) => {
289284
cleanupErrors.push(serializeError(classifyError(cause), { phase: 'cleanup', redact: processSecrets.redact }));
290285
});

‎packages/e2e/tests/integration/services.test.ts‎

Lines changed: 123 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1867,7 +1867,7 @@ test('reads a service', async ({ services }) => {
18671867

18681868
/** `e2e mcp` running in `dir` over stdio, with a client that sends requests and tool calls to it. */
18691869
async function mcpServer(dir: string) {
1870-
const server = spawn(process.execPath, [CLI, 'mcp'], { cwd: dir, env: { ...process.env, CI: '' }, stdio: ['pipe', 'pipe', 'pipe'] });
1870+
const server = spawn(process.execPath, [CLI, 'mcp', '--max-sessions', '2'], { cwd: dir, env: { ...process.env, CI: '', E2E_TELEMETRY_DISABLED: '1' }, stdio: ['pipe', 'pipe', 'pipe'] });
18711871
const output = { stderr: '' };
18721872

18731873
server.stderr.on('data', (chunk: Buffer) => {
@@ -1907,6 +1907,21 @@ test('reads a service', async ({ services }) => {
19071907
return reply;
19081908
};
19091909

1910+
const sendRequest = (method: string, params: object) => {
1911+
nextId += 1;
1912+
1913+
const id = nextId;
1914+
const reply = new Promise<McpMessage>((resolve) => replies.set(id, resolve));
1915+
1916+
server.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`);
1917+
1918+
return { id, reply };
1919+
};
1920+
1921+
const notify = (method: string, params: object) => {
1922+
server.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', method, params })}\n`);
1923+
};
1924+
19101925
const callTool = async (name: string, args: object): Promise<string> => {
19111926
const reply = await request('tools/call', { name, arguments: args });
19121927
const text = reply.result?.content.map((part) => part.text).join('\n') ?? '';
@@ -1920,9 +1935,115 @@ test('reads a service', async ({ services }) => {
19201935

19211936
server.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' })}\n`);
19221937

1923-
return { server, output, exited, request, callTool };
1938+
return { server, output, exited, request, sendRequest, notify, callTool };
19241939
}
19251940

1941+
/** Holds the app's shutdown until the test releases it. */
1942+
function heldAppProject(port: number, ready: boolean): FixtureProject {
1943+
const project = createProject({
1944+
'services.ts': SERVICES,
1945+
'server.cjs': SERVER.replace(" appendFileSync('events.log', 'app stop\\n');\n process.exit(0);", `
1946+
appendFileSync('events.log', 'app stopping\\n');
1947+
const timer = setInterval(() => {
1948+
if (!require('node:fs').existsSync('release-stop')) return;
1949+
clearInterval(timer);
1950+
appendFileSync('events.log', 'app stop\\n');
1951+
process.exit(0);
1952+
}, 10);`),
1953+
'e2e.config.ts': CONFIG
1954+
.replace("url: 'http://127.0.0.1:0',", `url: 'http://127.0.0.1:${port}',${ready ? '' : " readyUrl: 'http://127.0.0.1:1/',"}`)
1955+
.replace("PORT: '{port}'", `PORT: '${port}'`)
1956+
.replace('shutdownTimeout: 2000', 'startupTimeout: 60_000, shutdownTimeout: 15_000')
1957+
.replace(' ],', " { name: 'independent', platform: 'fake', engine: createFakeEngine().engine },\n ],"),
1958+
});
1959+
projects.push(project);
1960+
return project;
1961+
}
1962+
1963+
it.skipIf(process.platform === 'win32')('frees an unrelated session slot while another app is still stopping', async () => {
1964+
const project = heldAppProject(await freePort(), true);
1965+
const { server, exited, callTool } = await mcpServer(project.dir);
1966+
1967+
try {
1968+
const slow = sessionId(await callTool('open_session', { target: 'fake' }));
1969+
const other = sessionId(await callTool('open_session', { target: 'independent' }));
1970+
const closing = callTool('close_session', { session: slow });
1971+
try {
1972+
await expect.poll(() => eventLines(project), { timeout: 5_000 }).toContain('app stopping');
1973+
await expect(Promise.race([
1974+
callTool('close_session', { session: other }),
1975+
sleep(2_000, 'the unrelated close is still waiting', { ref: false }),
1976+
])).resolves.toContain(`Session ${other} closed`);
1977+
const next = sessionId(await callTool('open_session', { target: 'independent' }));
1978+
expect(next).toBeTruthy();
1979+
expect(eventLines(project)).not.toContain('app stop');
1980+
expect(eventLines(project)).not.toContain('stop alpha');
1981+
} finally {
1982+
writeFileSync(path.join(project.dir, 'release-stop'), '');
1983+
await closing;
1984+
}
1985+
} finally {
1986+
server.stdin.end();
1987+
expect(await exited).toBe(0);
1988+
}
1989+
});
1990+
1991+
it.skipIf(process.platform === 'win32')('stops a cancelled app start before releasing its services on server shutdown', async () => {
1992+
const port = await freePort();
1993+
const project = heldAppProject(port, false);
1994+
const { server, exited, request } = await mcpServer(project.dir);
1995+
1996+
try {
1997+
void request('tools/call', { name: 'open_session', arguments: { target: 'fake' } });
1998+
await expect.poll(() => fetch(`http://127.0.0.1:${port}`).then((response) => response.ok, () => false), { timeout: 5_000 }).toBe(true);
1999+
server.stdin.end();
2000+
await expect.poll(() => eventLines(project), { timeout: 5_000 }).toContain('app stopping');
2001+
} finally {
2002+
writeFileSync(path.join(project.dir, 'release-stop'), '');
2003+
server.stdin.end();
2004+
expect(await exited).toBe(0);
2005+
}
2006+
2007+
expect(eventLines(project)).toEqual(['start alpha', 'start beta', 'env', `app start ${port} http://alpha.test`, 'app stopping', 'app stop', 'stop beta', 'stop alpha']);
2008+
});
2009+
2010+
it.skipIf(process.platform === 'win32')('frees the slot when a queued reopen of a stopping target is cancelled', async () => {
2011+
const port = await freePort();
2012+
const project = heldAppProject(port, true);
2013+
const { server, exited, sendRequest, notify, callTool } = await mcpServer(project.dir);
2014+
2015+
try {
2016+
const slow = sessionId(await callTool('open_session', { target: 'fake' }));
2017+
const closing = callTool('close_session', { session: slow });
2018+
try {
2019+
await expect.poll(() => eventLines(project), { timeout: 5_000 }).toContain('app stopping');
2020+
const queued = sendRequest('tools/call', { name: 'open_session', arguments: { target: 'fake' } });
2021+
await expect.poll(() => eventLines(project).filter((line) => line === 'env').length, { timeout: 5_000 }).toBe(2);
2022+
await sleep(100);
2023+
notify('notifications/cancelled', { requestId: queued.id, reason: 'give up waiting on slow stop' });
2024+
let other = '';
2025+
await expect.poll(async () => {
2026+
const reply = await sendRequest('tools/call', { name: 'open_session', arguments: { target: 'independent' } }).reply;
2027+
if (reply.result?.isError === true) return false;
2028+
const text = reply.result?.content.map((part) => part.text).join('\n') ?? '';
2029+
other = sessionId(text);
2030+
return other.length > 0;
2031+
}, { timeout: 2_000 }).toBe(true);
2032+
expect(eventLines(project)).not.toContain('app stop');
2033+
expect(eventLines(project)).not.toContain('stop alpha');
2034+
await callTool('close_session', { session: other });
2035+
} finally {
2036+
writeFileSync(path.join(project.dir, 'release-stop'), '');
2037+
await closing;
2038+
}
2039+
} finally {
2040+
server.stdin.end();
2041+
expect(await exited).toBe(0);
2042+
}
2043+
2044+
expect(eventLines(project)).toEqual(['start alpha', 'start beta', 'env', `app start ${port} http://alpha.test`, 'app stopping', 'env', 'app stop', 'stop beta', 'stop alpha']);
2045+
});
2046+
19262047
it('stops the app and then the services when the client closes stdin with sessions open, and leaves no process behind', async () => {
19272048
const port = await freePort();
19282049

0 commit comments

Comments
 (0)