-
-
Notifications
You must be signed in to change notification settings - Fork 256
Expand file tree
/
Copy pathrepro-mcp-lifecycle-leak.ts
More file actions
331 lines (290 loc) · 9.01 KB
/
repro-mcp-lifecycle-leak.ts
File metadata and controls
331 lines (290 loc) · 9.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import { spawn } from 'node:child_process';
import process from 'node:process';
interface CliOptions {
iterations: number;
closeDelayMs: number;
settleMs: number;
shutdownMode: 'graceful-stdin' | 'parent-hard-exit';
}
interface PeerProcess {
pid: number;
ppid: number;
ageSeconds: number;
rssKb: number;
command: string;
}
function parseArgs(argv: string[]): CliOptions {
const options: CliOptions = {
iterations: 20,
closeDelayMs: 0,
settleMs: 2000,
shutdownMode: 'parent-hard-exit',
};
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
const value = argv[index + 1];
if (arg === '--iterations' && value) {
options.iterations = Number(value);
index += 1;
} else if (arg === '--close-delay-ms' && value) {
options.closeDelayMs = Number(value);
index += 1;
} else if (arg === '--settle-ms' && value) {
options.settleMs = Number(value);
index += 1;
} else if (arg === '--shutdown-mode' && value) {
if (value !== 'graceful-stdin' && value !== 'parent-hard-exit') {
throw new Error('--shutdown-mode must be graceful-stdin or parent-hard-exit');
}
options.shutdownMode = value;
index += 1;
}
}
if (!Number.isFinite(options.iterations) || options.iterations < 1) {
throw new Error('--iterations must be a positive number');
}
if (!Number.isFinite(options.closeDelayMs) || options.closeDelayMs < 0) {
throw new Error('--close-delay-ms must be a non-negative number');
}
if (!Number.isFinite(options.settleMs) || options.settleMs < 0) {
throw new Error('--settle-ms must be a non-negative number');
}
return options;
}
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function isLikelyMcpCommand(command: string): boolean {
const normalized = command.toLowerCase();
return (
/(^|\s)mcp(\s|$)/.test(normalized) &&
!/(^|\s)daemon(\s|$)/.test(normalized) &&
(normalized.includes('xcodebuildmcp') ||
normalized.includes('build/cli.js') ||
normalized.includes('/cli.js'))
);
}
function parseElapsedSeconds(value: string): number | null {
const trimmed = value.trim();
if (!trimmed) {
return null;
}
const daySplit = trimmed.split('-');
const timePart = daySplit.length === 2 ? daySplit[1] : daySplit[0];
const dayCount = daySplit.length === 2 ? Number(daySplit[0]) : 0;
const parts = timePart.split(':').map((part) => Number(part));
if (!Number.isFinite(dayCount) || parts.some((part) => !Number.isFinite(part))) {
return null;
}
if (parts.length === 1) {
return dayCount * 86400 + parts[0];
}
if (parts.length === 2) {
return dayCount * 86400 + parts[0] * 60 + parts[1];
}
if (parts.length === 3) {
return dayCount * 86400 + parts[0] * 3600 + parts[1] * 60 + parts[2];
}
return null;
}
async function sampleMcpProcesses(): Promise<PeerProcess[]> {
return new Promise((resolve, reject) => {
const child = spawn('ps', ['-axo', 'pid=,ppid=,etime=,rss=,command='], {
stdio: ['ignore', 'pipe', 'pipe'],
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk: Buffer) => {
stdout += chunk.toString();
});
child.stderr.on('data', (chunk: Buffer) => {
stderr += chunk.toString();
});
child.on('error', reject);
child.on('close', (code) => {
if (code !== 0) {
reject(new Error(stderr || `ps exited with code ${code}`));
return;
}
const processes = stdout
.split('\n')
.map((line) => line.trim())
.filter(Boolean)
.map((line) => {
const match = line.match(/^(\d+)\s+(\d+)\s+(\S+)\s+(\d+)\s+(.+)$/);
if (!match) {
return null;
}
const ageSeconds = parseElapsedSeconds(match[3]);
return {
pid: Number(match[1]),
ppid: Number(match[2]),
ageSeconds,
rssKb: Number(match[4]),
command: match[5],
};
})
.filter((entry): entry is PeerProcess => {
return (
entry !== null &&
Number.isFinite(entry.pid) &&
Number.isFinite(entry.ageSeconds) &&
Number.isFinite(entry.rssKb) &&
isLikelyMcpCommand(entry.command)
);
});
resolve(processes);
});
});
}
interface IterationResult {
helperExited: boolean;
childExited: boolean;
childPid: number | null;
}
async function runGracefulStdinIteration(closeDelayMs: number): Promise<IterationResult> {
return new Promise((resolve) => {
const child = spawn(process.execPath, ['build/cli.js', 'mcp'], {
cwd: process.cwd(),
stdio: ['pipe', 'ignore', 'ignore'],
});
let settled = false;
const finish = (result: IterationResult): void => {
if (settled) {
return;
}
settled = true;
resolve(result);
};
child.once('close', () => {
finish({ helperExited: true, childExited: true, childPid: child.pid ?? null });
});
child.once('error', () => {
finish({ helperExited: false, childExited: false, childPid: child.pid ?? null });
});
setTimeout(() => {
child.stdin.end();
}, closeDelayMs);
setTimeout(
() => {
finish({ helperExited: false, childExited: false, childPid: child.pid ?? null });
},
Math.max(1000, closeDelayMs + 1000),
);
});
}
async function runParentHardExitIteration(closeDelayMs: number): Promise<IterationResult> {
return new Promise((resolve) => {
const helper = spawn(
process.execPath,
[
'scripts/repro-mcp-parent-exit-helper.mjs',
process.execPath,
'build/cli.js',
process.cwd(),
String(closeDelayMs),
],
{
cwd: process.cwd(),
stdio: ['ignore', 'pipe', 'pipe'],
},
);
let childPid: number | null = null;
let settled = false;
let stdout = '';
const finish = (result: IterationResult): void => {
if (settled) {
return;
}
settled = true;
resolve(result);
};
helper.stdout.on('data', (chunk: Buffer) => {
stdout += chunk.toString();
const candidate = stdout.split('\n')[0]?.trim();
if (candidate && /^\d+$/.test(candidate)) {
childPid = Number(candidate);
}
});
helper.once('error', () => {
finish({ helperExited: false, childExited: false, childPid });
});
helper.once('close', (code) => {
finish({ helperExited: code === 0, childExited: false, childPid });
});
setTimeout(
() => {
finish({ helperExited: false, childExited: false, childPid });
},
Math.max(1500, closeDelayMs + 1500),
);
});
}
async function runIteration(options: CliOptions): Promise<IterationResult> {
if (options.shutdownMode === 'parent-hard-exit') {
return runParentHardExitIteration(options.closeDelayMs);
}
return runGracefulStdinIteration(options.closeDelayMs);
}
async function main(): Promise<void> {
const options = parseArgs(process.argv.slice(2));
const before = await sampleMcpProcesses();
const baselinePids = new Set(before.map((entry) => entry.pid));
let helperExitedCount = 0;
let childExitedCount = 0;
const spawnedChildPids = new Set<number>();
for (let index = 0; index < options.iterations; index += 1) {
const result = await runIteration(options);
if (result.helperExited) {
helperExitedCount += 1;
}
if (result.childExited) {
childExitedCount += 1;
}
if (result.childPid !== null) {
spawnedChildPids.add(result.childPid);
}
}
await delay(options.settleMs);
const after = await sampleMcpProcesses();
const lingering = after.filter((entry) => !baselinePids.has(entry.pid));
const lingeringSpawned = lingering.filter((entry) => spawnedChildPids.has(entry.pid));
console.log(
JSON.stringify(
{
shutdownMode: options.shutdownMode,
iterations: options.iterations,
helperExitedCount,
childExitedCount,
spawnedChildPidCount: spawnedChildPids.size,
baselineProcessCount: before.length,
finalProcessCount: after.length,
lingeringProcessCount: lingering.length,
lingeringSpawnedProcessCount: lingeringSpawned.length,
lingeringSpawned: lingeringSpawned.map(({ pid, ppid, ageSeconds, rssKb, command }) => ({
pid,
ppid,
ageSeconds,
rssKb,
command,
})),
lingering: lingering.map(({ pid, ppid, ageSeconds, rssKb, command }) => ({
pid,
ppid,
ageSeconds,
rssKb,
command,
})),
orphanedLingeringCount: lingering.filter((entry) => entry.ppid === 1).length,
maxLingeringRssKb: lingering.reduce((max, entry) => Math.max(max, entry.rssKb), 0),
},
null,
2,
),
);
process.exit(lingeringSpawned.length === 0 ? 0 : 1);
}
void main().catch((error) => {
console.error(error instanceof Error ? error.message : String(error));
process.exit(1);
});