Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(config): one config snapshot per MCP request (#6721)
garrytan44b0c06aa02c
diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.tsindex 26782d63f9..cce3878784 100644--- a/src/commands/serve-http-mcp.ts+++ b/src/commands/serve-http-mcp.ts@@ -43,6 +43,7 @@ import { getBrainHotMemoryMeta } from '../core/facts/meta-hook.ts';import { serializeError } from '../core/errors.ts';import { VERSION } from '../version.ts';import { executeRawJsonb } from '../core/sql-query.ts';+import { withRequestConfigSnapshot } from '../core/config-snapshot.ts';import { withBearerScopeHint } from './serve-http-oauth.ts';import type { ServeHttpContext } from './serve-http.ts';@@ -122,7 +123,12 @@ export function mountMcp(app: Express, ctx: ServeHttpContext): void {// read-only; grantScopes still caps each grant to the client row's scope.app.post('/mcp', withBearerScopeHint(requireBearerAuth({ verifier: resourceVerifier, resourceMetadataUrl }), ['read', 'write'],- ), async (req: Request, res: Response) => {+ ), (req: Request, res: Response) => withRequestConfigSnapshot(engine, () => handleMcpPost(req, res)));++ // #6721: one config snapshot serves every config read of one POST /mcp (the+ // surface, row-shape and writeback reads below, tools/list and a read op's+ // dispatch); dispatch reads live for a write op (config-snapshot.ts).+ async function handleMcpPost(req: Request, res: Response): Promise<void> {const startTime = Date.now();const authInfo = (req as any).auth as AuthInfo;@@ -167,7 +173,7 @@ export function mountMcp(app: Express, ctx: ServeHttpContext): void {const state: McpRequestState = { authInfo, agentName, startTime, mcpOperations, surface, surfaceCeiling, surfaceAllowedOps, resultRows, thinClient };const server = createMcpRequestServer(ctx, state, writeback);await serveMcpRequest(server, req, res);- });+ }}function createMcpRequestServer(diff --git a/src/core/config-snapshot.ts b/src/core/config-snapshot.tsindex ca0a0c5277..8835c79ebb 100644--- a/src/core/config-snapshot.ts+++ b/src/core/config-snapshot.ts@@ -17,6 +17,7 @@* the process, so a `gbrain config set` from another process is picked up by* the next command exactly as before.*/+import { AsyncLocalStorage } from 'node:async_hooks';/** The only thing config resolution needs from an engine. */export interface ConfigReader {@@ -63,3 +64,100 @@ export async function snapshotConfigReader(},};}++/**+ * One config snapshot per MCP request.+ *+ * A remote MCP `search` resolves its settings in a dozen modules, each with+ * its own `engine.getConfig(key)`, plus loaders that read the whole table.+ * Behind a transaction pooler each read is a round trip, about 30 ms each to+ * a remote database, for a statement the server answers in well under a+ * millisecond (#6721).+ *+ * `withRequestConfigSnapshot(engine, fn)` runs `fn` with one snapshot of that+ * engine's config table: the first read inside it takes the whole table in+ * one statement, and every later `getConfig` / `getAllConfig` on the same+ * engine object answers from it. The snapshot lives exactly as long as `fn`:+ * reads after it settles (background work it started included) and reads on+ * any other engine object (a transaction's, another brain's) go to the+ * database as before. `setConfig` / `unsetConfig` on the engine update the+ * snapshot, so a request reads its own writes. A write operation runs under+ * `withoutRequestConfigSnapshot`: it reads config live, and when it settles+ * the snapshot is dropped, so a later read in the same request takes a fresh+ * one (raw-SQL config writes included). A failed bulk read leaves every key+ * to its per-key read, the same fallback `loadConfigSnapshot` has.+ */+interface RequestSnapshot {+ engine: object;+ open: boolean;+ rows: Promise<Map<string, string> | null> | null;+}++const requestSnapshot = new AsyncLocalStorage<{ held: RequestSnapshot; live: boolean }>();++/** The open snapshot for `engine` in this async context, if any. */+function activeSnapshot(engine: object): RequestSnapshot | undefined {+ const store = requestSnapshot.getStore();+ return store && !store.live && store.held.open && store.held.engine === engine ? store.held : undefined;+}++/** Run `fn` with one config snapshot of `engine`; an enclosing snapshot of the same engine is reused. */+export async function withRequestConfigSnapshot<T>(engine: BulkConfigReader, fn: () => Promise<T>): Promise<T> {+ if (activeSnapshot(engine)) return fn();+ const held: RequestSnapshot = { engine, open: true, rows: null };+ try {+ return await requestSnapshot.run({ held, live: false }, fn);+ } finally {+ held.open = false;+ }+}++/** Run `fn` reading config live (a write operation inside a request); the request's snapshot is retaken after it. */+export async function withoutRequestConfigSnapshot<T>(fn: () => Promise<T>): Promise<T> {+ const store = requestSnapshot.getStore();+ if (!store) return fn();+ try {+ return await requestSnapshot.run({ held: store.held, live: true }, fn);+ } finally {+ store.held.rows = null;+ }+}++function snapshotRows(engine: BulkConfigReader, held: RequestSnapshot): Promise<Map<string, string> | null> {+ held.rows ??= requestSnapshot.run({ held, live: true }, () => loadConfigSnapshot(engine))+ .then(rows => rows ? new Map(Object.entries(rows)) : null);+ return held.rows;+}++/**+ * The value of `key` from the request's snapshot of `engine`: a string, null+ * when the key is unset, or undefined when no snapshot applies (no request+ * snapshot, another engine, or the bulk read failed); the engine then reads+ * the key itself.+ */+export async function requestConfigValue(engine: BulkConfigReader, key: string): Promise<string | null | undefined> {+ const held = activeSnapshot(engine);+ if (!held) return undefined;+ const rows = await snapshotRows(engine, held);+ return rows ? rows.get(key) ?? null : undefined;+}++/** The request's whole snapshot of `engine` as `getAllConfig` returns it, or undefined when none applies. */+export async function requestConfigRows(engine: BulkConfigReader): Promise<Record<string, string> | undefined> {+ const held = activeSnapshot(engine);+ if (!held) return undefined;+ const rows = await snapshotRows(engine, held);+ return rows ? Object.fromEntries(rows) : undefined;+}++/** Keep an open snapshot of `engine` equal to a write the engine just made (value null = key removed). */+export function noteRequestConfigWrite(engine: object, key: string, value: string | null): void {+ const held = activeSnapshot(engine);+ if (!held?.rows) return;+ held.rows = held.rows.then(rows => {+ if (!rows) return rows;+ const next = new Map(rows);+ if (value === null) next.delete(key); else next.set(key, value);+ return next;+ });+}diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 07bcb5e4d6..5084c1ffe4 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -1,4 +1,5 @@import { registerManagedFilesystemEngine } from './persistence/filesystem-guard.ts';+import { noteRequestConfigWrite, requestConfigRows, requestConfigValue } from './config-snapshot.ts';import { replaceDerivedLinks, replaceDerivedLinksBatch, type DerivedLinkBatchItem, type DerivedLinkOrigin, type DerivedLinkReplacementOptions } from './derived-links.ts';import { trackPgliteDatabase, PgliteClosingError, notifyPgliteOpened } from './pglite-lifecycle.ts';import { mutatePageTag } from './page-state/tags.ts';@@ -2824,6 +2825,8 @@ export class PGLiteEngine implements BrainEngine {// Configasync getConfig(key: string): Promise<string | null> {+ const held = await requestConfigValue(this, key);+ if (held !== undefined) return held;const { rows } = await this.db.query('SELECT value FROM config WHERE key = $1', [key]);return rows.length > 0 ? (rows[0] as { value: string }).value : null;}@@ -2834,6 +2837,7 @@ export class PGLiteEngine implements BrainEngine {ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`,[key, value]);+ noteRequestConfigWrite(this, key, value);}async unsetConfig(key: string): Promise<number> {@@ -2841,6 +2845,7 @@ export class PGLiteEngine implements BrainEngine {'DELETE FROM config WHERE key = $1',[key],) as { affectedRows?: number };+ noteRequestConfigWrite(this, key, null);return affectedRows ?? 0;}@@ -2855,6 +2860,8 @@ export class PGLiteEngine implements BrainEngine {}async getAllConfig(): Promise<Record<string, string>> {+ const held = await requestConfigRows(this);+ if (held) return held;const { rows } = await this.db.query('SELECT key, value FROM config');const out: Record<string, string> = {};for (const row of rows as { key: string; value: string }[]) out[row.key] = row.value;diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 26366f8fe6..ffed3f184d 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -1,4 +1,5 @@import { tryAcquirePoolLongHold, PoolCapacityError } from './pool-budget.ts';+import { noteRequestConfigWrite, requestConfigRows, requestConfigValue } from './config-snapshot.ts';import { replaceDerivedLinks, replaceDerivedLinksBatch, type DerivedLinkBatchItem, type DerivedLinkOrigin, type DerivedLinkReplacementOptions } from './derived-links.ts';import { mutatePageTag } from './page-state/tags.ts';import type { PageKey, PageSnapshot, PageSnapshotOptions, PageWriteOptions } from './page-state/types.ts';@@ -2661,6 +2662,8 @@ export class PostgresEngine implements BrainEngine {}async getConfig(key: string): Promise<string | null> {+ const held = await requestConfigValue(this, key);+ if (held !== undefined) return held;// #1603: a transient pooler drop on this read used to throw / fall through// to defaults silently — which on remote Postgres surfaces as the wrong// search mode/knobs and empty-stdout queries.@@ -2676,12 +2679,14 @@ export class PostgresEngine implements BrainEngine {INSERT INTO config (key, value) VALUES (${key}, ${value})ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`;+ noteRequestConfigWrite(this, key, value);});}async unsetConfig(key: string): Promise<number> {return this.connRetry(async () => {const result = await this.sql`DELETE FROM config WHERE key = ${key}` as unknown as { count: number };+ noteRequestConfigWrite(this, key, null);return result.count ?? 0;});}@@ -2700,6 +2705,8 @@ export class PostgresEngine implements BrainEngine {}async getAllConfig(): Promise<Record<string, string>> {+ const held = await requestConfigRows(this);+ if (held) return held;return this.connRetry(async () => {const rows = await this.sql<{ key: string; value: string }[]>`SELECT key, value FROM configdiff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 4642b8f742..8fbfec6146 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -13,6 +13,7 @@ import { operations, OperationError, enforceBoundClientOpAllowList, opError } frimport type { OperationContext, AuthInfo } from '../core/operations.ts';import type { OperationMeta } from '../core/ops/contract.ts';import { loadConfig } from '../core/config.ts';+import { withRequestConfigSnapshot, withoutRequestConfigSnapshot } from '../core/config-snapshot.ts';import { resolveBrainId } from '../core/brain-resolver.ts';import { getCliOptions } from '../core/cli-options.ts';import { VERB_NAMES, MEMORY_VERBS_VERSION } from '../core/verbs.ts';@@ -865,6 +866,20 @@ export async function dispatchToolCall(name: string,params: Record<string, unknown> | undefined,opts: DispatchOpts = {},+): Promise<ToolResult> {+ // #6721: a read op answers every config read from one snapshot of the table+ // (config-snapshot.ts); a write reads config live, so it sees its own writes.+ const run = () => dispatchResolvedCall(engine, name, params, opts);+ return operations.find(o => o.name === name)?.mutating === false+ ? withRequestConfigSnapshot(engine, run)+ : withoutRequestConfigSnapshot(run);+}++async function dispatchResolvedCall(+ engine: BrainEngine,+ name: string,+ params: Record<string, unknown> | undefined,+ opts: DispatchOpts,): Promise<ToolResult> {const startedMs = Date.now();const isVerb = VERB_NAME_SET.has(name);diff --git a/test/config-request-snapshot.test.ts b/test/config-request-snapshot.test.tsnew file mode 100644index 0000000000..523147b0d9--- /dev/null+++ b/test/config-request-snapshot.test.ts@@ -0,0 +1,180 @@+/**+ * #6721: one config snapshot per request.+ *+ * 1. Protects: a remote MCP `search` (stdio dispatch and POST /mcp) reads the+ * config table once, and a request still reads its own config writes.+ * 2. Fails when: a search-path module reads a key one statement at a time+ * again, dispatch or the /mcp route stops opening the snapshot, or the+ * snapshot outlives its request (stale config after it settles).+ * 3. Existing coverage: test/search-mode-config-snapshot.test.ts pins only the+ * mode loader; nothing counted the reads of a whole request.+ * Contributed by @troyhoffman-oss (#6734); revised for the LHF wave 2.+ * 4. Seam: none. Statements are counted on the PGLite handle the engine uses.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { Server } from 'node:http';+import express from 'express';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { serializeMarkdown } from '../src/core/markdown.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { buildServeHttpApp } from '../src/commands/serve-http.ts';+import { withRequestConfigSnapshot, withoutRequestConfigSnapshot } from '../src/core/config-snapshot.ts';++let engine: PGLiteEngine;+let server: Server;+let base: string;+let token: string;+const configStatements: string[] = [];++async function json<T>(res: Response): Promise<T> {+ expect(res.status).toBe(200);+ const text = await res.text();+ const data = text.split('\n').find(l => l.startsWith('data:'));+ return JSON.parse(data ? data.slice('data:'.length) : text) as T;+}++/** Config-table statements issued while `fn` runs. */+async function countConfigStatements(fn: () => Promise<unknown>): Promise<string[]> {+ configStatements.length = 0;+ await fn();+ return [...configStatements];+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ for (let i = 0; i < 3; i++) {+ await importFromContent(engine, `notes/widget-${i}`, serializeMarkdown({}, `Widget renewal terms, note ${i}.`, '', { type: 'note', title: `Widget ${i}`, tags: [] }), { noEmbed: true, forceRechunk: true });+ }+ const db = engine.db as unknown as { query: (sql: string, ...rest: unknown[]) => Promise<unknown> };+ const query = db.query.bind(db);+ db.query = (sql: string, ...rest: unknown[]) => {+ if (/\bFROM config\b/i.test(sql)) configStatements.push(sql.replace(/\s+/g, ' ').trim());+ return query(sql, ...rest);+ };+ const app = express();+ server = await new Promise(resolve => { const s = app.listen(0, '127.0.0.1', () => resolve(s)); });+ const port = (server.address() as { port: number }).port;+ base = `http://127.0.0.1:${port}`;+ const built = await buildServeHttpApp(app, engine, { port, tokenTtl: 3600, enableDcr: false, publicUrl: base });+ const login = await fetch(`${base}/admin/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: built.bootstrapToken }) });+ const cookie = login.headers.get('set-cookie')!.split(';')[0];+ const reg = await json<{ clientId: string; clientSecret: string }>(await fetch(`${base}/admin/api/register-client`, {+ method: 'POST', headers: { Cookie: cookie, 'Content-Type': 'application/json' },+ body: JSON.stringify({ name: 'snapshot-client', scopes: 'read', grantTypes: ['client_credentials'] }),+ }));+ token = (await json<{ access_token: string }>(await fetch(`${base}/token`, {+ method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({ grant_type: 'client_credentials', client_id: reg.clientId, client_secret: reg.clientSecret, scope: 'read' }),+ }))).access_token;+}, 120_000);++afterAll(async () => {+ await new Promise<void>(resolve => { server?.closeAllConnections?.(); server?.close(() => resolve()); });+ await engine?.disconnect();+});++describe('a remote search reads the config table once', () => {+ test('stdio/HTTP dispatch', async () => {+ const reads = await countConfigStatements(async () => {+ const r = await dispatchToolCall(engine, 'search', { query: 'widget renewal', limit: 5 }, { remote: true, transport: 'http', sourceId: 'default' });+ expect(r.isError).toBeFalsy();+ expect((JSON.parse(r.content[0].text!) as unknown[]).length).toBeGreaterThan(0);+ });+ expect(reads.filter(sql => sql === 'SELECT key, value FROM config')).toHaveLength(1);+ expect(reads.filter(sql => sql.startsWith('SELECT value FROM config WHERE key'))).toEqual([]);+ });++ test('POST /mcp: the route reads and the dispatched search share one snapshot', async () => {+ const post = () => fetch(`${base}/mcp`, {+ method: 'POST',+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'search', arguments: { query: 'widget renewal', limit: 5 } } }),+ });+ // The client's first call carries the one-time behavior-change disclosure, whose trust-claim read is its own statement.+ await json(await post());+ const reads = await countConfigStatements(async () => {+ const rpc = await json<{ result: { isError?: boolean; content: Array<{ text: string }> } }>(await post());+ expect(rpc.result.isError).toBeFalsy();+ expect((JSON.parse(rpc.result.content[0].text) as unknown[]).length).toBeGreaterThan(0);+ });+ // Token verification runs before the route and may read config on its own; the route reads the table once.+ expect(reads.filter(sql => sql === 'SELECT key, value FROM config')).toHaveLength(1);+ expect(reads.filter(sql => sql.startsWith('SELECT value FROM config WHERE key'))).toEqual([]);+ });+});++describe('the snapshot is scoped to its request', () => {+ test('a request reads its own engine writes; reads after it settles are live', async () => {+ await engine.unsetConfig('test.request_snapshot');+ await withRequestConfigSnapshot(engine, async () => {+ expect(await engine.getConfig('test.request_snapshot')).toBeNull();+ await engine.setConfig('test.request_snapshot', 'one');+ expect(await engine.getConfig('test.request_snapshot')).toBe('one');+ expect((await engine.getAllConfig())['test.request_snapshot']).toBe('one');+ // A write by another path inside the request is not seen until the request ends.+ await engine.executeRaw(`UPDATE config SET value = 'two' WHERE key = 'test.request_snapshot'`);+ expect(await engine.getConfig('test.request_snapshot')).toBe('one');+ await engine.unsetConfig('test.request_snapshot');+ expect(await engine.getConfig('test.request_snapshot')).toBeNull();+ });+ await engine.setConfig('test.request_snapshot', 'three');+ expect(await engine.getConfig('test.request_snapshot')).toBe('three');+ await engine.unsetConfig('test.request_snapshot');+ });++ test('a write op inside a request reads config live', async () => {+ await engine.setConfig('test.request_snapshot', 'before');+ const seen = await withRequestConfigSnapshot(engine, async () => {+ expect(await engine.getConfig('test.request_snapshot')).toBe('before');+ await engine.executeRaw(`UPDATE config SET value = 'after' WHERE key = 'test.request_snapshot'`);+ return withoutRequestConfigSnapshot(() => engine.getConfig('test.request_snapshot'));+ });+ expect(seen).toBe('after');+ await engine.unsetConfig('test.request_snapshot');+ });++ test('work a request started reads live once the request has settled', async () => {+ await engine.setConfig('test.request_snapshot', 'old');+ let later: Promise<string | null> = Promise.resolve(null);+ let release!: () => void;+ const gate = new Promise<void>(resolve => { release = resolve; });+ await withRequestConfigSnapshot(engine, async () => {+ expect(await engine.getConfig('test.request_snapshot')).toBe('old');+ later = gate.then(() => engine.getConfig('test.request_snapshot'));+ });+ await engine.executeRaw(`UPDATE config SET value = 'new' WHERE key = 'test.request_snapshot'`);+ release();+ expect(await later).toBe('new');+ await engine.unsetConfig('test.request_snapshot');+ });++ test('a write op inside a request drops the snapshot, so a later read retakes it', async () => {+ await engine.setConfig('test.request_snapshot', 'first');+ await withRequestConfigSnapshot(engine, async () => {+ expect(await engine.getConfig('test.request_snapshot')).toBe('first');+ await withoutRequestConfigSnapshot(() => engine.executeRaw(`UPDATE config SET value = 'second' WHERE key = 'test.request_snapshot'`));+ expect(await engine.getConfig('test.request_snapshot')).toBe('second');+ });+ await engine.unsetConfig('test.request_snapshot');+ });++ test('another engine object and a failed bulk read both read each key live', async () => {+ await engine.setConfig('test.request_snapshot', 'live');+ const other = Object.create(engine) as PGLiteEngine;+ const failing = Object.assign(Object.create(engine) as PGLiteEngine, { getAllConfig: async () => { throw new Error('bulk read sentinel'); } });+ await withRequestConfigSnapshot(engine, async () => {+ expect(await engine.getConfig('test.request_snapshot')).toBe('live');+ await engine.executeRaw(`UPDATE config SET value = 'changed' WHERE key = 'test.request_snapshot'`);+ expect(await other.getConfig('test.request_snapshot')).toBe('changed');+ });+ const reads = await countConfigStatements(() => withRequestConfigSnapshot(failing, async () => {+ expect(await failing.getConfig('test.request_snapshot')).toBe('changed');+ expect(await failing.getConfig('test.request_snapshot')).toBe('changed');+ }));+ expect(reads.filter(sql => sql.startsWith('SELECT value FROM config WHERE key'))).toHaveLength(2);+ await engine.unsetConfig('test.request_snapshot');+ });+});