1
0

mcp-startup-orphan.test.ts 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /**
  2. * Startup-orphan regression tests (#1185) — spawn-level.
  3. *
  4. * Reproduced bug: an MCP host kills the launcher chain within the server's
  5. * first ~100ms while keeping the stdio pipes open (config probe, instant
  6. * cancel, initialize-timeout teardown; Rust hosts that kill a child without
  7. * dropping its stdio handles hold pipes exactly like this). The server booted
  8. * already reparented, so its PPID-watchdog baseline read 1 (blind forever),
  9. * stdin never EOF'd, and the process lived until the HOST exited — one ~30MB
  10. * node process leaked per occurrence.
  11. *
  12. * These tests exercise the last-resort defense end-to-end on the real built
  13. * binary: a server that receives no MCP traffic shuts itself down when the
  14. * startup-handshake timeout lapses, and a server that got even one message
  15. * is never touched by it.
  16. *
  17. * POSIX-only: the blind spot is a POSIX reparenting artifact (Windows never
  18. * reparents, so its liveness-based check keeps working with a late baseline),
  19. * and the suite avoids the known Windows EPERM teardown quirk of spawned
  20. * `serve --mcp` children holding the temp cwd open.
  21. */
  22. import { describe, it, expect, beforeEach, afterEach } from 'vitest';
  23. import { spawn, ChildProcessWithoutNullStreams } from 'child_process';
  24. import * as fs from 'fs';
  25. import * as os from 'os';
  26. import * as path from 'path';
  27. const BIN = path.resolve(__dirname, '../dist/bin/codegraph.js');
  28. function spawnServer(cwd: string, handshakeTimeoutMs: number): ChildProcessWithoutNullStreams {
  29. return spawn(process.execPath, [BIN, 'serve', '--mcp'], {
  30. cwd,
  31. stdio: ['pipe', 'pipe', 'pipe'],
  32. env: {
  33. ...process.env,
  34. // Direct mode: hermetic (no detached daemon to leak from the suite).
  35. // The backstop is armed identically on the proxy path.
  36. CODEGRAPH_NO_DAEMON: '1',
  37. // Single process (skip the --liftoff-only re-exec) so exit-code and
  38. // liveness assertions observe the server itself.
  39. CODEGRAPH_WASM_RELAUNCHED: '1',
  40. // One less helper child; the liveness watchdog is not under test.
  41. CODEGRAPH_NO_WATCHDOG: '1',
  42. CODEGRAPH_TELEMETRY: '0',
  43. DO_NOT_TRACK: '1',
  44. CODEGRAPH_STARTUP_HANDSHAKE_TIMEOUT_MS: String(handshakeTimeoutMs),
  45. },
  46. }) as ChildProcessWithoutNullStreams;
  47. }
  48. function waitForExit(child: ChildProcessWithoutNullStreams, timeoutMs: number): Promise<number | null> {
  49. return new Promise((resolve, reject) => {
  50. if (child.exitCode !== null) { resolve(child.exitCode); return; }
  51. const timer = setTimeout(
  52. () => reject(new Error(`server did not exit within ${timeoutMs}ms`)),
  53. timeoutMs
  54. );
  55. child.on('exit', (code) => { clearTimeout(timer); resolve(code); });
  56. });
  57. }
  58. const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
  59. describe.skipIf(process.platform === 'win32')('startup-orphan backstop (#1185)', () => {
  60. let dir: string;
  61. let child: ChildProcessWithoutNullStreams | null = null;
  62. beforeEach(() => {
  63. dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-orphan-'));
  64. });
  65. afterEach(() => {
  66. if (child && child.exitCode === null) child.kill('SIGKILL');
  67. child = null;
  68. fs.rmSync(dir, { recursive: true, force: true });
  69. });
  70. it('a server that never receives MCP traffic shuts itself down', async () => {
  71. child = spawnServer(dir, 1000);
  72. let stderr = '';
  73. child.stderr.on('data', (c) => { stderr += c.toString(); });
  74. // Keep our pipe ends open the whole time — the abandoned-launch shape:
  75. // no stdin EOF ever arrives; only the backstop can reap the server.
  76. const code = await waitForExit(child, 15_000);
  77. expect(code).toBe(0);
  78. expect(stderr).toContain('No MCP traffic since startup');
  79. }, 20_000);
  80. it('a server that got an initialize is never reaped by the backstop', async () => {
  81. child = spawnServer(dir, 1000);
  82. child.stdin.write(JSON.stringify({
  83. jsonrpc: '2.0', id: 1, method: 'initialize',
  84. params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 't', version: '0' } },
  85. }) + '\n');
  86. // Well past the 1s backstop window: the first byte disarmed it for good.
  87. await sleep(3000);
  88. expect(child.exitCode).toBeNull();
  89. // Normal lifecycle still intact: closing stdin ends the session.
  90. child.stdin.end();
  91. const code = await waitForExit(child, 10_000);
  92. expect(code).toBe(0);
  93. }, 20_000);
  94. });