Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(pglite): engine-sql writes take the WAL checkpoint guard (GBRA-69 stamp wedge)

time-attack033a6481cabf
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.md
index 28c71edf4c..8722a424cb 100644
--- a/docs/architecture/key-files/engines-1.md
+++ b/docs/architecture/key-files/engines-1.md
@@ -35,7 +35,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/pglite-embedded-assets.ts` + `src/core/pglite-embedded-asset-paths.ts` — PGLite runtime-asset supply for every run mode (compiled binary, source checkout, bun-global install). `pglite-embedded-asset-paths.ts` is the bundler ANCHOR: five literal `with { type: 'file' }` imports of the wasm/data/extension-tarball assets via repo-relative node_modules paths (the package's `exports` map hides `./dist/*`) — keep the specifiers literal and byte-stable, an expression or indirection silently stops the bytes embedding and the compiled binary falls into the Bun-vfs ENOENT failure. `resolvePgliteAssetPaths()` in `pglite-embedded-assets.ts` is the tiered resolver: tier 1 dynamically `import()`s the anchor (the rejection under a hoisted install — bun-global upgrades dedupe `@electric-sql/pglite` to the global root, making the anchor's specifiers unresolvable — is EXPECTED and routes to tier 2, which is why the anchor is not a static import); tier 2 derives the dist dir via module resolution of `@electric-sql/pglite` (`import.meta.resolve` then `createRequire` — the SAME specifier the engine imports, so assets can never come from a different pglite copy than the loaded JS); tier 3 throws one actionable error naming everything tried, with the canonical GitHub reinstall command (never the npm-registry name, which is squatted — see the README install warning). `getEmbeddedPgliteOptions()` memoizes one build per process and hands PGLite compiled `WebAssembly.Module`s + fs-bundle Blob + materialized extension tarballs via `PGliteOptions`. Pinned by `test/pglite-embedded-assets.test.ts` + `test/pglite-hoisted-install.test.ts` (real `bun add -g`-shaped hoisted layout).
-- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all BrainEngine methods. The methods of every migrated storage domain (the `migrated` rows of `scripts/engine-sql-baseline.tsv`) are one-line delegations into `src/core/engine-sql/<domain>.ts` over the private `engineSql` getter (a fresh PGLite adapter over `this.db` on every access, so transaction clones run inside their transaction); PGLite-only code stays under `src/core/pglite-engine/`. `listLinkSources({sourceId?, sourceIds?})` returns distinct `link_source` provenances + counts (`ORDER BY count DESC, link_source ASC NULLS LAST`; scalar + federated scoped; one implementation in `engine-sql/links.ts`) powering `gbrain link-sources`. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the whole batch as one JSONB document via `jsonb_to_recordset(($1::jsonb)->'rows')` (bound through `executeRawJsonb` with a `{ rows }` wrapper; rows built by the shared `src/core/batch-rows.ts` helpers, NUL-stripped), and are `batchRetry`-wrapped. `connect()` retries a failed in-memory `PGlite.create()` once, cold, only while no database is attached. The retry omits the snapshot and clears its loaded flag so `initSchema()` replays the schema. Recovery warns on stderr; exhausted recovery retains both error diagnostics. Post-open setup errors instead close the existing database, preserving close-poison and ownership rules. The doctor scratch probe is a separate disk-backed path and does not use this retry. Remaining initialization failures use the existing classifier and, for the `wasm-abort` verdict on a persistent data dir (torn WAL/checkpoint state after an unclean shutdown; it presents like a macOS WASM bug but is not one), runs in-place auto-repair via `attemptWalRepairAndRetry` (static import from `pglite-repair.ts`, per the engine-live rule; the retry create is `preservingProcessExitCode`-wrapped; success sets the public `walRepairReceipt` field + prints `buildWalRepairNotice` to stderr and returns with the lock held). The seam never throws, so every non-repaired path funnels through the single lock-release-then-throw site; repair refuses when the lock was acquired by reaping (`LockHandle.reaped` → `'possibly-live-writer'`), when disabled (`GBRAIN_PGLITE_WAL_REPAIR=off`), on layout-validation failure, or inside the post-failure cooldown. `disconnect()` awaits mandatory resident-consumer stops, closes admission on tracked query/exec/transaction handles, drains admitted statements and best-effort background work, then awaits CHECKPOINT and close before kernel release. A deadline reports `pglite_closing` while actual shutdown continues with ownership retained; a failed close poisons reconnect until process exit. The out-of-band watchdog remains available for event-loop wedges. `searchKeyword`/`searchKeywordChunks` multiply `ts_rank` by the source-factor CASE at chunk grain; `searchVector` is a two-stage CTE — inner CTE keeps `ORDER BY cc.embedding <=> vec` so HNSW stays usable, outer SELECT re-ranks by `raw_score * source_factor`, inner LIMIT scales with offset to preserve pagination. `searchTakes`/`searchTakesVector` take full `SearchOpts` and apply the standard source-scope predicates (federated `sourceIds[]` wins over scalar `sourceId`, via the joined page's `source_id`) alongside the holder allow-list — parity SQL in postgres-engine.ts; pinned by `test/e2e/think-source-isolation-pglite.test.ts`. `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying PGLITE_SCHEMA_SQL — a one-line delegation to the shared `src/core/engine-sql/bootstrap.ts` (see its entry) with the PGLite dialect hooks; no-op on fresh installs and current brains (this is what keeps an upgrade from wedging on a forward-referenced column). `getBrainScore` returns 100/100 with full breakdown (35/25/15/15/10) when `pageCount === 0` (vacuous truth — empty brain has no coverage problem); Pinned by `test/brain-score-breakdown.test.ts` empty-brain assertion + `test/doctor-report-remote.serial.test.ts`. `PGlite.create()` runs inside `preservingProcessExitCode`: PGLite's Emscripten runtime writes its own status into `process.exitCode` (99 at create; in-memory brains run initdb whose status lands on a later tick; the exit status at close — and assigning `undefined` cannot clear a prior value), which would otherwise silently clobber an errored op's exit 1 back to 0. The wrapper keeps the global tidy for external readers; `db.close()` stays unwrapped (its 0-write is baseline behavior test runners depend on). The CLI's exit verdict is immune either way — it lives in the gbrain-owned channel in `cli-force-exit.ts` and never reads `process.exitCode` back. Exports `classifyPgliteInitError(message): 'bunfs' | 'wasm-abort' | 'corrupt' | 'unknown'` + `buildPgliteInitErrorMessage(verdict, original, platform?, ctx?)` + `stringifyPgliteInitError(err)` + `buildWalRepairNotice(receipt)` + the `PgliteInitRepairContext` type, routing the catch-block hint by failure shape (`bunfs` matches literal `$$bunfs` OR `ENOENT[\s\S]*pglite\.data` co-occurrence, surfaces a paste-ready `bun upgrade` + Node fallback; `corrupt` — 58P01/`internal_load_library`/missing vector type, catalog corruption WAL repair can't fix — stays matched BEFORE the wasm arm and routes to `reinit-pglite`; `wasm-abort` matches the real production shapes `Aborted()`/`RuntimeError`/`unreachable` plus legacy signatures, names the corrupt-WAL root cause + the recovery ladder (`pglite-repair` → rebuild → engine switch) + what auto-repair did per `ctx` incl. the honesty-critical `failed-not-restored` arm, and links the upstream tracking issue; `unknown` is platform-gated). `stringifyPgliteInitError` also surfaces message-less Emscripten objects (`ErrnoError (errno N)`) instead of `[object Object]`. Pinned by `test/pglite-init-classifier.test.ts` + `test/pglite-wal-repair.serial.test.ts` + `test/fix-wave-structural.test.ts`. `deletePages(slugs, {sourceId})` + `resolveSlugsByPaths(paths, {sourceId})` (in `engine-sql/pages.ts`) bind `slug = ANY($1::text[])`, caller-chunking primitive throwing when input exceeds `DELETE_BATCH_SIZE`, `deletePages` returns `RETURNING slug` rows so callers filter `pagesAffected` to confirmed deletes. Implements the embedding-signature stale-detection quartet — `sumStaleChunkChars({sourceId?, signature?})`, `setPageEmbeddingSignature(slug, {sourceId?, signature})`, `invalidateStaleSignatureEmbeddings({signature, sourceId?})`, widened `countStaleChunks({sourceId?, signature?})` (the `signature` opt widens via `JOIN pages p ... WHERE cc.embedding IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $signature)`, NULL grandfathered); one SQL copy in `src/core/engine-sql/chunks.ts`, shared with PostgresEngine. PGLite-specific DDL (pgvector, pg_trgm, triggers). Engine-path helper dependencies (`retry`, ontology, recency decay) avoid dynamic `import()`; the only lazy dynamic imports are `ai/gateway.ts` in `initSchema` and the chunk upsert (`engine-sql/chunks.ts` `upsertChunksOnce`, behind `_upsertChunksOnce`), line-marked because their local catches preserve compiled-default and stored-config fallbacks that eager module evaluation would bypass. `getRawData` pushes `p.deleted_at IS NULL` into its `where[]` unless `opts.includeDeleted` — parity twin of the Postgres `alive` fragment; see the postgres-engine.ts entry. Outermost `transaction()` calls run `PgliteCheckpointGuard` (`src/core/pglite-engine/checkpoint-guard.ts`) before BEGIN: when WAL since the last redo point passes half the automatic-checkpoint distance (256 MB with the default 1 GB `max_wal_size`) it issues a top-level `CHECKPOINT` (each probe is queued with its own transaction, so concurrent callers see their predecessors' WAL, and the whole guarded operation is admitted once into the datastore's shutdown drain), because PGLite runs the automatic checkpoint inline inside the WAL write that crosses the trigger and that nested checkpoint spins forever (#5449/#5284). Savepoint transactions never checkpoint; the direct read-only vector-search transaction and other direct driver transactions are not guarded. A failed WAL probe proceeds with a once-per-process warning; a failed `CHECKPOINT` refuses before BEGIN with a `GBrainError` naming `gbrain pglite-repair`. Tests: `test/pglite-checkpoint-guard.test.ts`; the large-store harness `scripts/pglite-checkpoint-harness/supervisor.ts` (external supervisor, WAL-bound assertion) runs outside CI.
+- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all BrainEngine methods. The methods of every migrated storage domain (the `migrated` rows of `scripts/engine-sql-baseline.tsv`) are one-line delegations into `src/core/engine-sql/<domain>.ts` over the private `engineSql` getter (a fresh PGLite adapter over `this.db` per access, so transaction clones run inside their transaction; outside one, writes take the #5449 checkpoint guard); PGLite-only code stays under `src/core/pglite-engine/`. `listLinkSources({sourceId?, sourceIds?})` returns distinct `link_source` provenances + counts (`ORDER BY count DESC, link_source ASC NULLS LAST`; scalar + federated scoped; one implementation in `engine-sql/links.ts`) powering `gbrain link-sources`. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the whole batch as one JSONB document via `jsonb_to_recordset(($1::jsonb)->'rows')` (bound through `executeRawJsonb` with a `{ rows }` wrapper; rows built by the shared `src/core/batch-rows.ts` helpers, NUL-stripped), and are `batchRetry`-wrapped. `connect()` retries a failed in-memory `PGlite.create()` once, cold, only while no database is attached. The retry omits the snapshot and clears its loaded flag so `initSchema()` replays the schema. Recovery warns on stderr; exhausted recovery retains both error diagnostics. Post-open setup errors instead close the existing database, preserving close-poison and ownership rules. The doctor scratch probe is a separate disk-backed path and does not use this retry. Remaining initialization failures use the existing classifier and, for the `wasm-abort` verdict on a persistent data dir (torn WAL/checkpoint state after an unclean shutdown; it presents like a macOS WASM bug but is not one), runs in-place auto-repair via `attemptWalRepairAndRetry` (static import from `pglite-repair.ts`, per the engine-live rule; the retry create is `preservingProcessExitCode`-wrapped; success sets the public `walRepairReceipt` field + prints `buildWalRepairNotice` to stderr and returns with the lock held). The seam never throws, so every non-repaired path funnels through the single lock-release-then-throw site; repair refuses when the lock was acquired by reaping (`LockHandle.reaped` → `'possibly-live-writer'`), when disabled (`GBRAIN_PGLITE_WAL_REPAIR=off`), on layout-validation failure, or inside the post-failure cooldown. `disconnect()` awaits mandatory resident-consumer stops, closes admission on tracked query/exec/transaction handles, drains admitted statements and best-effort background work, then awaits CHECKPOINT and close before kernel release. A deadline reports `pglite_closing` while actual shutdown continues with ownership retained; a failed close poisons reconnect until process exit. The out-of-band watchdog remains available for event-loop wedges. `searchKeyword`/`searchKeywordChunks` multiply `ts_rank` by the source-factor CASE at chunk grain; `searchVector` is a two-stage CTE — inner CTE keeps `ORDER BY cc.embedding <=> vec` so HNSW stays usable, outer SELECT re-ranks by `raw_score * source_factor`, inner LIMIT scales with offset to preserve pagination. `searchTakes`/`searchTakesVector` take full `SearchOpts` and apply the standard source-scope predicates (federated `sourceIds[]` wins over scalar `sourceId`, via the joined page's `source_id`) alongside the holder allow-list — parity SQL in postgres-engine.ts; pinned by `test/e2e/think-source-isolation-pglite.test.ts`. `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying PGLITE_SCHEMA_SQL — a one-line delegation to the shared `src/core/engine-sql/bootstrap.ts` (see its entry) with the PGLite dialect hooks; no-op on fresh installs and current brains (this is what keeps an upgrade from wedging on a forward-referenced column). `getBrainScore` returns 100/100 with full breakdown (35/25/15/15/10) when `pageCount === 0` (vacuous truth — empty brain has no coverage problem); Pinned by `test/brain-score-breakdown.test.ts` empty-brain assertion + `test/doctor-report-remote.serial.test.ts`. `PGlite.create()` runs inside `preservingProcessExitCode`: PGLite's Emscripten runtime writes its own status into `process.exitCode` (99 at create; in-memory brains run initdb whose status lands on a later tick; the exit status at close — and assigning `undefined` cannot clear a prior value), which would otherwise silently clobber an errored op's exit 1 back to 0. The wrapper keeps the global tidy for external readers; `db.close()` stays unwrapped (its 0-write is baseline behavior test runners depend on). The CLI's exit verdict is immune either way — it lives in the gbrain-owned channel in `cli-force-exit.ts` and never reads `process.exitCode` back. Exports `classifyPgliteInitError(message): 'bunfs' | 'wasm-abort' | 'corrupt' | 'unknown'` + `buildPgliteInitErrorMessage(verdict, original, platform?, ctx?)` + `stringifyPgliteInitError(err)` + `buildWalRepairNotice(receipt)` + the `PgliteInitRepairContext` type, routing the catch-block hint by failure shape (`bunfs` matches literal `$$bunfs` OR `ENOENT[\s\S]*pglite\.data` co-occurrence, surfaces a paste-ready `bun upgrade` + Node fallback; `corrupt` — 58P01/`internal_load_library`/missing vector type, catalog corruption WAL repair can't fix — stays matched BEFORE the wasm arm and routes to `reinit-pglite`; `wasm-abort` matches the real production shapes `Aborted()`/`RuntimeError`/`unreachable` plus legacy signatures, names the corrupt-WAL root cause + the recovery ladder (`pglite-repair` → rebuild → engine switch) + what auto-repair did per `ctx` incl. the honesty-critical `failed-not-restored` arm, and links the upstream tracking issue; `unknown` is platform-gated). `stringifyPgliteInitError` also surfaces message-less Emscripten objects (`ErrnoError (errno N)`) instead of `[object Object]`. Pinned by `test/pglite-init-classifier.test.ts` + `test/pglite-wal-repair.serial.test.ts` + `test/fix-wave-structural.test.ts`. `deletePages(slugs, {sourceId})` + `resolveSlugsByPaths(paths, {sourceId})` (in `engine-sql/pages.ts`) bind `slug = ANY($1::text[])`, caller-chunking primitive throwing when input exceeds `DELETE_BATCH_SIZE`, `deletePages` returns `RETURNING slug` rows so callers filter `pagesAffected` to confirmed deletes. Implements the embedding-signature stale-detection quartet — `sumStaleChunkChars({sourceId?, signature?})`, `setPageEmbeddingSignature(slug, {sourceId?, signature})`, `invalidateStaleSignatureEmbeddings({signature, sourceId?})`, widened `countStaleChunks({sourceId?, signature?})` (the `signature` opt widens via `JOIN pages p ... WHERE cc.embedding IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $signature)`, NULL grandfathered); one SQL copy in `src/core/engine-sql/chunks.ts`, shared with PostgresEngine. PGLite-specific DDL (pgvector, pg_trgm, triggers). Engine-path helper dependencies (`retry`, ontology, recency decay) avoid dynamic `import()`; the only lazy dynamic imports are `ai/gateway.ts` in `initSchema` and the chunk upsert (`engine-sql/chunks.ts` `upsertChunksOnce`, behind `_upsertChunksOnce`), line-marked because their local catches preserve compiled-default and stored-config fallbacks that eager module evaluation would bypass. `getRawData` pushes `p.deleted_at IS NULL` into its `where[]` unless `opts.includeDeleted` — parity twin of the Postgres `alive` fragment; see the postgres-engine.ts entry. Outermost `transaction()` calls run `PgliteCheckpointGuard` (`src/core/pglite-engine/checkpoint-guard.ts`) before BEGIN: when WAL since the last redo point passes half the automatic-checkpoint distance (256 MB with the default 1 GB `max_wal_size`) it issues a top-level `CHECKPOINT` (each probe is queued with its own transaction, so concurrent callers see their predecessors' WAL, and the whole guarded operation is admitted once into the datastore's shutdown drain), because PGLite runs the automatic checkpoint inline inside the WAL write that crosses the trigger and that nested checkpoint spins forever (#5449/#5284). Savepoint transactions never checkpoint; the direct read-only vector-search transaction and other direct driver transactions are not guarded. A failed WAL probe proceeds with a once-per-process warning; a failed `CHECKPOINT` refuses before BEGIN with a `GBrainError` naming `gbrain pglite-repair`. Tests: `test/pglite-checkpoint-guard.test.ts`; the large-store harness `scripts/pglite-checkpoint-harness/supervisor.ts` (external supervisor, WAL-bound assertion) runs outside CI.
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers every BrainEngine method whose SQL has not moved to `src/core/engine-sql/` (rows in `scripts/engine-sql-baseline.tsv`); each storage feature lands as a parity twin in both engines (search arms, graph traversal caps, source-scoped stats and health, page lifecycle and soft delete, chunk writes, statement-cache and WAL-checkpoint lifecycle); refactor wave 1 moves shared SQL to `src/core/engine-sql/`.
- `src/core/pglite-lifecycle.ts` — tracks admitted datastore statements and transactions across early-null, rejects new work through captured handles, and supplies the typed closing error. A successful same-datastore reopen resumes its stopped persistence consumer only after database open and filesystem-registry success; replaced or disposed services unregister their lifecycle hooks. Pending or failed close never resets the admission barrier. Both engines expose `registerBeforeDisconnect(stop)` (returns unregister) as a mandatory resident-consumer barrier and `transactionDirect(fn)` for short control work on the existing direct route; nested calls stay in their transaction.
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.md
index 722c4131bd..f92eaae0d9 100644
--- a/docs/architecture/key-files/engines-2.md
+++ b/docs/architecture/key-files/engines-2.md
@@ -17,10 +17,12 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
v
engine-sql/executor.ts SqlExecutor: query/run, executeRaw, unsafe, transaction; {rows, affectedRows}
|
- +--> dialect-pglite.ts db.query on the engine's cached, checkpoint-admitted handle
+ +--> dialect-pglite.ts db.query on the engine's cached, checkpoint-guarded handle
+--> dialect-postgres.ts runUnsafe(conn, sql, params, {signal?, prepare: true, simple: false}); no gauge
```
+ Outside `engine.transaction()`, `engineSql` routes WAL-writing statements through `PgliteCheckpointGuard.runStatement` and executor transactions through `runOutermost` (`src/core/pglite-engine/checkpoint-guard.ts`), like `executeRaw` and `transaction()`. Before that, engine-sql autocommit writes such as `markPagesExtractedBatch` never probed WAL; past the automatic trigger (about 528 MB with max_wal_size 1 GB) the crossing UPDATE ran the checkpoint inline and spun forever (GBRA-69). Pinned by `test/pglite-checkpoint-guard.test.ts` and `test/fixtures/pglite-engine-sql-wal-worker.ts`.
+
Inputs engine-sql never resolves arrive already resolved: source scope (`sourceIds` > `sourceId` > `'default'`), the registry-active embedding column (bare name, quoted with `quoteIdentifier`), page-state guards as callbacks (`lockPageKeys` / `readPageSnapshot`) and the engine's `transaction()` where master used it. A read master ran inside `withScopedReadTransaction` keeps that literal call in the engine method (the RLS AST inventory counts direct sites) and brands the tx handle's executor: `scopedRead(this.engineSqlOn(tx))` on Postgres, `scopedRead(this.engineSql)` on PGLite.
`fragment.ts` numbers placeholders at render time, so text is byte-identical to the tagged templates it replaced (`test/fixtures/goldens/sql-text/`). Capabilities (`maxBindParamsPerStatement`, `transactionAdvisoryLocks`, `probesEmbeddingCast`) carry the real engine differences; `docs/designs/refactor-wave-1/w1-inventory.md` classifies every method. Page-state orchestration stays in the engines: `putPage`'s transaction, page-key lock and revision check, and the `updateSlug` / `setPageAliases` transactions, call `pages.ts` on the transaction clone's executor; `getPage` / `readPageSnapshot` keep their SQL in `page-state/snapshot.ts`. Reads with an early return that must not open a scoped transaction (`listPrefixSampledPages`, `listCorpusSample`) take a `ScopedReadRunner`. Nothing here imports an engine façade (`check:layering`); SQL may splice only constant text (`check:engine-sql-dynamic`); brands are unforgeable (`check:engine-sql-brands`); engine SQL only shrinks (`check:engine-sql-ratchet`). Tests: docs/TESTING.md "Engine-sql".
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 4d45673fea..9ed74c95d7 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -760,7 +760,17 @@ export class PGLiteEngine implements BrainEngine {
* returns the tx handle) runs migrated domain SQL inside its transaction.
*/
private get engineSql(): SqlExecutor {
- return pgliteExecutor(this.db);
+ const db = this.db;
+ if (this._pageTransaction || this._dbWork === null) return pgliteExecutor(db);
+ // #5449: engine-sql writes outside engine.transaction() (autocommit statements and
+ // executor transactions) take the same WAL checkpoint guard as executeRaw/transaction.
+ const guard = this._checkpointGuard ??= new PgliteCheckpointGuard();
+ return pgliteExecutor({
+ query: ((sql: string, params?: unknown[]) => writesWal(sql)
+ ? guard.runStatement(q => db.query(q), () => db.query(sql, params))
+ : db.query(sql, params)) as PGlite['query'],
+ transaction: (fn => guard.runOutermost(q => db.query(q), () => db.transaction(fn))) as PGlite['transaction'],
+ });
}
// Lifecycle
diff --git a/test/fixtures/pglite-engine-sql-wal-worker.ts b/test/fixtures/pglite-engine-sql-wal-worker.ts
new file mode 100644
index 0000000000..4d5e447258
--- /dev/null
+++ b/test/fixtures/pglite-engine-sql-wal-worker.ts
@@ -0,0 +1,38 @@
+/**
+ * Child for test/pglite-checkpoint-guard.test.ts: stamps extraction watermarks
+ * through `markPagesExtractedBatch` (an engine-sql autocommit UPDATE, never
+ * engine.transaction() or executeRaw) in 100-page batches until about 150 MB
+ * of WAL has been written into a file-backed PGLite whose max_wal_size is
+ * 64 MB. Before engine-sql writes took the checkpoint guard, the crossing
+ * UPDATE ran Postgres's automatic checkpoint inline and spun forever (#5449,
+ * the GBRA-69 stamp wedge), so the parent kills this child on a timeout.
+ * argv[2]: an empty directory for the brain. Prints `done <batches>`.
+ */
+import { join } from 'node:path';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { configureGateway } from '../../src/core/ai/gateway.ts';
+
+configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+const path = join(process.argv[2]!, 'brain.pglite');
+let engine = new PGLiteEngine();
+await engine.connect({ engine: 'pglite', database_path: path } as never);
+await engine.initSchema();
+await engine.executeRaw(`INSERT INTO pages (slug, type, title, compiled_truth)
+ SELECT 'notes/page-' || g, 'note', 'Page ' || g, repeat('body ', 200) FROM generate_series(1, 1000) g`);
+await engine.executeRaw("ALTER SYSTEM SET max_wal_size = '64MB'");
+await engine.disconnect();
+engine = new PGLiteEngine();
+await engine.connect({ engine: 'pglite', database_path: path } as never);
+const refs = await engine.listAllPageRefs();
+const [start] = await engine.executeRaw<{ lsn: string }>('SELECT pg_current_wal_lsn()::text AS lsn');
+let batches = 0;
+for (;;) {
+ const [w] = await engine.executeRaw<{ wal: number }>('SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), $1::pg_lsn)::float8 AS wal', [start!.lsn]);
+ if (w!.wal > 150 * 1024 * 1024) break;
+ const at = (batches * 100) % refs.length;
+ await engine.markPagesExtractedBatch(refs.slice(at, at + 100), new Date(Date.UTC(2026, 0, 1, 0, 0, batches)).toISOString());
+ batches++;
+}
+await engine.disconnect();
+console.log(`done ${batches}`);
+process.exit(0);
diff --git a/test/pglite-checkpoint-guard.test.ts b/test/pglite-checkpoint-guard.test.ts
index 70a9700b29..4a6dc12d26 100644
--- a/test/pglite-checkpoint-guard.test.ts
+++ b/test/pglite-checkpoint-guard.test.ts
@@ -10,6 +10,8 @@ import { join } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { CHECKPOINT_GUARD_MAX_BYTES, PgliteCheckpointGuard, checkpointGuardThreshold, writesWal } from '../src/core/pglite-engine/checkpoint-guard.ts';
import { GBrainError } from '../src/core/types.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
const MB = 1024 * 1024;
type Guarded = { _checkpointGuard: PgliteCheckpointGuard | undefined; db: { query(sql: string): Promise<{ rows: Array<Record<string, unknown>> }> } };
@@ -222,4 +224,54 @@ describe('autocommit write statements take the guard', () => {
expect(stdout).toContain('done 200');
} finally { rmSync(dir, { recursive: true, force: true }); }
}, 120_000);
+
+ test('engine-sql autocommit writes (the extraction watermark stamp) past a 64 MB max_wal_size complete instead of wedging', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-engine-sql-wal-'));
+ try {
+ const child = Bun.spawn([process.execPath, join(import.meta.dir, 'fixtures', 'pglite-engine-sql-wal-worker.ts'), dir], { stdout: 'pipe', stderr: 'pipe' });
+ const timer = setTimeout(() => child.kill('SIGKILL'), 90_000);
+ const [stdout, code] = await Promise.all([new Response(child.stdout).text(), child.exited]);
+ clearTimeout(timer);
+ expect(code).toBe(0);
+ expect(stdout).toMatch(/done \d+/);
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+ }, 120_000);
+});
+
+describe('engine-sql writes take the guard (GBRA-69 stamp wedge)', () => {
+ let engine: PGLiteEngine;
+ const refs = [{ slug: 'notes/a', source_id: 'default' }, { slug: 'notes/b', source_id: 'default' }];
+ type Sql = { engineSql: { transaction<T>(fn: (tx: { executeRaw(sql: string): Promise<unknown> }) => Promise<T>): Promise<T> } };
+ beforeAll(async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ for (const { slug } of refs) await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: 'body' });
+ });
+ afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); resetGateway(); });
+
+ test('an autocommit engine-sql write past the threshold checkpoints', async () => {
+ const spy = install(engine, { threshold: 0 });
+ expect(await engine.markPagesExtractedBatch(refs, new Date().toISOString())).toBe(2);
+ expect(spy.checkpoints()).toBe(1);
+ });
+
+ test('an engine-sql executor transaction checkpoints before BEGIN', async () => {
+ const spy = install(engine, { threshold: 0 });
+ await (engine as unknown as Sql).engineSql.transaction(tx => tx.executeRaw("UPDATE pages SET links_extracted_at = now() WHERE slug = 'notes/a'"));
+ expect(spy.checkpoints()).toBe(1);
+ });
+
+ test('inside engine.transaction() only the outermost probe checkpoints', async () => {
+ const spy = install(engine, { threshold: 0 });
+ await engine.transaction(tx => tx.markPagesExtractedBatch(refs, new Date().toISOString()));
+ expect(spy.checkpoints()).toBe(1);
+ });
+
+ test('below the threshold an engine-sql write never checkpoints', async () => {
+ const spy = install(engine, { threshold: Number.MAX_SAFE_INTEGER });
+ await engine.markPagesExtractedBatch(refs, new Date().toISOString());
+ expect(spy.checkpoints()).toBe(0);
+ });
});