1
0

mcp-daemon.test.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. /**
  2. * Shared MCP daemon — issue #411.
  3. *
  4. * Validates the daemon architecture in `src/mcp/{daemon,proxy,session,index}.ts`
  5. * AFTER the review fixes:
  6. *
  7. * - The daemon is a *detached* background process; every `serve --mcp`
  8. * invocation is a thin proxy to it. Two invocations against one project
  9. * share ONE daemon.
  10. * - Concurrent launchers converge on a single daemon (the must-fix-1
  11. * lockfile-race: an empty-pidfile window used to let a racing candidate
  12. * delete the winner's lock → two daemons).
  13. * - Killing the launcher that spawned the daemon does NOT take the daemon
  14. * down — other attached clients keep working (the must-fix-2 detach: the
  15. * in-process daemon used to die with its launcher's process group and
  16. * orphan on host SIGKILL, regressing #277).
  17. * - A stale lockfile (dead pid) is cleared; `CODEGRAPH_NO_DAEMON=1` opts out;
  18. * the proxy refuses to attach across a version mismatch; the daemon
  19. * idle-times-out after the last client leaves (so a single session can't
  20. * leak a daemon forever).
  21. *
  22. * These tests intentionally spawn real `node dist/bin/codegraph.js` processes
  23. * over real sockets/pipes — the same surface a Claude Code / Cursor / Codex
  24. * install exercises. The daemon logs to `.codegraph/daemon.log` (it has no
  25. * client stderr of its own), so daemon-side assertions read that file.
  26. *
  27. * `realRoot` vs `tempDir`: processes are spawned with the (possibly symlinked)
  28. * `tempDir` as cwd/rootUri — on macOS `os.tmpdir()` lives under `/var`, a
  29. * symlink to `/private/var`, and a spawned child's `process.cwd()` is already
  30. * realpath'd. The daemon canonicalizes the root with `realpathSync`, so all
  31. * path assertions use `realRoot` (the canonical form). That this matches end to
  32. * end is itself the proof the canonicalization works.
  33. */
  34. import { afterEach, beforeEach, describe, expect, it } from 'vitest';
  35. import { ChildProcessWithoutNullStreams, spawn } from 'child_process';
  36. import * as fs from 'fs';
  37. import * as os from 'os';
  38. import * as path from 'path';
  39. import { CodeGraph } from '../src';
  40. import { getDaemonSocketPath } from '../src/mcp/daemon-paths';
  41. import { CodeGraphPackageVersion } from '../src/mcp/version';
  42. const BIN = path.resolve(__dirname, '../dist/bin/codegraph.js');
  43. interface SpawnedServer {
  44. child: ChildProcessWithoutNullStreams;
  45. stdout: string[];
  46. stderr: string[];
  47. }
  48. function spawnServer(cwd: string, env: NodeJS.ProcessEnv = {}): SpawnedServer {
  49. const child = spawn(process.execPath, [BIN, 'serve', '--mcp'], {
  50. cwd,
  51. stdio: ['pipe', 'pipe', 'pipe'],
  52. // #618: the daemon-attach log line is now off by default; opt the test
  53. // harness into it (CODEGRAPH_MCP_LOG_ATTACH=1) so the attach assertions
  54. // below can still observe a successful attach. A per-test env still wins.
  55. env: { CODEGRAPH_MCP_LOG_ATTACH: '1', ...process.env, ...env },
  56. }) as ChildProcessWithoutNullStreams;
  57. // Swallow spawn/EPIPE errors so killing a child mid-write can't surface as an
  58. // unhandled error that crashes the vitest worker.
  59. child.on('error', () => { /* ignore */ });
  60. child.stdin.on('error', () => { /* ignore */ });
  61. const stdout: string[] = [];
  62. const stderr: string[] = [];
  63. let stdoutBuf = '';
  64. let stderrBuf = '';
  65. child.stdout.on('data', (chunk: Buffer) => {
  66. stdoutBuf += chunk.toString('utf8');
  67. let idx: number;
  68. while ((idx = stdoutBuf.indexOf('\n')) !== -1) {
  69. stdout.push(stdoutBuf.slice(0, idx));
  70. stdoutBuf = stdoutBuf.slice(idx + 1);
  71. }
  72. });
  73. child.stderr.on('data', (chunk: Buffer) => {
  74. stderrBuf += chunk.toString('utf8');
  75. let idx: number;
  76. while ((idx = stderrBuf.indexOf('\n')) !== -1) {
  77. stderr.push(stderrBuf.slice(0, idx));
  78. stderrBuf = stderrBuf.slice(idx + 1);
  79. }
  80. });
  81. return { child, stdout, stderr };
  82. }
  83. function sendMessage(child: ChildProcessWithoutNullStreams, msg: unknown): void {
  84. try { child.stdin.write(JSON.stringify(msg) + '\n'); } catch { /* child may be gone */ }
  85. }
  86. function sendInitialize(child: ChildProcessWithoutNullStreams, rootUri: string, id: number): void {
  87. sendMessage(child, {
  88. jsonrpc: '2.0',
  89. id,
  90. method: 'initialize',
  91. params: {
  92. protocolVersion: '2024-11-05',
  93. capabilities: {},
  94. clientInfo: { name: 'test', version: '0.0.0' },
  95. rootUri,
  96. },
  97. });
  98. }
  99. /** Find a JSON-RPC response with the given id (result OR error) on stdout. */
  100. function findResponse(stdout: string[], id: number): any | null {
  101. for (const line of stdout) {
  102. if (!line.trim()) continue;
  103. try {
  104. const parsed = JSON.parse(line);
  105. if (parsed && parsed.id === id && (parsed.result !== undefined || parsed.error !== undefined)) {
  106. return parsed;
  107. }
  108. } catch { /* not JSON */ }
  109. }
  110. return null;
  111. }
  112. function waitFor<T>(
  113. predicate: () => T | undefined | null | false,
  114. timeoutMs: number,
  115. pollMs = 25,
  116. label = '',
  117. ): Promise<T> {
  118. return new Promise((resolve, reject) => {
  119. const started = Date.now();
  120. const tick = () => {
  121. let v: T | undefined | null | false;
  122. try { v = predicate(); } catch (e) { return reject(e); }
  123. if (v) return resolve(v as T);
  124. if (Date.now() - started > timeoutMs) {
  125. // Name the wait: an async stack loses the await site, so an unlabeled
  126. // timeout can't tell WHICH step flaked (the #662 test's recurring
  127. // timeout was undiagnosable for exactly this reason).
  128. return reject(new Error(`Timed out after ${timeoutMs}ms${label ? ` waiting for: ${label}` : ''}`));
  129. }
  130. setTimeout(tick, pollMs);
  131. };
  132. tick();
  133. });
  134. }
  135. function isAlive(pid: number): boolean {
  136. try { process.kill(pid, 0); return true; } catch { return false; }
  137. }
  138. function readLockPid(root: string): number | null {
  139. try {
  140. const raw = fs.readFileSync(path.join(root, '.codegraph', 'daemon.pid'), 'utf8');
  141. const info = JSON.parse(raw);
  142. return typeof info.pid === 'number' ? info.pid : null;
  143. } catch { return null; }
  144. }
  145. function readDaemonLog(root: string): string {
  146. try { return fs.readFileSync(path.join(root, '.codegraph', 'daemon.log'), 'utf8'); }
  147. catch { return ''; }
  148. }
  149. function countListeningLines(root: string): number {
  150. return readDaemonLog(root).split('\n').filter((l) => l.includes('[CodeGraph daemon] Listening on')).length;
  151. }
  152. function killTree(...procs: ChildProcessWithoutNullStreams[]): void {
  153. for (const p of procs) {
  154. if (!p.killed) { try { p.kill('SIGKILL'); } catch { /* gone */ } }
  155. }
  156. }
  157. async function waitProcessExit(pid: number, timeoutMs: number): Promise<boolean> {
  158. return waitFor(() => !isAlive(pid), timeoutMs).then(() => true).catch(() => false);
  159. }
  160. describe('Shared MCP daemon (issue #411)', () => {
  161. let tempDir: string; // the (possibly symlinked) path processes are spawned with
  162. let realRoot: string; // its canonical form — what the daemon keys paths on
  163. const servers: SpawnedServer[] = [];
  164. beforeEach(async () => {
  165. tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-mcp-daemon-'));
  166. const cg = await CodeGraph.init(tempDir);
  167. cg.close();
  168. realRoot = fs.realpathSync(tempDir);
  169. });
  170. afterEach(async () => {
  171. killTree(...servers.map((s) => s.child));
  172. // The daemon is detached (not a tracked child) — reap it explicitly via the
  173. // pid it recorded, so a test can't leak a background daemon. Guard against
  174. // our own pid: the version-mismatch test plants `pid: process.pid` in the
  175. // lockfile, and we must never SIGKILL the vitest worker.
  176. const daemonPid = readLockPid(realRoot);
  177. if (daemonPid && daemonPid !== process.pid && isAlive(daemonPid)) {
  178. try { process.kill(daemonPid, 'SIGKILL'); } catch { /* race */ }
  179. }
  180. await new Promise((r) => setTimeout(r, 50));
  181. servers.length = 0;
  182. fs.rmSync(tempDir, { recursive: true, force: true });
  183. });
  184. it('two invocations share ONE detached daemon; both attach as proxies', async () => {
  185. const env = { CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS: '15000' };
  186. const first = spawnServer(tempDir, env);
  187. servers.push(first);
  188. sendInitialize(first.child, `file://${tempDir}`, 1);
  189. const firstResp = await waitFor(() => findResponse(first.stdout, 1), 10000);
  190. expect(firstResp.result.serverInfo.name).toBe('codegraph');
  191. // The launcher is a PROXY (not the daemon itself) — that's the detach fix.
  192. await waitFor(() => first.stderr.some((l) => l.includes('Attached to shared daemon')), 8000);
  193. // A detached daemon came up and recorded itself.
  194. await waitFor(() => fs.existsSync(path.join(realRoot, '.codegraph', 'daemon.pid')), 8000);
  195. await waitFor(() => countListeningLines(realRoot) >= 1, 8000);
  196. const daemonPid = readLockPid(realRoot);
  197. expect(daemonPid).toBeTruthy();
  198. expect(isAlive(daemonPid!)).toBe(true);
  199. // The socket exists at the path the code computes from the canonical root.
  200. // On Windows the daemon listens on a named pipe (\\.\pipe\...), which isn't
  201. // a filesystem entry — existsSync doesn't apply there, and the "Attached to
  202. // shared daemon" proof above already confirms the proxy reached it.
  203. if (process.platform !== 'win32') {
  204. expect(fs.existsSync(getDaemonSocketPath(realRoot))).toBe(true);
  205. }
  206. // Second invocation attaches as a proxy to the SAME daemon.
  207. const second = spawnServer(tempDir, env);
  208. servers.push(second);
  209. sendInitialize(second.child, `file://${tempDir}`, 2);
  210. const secondResp = await waitFor(() => findResponse(second.stdout, 2), 10000);
  211. expect(secondResp.result.serverInfo.name).toBe('codegraph');
  212. await waitFor(() => second.stderr.some((l) => l.includes('Attached to shared daemon')), 8000);
  213. // Exactly one daemon ever bound, and it's the same pid both attached to.
  214. expect(countListeningLines(realRoot)).toBe(1);
  215. expect(readLockPid(realRoot)).toBe(daemonPid);
  216. }, 40000);
  217. it('concurrent launchers converge on a single daemon (lockfile race — must-fix 1)', async () => {
  218. const env = { CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS: '15000' };
  219. // Fire three launchers as close to simultaneously as possible — this is the
  220. // race window where the old code could end up with two daemons.
  221. const procs = [spawnServer(tempDir, env), spawnServer(tempDir, env), spawnServer(tempDir, env)];
  222. procs.forEach((p, i) => { servers.push(p); sendInitialize(p.child, `file://${tempDir}`, i + 1); });
  223. // All three get a valid initialize response...
  224. for (let i = 0; i < procs.length; i++) {
  225. const resp = await waitFor(() => findResponse(procs[i].stdout, i + 1), 12000);
  226. expect(resp.result.serverInfo.name).toBe('codegraph');
  227. }
  228. // ...and all three attached as proxies (none fell back / wedged).
  229. for (const p of procs) {
  230. await waitFor(() => p.stderr.some((l) => l.includes('Attached to shared daemon')), 10000);
  231. }
  232. // The decisive assertion: exactly ONE daemon bound the socket. Losing
  233. // candidates log "already holds the lock; exiting" and never listen.
  234. expect(countListeningLines(realRoot)).toBe(1);
  235. const daemonPid = readLockPid(realRoot);
  236. expect(daemonPid).toBeTruthy();
  237. expect(isAlive(daemonPid!)).toBe(true);
  238. }, 45000);
  239. it('daemon survives the first client dying; a second client keeps working (must-fix 2 / #277)', async () => {
  240. // Idle high so the daemon doesn't reap mid-test; poll fast so proxy 1
  241. // notices its dead parent quickly.
  242. const env = { CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS: '30000', CODEGRAPH_PPID_POLL_MS: '200' };
  243. const first = spawnServer(tempDir, env);
  244. servers.push(first);
  245. sendInitialize(first.child, `file://${tempDir}`, 1);
  246. await waitFor(() => findResponse(first.stdout, 1), 10000);
  247. await waitFor(() => (readLockPid(realRoot) ?? 0) > 0, 8000);
  248. const daemonPid = readLockPid(realRoot)!;
  249. expect(isAlive(daemonPid)).toBe(true);
  250. const second = spawnServer(tempDir, env);
  251. servers.push(second);
  252. sendInitialize(second.child, `file://${tempDir}`, 1);
  253. await waitFor(() => findResponse(second.stdout, 1), 10000);
  254. await waitFor(() => second.stderr.some((l) => l.includes('Attached to shared daemon')), 8000);
  255. // Kill the launcher that spawned the daemon. With the old in-process design
  256. // this would take the daemon (and thus the second client) down.
  257. killTree(first.child);
  258. // The daemon is detached — it must still be alive a beat later.
  259. await new Promise((r) => setTimeout(r, 1500));
  260. expect(isAlive(daemonPid)).toBe(true);
  261. // And the second client can still drive a real tool call through it.
  262. sendMessage(second.child, { jsonrpc: '2.0', id: 2, method: 'tools/list' });
  263. const toolsResp = await waitFor(() => findResponse(second.stdout, 2), 10000);
  264. expect(Array.isArray(toolsResp.result.tools)).toBe(true);
  265. expect(toolsResp.result.tools.length).toBeGreaterThan(0);
  266. }, 45000);
  267. it('CODEGRAPH_NO_DAEMON=1 keeps each process independent (no socket/pidfile)', async () => {
  268. const env = { CODEGRAPH_NO_DAEMON: '1' };
  269. const first = spawnServer(tempDir, env);
  270. servers.push(first);
  271. sendInitialize(first.child, `file://${tempDir}`, 1);
  272. await waitFor(() => findResponse(first.stdout, 1), 10000);
  273. // Direct mode — no daemon machinery touched.
  274. expect(first.stderr.some((l) => l.includes('Attached to shared daemon'))).toBe(false);
  275. expect(fs.existsSync(path.join(realRoot, '.codegraph', 'daemon.pid'))).toBe(false);
  276. expect(fs.existsSync(path.join(realRoot, '.codegraph', 'daemon.log'))).toBe(false);
  277. }, 20000);
  278. it('clears a stale (dead-pid) lockfile and a fresh daemon takes over', async () => {
  279. // Plant a lockfile pointing at a definitely-dead pid + the real socket path.
  280. fs.writeFileSync(
  281. path.join(realRoot, '.codegraph', 'daemon.pid'),
  282. JSON.stringify({
  283. pid: 999_999,
  284. version: '0.0.0-fake',
  285. socketPath: getDaemonSocketPath(realRoot),
  286. startedAt: Date.now() - 1000,
  287. }),
  288. );
  289. const env = { CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS: '15000' };
  290. const server = spawnServer(tempDir, env);
  291. servers.push(server);
  292. sendInitialize(server.child, `file://${tempDir}`, 1);
  293. const resp = await waitFor(() => findResponse(server.stdout, 1), 10000).catch((e) => {
  294. throw new Error(`${(e as Error).message}\nstderr:\n${server.stderr.join('\n')}\ndaemon.log:\n${readDaemonLog(realRoot)}`);
  295. });
  296. expect(resp.result.serverInfo.name).toBe('codegraph');
  297. await waitFor(() => countListeningLines(realRoot) >= 1, 10000);
  298. // The pidfile now names a live daemon, not the planted-dead 999999.
  299. const livePid = readLockPid(realRoot);
  300. expect(livePid).not.toBe(999_999);
  301. expect(isAlive(livePid!)).toBe(true);
  302. }, 40000);
  303. it('preserves paired daemon/writer locks when their live PID may have been reused', async () => {
  304. const env = { CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS: '30000' };
  305. const first = spawnServer(tempDir, env);
  306. servers.push(first);
  307. sendInitialize(first.child, `file://${tempDir}`, 1);
  308. await waitFor(() => findResponse(first.stdout, 1), 10000);
  309. await waitFor(() => countListeningLines(realRoot) >= 1, 10000);
  310. const killedPid = readLockPid(realRoot)!;
  311. process.kill(killedPid, 'SIGKILL');
  312. expect(await waitProcessExit(killedPid, 8000)).toBe(true);
  313. // Model OS PID reuse without risking another process: the stale lock now
  314. // names this live vitest worker, but no daemon answers the leftover socket.
  315. const daemonPath = path.join(realRoot, '.codegraph', 'daemon.pid');
  316. const writerPath = path.join(realRoot, '.codegraph', 'writer.pid');
  317. const staleDaemonLock = JSON.stringify({
  318. pid: process.pid,
  319. version: CodeGraphPackageVersion,
  320. socketPath: getDaemonSocketPath(realRoot),
  321. startedAt: Date.now() - 60_000,
  322. });
  323. const staleWriterLock = JSON.stringify({
  324. pid: process.pid,
  325. mode: 'daemon',
  326. startedAt: Date.now() - 60_000,
  327. }) + '\n';
  328. fs.writeFileSync(daemonPath, staleDaemonLock);
  329. fs.writeFileSync(writerPath, staleWriterLock);
  330. const second = spawnServer(tempDir, env);
  331. servers.push(second);
  332. sendInitialize(second.child, `file://${tempDir}`, 2);
  333. const response = await waitFor(() => findResponse(second.stdout, 2), 12000);
  334. expect(response.result.serverInfo.name).toBe('codegraph');
  335. await waitFor(
  336. () => second.stderr.some((line) =>
  337. line.includes('Attached to shared daemon') || line.includes('Shared daemon unavailable')
  338. ),
  339. 12000,
  340. 25,
  341. 'the proxy to attach or fall back',
  342. );
  343. expect(second.stderr.some((line) => line.includes('Attached to shared daemon'))).toBe(false);
  344. expect(countListeningLines(realRoot)).toBe(1);
  345. expect(fs.readFileSync(daemonPath, 'utf8')).toBe(staleDaemonLock);
  346. expect(fs.readFileSync(writerPath, 'utf8')).toBe(staleWriterLock);
  347. expect(isAlive(process.pid)).toBe(true);
  348. sendMessage(second.child, {
  349. jsonrpc: '2.0',
  350. id: 3,
  351. method: 'tools/call',
  352. params: { name: 'codegraph_status', arguments: {} },
  353. });
  354. const toolResponse = await waitFor(() => findResponse(second.stdout, 3), 5000);
  355. expect(toolResponse).toMatchObject({
  356. error: { message: expect.stringContaining('writer lock held') },
  357. });
  358. }, 50000);
  359. it('does not replace a live legacy lock with a second daemon', async () => {
  360. const pidPath = path.join(realRoot, '.codegraph', 'daemon.pid');
  361. fs.writeFileSync(pidPath, `${process.pid}\n`);
  362. const server = spawnServer(tempDir, { CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS: '15000' });
  363. servers.push(server);
  364. sendInitialize(server.child, `file://${tempDir}`, 1);
  365. const response = await waitFor(() => findResponse(server.stdout, 1), 12000);
  366. expect(response.result.serverInfo.name).toBe('codegraph');
  367. await waitFor(
  368. () => server.stderr.some((line) =>
  369. line.includes('Attached to shared daemon') || line.includes('Shared daemon unavailable')
  370. ),
  371. 12000,
  372. 25,
  373. 'the proxy to attach or fall back',
  374. );
  375. expect(server.stderr.some((line) => line.includes('Attached to shared daemon'))).toBe(false);
  376. expect(fs.readFileSync(pidPath, 'utf8')).toBe(`${process.pid}\n`);
  377. expect(countListeningLines(realRoot)).toBe(0);
  378. expect(isAlive(process.pid)).toBe(true);
  379. sendMessage(server.child, {
  380. jsonrpc: '2.0',
  381. id: 2,
  382. method: 'tools/call',
  383. params: { name: 'codegraph_status', arguments: {} },
  384. });
  385. const toolResponse = await waitFor(() => findResponse(server.stdout, 2), 5000);
  386. expect(toolResponse).toMatchObject({
  387. error: { message: expect.stringContaining('live legacy daemon') },
  388. });
  389. }, 30000);
  390. it('does not start a fallback writer when the daemon lock is unreadable', async () => {
  391. const pidPath = path.join(realRoot, '.codegraph', 'daemon.pid');
  392. fs.mkdirSync(pidPath);
  393. const server = spawnServer(tempDir);
  394. servers.push(server);
  395. sendInitialize(server.child, `file://${tempDir}`, 1);
  396. await waitFor(
  397. () => server.stderr.some((line) => line.includes('Shared daemon unavailable')),
  398. 12000,
  399. 25,
  400. 'the proxy to fall back',
  401. );
  402. sendMessage(server.child, {
  403. jsonrpc: '2.0',
  404. id: 2,
  405. method: 'tools/call',
  406. params: { name: 'codegraph_status', arguments: {} },
  407. });
  408. const toolResponse = await waitFor(() => findResponse(server.stdout, 2), 5000);
  409. expect(toolResponse).toMatchObject({
  410. error: { message: expect.stringContaining('daemon lock could not be read') },
  411. });
  412. }, 30000);
  413. it('proxy falls back to direct mode on a daemon version mismatch', async () => {
  414. const net = await import('net');
  415. const sockPath = getDaemonSocketPath(realRoot);
  416. // Plant a live-pid lockfile so the launcher treats the lock as held, and a
  417. // mini-server that answers with a mismatched-version hello.
  418. fs.writeFileSync(
  419. path.join(realRoot, '.codegraph', 'daemon.pid'),
  420. JSON.stringify({ pid: process.pid, version: '0.0.0-mismatch', socketPath: sockPath, startedAt: Date.now() }),
  421. );
  422. const miniServer = net.createServer((sock) => {
  423. sock.write(JSON.stringify({
  424. codegraph: '0.0.0-mismatch',
  425. pid: process.pid,
  426. socketPath: sockPath,
  427. protocol: 1,
  428. }) + '\n');
  429. });
  430. await new Promise<void>((resolve) => miniServer.listen(sockPath, () => resolve()));
  431. try {
  432. const server = spawnServer(tempDir);
  433. servers.push(server);
  434. sendInitialize(server.child, `file://${tempDir}`, 1);
  435. // Despite the mismatched daemon, the client still gets an initialize
  436. // response — the proxy answers the handshake locally and, refusing to
  437. // attach across the version mismatch, serves the session in-process.
  438. const resp = await waitFor(() => findResponse(server.stdout, 1), 10000);
  439. expect(resp.result.serverInfo.name).toBe('codegraph');
  440. await waitFor(
  441. () => server.stderr.some((l) => l.includes('serving this session in-process')),
  442. 6000,
  443. );
  444. sendMessage(server.child, {
  445. jsonrpc: '2.0',
  446. id: 2,
  447. method: 'tools/call',
  448. params: { name: 'codegraph_status', arguments: {} },
  449. });
  450. const toolResponse = await waitFor(() => findResponse(server.stdout, 2), 5000);
  451. expect(toolResponse).toMatchObject({
  452. error: { message: expect.stringContaining('live daemon') },
  453. });
  454. expect(fs.existsSync(path.join(realRoot, '.codegraph', 'writer.pid'))).toBe(false);
  455. } finally {
  456. await new Promise<void>((resolve) => miniServer.close(() => resolve()));
  457. }
  458. }, 30000);
  459. // The over-the-wire client-hello → record → sweep path, and the inactivity
  460. // backstop's liveness gate, are covered by the deterministic unit tests in
  461. // daemon-client-liveness (`reapDeadClients`, `backstopShouldExit`) — a
  462. // raw-socket variant here was flaky under heavy parallel load. What stays
  463. // here is the lifecycle behavior that needs real procs: a live-but-quiet
  464. // client must SURVIVE the inactivity backstop. Reaping it used to silently
  465. // degrade the session (and any others sharing the daemon) to an in-process
  466. // engine; on a real machine the backstop fired on live sessions far more
  467. // often than on the phantoms it exists for. The phantom case it still covers
  468. // (an unknown-pid connection) is the `backstopShouldExit` unit test.
  469. it('does NOT reap a live-but-quiet client on the inactivity backstop (#692)', async () => {
  470. // Backstop short, idle timeout long: with a client connected the idle timer
  471. // never arms, so the inactivity backstop is the only thing that could take
  472. // the daemon down — and it must not, because the client's peer is alive.
  473. const env = { CODEGRAPH_DAEMON_MAX_IDLE_MS: '1200', CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS: '60000' };
  474. const server = spawnServer(tempDir, env);
  475. servers.push(server);
  476. sendInitialize(server.child, `file://${tempDir}`, 1);
  477. await waitFor(() => findResponse(server.stdout, 1), 10000);
  478. await waitFor(() => (readLockPid(realRoot) ?? 0) > 0, 8000);
  479. const daemonPid = readLockPid(realRoot)!;
  480. expect(isAlive(daemonPid)).toBe(true);
  481. // Stay silent well past several backstop windows. The live session's peer is
  482. // provably alive, so the daemon must keep running (and never log a backstop
  483. // shutdown), with its lockfile intact.
  484. await new Promise((r) => setTimeout(r, 4000)); // > 3× maxIdle
  485. expect(isAlive(daemonPid)).toBe(true);
  486. expect(readDaemonLog(realRoot)).not.toContain('inactivity backstop');
  487. expect(readLockPid(realRoot)).toBe(daemonPid);
  488. }, 30000);
  489. it('daemon idle-times-out after the last client disconnects', async () => {
  490. const env = { CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS: '800', CODEGRAPH_PPID_POLL_MS: '200' };
  491. const server = spawnServer(tempDir, env);
  492. servers.push(server);
  493. sendInitialize(server.child, `file://${tempDir}`, 1);
  494. await waitFor(() => findResponse(server.stdout, 1), 10000);
  495. await waitFor(() => (readLockPid(realRoot) ?? 0) > 0, 8000);
  496. const daemonPid = readLockPid(realRoot)!;
  497. // Close the only client's stdin → proxy exits → daemon refcount hits 0 →
  498. // idle timer fires → daemon exits and cleans up its lockfile.
  499. server.child.stdin.end();
  500. expect(await waitProcessExit(daemonPid, 10000)).toBe(true);
  501. expect(fs.existsSync(path.join(realRoot, '.codegraph', 'daemon.pid'))).toBe(false);
  502. }, 30000);
  503. it('proxy survives the daemon dying mid-session and keeps serving (#662)', async () => {
  504. // The #662 scenario: an MCP host SIGTERM's the shared daemon while a session
  505. // is live. The proxy must NOT exit (losing CodeGraph for that session) — it
  506. // falls back to an in-process engine and keeps answering.
  507. const env = { CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS: '30000', CODEGRAPH_PPID_POLL_MS: '5000' };
  508. const server = spawnServer(tempDir, env);
  509. servers.push(server);
  510. sendInitialize(server.child, `file://${tempDir}`, 1);
  511. await waitFor(() => findResponse(server.stdout, 1), 20000, 25, 'initialize response');
  512. await waitFor(() => server.stderr.some((l) => l.includes('Attached to shared daemon')), 8000, 25, 'daemon attach log');
  513. await waitFor(() => (readLockPid(realRoot) ?? 0) > 0, 8000, 25, 'daemon pidfile');
  514. const daemonPid = readLockPid(realRoot)!;
  515. // A warm call goes through the daemon.
  516. sendMessage(server.child, { jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'codegraph_status', arguments: {} } });
  517. try {
  518. await waitFor(() => findResponse(server.stdout, 2), 30000, 25, 'warm tools/call via daemon');
  519. } catch (e) {
  520. // This is the wait that historically flaked — surface WHERE the request
  521. // died: proxy side (stderr) or daemon side (daemon.log).
  522. let daemonLog = '<no daemon.log>';
  523. try { daemonLog = fs.readFileSync(path.join(realRoot, '.codegraph', 'daemon.log'), 'utf8').split('\n').slice(-25).join('\n'); } catch { /* absent */ }
  524. throw new Error(
  525. `${(e as Error).message}\ndaemonAlive=${isAlive(daemonPid)} proxyAlive=${isAlive(server.child.pid!)}\n` +
  526. `--- proxy stderr tail ---\n${server.stderr.slice(-15).join('')}\n--- daemon.log tail ---\n${daemonLog}`
  527. );
  528. }
  529. // Kill the daemon out from under the live proxy.
  530. process.kill(daemonPid, 'SIGTERM');
  531. expect(await waitProcessExit(daemonPid, 8000)).toBe(true);
  532. // The proxy must still be alive and still answer — served in-process now.
  533. expect(isAlive(server.child.pid!)).toBe(true);
  534. await waitFor(() => server.stderr.some((l) => l.includes('serving this session in-process')), 8000, 25, 'in-process failover log');
  535. sendMessage(server.child, { jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: 'codegraph_status', arguments: {} } });
  536. const resp = await waitFor(() => findResponse(server.stdout, 3), 15000);
  537. expect(resp.result !== undefined || resp.error !== undefined).toBe(true);
  538. expect(isAlive(server.child.pid!)).toBe(true);
  539. }, 45000);
  540. });