From 1b8d5840fe310fd0f6a87fc3e431f9ce5d2c1b46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jean-Fran=C3=A7ois=20SEMA?= Date: Mon, 23 Nov 2026 14:51:00 +0100 Subject: [PATCH] fix(serve-http): memoize project detection on the stateless request path Stateless (2026-07-28) requests resolve the project root on every call, up to three times. For a server started outside a Git repository, each call falls through to a synchronous `git rev-parse` subprocess that blocks the event loop. On hosts with slow process creation (endpoint security scanners on Windows add 1-3 s per spawn) the stateless probe of Claude Code exceeded its 5 s budget and the client fell back to legacy sessions. Detection results, including "not a project", are now cached per path for 5 minutes (256 paths max). Co-Authored-By: Claude Opus 5.5 --- src/cli/commands/project-detection-cache.ts | 61 +++++++++++++++++++++ src/cli/commands/serve-http.ts | 10 +++- tests/cli/project-detection-cache.test.ts | 52 ++++++++++++++++++ 3 files changed, 120 insertions(+), 3 deletions(-) create mode 100644 src/cli/commands/project-detection-cache.ts create mode 100644 tests/cli/project-detection-cache.test.ts diff --git a/src/cli/commands/project-detection-cache.ts b/src/cli/commands/project-detection-cache.ts new file mode 100644 index 00000000..4b90820a --- /dev/null +++ b/src/cli/commands/project-detection-cache.ts @@ -0,0 +1,61 @@ +/** + * Short-lived memo for project detection on the HTTP request path. + * + * Stateless (2026-07-28) MCP requests carry no session, so serve-http resolves + * the project root on every request, up to three times. When that root is not + * inside a Git repository, detection falls through to a synchronous + * `git rev-parse` subprocess, which blocks the event loop. On hosts where + * process creation is slow (endpoint security scanners on Windows routinely + * add one to several seconds), the stateless probe of clients such as Claude + * Code then exceeds its budget and the client falls back to legacy sessions. + * + * Results, including "not a project", are cached per path for a bounded time + * so the subprocess runs at most once per path per TTL. + */ + +import type { ProjectInfo } from '../../types.js'; + +export const DEFAULT_PROJECT_DETECTION_CACHE_TTL_MS = 5 * 60 * 1000; +export const MAX_PROJECT_DETECTION_CACHE_ENTRIES = 256; + +export interface ProjectDetectionCacheOptions { + ttlMs?: number; + maxEntries?: number; + now?: () => number; +} + +export type CachedProjectDetector = ((root: string) => ProjectInfo | null) & { + /** Drop every cached result. */ + clear(): void; + /** Number of cached paths (diagnostics/tests). */ + size(): number; +}; + +export function createCachedProjectDetector( + detect: (root: string) => ProjectInfo | null, + options: ProjectDetectionCacheOptions = {}, +): CachedProjectDetector { + const ttlMs = options.ttlMs ?? DEFAULT_PROJECT_DETECTION_CACHE_TTL_MS; + const maxEntries = options.maxEntries ?? MAX_PROJECT_DETECTION_CACHE_ENTRIES; + const now = options.now ?? Date.now; + const cache = new Map(); + + const cached = ((root: string) => { + const at = now(); + const hit = cache.get(root); + if (hit && hit.expiresAt > at) return hit.project; + const project = detect(root); + cache.delete(root); + cache.set(root, { project, expiresAt: at + ttlMs }); + while (cache.size > maxEntries) { + const oldest = cache.keys().next().value as string | undefined; + if (oldest === undefined) break; + cache.delete(oldest); + } + return project; + }) as CachedProjectDetector; + + cached.clear = () => cache.clear(); + cached.size = () => cache.size; + return cached; +} diff --git a/src/cli/commands/serve-http.ts b/src/cli/commands/serve-http.ts index 6a7851d9..ff1f5463 100644 --- a/src/cli/commands/serve-http.ts +++ b/src/cli/commands/serve-http.ts @@ -33,6 +33,7 @@ import { CURRENT_MCP_PROTOCOL_VERSION, MCP_SERVER_NAME, getMcpDiagnostics } from import { createMcpStartupDiscoverResult, getMcpServerInfo } from '../../server/mcp-discovery.js'; import { parseTcpPortOrReport } from '../port.js'; import { mcpFileUriToPath } from '../mcp-root-path.js'; +import { createCachedProjectDetector } from './project-detection-cache.js'; /** * HTTP MCP is a shared control plane. A normal thinking break should not @@ -363,10 +364,13 @@ export default defineCommand({ const statelessBindingStore = new McpBindingStore(); await statelessBindingStore.init(controlPlaneBaseDir); const modernRuntimePool = new ModernMcpRuntimePool(MAX_STORE_CACHE_ENTRIES); + // Stateless requests resolve their project on every call. Memoize it so a + // non-Git root does not spawn `git rev-parse` (synchronously) per request. + const detectRequestProject = createCachedProjectDetector(detectorMod.detectProject); async function resolveModernDataDir(root: string, persisted?: { dataDir?: string }): Promise { if (persisted?.dataDir) return persisted.dataDir; - const detected = detectorMod.detectProject(root); + const detected = detectRequestProject(root); return detected ? persistMod.getProjectDataDir(detected.id) : controlPlaneBaseDir; @@ -383,7 +387,7 @@ export default defineCommand({ const root = persisted?.projectRoot ?? requestedRoot ?? projectRoot; const dataDir = await resolveModernDataDir(root, persisted); const binding = persisted ?? (() => { - const detected = detectorMod.detectProject(root); + const detected = detectRequestProject(root); if (!detected) return undefined; const existing = statelessBindingStore.findByProjectRoot(detected.rootPath); return existing ? statelessBindingStore.touch(existing.handleId) ?? existing : undefined; @@ -706,7 +710,7 @@ export default defineCommand({ const requestedRoot = typeof req.headers['mcp-project-root'] === 'string' ? req.headers['mcp-project-root'] : projectRoot; - const detected = detectorMod.detectProject(requestedRoot); + const detected = detectRequestProject(requestedRoot); if (detected) { const bindingDataDir = await persistMod.getProjectDataDir(detected.id); const binding = statelessBindingStore.findByProjectRoot(detected.rootPath) diff --git a/tests/cli/project-detection-cache.test.ts b/tests/cli/project-detection-cache.test.ts new file mode 100644 index 00000000..7b66ab26 --- /dev/null +++ b/tests/cli/project-detection-cache.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it, vi } from 'vitest'; + +import { + DEFAULT_PROJECT_DETECTION_CACHE_TTL_MS, + createCachedProjectDetector, +} from '../../src/cli/commands/project-detection-cache.js'; + +const project = { id: 'local/demo', name: 'demo', rootPath: '/repo/demo' }; + +describe('createCachedProjectDetector', () => { + it('runs detection once per path within the TTL, including negative results', () => { + const detect = vi.fn((root: string) => (root === '/repo/demo' ? project : null)); + let clock = 0; + const cached = createCachedProjectDetector(detect, { now: () => clock }); + + expect(cached('/repo/demo')).toEqual(project); + expect(cached('/not-a-repo')).toBeNull(); + clock += DEFAULT_PROJECT_DETECTION_CACHE_TTL_MS - 1; + expect(cached('/repo/demo')).toEqual(project); + expect(cached('/not-a-repo')).toBeNull(); + expect(detect).toHaveBeenCalledTimes(2); + }); + + it('detects again once the TTL has elapsed', () => { + const detect = vi.fn((): typeof project | null => null); + let clock = 0; + const cached = createCachedProjectDetector(detect, { ttlMs: 1_000, now: () => clock }); + + expect(cached('/repo/new')).toBeNull(); + detect.mockReturnValue(project); + clock += 1_000; + expect(cached('/repo/new')).toEqual(project); + expect(detect).toHaveBeenCalledTimes(2); + }); + + it('keeps at most maxEntries paths, evicting the oldest', () => { + const detect = vi.fn(() => null); + const cached = createCachedProjectDetector(detect, { maxEntries: 2 }); + + cached('/a'); + cached('/b'); + cached('/c'); + expect(cached.size()).toBe(2); + cached('/b'); + cached('/c'); + expect(detect).toHaveBeenCalledTimes(3); + cached('/a'); + expect(detect).toHaveBeenCalledTimes(4); + cached.clear(); + expect(cached.size()).toBe(0); + }); +});