Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): B-10 rename, phantom redirect and relink drop a duplicate ontology observation before re-keying it
garrytanb1ef6567735c
diff --git a/src/core/facts/ontology-rekey.ts b/src/core/facts/ontology-rekey.tsnew file mode 100644index 0000000000..ec3ca22718--- /dev/null+++ b/src/core/facts/ontology-rekey.ts@@ -0,0 +1,41 @@+import type { BrainEngine } from '../engine.ts';++/**+ * B-10 (#6948 sweep): `idx_facts_ontology_stint_dedup` (v188) is UNIQUE on (source, entity_slug, dimension, value_hash,+ * source_markdown_slug, valid_from) for every ontology row, expired or not. Before a writer re-keys rows onto another+ * entity or source slug (a rename, the phantom redirect), this drops the observations the move would duplicate, so the+ * UPDATE cannot raise 23505 and roll the whole write back. Of each set of rows that would share a key, the active one+ * survives, then the row already at the target, then the oldest; supersession links to a dropped row are repointed at+ * the survivor. Runs in the caller's transaction, immediately before its UPDATE.+ *+ * `move.where` selects the moving rows of alias `f`; `move.entity` and `move.sms` are the SQL values they take.+ * Both may use `$2` and `$3` (`move.params`); `$1` is the source id. Returns the number of rows dropped.+ */+export async function dropRekeyDuplicates(+ tx: Pick<BrainEngine, 'executeRaw'>,+ sourceId: string,+ move: { where: string; entity: string; sms: string; params: [unknown, unknown] },+): Promise<number> {+ const losers = await tx.executeRaw<{ id: number | string; keep: number | string }>(`WITH m AS (+ SELECT f.id, f.expired_at, ${move.entity} AS e, ${move.sms} AS s, f.dimension, f.value_hash, f.valid_from+ FROM facts f WHERE f.source_id = $1 AND f.dimension IS NOT NULL AND ${move.where}),+ cand AS (+ SELECT m.id, m.expired_at, m.e, m.s, m.dimension, m.value_hash, m.valid_from, 1 AS moving FROM m+ UNION ALL+ SELECT t.id, t.expired_at, t.entity_slug, t.source_markdown_slug, t.dimension, t.value_hash, t.valid_from, 0 FROM facts t+ WHERE t.source_id = $1 AND t.dimension IS NOT NULL AND NOT EXISTS (SELECT 1 FROM m WHERE m.id = t.id)+ AND EXISTS (SELECT 1 FROM m WHERE m.e = t.entity_slug AND m.s = t.source_markdown_slug AND m.dimension = t.dimension+ AND m.value_hash = t.value_hash AND m.valid_from = t.valid_from)),+ ranked AS (+ SELECT id, row_number() OVER w AS rn, first_value(id) OVER w AS keep FROM cand+ WHERE e IS NOT NULL AND s IS NOT NULL AND value_hash IS NOT NULL AND valid_from IS NOT NULL+ WINDOW w AS (PARTITION BY e, s, dimension, value_hash, valid_from ORDER BY (expired_at IS NULL) DESC, moving, id))+ SELECT id, keep FROM ranked WHERE rn > 1`, [sourceId, ...move.params]);+ if (!losers.length) return 0;+ const ids = losers.map(l => Number(l.id));+ const keeps = losers.map(l => Number(l.keep));+ await tx.executeRaw(`UPDATE facts f SET superseded_by = CASE WHEN f.id = x.keep THEN NULL ELSE x.keep END+ FROM unnest($1::bigint[], $2::bigint[]) AS x(id, keep) WHERE f.superseded_by = x.id`, [ids, keeps]);+ await tx.executeRaw('DELETE FROM facts WHERE id = ANY($1::bigint[])', [ids]);+ return ids.length;+}diff --git a/src/core/facts/relink-publish.ts b/src/core/facts/relink-publish.tsindex 4041845481..04a5e96ff8 100644--- a/src/core/facts/relink-publish.ts+++ b/src/core/facts/relink-publish.ts@@ -128,6 +128,19 @@ async function classify(db: BrainEngine, row: WriteRequest, intent: RelinkIntent: { id: f.id, action: 'skip', reason: 'visibility_conflict' });continue;}+ // B-10: an ontology observation the page already holds at the same key would collide on+ // idx_facts_ontology_stint_dedup once linked; it retires as that row's duplicate instead.+ if (v.dimension != null) {+ const [held] = await db.executeRaw<{ id: number | string }>(+ `SELECT t.id FROM facts m JOIN facts t ON t.source_id = m.source_id AND t.dimension = m.dimension AND t.value_hash = m.value_hash+ AND t.valid_from = m.valid_from AND t.id <> m.id+ WHERE m.source_id=$1 AND m.id=$3 AND t.entity_slug=$2 AND t.source_markdown_slug=$2+ ORDER BY (t.expired_at IS NULL) DESC, t.id LIMIT 1`, [row.source_id, row.slug, f.id]);+ if (held) {+ out.push({ id: f.id, action: 'retire', duplicateOf: Number(held.id) });+ continue;+ }+ }const exact = await decideSingleFact(db, row.source_id,{ entity_slug: row.slug, fact: String(v.fact), kind: v.kind as never, visibility }, null);if (exact.status === 'duplicate' && exact.candidate) {diff --git a/src/core/page-state/rename-alias.ts b/src/core/page-state/rename-alias.tsindex 5be7b68820..9546c2fd24 100644--- a/src/core/page-state/rename-alias.ts+++ b/src/core/page-state/rename-alias.ts@@ -1,6 +1,7 @@import type { BrainEngine } from '../engine.ts';import { isMissingSchemaObject } from '../utils.ts';import { MOVE_WITHDRAWAL_SUBJECT_SQL } from '../facts/withdrawal-schema.ts';+import { dropRekeyDuplicates } from '../facts/ontology-rekey.ts';/*** Record `old -> new` in slug_aliases when a page is renamed, inside the@@ -57,8 +58,10 @@ export async function recordSlugLineAlias(tx: Pick<BrainEngine, 'transaction'>,* its fact withdrawals (a forgotten claim stays forgotten). Runs inside the* caller's rename transaction. The new slug is free (the page UPDATE* succeeded), so fence rows or aliases still keyed to it belong to a purged- * page and yield to the moved ones. A brain whose schema predates the facts or- * alias tables skips them inside a savepoint.+ * page and yield to the moved ones. An ontology observation the new slug+ * already holds is dropped before its key moves (B-10, dropRekeyDuplicates).+ * A brain whose schema predates the facts or alias tables skips them inside a+ * savepoint.*/export async function moveSlugBindings(tx: Pick<BrainEngine, 'transaction' | 'executeRaw'>,@@ -68,20 +71,24 @@ export async function moveSlugBindings(): Promise<void> {if (oldSlug === newSlug) return;await tx.executeRaw(MOVE_WITHDRAWAL_SUBJECT_SQL, [sourceId, oldSlug, newSlug]);- const statements = [- `UPDATE facts SET entity_slug = $3 WHERE source_id = $1 AND entity_slug = $2`,- `DELETE FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug = $3 AND f.row_num IS NOT NULL- AND EXISTS (SELECT 1 FROM facts o WHERE o.source_id = $1 AND o.source_markdown_slug = $2 AND o.row_num = f.row_num)`,- `UPDATE facts SET source_markdown_slug = $3 WHERE source_id = $1 AND source_markdown_slug = $2`,- `DELETE FROM page_aliases a WHERE a.source_id = $1 AND a.slug = $3- AND EXISTS (SELECT 1 FROM page_aliases o WHERE o.source_id = $1 AND o.slug = $2 AND o.alias_norm = a.alias_norm AND o.origin = a.origin)`,- `UPDATE page_aliases SET slug = $3 WHERE source_id = $1 AND slug = $2`,+ type Savepoint = Pick<BrainEngine, 'executeRaw'>;+ const sql = (text: string) => (savepoint: Savepoint) => savepoint.executeRaw(text, [sourceId, oldSlug, newSlug]);+ const statements: Array<(savepoint: Savepoint) => Promise<unknown>> = [+ savepoint => dropRekeyDuplicates(savepoint, sourceId, { where: 'f.entity_slug = $2', entity: '$3::text', sms: 'f.source_markdown_slug', params: [oldSlug, newSlug] }),+ sql(`UPDATE facts SET entity_slug = $3 WHERE source_id = $1 AND entity_slug = $2`),+ sql(`DELETE FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug = $3 AND f.row_num IS NOT NULL+ AND EXISTS (SELECT 1 FROM facts o WHERE o.source_id = $1 AND o.source_markdown_slug = $2 AND o.row_num = f.row_num)`),+ savepoint => dropRekeyDuplicates(savepoint, sourceId, { where: 'f.source_markdown_slug = $2', entity: 'f.entity_slug', sms: '$3::text', params: [oldSlug, newSlug] }),+ sql(`UPDATE facts SET source_markdown_slug = $3 WHERE source_id = $1 AND source_markdown_slug = $2`),+ sql(`DELETE FROM page_aliases a WHERE a.source_id = $1 AND a.slug = $3+ AND EXISTS (SELECT 1 FROM page_aliases o WHERE o.source_id = $1 AND o.slug = $2 AND o.alias_norm = a.alias_norm AND o.origin = a.origin)`),+ sql(`UPDATE page_aliases SET slug = $3 WHERE source_id = $1 AND slug = $2`),];- for (const sql of statements) {+ for (const statement of statements) {try {- await tx.transaction(savepoint => savepoint.executeRaw(sql, [sourceId, oldSlug, newSlug]));+ await tx.transaction(savepoint => statement(savepoint));} catch (error) {- if (!isMissingSchemaObject(error, 'table', ['facts', 'page_aliases'])) throw error;+ if (!isMissingSchemaObject(error, 'table', ['facts', 'page_aliases']) && !isMissingSchemaObject(error, 'column', ['dimension', 'value_hash'])) throw error;}}}diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex edcbd239b4..afb7396c2b 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -12,6 +12,7 @@ import { readPageSnapshot as readCanonicalPageSnapshot } from './page-state/snapimport { readPageSnapshotsBatch } from './page-snapshot-batch.ts';import { createPageVersion } from './page-state/versions.ts';import { moveSlugBindings, recordRenameAlias } from './page-state/rename-alias.ts';+import { dropRekeyDuplicates } from './facts/ontology-rekey.ts';import { composablePgliteTransaction, transactionMemo } from './page-state/transactions.ts';import { configurePgliteCodecs, PgliteStatementCache } from './pglite-statements.ts';import { snapshotSchemaInputs } from './snapshot-schema-inputs.ts';@@ -1327,6 +1328,9 @@ export class PGLiteEngine implements BrainEngine {// stays NULL, expired rows count — see the Postgres twin). Active rows// only (expired_at IS NULL) so we don't disturb the supersession audit// trail.+ // B-10: an observation the canonical page already holds would collide on idx_facts_ontology_stint_dedup; drop it first.+ await dropRekeyDuplicates(this, sourceId, { where: 'f.source_markdown_slug = $3 AND f.expired_at IS NULL', entity: '$2::text', sms: '$2::text',+ params: [canonicalSlug, phantomSlug] });const { rows } = await this.db.query(`UPDATE factsSET entity_slug = $1,diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 2e9f84b425..bd93a08b03 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -10,6 +10,7 @@ import { readPageSnapshot as readCanonicalPageSnapshot } from './page-state/snapimport { readPageSnapshotsBatch } from './page-snapshot-batch.ts';import { createPageVersion } from './page-state/versions.ts';import { moveSlugBindings, recordRenameAlias } from './page-state/rename-alias.ts';+import { dropRekeyDuplicates } from './facts/ontology-rekey.ts';import { composablePostgresTransaction, transactionMemo } from './page-state/transactions.ts';import type { PageReadScope } from './types.ts';import type { PageReadPolicy } from './types.ts';@@ -910,6 +911,9 @@ export class PostgresEngine implements BrainEngine {// expiry stay where they are — soft-deleting the phantom page is// sufficient to make them invisible without rewriting their slug// (and rewriting would break the audit trail in listSupersessions).+ // B-10: an observation the canonical page already holds would collide on idx_facts_ontology_stint_dedup; drop it first.+ await dropRekeyDuplicates(this, sourceId, { where: 'f.source_markdown_slug = $3 AND f.expired_at IS NULL', entity: '$2::text', sms: '$2::text',+ params: [canonicalSlug, phantomSlug] });const result = await sql`UPDATE factsSET entity_slug = ${canonicalSlug},diff --git a/test/pathological/b-10-ontology-rekey-collision.test.ts b/test/pathological/b-10-ontology-rekey-collision.test.tsindex 108a286547..0d0ac1f306 100644--- a/test/pathological/b-10-ontology-rekey-collision.test.ts+++ b/test/pathological/b-10-ontology-rekey-collision.test.ts@@ -66,6 +66,21 @@ for (const backend of backends) {expect(after.filter(r => r.entity_slug === 'people/a')).toEqual([]);});+ test('the active observation survives when the target only holds an expired copy, and supersession links follow it', async () => {+ await importFromContent(engine(), 'people/e', md('E Example', 'person'), { noEmbed: true });+ await observe(engine(), 'people/e', 'meetings/m-example');+ await observe(engine(), 'people/e-x', 'meetings/m-example');+ const [moving, target] = (await rows(engine())).map(r => Number(r.id));+ await engine().executeRaw(`UPDATE facts SET expired_at = now() WHERE id = $1`, [target]);+ await observe(engine(), 'people/f', 'meetings/m-example');+ await engine().executeRaw(`UPDATE facts SET superseded_by = $1 WHERE entity_slug = 'people/f'`, [target]);+ await engine().updateSlug('people/e', 'people/e-x');+ const after = await rows(engine());+ expect(after.filter(r => r.entity_slug === 'people/e-x').map(r => [Number(r.id), r.expired_at])).toEqual([[moving, null]]);+ const [{ superseded_by }] = await engine().executeRaw<{ superseded_by: number | string }>(`SELECT superseded_by FROM facts WHERE entity_slug = 'people/f'`);+ expect(Number(superseded_by)).toBe(moving);+ });+test('renaming the source page of two identical observations keeps one', async () => {await importFromContent(engine(), 'meetings/m-old', md('Meeting Example', 'meeting'), { noEmbed: true });await observe(engine(), 'people/b', 'meetings/m-old');