Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(postgres): the direct pool follows the command: 3 for daemons, 1 for short-lived commands, none for one-shot commands without a lease

garrytanb5948e179f26
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 5a696d6d42..22ee959bcf 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -780,7 +780,7 @@ Size the pooler for every process at once:
```
long-running processes x GBRAIN_POOL_SIZE
- + processes whose direct route lands on this pooler x GBRAIN_DIRECT_POOL_SIZE (default 3)
+ + processes whose direct route lands on this pooler x their direct pool (see below)
+ one-shot commands running at the same time x their pool (a full `gbrain sync` is one too)
+ parallel import workers x 2 (an unmanaged sync of more than 100 files, `--workers N`, or the sync a serve runs)
<= the pooler's client limit (Supabase Supavisor: the project's pool_size)
@@ -795,6 +795,21 @@ defaults (10 + 3 each) already pass a client limit of 25, so a scheduled
`gbrain sync` next to a `gbrain serve` on the same session port can exhaust it.
`GBRAIN_MAX_CONNECTIONS` caps a sync's worker fan-out to fit a budget.
+<a id="direct-pool-by-command"></a>The direct pool's size follows the command.
+`gbrain serve`, `gbrain jobs`, `gbrain autopilot` and `gbrain sync --watch`
+open up to 3 direct connections. A command that exits but owns writes or takes
+a lease (`sync`, `put`, `import`, `dream`, `cycle`, `sources`, `mcp`,
+`migrate-graduation`) and the diagnostics that report the route (`doctor`,
+`engine`) open 1. Every other command routes nothing through the direct pool:
+its statements use the ordinary pool, as with `GBRAIN_DISABLE_DIRECT_POOL=1`.
+Two exceptions keep the direct route for it: applying pending schema
+migrations (one connection, for the session advisory lock and the 30-minute
+statement timeout), and taking a lease such as an embed or extract lock
+(the command then opens 1, so the lease heartbeat keeps its own connection).
+`GBRAIN_DIRECT_POOL_SIZE` still sets the size wherever a direct pool opens.
+`GBRAIN_DIRECT_POOL_BY_COMMAND=0` restores the earlier behavior: every command
+may open the full 3-connection direct pool.
+
When the sum does not fit, run fewer long-running processes (for example one
shared `gbrain serve --http` instead of one stdio `serve` per agent session),
or raise the pooler's limit. Do not lower a long-running process below 6.
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.md
index 2a92fe17b3..bc221f067d 100644
--- a/docs/architecture/key-files/engines-1.md
+++ b/docs/architecture/key-files/engines-1.md
@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- Primary `searchVector` generation filters in both engines require the resolved model and either a current embedded-text hash or a grandfathered pre-v133 NULL hash. A budget/resume marker alone never changes a matching-model legacy vector's eligibility; known stale hashes and incompatible models remain excluded. On HNSW-indexed columns the hash test runs after the candidate scan (see `search/vector-statement.ts`), so a stale chunk can occupy a candidate slot but never a result. This does not infer provenance for legacy fact vectors. `test/legacy-vector-compatibility.test.ts` and its PostgreSQL wrapper pin actual hybrid retrieval through a failed provider probe and retained migration marker without rewriting stored vectors.
-- `src/core/connection-manager.ts` — routes ordinary and direct Postgres pools. Supabase-shaped URLs retain automatic derivation; a valid explicit `GBRAIN_DIRECT_DATABASE_URL` or constructor override also enables dual routing for generic Postgres and PgBouncer on custom ports. The kill switch and inherited parent route stay authoritative. `describeMode()` reports the same route used by `ddl()` and `bulk()`. Regression coverage: `test/connection-manager.serial.test.ts` and the real 24-case persistence runtime matrix.
+- `src/core/connection-manager.ts` — routes ordinary and direct Postgres pools. Supabase-shaped URLs derive the direct route; a valid explicit `GBRAIN_DIRECT_DATABASE_URL` or constructor override enables it for generic Postgres and custom-port PgBouncer. The kill switch and inherited parent route stay authoritative. `direct-pool-profile.ts` (per CLI command) sizes it: resident 3, short-lived 1, one-shot none until a lease; DDL stays direct. Tests: `test/connection-manager.serial.test.ts`, `test/direct-pool-profile.test.ts`.
- `src/core/db-lock.ts` + `lease-schema.ts` — row leases survive transaction-mode PgBouncer. Migration 152 gives every `gbrain_cycle_locks` acquisition a UUID; refresh/release, takeover/reaper and manual/age-gated breaks match (id, holder_pid, acquisition_token), never the `acquired_at` epoch text, which is diagnostics only (#6028). `withRefreshingLock` always passes an aborting work signal, rejects results after ownership loss/TTL expiry, tracks a single actual renewal through timeout cancellation, and drains late completion before release. Release uses the live pool, surviving `engine.reconnect()`. Renewal deadlines start before the database round trip. `performSync` composes this signal with caller cancellation. `inspectLock`, `listStaleLocks`, `listLiveLocks`, `classifyHolderLiveness` and namespace-scoped `reapDeadHolderLocks` keep their status/recovery contracts. Tests: `test/db-lock-concurrency.test.ts`, `test/db-lock-token-predicate.test.ts`, `test/e2e/db-lock-acquisition-token.test.ts`, fencing/reaper/inspection suites.
diff --git a/llms-full.txt b/llms-full.txt
index 9026a08a0e..226dc22ff2 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -6095,7 +6095,7 @@ Size the pooler for every process at once:
```
long-running processes x GBRAIN_POOL_SIZE
- + processes whose direct route lands on this pooler x GBRAIN_DIRECT_POOL_SIZE (default 3)
+ + processes whose direct route lands on this pooler x their direct pool (see below)
+ one-shot commands running at the same time x their pool (a full `gbrain sync` is one too)
+ parallel import workers x 2 (an unmanaged sync of more than 100 files, `--workers N`, or the sync a serve runs)
<= the pooler's client limit (Supabase Supavisor: the project's pool_size)
@@ -6110,6 +6110,21 @@ defaults (10 + 3 each) already pass a client limit of 25, so a scheduled
`gbrain sync` next to a `gbrain serve` on the same session port can exhaust it.
`GBRAIN_MAX_CONNECTIONS` caps a sync's worker fan-out to fit a budget.
+<a id="direct-pool-by-command"></a>The direct pool's size follows the command.
+`gbrain serve`, `gbrain jobs`, `gbrain autopilot` and `gbrain sync --watch`
+open up to 3 direct connections. A command that exits but owns writes or takes
+a lease (`sync`, `put`, `import`, `dream`, `cycle`, `sources`, `mcp`,
+`migrate-graduation`) and the diagnostics that report the route (`doctor`,
+`engine`) open 1. Every other command routes nothing through the direct pool:
+its statements use the ordinary pool, as with `GBRAIN_DISABLE_DIRECT_POOL=1`.
+Two exceptions keep the direct route for it: applying pending schema
+migrations (one connection, for the session advisory lock and the 30-minute
+statement timeout), and taking a lease such as an embed or extract lock
+(the command then opens 1, so the lease heartbeat keeps its own connection).
+`GBRAIN_DIRECT_POOL_SIZE` still sets the size wherever a direct pool opens.
+`GBRAIN_DIRECT_POOL_BY_COMMAND=0` restores the earlier behavior: every command
+may open the full 3-connection direct pool.
+
When the sum does not fit, run fewer long-running processes (for example one
shared `gbrain serve --http` instead of one stdio `serve` per agent session),
or raise the pooler's limit. Do not lower a long-running process below 6.
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 223b4b997f..8515484a53 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -367,6 +367,10 @@ async function main() {
command = routed.command;
const subArgs = routed.subArgs;
dispatchedCommand = command;
+ {
+ const { directPoolProfileForCommand, setDirectPoolProfile } = await import('../core/direct-pool-profile.ts');
+ setDirectPoolProfile(directPoolProfileForCommand(command, subArgs));
+ }
// Local patch 2026-06-11 — mark one-shot CLI processes so the facts
// backstop routes absorb work to the durable jobs worker instead of the
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index b4e1766b04..b1e442958f 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1095,6 +1095,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// GBRA-133 (file-drift provenance, database and signal stops). `since` is stamped at the merge slot.
{ since: '0.60.359.0', text: 'A `gbrain repair file-drift --held --side deleted --state file_gone` preview names each gone file\'s provenance (`details.pages[].provenance`, counted in `details.provenance`): the newest commit of HEAD\'s full history that deleted it (sha, author, date, subject), `never_committed` when no commit held it, or `deletion_uncommitted` when HEAD still holds it. New `--provenance never_committed|deleted_by_commit|deletion_uncommitted` keeps only the holds of one provenance. `--provenance never_committed --prefer database` keeps each page database-only: no file is written, the page forgets its recorded path (`database_only_reason=detached`) and the hold is cleared, so the next sync holds nothing again; `--prefer file` with it is refused, since each page holds the only copy.' },
{ since: '0.60.359.0', text: 'A `gbrain repair <kind> --apply` that the database refuses mid-run (deadlock 40P01, serialization failure 40001, a lost connection) now stops with a result (`stopped.reason` `database_contention` or `connection_lost`, the SQLSTATE in its message, what it applied, and the command that resumes from the refused item) instead of ending with an error and, under `--json`, no record of what it applied. A SIGTERM or SIGHUP (an outer timeout, a closed terminal) stops the apply before its next item with `stopped.reason: interrupted` and the same result; a second signal exits at once.' },
+ // GBRA-133 (direct pool by command). `since` is stamped at the merge slot.
+ { since: 'TBD', text: 'Behind a split pooler route (a Supabase pooler URL or `GBRAIN_DIRECT_DATABASE_URL`), the direct pool now follows the command (approved by the maintainer, 2026-10-21). `gbrain serve`, `jobs`, `autopilot` and `sync --watch` keep up to 3 direct connections. `sync`, `put`, `import`, `dream`, `cycle`, `sources`, `mcp`, `migrate-graduation`, `doctor` and `engine` open 1. Every other command opens none and runs its statements on the ordinary pool, except to apply pending schema migrations or once it takes a lease, when it opens 1. `gbrain engine status --probe` reports the profile as `mode.direct_profile` (and `single (one-shot command)` where the route is configured but unused). `GBRAIN_DIRECT_POOL_SIZE` still sets the size; `GBRAIN_DIRECT_POOL_BY_COMMAND=0` restores the earlier behavior.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/connection-manager.ts b/src/core/connection-manager.ts
index 907e881c7d..c7f1b5ead7 100644
--- a/src/core/connection-manager.ts
+++ b/src/core/connection-manager.ts
@@ -41,6 +41,7 @@ import { traceSqlOptions } from './sql-trace.ts';
import { gbrainApplicationName, readPoolPipelineOptions, transactionPipelineOptions, resolvePrepare, resolveSessionTimeouts, resolvePoolSize, resolveMaxLifetimeSeconds, resolveUrlConnectTimeout, resolveSharedTypes, resolveArrayTypes, endPoolBounded, poolHealthOptions, type PoolHealthHooks } from './db.ts';
import { redactPgUrl } from './url-redact.ts';
import { logConnectionEvent } from './connection-audit.ts';
+import { directPoolProfile, type DirectPoolProfile } from './direct-pool-profile.ts';
export type Sql = ReturnType<typeof postgres>;
@@ -251,7 +252,8 @@ export function readKillSwitchEnv(): boolean {
}
/**
- * Resolve direct pool size: explicit > env > default.
+ * Resolve direct pool size: explicit > env > the process profile's default
+ * (3 for a resident process, 1 otherwise).
*/
export function resolveDirectPoolSize(explicit?: number): number {
if (typeof explicit === 'number' && explicit > 0) return explicit;
@@ -260,7 +262,7 @@ export function resolveDirectPoolSize(explicit?: number): number {
const parsed = parseInt(raw, 10);
if (Number.isFinite(parsed) && parsed > 0 && parsed <= 20) return parsed;
}
- return DEFAULT_DIRECT_POOL_SIZE;
+ return directPoolProfile() === 'resident' ? DEFAULT_DIRECT_POOL_SIZE : 1;
}
export class ConnectionManager {
@@ -306,7 +308,12 @@ export class ConnectionManager {
}
/** Known poolers derive their route; other deployments require a valid explicit override. */
+ /** Statements route through the direct pool. A one-shot command keeps it for schema DDL only (`ddl()`). */
isDualPoolActive(): boolean {
+ return directPoolProfile() !== 'one_shot' && this.isDirectRouteConfigured();
+ }
+
+ private isDirectRouteConfigured(): boolean {
if (this._killSwitch || !this._directUrl) return false;
if (this._isSupabase) return true;
if (this._directUrlAutoDerived) return false;
@@ -381,12 +388,14 @@ export class ConnectionManager {
/**
* Acquire (and lazy-init) the direct DDL pool. The kill switch or an
* unconfigured direct route returns the read pool (single-pool fallback).
+ * A one-shot command still gets the direct pool here: schema DDL needs its
+ * session advisory lock and long statement timeout.
*
* A1: lazy init wraps in a cached Promise<Sql> so concurrent first-callers
* await the same init instead of racing two pool constructions.
*/
async ddl(): Promise<Sql> {
- if (!this.isDualPoolActive()) {
+ if (!this.isDirectRouteConfigured()) {
return this.getReadPool();
}
return this.getDirectPool();
@@ -595,13 +604,15 @@ export class ConnectionManager {
* Diagnostic snapshot for doctor / get_health surfaces.
*/
describeMode(): {
- mode: 'split' | 'single (kill-switch)' | 'single (non-supabase)' | 'single (no-direct-url)';
+ mode: 'split' | 'single (kill-switch)' | 'single (non-supabase)' | 'single (no-direct-url)' | 'single (one-shot command)';
direct_host?: string;
kill_switch_active: boolean;
direct_pool_size: number;
+ direct_profile: DirectPoolProfile;
} {
- let mode: 'split' | 'single (kill-switch)' | 'single (non-supabase)' | 'single (no-direct-url)';
+ let mode: 'split' | 'single (kill-switch)' | 'single (non-supabase)' | 'single (no-direct-url)' | 'single (one-shot command)';
if (this.isDualPoolActive()) mode = 'split';
+ else if (this.isDirectRouteConfigured()) mode = 'single (one-shot command)';
else if (this._killSwitch && (this._isSupabase || this._directUrl)) mode = 'single (kill-switch)';
else if (!this._isSupabase) mode = 'single (non-supabase)';
else mode = 'single (no-direct-url)';
@@ -610,6 +621,7 @@ export class ConnectionManager {
direct_host: this._directUrl ? this.hostOnly(this._directUrl) : undefined,
kill_switch_active: this._killSwitch,
direct_pool_size: resolveDirectPoolSize(this.opts.directPoolSize),
+ direct_profile: directPoolProfile(),
};
}
diff --git a/src/core/db-lock.ts b/src/core/db-lock.ts
index a5fda12fbf..9b86c3bb5e 100644
--- a/src/core/db-lock.ts
+++ b/src/core/db-lock.ts
@@ -24,6 +24,7 @@
import { hostname } from 'os';
import { randomUUID } from 'node:crypto';
import type { BrainEngine } from './engine.ts';
+import { noteDirectPoolLease } from './direct-pool-profile.ts';
export interface DbLockHandle {
id: string;
@@ -266,6 +267,7 @@ export async function tryAcquireDbLock(
RETURNING id, extract(epoch from acquired_at)::text AS fence
`;
if (rows.length === 0) return null;
+ noteDirectPoolLease();
// The UUID is the fence; the epoch text rides on the handle for
// diagnostics (migration-orchestration-lock.ts reports it when a lease
// is lost) and is never compared (#6028).
diff --git a/src/core/direct-pool-profile.ts b/src/core/direct-pool-profile.ts
new file mode 100644
index 0000000000..a732ad525e
--- /dev/null
+++ b/src/core/direct-pool-profile.ts
@@ -0,0 +1,37 @@
+/**
+ * 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.
+ * - 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
+ * and long statement timeout. Taking a lease makes it short_lived.
+ * GBRAIN_DIRECT_POOL_BY_COMMAND=0 restores the earlier behavior: resident everywhere.
+ *
+ * No imports: db-lock.ts reads this on PGLite too.
+ */
+export type DirectPoolProfile = 'resident' | 'short_lived' | 'one_shot';
+
+const RESIDENT_COMMANDS = new Set(['serve', 'jobs', 'autopilot']);
+/** The claim owners (persistence/claim-phase.ts) that exit, plus the diagnostics that report the direct route. */
+const SHORT_LIVED_COMMANDS = new Set(['sync', 'mcp', 'dream', 'cycle', 'sources', 'migrate-graduation', 'put', 'import', 'doctor', 'engine']);
+
+let processProfile: DirectPoolProfile = 'resident';
+
+export function directPoolProfileForCommand(command: string, args: readonly string[]): DirectPoolProfile {
+ if (RESIDENT_COMMANDS.has(command) || (command === 'sync' && args.includes('--watch'))) return 'resident';
+ return SHORT_LIVED_COMMANDS.has(command) ? 'short_lived' : 'one_shot';
+}
+
+export function setDirectPoolProfile(profile: DirectPoolProfile): void {
+ processProfile = profile;
+}
+
+/** A one-shot command that takes a lease renews it on the direct lane, so it becomes short-lived. */
+export function noteDirectPoolLease(): void {
+ if (processProfile === 'one_shot') processProfile = 'short_lived';
+}
+
+export function directPoolProfile(): DirectPoolProfile {
+ return process.env.GBRAIN_DIRECT_POOL_BY_COMMAND === '0' ? 'resident' : processProfile;
+}
diff --git a/src/core/persistence/claim-phase.ts b/src/core/persistence/claim-phase.ts
index 860f181226..cade410fca 100644
--- a/src/core/persistence/claim-phase.ts
+++ b/src/core/persistence/claim-phase.ts
@@ -126,7 +126,7 @@ export function isOwnerThisProcess(owner: Pick<ClaimOwner, 'pid' | 'nonce'> | nu
return claimOwnerIsThisProcess(owner);
}
-const OWNER_COMMANDS = new Set(['sync', 'serve', 'jobs', 'autopilot', 'mcp', 'dream', 'cycle', 'sources', 'migrate-graduation', 'put', 'import']);
+export const OWNER_COMMANDS: ReadonlySet<string> = new Set(['sync', 'serve', 'jobs', 'autopilot', 'mcp', 'dream', 'cycle', 'sources', 'migrate-graduation', 'put', 'import']);
let ownerOverride: ClaimOwner | undefined;
/** The gbrain command this process runs (`cli` when none is recognisable). */
export function claimOwnerKind(): string {
diff --git a/test/cli-socket.test.ts b/test/cli-socket.test.ts
index 39d0fbc76d..1e150ff09b 100644
--- a/test/cli-socket.test.ts
+++ b/test/cli-socket.test.ts
@@ -85,7 +85,7 @@ const NOT_READ_BEHAVIOR_PREFIXES = [
const NOT_READ_BEHAVIOR = new Set([
'GBRAIN_HOME', 'GBRAIN_BRAIN_ID', 'GBRAIN_MOUNTS_PATH', 'GBRAIN_CWD_ENV_QUARANTINED',
'GBRAIN_FAIL_ON_EMPTY', 'GBRAIN_CLI_SOCKET', 'GBRAIN_DEBUG', 'GBRAIN_SQL_TRACE', 'GBRAIN_SQL_TRACE_LABEL', 'GBRAIN_LME_DEBUG', 'GBRAIN_SOURCE',
- 'GBRAIN_DATABASE_URL', 'GBRAIN_DIRECT_DATABASE_URL', 'GBRAIN_DIRECT_POOL_SIZE', 'GBRAIN_DISABLE_DIRECT_POOL', 'GBRAIN_PREPARE',
+ 'GBRAIN_DATABASE_URL', 'GBRAIN_DIRECT_DATABASE_URL', 'GBRAIN_DIRECT_POOL_SIZE', 'GBRAIN_DIRECT_POOL_BY_COMMAND', 'GBRAIN_DISABLE_DIRECT_POOL', 'GBRAIN_PREPARE',
'GBRAIN_IDLE_TX_TIMEOUT', 'GBRAIN_MAX_CONNECTIONS', 'GBRAIN_NO_RETRY_CONNECT', 'GBRAIN_DB_ACCESS',
'GBRAIN_ACCEPT_PENDING', 'GBRAIN_ACCEPT_SILENT_WIDEN', 'GBRAIN_WRITE_WAIT_MS', 'GBRAIN_PREADMIT_CACHE', 'GBRAIN_PREPARATION_DEADLINES',
'GBRAIN_SINGLE_CONSUMER', 'GBRAIN_SINGLE_WRITE_GROUP', 'GBRAIN_CONSUMER_DIRECT_LANE', 'GBRAIN_COMMIT_LOCK_WAIT_SECONDS',
diff --git a/test/direct-pool-profile.test.ts b/test/direct-pool-profile.test.ts
new file mode 100644
index 0000000000..d7d7265bd0
--- /dev/null
+++ b/test/direct-pool-profile.test.ts
@@ -0,0 +1,147 @@
+/**
+ * The direct (session) pool follows the command (Garry, 2026-10-21). Daemons keep the 3-connection pool; a short-lived
+ * command that owns a consumer or takes a lease gets one connection; a one-shot command that takes no lease routes
+ * nothing through it until it takes a lease, while schema DDL keeps the direct route for its session advisory lock and
+ * 30-minute statement timeout. `GBRAIN_DIRECT_POOL_BY_COMMAND=0` restores the earlier behavior. Pure resolution, then
+ * real PGLite and Postgres (when DATABASE_URL is set) with the direct route pointed at the test database.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { ConnectionManager, resolveDirectPoolSize } from '../src/core/connection-manager.ts';
+import { directPoolProfile, directPoolProfileForCommand, setDirectPoolProfile } from '../src/core/direct-pool-profile.ts';
+import { OWNER_COMMANDS } from '../src/core/persistence/claim-phase.ts';
+import { tryAcquireDbLock } from '../src/core/db-lock.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../src/core/postgres-engine.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const DIRECT_STATEMENT_TIMEOUT = '30min';
+const ROUTE = { GBRAIN_DIRECT_POOL_SIZE: undefined, GBRAIN_DIRECT_POOL_BY_COMMAND: undefined, GBRAIN_DISABLE_DIRECT_POOL: undefined };
+
+let pglite: PGLiteEngine | null = null;
+
+beforeAll(async () => {
+ if (!testBackends().includes('pglite')) return;
+ pglite = new PGLiteEngine();
+ await pglite.connect({ database_url: '' });
+ await pglite.initSchema();
+}, 60_000);
+
+afterAll(async () => { await pglite?.disconnect(); });
+
+afterEach(() => setDirectPoolProfile('resident'));
+
+describe('directPoolProfileForCommand', () => {
+ test('daemons are resident, exiting claim owners and route diagnostics short-lived, everything else one-shot', () => {
+ for (const command of ['serve', 'jobs', 'autopilot']) expect(directPoolProfileForCommand(command, [])).toBe('resident');
+ expect(directPoolProfileForCommand('sync', ['--watch'])).toBe('resident');
+ for (const command of ['sync', 'put', 'import', 'dream', 'cycle', 'sources', 'mcp', 'migrate-graduation', 'doctor', 'engine'])
+ expect(directPoolProfileForCommand(command, [])).toBe('short_lived');
+ for (const command of ['search', 'query', 'get', 'capture', 'embed', 'extract', 'apply-migrations'])
+ expect(directPoolProfileForCommand(command, [])).toBe('one_shot');
+ });
+
+ test('every claim owner keeps a direct route', () => {
+ for (const command of OWNER_COMMANDS) expect(directPoolProfileForCommand(command, [])).not.toBe('one_shot');
+ });
+});
+
+describe('direct pool size and routing by profile', () => {
+ const manager = () => new ConnectionManager({ url: 'postgresql://u:p@localhost:5432/db', directUrl: 'postgresql://u:p@localhost:5433/db' });
+
+ test('resident keeps 3 and the route; short-lived gets 1 and the route; one-shot gets no route', async () => {
+ await withEnv(ROUTE, async () => {
+ expect(resolveDirectPoolSize()).toBe(3);
+ expect(manager().isDualPoolActive()).toBe(true);
+ setDirectPoolProfile('short_lived');
+ expect(resolveDirectPoolSize()).toBe(1);
+ expect(manager().isDualPoolActive()).toBe(true);
+ setDirectPoolProfile('one_shot');
+ expect(manager().isDualPoolActive()).toBe(false);
+ expect(manager().describeMode()).toMatchObject({ mode: 'single (one-shot command)', direct_profile: 'one_shot', direct_pool_size: 1 });
+ });
+ });
+
+ test('GBRAIN_DIRECT_POOL_SIZE still sets the size, and the kill switch still wins', async () => {
+ setDirectPoolProfile('short_lived');
+ await withEnv({ ...ROUTE, GBRAIN_DIRECT_POOL_SIZE: '5' }, async () => { expect(resolveDirectPoolSize()).toBe(5); });
+ await withEnv({ ...ROUTE, GBRAIN_DISABLE_DIRECT_POOL: '1' }, async () => {
+ expect(manager().isDualPoolActive()).toBe(false);
+ expect(manager().describeMode().mode).toBe('single (kill-switch)');
+ });
+ });
+
+ test('GBRAIN_DIRECT_POOL_BY_COMMAND=0 restores the earlier behavior for every command', async () => {
+ setDirectPoolProfile('one_shot');
+ await withEnv({ ...ROUTE, GBRAIN_DIRECT_POOL_BY_COMMAND: '0' }, async () => {
+ expect(directPoolProfile()).toBe('resident');
+ expect(resolveDirectPoolSize()).toBe(3);
+ expect(manager().isDualPoolActive()).toBe(true);
+ });
+ });
+});
+
+describe('real engines', () => {
+ for (const backend of testBackends()) {
+ test(`${backend}: a one-shot command routes nothing direct until it takes a lease; schema DDL keeps the direct route`, async () => {
+ if (backend === 'pglite') {
+ setDirectPoolProfile('one_shot');
+ const handle = await tryAcquireDbLock(pglite!, 'test-direct-pool-profile', 5);
+ expect(handle).not.toBeNull();
+ expect(await handle!.refresh()).toBe(true);
+ await handle!.release();
+ expect(directPoolProfile()).toBe('one_shot');
+ return;
+ }
+ const brain = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ const engine = new PostgresEngine();
+ try {
+ await withEnv({ ...ROUTE, GBRAIN_DIRECT_DATABASE_URL: brain.databaseUrl }, async () => {
+ await engine.connect({ database_url: brain.databaseUrl, poolSize: 2 });
+ });
+ await withEnv(ROUTE, async () => {
+ const directTimeout = async () => (await engine.executeRawDirect<{ statement_timeout: string }>('SHOW statement_timeout'))[0]!.statement_timeout;
+ setDirectPoolProfile('one_shot');
+ expect(await directTimeout()).not.toBe(DIRECT_STATEMENT_TIMEOUT);
+ expect(await engine.transactionDirect(async tx => (await tx.executeRaw<{ statement_timeout: string }>('SHOW statement_timeout'))[0]!.statement_timeout)).not.toBe(DIRECT_STATEMENT_TIMEOUT);
+
+ const ddl = await engine.connectionManager!.ddl();
+ expect(ddl.options.max).toBe(1);
+ expect((await ddl`SHOW statement_timeout`)[0]!.statement_timeout).toBe(DIRECT_STATEMENT_TIMEOUT);
+ await engine.initSchema();
+
+ const handle = await tryAcquireDbLock(engine, 'test-direct-pool-profile', 5);
+ expect(handle).not.toBeNull();
+ expect(directPoolProfile()).toBe('short_lived');
+ expect(await directTimeout()).toBe(DIRECT_STATEMENT_TIMEOUT);
+ expect(await handle!.refresh()).toBe(true);
+ await handle!.release();
+ });
+ } finally {
+ await engine.disconnect();
+ await brain.close();
+ }
+ }, 120_000);
+ }
+
+ if (testBackends().includes('postgres')) {
+ test('postgres: a resident process and the restore switch open the 3-connection direct pool', async () => {
+ for (const env of [{}, { GBRAIN_DIRECT_POOL_BY_COMMAND: '0' }]) {
+ const brain = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ const engine = new PostgresEngine();
+ try {
+ if ('GBRAIN_DIRECT_POOL_BY_COMMAND' in env) setDirectPoolProfile('one_shot');
+ await withEnv({ ...ROUTE, ...env, GBRAIN_DIRECT_DATABASE_URL: brain.databaseUrl }, async () => {
+ await engine.connect({ database_url: brain.databaseUrl, poolSize: 2 });
+ expect((await engine.executeRawDirect<{ statement_timeout: string }>('SHOW statement_timeout'))[0]!.statement_timeout).toBe(DIRECT_STATEMENT_TIMEOUT);
+ expect((await engine.connectionManager!.ddl()).options.max).toBe(3);
+ });
+ } finally {
+ await engine.disconnect();
+ await brain.close();
+ }
+ }
+ }, 120_000);
+ }
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index f74601016c..486835fed2 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -49,6 +49,7 @@ test/db-lock-reconnect.test.ts
test/decide/conflict-proposals-managed.test.ts
test/declared-lineage-visibility.test.ts
test/derived-link-reconciliation.test.ts
+test/direct-pool-profile.test.ts
test/doctor-frontmatter-holds.test.ts
test/doctor-image-embedding-coverage.test.ts
test/doctor-keyword-plan-6495.test.ts