Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(purge): derivation sweep matches the normalized claim, scoped to rewritten pages and unbacked rows
garrytan4ed9df8ff449
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex ecb7f82274..ffe2711b46 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1060,6 +1060,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;// PR 4 4a{ since: 'TBD', text: 'Links, mentions, timeline entries and facts/takes fences of a large (segmented) page are now kept per segment, so a write reads only the segments it changed, and an append reads its new tail instead of the whole page. A rewrite of the whole page does the same work as before. The results are unchanged.' },{ since: 'TBD', text: 'Forgetting, purging or withdrawing a fact on a large page now also deletes the stored link, mention, timeline and fence results of the segment that held it, and of segments an earlier write replaced, in the same transaction. A fact purge also deletes every stored result anywhere in the source that still holds the claim (including a page since stored inline) and counts them as `page_segment_derivations`; stored fence results keep a digest of the fence, never its text. A derivation that read a page before a purge, forget or edit no longer writes its results after it.' },+ { since: 'TBD', text: 'A fact purge now finds stored link, mention, timeline and fence results by the claim\'s normalized form, as its fact fingerprint does, so a result that states the claim in other letter case, spacing or punctuation, or in a script whose lowercase JavaScript and the database spell differently (Greek, Turkish), is deleted and the receipt sees it. The claim must fill whole words of one stored value. Only results of the pages the purge rewrote, and results no live segment backs any more, are searched and deleted; a result of a live segment of another page holds what that page\'s prose still says, and the receipt lists it under `page_segment_derivations` as `out_of_scope` with that prose.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.tsindex 6e9cd17b5f..ef07887774 100644--- a/src/core/facts/purge-verify.ts+++ b/src/core/facts/purge-verify.ts@@ -27,6 +27,7 @@ import { DELETION_INVENTORY, OUT_OF_REACH_RESIDUALS, type InventoryEntry } fromimport type { PurgePlan, PurgeTarget } from './purge.ts';import { gitChildEnv } from '../git-env.ts';import { segmentedBodyContains } from '../page-body/segment-rewrite.ts';+import { derivationHoldsClaimSql, derivationSweepScopeSql } from '../page-body/segment-derive.ts';import { stagingNeedsTextSql } from '../page-body/schema.ts';import { claimForms, quotes, type LedgerPurgeReport } from '../belief/purge.ts';import { CARRYING_FIELDS } from '../belief/keys.ts';@@ -121,6 +122,26 @@ async function segmentTextReport(engine: BrainEngine, sourceId: string, needles:: { store: 'page_segment_texts', status: removed ? 'deleted' : 'not_present', removed };}+/**+ * Derivation rows holding the claim, matched and scoped as the purge sweeps them (segment-derive.ts+ * derivationHoldsClaimSql, derivationSweepScopeSql): a row the sweep covers is a residual (`incomplete`); a row of a+ * live segment of a page the purge did not rewrite is that page's prose, reported with it.+ */+async function derivationTextReport(engine: BrainEngine, sourceId: string, pageIds: readonly number[], claims: readonly string[], removed: number,+ deadline: number): Promise<StoreReport> {+ const carrying = `SELECT 1 FROM page_segment_derivations d JOIN pages p ON p.id=d.page_id WHERE p.source_id=$1 AND ${derivationHoldsClaimSql('d', '$2')}`;+ const params = [sourceId, claims.filter(Boolean), [...pageIds]];+ const swept = await boundedCount(engine, `${carrying} AND ${derivationSweepScopeSql('d', 'p', '$3')}`, params, deadline);+ if ('unverified' in swept) return { store: 'page_segment_derivations', status: 'unverified', reason: swept.unverified, removed };+ if (swept.count) return { store: 'page_segment_derivations', status: 'incomplete', remaining: swept.count, removed };+ const kept = await boundedCount(engine, `${carrying} AND NOT ${derivationSweepScopeSql('d', 'p', '$3')}`, params, deadline);+ if ('unverified' in kept) return { store: 'page_segment_derivations', status: 'unverified', reason: kept.unverified, removed };+ return kept.count+ ? { store: 'page_segment_derivations', status: 'out_of_scope', reason: 'source_prose', remaining: kept.count, removed,+ detail: 'Derivations of live segments of pages the purge did not rewrite hold the text their prose still states; they are listed under pages.' }+ : { store: 'page_segment_derivations', status: removed ? 'deleted' : 'not_present', removed };+}+type ProbeResult = { count: number } | { unverified: string };/** #6911: a rebuildable cache table that does not exist holds nothing to verify. */@@ -446,6 +467,7 @@ export async function verifyFactPurge(engine: BrainEngine, input: { target: Purgdetail: `${legacy.n} model-derived page(s) in this source predate derivation edges, so purge cannot tell whether they restate the claim in other words.` });if (!dryRun) {stores.push(await segmentTextReport(engine, src, [...new Set([claim, escapeFenceCell(claim)])], removed.page_segment_texts ?? 0, deadline));+ stores.push(await derivationTextReport(engine, src, plan.pages.map(page => page.page_id), [claim, escapeFenceCell(claim)], removed.page_segment_derivations ?? 0, deadline));stores.push(...await ledgerReports(engine, src, [claim], input.ledger, deadline));stores.push(await effectPayloadReport(engine, src, [claim], deadline, removed.persistence_effects ?? 0));}diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.tsindex 1a4796f6f9..21fdabf64b 100644--- a/src/core/facts/purge.ts+++ b/src/core/facts/purge.ts@@ -523,8 +523,8 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Recconst facts = (await tx.executeRaw('DELETE FROM facts WHERE id=ANY($1::bigint[]) AND source_id=$2 RETURNING id', [ids, p.sourceId])).length;const bodies = await rewritePageBodies(tx, p.sourceId, plan.pages);({ rewritten, unsealed } = bodies);- const derivationRows = bodies.derivations + await sweepDerivationText(tx, p.sourceId, [current.fact, escapeFenceCell(current.fact)]);const pageIds = plan.pages.map(page => page.page_id);+ const derivationRows = bodies.derivations + await sweepDerivationText(tx, p.sourceId, pageIds, [current.fact, escapeFenceCell(current.fact)]);// A segmented page's flip already retired only the chunks of the occurrences it rewrote.const inline = pageIds.filter(id => !bodies.segmented.includes(id));const chunks = inline.length ? (await tx.executeRaw('DELETE FROM content_chunks WHERE page_id=ANY($1::integer[]) RETURNING 1', [inline])).length : 0;diff --git a/src/core/page-body/derivations.ts b/src/core/page-body/derivations.tsindex f098366ce8..31e62a3e4e 100644--- a/src/core/page-body/derivations.ts+++ b/src/core/page-body/derivations.ts@@ -25,8 +25,10 @@ export const SETTLED_DERIVATION_STATES: readonly SegmentDerivationState[] = ['do/*** What a pipeline records for one occurrence. `output` stays bounded per segment (candidates, keys, digests, anchors).* It is not text-free: a links row keeps the excerpts and dated lines its candidates carry (what links.context and the- * temporal pass store), so the store is swept, not probed: a fact purge deletes every row whose output or receipt holds- * the claim (segment-derive.ts sweepDerivationText), fence rewrites delete the rows of the runs they touched and of+ * temporal pass store), so the store is swept, not probed: a fact purge deletes every row of the pages it rewrote, or that+ * no live segment backs, whose output or receipt holds the claim in its normalized form (segment-derive.ts+ * sweepDerivationText; a live segment's row on another page holds what that page's prose still says, and the receipt+ * reports it with that prose), fence rewrites delete the rows of the runs they touched and of* occurrences no longer live, and demotion to inline deletes the page's rows. Prefer digests and offsets where the* pipeline can read the segment again (a fences row keeps fence digests, never fence text).*/diff --git a/src/core/page-body/segment-derive.ts b/src/core/page-body/segment-derive.tsindex 4d57f73657..26f648fc97 100644--- a/src/core/page-body/segment-derive.ts+++ b/src/core/page-body/segment-derive.ts@@ -345,17 +345,54 @@ export async function deleteRewrittenDerivations(engine: BrainEngine, pageId: nu}/**- * Delete every derivation row of a source's pages (live, soft-deleted or demoted; any occurrence, any kind) whose- * output or receipt holds one of `needles`, matched as the purge receipt probes the store: case-insensitive, raw and- * JSON-escaped. A fact purge runs it in its transaction after the body rewrites, so a row a rewrite could not place- * (an occurrence retired before it, a page demoted to inline) goes too. Returns the rows deleted.+ * SQL predicate: derivation row `d` holds one of the claims in the text[] parameter `needles`. Both sides go through+ * gbrain_fact_normalize, the fact fingerprint's normalization (lowercase, punctuation folded, whitespace collapsed), in+ * the database, so a row matches whatever case, spacing or locale lowercasing the claim was written in. The claim must+ * fill whole words of one string value or object key of the row's output or receipt (link excerpts carry it inside a+ * longer window, so equality would miss them): "plays oboe" never matches "plays oboes", nor a claim straddling two fields.*/-export async function sweepDerivationText(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, needles: readonly string[]): Promise<number> {- const list = [...new Set(needles.filter(Boolean).flatMap(n => [n.toLowerCase(), JSON.stringify(n).slice(1, -1).toLowerCase()]))];+export function derivationHoldsClaimSql(d: string, needles: string): string {+ return `EXISTS (SELECT 1 FROM (VALUES (${d}.output), (${d}.receipt)) doc(j),+ LATERAL (SELECT jsonb_path_query(doc.j, 'strict $.** ? (@.type() == "string")') #>> '{}' AS t+ UNION ALL SELECT jsonb_path_query(doc.j, 'strict $.** ? (@.type() == "object").keyvalue().key') #>> '{}') s,+ (SELECT DISTINCT ' ' || gbrain_fact_normalize(n) || ' ' AS n FROM unnest(${needles}::text[]) n) k+ WHERE k.n <> ' ' AND strpos(' ' || gbrain_fact_normalize(s.t) || ' ', k.n) > 0)`;+}++/**+ * SQL predicate: derivation row `d` of page `p` is one a fact purge sweeps: a row of a page the purge rewrote (the+ * int[] parameter `pageIds`), or a row no live segment backs (its occurrence retired, its page demoted to inline or+ * soft-deleted). Any other row was derived from a live segment of a page the purge left alone, so it holds only what+ * that page's prose still says, and the next derivation would write it back.+ */+export function derivationSweepScopeSql(d: string, p: string, pageIds: string): string {+ return `(${d}.page_id = ANY(${pageIds}::int[]) OR ${p}.deleted_at IS NOT NULL OR NOT EXISTS (SELECT 1 FROM page_body_manifest m+ WHERE m.page_id = ${d}.page_id AND m.occurrence_id = ${d}.occurrence_id AND m.gen_to IS NULL AND m.staging_id IS NULL AND m.sha256 = ${d}.segment_sha256))`;+}++/** @internal Per page, for the work-volume tests (counts, not time): derivation rows each sweep read and deleted. */+export const derivationSweepWork: Array<{ pageId: number; scanned: number; deleted: number }> = [];++/**+ * Delete the derivation rows of a source that hold one of `claims` (derivationHoldsClaimSql) among the rows a fact purge+ * sweeps (derivationSweepScopeSql over `pageIds`, the pages it rewrote), in the purge's transaction after the body+ * rewrites, so a row a rewrite could not place goes too. Only rows in scope are normalized and matched; the purge+ * receipt probes the store with the same two predicates. Returns the rows deleted.+ */+export async function sweepDerivationText(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, pageIds: readonly number[],+ claims: readonly string[]): Promise<number> {+ const list = [...new Set(claims.filter(Boolean))];if (!list.length) return 0;- return (await engine.executeRaw(`DELETE FROM page_segment_derivations d USING pages p WHERE p.id=d.page_id AND p.source_id=$1- AND EXISTS (SELECT 1 FROM unnest($2::text[]) n WHERE strpos(lower(COALESCE(d.output::text,'')),n)>0 OR strpos(lower(COALESCE(d.receipt::text,'')),n)>0)- RETURNING 1`, [sourceId, list])).length;+ const rows = await engine.executeRaw<{ page_id: number; scanned: number; deleted: number }>(`WITH scope AS MATERIALIZED (+ SELECT d.page_id, d.pipeline, d.occurrence_id, ${derivationHoldsClaimSql('d', '$3')} AS hit+ FROM page_segment_derivations d JOIN pages p ON p.id = d.page_id WHERE p.source_id = $1 AND ${derivationSweepScopeSql('d', 'p', '$2')}+ ), gone AS (+ DELETE FROM page_segment_derivations x USING scope s WHERE s.hit AND x.page_id = s.page_id AND x.pipeline = s.pipeline+ AND x.occurrence_id = s.occurrence_id RETURNING x.page_id+ ) SELECT s.page_id, count(*)::int AS scanned, (SELECT count(*)::int FROM gone g WHERE g.page_id = s.page_id) AS deleted+ FROM scope s GROUP BY s.page_id ORDER BY s.page_id`, [sourceId, [...pageIds], list]);+ for (const row of rows) derivationSweepWork.push({ pageId: Number(row.page_id), scanned: Number(row.scanned), deleted: Number(row.deleted) });+ return rows.reduce((n, row) => n + Number(row.deleted), 0);}/** SHA-256 hex (its first 32 digits) of a key, recorded in an output instead of the key's text. */diff --git a/test/helpers/derivation-purge-cases.ts b/test/helpers/derivation-purge-cases.tsindex dbd36ec7d6..f9a32d5d03 100644--- a/test/helpers/derivation-purge-cases.ts+++ b/test/helpers/derivation-purge-cases.ts@@ -11,7 +11,7 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';import type { BrainEngine } from '../../src/core/engine.ts';import { runExtractFacts } from '../../src/core/cycle/extract-facts.ts';-import { __setBeforeDerivationWriteForTests, segmentDeriveWork } from '../../src/core/page-body/segment-derive.ts';+import { __setBeforeDerivationWriteForTests, derivationSweepWork, segmentDeriveWork } from '../../src/core/page-body/segment-derive.ts';import { incrementalFactsFenceView, segmentedFactsFenceView } from '../../src/core/page-body/segment-facts.ts';import { forgetFactInFence } from '../../src/core/facts/forget.ts';import { deriveAll, KINDS, liveOccurrences, resetDeriveWork, storedPage } from './derivation-equivalence-cases.ts';@@ -39,6 +39,26 @@ async function holders(engine: BrainEngine, pageId: number, claim: string): Prom[pageId, claim.toLowerCase()])).map(row => ({ pipeline: row.pipeline, occurrence_id: Number(row.occurrence_id) }));}+/** A segmented page whose last truth paragraph states `text` next to a link, so its links rows carry it in an excerpt. */+function prosePage(text: string, seed: number): string {+ return ['---\ntype: note\ntitle: Prose Example\n---\n\n', prose(1_300_000, seed), `\n\nClosing: met [[people/alice-example]]. ${text}.\n`].join('');+}++/** Derivation rows of a page whose output or receipt holds `text` byte for byte (no case folding on either side). */+async function exactHolders(engine: BrainEngine, pageId: number, text: string): Promise<Array<{ pipeline: string; occurrence_id: number }>> {+ return (await engine.executeRaw<{ pipeline: string; occurrence_id: string }>(`SELECT pipeline, occurrence_id::text AS occurrence_id FROM page_segment_derivations+ WHERE page_id=$1 AND (strpos(COALESCE(output::text,''),$2)>0 OR strpos(COALESCE(receipt::text,''),$2)>0) ORDER BY pipeline, occurrence_id`,+ [pageId, text])).map(row => ({ pipeline: row.pipeline, occurrence_id: Number(row.occurrence_id) }));+}++/** Per page of the source: derivation rows no live segment backs (occurrence retired, page inline or soft-deleted). */+async function unbackedRows(engine: BrainEngine): Promise<Map<number, number>> {+ const rows = await engine.executeRaw<{ page_id: number; n: number }>(`SELECT d.page_id, count(*)::int AS n FROM page_segment_derivations d+ JOIN pages p ON p.id=d.page_id WHERE p.source_id=$1 AND (p.deleted_at IS NOT NULL OR NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.page_id=d.page_id+ AND m.occurrence_id=d.occurrence_id AND m.gen_to IS NULL AND m.staging_id IS NULL AND m.sha256=d.segment_sha256)) GROUP BY d.page_id`, [SOURCE]);+ return new Map(rows.map(row => [Number(row.page_id), Number(row.n)]));+}+export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): void {describe(`purge leaves no derivation row holding the claim (${kind})`, () => {let brain: AppendBrain;@@ -152,5 +172,72 @@ export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): voidcomplete(await purge(id));expect(await holders(brain.engine, page.id, claim)).toEqual([]);}, 600_000);++ /**+ * A page that is not purged retires the occurrence whose links rows carry `planted` (an append replaces its last+ * segment), so only the purge's derivation sweep can reach those rows.+ */+ const retiredHolder = async (slug: string, planted: string, seedNo: number) => {+ await brain.seed(slug, prosePage(planted, seedNo));+ const page = await storedPage(brain.engine, slug);+ await deriveAll(brain.engine, page);+ const res = await brain.call('append_page', { slug, text: 'Appended note: nothing more.\n', region: 'truth', request_id: randomUUID() });+ expect(res).toMatchObject({ isError: false });+ const live = await liveOccurrences(brain.engine, page.id);+ const held = await exactHolders(brain.engine, page.id, planted);+ expect(held.length).toBeGreaterThan(0);+ expect(held.filter(row => live.has(row.occurrence_id))).toEqual([]);+ return page;+ };++ const derivationStore = (receipt: Record<string, any>) =>+ (receipt.stores as Array<{ store: string; status: string; remaining?: number }>).find(s => s.store === 'page_segment_derivations');++ for (const variant of [+ { name: 'Greek capitals (final sigma)', claim: 'ΤΟ ΚΛΕΙΔΙ ΤΗΣ ΑΠΟΘΗΚΗΣ ΕΙΝΑΙ 2207', planted: 'ΤΟ ΚΛΕΙΔΙ ΤΗΣ ΑΠΟΘΗΚΗΣ ΕΙΝΑΙ 2207', n: 1 },+ { name: 'Turkish dotted capital I', claim: 'İSTANBUL DEPOSU KODU 6114', planted: 'İSTANBUL DEPOSU KODU 6114', n: 2 },+ { name: 'other case and spacing', claim: 'Purge Example lift code is 6610', planted: 'purge example LIFT code is 6610', n: 3 },+ ]) {+ test(`a purge deletes a retired row stating the claim in its normalized form: ${variant.name}`, async () => {+ const holder = await retiredHolder(`notes/normalized-holder-${variant.n}`, variant.planted, 50 + variant.n);+ const id = await seed(`notes/normalized-purge-${variant.n}`, variant.claim);+ const receipt = await purge(id);+ expect({ rows: await exactHolders(brain.engine, holder.id, variant.planted), receipt: derivationStore(receipt)?.status })+ .toEqual({ rows: [], receipt: 'deleted' });+ complete(receipt);+ }, 600_000);+ }++ test('a purge sweeps only rows of the pages it rewrote and rows no live segment backs, matching whole words', async () => {+ const claim = 'Plays oboe';+ const unrelated = await retiredHolder('notes/sweep-unrelated', 'Alice Example plays oboes on weekends', 61);+ const retired = await retiredHolder('notes/sweep-retired', 'Alice Example PLAYS OBOE', 62);+ await brain.seed('notes/sweep-live', prosePage(claim, 63));+ const live = await storedPage(brain.engine, 'notes/sweep-live');+ await deriveAll(brain.engine, live);+ const liveHeld = await exactHolders(brain.engine, live.id, claim);+ expect(liveHeld.length).toBeGreaterThan(0);+ const id = await seed('notes/sweep-purge', claim);+ const target = await storedPage(brain.engine, 'notes/sweep-purge');+ await deriveAll(brain.engine, target);+ const unbacked = await unbackedRows(brain.engine);+ const unrelatedRows = (await brain.engine.readSegmentDerivations(unrelated.id)).length;+ const retiredHeld = (await exactHolders(brain.engine, retired.id, 'Alice Example PLAYS OBOE')).length;+ expect(unbacked.has(live.id)).toBe(false);+ derivationSweepWork.length = 0;+ const receipt = await purge(id);+ expect(derivationSweepWork.some(w => w.pageId === target.id && w.scanned > 0)).toBe(true);+ const expected = [...unbacked].filter(([pageId]) => pageId !== target.id).sort((a, b) => a[0] - b[0])+ .map(([pageId, scanned]) => ({ pageId, scanned, deleted: pageId === retired.id ? retiredHeld : 0 }));+ expect(derivationSweepWork.filter(w => w.pageId !== target.id)).toEqual(expected);+ expect(derivationSweepWork.find(w => w.pageId === live.id)).toBeUndefined();+ expect(expected.find(w => w.pageId === unrelated.id)?.deleted).toBe(0);+ expect(unbacked.get(unrelated.id)).toBeLessThan(unrelatedRows);+ expect((await brain.engine.readSegmentDerivations(unrelated.id)).length).toBe(unrelatedRows);+ expect(await exactHolders(brain.engine, retired.id, 'Alice Example PLAYS OBOE')).toEqual([]);+ expect(await exactHolders(brain.engine, live.id, claim)).toEqual(liveHeld);+ expect(derivationStore(receipt)).toMatchObject({ status: 'out_of_scope', reason: 'source_prose', remaining: liveHeld.length });+ expect((receipt.stores as Array<{ status: string }>).filter(s => s.status === 'incomplete')).toEqual([]);+ }, 600_000);});}