Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(schema): alias rows cascade with their source (#5094)
garrytan58c3051b7006
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex 42c4b63f99..77fa762a64 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -192,6 +192,7 @@ src/core/schema-migrations/v123-configurable-fts-language.ts 1 schema Schema inssrc/core/schema-migrations/v142-takes-embedding-dimension-matches-config.ts 1 schema Schema installation and forward-reference DDL; coordinated activation quiesces canonical writers.src/core/schema-migrations/v144-open-loops.ts 1 schema Schema installation and forward-reference DDL; coordinated activation quiesces canonical writers.src/core/schema-migrations/v189-pages-credential-projection-pending.ts 1 schema Projection-only: unseals live pages whose canonical body holds a private-key marker and queues their keyless rebuild; canonical page columns are unchanged.+src/core/schema-migrations/v190-alias-source-cascade.ts 2 schema Orphan alias GC before the alias→sources FK (#5094); grants exactly the orphan rows' sources through gbrain.write_sources for its transaction.src/core/persistence/connector-path.ts 1 coordinator Connector path clear locks the source row, refuses filesystem sources and bound connectors, and runs as a coordinated write on managed brains.src/core/source-delete.ts 1 engine_guard Unmanaged source delete with its incarnation binding; managed brains route removal through source lifecycle first and the writer guard refuses a direct delete.src/core/repair/extractor-facts.ts 1 coordinator `gbrain repair extractor-facts` (#5731) clears expired_at on preview-approved conversation-extractor facts and gives each a fresh row number. On a managed brain the UPDATE runs only inside the managed_maintenance_restore_extractor_facts publication (withCoordinatedWrite, page key locked, each fact reclassified first); an unmanaged brain runs the same function in one transaction under the page lock.diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 3879d88fb8..300159b15b 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -190,6 +190,7 @@ import { v186 } from './v186-decide-proposals.ts';import { v187 } from './v187-fact-relink-attempts.ts';import { v188 } from './v188-facts-ontology-stint-dedup.ts';import { v189 } from './v189-pages-credential-projection-pending.ts';+import { v190 } from './v190-alias-source-cascade.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -378,4 +379,5 @@ export const MIGRATIONS: Migration[] = [v187,v188,v189,+ v190,];diff --git a/src/core/schema-migrations/v190-alias-source-cascade.ts b/src/core/schema-migrations/v190-alias-source-cascade.tsnew file mode 100644index 0000000000..799e9b7541--- /dev/null+++ b/src/core/schema-migrations/v190-alias-source-cascade.ts@@ -0,0 +1,64 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// #5094: page_aliases and slug_aliases carry source_id but had no foreign key,+// so `sources remove` left their rows behind (doctor dangling_aliases). This+// deletes alias rows whose source no longer exists, then adds+// `FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE` to both.+//+// Managed brains: both tables carry managed_writer_guard, which refuses a+// delete unless the row's source is in gbrain.write_sources, so the GC grants+// exactly the orphan rows' source ids for this transaction and restores the+// previous value. The FK is added NOT VALID (no full scan under the ADD lock)+// and validated by the handler in its own statement. entity_identities needs+// nothing: its page_id FK already cascades when a source's pages go.+const ALIAS_TABLES = ['page_aliases', 'slug_aliases'] as const;++export const v190: Migration = {+ version: 190,+ name: 'alias_source_cascade',+ idempotent: true,+ sql: `+ DO $alias_gc$+ DECLARE orphan_sources jsonb; previous text;+ BEGIN+ SELECT COALESCE(jsonb_agg(DISTINCT o.source_id), '[]'::jsonb) INTO orphan_sources FROM (+ SELECT a.source_id FROM page_aliases a WHERE NOT EXISTS (SELECT 1 FROM sources s WHERE s.id = a.source_id)+ UNION+ SELECT a.source_id FROM slug_aliases a WHERE NOT EXISTS (SELECT 1 FROM sources s WHERE s.id = a.source_id)+ ) o;+ IF orphan_sources <> '[]'::jsonb THEN+ previous := current_setting('gbrain.write_sources', true);+ PERFORM set_config('gbrain.write_sources', orphan_sources::text, true);+ DELETE FROM page_aliases a WHERE NOT EXISTS (SELECT 1 FROM sources s WHERE s.id = a.source_id);+ DELETE FROM slug_aliases a WHERE NOT EXISTS (SELECT 1 FROM sources s WHERE s.id = a.source_id);+ PERFORM set_config('gbrain.write_sources', COALESCE(previous, ''), true);+ END IF;+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'page_aliases_source_fk' AND conrelid = 'page_aliases'::regclass) THEN+ ALTER TABLE page_aliases ADD CONSTRAINT page_aliases_source_fk+ FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE NOT VALID;+ END IF;+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'slug_aliases_source_fk' AND conrelid = 'slug_aliases'::regclass) THEN+ ALTER TABLE slug_aliases ADD CONSTRAINT slug_aliases_source_fk+ FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE NOT VALID;+ END IF;+ END $alias_gc$;+ `,+ handler: async (engine) => {+ for (const table of ALIAS_TABLES) {+ const [constraint] = await engine.executeRaw<{ convalidated: boolean }>(+ `SELECT convalidated FROM pg_constraint WHERE conname = $1 AND conrelid = $2::regclass`, [`${table}_source_fk`, table]);+ if (constraint && !constraint.convalidated) {+ await engine.runMigration(190, `ALTER TABLE ${table} VALIDATE CONSTRAINT ${table}_source_fk`);+ }+ }+ },+ verify: async (engine) => {+ const rows = await engine.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM pg_constraint+ WHERE conname IN ('page_aliases_source_fk', 'slug_aliases_source_fk') AND contype = 'f' AND convalidated`);+ return Number(rows[0]?.n ?? 0) === ALIAS_TABLES.length;+ },+};diff --git a/test/alias-source-cascade-5094.test.ts b/test/alias-source-cascade-5094.test.tsnew file mode 100644index 0000000000..efaeedea4b--- /dev/null+++ b/test/alias-source-cascade-5094.test.ts@@ -0,0 +1,88 @@+/**+ * #5094: alias rows follow their source.+ *+ * Protects: removing a source removes its page_aliases and slug_aliases rows+ * (ON DELETE CASCADE), and the upgrade that adds the foreign key first deletes+ * alias rows whose source is already gone, including on a managed brain whose+ * managed_writer_guard refuses ungranted deletes; live aliases survive.+ * Fails when: the alias tables have no FK to sources, or the orphan GC runs+ * without granting the orphan sources (writer_coordinator_required aborts+ * the upgrade).+ * Seams: none; PGLite always, Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { MIGRATIONS, runMigrations } from '../src/core/migrate.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { runManagedSourceLifecycle } from '../src/core/persistence/source-lifecycle.ts';+import { mkdirSync } from 'node:fs';+import { join } from 'node:path';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++const aliasRows = async (engine: BrainEngine) => ({+ page: (await engine.executeRaw<{ source_id: string }>('SELECT source_id FROM page_aliases ORDER BY source_id')).map(r => r.source_id),+ slug: (await engine.executeRaw<{ source_id: string }>('SELECT source_id FROM slug_aliases ORDER BY source_id')).map(r => r.source_id),+});+const fks = (engine: BrainEngine) => engine.executeRaw<{ conname: string; convalidated: boolean; confdeltype: string }>(+ `SELECT conname, convalidated, confdeltype FROM pg_constraint WHERE conname IN ('page_aliases_source_fk', 'slug_aliases_source_fk') ORDER BY conname`);++async function insertAliases(engine: BrainEngine, sourceId: string): Promise<void> {+ await engine.transaction(async tx => {+ await tx.executeRaw("SELECT set_config('gbrain.write_sources', $1, true)", [JSON.stringify([sourceId])]);+ await tx.executeRaw(`INSERT INTO page_aliases (source_id, alias_norm, slug) VALUES ($1, 'context compiler', 'concepts/target')`, [sourceId]);+ await tx.executeRaw(`INSERT INTO slug_aliases (source_id, alias_slug, canonical_slug) VALUES ($1, 'concepts/old-target', 'concepts/target')`, [sourceId]);+ });+}++describe('unmanaged brain', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+ afterAll(async () => { await engine.disconnect(); });++ test('removing a source cascades to its alias rows', async () => {+ expect(await fks(engine)).toEqual([+ { conname: 'page_aliases_source_fk', convalidated: true, confdeltype: 'c' },+ { conname: 'slug_aliases_source_fk', convalidated: true, confdeltype: 'c' },+ ]);+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('alias-probe', 'alias-probe')`);+ await insertAliases(engine, 'alias-probe');+ await insertAliases(engine, 'default');+ await engine.executeRaw(`DELETE FROM sources WHERE id = 'alias-probe'`);+ expect(await aliasRows(engine)).toEqual({ page: ['default'], slug: ['default'] });+ });+});++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ test(`${backend}: a managed brain with orphan alias rows upgrades cleanly`, async () => {+ await managedBrain(async ({ engine }) => {+ for (const table of ['page_aliases', 'slug_aliases']) await engine.executeRaw(`ALTER TABLE ${table} DROP CONSTRAINT ${table}_source_fk`);+ await insertAliases(engine, 'removed-source');+ await insertAliases(engine, 'default');+ const latest = Number(await engine.getConfig('version'));+ const cascade = MIGRATIONS.find(m => m.name === 'alias_source_cascade')!.version;+ await engine.setConfig('version', String(cascade - 1));++ const { applied } = await runMigrations(engine);+ expect(applied).toBe(latest - cascade + 1);+ expect(await aliasRows(engine)).toEqual({ page: ['default'], slug: ['default'] });+ expect((await fks(engine)).map(r => [r.conname, r.convalidated])).toEqual([['page_aliases_source_fk', true], ['slug_aliases_source_fk', true]]);+ expect(await engine.getConfig('version')).toBe(String(latest));+ }, { databaseUrl });+ }, 120_000);+}++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ test(`${backend}: managed source removal takes its alias rows with it`, async () => {+ await managedBrain(async ({ engine, root }) => {+ const probe = join(root, '..', 'alias-probe'); mkdirSync(probe);+ await runManagedSourceLifecycle(engine, { operation: 'add', sourceId: 'alias-probe', path: probe });+ await insertAliases(engine, 'alias-probe');+ await insertAliases(engine, 'default');+ expect(await runManagedSourceLifecycle(engine, { operation: 'remove', sourceId: 'alias-probe', confirmDestructive: true })).toMatchObject({ state: 'committed' });+ expect(await aliasRows(engine)).toEqual({ page: ['default'], slug: ['default'] });+ }, { databaseUrl });+ }, 120_000);+}diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex 60478f21d8..ef3b84e576 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -140,6 +140,7 @@"open_loops.open_loops_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))","page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",+ "page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)","page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))","page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)",@@ -218,6 +219,7 @@"shared_skill_state.shared_skill_state_singleton_check": "c CHECK ((singleton = 1))","slug_aliases.slug_aliases_no_self": "c CHECK ((alias_slug <> canonical_slug))","slug_aliases.slug_aliases_pkey": "p PRIMARY KEY (id)",+ "slug_aliases.slug_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","slug_aliases.slug_aliases_uniq": "u UNIQUE (source_id, alias_slug)","source_ingestion_receipts.source_ingestion_receipts_approved_revision_check": "c CHECK ((approved_revision ~ '^([a-f0-9]{40}|[a-f0-9]{64})$'::text))","source_ingestion_receipts.source_ingestion_receipts_check": "c CHECK (((phase = 'COMPLETE'::text) = (outcome = 'complete'::text)))",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex 9cfdfb9eba..eaaee9f1c9 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -140,6 +140,7 @@"open_loops.open_loops_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))","page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",+ "page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)","page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))","page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)",@@ -218,6 +219,7 @@"shared_skill_state.shared_skill_state_singleton_check": "c CHECK ((singleton = 1))","slug_aliases.slug_aliases_no_self": "c CHECK ((alias_slug <> canonical_slug))","slug_aliases.slug_aliases_pkey": "p PRIMARY KEY (id)",+ "slug_aliases.slug_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","slug_aliases.slug_aliases_uniq": "u UNIQUE (source_id, alias_slug)","source_ingestion_receipts.source_ingestion_receipts_approved_revision_check": "c CHECK ((approved_revision ~ '^([a-f0-9]{40}|[a-f0-9]{64})$'::text))","source_ingestion_receipts.source_ingestion_receipts_check": "c CHECK (((phase = 'COMPLETE'::text) = (outcome = 'complete'::text)))",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex e290681008..be90ea8b67 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -140,6 +140,7 @@"open_loops.open_loops_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))","page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",+ "page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)","page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))","page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)",@@ -218,6 +219,7 @@"shared_skill_state.shared_skill_state_singleton_check": "c CHECK ((singleton = 1))","slug_aliases.slug_aliases_no_self": "c CHECK ((alias_slug <> canonical_slug))","slug_aliases.slug_aliases_pkey": "p PRIMARY KEY (id)",+ "slug_aliases.slug_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","slug_aliases.slug_aliases_uniq": "u UNIQUE (source_id, alias_slug)","source_ingestion_receipts.source_ingestion_receipts_approved_revision_check": "c CHECK ((approved_revision ~ '^([a-f0-9]{40}|[a-f0-9]{64})$'::text))","source_ingestion_receipts.source_ingestion_receipts_check": "c CHECK (((phase = 'COMPLETE'::text) = (outcome = 'complete'::text)))",diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 0f6cbcd7e6..9a3abf2f13 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 184,+ "count": 185,"gaps": [17,18,@@ -8,6 +8,7 @@100],"helpers": {+ "ALIAS_TABLES": "cddd37c636af42d862c08ca7754a57dfe9d12576b769fa8f74a5f02c803f67a0","FACT_RELINK_TABLE_SQL": "1fdde4b99d0077365274096f294be64a992961c7b4544af794224de238b03630","FACT_UNLINKED_INDEX_SQL": "87dcf23c3fa570d93bfb214b6bbb024faa9ff9bff227aa78869a29580be03298","PERSISTENCE_DATABASE_PENDING_INDEX_SQL": "6e0f618be33d037454933ea4dea11438413d45aef35d3bd4f33e89624d6e199e",@@ -27,7 +28,7 @@"slugifyPath": "401dbca23580865d8b168dd8d84db4a6c708c6610d7cb61abafc7d0ee9809063","verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"},- "latest": 189,+ "latest": 190,"records": [{"handler": {@@ -2800,6 +2801,31 @@"transaction": "absent","verify": "absent","version": 189+ },+ {+ "handler": {+ "form": "arrow",+ "helpers": [+ "ALIAS_TABLES"+ ],+ "sha256": "45224f500afd55c6199d9f667887c44bba7a3d463e925334e4486c7d18117a28"+ },+ "idempotent": true,+ "name": "alias_source_cascade",+ "sql": {+ "length": 1559,+ "sha256": "7cb560db434807adbc5c12519cd113046ddfebc8e033b6fc0a13f4be9deb8d56"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": {+ "form": "arrow",+ "helpers": [+ "ALIAS_TABLES"+ ],+ "sha256": "052f104e335dfd940101c094e4d3aff16229d0ef5cf8ae59334eb9341a66d95a"+ },+ "version": 190}],"versions": [@@ -2986,7 +3012,8 @@186,187,188,- 189+ 189,+ 190]},"normalizer": "migrations-record-v1"