Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.60.80.0 fix(postgres): GBRAIN_POOL_SIZE=1 runs transaction:false migrations, init --db-only, repair and backfill
garrytanb96a27e6a651
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 6d109540ff..6edd1bf1b8 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.60.78.0",+ "version": "0.60.80.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 52d927e49e..d00ad275e5 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.60.78.0",+ "version": "0.60.80.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex d9209b3e14..df4d5cb609 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.60.78.0 -->+<!-- gbrain-runbook-stamp: 0.60.80.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex adf2e52ef8..c3d0d93ef5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,30 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.80.0] - 2026-10-06++**A Postgres brain set to one database connection (`GBRAIN_POOL_SIZE=1`) can be created and migrated again: `gbrain init --db-only`, `gbrain apply-migrations`, `gbrain repair request-indexes` and `gbrain backfill` no longer stop with "No pool capacity is available for long-running writes".**++Schema migrations that cannot run inside a transaction (concurrent index builds and similar DDL) run on a reserved connection. gbrain keeps one connection free for reads and control work whenever something holds a connection for a long time, so a pool of one refused every such migration and a fresh `gbrain init` failed at migration 48. Migration DDL, concurrent index builds and backfill batches use nothing but their own connection, like a transaction, so they may now take a single connection. Holds that keep other work running alongside them (write publication, the writer's idle probe, embedding index builds that report progress) still leave a connection free, and the only direct session at `GBRAIN_DIRECT_POOL_SIZE=1` is still never lent.++| With `GBRAIN_POOL_SIZE=1` on Postgres | Before | After |+| --- | --- | --- |+| `gbrain init --db-only` on a fresh database | fails at migration 48 with `writer_pool_capacity` | succeeds |+| `gbrain apply-migrations`, or any command that auto-applies pending schema migrations | fails at the first `transaction: false` migration | succeeds |+| `gbrain repair request-indexes --apply`, `gbrain backfill <kind>` | `internal_error`: no pool capacity | succeeds |++### Things to watch++- **Managed writes still need two connections.** With one connection, a managed write stays queued with `writer_pool_capacity`, so `gbrain init` without `--db-only` creates the schema and then stops at its packaged-skill install with `write_pending`. Rerun with `GBRAIN_POOL_SIZE=2`; init resumes the same request. Long-running processes still need 6 ([pool sizing](docs/ENGINES.md#pool-sizing)).++For contributors and agents working on gbrain:++- `withReservedConnection(fn, { selfContained: true })` declares that `fn` uses only the reserved connection and never waits on the pool while holding it. Only such holders may take the only connection of a one-connection ordinary pool. Tests: `test/pool-budget.test.ts`, `test/postgres-engine-reserved-routing.test.ts`, `test/e2e/pool-size-one-migrations.test.ts`.++## To take advantage of v0.60.80.0++`gbrain upgrade`. No schema migration.+## [0.60.78.0] - 2026-10-06**Green master wave: a brain with embedding turned off no longer sends your text to an embedding provider, lint survives a file vanishing mid-scan, embed and reindex-code stop failing when a background rebuild wins a race, and a release only publishes after its tests pass.**diff --git a/VERSION b/VERSIONindex 12adcd74b6..af8767a0a7 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.60.78.0+0.60.80.0diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex a38276dbf0..86f051808e 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -580,7 +580,15 @@ config key). A long-running process (`gbrain serve`, `gbrain autopilot`,`gbrain jobs work`) needs at least **6**: two for write publication, one for theidle work probe, one each for the projection and effects workers, and one forreads and tool calls. Below that, boot or projection draining stalls under-traffic. One-shot CLI commands can use `GBRAIN_POOL_SIZE=2`.+traffic. One-shot CLI commands can use `GBRAIN_POOL_SIZE=2`. With+`GBRAIN_POOL_SIZE=1`, schema setup and maintenance still run (`gbrain init+--db-only`, `apply-migrations`, `repair request-indexes`, `backfill`), but+managed writes need two connections: they stay queued with+`writer_pool_capacity`, so `gbrain init` without `--db-only` stops at its+packaged-skill install. Long holds keep one connection free for reads and+control work; only holds that use nothing but their own connection (migration+DDL, concurrent index builds, backfill batches) may take a single+connection.Size the pooler for every process at once:diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.mdindex e2a772abb7..69bf14e0b6 100644--- a/docs/architecture/key-files/engines-2.md+++ b/docs/architecture/key-files/engines-2.md@@ -31,7 +31,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/pglite-resetwal.ts` — pg_resetwal for PGLite NodeFS data dirs, in TypeScript (a port of the electric-sql/pglite pg_resetwal contribution, PR #994, Apache-2.0). Validates the PG17 pg_control layout fail-closed (`WalResetUnsupportedError` on any unsupported shape — PG_VERSION ≠ 17, control ≠ 8192 bytes, control version ≠ 1700, bad seg/block size), removes stale postmaster.pid + old WAL segments + archive_status/summaries entries, writes a replacement shutdown-checkpoint WAL segment + CRC32C'd pg_control. Both file writes are atomic + durable (tmp cleared then opened `'wx'` so a pre-planted symlink at the predictable tmp name can never redirect the write, + fsync(tmp) + rename + fsync(parent dir)); write order is segment-first/control-last so a mid-write kill leaves a state that still fails startup and the next attempt re-runs (idempotent — a torn pair can never claim success). WAL segment size is capped at 64MB (pglite ships 16MB; the Postgres-general 1GB bound would let a corrupt-but-plausible control field drive a 1GB allocation on the repair path). Exports the shared PG17 layout literals (`PG_CONTROL_FILE_SIZE`, `isWalSegmentName`) consumed by pglite-repair.ts. LAYOUT COUPLING: any pglite bump past PG17 must revisit this file together with the `./vector` export blocker (TODOS.md "pglite upgrade blocker" entry). Pinned by `test/pglite-resetwal.test.ts`.-- `src/core/pool-budget.ts` + `src/core/persistence/pool-capacity.ts` — physical-pool shared long-hold ceilings retain one ordinary/control connection across engine clones; pool size one pauses canonical consumption with `writer_pool_capacity`. Publication concurrency is capped at two per actual Postgres pool and one per PGLite owner. `persistence/takes-prepare.ts` journals semantic takes with frozen dates/resolver identity and original/current holder ceilings; canonical row updates and receipt commit together. Publication retains the actual affected holders privately in authority JSON, so narrowed holder grants also hide committed/replayed receipts after input compaction.+- `src/core/pool-budget.ts` + `src/core/persistence/pool-capacity.ts` — physical-pool shared long-hold ceilings retain one ordinary/control connection across engine clones; pool size one pauses canonical consumption with `writer_pool_capacity`. `withReservedConnection(fn, { selfContained: true })` (migration DDL, `buildIndexOnline`, backfill batches: `fn` touches only its reserved connection, like a transaction) may take the only connection of a one-connection ordinary pool, never the only direct session; pinned by `test/pool-budget.test.ts` and `test/e2e/pool-size-one-migrations.test.ts`. Publication concurrency is capped at two per actual Postgres pool and one per PGLite owner. `persistence/takes-prepare.ts` journals semantic takes with frozen dates/resolver identity and original/current holder ceilings; canonical row updates and receipt commit together. Publication retains the actual affected holders privately in authority JSON, so narrowed holder grants also hide committed/replayed receipts after input compaction.- `src/core/pool-gauge.ts` — `CheckoutGauge`: approximate in-flight counters at the engine's raw/direct/reserved/tx seams, surfaced via duck-typed `PostgresEngine.getPoolDiagnostics()` (no BrainEngine change, no PGLite stub). HONESTY CONTRACT in the module doc: tagged-template traffic is untracked; consumers must label counts as a subset and never derive waiter/available figures. Fail-open (clamped release, try/finally around sync-throwing runUnsafe). Consumed by db-probe.ts. Pinned by `test/pool-gauge.test.ts`. `PoisonedDiscardCounter` counts the driver's non-idle connection discards and writes one fixed-shape `pg_connection_poisoned` warn line each; the engine wires it into every pool it creates and reports it as `poisonedDiscards`. `onCheckout(listener)` (exposed as `PostgresEngine.onCheckout`) fires after a connection is actually obtained: signalled raw reserve resolution, transaction-callback entry and `withReservedConnection` reserve resolution; it never fires for a call still waiting (pinned by `test/e2e/postgres-checkout-observer.test.ts`).diff --git a/llms-full.txt b/llms-full.txtindex 5fa4626444..97c190bf1f 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -5602,7 +5602,15 @@ config key). A long-running process (`gbrain serve`, `gbrain autopilot`,`gbrain jobs work`) needs at least **6**: two for write publication, one for theidle work probe, one each for the projection and effects workers, and one forreads and tool calls. Below that, boot or projection draining stalls under-traffic. One-shot CLI commands can use `GBRAIN_POOL_SIZE=2`.+traffic. One-shot CLI commands can use `GBRAIN_POOL_SIZE=2`. With+`GBRAIN_POOL_SIZE=1`, schema setup and maintenance still run (`gbrain init+--db-only`, `apply-migrations`, `repair request-indexes`, `backfill`), but+managed writes need two connections: they stay queued with+`writer_pool_capacity`, so `gbrain init` without `--db-only` stops at its+packaged-skill install. Long holds keep one connection free for reads and+control work; only holds that use nothing but their own connection (migration+DDL, concurrent index builds, backfill batches) may take a single+connection.Size the pooler for every process at once:diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex d9d84ca5cb..ccf9fc29f3 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.60.78.0",+ "version": "0.60.80.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","kind": "context-engine",diff --git a/package.json b/package.jsonindex eb3ba59518..00dc7b6329 100644--- a/package.json+++ b/package.json@@ -224,7 +224,7 @@"bun": ">=1.4.0"},"license": "MIT",- "version": "0.60.78.0",+ "version": "0.60.80.0","overrides": {"@ai-sdk/provider-utils": "4.0.56","@hono/node-server": "^2.0.5",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex 3bc6cfa0a9..4dbbedb715 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.60.78.0",+ "version": "0.60.80.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex 6f5e84ae29..2cf8c50efd 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.60.78.0",+ "version": "0.60.80.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex c5a934ac6f..d01d5a088d 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.78.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.80.0 --># gbrain-coding (generated persona variant — do not hand-edit)Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex d35d24c74f..7da739100e 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.60.78.0",+ "version": "0.60.80.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex 87508d43db..02d38f7826 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.60.78.0",+ "version": "0.60.80.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex 96607512c1..8e395b6a7a 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.78.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.80.0 --># gbrain-daily (generated persona variant — do not hand-edit)Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.diff --git a/plugin/README.md b/plugin/README.mdindex 15c2299bb8..c82a25b104 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.78.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.80.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/src/core/backfill-base.ts b/src/core/backfill-base.tsindex 4791a04cff..2d6316cd44 100644--- a/src/core/backfill-base.ts+++ b/src/core/backfill-base.ts@@ -182,7 +182,7 @@ export async function ensureBackfillIndex<TRow>(// semantics directly.await engine.withReservedConnection(async conn => {await conn.executeRaw(sql);- });+ }, { selfContained: true });return { existed: false, created: true };} catch (err) {process.stderr.write(`[backfill] index creation failed: ${(err as Error).message}; will continue without partial index\n`);@@ -318,7 +318,7 @@ export async function runBackfill<TRow = Record<string, unknown>>(}throw err;}- });+ }, { selfContained: true });} catch (err) {if (err instanceof BackfillRollbackError) throw err;errors++;diff --git a/src/core/engine.ts b/src/core/engine.tsindex cef81dc187..9a4f63a76e 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -771,11 +771,11 @@ export interface BrainEngine {/** Mandatory resident-consumer stop barrier before datastore/pool shutdown. */registerBeforeDisconnect(stop: () => Promise<void>): () => void;/**- * Run `fn` with a dedicated connection (Postgres: reserved backend;- * PGLite: pass-through). See `ReservedConnection` for semantics and- * usage constraints. Release is automatic. `route: 'ordinary'` skips the direct route.+ * Run `fn` with a dedicated connection (Postgres: reserved backend; PGLite: pass-through). See `ReservedConnection`+ * for semantics and usage constraints. Release is automatic. `route: 'ordinary'` skips the direct route. `selfContained`:+ * `fn` uses only `conn` and never waits on the pool (like a transaction), so a one-connection ordinary pool may lend it.*/- withReservedConnection<T>(fn: (conn: ReservedConnection) => Promise<T>, opts?: { route?: 'ordinary' }): Promise<T>;+ withReservedConnection<T>(fn: (conn: ReservedConnection) => Promise<T>, opts?: { route?: 'ordinary'; selfContained?: boolean }): Promise<T>;// Pages CRUD/**diff --git a/src/core/migrate.ts b/src/core/migrate.tsindex dad55f1367..2fd7e1bd46 100644--- a/src/core/migrate.ts+++ b/src/core/migrate.ts@@ -241,7 +241,7 @@ async function runMigrationSQL(// Falling through means the DDL runs with the server default.}await conn.executeRaw(sql);- });+ }, { selfContained: true });}}diff --git a/src/core/pool-budget.ts b/src/core/pool-budget.tsindex 46587753ef..3a9e6164ba 100644--- a/src/core/pool-budget.ts+++ b/src/core/pool-budget.ts@@ -6,14 +6,21 @@ export class PoolCapacityError extends Error {readonly code = 'writer_pool_capacity';constructor() { super('No pool capacity is available for long-running writes. Configure at least two ordinary connections; one connection is reserved for reads and control work.'); }}-export function poolLongHoldCapacity(pool: BudgetPool, fallback?: number): number {+/**+ * Long holds leave one connection free for reads and control work (heartbeats, claims, lock renewal).+ * `selfContained` holders use only the reserved connection and never wait on the pool while holding,+ * like a transaction, so they may take the only connection of a single-connection pool.+ */+export interface LongHoldOptions { selfContained?: boolean }+export function poolLongHoldCapacity(pool: BudgetPool, fallback?: number, opts?: LongHoldOptions): number {const max = fallback === undefined ? pool.options?.max ?? 10 : Math.min(pool.options?.max ?? fallback, fallback);- return Number.isSafeInteger(max) && max > 1 ? max - 1 : 0;+ if (!Number.isSafeInteger(max) || max < 1) return 0;+ return max > 1 ? max - 1 : opts?.selfContained ? 1 : 0;}-export function tryAcquirePoolLongHold(pool: BudgetPool, fallback?: number): (() => void) | null {+export function tryAcquirePoolLongHold(pool: BudgetPool, fallback?: number, opts?: LongHoldOptions): (() => void) | null {let budget = budgets.get(pool);if (!budget) { budget = { held: 0 }; budgets.set(pool, budget); }- if (budget.held >= poolLongHoldCapacity(pool, fallback)) return null;+ if (budget.held >= poolLongHoldCapacity(pool, fallback, opts)) return null;budget.held++;let released = false;return () => { if (!released) { released = true; budget!.held--; } };diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 55039f1eac..ac5653e21b 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -621,7 +621,7 @@ export class PostgresEngine implements BrainEngine {}/** Long holds share a budget across every engine that uses the same physical pool. */- async withReservedConnection<T>(fn: (conn: ReservedConnection) => Promise<T>, opts?: { route?: 'ordinary' }): Promise<T> {+ async withReservedConnection<T>(fn: (conn: ReservedConnection) => Promise<T>, opts?: { route?: 'ordinary'; selfContained?: boolean }): Promise<T> {let pool = this.sql;let releasePermit: (() => void) | null = null;if (!this._pageTransaction && opts?.route !== 'ordinary' && this.connectionManager?.isDualPoolActive()) {@@ -633,7 +633,7 @@ export class PostgresEngine implements BrainEngine {// A disabled direct route falls back to the same bounded ordinary pool.}}- releasePermit ??= tryAcquirePoolLongHold(pool);+ releasePermit ??= tryAcquirePoolLongHold(pool, undefined, { selfContained: opts?.selfContained });if (!releasePermit) throw new PoolCapacityError();// Gauge BEFORE reserve(): a reserve() stuck waiting for a free slot is// exactly the in-flight pressure the probe diagnostics should surface.diff --git a/src/core/schema-migrations/helpers.ts b/src/core/schema-migrations/helpers.tsindex 4a952bd628..c01509d2c9 100644--- a/src/core/schema-migrations/helpers.ts+++ b/src/core/schema-migrations/helpers.ts@@ -108,7 +108,7 @@ export async function buildIndexOnline(// No session SET: a reservation can fall back to a transaction-pooled connection, where a SET or RESET// reaches another client's backend. The build runs under the session's startup timeouts; one that times// out leaves an INVALID index, which the next call drops and rebuilds.- await engine.withReservedConnection(conn => conn.executeRaw(index.sql.replace('CREATE INDEX', 'CREATE INDEX CONCURRENTLY')));+ await engine.withReservedConnection(conn => conn.executeRaw(index.sql.replace('CREATE INDEX', 'CREATE INDEX CONCURRENTLY')), { selfContained: true });// IF NOT EXISTS also skips an INVALID index a concurrent caller's failed build left behind.const [built] = await engine.executeRaw<{ valid: boolean }>('SELECT indisvalid AS valid FROM pg_index WHERE indexrelid = to_regclass($1)', [index.name]);if (!built?.valid) throw new Error(`Index ${index.name} is not valid after its concurrent build; rerun: gbrain repair request-indexes --apply`);diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 08c4dcd83c..b2b977801f 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.60.78.0 -->+<!-- gbrain-template-stamp: 0.60.80.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/e2e/pool-size-one-migrations.test.ts b/test/e2e/pool-size-one-migrations.test.tsnew file mode 100644index 0000000000..06fa0e541d--- /dev/null+++ b/test/e2e/pool-size-one-migrations.test.ts@@ -0,0 +1,87 @@+/**+ * E2E: a one-connection Postgres pool (GBRAIN_POOL_SIZE=1) initializes a fresh+ * brain and runs every schema migration.+ *+ * `transaction: false` migrations (CREATE INDEX CONCURRENTLY and friends) run+ * on a reserved connection. The long-hold permit keeps one connection free for+ * reads and control work, so before the fix a pool of one refused them with+ * writer_pool_capacity at the first such migration and `gbrain init` failed.+ * Migration holds are self-contained (they use only the reserved connection),+ * so they may take the only connection; ordinary long holds still may not.+ *+ * Run: DATABASE_URL=postgresql://.../gbrain_test bun run test:e2e \+ * test/e2e/pool-size-one-migrations.test.ts+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import postgres from '#postgres';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { LATEST_VERSION, MIGRATIONS } from '../../src/core/migrate.ts';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';+import { makeDoctorHome, runGbrain, type DoctorHome } from '../helpers/doctor-json-golden.ts';++const DATABASE_URL = process.env.DATABASE_URL;+const drops: Array<() => Promise<void>> = [];+const homes: DoctorHome[] = [];+afterAll(async () => {+ for (const drop of drops) await drop();+ for (const h of homes) h.cleanup();+});++async function freshDatabase(): Promise<string> {+ assertSafeE2eDatabaseUrl(DATABASE_URL!);+ const name = `gbrain_test_pool_one_${randomUUID().replaceAll('-', '')}`;+ const admin = postgres(DATABASE_URL!, { max: 1, prepare: false });+ await admin.unsafe(`CREATE DATABASE ${name}`);+ drops.push(async () => {+ try { await admin.unsafe(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`); } finally { await admin.end(); }+ });+ const url = new URL(DATABASE_URL!);+ url.pathname = `/${name}`;+ return url.toString();+}++async function schemaVersion(url: string): Promise<number> {+ const sql = postgres(url, { max: 1, prepare: false });+ try {+ const [row] = await sql<{ value: string }[]>`SELECT value FROM config WHERE key = 'version'`;+ return Number(row?.value);+ } finally { await sql.end(); }+}++describe.skipIf(!DATABASE_URL)('pool size one: fresh init and migrations (E2E)', () => {+ test('the migration chain contains transaction:false migrations, so this exercises the reserved path', () => {+ expect(MIGRATIONS.some(m => m.transaction === false)).toBe(true);+ });++ test('initSchema on a fresh database with a one-connection pool reaches the latest version', async () => {+ const url = await freshDatabase();+ const engine = new PostgresEngine();+ await engine.connect({ database_url: url, poolSize: 1 });+ try {+ expect((engine.sql as unknown as { options: { max: number } }).options.max).toBe(1);+ await engine.initSchema();+ expect(Number(await engine.getConfig('version'))).toBe(LATEST_VERSION);+ await expect(engine.withReservedConnection(async () => 'held')).rejects.toMatchObject({ code: 'writer_pool_capacity' });+ expect((await engine.executeRaw<{ ok: number }>('SELECT 1 AS ok'))[0]?.ok).toBe(1);+ } finally {+ await engine.disconnect();+ }+ }, 180_000);++ test('GBRAIN_POOL_SIZE=1 gbrain init then apply-migrations succeed on a fresh database', async () => {+ const url = await freshDatabase();+ const h = makeDoctorHome('pool-one');+ homes.push(h);+ const env = { GBRAIN_POOL_SIZE: '1' };+ const init = await runGbrain(h, ['init', '--url', url, '--no-embedding', '--non-interactive', '--db-only'], env, 180_000);+ expect(init.stderr).not.toContain('writer_pool_capacity');+ expect(init.stderr).not.toContain('No pool capacity');+ expect(init.exitCode).toBe(0);+ expect(await schemaVersion(url)).toBe(LATEST_VERSION);+ const apply = await runGbrain(h, ['apply-migrations', '--yes', '--no-autopilot-install'], env, 180_000);+ expect(apply.stderr).not.toContain('No pool capacity');+ expect(apply.exitCode).toBe(0);+ expect(await schemaVersion(url)).toBe(LATEST_VERSION);+ }, 400_000);+});diff --git a/test/pool-budget.test.ts b/test/pool-budget.test.tsnew file mode 100644index 0000000000..3f6e0ec92e--- /dev/null+++ b/test/pool-budget.test.ts@@ -0,0 +1,67 @@+/**+ * Long-hold permit math (src/core/pool-budget.ts). Long holds leave one+ * connection free for reads and control work; a self-contained holder (one+ * that uses only its reserved connection, like a transaction) may take the+ * only connection of a one-connection pool, so GBRAIN_POOL_SIZE=1 can run+ * `transaction: false` migrations.+ */+import { describe, expect, test } from 'bun:test';+import { poolLongHoldCapacity, tryAcquirePoolLongHold } from '../src/core/pool-budget.ts';++const pool = (max?: number) => ({ options: max === undefined ? {} : { max } });++describe('poolLongHoldCapacity', () => {+ test('ordinary long holds keep one connection free', () => {+ expect(poolLongHoldCapacity(pool(1))).toBe(0);+ expect(poolLongHoldCapacity(pool(2))).toBe(1);+ expect(poolLongHoldCapacity(pool(10))).toBe(9);+ expect(poolLongHoldCapacity(pool())).toBe(9);+ });++ test('a self-contained holder may use the only connection of a one-connection pool', () => {+ expect(poolLongHoldCapacity(pool(1), undefined, { selfContained: true })).toBe(1);+ expect(poolLongHoldCapacity(pool(2), undefined, { selfContained: true })).toBe(1);+ expect(poolLongHoldCapacity(pool(10), undefined, { selfContained: true })).toBe(9);+ });++ test('the direct-route fallback still caps the pool size', () => {+ expect(poolLongHoldCapacity(pool(10), 1)).toBe(0);+ expect(poolLongHoldCapacity(pool(10), 3)).toBe(2);+ expect(poolLongHoldCapacity(pool(), 1, { selfContained: true })).toBe(1);+ });++ test('invalid pool sizes grant nothing', () => {+ for (const max of [0, -1, Number.NaN, 1.5]) {+ expect(poolLongHoldCapacity(pool(max))).toBe(0);+ expect(poolLongHoldCapacity(pool(max), undefined, { selfContained: true })).toBe(0);+ }+ });+});++describe('tryAcquirePoolLongHold', () => {+ test('one-connection pool: refuses ordinary holders, grants one self-contained holder at a time', () => {+ const single = pool(1);+ expect(tryAcquirePoolLongHold(single)).toBeNull();+ const release = tryAcquirePoolLongHold(single, undefined, { selfContained: true });+ expect(release).not.toBeNull();+ expect(tryAcquirePoolLongHold(single, undefined, { selfContained: true })).toBeNull();+ expect(tryAcquirePoolLongHold(single)).toBeNull();+ release!();+ release!();+ const again = tryAcquirePoolLongHold(single, undefined, { selfContained: true });+ expect(again).not.toBeNull();+ again!();+ });++ test('a self-contained holder shares the budget with ordinary holders on larger pools', () => {+ const shared = pool(2);+ const ordinary = tryAcquirePoolLongHold(shared);+ expect(ordinary).not.toBeNull();+ expect(tryAcquirePoolLongHold(shared, undefined, { selfContained: true })).toBeNull();+ ordinary!();+ const contained = tryAcquirePoolLongHold(shared, undefined, { selfContained: true });+ expect(contained).not.toBeNull();+ expect(tryAcquirePoolLongHold(shared)).toBeNull();+ contained!();+ });+});diff --git a/test/postgres-engine-reserved-routing.test.ts b/test/postgres-engine-reserved-routing.test.tsindex 8f654bb36c..6db8c7764c 100644--- a/test/postgres-engine-reserved-routing.test.ts+++ b/test/postgres-engine-reserved-routing.test.ts@@ -173,3 +173,42 @@ test('two engines sharing a physical pool share one long-hold ceiling', async ()await second.withReservedConnection(async () => {});expect(log).toEqual(['reserve:read','release:read','reserve:read','release:read']);});++describe('withReservedConnection on a one-connection ordinary pool (GBRAIN_POOL_SIZE=1)', () => {+ test('an ordinary long hold is refused before reserving', async () => {+ const log: string[] = [];+ const engine = makeEngine({ dualPool: false, log });+ (engine.sql as unknown as { options: { max: number } }).options.max = 1;+ await expect(engine.withReservedConnection(async () => 'x')).rejects.toMatchObject({ code: 'writer_pool_capacity' });+ expect(log).toEqual([]);+ });++ test('a self-contained hold reserves the only connection and releases it', async () => {+ const log: string[] = [];+ const engine = makeEngine({ dualPool: false, log });+ (engine.sql as unknown as { options: { max: number } }).options.max = 1;+ expect(await engine.withReservedConnection(async () => 'ddl', { selfContained: true })).toBe('ddl');+ expect(await engine.withReservedConnection(async () => 'again', { selfContained: true })).toBe('again');+ expect(log).toEqual(['reserve:read', 'release:read', 'reserve:read', 'release:read']);+ });++ test('a second concurrent self-contained hold is refused instead of waiting on the only connection', async () => {+ const log: string[] = [];+ const engine = makeEngine({ dualPool: false, log });+ (engine.sql as unknown as { options: { max: number } }).options.max = 1;+ let release!: () => void;+ const held = engine.withReservedConnection(() => new Promise<void>(resolve => { release = resolve; }), { selfContained: true });+ await Promise.resolve();+ await expect(engine.withReservedConnection(async () => {}, { selfContained: true })).rejects.toMatchObject({ code: 'writer_pool_capacity' });+ release(); await held;+ expect(log).toEqual(['reserve:read', 'release:read']);+ });++ test('direct_pool_size=1 still never lends the only direct session; the hold uses the ordinary pool', async () => {+ const log: string[] = [];+ const engine = makeEngine({ dualPool: true, directPoolSize: 1, log });+ (engine.sql as unknown as { options: { max: number } }).options.max = 1;+ await engine.withReservedConnection(async () => 'ok', { selfContained: true });+ expect(log).toEqual(['reserve:read', 'release:read']);+ });+});