Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(purge): fold final sigma in the derivation sweep, prefilter it, type its timeout

garrytan5d5d152fb5bd
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 7079b7da85..f668d3da0f 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1068,6 +1068,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ 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.' },
+ { 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.' },
];
/** 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.ts
index ef07887774..5931a8a36f 100644
--- a/src/core/facts/purge-verify.ts
+++ b/src/core/facts/purge-verify.ts
@@ -27,7 +27,7 @@ import { DELETION_INVENTORY, OUT_OF_REACH_RESIDUALS, type InventoryEntry } from
import 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 { derivationHoldsClaimSql, derivationNeedles, 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';
@@ -129,8 +129,10 @@ async function segmentTextReport(engine: BrainEngine, sourceId: string, needles:
*/
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 { needles, patterns } = await derivationNeedles(engine, claims);
+ if (!needles.length) return { store: 'page_segment_derivations', status: removed ? 'deleted' : 'not_present', removed };
+ 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', '$4')}`;
+ const params = [sourceId, needles, [...pageIds], patterns];
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 };
diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.ts
index 21fdabf64b..3ecc6c8072 100644
--- a/src/core/facts/purge.ts
+++ b/src/core/facts/purge.ts
@@ -225,6 +225,17 @@ async function ledgerLookup<T>(fn: () => Promise<T>, factId: number, sourceId: s
}
}
+/** The derivation sweep's statement timeout 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> {
+ try { return await fn(); } catch (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 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'] }) });
+ }
+}
+
/** Pages with a pending recovery record or an unfinished mirror refuse a purge, as effects refuse other writes. */
async function assertNoPendingPublication(tx: BrainEngine, sourceId: string, pages: PurgePlan['pages'], ownRequest: string): Promise<void> {
if (!pages.length) return;
@@ -524,7 +535,8 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Rec
const 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 sweepDerivationText(tx, p.sourceId, pageIds, [current.fact, escapeFenceCell(current.fact)]);
+ 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);
// 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/segment-derive.ts b/src/core/page-body/segment-derive.ts
index 26f648fc97..9dd941c25b 100644
--- a/src/core/page-body/segment-derive.ts
+++ b/src/core/page-body/segment-derive.ts
@@ -345,18 +345,60 @@ export async function deleteRewrittenDerivations(engine: BrainEngine, pageId: nu
}
/**
- * 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.
+ * Claims as the derivation predicates match them: each claim's folded normalized text between spaces (`needles`), and
+ * for each a LIKE pattern of its words in order (`patterns`), which the prefilter tries on a row's raw text.
*/
-export function derivationHoldsClaimSql(d: string, needles: string): string {
- return `EXISTS (SELECT 1 FROM (VALUES (${d}.output), (${d}.receipt)) doc(j),
+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.
+ */
+export async function derivationNeedles(engine: Pick<BrainEngine, 'executeRaw'>, claims: readonly string[]): Promise<DerivationNeedles> {
+ const list = [...new Set(claims.filter(Boolean))];
+ const rows = list.length ? await engine.executeRaw<{ f: string }>(`SELECT DISTINCT f FROM (SELECT ${foldSql('gbrain_fact_normalize(c)')} AS f
+ FROM unnest($1::text[]) c) x WHERE f <> '' ORDER BY f`, [list]) : [];
+ // A word holding a control character is spelled \uXXXX in a row's JSON text, so it cannot prefilter.
+ const pattern = (text: string) => ['', ...text.split(' ').filter(t => t && !/[\u0000-\u001f]/.test(t)).map(t => t.replace(/[\\%_]/g, '\\$&')), ''].join('%');
+ return { needles: rows.map(row => ` ${row.f} `), patterns: rows.map(row => pattern(row.f)) };
+}
+
+/**
+ * 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,
- (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)`;
+ 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`;
}
/**
@@ -370,28 +412,38 @@ export function derivationSweepScopeSql(d: string, p: string, pageIds: string):
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 }> = [];
+/**
+ * @internal Per page, for the work-volume tests (counts, not time): derivation rows each sweep read, normalized and
+ * deleted. Recorded only while __setDerivationSweepWorkForTests(true) is in effect.
+ */
+export const derivationSweepWork: Array<{ pageId: number; scanned: number; normalized: number; deleted: number }> = [];
+let recordSweepWork = false;
+/** @internal Test seam: start (clearing what is there) or stop recording derivationSweepWork. */
+export function __setDerivationSweepWorkForTests(on: boolean): void { recordSweepWork = on; derivationSweepWork.length = 0; }
/**
* 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.
+ * rewrites and under its statement budget, so a row a rewrite could not place goes too. Only rows in scope that pass the
+ * prefilter (derivationClaimCandidateSql) are normalized; the purge receipt probes the store with the same 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;
- 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
+ const { needles, patterns } = await derivationNeedles(engine, claims);
+ if (!needles.length) return 0;
+ const rows = await engine.executeRaw<{ page_id: number; scanned: number; normalized: number; deleted: number }>(`WITH scope AS MATERIALIZED (
+ SELECT d.page_id, d.pipeline, d.occurrence_id, d.output, d.receipt, ${derivationClaimCandidateSql('d', '$4')} AS candidate
FROM page_segment_derivations d JOIN pages p ON p.id = d.page_id WHERE p.source_id = $1 AND ${derivationSweepScopeSql('d', 'p', '$2')}
+ ), 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 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) });
+ 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
+ ) 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
+ FROM scope s GROUP BY s.page_id ORDER BY s.page_id`, [sourceId, [...pageIds], needles, patterns]);
+ if (recordSweepWork) for (const row of rows) derivationSweepWork.push({ pageId: Number(row.page_id), scanned: Number(row.scanned), normalized: Number(row.normalized), deleted: Number(row.deleted) });
return rows.reduce((n, row) => n + Number(row.deleted), 0);
}
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index 6e669d6fbc..e2471b4494 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -45,6 +45,8 @@ 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.
+ | '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'
// #6712 PR 4b: before each round of a pass reads its level (`round`), and after it read it (`level`: its statements and its
diff --git a/test/helpers/derivation-purge-cases.ts b/test/helpers/derivation-purge-cases.ts
index f9a32d5d03..2d5f6ce4e4 100644
--- a/test/helpers/derivation-purge-cases.ts
+++ b/test/helpers/derivation-purge-cases.ts
@@ -11,7 +11,8 @@ 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, derivationSweepWork, segmentDeriveWork } from '../../src/core/page-body/segment-derive.ts';
+import { __setBeforeDerivationWriteForTests, __setDerivationSweepWorkForTests, 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';
import { forgetFactInFence } from '../../src/core/facts/forget.ts';
import { deriveAll, KINDS, liveOccurrences, resetDeriveWork, storedPage } from './derivation-equivalence-cases.ts';
@@ -51,11 +52,16 @@ async function exactHolders(engine: BrainEngine, pageId: number, text: string):
[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>> {
+/**
+ * Per page of the source: derivation rows no live segment backs (occurrence retired, page inline or soft-deleted), and
+ * whose lowercased output and receipt text match the LIKE `pattern` (ASCII, so lowercasing is the same everywhere).
+ */
+async function unbackedRows(engine: BrainEngine, pattern = '%'): 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]);
+ 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))
+ AND lower(COALESCE(d.output::text,'') || ' ' || COALESCE(d.receipt::text,'')) LIKE $2
+ GROUP BY d.page_id`, [SOURCE, pattern]);
return new Map(rows.map(row => [Number(row.page_id), Number(row.n)]));
}
@@ -197,6 +203,9 @@ export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): void
{ 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 },
+ { name: 'Greek capitals, stored in lowercase with final sigma', claim: 'Ο ΚΩΔΙΚΟΣ ΤΗΣ ΑΠΟΘΗΚΗΣ ΕΙΝΑΙ 3308', planted: 'ο κωδικος της αποθηκης ειναι 3308', n: 4 },
+ { name: 'Greek lowercase with final sigma, stored in capitals', claim: 'ο αριθμος της πορτας ειναι 7719', planted: 'Ο ΑΡΙΘΜΟΣ ΤΗΣ ΠΟΡΤΑΣ ΕΙΝΑΙ 7719', n: 5 },
+ { name: 'Turkish dotted capital I, stored as JavaScript lowercases it', claim: 'İZMİR DEPOSU KODU 5521', planted: 'İZMİR DEPOSU KODU 5521'.toLowerCase(), n: 6 },
]) {
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);
@@ -224,20 +233,58 @@ export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): void
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 worded = await unbackedRows(brain.engine, '%plays%oboe%');
+ __setDerivationSweepWorkForTests(true);
+ let receipt: Record<string, any>;
+ let work: typeof derivationSweepWork;
+ try { receipt = await purge(id); work = [...derivationSweepWork]; } finally { __setDerivationSweepWorkForTests(false); }
+ expect(work.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();
+ .map(([pageId, scanned]) => ({ pageId, scanned, normalized: worded.get(pageId) ?? 0, deleted: pageId === retired.id ? retiredHeld : 0 }));
+ expect(work.filter(w => w.pageId !== target.id)).toEqual(expected);
+ expect(work.find(w => w.pageId === live.id)).toBeUndefined();
+ const others = work.filter(w => w.pageId !== target.id);
+ expect(others.reduce((n, w) => n + w.normalized, 0)).toBe([...worded].filter(([pageId]) => pageId !== target.id).reduce((n, [, k]) => n + k, 0));
+ expect(others.reduce((n, w) => n + w.normalized, 0)).toBeLessThan(others.reduce((n, w) => n + w.scanned, 0));
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([]);
+ 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);
+
+ test('a sweep records no work unless a test asks for it', async () => {
+ const id = await seed('notes/sweep-unrecorded', 'Purge Example shed code is 1186');
+ __setDerivationSweepWorkForTests(false);
+ await purge(id);
+ expect(derivationSweepWork).toEqual([]);
+ }, 600_000);
+
+ test('a statement timeout of the derivation sweep fails the purge with the typed code and purges nothing', async () => {
+ const claim = 'Purge Example safe code is 2093';
+ const holder = await retiredHolder('notes/sweep-timeout-holder', claim, 64);
+ const id = await seed('notes/sweep-timeout', claim);
+ const held = await exactHolders(brain.engine, holder.id, claim);
+ const dry = await brain.call('purge_fact', { id, dry_run: true });
+ let seen = 0;
+ installFaultHook(point => {
+ if (point !== 'purge:derivation_sweep') return;
+ seen++;
+ throw Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' });
+ });
+ let failed: { isError: boolean; body: Record<string, any> };
+ try { failed = await brain.call('purge_fact', { id, confirm: dry.body.confirm_token, expected_revision: dry.body.expected_revision }); }
+ finally { installFaultHook(undefined); }
+ expect(seen).toBe(1);
+ expect({ isError: failed.isError, code: failed.body.error ?? failed.body.code }).toEqual({ isError: true, code: 'purge_lookup_timeout' });
+ expect(failed.body.state).not.toBe('committed');
+ 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);
+ expect(await exactHolders(brain.engine, holder.id, claim)).toEqual(held);
+ const receipt = await purge(id);
+ expect({ rows: await exactHolders(brain.engine, holder.id, claim), receipt: derivationStore(receipt)?.status }).toEqual({ rows: [], receipt: 'deleted' });
}, 600_000);
});
}