diff --git a/src/config/loader.ts b/src/config/loader.ts index 0b5665b..c2a8ba7 100644 --- a/src/config/loader.ts +++ b/src/config/loader.ts @@ -323,6 +323,9 @@ export function shouldSkipDangerousPatternCheck(): boolean { * - POOL_MAX_CONCURRENT: Maximum concurrent requests (default: 100) * - POOL_QUEUE_SIZE: Queue size when at capacity (default: 200) * - POOL_QUEUE_TIMEOUT_MS: Queue timeout in ms (default: 30000) + * - POOL_CONNECT_TIMEOUT_MS: Per-server connect timeout in ms (default: 20000) + * - POOL_STARTUP_CONCURRENCY: Max servers connecting at once at startup (default: 6) + * - POOL_STARTUP_RETRIES: Serial connect retries for servers that missed the first window (default: 1) * * @returns Validated pool configuration with defaults * @throws {z.ZodError} If environment variables are invalid (non-numeric, out of bounds) @@ -334,6 +337,8 @@ export function getPoolConfig(): PoolConfig { queueSize: parseEnvInt(process.env.POOL_QUEUE_SIZE, 'POOL_QUEUE_SIZE'), queueTimeoutMs: parseEnvInt(process.env.POOL_QUEUE_TIMEOUT_MS, 'POOL_QUEUE_TIMEOUT_MS'), connectTimeoutMs: parseEnvInt(process.env.POOL_CONNECT_TIMEOUT_MS, 'POOL_CONNECT_TIMEOUT_MS'), + startupConcurrency: parseEnvInt(process.env.POOL_STARTUP_CONCURRENCY, 'POOL_STARTUP_CONCURRENCY'), + startupRetries: parseEnvInt(process.env.POOL_STARTUP_RETRIES, 'POOL_STARTUP_RETRIES'), }); } catch (error) { // WHY: Wrap Zod errors with user-friendly messages @@ -343,7 +348,7 @@ export function getPoolConfig(): PoolConfig { const field = firstError?.path.join('.') || 'unknown'; throw new Error( `Invalid pool configuration: ${field} - ${firstError?.message}. ` + - `Check environment variables: POOL_MAX_CONCURRENT (1-1000), POOL_QUEUE_SIZE (1-1000), POOL_QUEUE_TIMEOUT_MS (1000-300000), POOL_CONNECT_TIMEOUT_MS (1000-120000).` + `Check environment variables: POOL_MAX_CONCURRENT (1-1000), POOL_QUEUE_SIZE (1-1000), POOL_QUEUE_TIMEOUT_MS (1000-300000), POOL_CONNECT_TIMEOUT_MS (1000-120000), POOL_STARTUP_CONCURRENCY (1-64), POOL_STARTUP_RETRIES (0-5).` ); } // Re-throw non-Zod errors (e.g., parseEnvInt errors) diff --git a/src/config/types.ts b/src/config/types.ts index 62b2671..45d28d3 100644 --- a/src/config/types.ts +++ b/src/config/types.ts @@ -30,6 +30,15 @@ export type RateLimitConfig = z.infer; * - queueTimeoutMs: 1s-5min ensures reasonable wait times * - connectTimeoutMs: 1s-2min caps how long a single downstream MCP server may * take to connect, so one slow/unreachable server cannot stall pool startup + * - startupConcurrency: 1-64 caps how many downstream servers spawn+handshake at + * once. Connecting all servers simultaneously (unbounded Promise.all) makes many + * cold-starting `uvx`/`npx` children contend for CPU/IO — a "thundering herd" + * that pushes the slowest server (e.g. basic-memory) over connectTimeoutMs. A + * bounded window keeps startup fast while removing that contention. + * - startupRetries: 0-5 extra connect attempts for servers that missed the first + * window. Retries run serially AFTER the initial batch settles — with the herd + * gone, a slow server gets the machine to itself and connects on the retry + * instead of being dropped for the whole process lifetime. */ export const PoolConfigSchema = z.object({ /** Maximum concurrent requests (default: 100) */ @@ -38,8 +47,12 @@ export const PoolConfigSchema = z.object({ queueSize: z.number().int().min(1).max(1000).default(200), /** Queue timeout in milliseconds (default: 30000ms = 30s) */ queueTimeoutMs: z.number().int().min(1000).max(300000).default(30000), - /** Per-server connect timeout in milliseconds (default: 15000ms = 15s) */ - connectTimeoutMs: z.number().int().min(1000).max(120000).default(15000), + /** Per-server connect timeout in milliseconds (default: 20000ms = 20s) */ + connectTimeoutMs: z.number().int().min(1000).max(120000).default(20000), + /** Max downstream servers connecting concurrently at startup (default: 6) */ + startupConcurrency: z.number().int().min(1).max(64).default(6), + /** Serial connect retries for servers that missed the first window (default: 1) */ + startupRetries: z.number().int().min(0).max(5).default(1), }); export type PoolConfig = z.infer; diff --git a/src/mcp/client-pool.ts b/src/mcp/client-pool.ts index caba777..ae9d5d2 100644 --- a/src/mcp/client-pool.ts +++ b/src/mcp/client-pool.ts @@ -22,6 +22,57 @@ import type { SchemaCache } from '../validation/schema-cache.js'; import { ConnectionQueue } from './connection-queue.js'; import type { MetricsExporter } from '../observability/metrics-exporter.js'; +/** Result of a single downstream-server connect attempt (used by initialize()). */ +interface ConnectOutcome { + serverName: string; + ok: boolean; + /** Wall-clock duration of the (last) attempt, ms. */ + ms: number; + /** Failure message, present only when ok === false. */ + error?: string; + /** True when the server connected on a retry rather than the first window. */ + viaRetry?: boolean; +} + +/** + * Run `worker` over `items` with at most `limit` in flight at once, preserving + * input order in the returned array. A bounded alternative to + * `Promise.all(items.map(worker))` for when unbounded fan-out would overload a + * shared resource — here, many cold-starting downstream MCP children spawning + * simultaneously and starving each other's connect handshake. + * + * Uses a fixed set of `limit` runners pulling from a shared cursor (sliding + * window), so a fast item never waits behind a slow one in the same batch. The + * cursor read+increment is synchronous (single-threaded event loop), so no lock + * is needed. `worker` is expected not to throw — callers wrap per-item errors + * into a result object; a throw rejects the whole run, matching Promise.all. + */ +export async function mapWithConcurrency( + items: readonly T[], + limit: number, + worker: (item: T, index: number) => Promise +): Promise { + const results = new Array(items.length); + let next = 0; + // Defensive: a non-finite or <1 limit must never yield 0 workers, which would + // leave `results` holes (undefined) and silently drop items. Fall back to + // serial (1) so every item is still processed. + const safeLimit = Number.isFinite(limit) && limit >= 1 ? Math.floor(limit) : 1; + const workerCount = Math.min(safeLimit, items.length); + const runners: Promise[] = []; + for (let w = 0; w < workerCount; w++) { + runners.push( + (async () => { + for (let current = next++; current < items.length; current = next++) { + results[current] = await worker(items[current]!, current); + } + })() + ); + } + await Promise.all(runners); + return results; +} + /** * MCP Client Pool Configuration (US4: FR-4) * @@ -47,8 +98,12 @@ export interface MCPClientPoolConfig { queueSize?: number; /** Queue timeout in milliseconds (default: 30000ms = 30s) */ queueTimeoutMs?: number; - /** Per-server connect timeout in milliseconds (default: 15000ms = 15s) */ + /** Per-server connect timeout in milliseconds (default: 20000ms = 20s) */ connectTimeoutMs?: number; + /** Max downstream servers connecting concurrently at startup (default: 6) */ + startupConcurrency?: number; + /** Serial connect retries for servers that missed the first window (default: 1) */ + startupRetries?: number; } /** @@ -73,6 +128,15 @@ export class MCPClientPool implements IToolSchemaProvider { // trigger a supervisor restart loop). See connectStdio/connectHttp. private connectTimeoutMs: number; + // Startup fan-out control. connectToServer() for all configured servers used to + // run under one unbounded Promise.all — every cold-starting `uvx`/`npx` child + // spawning at once contends for CPU/IO (a "thundering herd") and pushes the + // slowest server over connectTimeoutMs. startupConcurrency bounds how many + // connect at once; startupRetries re-attempts the ones that missed the first + // window, serially, after the herd has cleared. See initialize(). + private startupConcurrency: number; + private startupRetries: number; + // STDIO transports that have spawned a child process but whose connect() has // not yet resolved. Tracked here so a child can still be reaped if the whole // pool is torn down (or the process exits) before connect() completes — @@ -116,6 +180,10 @@ export class MCPClientPool implements IToolSchemaProvider { // Per-server connect timeout (Priority: explicit config > env-validated default) this.connectTimeoutMs = config?.connectTimeoutMs ?? poolConfig.connectTimeoutMs; + // Startup fan-out control (Priority: explicit config > env-validated default) + this.startupConcurrency = config?.startupConcurrency ?? poolConfig.startupConcurrency; + this.startupRetries = config?.startupRetries ?? poolConfig.startupRetries; + // T053: Initialize connection queue this.connectionQueue = new ConnectionQueue({ maxSize: config?.queueSize ?? poolConfig.queueSize, @@ -344,24 +412,71 @@ export class MCPClientPool implements IToolSchemaProvider { // server can never block the others — failures degrade gracefully and the // pool comes up with whatever connected. A failed server is NEVER added to // `clients`/`toolCache`, so its tools are not discoverable or callable. + // + // Fan-out is bounded (startupConcurrency) instead of one unbounded + // Promise.all: connecting every server at once makes cold-starting + // `uvx`/`npx` children contend for CPU/IO and pushes the slowest (e.g. + // basic-memory) past connectTimeoutMs. Servers that still miss the window + // are retried serially (startupRetries) once the herd has cleared. const serverNames = filteredServers.map(([name]) => name); - const outcomes = await Promise.all( - filteredServers.map(async ([serverName, serverConfig]) => { - const startedAt = Date.now(); - try { - await this.connectToServer(serverName, serverConfig); - return { serverName, ok: true as const, ms: Date.now() - startedAt }; - } catch (error) { - return { - serverName, - ok: false as const, - ms: Date.now() - startedAt, - error: error instanceof Error ? error.message : String(error), - }; - } - }) + const configByName = new Map(filteredServers); + + const connectOne = async ( + serverName: string, + serverConfig: MCPServerConfig + ): Promise => { + const startedAt = Date.now(); + try { + await this.connectToServer(serverName, serverConfig); + return { serverName, ok: true, ms: Date.now() - startedAt }; + } catch (error) { + return { + serverName, + ok: false, + ms: Date.now() - startedAt, + error: error instanceof Error ? error.message : String(error), + }; + } + }; + + // First window: bounded-concurrency connect across all servers. + const outcomeByName = new Map(); + const firstRound = await mapWithConcurrency( + filteredServers, + this.startupConcurrency, + ([serverName, serverConfig]) => connectOne(serverName, serverConfig) ); + for (const outcome of firstRound) { + outcomeByName.set(outcome.serverName, outcome); + } + + // Serial retry for servers that missed the first window. With the herd + // gone, a slow server usually connects immediately on the retry instead of + // being dropped for the whole process lifetime (there is no lazy reconnect). + for (let attempt = 1; attempt <= this.startupRetries; attempt++) { + const stillFailed = [...outcomeByName.values()].filter(o => !o.ok); + if (stillFailed.length === 0) { + break; + } + console.error( + `🔁 Retry ${attempt}/${this.startupRetries} for ${stillFailed.length} server(s) that missed the startup window: ${stillFailed.map(o => o.serverName).join(', ')}` + ); + for (const failed of stillFailed) { + const serverConfig = configByName.get(failed.serverName); + if (!serverConfig) { + continue; + } + const retried = await connectOne(failed.serverName, serverConfig); + if (retried.ok) { + retried.viaRetry = true; + } + outcomeByName.set(failed.serverName, retried); + } + } + // Report in original config order (Map preserves insertion order, but be + // explicit so a future config-merge change can't reorder the report). + const outcomes = serverNames.map(name => outcomeByName.get(name)!); const failures = outcomes.filter(o => !o.ok); const successes = outcomes.length - failures.length; @@ -374,7 +489,7 @@ export class MCPClientPool implements IToolSchemaProvider { console.error(`📋 MCP server startup report (${successes}/${serverNames.length} connected):`); for (const o of outcomes) { if (o.ok) { - console.error(` ✓ ${o.serverName} (${o.ms}ms)`); + console.error(` ✓ ${o.serverName} (${o.ms}ms)${o.viaRetry ? ' [via retry]' : ''}`); } else { console.error(` ✗ ${o.serverName} (${o.ms}ms): ${o.error}`); } diff --git a/tests/exclude-servers.test.ts b/tests/exclude-servers.test.ts index 480326e..6a88f8d 100644 --- a/tests/exclude-servers.test.ts +++ b/tests/exclude-servers.test.ts @@ -32,6 +32,9 @@ describe('excludeServers', () => { maxConcurrent: 100, queueSize: 200, queueTimeoutMs: 30000, + connectTimeoutMs: 20000, + startupConcurrency: 6, + startupRetries: 1, }); pool = new MCPClientPool(); diff --git a/tests/map-with-concurrency.test.ts b/tests/map-with-concurrency.test.ts new file mode 100644 index 0000000..a226a04 --- /dev/null +++ b/tests/map-with-concurrency.test.ts @@ -0,0 +1,110 @@ +/** + * Unit tests for mapWithConcurrency — the bounded startup fan-out helper. + * + * This replaces the unbounded `Promise.all(servers.map(connect))` in the MCP + * client pool: connecting every downstream server at once made cold-starting + * children contend and pushed the slowest past its connect timeout. The helper + * must (a) process every item, (b) preserve input order in the result, and + * (c) never run more than `limit` workers at once. + */ + +import { describe, it, expect } from 'vitest'; +import { mapWithConcurrency } from '../src/mcp/client-pool.js'; + +/** Resolve after `ms` via a microtask chain (no real timers → fast, deterministic). */ +function tick(rounds: number): Promise { + let p = Promise.resolve(); + for (let i = 0; i < rounds; i++) { + p = p.then(() => undefined); + } + return p; +} + +describe('mapWithConcurrency', () => { + it('preserves input order in the result regardless of completion order', async () => { + const items = [0, 1, 2, 3, 4, 5]; + + // Later items resolve sooner (more items complete first) — result must + // still be in input order, not completion order. + const result = await mapWithConcurrency(items, 3, async (n) => { + await tick(items.length - n); + return n * 10; + }); + + expect(result).toEqual([0, 10, 20, 30, 40, 50]); + }); + + it('processes every item exactly once', async () => { + const items = Array.from({ length: 25 }, (_, i) => i); + const seen: number[] = []; + + const result = await mapWithConcurrency(items, 4, async (n) => { + seen.push(n); + return n; + }); + + expect(result).toEqual(items); + expect([...seen].sort((a, b) => a - b)).toEqual(items); + expect(seen.length).toBe(items.length); + }); + + it('never exceeds the concurrency limit', async () => { + const items = Array.from({ length: 20 }, (_, i) => i); + let inFlight = 0; + let maxInFlight = 0; + + await mapWithConcurrency(items, 5, async () => { + inFlight++; + maxInFlight = Math.max(maxInFlight, inFlight); + await tick(3); + inFlight--; + }); + + expect(maxInFlight).toBeLessThanOrEqual(5); + // Sanity: with 20 items and limit 5, the window should actually fill. + expect(maxInFlight).toBe(5); + }); + + it('passes the correct index to the worker', async () => { + const items = ['a', 'b', 'c']; + + const result = await mapWithConcurrency(items, 2, async (item, index) => `${index}:${item}`); + + expect(result).toEqual(['0:a', '1:b', '2:c']); + }); + + it('returns an empty array for empty input (no workers spawned)', async () => { + let called = false; + const result = await mapWithConcurrency([], 4, async () => { + called = true; + return 1; + }); + + expect(result).toEqual([]); + expect(called).toBe(false); + }); + + it('handles limit larger than item count', async () => { + const items = [1, 2, 3]; + const result = await mapWithConcurrency(items, 100, async (n) => n * 2); + + expect(result).toEqual([2, 4, 6]); + }); + + it('treats limit < 1 as a single serial worker', async () => { + const items = [1, 2, 3, 4]; + let inFlight = 0; + let maxInFlight = 0; + + const result = await mapWithConcurrency(items, 0, async (n) => { + inFlight++; + maxInFlight = Math.max(maxInFlight, inFlight); + await tick(2); + inFlight--; + return n; + }); + + expect(result).toEqual(items); + expect(maxInFlight).toBe(1); + }); +}); diff --git a/tests/pool-config-validation.test.ts b/tests/pool-config-validation.test.ts index 23b4a2d..d5a472c 100644 --- a/tests/pool-config-validation.test.ts +++ b/tests/pool-config-validation.test.ts @@ -21,6 +21,8 @@ describe('Pool Configuration Validation (SEC-002)', () => { delete process.env.POOL_QUEUE_SIZE; delete process.env.POOL_QUEUE_TIMEOUT_MS; delete process.env.POOL_CONNECT_TIMEOUT_MS; + delete process.env.POOL_STARTUP_CONCURRENCY; + delete process.env.POOL_STARTUP_RETRIES; }); afterEach(() => { @@ -35,7 +37,61 @@ describe('Pool Configuration Validation (SEC-002)', () => { expect(config.maxConcurrent).toBe(100); expect(config.queueSize).toBe(200); expect(config.queueTimeoutMs).toBe(30000); - expect(config.connectTimeoutMs).toBe(15000); + expect(config.connectTimeoutMs).toBe(20000); + expect(config.startupConcurrency).toBe(6); + expect(config.startupRetries).toBe(1); + }); + }); + + describe('Startup fan-out config (concurrency + retries)', () => { + it('should_parseValidValues_when_startupEnvVarsSet', () => { + process.env.POOL_STARTUP_CONCURRENCY = '4'; + process.env.POOL_STARTUP_RETRIES = '2'; + + const config = getPoolConfig(); + + expect(config.startupConcurrency).toBe(4); + expect(config.startupRetries).toBe(2); + }); + + it('should_acceptZeroRetries_when_retriesDisabled', () => { + process.env.POOL_STARTUP_RETRIES = '0'; // 0 is valid: disables retry + + expect(getPoolConfig().startupRetries).toBe(0); + }); + + it('should_acceptBounds_when_atLimits', () => { + process.env.POOL_STARTUP_CONCURRENCY = '64'; // max + process.env.POOL_STARTUP_RETRIES = '5'; // max + + const config = getPoolConfig(); + + expect(config.startupConcurrency).toBe(64); + expect(config.startupRetries).toBe(5); + }); + + it('should_throwZodError_when_startupConcurrencyZero', () => { + process.env.POOL_STARTUP_CONCURRENCY = '0'; // min is 1 + + expect(() => getPoolConfig()).toThrow(); + }); + + it('should_throwZodError_when_startupConcurrencyExceedsMax', () => { + process.env.POOL_STARTUP_CONCURRENCY = '65'; // max is 64 + + expect(() => getPoolConfig()).toThrow(); + }); + + it('should_throwZodError_when_startupRetriesNegative', () => { + process.env.POOL_STARTUP_RETRIES = '-1'; // min is 0 + + expect(() => getPoolConfig()).toThrow(); + }); + + it('should_throwZodError_when_startupRetriesExceedsMax', () => { + process.env.POOL_STARTUP_RETRIES = '6'; // max is 5 + + expect(() => getPoolConfig()).toThrow(); }); }); diff --git a/tests/recursion-guard.test.ts b/tests/recursion-guard.test.ts index a63f663..539a51d 100644 --- a/tests/recursion-guard.test.ts +++ b/tests/recursion-guard.test.ts @@ -39,7 +39,9 @@ describe('recursion guard', () => { maxConcurrent: 100, queueSize: 200, queueTimeoutMs: 30000, - connectTimeoutMs: 15000, + connectTimeoutMs: 20000, + startupConcurrency: 6, + startupRetries: 1, }); pool = new MCPClientPool();