Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(pglite): ANALYZE and VACUUM clear the statement cache so pre-statistics plans are replanned

garrytan9936f8764629
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7f26d3c6bb..03abf61f4b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,14 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**A long-running PGLite process picks up fresh planner statistics instead of keeping the plans it made before them.** PGLite has no autovacuum, so a freshly imported brain has no statistics until planner-stats' first-read refresh runs `ANALYZE`. But gbrain's PGLite statement cache keeps named prepared statements, and PostgreSQL keeps a prepared statement's plan across `ANALYZE`, so every statement prepared before the refresh kept its no-statistics plan for the life of the process (a `gbrain serve`, an agent session, a script). On a 55,838-page brain imported without statistics, `entity names` with 50 names stayed at 3.4 to 3.7 s for every call after the refresh. With this fix the calls after the first take 1.2 to 1.5 s, the same as a freshly started process.
+
+### Itemized changes
+
+- **`ANALYZE` and `VACUUM` clear the PGLite statement cache** (`src/core/pglite-statements.ts`), like DDL already did, so the next call re-prepares and plans with the new statistics. This covers planner-stats' refreshes, `gbrain repair planner-stats`, projection statistics and the persistence journal's `VACUUM (ANALYZE)`. Postgres is unchanged. `test/pglite-statements.test.ts` checks that a statement prepared before `ANALYZE` is re-prepared after it; the check fails without the fix.
+
## [0.60.190.0] - 2026-10-13
**No Postgres statement outlives its budget now, a stalled managed sync says what is blocking it, and doctor stops misleading on managed and image-heavy brains (#6543, part 2).** v0.60.187.0 stopped the Supavisor wedge itself. This release closes the gaps the reporter hit around it. A statement that kept receiving bytes was never retired, so `/health?deep=1` stayed red forever. A sync stalled 300-600 s with "claimable here: no" no matter the cause. `repair failed-writes --apply` stopped at every pending write. Doctor recommended a `--retry-failed` that did nothing on a managed brain, and reported existing images as missing when only their letter case differed.
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.md
index 07442ef275..f3cb55790d 100644
--- a/docs/architecture/key-files/engines-1.md
+++ b/docs/architecture/key-files/engines-1.md
@@ -41,7 +41,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/pglite-lock.ts` — persistent datastore ownership uses a canonical sibling `.gbrain-owner.lock` retained inode and the native kernel binding. `.gbrain-lock/lock` retains PID, structured argv, command/subcommand and heartbeat diagnostics for `inspectLockHolder`/`peekLock` and engine-free IPC routing; `peekLock` also reports a serve holder's transport (`http` from its recorded `--http` argv) and `acquiredAt`, in one metadata read. `heldLockFor(dataDir)` answers "does this process hold it" from the in-memory retained handles (no file access while none are held). The exported ps/proc/Windows CIM process probe is diagnostic compatibility only; ownership and takeover never consult it. Metadata age, corruption and PID reuse never override a kernel owner. The initial protocol upgrade refuses live/unknown legacy owners; all older processes must be stopped. Handles remain strongly retained until explicit release, so GC cannot unlock a datastore after a close timeout. Dead legacy migration keeps the one-acquisition WAL-repair quarantine; `msSinceLastReap` reads older persisted quarantine markers. Tests: `test/pglite-lock.test.ts` (real paused/crashed process, replacement/aliases, migration, metadata).
-- `src/core/pglite-statements.ts` — `PgliteStatementCache`, the PGLite counterpart of postgres.js prepared statements. `PGLiteEngine._attachDatabase` routes the root handle's `query`/`exec` through it and `transaction()` routes each transaction handle. A statement text seen twice is prepared once as a named server-side statement; later calls send one Bind/Execute/Sync batch and parse rows with parsers resolved at prepare time, instead of PGlite's parse/describe round trips and its per-query copy of `db.parsers`. PostgreSQL's plan cache replans on invalidation; a changed result shape (`0A000`) or missing statement (`26000`) drops the entry and retries outside a transaction. `ALTER`/`CREATE`/`DROP`/`DO`/`DISCARD`/`DEALLOCATE` text and any non-transaction-control `exec` clear the cache, retired names are closed in the next prepare batch, an instance-level `query`/`exec` override (test seams) takes precedence on the root handle, and `_closeInternal` drops the cache with the database so a disconnected engine does not retain its PGLite instance. `dropRowTypeArrayParsers` removes composite-row array parsers after connect, since gbrain never selects those arrays. Pinned by `test/pglite-statements.test.ts`.
+- `src/core/pglite-statements.ts` — `PgliteStatementCache`, the PGLite counterpart of postgres.js prepared statements. `PGLiteEngine._attachDatabase` routes the root handle's `query`/`exec` through it and `transaction()` routes each transaction handle. A statement text seen twice is prepared once as a named server-side statement; later calls send one Bind/Execute/Sync batch and parse rows with parsers resolved at prepare time, instead of PGlite's parse/describe round trips and its per-query copy of `db.parsers`. PostgreSQL's plan cache replans on invalidation; a changed result shape (`0A000`) or missing statement (`26000`) drops the entry and retries outside a transaction. `ALTER`/`CREATE`/`DROP`/`DO`/`DISCARD`/`DEALLOCATE` text, `ANALYZE`/`VACUUM` (PostgreSQL keeps a prepared plan across a statistics refresh, so a plan made before the table had statistics would outlive planner-stats' first-read ANALYZE) and any non-transaction-control `exec` clear the cache, retired names are closed in the next prepare batch, an instance-level `query`/`exec` override (test seams) takes precedence on the root handle, and `_closeInternal` drops the cache with the database so a disconnected engine does not retain its PGLite instance. `dropRowTypeArrayParsers` removes composite-row array parsers after connect, since gbrain never selects those arrays. Pinned by `test/pglite-statements.test.ts`.
- `src/core/pglite-repair.ts` — WAL-repair orchestrator wrapping the resetWal port with the safety layers that make it runnable automatically from `connect()`: `validateWalRepairTarget` (read-only, fail-closed; refuses symlinked dataDir/pg_wal/`global`/pg_control — lstat follows INTERMEDIATE symlinks, so `global/` itself must be checked or surgery would write pg_control through it into a foreign dir; tolerates the in-dir `.gbrain-lock`), rename-based backup (the ENTIRE `pg_wal/` dir + postmaster.pid renamed into a sibling `<dataDir>.wal-repair-backup-<ts>/`, only the 8KB pg_control copied — zero transient disk cost), `restoreWalBackup` (overwrite order: control first via atomic tmp+rename, then a pg_wal dir swap with the reset dir set ASIDE inside the backup — nothing is ever deleted during restore; mtime guard refuses when a foreign segment is newer than the backup; a missing/empty backup NEVER reports `restored:true`), `WalRepairError` (thrown when resetWal fails AFTER the backup — carries the receipt + the best-effort restore's REAL result so the seam's `restored` flag and the `failed-restored`/`failed-not-restored` message arms never lie), a cooldown sidecar `<dataDir>.wal-repair-attempt.json` (skip `'recently-failed'` inside `GBRAIN_PGLITE_WAL_REPAIR_COOLDOWN_SECONDS`, default 3600 — bounds the autopilot/supervisor reconnect loops) with episode-scoped backups (attempts within one corruption episode REUSE the episode's first backup — the pre-damage forensic state, honored only when the sidecar's path is a real non-symlink `<dataDir>.wal-repair-backup-*` sibling since the sidecar is user-writable JSON; retention keeps the newest 3 episodes, never pruning the open episode's), and `attemptWalRepairAndRetry` — the engine seam that NEVER throws (gates: kill-switch → reaped-lock `'possibly-live-writer'` → 10-minute reap-marker quarantine (`msSinceLastReap`, cross-process) → validation → cooldown; then repair → retry create once → restore-and-record on failure; prints a repair-start stderr line so a timeout-killed attempt is self-explaining). `inspectPgliteDataDir` is the read-only diagnosis for `gbrain doctor` + `pglite-repair --dry-run`. Imports runtime values only from `pglite-lock.ts`/`pglite-resetwal.ts`/node:fs — never from `pglite-engine.ts` (no cycle; the engine statically imports THIS file per the engine-live rule). Pinned by `test/pglite-repair.test.ts` + `test/pglite-wal-repair.serial.test.ts`.
- `src/core/pglite-repair-consent.ts` + the repair-failed marker in `src/core/pglite-repair.ts` — when automatic WAL repair fails (or a recent failure put it on cooldown) `recordFailedAutoRepair` writes the sibling `<dataDir>.repair-failed.json`; while it exists `PGLiteEngine.connect()` refuses before `acquireLock` (zero writes to the data dir) with `repairFailedRefusal`: the exit-3 consent payload (effects `destructive`, fix `gbrain pglite-repair [--path] --yes --expect <plan_hash>` from the same `walRepairPlan` the command binds, preview `--dry-run --json`, and the hands-off text `HANDS_OFF_BRAIN_FILES`). The CLI's `exitOnRepairFailed` (`src/cli/cli-error.ts`) exits 3 on it from `connectEngine`; stdio serve maps it to status reason `repair_failed`. Cleared by a completed `pglite-repair` or `reinit-pglite`. Pinned by `test/agent-operator-gate-fixes.{,serial.}test.ts`.
diff --git a/src/core/pglite-statements.ts b/src/core/pglite-statements.ts
index 2423cda174..835f3ff4d0 100644
--- a/src/core/pglite-statements.ts
+++ b/src/core/pglite-statements.ts
@@ -23,8 +23,12 @@ const { serialize } = protocol as unknown as {
};
const defaultParsers = types.parsers as unknown as Record<number, Parser>;
-/** Statements that can change a cached statement's result shape or drop session statements. */
-const SHAPE_CHANGING = /^\s*(?:ALTER|CREATE|DROP|DO|DISCARD|DEALLOCATE)\b/i;
+/**
+ * Statements that can change a cached statement's result shape or drop session statements, and
+ * statistics refreshes: PostgreSQL keeps a prepared statement's plan across ANALYZE, so a plan made
+ * before a table had statistics (PGLite has no autovacuum) would otherwise outlive the refresh.
+ */
+const SHAPE_CHANGING = /^\s*(?:ALTER|CREATE|DROP|DO|DISCARD|DEALLOCATE|ANALYZE|VACUUM)\b/i;
const TRANSACTION_CONTROL = /^\s*(?:BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\b/i;
/** Plan-cache errors that a fresh Parse resolves: changed result type, missing statement. */
const STALE_STATEMENT = new Set(['0A000', '26000']);
@@ -63,7 +67,7 @@ function concat(parts: Uint8Array[]): Uint8Array {
* every call as an unnamed statement over five protocol round trips; a
* statement seen twice is prepared once and later runs as one Bind/Execute/Sync
* batch. PostgreSQL still replans on invalidation and rejects a changed result
- * shape, which drops the entry. Shape-changing SQL clears the cache.
+ * shape, which drops the entry. Shape-changing SQL, ANALYZE and VACUUM clear the cache.
*/
export class PgliteStatementCache {
private statements = new Map<string, Statement>();
diff --git a/test/pglite-statements.test.ts b/test/pglite-statements.test.ts
index ed9a171967..9eb16549f6 100644
--- a/test/pglite-statements.test.ts
+++ b/test/pglite-statements.test.ts
@@ -53,6 +53,22 @@ describe('PGLite named statement cache', () => {
expect((await db.query<{ label: string }>(select, [3])).rows[0].label).toBe('item-3');
});
+ test('ANALYZE re-prepares statements planned before the table had statistics', async () => {
+ await raw.exec(`CREATE TABLE skew (id int, k int); CREATE INDEX skew_k ON skew (k);
+ INSERT INTO skew SELECT g, CASE WHEN g % 1000 = 0 THEN g ELSE 0 END FROM generate_series(1, 20000) g`);
+ const select = 'SELECT id FROM skew WHERE k = $1';
+ const prepared = async () => (await raw.query<{ name: string }>(
+ 'SELECT name FROM pg_prepared_statements WHERE statement = $1', [select])).rows.map(row => row.name);
+ for (let run = 0; run < 8; run++) await db.query(select, [5000]);
+ const before = await prepared();
+ expect(before).toHaveLength(1);
+ await db.query('ANALYZE skew');
+ for (let run = 0; run < 3; run++) expect((await db.query<{ id: number }>(select, [5000])).rows).toEqual([{ id: 5000 }]);
+ const after = await prepared();
+ expect(after).toHaveLength(1);
+ expect(after[0]).not.toBe(before[0]);
+ });
+
test('errors keep PGlite fields, and transactions roll back and continue', async () => {
const insert = 'INSERT INTO items(id,label) VALUES ($1,$2)';
await db.query(insert, [10, 'ten']);