Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test: per-test parity reset deletes rows instead of re-truncating 26 tables
garrytan1df7b6d77601
diff --git a/scripts/e2e-backend-matrix.txt b/scripts/e2e-backend-matrix.txtindex aadc6030dc..c5c48ec111 100644--- a/scripts/e2e-backend-matrix.txt+++ b/scripts/e2e-backend-matrix.txt@@ -27,7 +27,7 @@ test/e2e/backup-coverage-parity.test.tstest/e2e/chronicle-event-projection-parity.test.tstest/e2e/code-edges-read-parity.test.tstest/e2e/doctor-silent-death-parity.test.ts-test/e2e/embedding-recovery-parity.test.ts pooled-timeout=600+test/e2e/embedding-recovery-parity.test.tstest/e2e/engine-parity-cjk.test.tstest/e2e/engine-parity-salience.test.tstest/e2e/engine-parity.test.tsdiff --git a/test/embedding-recovery.serial.test.ts b/test/embedding-recovery.serial.test.tsindex 7ca0aee747..e5d08330ac 100644--- a/test/embedding-recovery.serial.test.ts+++ b/test/embedding-recovery.serial.test.ts@@ -4,7 +4,7 @@ import { PostgresEngine } from '../src/core/postgres-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 { resetPgliteState } from './helpers/reset-pglite.ts';+import { resetPgliteState, truncateCascade } from './helpers/reset-pglite.ts';import { configureGateway, getEmbeddingModel, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';import { applyEmbeddingMigration, planEmbeddingMigration, runSchemaTransition, verifyMigrationComplete, readMigrationState, reconcilePageSignatures, verifySearchRoundTrip } from '../src/core/embedding-migration.ts';import { readContentChunksEmbeddingDim } from '../src/core/embedding-dim-check.ts';@@ -62,7 +62,7 @@ for (const kind of backends) {beforeEach(async () => {if (kind === 'pglite') await resetPgliteState(engine as PGLiteEngine);else {- await engine.executeRaw('TRUNCATE facts, pages, fact_withdrawals, page_projection_jobs CASCADE');+ await truncateCascade(engine, ['facts', 'pages', 'fact_withdrawals', 'page_projection_jobs']);await engine.executeRaw("DELETE FROM config WHERE key LIKE 'embedding_migration.%'");}await engine.setConfig('embedding_model', model);@@ -113,7 +113,7 @@ for (const kind of backends) {}describe('archived eligibility boundary', () => {afterEach(async () => {- await engine.executeRaw('TRUNCATE pages CASCADE');+ await truncateCascade(engine, ['pages']);await engine.executeRaw("UPDATE sources SET archived=false WHERE id='default'");});for (const scenario of ['drift', 'null', 'unsealed', 'chunkless', 'signature', 'false-stamp']) {@@ -404,7 +404,7 @@ for (const kind of backends) {});describe('explicit archived admission', () => {afterEach(async () => {- await engine.executeRaw('TRUNCATE pages CASCADE');+ await truncateCascade(engine, ['pages']);await engine.executeRaw("UPDATE sources SET archived=false WHERE id='default'");});async function seedExplicit(scenario: string) {@@ -632,7 +632,7 @@ for (const kind of backends) {expect(row.chunk.embedded_at).toBeNull();}expect(await engine.invalidateContentDriftEmbeddings({ sourceId })).toBe(0);- } finally { await engine.executeRaw('TRUNCATE pages CASCADE'); }+ } finally { await truncateCascade(engine, ['pages']); }});}test('deleted legacy drift: same-width migration completes and preserves deleted vector hash and timestamp', async () => {@@ -647,7 +647,7 @@ for (const kind of backends) {AND cc.embedded_text_hash=md5(cc.chunk_text) AND cc.model=$1 AS correctFROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE p.slug='live-drift'`, ['openai:text-embedding-3-large']);expect(live).toEqual([{ correct: true }, { correct: true }]);- } finally { await engine.executeRaw('TRUNCATE pages CASCADE'); }+ } finally { await truncateCascade(engine, ['pages']); }});for (const retained of [true, false]) {const label = retained ? 'retained vector' : 'NULL vector';@@ -759,7 +759,7 @@ for (const kind of backends) {expect(after).toEqual({ width: targetDimensions, model: targetModel, sealed: true });} finally {rmSync(dir, { recursive: true, force: true });- await engine.executeRaw('TRUNCATE pages CASCADE');+ await truncateCascade(engine, ['pages']);await runSchemaTransition(engine, dimensions);}});@@ -800,7 +800,7 @@ for (const kind of backends) {if (!blocked) expect(await engine.countStaleChunks({ sourceId: 'default' })).toBe(0);} finally {await engine.executeRaw('UPDATE sources SET archived=false,archived_at=NULL,archive_expires_at=NULL WHERE id=$1', [archivedSource]);- await engine.executeRaw('TRUNCATE facts,pages CASCADE');+ await truncateCascade(engine, ['facts', 'pages']);await runSchemaTransition(engine, dimensions);}});@@ -1043,7 +1043,7 @@ for (const kind of backends) {expect((await readContentChunksEmbeddingDim(engine)).dims).toBe(dimensions);} finally {await engine.executeRaw("UPDATE sources SET archived=false WHERE id='default'");- await engine.executeRaw('TRUNCATE facts, pages CASCADE');+ await truncateCascade(engine, ['facts', 'pages']);await runSchemaTransition(engine, dimensions);}});@@ -1162,7 +1162,7 @@ for (const kind of backends) {expect((await countStaleFactEmbeddings(engine, 'openai:text-embedding-3-large', dimensions * 2)).count).toBe(0);} finally {await engine.executeRaw("UPDATE sources SET archived=false,archived_at=NULL,archive_expires_at=NULL WHERE id='default'");- await engine.executeRaw('TRUNCATE facts, fact_withdrawals, pages CASCADE');+ await truncateCascade(engine, ['facts', 'fact_withdrawals', 'pages']);await runSchemaTransition(engine, dimensions);}});diff --git a/test/helpers/reset-pglite.test.ts b/test/helpers/reset-pglite.test.tsindex 4a748ea485..fe6cae42c0 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 } from './reset-pglite.ts';+import { resetPgliteState, truncateCascade } from './reset-pglite.ts';let engine: PGLiteEngine;@@ -213,3 +213,60 @@ 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.tsindex 12cb859bc1..14e5d8aee2 100644--- a/test/helpers/reset-pglite.ts+++ b/test/helpers/reset-pglite.ts@@ -65,6 +65,22 @@ import { disposePersistenceConsumer } from '../../src/core/persistence/service.t// after a reset. Production never truncates the clock table.const PRESERVE_TABLES = new Set(['schema_version', 'page_generation_clock', 'persistence_brain']);+// Conditions (over plpgsql variables `tables regclass[]` and `storage_bytes`)+// under which a replica-role DELETE of `tables` would not match TRUNCATE:+// TRUNCATE or always/replica triggers, always/replica rules, inheritance,+// no superuser to set session_replication_role, or enough storage that dead+// rows should be reclaimed by TRUNCATE instead.+const DELETE_DIVERGES_FROM_TRUNCATE = `storage_bytes > 8 * 1024 * 1024 OR EXISTS (+ SELECT 1 FROM pg_trigger WHERE tgrelid = ANY(tables)+ AND ((tgtype::int & 32) <> 0 OR tgenabled IN ('A', 'R'))+ ) OR EXISTS (+ SELECT 1 FROM pg_rewrite WHERE ev_class = ANY(tables) AND ev_enabled IN ('A', 'R')+ ) OR EXISTS (+ SELECT 1 FROM pg_inherits WHERE inhrelid = ANY(tables) OR inhparent = ANY(tables)+ ) OR NOT EXISTS (+ SELECT 1 FROM pg_roles WHERE rolname = current_user AND rolsuper+ )`;+export async function resetPgliteState(engine: PGLiteEngine): Promise<void> {await disposePersistenceConsumer(engine);await engine.executeRaw(`DO $reset$@@ -83,20 +99,11 @@ export async function resetPgliteState(engine: PGLiteEngine): Promise<void> {WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p')AND c.relname NOT IN (${[...PRESERVE_TABLES].map(t => `'${t}'`).join(', ')});IF targets IS NULL THEN RETURN; END IF;- IF storage_bytes > 8 * 1024 * 1024 OR EXISTS (- SELECT 1 FROM pg_trigger WHERE tgrelid = ANY(tables)- AND ((tgtype::int & 32) <> 0 OR tgenabled IN ('A', 'R'))- ) OR EXISTS (- SELECT 1 FROM pg_rewrite WHERE ev_class = ANY(tables) AND ev_enabled IN ('A', 'R')- ) OR EXISTS (+ IF ${DELETE_DIVERGES_FROM_TRUNCATE} OR EXISTS (SELECT 1 FROM pg_constraint WHERE contype = 'f'AND confrelid = ANY(tables) AND NOT conrelid = ANY(tables)- ) OR EXISTS (- SELECT 1 FROM pg_inherits WHERE inhrelid = ANY(tables) OR inhparent = ANY(tables)) OR EXISTS (SELECT 1 FROM pg_event_trigger WHERE evtenabled <> 'D'- ) OR NOT EXISTS (- SELECT 1 FROM pg_roles WHERE rolname = current_user AND rolsuper) THENEXECUTE 'TRUNCATE ' || targets || ' RESTART IDENTITY CASCADE';ELSE@@ -180,3 +187,49 @@ export async function resetPgliteStateNarrow();}}++/**+ * Same end state as `TRUNCATE <tables> CASCADE` (sequences continue): empties+ * 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.+ */+export async function truncateCascade(engine: NarrowResetEngine, tables: string[]): Promise<void> {+ if (tables.length === 0) throw new Error('truncateCascade: table list must be non-empty');+ for (const t of tables) {+ if (!TABLE_NAME_RE.test(t)) {+ throw new Error(`truncateCascade: invalid table name ${JSON.stringify(t)} (must match ${TABLE_NAME_RE})`);+ }+ }+ const quoted = tables.map(t => `"${t}"`).join(', ');+ await engine.executeRaw(`DO $truncate$+ DECLARE+ tables regclass[];+ storage_bytes bigint;+ target regclass;+ original_role text := current_setting('session_replication_role');+ BEGIN+ WITH RECURSIVE closure(oid) AS (+ SELECT unnest(ARRAY[${tables.map(t => `'"${t}"'`).join(', ')}]::regclass[])::oid+ UNION+ 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+ EXECUTE 'TRUNCATE ${quoted} CASCADE';+ ELSE+ PERFORM set_config('session_replication_role', 'replica', true);+ FOREACH target IN ARRAY tables LOOP+ EXECUTE format('DELETE FROM %s', target);+ END LOOP;+ PERFORM set_config('session_replication_role', original_role, true);+ END IF;+ END $truncate$`);+}