Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
lane 4a round 6: sweep a fact purge's derivation rows after it commits, in short resumable batches
garrytane7980aa215dd
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 440198cea7..8695c0ceb0 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1075,6 +1075,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ 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.' },{ since: 'TBD', text: 'A fact purge now also finds stored link, mention, timeline and fence results that spell a Greek claim with a final sigma (ς) where the claim has σ or Σ, or the other way round, or a Turkish dotted capital İ the way JavaScript lowercases it (i̇). It normalizes only the results that contain the claim\'s words in order, so the search costs about what the plain substring search did. When that search still runs past the purge transaction\'s statement budget, the purge fails with `purge_lookup_timeout` and nothing is purged, instead of being retried until the transaction gives up.' },{ since: 'TBD', text: 'A fact purge now searches stored link, mention, timeline and fence results in batches of 500 rows per statement, and its receipt checks them the same way, so a claim whose words appear in tens of thousands of stored results can be purged instead of always failing with `purge_lookup_timeout`. The purge still commits all at once. It fails with `purge_lookup_timeout`, purging nothing, only when the search runs past two minutes.' },+ { since: 'TBD', text: 'A fact purge no longer searches stored link, mention, timeline and fence results inside its transaction, so other writes to the source are no longer blocked while it walks them. The purge records the claim and commits; it then deletes the results holding the claim in batches of 500 stored results, each in a short transaction of its own, for up to two minutes. From the commit on, a result holding the claim cannot be written back into what the purge covers. When the walk does not finish in that time, the purge still commits, but its receipt reports `page_segment_derivations` as `incomplete`, `completion: incomplete` (exit 75) and `derivation_sweep: pending`. Running the same purge again with its request id, or purging another fact in the source, continues from where the walk stopped. The walk no longer fails a purge with `purge_lookup_timeout` (this replaces the two-minute failure above).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.tsindex c5efd13a67..7137c1a930 100644--- a/src/core/deletion-inventory.ts+++ b/src/core/deletion-inventory.ts@@ -120,6 +120,7 @@ const ROWS: readonly Row[] = [['page_projection_jobs', 'out_of_scope', 'no_memory_text', 'slug reason'],['page_purges', 'out_of_scope', 'text_free_ledger', 'source_id content_hash slug'],['page_segment_derivations', 'swept', 'segment_derivations', 'pipeline segment_sha256 context_hash state output receipt', 'output receipt'],+ ['page_segment_derivation_purges', 'swept', 'segment_derivations', 'source_id needles patterns page_ids cursor_pipeline'],['page_segment_texts', 'swept', 'segment_texts', 'source_id sha256 body', 'body'],['page_view_digests', 'out_of_scope', 'no_memory_text', 'revision view audience sha256'],['page_versions', 'swept', 'page_versions', 'compiled_truth frontmatter timeline title type tags source_path write_principal_kind write_principal_id archived_principal_kind archived_principal_id trust_tier write_origin body_storage content_hash'],diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.tsindex f3ae62c225..36d9baa063 100644--- a/src/core/facts/purge-verify.ts+++ b/src/core/facts/purge-verify.ts@@ -27,9 +27,9 @@ 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 { derivationAfterSql, derivationBatchRows, derivationClaimCandidateSql, derivationHoldsClaimSql, derivationNeedles, derivationSweepScopeSql,- recordDerivationStatement, type DerivationKey } from '../page-body/segment-derive.ts';-import { stagingNeedsTextSql } from '../page-body/schema.ts';+import { derivationAfterSql, derivationBatchRows, derivationNeedles, derivationPurgePending, recordDerivationStatement,+ type DerivationKey } from '../page-body/segment-derive.ts';+import { derivationClaimCandidateSql, derivationHoldsClaimSql, derivationSweepScopeSql, stagingNeedsTextSql } from '../page-body/schema.ts';import { claimForms, quotes, type LedgerPurgeReport } from '../belief/purge.ts';import { CARRYING_FIELDS } from '../belief/keys.ts';import { relationExists } from '../persistence/rebuildable-cache.ts';@@ -151,7 +151,7 @@ async function derivationTextReport(engine: BrainEngine, sourceId: string, pageIFROM batch b JOIN page_segment_derivations d ON d.page_id=b.page_id AND d.pipeline=b.pipeline AND d.occurrence_id=b.occurrence_idCROSS JOIN LATERAL (SELECT ${derivationClaimCandidateSql('d', '$4')} AS candidate) c), last AS (- SELECT page_id, pipeline, occurrence_id::text AS occurrence_id FROM batch ORDER BY page_id DESC, pipeline DESC, occurrence_id DESC LIMIT 1+ SELECT b.page_id, b.pipeline, b.occurrence_id::text AS occurrence_id FROM batch b ORDER BY b.page_id DESC, b.pipeline DESC, b.occurrence_id DESC LIMIT 1) SELECT (SELECT count(*)::int FROM batch) AS scanned, count(*) FILTER (WHERE candidate)::int AS normalized,count(*) FILTER (WHERE hit AND swept)::int AS swept, count(*) FILTER (WHERE hit AND NOT swept)::int AS kept,(SELECT page_id FROM last) AS last_page, (SELECT pipeline FROM last) AS last_pipeline, (SELECT occurrence_id FROM last) AS last_occurrence@@ -681,7 +681,8 @@ export async function verifyPagePurge(engine: BrainEngine, input: { sourceId: st* still holds the claim. Out-of-reach residuals never make it incomplete.*/export async function purgeCompletion(engine: BrainEngine, row: Pick<WriteRequest, 'id' | 'state' | 'source_id' | 'outcome'>, receipt?: Pick<PurgeReceipt, 'stores'>):- Promise<{ completion: PurgeCompletion; effects: Array<{ kind: string; state: string; error_code: string | null }>; exit_code: number; fingerprint_probe?: Record<string, number> }> {+ Promise<{ completion: PurgeCompletion; effects: Array<{ kind: string; state: string; error_code: string | null }>; exit_code: number; fingerprint_probe?: Record<string, number>;+ derivation_sweep?: 'pending' }> {if (row.state !== 'committed') return { completion: 'incomplete', effects: [], exit_code: 75 };const effects = await engine.executeRaw<{ kind: string; state: string; error_code: string | null; parked: boolean }>(`SELECT kind,state,error_code,jsonb_array_length(COALESCE(data->'parked','[]'::jsonb))>0 AS parked FROM persistence_effects WHERE request_id=$1::uuid ORDER BY kind`, [row.id]);@@ -695,9 +696,11 @@ export async function purgeCompletion(engine: BrainEngine, row: Pick<WriteRequesfingerprint = { facts: Number(probe?.facts ?? 0), takes: Number(probe?.takes ?? 0) };}const failed = effects.some(e => e.state === 'failed' || e.parked);- const sweptResidual = receipt?.stores.some(s => s.status === 'incomplete') || (fingerprint && (fingerprint.facts || fingerprint.takes));+ const sweeping = await derivationPurgePending(engine, row.id);+ const sweptResidual = sweeping || receipt?.stores.some(s => s.status === 'incomplete') || (fingerprint && (fingerprint.facts || fingerprint.takes));const pending = effects.some(e => e.state !== 'committed');const completion: PurgeCompletion = failed || sweptResidual ? 'incomplete' : pending ? 'committed' : 'complete';return { completion, effects: effects.map(({ kind, state, error_code }) => ({ kind, state, error_code })),- exit_code: completion === 'complete' ? 0 : completion === 'committed' ? 10 : 75, ...(fingerprint ? { fingerprint_probe: fingerprint } : {}) };+ exit_code: completion === 'complete' ? 0 : completion === 'committed' ? 10 : 75, ...(fingerprint ? { fingerprint_probe: fingerprint } : {}),+ ...(sweeping ? { derivation_sweep: 'pending' as const } : {}) };}diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.tsindex 91a2574345..4d42a9d258 100644--- a/src/core/facts/purge.ts+++ b/src/core/facts/purge.ts@@ -27,7 +27,7 @@ import { readFix } from '../ops/op-fix.ts';import { faultPoint } from '../persistence/fault-points.ts';import { contentHash, rowToPage } from '../utils.ts';import { rewriteLiveSegmentedFences, rewriteSegmentedGeneration, segmentedBodyContains } from '../page-body/segment-rewrite.ts';-import { DerivationSweepBudgetExceeded, sweepDerivationText } from '../page-body/segment-derive.ts';+import { continueDerivationPurges, recordDerivationPurge } from '../page-body/segment-derive.ts';import { discoverWithdrawalTargets, withdrawalDiscoveryFailure } from './withdrawal-discovery.ts';import { dropPurgedFenceRows } from './purge-overlay.ts';import { derivedRowsFrom, hideDerivedRows, type DerivationRef } from './derivation-inputs.ts';@@ -225,16 +225,12 @@ async function ledgerLookup<T>(fn: () => Promise<T>, factId: number, sourceId: s}}-/**- * A statement timeout of the derivation sweep, or the sweep passing its overall budget (DerivationSweepBudgetExceeded),- * refuses the whole purge with the typed code, as the ledger redaction does.- */-async function derivationSweep(fn: () => Promise<number>, factId: number, sourceId: string): Promise<number> {+/** A statement timeout recording the derivation sweep refuses the whole purge with the typed code, as the ledger redaction does. */+async function derivationSweep(fn: () => Promise<void>, factId: number, sourceId: string): Promise<void> {try { return await fn(); } catch (error) {- const budget = error instanceof DerivationSweepBudgetExceeded;- if (!budget && (error as { code?: unknown } | null)?.code !== '57014') throw error;+ if ((error as { code?: unknown } | null)?.code !== '57014') throw error;throw opError('purge_lookup_timeout', 'This purge could not finish; nothing was purged. Do not assume the requested content was erased.',- `The sweep of stored derivation results holding fact ${factId} in source ${sourceId} exceeded ${budget ? `its overall budget (${(error as Error).message})` : "the purge transaction's statement budget"}, so the transaction rolled back and nothing was removed, tombstoned or redacted. `+ `Recording the sweep of stored derivation results holding fact ${factId} in source ${sourceId} exceeded the purge transaction's statement budget, so the transaction rolled back and nothing was removed, tombstoned or redacted. `+ 'Run the purge again with a new request id; if it times out again, report it with the output of gbrain doctor --json.',{ fix: readFix('Reports the brain\'s health, read-only.', { argv: ['gbrain', 'doctor', '--json'] }) });}@@ -447,6 +443,7 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Recconst prior = await getWriteRequest(ctx.engine, principal, p.requestId);if (prior) {assertReplayIntent(prior, intentDigest({ operation: PURGE_OPERATION, sourceId: p.sourceId, slug: prior.slug, callerIntent }));+ if (prior.state === 'committed') await continueDerivationPurges(ctx.engine, prior.source_id);return { ...(prior.outcome ?? {}), request_id: prior.request_id, state: prior.state, replayed: true, ...await purgeCompletion(ctx.engine, prior) };}}@@ -539,8 +536,9 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Recconst bodies = await rewritePageBodies(tx, p.sourceId, plan.pages);({ rewritten, unsealed } = bodies);const pageIds = plan.pages.map(page => page.page_id);- const derivationRows = bodies.derivations + await derivationSweep(() => faultPoint('purge:derivation_sweep', { sourceId: p.sourceId, operation: PURGE_OPERATION })- .then(() => sweepDerivationText(tx, p.sourceId, pageIds, [current.fact, escapeFenceCell(current.fact)])), current.id, p.sourceId);+ // The rows a rewrite could not place are swept after the commit, in batches of their own (continueDerivationPurges).+ await derivationSweep(() => faultPoint('purge:derivation_sweep', { sourceId: p.sourceId, operation: PURGE_OPERATION })+ .then(() => recordDerivationPurge(tx, admitted.id, p.sourceId, pageIds, [current.fact, escapeFenceCell(current.fact)])), current.id, p.sourceId);// 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;@@ -560,7 +558,7 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Rectargets: pages.map(page => ({ slug: page.slug, page_id: Number(page.id), revision: page.knowledge_revision })) })]);counts = { facts, takes, chunks, page_versions: versions.redacted, pages: rewritten.length, persistence_requests: intents,query_cache: cache, decide_review: review, open_loops: loops, take_proposals: proposals, core_edit_notices: notices,- write_gate_holds: holdIds.length, write_gate_receipts: gateReceipts, page_segment_texts: segments.texts, page_segment_derivations: derivationRows,+ write_gate_holds: holdIds.length, write_gate_receipts: gateReceipts, page_segment_texts: segments.texts, page_segment_derivations: bodies.derivations,page_body_stagings: segments.stagings, page_body_staging_parts: segments.parts, persistence_requests_cancelled: segments.cancelled,derived_hidden: Object.values(derived.hidden).reduce((a, b) => a + b, 0) };derivedHidden = derived;@@ -590,6 +588,7 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Recfor (const slug of unsealed) await buildSegmentedProjection(ctx.engine, { sourceId: p.sourceId, slug }).catch(() => undefined);if (row.state !== 'committed') return { ...(row.outcome ?? {}), request_id: row.request_id, state: row.state, error: row.error_code };appendPurgeCommitted(row.id);+ counts.page_segment_derivations = (counts.page_segment_derivations ?? 0) + await continueDerivationPurges(ctx.engine, p.sourceId);if (beliefReport.appended || ledger?.derived_hidden) await markBeliefCommits(ctx.engine, [row.id]).catch(() => undefined);const receipt: PurgeReceipt = await verifyFactPurge(ctx.engine, { target, plan: committedPlan, dryRun: false, removed: counts, prose,vacuum: params.vacuum === true, ledger });diff --git a/src/core/page-body/derivations.ts b/src/core/page-body/derivations.tsindex 31e62a3e4e..84d29dea0e 100644--- a/src/core/page-body/derivations.ts+++ b/src/core/page-body/derivations.ts@@ -27,7 +27,7 @@ export const SETTLED_DERIVATION_STATES: readonly SegmentDerivationState[] = ['do* 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 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+ * continueDerivationPurges, in batches after the purge commits; 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/schema.ts b/src/core/page-body/schema.tsindex 10b9dd21b0..4139a9c845 100644--- a/src/core/page-body/schema.ts+++ b/src/core/page-body/schema.ts@@ -176,15 +176,72 @@ export const SEGMENT_DERIVATION_KINDS = ['links', 'mentions', 'timeline', 'fenceexport const SEGMENT_DERIVATION_STATES = ['done', 'partial', 'failed', 'skipped'] as const;const sqlList = (values: readonly string[]) => values.map(v => `'${v}'`).join(',');+/**+ * Folds the lowercase forms a database writes depending on context or locale, applied after lowering on both sides:+ * Greek final sigma (lower('ΚΩΣΤΑΣ') is 'κωστασ' while stored text keeps 'κωστας') and the dot JavaScript and ICU keep+ * after a lowered Turkish İ ('i̇'). gbrain_fact_normalize itself stays as it is: fact fingerprints are stored.+ */+export const foldSql = (expr: string) => `replace(translate(${expr}, 'ς', 'σ'), 'i\u0307', 'i')`;++/**+ * SQL predicate, the prefilter: `text`, lowered and folded, matches one of the patterns in the text[] parameter+ * `patterns` (from derivationNeedles): has a claim's words in the claim's order. Normalization only lowers, folds+ * characters to spaces and collapses spaces, keeping order, so the words of a claim a text holds occur in it in that+ * order (in a row's JSON text too: JSON escapes only quotes, backslashes and control characters, which no word holds);+ * a text this rejects never holds the claim.+ */+const hasWordsSql = (text: string, patterns: string) => `${foldSql(`lower(${text})`)} LIKE ANY (${patterns}::text[])`;++/** SQL predicate: derivation row `d`'s output and receipt JSON text passes the prefilter (see hasWordsSql). */+export function derivationClaimCandidateSql(d: string, patterns: string): string {+ return hasWordsSql(`COALESCE(${d}.output::text, '') || ' ' || COALESCE(${d}.receipt::text, '')`, patterns);+}++/**+ * SQL predicate: derivation row `d` holds one of the claims (the text[] parameters `needles` and `patterns`, from+ * derivationNeedles). The row goes through the needle's own normalization (gbrain_fact_normalize, the fact fingerprint's:+ * lowercase, punctuation folded, whitespace collapsed; then foldSql) in the database, so it 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. Only a row, and then a value, passing the+ * prefilter is normalized.+ */+export function derivationHoldsClaimSql(d: string, needles: string, patterns: string): string {+ return `CASE WHEN ${derivationClaimCandidateSql(d, patterns)} THEN 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+ WHERE CASE WHEN ${hasWordsSql('s.t', patterns)} THEN EXISTS (SELECT 1 FROM unnest(${needles}::text[]) k(n)+ WHERE strpos(' ' || ${foldSql('gbrain_fact_normalize(s.t)')} || ' ', k.n) > 0) ELSE false END) ELSE false END`;+}++/**+ * 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))`;+}+/*** Per-segment derivation watermarks (migration v265): one row per page, pipeline and manifest occurrence, recording* the segment text and the context (`context_hash`: entry state plus the page-level inputs the pipeline reads) it was* derived from, the pipeline version, the outcome and a bounded per-segment output. A pipeline's work on a page is the* live occurrences without a settled row whose segment sha, context hash and version match, found from metadata alone.* Rows of an occurrence that left the live generation are deleted by their pipeline (retireSegmentDerivations) or by a- * fence rewrite; demotion to inline deletes the page's rows, a fact purge every row holding the claim, and a page+ * fence rewrite; demotion to inline deletes the page's rows, a fact purge the rows holding the claim, and a page* delete cascades. The output holds link context and window anchors, so the table gets the segment tables' RLS posture.*+ * page_segment_derivation_purges holds a fact purge's derivation sweep from the purge's commit until a walk of the+ * source's rows has deleted every row in its scope holding the claim (segment-derive.ts continueDerivationPurges): the+ * claim's normalized forms, the pages the purge rewrote and the walk's cursor. While it is there, the trigger on+ * page_segment_derivations drops a write of a row of the source that the sweep would delete (in its scope,+ * derivationSweepScopeSql, and holding the claim; returns NULL: the row is not stored and the pipeline derives it again+ * after the sweep), so a row the walk has passed cannot come back behind it. A derivation write that read a purged+ * page before the purge committed is refused by its own generation guard instead.+ ** PR 4 (Wave B incremental derivation, transcripts): page_derivation_spend is the per-page lifetime spend ledger of each* paid derivation family (`facts`, `atoms`, `synopsis`; page-spend.ts), each capped by `derive.max_usd_per_page` on its own,* apart from the embedding ledger (page_embedding_budget), so derivation spend never starves a page's embeddings.@@ -212,12 +269,37 @@ CREATE TABLE IF NOT EXISTS page_derivation_spend (reserved_at TIMESTAMPTZ,updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),PRIMARY KEY (page_id, family)-);`;+);+CREATE TABLE IF NOT EXISTS page_segment_derivation_purges (+ request_id UUID PRIMARY KEY,+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ needles TEXT[] NOT NULL,+ patterns TEXT[] NOT NULL,+ page_ids INTEGER[] NOT NULL DEFAULT '{}',+ cursor_page INTEGER,+ cursor_pipeline TEXT,+ cursor_occurrence BIGINT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS page_segment_derivation_purges_source ON page_segment_derivation_purges (source_id, created_at);+CREATE OR REPLACE FUNCTION gbrain_refuse_purging_derivation() RETURNS trigger SET search_path = pg_catalog, public AS $func$+BEGIN+ IF EXISTS (SELECT 1 FROM page_segment_derivation_purges x JOIN pages p ON p.source_id = x.source_id+ WHERE p.id = NEW.page_id AND ${derivationSweepScopeSql('NEW', 'p', 'x.page_ids')}+ AND ${derivationHoldsClaimSql('NEW', 'x.needles', 'x.patterns')}) THEN+ RETURN NULL;+ END IF;+ RETURN NEW;+END+$func$ LANGUAGE plpgsql;+DROP TRIGGER IF EXISTS page_segment_derivations_refuse_purging ON page_segment_derivations;+CREATE TRIGGER page_segment_derivations_refuse_purging BEFORE INSERT OR UPDATE OF output, receipt ON page_segment_derivations+ FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purging_derivation();`;/*** The segment tables hold page text (`page_segment_texts`, `page_body_staging_parts`) or a page's shape and* headings (`page_body_manifest`, `page_body_stagings`, `page_view_digests`) or derived link context- * (`page_segment_derivations`), so they get the posture of `pages`+ * (`page_segment_derivations`, and the purged claims `page_segment_derivation_purges` holds), so they get the posture of `pages`* and `content_chunks`: RLS on, re-asserted on every schema replay like the core list in src/schema.sql, so a brain* the auto-RLS event trigger (v35) missed, or one where it was dropped or disabled, never serves segment text to a* role `pages` returns no rows to. Only under a role that bypasses RLS (else the runtime role would lock itself out),@@ -225,7 +307,8 @@ CREATE TABLE IF NOT EXISTS page_derivation_spend (* `page_view_digests` is absent while migration v248 runs. Postgres only: PGLite has no role system, and its* bootstrap enables RLS on no core table either. Source-scoped policies are operator SQL (docs/ENGINES.md).*/-export const PAGE_BODY_RLS_TABLES = ['page_segment_texts', 'page_body_manifest', 'page_body_stagings', 'page_body_staging_parts', 'page_view_digests', 'page_body_staging_texts', 'page_segment_derivations'] as const;+export const PAGE_BODY_RLS_TABLES = ['page_segment_texts', 'page_body_manifest', 'page_body_stagings', 'page_body_staging_parts', 'page_view_digests', 'page_body_staging_texts', 'page_segment_derivations',+ 'page_segment_derivation_purges'] as const;export const PAGE_BODY_RLS_SQL = `DO $rls$DECLARE target TEXT;BEGINdiff --git a/src/core/page-body/segment-derive.ts b/src/core/page-body/segment-derive.tsindex 2702df85fc..366484b6e1 100644--- a/src/core/page-body/segment-derive.ts+++ b/src/core/page-body/segment-derive.ts@@ -18,6 +18,7 @@ import type { BrainEngine } from '../engine.ts';import { canonicalJson } from '../belief/keys.ts';import { planSegmentDerivations, segmentDerivationContextHash, type LiveSegment, type SegmentDerivationKind,type SegmentDerivationRow } from './derivations.ts';+import { derivationClaimCandidateSql, derivationHoldsClaimSql, derivationSweepScopeSql, foldSql } from './schema.ts';import { bodyBlocks, type BodyBlock } from './segment-blocks.ts';import { ledgerApplies, readBodyLedger } from './segment-ledger.ts';import { SEGMENTER_VERSION } from './segmenter.ts';@@ -350,13 +351,6 @@ export async function deleteRewrittenDerivations(engine: BrainEngine, pageId: nu*/export interface DerivationNeedles { needles: string[]; patterns: string[] }-/**- * Folds the lowercase forms a database writes depending on context or locale, applied after lowering on both sides:- * Greek final sigma (lower('ΚΩΣΤΑΣ') is 'κωστασ' while stored text keeps 'κωστας') and the dot JavaScript and ICU keep- * after a lowered Turkish İ ('i̇'). gbrain_fact_normalize itself stays as it is: fact fingerprints are stored.- */-const foldSql = (expr: string) => `replace(translate(${expr}, 'ς', 'σ'), 'i\u0307', 'i')`;-/*** The claims in the form the derivation predicates take, normalized by the database (gbrain_fact_normalize, then* foldSql), so the needle and the rows go through the same SQL. A claim that normalizes to nothing matches nothing.@@ -371,54 +365,16 @@ export async function derivationNeedles(engine: Pick<BrainEngine, 'executeRaw'>,}/**- * SQL predicate, the prefilter: `text`, lowered and folded, matches one of the patterns in the text[] parameter- * `patterns` (from derivationNeedles): has a claim's words in the claim's order. Normalization only lowers, folds- * characters to spaces and collapses spaces, keeping order, so the words of a claim a text holds occur in it in that- * order (in a row's JSON text too: JSON escapes only quotes, backslashes and control characters, which no word holds);- * a text this rejects never holds the claim.+ * Bounds of a fact purge's derivation sweep and of its receipt probe: each statement reads at most `batchRows` rows of+ * the source, walking them in primary-key order (so the rows it normalizes are bounded too); a sweep statement runs in a+ * transaction of its own under `statementMs`; one continueDerivationPurges call starts no new batch past `totalMs`+ * (it runs at least one), and the next call resumes from the stored cursor.*/-const hasWordsSql = (text: string, patterns: string) => `${foldSql(`lower(${text})`)} LIKE ANY (${patterns}::text[])`;--/** SQL predicate: derivation row `d`'s output and receipt JSON text passes the prefilter (see hasWordsSql). */-export function derivationClaimCandidateSql(d: string, patterns: string): string {- return hasWordsSql(`COALESCE(${d}.output::text, '') || ' ' || COALESCE(${d}.receipt::text, '')`, patterns);-}--/**- * SQL predicate: derivation row `d` holds one of the claims (the text[] parameters `needles` and `patterns`, from- * derivationNeedles). The row goes through the needle's own normalization (gbrain_fact_normalize, the fact fingerprint's:- * lowercase, punctuation folded, whitespace collapsed; then foldSql) in the database, so it 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. Only a row, and then a value, passing the- * prefilter is normalized.- */-export function derivationHoldsClaimSql(d: string, needles: string, patterns: string): string {- return `CASE WHEN ${derivationClaimCandidateSql(d, patterns)} THEN 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- WHERE CASE WHEN ${hasWordsSql('s.t', patterns)} THEN EXISTS (SELECT 1 FROM unnest(${needles}::text[]) k(n)- WHERE strpos(' ' || ${foldSql('gbrain_fact_normalize(s.t)')} || ' ', k.n) > 0) ELSE false END) ELSE false END`;-}--/**- * 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))`;-}--/**- * Rows of one derivation statement: a fact purge's sweep and its receipt probe each read at most `batchRows` rows per- * statement (so the rows they normalize per statement are bounded too, well inside a statement budget), walking the- * source's rows in primary-key order; the sweep gives up, failing the purge, past `totalMs`.- */-export const DERIVATION_SWEEP_LIMITS = { batchRows: 500, totalMs: 120_000 } as const;-let sweepLimits: { batchRows: number; totalMs: number } = { ...DERIVATION_SWEEP_LIMITS };+export const DERIVATION_SWEEP_LIMITS = { batchRows: 500, totalMs: 120_000, statementMs: 5_000 } as const;+let sweepLimits: { batchRows: number; totalMs: number; statementMs: number } = { ...DERIVATION_SWEEP_LIMITS };+let afterSweepBatch: (() => Promise<void>) | null = null;+/** @internal Test seam: run `fn` after each committed batch of continueDerivationPurges (null removes it). */+export function __setAfterDerivationSweepBatchForTests(fn: (() => Promise<void>) | null): void { afterSweepBatch = fn; }/** @internal Test seam: shrink the sweep's bounds (null restores them). */export function __setDerivationSweepLimitsForTests(limits: Partial<typeof sweepLimits> | null): void {sweepLimits = { ...DERIVATION_SWEEP_LIMITS, ...(limits ?? {}) };@@ -426,14 +382,6 @@ export function __setDerivationSweepLimitsForTests(limits: Partial<typeof sweepL/** The rows one sweep or probe statement reads. */export function derivationBatchRows(): number { return sweepLimits.batchRows; }-/** A purge's derivation sweep passed DERIVATION_SWEEP_LIMITS.totalMs; the purge fails as on a statement timeout. */-export class DerivationSweepBudgetExceeded extends Error {- readonly code = 'derivation_sweep_budget';- constructor(readonly rows: number, readonly statements: number) {- super(`The derivation sweep read ${rows} rows in ${statements} statements and passed its ${sweepLimits.totalMs} ms budget.`);- }-}-/** A derivation row's primary key, the cursor a batched walk resumes after. */export type DerivationKey = [pageId: number, pipeline: string, occurrenceId: string];@@ -462,54 +410,87 @@ export function recordDerivationStatement(entry: { phase: 'sweep' | 'probe'; sca}/**- * 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. The rows in scope are walked in primary-key order, at most- * DERIVATION_SWEEP_LIMITS.batchRows per statement, each statement under the purge's statement budget; only the rows- * that pass the prefilter (derivationClaimCandidateSql) are normalized. Past DERIVATION_SWEEP_LIMITS.totalMs it throws- * DerivationSweepBudgetExceeded, and the caller's transaction rolls back. The purge receipt probes the store with the same- * predicates. Returns the rows deleted.+ * Record a fact purge's derivation sweep in the purge's transaction: the claims' normalized forms (derivationNeedles)+ * and `pageIds`, the pages it rewrote, keyed by the purge request. From the purge's commit the trigger on+ * page_segment_derivations refuses rows holding the claim on those pages (schema.ts), and continueDerivationPurges+ * deletes the rows already there. A claim that normalizes to nothing records nothing.*/-export async function sweepDerivationText(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, pageIds: readonly number[],- claims: readonly string[]): Promise<number> {+export async function recordDerivationPurge(engine: Pick<BrainEngine, 'executeRaw'>, requestId: string, sourceId: string, pageIds: readonly number[],+ claims: readonly string[]): Promise<void> {const { needles, patterns } = await derivationNeedles(engine, claims);- if (!needles.length) return 0;- const { batchRows, totalMs } = sweepLimits;+ if (!needles.length) return;+ await engine.executeRaw(`INSERT INTO page_segment_derivation_purges (request_id, source_id, needles, patterns, page_ids)+ VALUES ($1::uuid, $2, $3::text[], $4::text[], $5::int[]) ON CONFLICT (request_id) DO NOTHING`, [requestId, sourceId, needles, patterns, [...pageIds]]);+}++/** Whether a purge request's derivation sweep is still recorded, so its rows are not all deleted yet. */+export async function derivationPurgePending(engine: Pick<BrainEngine, 'executeRaw'>, requestId: string): Promise<boolean> {+ return (await engine.executeRaw('SELECT 1 FROM page_segment_derivation_purges WHERE request_id=$1::uuid', [requestId])).length > 0;+}++/**+ * Continue the recorded derivation sweeps of a source, oldest first: each batch is a transaction of its own that locks+ * the sweep's record (a sweep another caller is walking is left to it), reads the next DERIVATION_SWEEP_LIMITS.batchRows+ * rows of the source after the stored cursor, deletes those in the sweep's scope (derivationSweepScopeSql over its+ * pages) that hold the claim (derivationHoldsClaimSql; only rows passing the prefilter, derivationClaimCandidateSql, are+ * normalized) and stores the cursor, or deletes the record after the source's last row. No batch locks the source or a+ * page, so writes go on during a sweep. A batch is not started past DERIVATION_SWEEP_LIMITS.totalMs, and a statement+ * timeout ends the call with its batch rolled back; either way the next call (a later purge of the source, a replay of the+ * purge request) resumes from the cursor. Returns the rows deleted.+ */+export async function continueDerivationPurges(engine: BrainEngine, sourceId: string): Promise<number> {+ const { batchRows, totalMs, statementMs } = sweepLimits;const deadline = performance.now() + totalMs;const pages = new Map<number, { scanned: number; normalized: number; deleted: number }>();- let cursor: DerivationKey | null = null, read = 0, statements = 0;- for (;;) {- const rows: Array<{ page_id: number; scanned: number; normalized: number; deleted: number; last_page: number; last_pipeline: string; last_occurrence: string }> =- await engine.executeRaw(`WITH batch AS MATERIALIZED (- SELECT d.page_id, d.pipeline, d.occurrence_id FROM page_segment_derivations d JOIN pages p ON p.id = d.page_id- WHERE p.source_id = $1 AND ${derivationSweepScopeSql('d', 'p', '$2')} AND ${derivationAfterSql('d', ['$5', '$6', '$7'])}- ORDER BY d.page_id, d.pipeline, d.occurrence_id LIMIT $8- ), scope AS MATERIALIZED (- SELECT d.page_id, d.pipeline, d.occurrence_id, d.output, d.receipt, ${derivationClaimCandidateSql('d', '$4')} AS candidate- FROM batch b JOIN page_segment_derivations d ON d.page_id = b.page_id AND d.pipeline = b.pipeline AND d.occurrence_id = b.occurrence_id- ), hits AS MATERIALIZED (- SELECT s.page_id, s.pipeline, s.occurrence_id FROM scope s WHERE s.candidate AND ${derivationHoldsClaimSql('s', '$3', '$4')}- ), gone AS (- DELETE FROM page_segment_derivations x USING hits h WHERE x.page_id = h.page_id AND x.pipeline = h.pipeline- AND x.occurrence_id = h.occurrence_id RETURNING x.page_id- ), last AS (- SELECT page_id, pipeline, occurrence_id::text AS occurrence_id FROM batch ORDER BY page_id DESC, pipeline DESC, occurrence_id DESC LIMIT 1- ) SELECT s.page_id, count(*)::int AS scanned, count(*) FILTER (WHERE s.candidate)::int AS normalized,- (SELECT count(*)::int FROM gone g WHERE g.page_id = s.page_id) AS deleted,- (SELECT page_id FROM last) AS last_page, (SELECT pipeline FROM last) AS last_pipeline, (SELECT occurrence_id FROM last) AS last_occurrence- FROM scope s GROUP BY s.page_id ORDER BY s.page_id`,- [sourceId, [...pageIds], needles, patterns, cursor?.[0] ?? null, cursor?.[1] ?? null, cursor?.[2] ?? null, batchRows]);- statements++;- const scanned = rows.reduce((n, row) => n + Number(row.scanned), 0);- read += scanned;- recordDerivationStatement({ phase: 'sweep', scanned, normalized: rows.reduce((n, row) => n + Number(row.normalized), 0) });- for (const row of rows) {- const page = pages.get(Number(row.page_id)) ?? { scanned: 0, normalized: 0, deleted: 0 };- pages.set(Number(row.page_id), { scanned: page.scanned + Number(row.scanned), normalized: page.normalized + Number(row.normalized), deleted: page.deleted + Number(row.deleted) });+ try {+ for (let batches = 0; batches === 0 || performance.now() <= deadline; batches++) {+ type Row = { page_id: number | null; swept: number; normalized: number; deleted: number; scanned: number; last_page: number; last_pipeline: string; last_occurrence: string };+ const rows = await engine.transaction(async tx => {+ await tx.executeRaw("SELECT set_config('statement_timeout',$1,true)", [`${statementMs}ms`]);+ const [purge] = await tx.executeRaw<{ request_id: string; needles: string[]; patterns: string[]; page_ids: number[]; cursor_page: number | null;+ cursor_pipeline: string | null; cursor_occurrence: string | null }>(`SELECT request_id::text AS request_id, needles, patterns, page_ids, cursor_page,+ cursor_pipeline, cursor_occurrence::text AS cursor_occurrence FROM page_segment_derivation_purges WHERE source_id=$1+ ORDER BY created_at, request_id LIMIT 1 FOR UPDATE SKIP LOCKED`, [sourceId]);+ if (!purge) return null;+ const batch = await tx.executeRaw<Row>(`WITH batch AS MATERIALIZED (+ SELECT d.page_id, d.pipeline, d.occurrence_id, ${derivationSweepScopeSql('d', 'p', '$2')} AS swept FROM page_segment_derivations d+ JOIN pages p ON p.id = d.page_id WHERE p.source_id = $1 AND ${derivationAfterSql('d', ['$5', '$6', '$7'])}+ ORDER BY d.page_id, d.pipeline, d.occurrence_id LIMIT $8+ ), scope AS MATERIALIZED (+ SELECT d.page_id, d.pipeline, d.occurrence_id, d.output, d.receipt, ${derivationClaimCandidateSql('d', '$4')} AS candidate+ FROM batch b JOIN page_segment_derivations d ON d.page_id = b.page_id AND d.pipeline = b.pipeline AND d.occurrence_id = b.occurrence_id+ WHERE b.swept+ ), hits AS MATERIALIZED (+ SELECT s.page_id, s.pipeline, s.occurrence_id FROM scope s WHERE s.candidate AND ${derivationHoldsClaimSql('s', '$3', '$4')}+ ), gone AS (+ DELETE FROM page_segment_derivations x USING hits h WHERE x.page_id = h.page_id AND x.pipeline = h.pipeline+ AND x.occurrence_id = h.occurrence_id RETURNING x.page_id+ ), last AS (+ SELECT b.page_id, b.pipeline, b.occurrence_id::text AS occurrence_id FROM batch b ORDER BY b.page_id DESC, b.pipeline DESC, b.occurrence_id DESC LIMIT 1+ ), per_page AS (+ SELECT s.page_id, count(*)::int AS swept, count(*) FILTER (WHERE s.candidate)::int AS normalized,+ (SELECT count(*)::int FROM gone g WHERE g.page_id = s.page_id) AS deleted FROM scope s GROUP BY s.page_id+ ) SELECT pp.page_id, COALESCE(pp.swept, 0) AS swept, COALESCE(pp.normalized, 0) AS normalized, COALESCE(pp.deleted, 0) AS deleted,+ (SELECT count(*)::int FROM batch) AS scanned, l.page_id AS last_page, l.pipeline AS last_pipeline, l.occurrence_id AS last_occurrence+ FROM (SELECT 1) one LEFT JOIN last l ON true LEFT JOIN per_page pp ON true ORDER BY pp.page_id`,+ [sourceId, purge.page_ids, purge.needles, purge.patterns, purge.cursor_page, purge.cursor_pipeline, purge.cursor_occurrence, batchRows]);+ const scanned = Number(batch[0]?.scanned ?? 0);+ if (scanned < batchRows) await tx.executeRaw('DELETE FROM page_segment_derivation_purges WHERE request_id=$1::uuid', [purge.request_id]);+ else await tx.executeRaw(`UPDATE page_segment_derivation_purges SET cursor_page=$2, cursor_pipeline=$3, cursor_occurrence=$4::bigint+ WHERE request_id=$1::uuid`, [purge.request_id, Number(batch[0]!.last_page), batch[0]!.last_pipeline, String(batch[0]!.last_occurrence)]);+ return batch;+ });+ if (!rows) break;+ recordDerivationStatement({ phase: 'sweep', scanned: Number(rows[0]?.scanned ?? 0), normalized: rows.reduce((n, row) => n + Number(row.normalized), 0) });+ for (const row of rows) {+ if (row.page_id === null) continue;+ const page = pages.get(Number(row.page_id)) ?? { scanned: 0, normalized: 0, deleted: 0 };+ pages.set(Number(row.page_id), { scanned: page.scanned + Number(row.swept), normalized: page.normalized + Number(row.normalized), deleted: page.deleted + Number(row.deleted) });+ }+ await afterSweepBatch?.();}- if (scanned < batchRows) break;- cursor = [Number(rows[0]!.last_page), rows[0]!.last_pipeline, String(rows[0]!.last_occurrence)];- if (performance.now() > deadline) throw new DerivationSweepBudgetExceeded(read, statements);+ } catch (error) {+ if ((error as { code?: unknown } | null)?.code !== '57014') throw error;}const sorted = [...pages].sort((a, b) => a[0] - b[0]);if (recordSweepWork) for (const [pageId, work] of sorted) derivationSweepWork.push({ pageId, ...work });diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.tsindex e2471b4494..42b381f0ca 100644--- a/src/core/persistence/fault-points.ts+++ b/src/core/persistence/fault-points.ts@@ -45,7 +45,7 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect| 'purge:sweep_chunk' | 'purge:carrying_lookup'// W1: before each keyset batch of the belief ledger's purge redaction (belief/purge.ts); a 57014 from the hook models its statement timeout.| 'purge:ledger_redaction'- // Before a fact purge's derivation sweep (segment-derive.ts sweepDerivationText); a 57014 from the hook models its statement timeout.+ // Before a fact purge records its derivation sweep in its transaction (segment-derive.ts recordDerivationPurge); a 57014 from the hook models its statement timeout.| 'purge:derivation_sweep'// #6712 PR 4b: after a page-row deletion of a managed Git source wrote its origin's deletion marker (sync-markers.ts), before the row goes.| 'purge:marker_written'diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex 2a024c8615..ea03e6223e 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -1413,6 +1413,36 @@ CREATE TABLE IF NOT EXISTS page_derivation_spend (updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),PRIMARY KEY (page_id, family));+CREATE TABLE IF NOT EXISTS page_segment_derivation_purges (+ request_id UUID PRIMARY KEY,+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ needles TEXT[] NOT NULL,+ patterns TEXT[] NOT NULL,+ page_ids INTEGER[] NOT NULL DEFAULT '{}',+ cursor_page INTEGER,+ cursor_pipeline TEXT,+ cursor_occurrence BIGINT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS page_segment_derivation_purges_source ON page_segment_derivation_purges (source_id, created_at);+CREATE OR REPLACE FUNCTION gbrain_refuse_purging_derivation() RETURNS trigger SET search_path = pg_catalog, public AS \$func\$+BEGIN+ IF EXISTS (SELECT 1 FROM page_segment_derivation_purges x JOIN pages p ON p.source_id = x.source_id+ WHERE p.id = NEW.page_id AND (NEW.page_id = ANY(x.page_ids::int[]) OR p.deleted_at IS NOT NULL OR NOT EXISTS (SELECT 1 FROM page_body_manifest m+ WHERE m.page_id = NEW.page_id AND m.occurrence_id = NEW.occurrence_id AND m.gen_to IS NULL AND m.staging_id IS NULL AND m.sha256 = NEW.segment_sha256))+ AND CASE WHEN replace(translate(lower(COALESCE(NEW.output::text, '') || ' ' || COALESCE(NEW.receipt::text, '')), 'ς', 'σ'), 'i̇', 'i') LIKE ANY (x.patterns::text[]) THEN EXISTS (SELECT 1 FROM (VALUES (NEW.output), (NEW.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+ WHERE CASE WHEN replace(translate(lower(s.t), 'ς', 'σ'), 'i̇', 'i') LIKE ANY (x.patterns::text[]) THEN EXISTS (SELECT 1 FROM unnest(x.needles::text[]) k(n)+ WHERE strpos(' ' || replace(translate(gbrain_fact_normalize(s.t), 'ς', 'σ'), 'i̇', 'i') || ' ', k.n) > 0) ELSE false END) ELSE false END) THEN+ RETURN NULL;+ END IF;+ RETURN NEW;+END+\$func\$ LANGUAGE plpgsql;+DROP TRIGGER IF EXISTS page_segment_derivations_refuse_purging ON page_segment_derivations;+CREATE TRIGGER page_segment_derivations_refuse_purging BEFORE INSERT OR UPDATE OF output, receipt ON page_segment_derivations+ FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purging_derivation();diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex c9e27e65d6..2475505558 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -2157,6 +2157,36 @@ CREATE TABLE IF NOT EXISTS page_derivation_spend (updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),PRIMARY KEY (page_id, family));+CREATE TABLE IF NOT EXISTS page_segment_derivation_purges (+ request_id UUID PRIMARY KEY,+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ needles TEXT[] NOT NULL,+ patterns TEXT[] NOT NULL,+ page_ids INTEGER[] NOT NULL DEFAULT '{}',+ cursor_page INTEGER,+ cursor_pipeline TEXT,+ cursor_occurrence BIGINT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS page_segment_derivation_purges_source ON page_segment_derivation_purges (source_id, created_at);+CREATE OR REPLACE FUNCTION gbrain_refuse_purging_derivation() RETURNS trigger SET search_path = pg_catalog, public AS \$func\$+BEGIN+ IF EXISTS (SELECT 1 FROM page_segment_derivation_purges x JOIN pages p ON p.source_id = x.source_id+ WHERE p.id = NEW.page_id AND (NEW.page_id = ANY(x.page_ids::int[]) OR p.deleted_at IS NOT NULL OR NOT EXISTS (SELECT 1 FROM page_body_manifest m+ WHERE m.page_id = NEW.page_id AND m.occurrence_id = NEW.occurrence_id AND m.gen_to IS NULL AND m.staging_id IS NULL AND m.sha256 = NEW.segment_sha256))+ AND CASE WHEN replace(translate(lower(COALESCE(NEW.output::text, '') || ' ' || COALESCE(NEW.receipt::text, '')), 'ς', 'σ'), 'i̇', 'i') LIKE ANY (x.patterns::text[]) THEN EXISTS (SELECT 1 FROM (VALUES (NEW.output), (NEW.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+ WHERE CASE WHEN replace(translate(lower(s.t), 'ς', 'σ'), 'i̇', 'i') LIKE ANY (x.patterns::text[]) THEN EXISTS (SELECT 1 FROM unnest(x.needles::text[]) k(n)+ WHERE strpos(' ' || replace(translate(gbrain_fact_normalize(s.t), 'ς', 'σ'), 'i̇', 'i') || ' ', k.n) > 0) ELSE false END) ELSE false END) THEN+ RETURN NULL;+ END IF;+ RETURN NEW;+END+\$func\$ LANGUAGE plpgsql;+DROP TRIGGER IF EXISTS page_segment_derivations_refuse_purging ON page_segment_derivations;+CREATE TRIGGER page_segment_derivations_refuse_purging BEFORE INSERT OR UPDATE OF output, receipt ON page_segment_derivations+ FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purging_derivation();-- END GENERATED from src/core/page-body/schema.ts (PAGE_SEGMENT_DERIVATIONS_SQL)-- BEGIN GENERATED from src/core/page-body/schema.ts (PAGE_BODY_RLS_SQL). Edit that file, then run: bun run build:schema@@ -2164,7 +2194,7 @@ DO \$rls\$DECLARE target TEXT;BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- FOREACH target IN ARRAY ARRAY['page_segment_texts','page_body_manifest','page_body_stagings','page_body_staging_parts','page_view_digests','page_body_staging_texts','page_segment_derivations'] LOOP+ FOREACH target IN ARRAY ARRAY['page_segment_texts','page_body_manifest','page_body_stagings','page_body_staging_parts','page_view_digests','page_body_staging_texts','page_segment_derivations','page_segment_derivation_purges'] LOOPIF EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespaceWHERE n.nspname = current_schema() AND c.relname = target AND c.relkind = 'r' AND NOT c.relrowsecurity) THENEXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', target);diff --git a/src/schema.sql b/src/schema.sqlindex 859577e230..178b94e01f 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -2153,6 +2153,36 @@ CREATE TABLE IF NOT EXISTS page_derivation_spend (updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),PRIMARY KEY (page_id, family));+CREATE TABLE IF NOT EXISTS page_segment_derivation_purges (+ request_id UUID PRIMARY KEY,+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ needles TEXT[] NOT NULL,+ patterns TEXT[] NOT NULL,+ page_ids INTEGER[] NOT NULL DEFAULT '{}',+ cursor_page INTEGER,+ cursor_pipeline TEXT,+ cursor_occurrence BIGINT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS page_segment_derivation_purges_source ON page_segment_derivation_purges (source_id, created_at);+CREATE OR REPLACE FUNCTION gbrain_refuse_purging_derivation() RETURNS trigger SET search_path = pg_catalog, public AS $func$+BEGIN+ IF EXISTS (SELECT 1 FROM page_segment_derivation_purges x JOIN pages p ON p.source_id = x.source_id+ WHERE p.id = NEW.page_id AND (NEW.page_id = ANY(x.page_ids::int[]) OR p.deleted_at IS NOT NULL OR NOT EXISTS (SELECT 1 FROM page_body_manifest m+ WHERE m.page_id = NEW.page_id AND m.occurrence_id = NEW.occurrence_id AND m.gen_to IS NULL AND m.staging_id IS NULL AND m.sha256 = NEW.segment_sha256))+ AND CASE WHEN replace(translate(lower(COALESCE(NEW.output::text, '') || ' ' || COALESCE(NEW.receipt::text, '')), 'ς', 'σ'), 'i̇', 'i') LIKE ANY (x.patterns::text[]) THEN EXISTS (SELECT 1 FROM (VALUES (NEW.output), (NEW.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+ WHERE CASE WHEN replace(translate(lower(s.t), 'ς', 'σ'), 'i̇', 'i') LIKE ANY (x.patterns::text[]) THEN EXISTS (SELECT 1 FROM unnest(x.needles::text[]) k(n)+ WHERE strpos(' ' || replace(translate(gbrain_fact_normalize(s.t), 'ς', 'σ'), 'i̇', 'i') || ' ', k.n) > 0) ELSE false END) ELSE false END) THEN+ RETURN NULL;+ END IF;+ RETURN NEW;+END+$func$ LANGUAGE plpgsql;+DROP TRIGGER IF EXISTS page_segment_derivations_refuse_purging ON page_segment_derivations;+CREATE TRIGGER page_segment_derivations_refuse_purging BEFORE INSERT OR UPDATE OF output, receipt ON page_segment_derivations+ FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purging_derivation();-- END GENERATED from src/core/page-body/schema.ts (PAGE_SEGMENT_DERIVATIONS_SQL)-- BEGIN GENERATED from src/core/page-body/schema.ts (PAGE_BODY_RLS_SQL). Edit that file, then run: bun run build:schema@@ -2160,7 +2190,7 @@ DO $rls$DECLARE target TEXT;BEGINIF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN- FOREACH target IN ARRAY ARRAY['page_segment_texts','page_body_manifest','page_body_stagings','page_body_staging_parts','page_view_digests','page_body_staging_texts','page_segment_derivations'] LOOP+ FOREACH target IN ARRAY ARRAY['page_segment_texts','page_body_manifest','page_body_stagings','page_body_staging_parts','page_view_digests','page_body_staging_texts','page_segment_derivations','page_segment_derivation_purges'] LOOPIF EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespaceWHERE n.nspname = current_schema() AND c.relname = target AND c.relkind = 'r' AND NOT c.relrowsecurity) THENEXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', target);diff --git a/test/helpers/derivation-purge-cases.ts b/test/helpers/derivation-purge-cases.tsindex beaaa948cd..25d0ce001b 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, __setDerivationSweepLimitsForTests, __setDerivationSweepWorkForTests, derivationSweepStatements, derivationSweepWork,+import { __setAfterDerivationSweepBatchForTests, __setBeforeDerivationWriteForTests, __setDerivationSweepLimitsForTests, __setDerivationSweepWorkForTests, derivationSweepStatements, derivationSweepWork,segmentDeriveWork } from '../../src/core/page-body/segment-derive.ts';import { installFaultHook } from '../../src/core/persistence/fault-points.ts';import { incrementalFactsFenceView, segmentedFactsFenceView } from '../../src/core/page-body/segment-facts.ts';@@ -327,24 +327,157 @@ export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): void}}, 600_000);- test('a sweep past its overall budget fails the purge with the typed code and purges nothing', async () => {+ /** Derivation rows of the source. */+ const sourceRows = async () => Number((await brain.engine.executeRaw<{ n: number }>(+ 'SELECT count(*)::int AS n FROM page_segment_derivations d JOIN pages p ON p.id=d.page_id WHERE p.source_id=$1', [SOURCE]))[0]!.n);+ const sweepsRecorded = async () => Number((await brain.engine.executeRaw<{ n: number }>(+ 'SELECT count(*)::int AS n FROM page_segment_derivation_purges WHERE source_id=$1', [SOURCE]))[0]!.n);+ const sweepStatements = () => derivationSweepStatements.filter(s => s.phase === 'sweep');+ const confirmed = async (id: number) => {+ const dry = await brain.call('purge_fact', { id, dry_run: true });+ return { id, confirm: dry.body.confirm_token, expected_revision: dry.body.expected_revision, request_id: randomUUID() };+ };++ test('a large source\'s sweep resumes from its cursor on each replay and completes with no residual', async () => {const claim = 'Purge Example vent code is 8350', batch = 200, holding = 3;const rows = await candidateRowsPage('notes/sweep-budget-rows', claim, 600, holding);const id = await seed('notes/sweep-budget-purge', claim);- const dry = await brain.call('purge_fact', { id, dry_run: true });+ const params = await confirmed(id);__setDerivationSweepLimitsForTests({ batchRows: batch, totalMs: 0 });__setDerivationSweepWorkForTests(true);try {- const failed = await brain.call('purge_fact', { id, confirm: dry.body.confirm_token, expected_revision: dry.body.expected_revision });- expect({ isError: failed.isError, code: failed.body.error ?? failed.body.code }).toEqual({ isError: true, code: 'purge_lookup_timeout' });- expect(derivationSweepStatements.filter(s => s.phase === 'sweep').map(s => s.scanned)).toEqual([batch]);+ const first = await brain.call('purge_fact', params);+ expect({ isError: first.isError, state: first.body.state, completion: first.body.completion, sweep: first.body.derivation_sweep, store: derivationStore(first.body)?.status })+ .toEqual({ isError: false, state: 'committed', completion: 'incomplete', sweep: 'pending', store: 'incomplete' });+ expect(sweepStatements().map(s => s.scanned)).toEqual([batch]);+ const [fact] = await brain.engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM facts WHERE id=$1', [id]);+ expect(Number(fact!.n)).toBe(0);+ let last = first, calls = 1;+ while (last.body.derivation_sweep === 'pending' && calls < 1000) {+ last = await brain.call('purge_fact', params);+ calls++;+ }+ const sweeps = sweepStatements();+ expect(calls).toBeGreaterThan(2);+ expect(sweeps.length).toBe(calls);+ expect(sweeps.slice(0, -1).every(s => s.scanned === batch) && sweeps.at(-1)!.scanned < batch).toBe(true);+ expect(sweeps.reduce((n, s) => n + s.scanned, 0)).toBe(await sourceRows() + derivationSweepWork.reduce((n, w) => n + w.deleted, 0));+ expect({ replayed: last.body.replayed, sweep: last.body.derivation_sweep }).toEqual({ replayed: true, sweep: undefined });+ } finally {+ __setDerivationSweepLimitsForTests(null);+ __setDerivationSweepWorkForTests(false);+ }+ expect(await exactHolders(brain.engine, rows, claim)).toEqual([]);+ expect((await brain.engine.readSegmentDerivations(rows)).length).toBe(600);+ expect(await sweepsRecorded()).toBe(0);+ }, 600_000);++ test('a row holding the claim written behind the sweep\'s cursor while it walks is refused, and no residual is left', async () => {+ const claim = 'Purge Example latch code is 4471', batch = 100;+ const behind = await candidateRowsPage('notes/sweep-behind-early', claim, 0, 1);+ const rows = await candidateRowsPage('notes/sweep-behind-rows', claim, 300, 2);+ const id = await seed('notes/sweep-behind-purge', claim);+ const written: number[] = [];+ __setDerivationSweepLimitsForTests({ batchRows: batch });+ __setDerivationSweepWorkForTests(true);+ __setAfterDerivationSweepBatchForTests(async () => {+ if (sweepStatements().at(-1)!.scanned < batch) return;+ written.push((await brain.engine.executeRaw(`INSERT INTO page_segment_derivations (page_id, pipeline, occurrence_id, pipeline_version, segment_sha256,+ context_hash, state, output, receipt) VALUES ($1, 'links', $2, 1, decode(repeat('00', 32), 'hex'), decode(repeat('00', 32), 'hex'), 'done',+ jsonb_build_object('candidates', jsonb_build_array(jsonb_build_object('context', 'Late: ' || $3::text))), NULL)+ ON CONFLICT (page_id, pipeline, occurrence_id) DO UPDATE SET output = EXCLUDED.output RETURNING 1`, [behind, 1000 + written.length, claim])).length);+ });+ let receipt: Record<string, any>;+ try { receipt = await purge(id); } finally {+ __setAfterDerivationSweepBatchForTests(null);+ __setDerivationSweepLimitsForTests(null);+ __setDerivationSweepWorkForTests(false);+ }+ expect(written.length).toBeGreaterThan(1);+ expect({ written: written.reduce((n, k) => n + k, 0), behind: await exactHolders(brain.engine, behind, claim), rows: await exactHolders(brain.engine, rows, claim) })+ .toEqual({ written: 0, behind: [], rows: [] });+ complete(receipt!);+ expect(receipt!.derivation_sweep).toBeUndefined();+ }, 600_000);++ test('writes to other pages of the source commit while a sweep walks a large source', async () => {+ const claim = 'Purge Example dock code is 3920', batch = 100;+ const rows = await candidateRowsPage('notes/sweep-writer-rows', claim, 300, 1);+ const id = await seed('notes/sweep-writer-purge', claim);+ const results: Array<{ isError: boolean; code: unknown }> = [];+ __setDerivationSweepLimitsForTests({ batchRows: batch });+ __setDerivationSweepWorkForTests(true);+ __setAfterDerivationSweepBatchForTests(async () => {+ const k = results.length;+ const res = await brain.call('put_page', { slug: `notes/sweep-writer-other-${k}`, content: `---\ntype: note\ntitle: Writer Example ${k}\n---\n\nWritten during the sweep.\n`,+ request_id: randomUUID() });+ results.push({ isError: res.isError, code: res.body.error ?? res.body.code ?? null });+ });+ let receipt: Record<string, any>, statements = 0;+ try { receipt = await purge(id); statements = sweepStatements().length; } finally {+ __setAfterDerivationSweepBatchForTests(null);+ __setDerivationSweepLimitsForTests(null);+ __setDerivationSweepWorkForTests(false);+ }+ expect(statements).toBeGreaterThan(3);+ expect({ writes: results.length, failed: results.filter(r => r.isError) }).toEqual({ writes: statements, failed: [] });+ const [pages] = await brain.engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pages WHERE source_id=$1 AND slug LIKE 'notes/sweep-writer-other-%'", [SOURCE]);+ expect(Number(pages!.n)).toBe(statements);+ expect(await exactHolders(brain.engine, rows, claim)).toEqual([]);+ complete(receipt!);+ }, 600_000);++ test('a sweep call starts no batch past its deadline, also after the last short batch of a sweep', async () => {+ const claimA = 'Purge Example cellar code is 5307', claimB = 'Purge Example attic code is 6418';+ const rows = await candidateRowsPage('notes/sweep-deadline-rows', claimA, 300, 1);+ const a = await confirmed(await seed('notes/sweep-deadline-a', claimA));+ const idB = await seed('notes/sweep-deadline-b', claimB);+ try {+ __setDerivationSweepLimitsForTests({ batchRows: 100, totalMs: 0 });+ __setDerivationSweepWorkForTests(true);+ expect((await brain.call('purge_fact', a)).body.derivation_sweep).toBe('pending');+ expect(sweepStatements().map(s => s.scanned)).toEqual([100]);+ __setDerivationSweepLimitsForTests({ batchRows: 1_000_000, totalMs: 0 });+ __setDerivationSweepWorkForTests(true);+ const b = await purge(idB);+ const sweeps = sweepStatements();+ expect({ statements: sweeps.length, short: sweeps[0]!.scanned < 1_000_000, sweep: b.derivation_sweep, recorded: await sweepsRecorded() })+ .toEqual({ statements: 1, short: true, sweep: 'pending', recorded: 1 });+ expect(await exactHolders(brain.engine, rows, claimA)).toEqual([]);+ const replay = await brain.call('purge_fact', a);+ expect({ replayed: replay.body.replayed, sweep: replay.body.derivation_sweep, statements: sweepStatements().length, recorded: await sweepsRecorded() })+ .toEqual({ replayed: true, sweep: undefined, statements: 2, recorded: 0 });+ } finally {+ __setDerivationSweepLimitsForTests(null);+ __setDerivationSweepWorkForTests(false);+ }+ }, 600_000);++ test('a sweep statement reads at most batchRows rows of the source, rows outside its scope included', async () => {+ const claim = 'Purge Example porch code is 7084', batch = 10;+ await brain.seed('notes/sweep-bounded-live', prosePage('Alice Example keeps bees', 65));+ const live = await storedPage(brain.engine, 'notes/sweep-bounded-live');+ await deriveAll(brain.engine, live);+ const rows = await candidateRowsPage('notes/sweep-bounded-rows', claim, 120, 1);+ const id = await seed('notes/sweep-bounded-purge', claim);+ const outside = (await brain.engine.readSegmentDerivations(live.id)).length;+ expect(outside).toBeGreaterThan(batch);+ expect((await unbackedRows(brain.engine)).has(live.id)).toBe(false);+ __setDerivationSweepLimitsForTests({ batchRows: batch });+ __setDerivationSweepWorkForTests(true);+ try {+ const receipt = await purge(id);+ const sweeps = sweepStatements();+ expect(sweeps.length).toBeGreaterThan(2);+ expect(sweeps.slice(0, -1).every(s => s.scanned === batch) && sweeps.at(-1)!.scanned < batch).toBe(true);+ expect(sweeps.reduce((n, s) => n + s.scanned, 0)).toBe(await sourceRows() + derivationSweepWork.reduce((n, w) => n + w.deleted, 0));+ expect(derivationSweepWork.find(w => w.pageId === live.id)).toBeUndefined();+ expect(await exactHolders(brain.engine, rows, claim)).toEqual([]);+ complete(receipt);} finally {__setDerivationSweepLimitsForTests(null);__setDerivationSweepWorkForTests(false);}- expect(await exactHolders(brain.engine, rows, claim)).toHaveLength(holding);- const [fact] = await brain.engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM facts WHERE id=$1', [id]);- expect(Number(fact!.n)).toBe(1);}, 600_000);});}