Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test: truncateCascade keeps TRUNCATE without autovacuum; dual-backend helper tests

garrytan9d471877adf8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9b7134bf0b..9335d6167b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,15 +12,16 @@ identifiers and attribution are available in the pre-removal Git revision
## [0.60.83.0] - 2026-10-06
-**The Postgres embedding-recovery parity suite runs in about 25 seconds instead of 200 to 260, so it no longer hits the 180-second per-file E2E cap.**
+**The Postgres embedding-recovery parity suite runs in about 25 seconds instead of 210 to 260, so it no longer hits the 180-second per-file E2E cap.**
-Its per-test reset ran `TRUNCATE ... CASCADE` on `pages` and `facts`. That reaches 26 tables and 126 indexes, and Postgres gives every one of them new storage even when they are already empty, so each reset cost about 0.8 seconds. With more than 200 resets across 157 tests, resets were most of the file's runtime, and slower or loaded machines pushed it past the cap. A new test helper empties the same tables by deleting their rows instead, which takes about 4 milliseconds. It falls back to `TRUNCATE` whenever a delete could behave differently. Every test and assertion is unchanged. gbrain itself does not change.
+Its per-test reset ran `TRUNCATE ... CASCADE` on `pages` and `facts`. That reaches 26 tables and 126 indexes, and Postgres gives each of them new storage files even when they are already empty, so each reset cost about 0.8 seconds. With more than 200 resets across 157 tests, resets were most of the file's runtime, and slower or busier machines pushed it past the cap. A new test helper empties the same tables on Postgres by deleting their rows, which takes about 4 milliseconds, and falls back to `TRUNCATE` whenever a delete could behave differently. Every test and assertion is unchanged, and gbrain itself does not change.
### For contributors
-- `truncateCascade(engine, tables)` in `test/helpers/reset-pglite.ts` leaves the same end state as `TRUNCATE <tables> CASCADE` on either engine: it empties the named tables and every table that references them through a foreign key, and sequences keep counting. Small closures are deleted under `session_replication_role = replica`. It uses `TRUNCATE` instead when a closure has TRUNCATE triggers, always- or replica-enabled triggers or rules, inheritance, more than 8 MiB of storage, or no superuser to switch roles. `resetPgliteState` now uses the same fallback rules.
-- `test/embedding-recovery.serial.test.ts` uses the helper for all nine of its resets. On a local pgvector container the direct-Postgres file took 206, 251 and 243 seconds before the change, and 24, 25 and 24 seconds after. With four busy CPU cores it took 243 and 262 seconds before and 26 to 28 seconds after. The PgBouncer pass now takes about 42 seconds.
+- `truncateCascade(engine, tables)` in `test/helpers/reset-pglite.ts` leaves the same end state as `TRUNCATE <tables> CASCADE`: it empties the named tables and every table that references them through a foreign key, and sequences keep counting. On Postgres it deletes the rows with `session_replication_role = replica`. It runs `TRUNCATE` instead when the tables have TRUNCATE triggers, always- or replica-enabled triggers or rules, inheritance, more than 8 MiB of storage, or no superuser to switch roles. It also runs `TRUNCATE` when no autovacuum launcher is running, which includes PGLite. With nothing to clean up the deleted rows there, two later PGLite tests slowed from about 2 seconds to 11, and `TRUNCATE` on PGLite runs in memory. `resetPgliteState` now uses the same fallback rules.
+- `test/embedding-recovery.serial.test.ts` uses the helper for all nine of its resets. On a local pgvector container, the direct-Postgres file took 206 to 251 seconds before the change and 24 to 25 seconds after. With four busy CPU cores it took 243 to 262 seconds before and 26 to 28 seconds after. The PgBouncer pass dropped from 248 seconds to 42 or 43. The PGLite run is unchanged at about 47 seconds.
- `scripts/e2e-backend-matrix.txt` drops the file's `pooled-timeout=600` override, so the PgBouncer pass is held to the standard 180-second cap again.
+- `test/truncate-cascade.test.ts` (PGLite, unit lane) and its Postgres wrapper `test/e2e/truncate-cascade-postgres.test.ts` cover each fallback rule. They check the end state, and they check that Postgres keeps its storage while PGLite gets new storage.
## [0.60.82.0] - 2026-10-06
diff --git a/test/e2e/truncate-cascade-postgres.test.ts b/test/e2e/truncate-cascade-postgres.test.ts
new file mode 100644
index 0000000000..67ef95705d
--- /dev/null
+++ b/test/e2e/truncate-cascade-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../truncate-cascade.test.ts'));
diff --git a/test/helpers/reset-pglite.test.ts b/test/helpers/reset-pglite.test.ts
index fe6cae42c0..4a748ea485 100644
--- a/test/helpers/reset-pglite.test.ts
+++ b/test/helpers/reset-pglite.test.ts
@@ -1,6 +1,6 @@
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
-import { resetPgliteState, truncateCascade } from './reset-pglite.ts';
+import { resetPgliteState } from './reset-pglite.ts';
let engine: PGLiteEngine;
@@ -213,60 +213,3 @@ describe('resetPgliteState', () => {
await expect(engine.executeRaw('INSERT INTO reset_fixture_child (parent_id) VALUES (999)')).rejects.toThrow('foreign key');
});
});
-
-describe('truncateCascade', () => {
- test('empties the named table and its transitive referencers, reusing storage and continuing sequences', async () => {
- await engine.executeRaw('CREATE SCHEMA reset_fixture_external');
- await engine.executeRaw('CREATE TABLE reset_fixture_external.child (id serial PRIMARY KEY, child_id int REFERENCES reset_fixture_child)');
- await engine.executeRaw('CREATE TABLE reset_fixture_added (id serial PRIMARY KEY)');
- await engine.executeRaw("INSERT INTO reset_fixture_parent (value) VALUES ('parent')");
- await engine.executeRaw('INSERT INTO reset_fixture_child (parent_id) VALUES (1)');
- await engine.executeRaw('INSERT INTO reset_fixture_external.child (child_id) VALUES (1)');
- await engine.executeRaw('INSERT INTO reset_fixture_added DEFAULT VALUES');
- const sql = "SELECT oid, relfilenode FROM pg_class WHERE oid IN ('reset_fixture_parent'::regclass, 'reset_fixture_child_pkey'::regclass) ORDER BY oid";
- const storage = await engine.executeRaw(sql);
- await truncateCascade(engine, ['reset_fixture_parent']);
- expect(await engine.executeRaw(sql)).toEqual(storage);
- for (const table of ['reset_fixture_parent', 'reset_fixture_child', 'reset_fixture_external.child']) {
- expect(await engine.executeRaw(`SELECT * FROM ${table}`)).toEqual([]);
- }
- expect(await engine.executeRaw('SELECT id FROM reset_fixture_added')).toEqual([{ id: 1 }]);
- expect(await engine.executeRaw("INSERT INTO reset_fixture_parent (value) VALUES ('next') RETURNING id")).toEqual([{ id: 2 }]);
- expect(await engine.executeRaw("SELECT current_setting('session_replication_role') AS role")).toEqual([{ role: 'origin' }]);
- await expect(engine.executeRaw('INSERT INTO reset_fixture_child (parent_id) VALUES (999)')).rejects.toThrow('foreign key');
- });
-
- test('bypasses ordinary DELETE triggers like TRUNCATE and leaves them active afterwards', async () => {
- await engine.executeRaw("CREATE FUNCTION reset_fixture_guard() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'delete trigger is active'; END $$");
- await engine.executeRaw('CREATE TRIGGER reset_fixture_delete BEFORE DELETE ON reset_fixture_child FOR EACH ROW EXECUTE FUNCTION reset_fixture_guard()');
- await engine.executeRaw("INSERT INTO reset_fixture_parent (value) VALUES ('parent')");
- await engine.executeRaw('INSERT INTO reset_fixture_child (parent_id) VALUES (1)');
- await truncateCascade(engine, ['reset_fixture_parent']);
- expect(await engine.executeRaw('SELECT * FROM reset_fixture_child')).toEqual([]);
- await engine.executeRaw('INSERT INTO reset_fixture_child (parent_id) VALUES (NULL)');
- await expect(engine.executeRaw('DELETE FROM reset_fixture_child')).rejects.toThrow('delete trigger is active');
- });
-
- test.each(['ALWAYS', 'REPLICA'])('falls back to TRUNCATE with an ENABLE %s row trigger in the closure', async mode => {
- await engine.executeRaw("CREATE FUNCTION reset_fixture_guard() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'replica delete trigger'; END $$");
- await engine.executeRaw('CREATE TRIGGER reset_fixture_delete BEFORE DELETE ON reset_fixture_child FOR EACH ROW EXECUTE FUNCTION reset_fixture_guard()');
- await engine.executeRaw(`ALTER TABLE reset_fixture_child ENABLE ${mode} TRIGGER reset_fixture_delete`);
- await engine.executeRaw("INSERT INTO reset_fixture_parent (value) VALUES ('parent')");
- await engine.executeRaw('INSERT INTO reset_fixture_child (parent_id) VALUES (1)');
- await truncateCascade(engine, ['reset_fixture_parent']);
- expect(await engine.executeRaw('SELECT * FROM reset_fixture_child')).toEqual([]);
- });
-
- test('fires TRUNCATE triggers anywhere in the closure', async () => {
- await engine.executeRaw('CREATE TEMP TABLE reset_fixture_truncate_events (value text)');
- await engine.executeRaw("CREATE FUNCTION reset_fixture_guard() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN INSERT INTO reset_fixture_truncate_events VALUES (TG_TABLE_NAME); RETURN NULL; END $$");
- await engine.executeRaw('CREATE TRIGGER reset_fixture_truncate AFTER TRUNCATE ON reset_fixture_child EXECUTE FUNCTION reset_fixture_guard()');
- await truncateCascade(engine, ['reset_fixture_parent']);
- expect(await engine.executeRaw('SELECT * FROM reset_fixture_truncate_events')).toEqual([{ value: 'reset_fixture_child' }]);
- });
-
- test('refuses empty or unsafe table lists', async () => {
- await expect(truncateCascade(engine, [])).rejects.toThrow('non-empty');
- await expect(truncateCascade(engine, ['pages; DROP TABLE pages'])).rejects.toThrow('invalid table name');
- });
-});
diff --git a/test/helpers/reset-pglite.ts b/test/helpers/reset-pglite.ts
index 14e5d8aee2..6b506dad31 100644
--- a/test/helpers/reset-pglite.ts
+++ b/test/helpers/reset-pglite.ts
@@ -193,13 +193,19 @@ export async function resetPgliteStateNarrow(
* the named tables and every table that references them, transitively, by
* foreign key. Works on either engine.
*
- * TRUNCATE gives every table and index in that closure new storage, even when
- * all of them are already empty. `pages` alone reaches 23 tables and over 100
- * indexes, so on a Postgres container one call costs ~0.8 s; a per-test reset
- * built on it dominated embedding-recovery-parity's wall clock. This deletes
- * the closure's rows under replica role instead (no file churn), and keeps
- * TRUNCATE whenever DELETE could behave differently (DELETE_DIVERGES_FROM_TRUNCATE).
- * No ALTER SEQUENCE is issued, so event triggers see nothing on either path.
+ * On Postgres, TRUNCATE gives every table and index in that closure new
+ * storage files, even when all of them are already empty. `pages` alone
+ * reaches 23 tables and over 100 indexes, so one call costs ~0.8 s on a
+ * container; a per-test reset built on it dominated embedding-recovery-parity's
+ * wall clock. There this deletes the closure's rows under replica role instead
+ * (~4 ms), and keeps TRUNCATE whenever DELETE could behave differently
+ * (DELETE_DIVERGES_FROM_TRUNCATE).
+ *
+ * Without an autovacuum launcher (PGLite) TRUNCATE is kept: nothing reclaims
+ * the deleted rows, and the stale page counts misled the planner enough to
+ * slow two later embedding-recovery tests from ~2 s to ~11 s, while TRUNCATE
+ * there is an in-memory operation. No ALTER SEQUENCE is issued, so event
+ * triggers see nothing on either path.
*/
export async function truncateCascade(engine: NarrowResetEngine, tables: string[]): Promise<void> {
if (tables.length === 0) throw new Error('truncateCascade: table list must be non-empty');
@@ -222,7 +228,9 @@ export async function truncateCascade(engine: NarrowResetEngine, tables: string[
SELECT c.conrelid FROM pg_constraint c JOIN closure ON c.confrelid = closure.oid WHERE c.contype = 'f'
)
SELECT array_agg(oid::regclass), sum(pg_total_relation_size(oid)) INTO tables, storage_bytes FROM closure;
- IF ${DELETE_DIVERGES_FROM_TRUNCATE} THEN
+ IF ${DELETE_DIVERGES_FROM_TRUNCATE} OR NOT EXISTS (
+ SELECT 1 FROM pg_stat_activity WHERE backend_type = 'autovacuum launcher'
+ ) THEN
EXECUTE 'TRUNCATE ${quoted} CASCADE';
ELSE
PERFORM set_config('session_replication_role', 'replica', true);
diff --git a/test/truncate-cascade.test.ts b/test/truncate-cascade.test.ts
new file mode 100644
index 0000000000..b4b1552418
--- /dev/null
+++ b/test/truncate-cascade.test.ts
@@ -0,0 +1,92 @@
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { setupDB, teardownDB } from './e2e/helpers.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { truncateCascade } from './helpers/reset-pglite.ts';
+
+for (const kind of testBackends()) {
+ describe(`truncateCascade (${kind})`, () => {
+ let engine: BrainEngine;
+ beforeAll(async () => {
+ if (kind === 'postgres') engine = await setupDB();
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
+ await engine.executeRaw('CREATE TABLE truncate_fixture_parent (id serial PRIMARY KEY, value text)');
+ await engine.executeRaw('CREATE TABLE truncate_fixture_child (id serial PRIMARY KEY, parent_id int REFERENCES truncate_fixture_parent)');
+ await engine.executeRaw('CREATE TABLE truncate_fixture_unrelated (id serial PRIMARY KEY)');
+ }, 60_000);
+ beforeEach(async () => {
+ await engine.executeRaw('TRUNCATE truncate_fixture_parent, truncate_fixture_unrelated RESTART IDENTITY CASCADE');
+ });
+ afterEach(async () => {
+ await engine.executeRaw('DROP SCHEMA IF EXISTS truncate_fixture_external CASCADE');
+ await engine.executeRaw('DROP TABLE IF EXISTS truncate_fixture_events');
+ await engine.executeRaw('DROP FUNCTION IF EXISTS truncate_fixture_guard() CASCADE');
+ });
+ afterAll(async () => {
+ await engine.executeRaw('DROP TABLE IF EXISTS truncate_fixture_child, truncate_fixture_parent, truncate_fixture_unrelated CASCADE');
+ if (kind === 'postgres') await teardownDB();
+ else await engine.disconnect();
+ });
+
+ test('empties the named table and its transitive referencers, continuing sequences', async () => {
+ await engine.executeRaw('CREATE SCHEMA truncate_fixture_external');
+ await engine.executeRaw('CREATE TABLE truncate_fixture_external.grandchild (id serial PRIMARY KEY, child_id int REFERENCES truncate_fixture_child)');
+ await engine.executeRaw("INSERT INTO truncate_fixture_parent (value) VALUES ('parent')");
+ await engine.executeRaw('INSERT INTO truncate_fixture_child (parent_id) VALUES (1)');
+ await engine.executeRaw('INSERT INTO truncate_fixture_external.grandchild (child_id) VALUES (1)');
+ await engine.executeRaw('INSERT INTO truncate_fixture_unrelated DEFAULT VALUES');
+ await truncateCascade(engine, ['truncate_fixture_parent']);
+ for (const table of ['truncate_fixture_parent', 'truncate_fixture_child', 'truncate_fixture_external.grandchild']) {
+ expect(await engine.executeRaw(`SELECT * FROM ${table}`)).toEqual([]);
+ }
+ expect(await engine.executeRaw('SELECT id FROM truncate_fixture_unrelated')).toEqual([{ id: 1 }]);
+ expect(await engine.executeRaw("INSERT INTO truncate_fixture_parent (value) VALUES ('next') RETURNING id")).toEqual([{ id: 2 }]);
+ expect(await engine.executeRaw("SELECT current_setting('session_replication_role') AS role")).toEqual([{ role: 'origin' }]);
+ await expect(engine.executeRaw('INSERT INTO truncate_fixture_child (parent_id) VALUES (999)')).rejects.toThrow('foreign key');
+ });
+
+ test(`${kind === 'postgres' ? 'reuses' : 'replaces'} table and index storage`, async () => {
+ await engine.executeRaw("INSERT INTO truncate_fixture_parent (value) VALUES ('parent')");
+ const sql = "SELECT relfilenode FROM pg_class WHERE oid IN ('truncate_fixture_parent'::regclass, 'truncate_fixture_child_pkey'::regclass) ORDER BY oid";
+ const storage = await engine.executeRaw(sql);
+ await truncateCascade(engine, ['truncate_fixture_parent']);
+ if (kind === 'postgres') expect(await engine.executeRaw(sql)).toEqual(storage);
+ else expect(await engine.executeRaw(sql)).not.toEqual(storage);
+ });
+
+ test('bypasses ordinary DELETE triggers like TRUNCATE and leaves them active afterwards', async () => {
+ await engine.executeRaw("CREATE FUNCTION truncate_fixture_guard() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'delete trigger is active'; END $$");
+ await engine.executeRaw('CREATE TRIGGER truncate_fixture_delete BEFORE DELETE ON truncate_fixture_child FOR EACH ROW EXECUTE FUNCTION truncate_fixture_guard()');
+ await engine.executeRaw("INSERT INTO truncate_fixture_parent (value) VALUES ('parent')");
+ await engine.executeRaw('INSERT INTO truncate_fixture_child (parent_id) VALUES (1)');
+ await truncateCascade(engine, ['truncate_fixture_parent']);
+ expect(await engine.executeRaw('SELECT * FROM truncate_fixture_child')).toEqual([]);
+ await engine.executeRaw('INSERT INTO truncate_fixture_child (parent_id) VALUES (NULL)');
+ await expect(engine.executeRaw('DELETE FROM truncate_fixture_child')).rejects.toThrow('delete trigger is active');
+ });
+
+ test.each(['ALWAYS', 'REPLICA'])('falls back to TRUNCATE with an ENABLE %s row trigger in the closure', async mode => {
+ await engine.executeRaw("CREATE FUNCTION truncate_fixture_guard() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'replica delete trigger'; END $$");
+ await engine.executeRaw('CREATE TRIGGER truncate_fixture_delete BEFORE DELETE ON truncate_fixture_child FOR EACH ROW EXECUTE FUNCTION truncate_fixture_guard()');
+ await engine.executeRaw(`ALTER TABLE truncate_fixture_child ENABLE ${mode} TRIGGER truncate_fixture_delete`);
+ await engine.executeRaw("INSERT INTO truncate_fixture_parent (value) VALUES ('parent')");
+ await engine.executeRaw('INSERT INTO truncate_fixture_child (parent_id) VALUES (1)');
+ await truncateCascade(engine, ['truncate_fixture_parent']);
+ expect(await engine.executeRaw('SELECT * FROM truncate_fixture_child')).toEqual([]);
+ });
+
+ test('fires TRUNCATE triggers anywhere in the closure', async () => {
+ await engine.executeRaw('CREATE TABLE truncate_fixture_events (value text)');
+ await engine.executeRaw("CREATE FUNCTION truncate_fixture_guard() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN INSERT INTO truncate_fixture_events VALUES (TG_TABLE_NAME); RETURN NULL; END $$");
+ await engine.executeRaw('CREATE TRIGGER truncate_fixture_truncate AFTER TRUNCATE ON truncate_fixture_child EXECUTE FUNCTION truncate_fixture_guard()');
+ await truncateCascade(engine, ['truncate_fixture_parent']);
+ expect(await engine.executeRaw('SELECT * FROM truncate_fixture_events')).toEqual([{ value: 'truncate_fixture_child' }]);
+ });
+
+ test('refuses empty or unsafe table lists', async () => {
+ await expect(truncateCascade(engine, [])).rejects.toThrow('non-empty');
+ await expect(truncateCascade(engine, ['pages; DROP TABLE pages'])).rejects.toThrow('invalid table name');
+ });
+ });
+}