Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test: stdio warm-search trace counts only its own request's statements (serve-request-round-trips race)
garrytanb470e9e5aeaa
diff --git a/test/fixtures/mcp-stdio-round-trip-driver.ts b/test/fixtures/mcp-stdio-round-trip-driver.tsindex 209aa662a6..6e8475967f 100644--- a/test/fixtures/mcp-stdio-round-trip-driver.ts+++ b/test/fixtures/mcp-stdio-round-trip-driver.ts@@ -2,6 +2,13 @@// (test/helpers/statement-depth.ts), for test/serve-request-round-trips.test.ts. Each statement is// appended to ROUND_TRIP_LOG as one JSON line. One registered non-default source (source-a, under the cwd's// child directory) with an empty 'default', so an unbound call resolves through tier 5.5 like the trace.+//+// Each stdin chunk is handled inside an AsyncLocalStorage scope named by the JSON-RPC id it carries, so every+// statement records the request that sent it (`scope`, null for the server's own background work such as the+// resident persistence consumer's ticks) and its depth counts only that request's round trips.+// ROUND_TRIP_INTERLEAVE=<id> sends one background statement while that request's config snapshot read is in+// flight, the interleaving a resident tick produces by chance.+import { AsyncLocalStorage } from 'node:async_hooks';import { appendFileSync, mkdirSync } from 'node:fs';import { join } from 'node:path';@@ -17,5 +24,21 @@ const side = join(process.cwd(), 'source-a-example');mkdirSync(side, { recursive: true });await engine.executeRaw(`INSERT INTO sources (id, name, local_path, config) VALUES ('source-a', 'source-a', $1, '{"federated": true}'::jsonb)`, [side]);const log = process.env.ROUND_TRIP_LOG!;-recordStatementDepth(engine, { onRecord: record => appendFileSync(log, JSON.stringify(record) + '\n') });+const interleave = process.env.ROUND_TRIP_INTERLEAVE ? Number(process.env.ROUND_TRIP_INTERLEAVE) : null;+const request = new AsyncLocalStorage<number>();+const emit = process.stdin.emit.bind(process.stdin) as (event: string | symbol, ...args: unknown[]) => boolean;+process.stdin.emit = ((event: string | symbol, ...args: unknown[]) => {+ const id = event === 'data' ? /"id":(\d+)/.exec(String(args[0]))?.[1] : undefined;+ return id === undefined ? emit(event, ...args) : request.run(Number(id), () => emit(event, ...args));+}) as typeof process.stdin.emit;+let interleaved = false;+recordStatementDepth(engine, {+ scope: () => request.getStore() ?? null,+ onRecord: record => {+ appendFileSync(log, JSON.stringify(record) + '\n');+ if (interleave === null || interleaved || record.scope !== interleave || !/^SELECT key, value FROM config$/.test(record.sql)) return;+ interleaved = true;+ request.exit(() => setTimeout(() => { void engine.executeRaw('SELECT count(*)::int AS n FROM page_projection_jobs'); }, 0));+ },+});await startMcpServer(engine, {});diff --git a/test/helpers/statement-depth.ts b/test/helpers/statement-depth.tsindex 67399e33d3..cbdc6c2bfd 100644--- a/test/helpers/statement-depth.ts+++ b/test/helpers/statement-depth.ts@@ -3,23 +3,27 @@** Every statement is held `delayMs` (a stand-in for the network round trip) and records its depth: one more than the* deepest statement already answered when it was sent. Statements sent together share a depth, so the deepest depth of- * a request is the number of serial round trips it pays, whatever the machine's speed.+ * a request is the number of serial round trips it pays, whatever the machine's speed. With `scope`, each statement+ * records the scope it was sent from and counts only statements of that scope, so concurrent background work neither+ * deepens nor joins a request's round trips.*/import type { PGLiteEngine } from '../../src/core/pglite-engine.ts';-export interface DepthRecord { sql: string; depth: number }+export interface DepthRecord { sql: string; depth: number; scope?: unknown }-export function recordStatementDepth(engine: PGLiteEngine, opts: { delayMs?: number; onRecord?: (record: DepthRecord) => void } = {}): { records: DepthRecord[]; reset(): void } {+export function recordStatementDepth(engine: PGLiteEngine, opts: { delayMs?: number; onRecord?: (record: DepthRecord) => void; scope?: () => unknown } = {}): { records: DepthRecord[]; reset(): void } {const db = engine.db as unknown as { query: (sql: string, ...rest: unknown[]) => Promise<unknown> };const query = db.query.bind(db);const records: DepthRecord[] = [];- let answered = 0;+ const answered = new Map<unknown, number>();db.query = async (sql: string, ...rest: unknown[]) => {- const record = { sql: sql.replace(/\s+/g, ' ').trim(), depth: answered + 1 };+ const scope = opts.scope?.();+ const record: DepthRecord = { sql: sql.replace(/\s+/g, ' ').trim(), depth: (answered.get(scope) ?? 0) + 1 };+ if (opts.scope) record.scope = scope;records.push(record);opts.onRecord?.(record);await Bun.sleep(opts.delayMs ?? 5);- try { return await query(sql, ...rest); } finally { answered = Math.max(answered, record.depth); }+ try { return await query(sql, ...rest); } finally { answered.set(scope, Math.max(answered.get(scope) ?? 0, record.depth)); }};- return { records, reset: () => { records.length = 0; answered = 0; } };+ return { records, reset: () => { records.length = 0; answered.clear(); } };}diff --git a/test/serve-request-round-trips.test.ts b/test/serve-request-round-trips.test.tsindex 0821f61150..3764c85002 100644--- a/test/serve-request-round-trips.test.ts+++ b/test/serve-request-round-trips.test.ts@@ -11,7 +11,9 @@* 3. Existing coverage: test/cold-read-folded-statements.test.ts counts the sources reads of one snapshot, not their* order; test/facts-context-injection.serial.test.ts pins the hook's payload, not when it runs.* 4. Seam: none. test/helpers/statement-depth.ts holds every PGLite statement and records its serial depth; the stdio- * arm runs the real `startMcpServer` (test/fixtures/mcp-stdio-round-trip-driver.ts).+ * arm runs the real `startMcpServer` (test/fixtures/mcp-stdio-round-trip-driver.ts), which tags each statement with+ * the JSON-RPC request that sent it, so the server's background work (the resident persistence consumer ticks every+ * 250ms or more) never lands in, or deepens, the request's trace. A second stdio case forces that interleaving.*/import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';@@ -143,7 +145,7 @@ describe('MCP stdio warm search (real startMcpServer)', () => {const DRIVER = join(REPO_ROOT, 'test', 'fixtures', 'mcp-stdio-round-trip-driver.ts');const CHILD_STRIP = ['GBRAIN_DATABASE_URL', 'DATABASE_URL', 'GBRAIN_BRAIN_ID', 'GBRAIN_SOURCE', 'GBRAIN_SURFACE', 'GBRAIN_MCP_FORCE_SURFACE', 'GBRAIN_MCP_INSTRUCTIONS'];- test('resolves its source and reads config in one round trip; the hook runs beside the op', async () => {+ const warmSearch = async (extraEnv: Record<string, string>) => {const parent = mkdtempSync(join(tmpdir(), 'gbrain-stdio-round-trips-'));const log = join(parent, 'statements.ndjson');writeFileSync(log, '');@@ -151,7 +153,7 @@ describe('MCP stdio warm search (real startMcpServer)', () => {writeFileSync(join(parent, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: join(parent, 'db'), embedding_dimensions: 1536 }));const env = { ...process.env } as Record<string, string>;for (const k of CHILD_STRIP) delete env[k];- Object.assign(env, { GBRAIN_HOME: parent, HOME: parent, GBRAIN_SWEEP: '0', GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_SERVE_SYNC_IPC: '0', ROUND_TRIP_LOG: log });+ Object.assign(env, { GBRAIN_HOME: parent, HOME: parent, GBRAIN_SWEEP: '0', GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_SERVE_SYNC_IPC: '0', ROUND_TRIP_LOG: log, ...extraEnv });const proc = Bun.spawn([process.execPath, DRIVER], { cwd: parent, env, stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' });const responses = new Map<number, unknown>();const reader = (async () => {@@ -185,19 +187,20 @@ describe('MCP stdio warm search (real startMcpServer)', () => {send({ jsonrpc: '2.0', method: 'notifications/initialized' });searchCall(2);await waitFor(2);- await Bun.sleep(500);- const before = logged().length;searchCall(3);const result = await waitFor(3) as { isError?: boolean };- await Bun.sleep(200);- const call = logged().slice(before);- const base = call[0]!.depth - 1;- const records = call.map(r => ({ ...r, depth: r.depth - base }));+ const all = logged();+ const records = all.filter(r => r.scope === 3);expect(result.isError).toBeFalsy();const { resolution, op } = resolutionThenOp(records);expect(resolution.length).toBeGreaterThanOrEqual(2);expect(resolution.map(r => r.depth)).toEqual(resolution.map(() => 1));expect(op.depth).toBe(2);+ if (extraEnv.ROUND_TRIP_INTERLEAVE) {+ const background = all.findIndex(r => r.scope === null && r.sql === 'SELECT count(*)::int AS n FROM page_projection_jobs');+ expect(background).toBeGreaterThan(all.indexOf(resolution[0]!));+ expect(background).toBeLessThan(all.indexOf(op));+ }const withdrawals = records.find(r => WITHDRAWALS.test(r.sql));const generation = records.find(r => GENERATION.test(r.sql));const search = records.find(r => SEARCH.test(r.sql))!;@@ -209,5 +212,14 @@ describe('MCP stdio warm search (real startMcpServer)', () => {await reader.catch(() => {});rmSync(parent, { recursive: true, force: true });}- }, 120_000);+ };++ test('resolves its source and reads config in one round trip; the hook runs beside the op', () => warmSearch({}), 120_000);++ // Value: protects=the stdio trace counts only the request's own statements, so a background statement sent while the+ // config snapshot read is in flight (a resident persistence consumer tick, by chance about 1 run in 6 on a loaded+ // runner) neither becomes the "op" nor shifts its depth; fails_when=the trace goes back to "every statement logged+ // after the previous call" (op.depth 1, expected 2, as full-ci saw); why_new=the case above meets the race only by+ // chance; seam=ROUND_TRIP_INTERLEAVE in the driver sends the background statement; no_claim=how often ticks fire+ test('a background statement sent beside the request leaves its trace and depths unchanged', () => warmSearch({ ROUND_TRIP_INTERLEAVE: '3' }), 120_000);});