Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(serve): a read-only stdio serve runs no resident write duty and holds no session-lane connection (#7599)

garrytan8c9a80080ed7
diff --git a/src/commands/serve.ts b/src/commands/serve.ts
index 3a191bd538..dbbe1893a6 100644
--- a/src/commands/serve.ts
+++ b/src/commands/serve.ts
@@ -13,6 +13,7 @@ import { redirectStdoutLoggingToStderr } from '../core/console-prefix.ts';
import { startFactsDrainScheduler, type FactsDrainScheduler, type FactsDrainSchedulerOpts } from '../core/facts/drain-scheduler.ts';
import { startMovementWatch, type MovementWatch } from '../core/persistence/sync-movement.ts';
import { startServeHeadWatcher } from '../core/serve-head-watcher.ts';
+import { isReadOnlyServeArgs } from '../core/direct-pool-profile.ts';
import { onForwardProgress } from '../core/forward-progress.ts';
import { foregroundWindow } from '../core/foreground-activity.ts';
import { graduationHandoffRequested, writeServeGraduationEnvelope } from '../core/persistence/graduation-serve-guard.ts';
@@ -853,7 +854,9 @@ function installStdioLifecycle(
// it can never hold the process open. Cleared in beginShutdown. Kill
// switch: GBRAIN_SWEEP=0 (seam: opts.sweepEnabled). Chunk-level stdin
// 'data' granularity is sufficient — same rationale as armIdle below.
- const sweepEnabled = opts.sweepEnabled ?? (process.env.GBRAIN_SWEEP !== '0');
+ // #7599: a read-only serve runs no resident write duty (no idle sweep, facts drain, movement watch or on-commit watcher).
+ const readOnly = isReadOnlyServeArgs(args);
+ const sweepEnabled = !readOnly && (opts.sweepEnabled ?? (process.env.GBRAIN_SWEEP !== '0'));
if (sweepEnabled) {
const runIdleSweep = opts.sweep ?? (async (e: BrainEngine) => {
// #4409: the runner loads lazily here too — the sweep fires after
@@ -911,7 +914,7 @@ function installStdioLifecycle(
}
// Automatic facts drain (Lane D) and the #6317 movement watch: see installResidentTickers.
- factsDrain = installResidentTickers(engine, opts, deps, () => shuttingDown);
+ factsDrain = readOnly ? null : installResidentTickers(engine, opts, deps, () => shuttingDown);
// Optional idle-timeout safety net. Default OFF; opt-in via
// `--stdio-idle-timeout <seconds>`. The flag is for the rare case where
diff --git a/src/core/direct-pool-profile.ts b/src/core/direct-pool-profile.ts
index 6986f6fc3a..d0069efe48 100644
--- a/src/core/direct-pool-profile.ts
+++ b/src/core/direct-pool-profile.ts
@@ -2,7 +2,8 @@
* How much of the direct (session) lane this process may hold. The CLI sets it
* once per command; every other caller (embedders, tests) stays resident.
* - resident: daemons (serve, jobs, autopilot, sync --watch) keep the full pool; a stdio
- * `serve --access read-only` is one_shot instead (#7599), since harnesses run one per session.
+ * `serve --access read-only` is one_shot instead (#7599): harnesses run one per session, and it
+ * starts no persistence consumer, takes no notifier lease and runs no sweep.
* - short_lived: a command that owns a consumer or takes a lease gets one connection.
* - one_shot: a command that takes no lease routes nothing through the direct
* pool; schema DDL still uses one connection for its session advisory lock
@@ -20,8 +21,14 @@ const SHORT_LIVED_COMMANDS = new Set(['sync', 'mcp', 'dream', 'cycle', 'sources'
let processProfile: DirectPoolProfile = 'resident';
+/** `serve ... --access read-only`: a stdio serve that runs no resident write duty (#7599). */
+export function isReadOnlyServeArgs(args: readonly string[]): boolean {
+ const at = args.indexOf('--access');
+ return at >= 0 && args[at + 1] === 'read-only';
+}
+
export function directPoolProfileForCommand(command: string, args: readonly string[]): DirectPoolProfile {
- if (command === 'serve' && args.includes('--access') && args[args.indexOf('--access') + 1] === 'read-only') return 'one_shot';
+ if (command === 'serve' && isReadOnlyServeArgs(args)) return 'one_shot';
if (RESIDENT_COMMANDS.has(command) || (command === 'sync' && args.includes('--watch'))) return 'resident';
return SHORT_LIVED_COMMANDS.has(command) ? 'short_lived' : 'one_shot';
}
diff --git a/src/mcp/resolve-ipc-binding.ts b/src/mcp/resolve-ipc-binding.ts
index 90fd664483..947587c881 100644
--- a/src/mcp/resolve-ipc-binding.ts
+++ b/src/mcp/resolve-ipc-binding.ts
@@ -143,6 +143,8 @@ export async function bindResolveIpcForServe(
persistenceProvider?: PersistenceIpcProvider,
opts: {
rememberCallable?: boolean | (() => boolean);
+ /** #7599: a read-only stdio serve registers no delegated sync, nudge or sweep kind (clients get the polite refusal). */
+ readOnly?: boolean;
/** Delay before each re-bind attempt of a socket this serve does not hold; tests inject a short one. */
rebindDelayMs?: () => number;
} = {},
@@ -191,8 +193,9 @@ export async function bindResolveIpcForServe(
// catch would otherwise swallow the error and start NO listener).
// Kill switch: GBRAIN_SERVE_SYNC_IPC=0 → the kinds are simply not
// registered and clients get 'unsupported_kind' (the polite refusal).
+ const delegation = process.env.GBRAIN_SERVE_SYNC_IPC !== '0' && !opts.readOnly;
let syncHandlers: Pick<IpcHandlers, 'sync_start' | 'sync_status' | 'sync_abort' | 'sync_nudge'> = {};
- if (process.env.GBRAIN_SERVE_SYNC_IPC !== '0') {
+ if (delegation) {
try {
const runner = await import('../core/serve-sync-runner.ts');
syncHandlers = {
@@ -217,7 +220,7 @@ export async function bindResolveIpcForServe(
// try/catch so a runner failure never takes the other kinds down.
// Shares the GBRAIN_SERVE_SYNC_IPC kill switch (one delegation family).
let sweepHandlers: Pick<IpcHandlers, 'sweep_start' | 'sweep_status'> = {};
- if (process.env.GBRAIN_SERVE_SYNC_IPC !== '0') {
+ if (delegation) {
try {
const sweepRunner = await import('../core/serve-sweep-runner.ts');
sweepHandlers = {
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index dda7e3b742..ff4a69a737 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -529,10 +529,18 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
const [{ createPersistenceIpcProvider, residentPersistenceConfig }, { bindResolveIpcForServe }] = await Promise.all([import('../core/persistence/provider.ts'), import('./resolve-ipc-binding.ts')]);
bootPhase('source_scope');
const { sourceId: ipcSourceId } = await resolveMcpStdioSourceScope(engine);
+ // #7599: a read-only serve runs no resident write duty: no persistence consumer, no delegated sync, nudge or sweep,
+ // no session-cursor GC and no sweep of its own (serve.ts also skips the idle sweep, facts drain and on-commit watcher).
+ // The long-lived serve, worker or autopilot owns them; doctor's commit_notifier and two_consumers_on_host say when none runs.
bootPhase('persistence_consumer');
- const persistence = await createPersistenceIpcProvider(engine, residentPersistenceConfig(config) ?? { engine: engine.kind });
+ const persistence = session.readOnly ? undefined : await createPersistenceIpcProvider(engine, residentPersistenceConfig(config) ?? { engine: engine.kind });
bootPhase('resolve_ipc_bind');
- ipcBinding = await bindResolveIpcForServe(engine, ipcSourceId, persistence, { rememberCallable: () => !session.allowedOps || session.allowedOps.has('remember') });
+ ipcBinding = await bindResolveIpcForServe(engine, ipcSourceId, persistence, { rememberCallable: () => !session.allowedOps || session.allowedOps.has('remember'), ...(session.readOnly ? { readOnly: true } : {}) });
+ if (session.readOnly) {
+ process.stderr.write('[gbrain-serve] read-only: no persistence consumer, on-commit sync or sweep runs here; a read-write serve, jobs work or autopilot owns them.\n');
+ import('../core/onboard/mcp-onboarding.ts').then(m => m.startOnboardingRefresher(engine, { idle: () => _stdioRpcsInFlight === 0 })).catch(() => { /* coaching is best-effort */ });
+ return;
+ }
// v0.45.7 ambient recall: age out stale session cursors once per serve boot
// (7-day TTL, indexed DELETE). Best-effort — GC failure never blocks serve.
diff --git a/test/e2e/serve-read-only-session-lane-postgres.test.ts b/test/e2e/serve-read-only-session-lane-postgres.test.ts
new file mode 100644
index 0000000000..47c7685faf
--- /dev/null
+++ b/test/e2e/serve-read-only-session-lane-postgres.test.ts
@@ -0,0 +1,118 @@
+/**
+ * #7599: a harness runs one stdio `gbrain serve --access read-only` per session, so each one's resident direct pool held
+ * session-lane connections (3 each) and a few sessions could starve the long-lived serve, worker and autopilot. A read-only
+ * serve now takes the one-shot direct-pool profile and runs no resident write duty (persistence consumer, on-commit
+ * notifier lease, sweeps), so it holds no session-lane connection after startup or after a search. A read-write serve
+ * keeps its 3. The direct lane is tagged with an application_name so pg_stat_activity counts only it. Runs when
+ * DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { spawn, type ChildProcess } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { withManagedFixtureWrite } from '../helpers/managed-e2e-fixture-write.ts';
+import { keylessBrainEnv } from '../helpers/provider-env.ts';
+
+const DATABASE_URL = process.env.DATABASE_URL;
+const WORD = 'quillmarsh';
+
+describe.skipIf(!DATABASE_URL)('#7599 serve --access read-only on the session lane (postgres)', () => {
+ let home: string;
+ let env: Record<string, string>;
+ let close: (() => Promise<void>) | undefined;
+ let admin: PostgresEngine | null = null;
+ let tag = '';
+ let directBase = '';
+ let serve: ChildProcess | null = null;
+
+ const directConnections = async () => Number((await admin!.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pg_stat_activity WHERE application_name = $1', [tag]))[0]!.n);
+
+ async function startServe(access: 'read-only' | 'full'): Promise<{ call: (id: number, method: string, params: object) => Promise<any>; log: () => string }> {
+ let log = '';
+ let out = '';
+ tag = `gbrain_direct_7599_${access.replace('-', '_')}_${process.pid}`;
+ const direct = new URL(directBase);
+ direct.searchParams.set('application_name', tag);
+ const child = spawn('bun', ['--no-env-file', 'run', 'src/cli.ts', 'serve', '--surface', 'full', '--access', access],
+ { cwd: process.cwd(), env: { ...env, GBRAIN_DIRECT_DATABASE_URL: direct.toString() }, stdio: ['pipe', 'pipe', 'pipe'] });
+ serve = child;
+ child.stderr!.on('data', data => { log += String(data); });
+ child.stdout!.on('data', data => { out += String(data); });
+ const call = async (id: number, method: string, params: object) => {
+ child.stdin!.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');
+ for (let i = 0; i < 240; i++) {
+ const line = out.split('\n').find(l => l.includes(`"id":${id}`));
+ if (line) return JSON.parse(line);
+ await Bun.sleep(250);
+ }
+ throw new Error(`no response to ${method}; serve log:\n${log}`);
+ };
+ await call(1, 'initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'test-7599', version: '1' } });
+ child.stdin!.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n');
+ return { call, log: () => log };
+ }
+
+ async function stopServe(): Promise<void> {
+ const child = serve;
+ serve = null;
+ if (!child || child.exitCode !== null || child.signalCode !== null) return;
+ await new Promise<void>(resolve => {
+ const deadline = setTimeout(() => child.kill('SIGKILL'), 5_000);
+ child.once('exit', () => { clearTimeout(deadline); resolve(); });
+ child.stdin!.end();
+ });
+ }
+
+ beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-7599-'));
+ const isolated = await isolatedPersistencePostgres(DATABASE_URL!);
+ close = isolated.close;
+ await importFromContent(isolated.engine, 'notes/alpha-example', `---\ntitle: notes/alpha-example\ntype: note\n---\n\n${WORD} synthetic page.\n`, {
+ sourceId: 'default', noEmbed: true,
+ prepare: async prepared => { await withManagedFixtureWrite(isolated.engine, ['default'], tx => prepared.apply(tx)); return prepared.result; },
+ });
+ await isolated.engine.disconnect();
+ mkdirSync(join(home, '.gbrain'));
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', database_url: isolated.databaseUrl }));
+ directBase = isolated.databaseUrl;
+ env = keylessBrainEnv(process.env, home, {
+ DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_ENGINE: undefined, GBRAIN_SOURCE: undefined,
+ GBRAIN_DISABLE_DIRECT_POOL: undefined, GBRAIN_DIRECT_POOL_SIZE: undefined,
+ GBRAIN_DIRECT_POOL_BY_COMMAND: undefined, GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_NO_RETRY_CONNECT: '1',
+ });
+ admin = new PostgresEngine();
+ await admin.connect({ database_url: DATABASE_URL!, poolSize: 1 });
+ }, 180_000);
+
+ afterAll(async () => {
+ await stopServe();
+ await admin?.disconnect();
+ await close?.();
+ if (home) rmSync(home, { recursive: true, force: true });
+ }, 60_000);
+
+ test('a read-only serve holds no session-lane connection after startup or after a search, and runs no resident write duty', async () => {
+ const s = await startServe('read-only');
+ await Bun.sleep(5_000);
+ expect(await directConnections()).toBe(0);
+ const found = await s.call(2, 'tools/call', { name: 'search', arguments: { query: WORD } });
+ expect(JSON.stringify(found.result)).toContain('notes/alpha-example');
+ await Bun.sleep(2_000);
+ expect(await directConnections()).toBe(0);
+ expect(s.log()).toContain('[gbrain-serve] read-only: no persistence consumer, on-commit sync or sweep runs here');
+ expect(s.log()).not.toContain("owner of this host's notifier");
+ await stopServe();
+ }, 120_000);
+
+ test('a read-write serve keeps its 3-connection resident direct pool', async () => {
+ await startServe('full');
+ let n = 0;
+ for (let i = 0; i < 60 && n < 3; i++) { n = await directConnections(); if (n < 3) await Bun.sleep(500); }
+ expect(n).toBe(3);
+ await stopServe();
+ }, 120_000);
+});