Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(purge): batch the derivation sweep and its receipt probe by primary key
garrytan8300325ea97c
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex e9b73776a2..49be2ff727 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1073,6 +1073,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ 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.' },+ { 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.' },];/** 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 5931a8a36f..f3ae62c225 100644--- a/src/core/facts/purge-verify.ts+++ b/src/core/facts/purge-verify.ts@@ -27,7 +27,8 @@ 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, derivationNeedles, derivationSweepScopeSql } from '../page-body/segment-derive.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 { claimForms, quotes, type LedgerPurgeReport } from '../belief/purge.ts';import { CARRYING_FIELDS } from '../belief/keys.ts';@@ -125,21 +126,52 @@ async function segmentTextReport(engine: BrainEngine, sourceId: string, needles:/*** 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.+ * live segment of a page the purge did not rewrite is that page's prose, reported with it. The source's rows are walked+ * in primary-key order, segment-derive.ts derivationBatchRows() per statement, each under the probe's statement bound.*/async function derivationTextReport(engine: BrainEngine, sourceId: string, pageIds: readonly number[], claims: readonly string[], removed: number,deadline: number): Promise<StoreReport> {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 };- 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,+ const unverified = (reason: string): StoreReport => ({ store: 'page_segment_derivations', status: 'unverified', reason, removed });+ let swept = 0, kept = 0;+ let cursor: DerivationKey | null = null;+ for (;;) {+ if (performance.now() > deadline) return unverified('verification_deadline');+ let row: { scanned: number; normalized: number; swept: number; kept: number; last_page: number | null; last_pipeline: string | null; last_occurrence: string | null };+ try {+ row = await engine.transaction(async tx => {+ await tx.executeRaw("SELECT set_config('statement_timeout',$1,true)", [`${probeLimits.statementMs}ms`]);+ const [counted] = await tx.executeRaw<typeof row>(`WITH batch AS MATERIALIZED (+ SELECT d.page_id, d.pipeline, d.occurrence_id, ${derivationSweepScopeSql('d', 'p', '$3')} 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+ ), checked AS MATERIALIZED (+ SELECT b.swept, c.candidate, CASE WHEN c.candidate THEN ${derivationHoldsClaimSql('d', '$2', '$4')} ELSE false END AS hit+ 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+ CROSS 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 (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+ FROM checked`, [sourceId, needles, [...pageIds], patterns, cursor?.[0] ?? null, cursor?.[1] ?? null, cursor?.[2] ?? null, derivationBatchRows()]);+ return counted!;+ });+ } catch (error) {+ if (getCode(error) === '57014') return unverified('statement_deadline');+ throw error;+ }+ recordDerivationStatement({ phase: 'probe', scanned: Number(row.scanned), normalized: Number(row.normalized) });+ swept += Number(row.swept);+ kept += Number(row.kept);+ if (swept > probeLimits.rows || kept > probeLimits.rows) return unverified('row_bound');+ if (Number(row.scanned) < derivationBatchRows()) break;+ cursor = [Number(row.last_page), row.last_pipeline!, String(row.last_occurrence)];+ }+ if (swept) return { store: 'page_segment_derivations', status: 'incomplete', remaining: swept, removed };+ return kept+ ? { store: 'page_segment_derivations', status: 'out_of_scope', reason: 'source_prose', remaining: kept, 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 };}diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.tsindex 3ecc6c8072..91a2574345 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 { sweepDerivationText } from '../page-body/segment-derive.ts';+import { DerivationSweepBudgetExceeded, sweepDerivationText } 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,12 +225,16 @@ 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. */+/**+ * 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> {try { return await fn(); } catch (error) {- if ((error as { code?: unknown } | null)?.code !== '57014') throw error;+ const budget = error instanceof DerivationSweepBudgetExceeded;+ if (!budget && (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. `+ `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. `+ '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'] }) });}diff --git a/src/core/page-body/segment-derive.ts b/src/core/page-body/segment-derive.tsindex 9dd941c25b..2702df85fc 100644--- a/src/core/page-body/segment-derive.ts+++ b/src/core/page-body/segment-derive.ts@@ -413,38 +413,107 @@ export function derivationSweepScopeSql(d: string, p: string, pageIds: string):}/**- * @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.+ * 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 };+/** @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 ?? {}) };+}+/** 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];++/** SQL predicate: row `d` comes after the cursor in the int, text and bigint parameters `at` (all null: the first batch). */+export function derivationAfterSql(d: string, at: [string, string, string]): string {+ return `(${at[0]}::int IS NULL OR (${d}.page_id, ${d}.pipeline, ${d}.occurrence_id) > (${at[0]}::int, ${at[1]}::text, ${at[2]}::bigint))`;+}++/**+ * @internal For the work-volume tests (counts, not time): per page, the derivation rows each sweep read, normalized and+ * deleted; per statement of a sweep or a receipt probe, the rows it read and normalized. Recorded only while+ * __setDerivationSweepWorkForTests(true) is in effect.*/export const derivationSweepWork: Array<{ pageId: number; scanned: number; normalized: number; deleted: number }> = [];+export const derivationSweepStatements: Array<{ phase: 'sweep' | 'probe'; scanned: number; normalized: 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; }+/** @internal Test seam: start (clearing what is there) or stop recording derivationSweepWork and derivationSweepStatements. */+export function __setDerivationSweepWorkForTests(on: boolean): void {+ recordSweepWork = on;+ derivationSweepWork.length = 0;+ derivationSweepStatements.length = 0;+}+/** @internal Records one statement's rows while a test records sweep work. */+export function recordDerivationStatement(entry: { phase: 'sweep' | 'probe'; scanned: number; normalized: number }): void {+ if (recordSweepWork) derivationSweepStatements.push(entry);+}/*** 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 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.+ * 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.*/export async function sweepDerivationText(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, pageIds: readonly number[],claims: readonly string[]): Promise<number> {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 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);+ const { batchRows, totalMs } = 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) });+ }+ 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);+ }+ const sorted = [...pages].sort((a, b) => a[0] - b[0]);+ if (recordSweepWork) for (const [pageId, work] of sorted) derivationSweepWork.push({ pageId, ...work });+ return sorted.reduce((n, [, work]) => n + work.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 2d5f6ce4e4..beaaa948cd 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, __setDerivationSweepWorkForTests, derivationSweepWork, segmentDeriveWork } from '../../src/core/page-body/segment-derive.ts';+import { __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';import { forgetFactInFence } from '../../src/core/facts/forget.ts';@@ -286,5 +287,64 @@ export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): voidconst receipt = await purge(id);expect({ rows: await exactHolders(brain.engine, holder.id, claim), receipt: derivationStore(receipt)?.status }).toEqual({ rows: [], receipt: 'deleted' });}, 600_000);++ /** An inline page whose derivation rows no live segment backs: `holding` state `claim`, `common` more state its words in order. */+ const candidateRowsPage = async (slug: string, claim: string, common: number, holding: number) => {+ await brain.engine.putPage(slug, { type: 'note', title: 'Batch Rows', compiled_truth: 'Batch rows fixture.', timeline: '', frontmatter: {} }, { sourceId: SOURCE });+ const [row] = await brain.engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [SOURCE, slug]);+ const [first, ...rest] = claim.split(' ');+ await brain.engine.executeRaw(`INSERT INTO page_segment_derivations (page_id, pipeline, occurrence_id, pipeline_version, segment_sha256, context_hash, state, output, receipt)+ SELECT $1, 'links', g, 1, decode(repeat('00', 32), 'hex'), decode(repeat('00', 32), 'hex'), 'done',+ jsonb_build_object('candidates', jsonb_build_array(jsonb_build_object('context',+ CASE WHEN g <= $3 THEN 'Note: ' || $4 || ' today' ELSE $5 || ' row ' || g || ' said ' || $6 || ' not' END))), NULL+ FROM generate_series(1, $2::int) g`, [Number(row!.id), common + holding, holding, claim, first, rest.join(' ')]);+ expect(await exactHolders(brain.engine, Number(row!.id), claim)).toHaveLength(holding);+ return Number(row!.id);+ };++ test('a sweep and its receipt walk thousands of candidate rows in statements of bounded rows, and the purge completes', async () => {+ const claim = 'Purge Example hatch code is 6142', batch = 200, common = 1000, holding = 3;+ const rows = await candidateRowsPage('notes/sweep-batch-rows', claim, common, holding);+ const id = await seed('notes/sweep-batch-purge', claim);+ __setDerivationSweepLimitsForTests({ batchRows: batch });+ __setDerivationSweepWorkForTests(true);+ try {+ const receipt = await purge(id);+ const sweeps = derivationSweepStatements.filter(s => s.phase === 'sweep'), probes = derivationSweepStatements.filter(s => s.phase === 'probe');+ expect(Math.max(...sweeps.map(s => s.scanned))).toBe(batch);+ expect(sweeps.length).toBeGreaterThanOrEqual(Math.ceil((common + holding) / batch));+ expect(sweeps.slice(0, -1).every(s => s.scanned === batch) && sweeps.at(-1)!.scanned < batch).toBe(true);+ expect(sweeps.reduce((n, s) => n + s.normalized, 0)).toBeGreaterThanOrEqual(common + holding);+ expect(probes.slice(0, -1).every(s => s.scanned === batch) && probes.at(-1)!.scanned < batch).toBe(true);+ expect(probes.reduce((n, s) => n + s.normalized, 0)).toBeGreaterThanOrEqual(common);+ expect(await exactHolders(brain.engine, rows, claim)).toEqual([]);+ expect((await brain.engine.readSegmentDerivations(rows)).length).toBe(common);+ complete(receipt);+ expect(derivationStore(receipt)?.status).toBe('deleted');+ } finally {+ __setDerivationSweepLimitsForTests(null);+ __setDerivationSweepWorkForTests(false);+ }+ }, 600_000);++ test('a sweep past its overall budget fails the purge with the typed code and purges nothing', 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 });+ __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]);+ } 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);});}