Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

pglite: autocommit write statements take the WAL checkpoint guard

garrytan854ca64a35f9
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 138e0e292e..677372b6a6 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -129,7 +129,7 @@ import {
import { hasCJK } from './cjk.ts';
import * as factsImpl from './engine-sql/facts.ts';
import * as takesImpl from './engine-sql/takes.ts';
-import { PgliteCheckpointGuard } from './pglite-engine/checkpoint-guard.ts';
+import { PgliteCheckpointGuard, writesWal } from './pglite-engine/checkpoint-guard.ts';
import { pgliteExecutor } from './engine-sql/dialect-pglite.ts';
import type { SqlExecutor } from './engine-sql/executor.ts';
import { scopedRead, unscopedExecutor } from './engine-sql/brands.ts';
@@ -2749,7 +2749,10 @@ export class PGLiteEngine implements BrainEngine {
if (opts?.signal?.aborted) {
throw new DOMException('aborted', 'AbortError');
}
- const queryPromise = this.db.query(sql, params).then((r) => r.rows as T[]);
+ const queryPromise = this.autocommitWrite(sql)
+ ? (this._checkpointGuard ??= new PgliteCheckpointGuard())
+ .runStatement(q => this.db.query(q), () => this.db.query(sql, params)).then((r) => r.rows as T[])
+ : this.db.query(sql, params).then((r) => r.rows as T[]);
if (!opts?.signal) return queryPromise;
const abortPromise = new Promise<T[]>((_resolve, reject) => {
opts.signal!.addEventListener('abort', () => {
@@ -2759,6 +2762,16 @@ export class PGLiteEngine implements BrainEngine {
return Promise.race([queryPromise, abortPromise]);
}
+ /**
+ * #5449 for statements outside engine.transaction(): an autocommit write is
+ * its own outermost transaction, so it takes the same checkpoint guard. Bulk
+ * raw writers (extract batches, vector updates) otherwise grow WAL past the
+ * automatic trigger and wedge PGLite inside the write that crosses it.
+ */
+ private autocommitWrite(sql: string): boolean {
+ return !this._pageTransaction && this._dbWork !== null && writesWal(sql);
+ }
+
/**
* PGLite is in-process WASM with no connection pooler, so the direct-pool
* routing that `executeRawDirect` provides on Postgres is a no-op here:
diff --git a/src/core/pglite-engine/checkpoint-guard.ts b/src/core/pglite-engine/checkpoint-guard.ts
index efca898876..2c8f8cb92d 100644
--- a/src/core/pglite-engine/checkpoint-guard.ts
+++ b/src/core/pglite-engine/checkpoint-guard.ts
@@ -6,12 +6,23 @@
* spins forever at 100% CPU. The guard keeps the automatic trigger from ever
* firing mid-transaction: before an outermost write transaction begins, it
* runs a top-level CHECKPOINT once WAL since redo passes half of the trigger
- * distance (256 MB with the default 1 GB max_wal_size).
+ * distance (256 MB with the default 1 GB max_wal_size). A write statement run
+ * outside engine.transaction() is its own outermost transaction and takes the
+ * same guard (`writesWal`).
*/
import { GBrainError } from '../types.ts';
export const CHECKPOINT_GUARD_MAX_BYTES = 256 * 1024 * 1024;
+/** Reads and transaction control never start a WAL-writing transaction of their own. */
+const READ_OR_CONTROL = /^\s*(select|show|explain|values|table|begin|start|commit|end|rollback|savepoint|release|set|reset|checkpoint)\b/i;
+
+/** Whether a statement run on its own (autocommit) may write WAL, so it takes the guard like an outermost transaction. */
+export function writesWal(sql: string): boolean {
+ if (READ_OR_CONTROL.test(sql)) return false;
+ return !/^\s*with\b/i.test(sql) || /\b(insert|update|delete|merge)\b/i.test(sql);
+}
+
type Query = (sql: string) => Promise<{ rows: Array<Record<string, unknown>> }>;
/**
@@ -29,6 +40,7 @@ export class PgliteCheckpointGuard {
private threshold: number | undefined;
private warned = false;
private tail: Promise<void> = Promise.resolve();
+ private outermost = 0;
/** `query` replaces the admitted database's query function (tests inject failures here). */
constructor(private readonly override?: Query, private readonly warn: (message: string) => void = message => console.warn(message)) {}
@@ -42,11 +54,23 @@ export class PgliteCheckpointGuard {
const prior = this.tail;
const turn = Promise.withResolvers<void>();
this.tail = turn.promise;
- await prior;
+ this.outermost++;
try {
+ await prior;
await this.beforeOutermostTransaction(this.override ?? query);
return await transaction();
- } finally { turn.resolve(); }
+ } finally { this.outermost--; turn.resolve(); }
+ }
+
+ /**
+ * An autocommit write statement probes like an outermost transaction but
+ * never queues behind one: a statement issued from inside an open
+ * transaction's callback must not wait for that transaction to finish. While
+ * a guarded transaction is open or queued, its own probe covers the WAL.
+ */
+ async runStatement<T>(query: Query, statement: () => Promise<T>): Promise<T> {
+ if (this.outermost === 0) await this.beforeOutermostTransaction(this.override ?? query);
+ return statement();
}
private async beforeOutermostTransaction(query: Query): Promise<void> {
diff --git a/test/fixtures/pglite-autocommit-wal-worker.ts b/test/fixtures/pglite-autocommit-wal-worker.ts
new file mode 100644
index 0000000000..ad01499947
--- /dev/null
+++ b/test/fixtures/pglite-autocommit-wal-worker.ts
@@ -0,0 +1,27 @@
+/**
+ * Child for test/pglite-checkpoint-guard.test.ts: writes about 200 MB of WAL
+ * through autocommit `executeRaw` statements (never engine.transaction()) into
+ * a file-backed PGLite whose max_wal_size is 64 MB, so the automatic
+ * checkpoint trigger is crossed many times. Before the guard covered
+ * autocommit writes, PGLite ran that checkpoint inline inside the crossing
+ * write and spun forever (#5449), 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';
+
+const path = join(process.argv[2]!, 'brain.pglite');
+let engine = new PGLiteEngine();
+await engine.connect({ engine: 'pglite', database_path: path } as never);
+await engine.executeRaw("ALTER SYSTEM SET max_wal_size = '64MB'");
+await engine.executeRaw('CREATE TABLE wal_bulk (id int, v text)');
+await engine.disconnect();
+engine = new PGLiteEngine();
+await engine.connect({ engine: 'pglite', database_path: path } as never);
+const batches = 200;
+for (let i = 0; i < batches; i++) {
+ await engine.executeRaw("INSERT INTO wal_bulk SELECT g, md5(random()::text) || repeat('x', 900) FROM generate_series(1, 1000) g");
+}
+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 2cbd93af3f..6ead892886 100644
--- a/test/pglite-checkpoint-guard.test.ts
+++ b/test/pglite-checkpoint-guard.test.ts
@@ -1,10 +1,14 @@
-/** #5449: the outermost PGLite write transaction checkpoints before BEGIN; savepoints never do. */
+/**
+ * #5449: the outermost PGLite write transaction checkpoints before BEGIN; savepoints never do.
+ * An autocommit write statement (executeRaw outside engine.transaction()) takes the same guard:
+ * the PGLite 20k scale tier wedged in its raw vector UPDATEs once WAL crossed the trigger.
+ */
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { CHECKPOINT_GUARD_MAX_BYTES, PgliteCheckpointGuard, checkpointGuardThreshold } from '../src/core/pglite-engine/checkpoint-guard.ts';
+import { CHECKPOINT_GUARD_MAX_BYTES, PgliteCheckpointGuard, checkpointGuardThreshold, writesWal } from '../src/core/pglite-engine/checkpoint-guard.ts';
import { GBrainError } from '../src/core/types.ts';
const MB = 1024 * 1024;
@@ -174,3 +178,40 @@ describe('guarded transactions and shutdown', () => {
expect(guarded._checkpointGuard).not.toBe(before);
});
});
+
+describe('autocommit write statements take the guard', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.executeRaw('CREATE TABLE autocommit_probe (id int PRIMARY KEY, v text)');
+ });
+ afterAll(async () => { await engine.disconnect(); });
+
+ test('writes, DML in a WITH and DDL are guarded; reads and transaction control are not', () => {
+ for (const sql of ['INSERT INTO t VALUES (1)', ' update t set v = 1', 'DELETE FROM t', 'WITH x AS (UPDATE t SET v = 1 RETURNING id) SELECT * FROM x',
+ 'CREATE INDEX i ON t (v)', 'ANALYZE t', 'VACUUM t']) expect(writesWal(sql)).toBe(true);
+ for (const sql of ['SELECT 1', ' select * from t', 'WITH x AS (SELECT 1) SELECT * FROM x', 'EXPLAIN SELECT 1', 'SHOW max_wal_size',
+ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SAVEPOINT s', 'SET search_path = public', 'CHECKPOINT']) expect(writesWal(sql)).toBe(false);
+ });
+
+ test('an autocommit write past the threshold checkpoints first; a read never does', async () => {
+ const spy = install(engine, { threshold: 0 });
+ await engine.executeRaw("INSERT INTO autocommit_probe VALUES (1, 'guarded')");
+ expect(spy.checkpoints()).toBe(1);
+ await engine.executeRaw('SELECT * FROM autocommit_probe');
+ expect(spy.checkpoints()).toBe(1);
+ });
+
+ test('about 200 MB of autocommit WAL past a 64 MB max_wal_size completes instead of wedging', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-autocommit-wal-'));
+ try {
+ const child = Bun.spawn([process.execPath, join(import.meta.dir, 'fixtures', 'pglite-autocommit-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).toContain('done 200');
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+ }, 120_000);
+});