Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

lane 4a round 9: probe residuals re-open the sweep, bounded sweep end, isolated sweep tests

garrytan72907b37e595
diff --git a/src/commands/doctor/checks/derivation-purge-sweeps.ts b/src/commands/doctor/checks/derivation-purge-sweeps.ts
index 8666817785..79108a1c66 100644
--- a/src/commands/doctor/checks/derivation-purge-sweeps.ts
+++ b/src/commands/doctor/checks/derivation-purge-sweeps.ts
@@ -40,7 +40,7 @@ async function runDerivationPurgeSweeps(ctx: DoctorContext): Promise<Check[]> {
+ 'Until each ends, paid atom, synopsis and fact extraction makes no call on the pages it covers (purge_sweep_pending). '
+ `Continue each with gbrain forget --purge --status --request-id <request_id> --continue.`,
...(first ? { fix: { argv: continueSweepArgv(first), consent: [], actor: 'agent' as const, requires_exclusive: false, verify: doctorVerify('derivation_purge_sweeps'),
- why: 'Continues the purge\'s sweep (a stalled one is tried again) and reports its completion; it deletes only stored results holding the claim the user already purged. Run it once per request id listed.' } }
+ why: 'Continues the purge\'s sweep (a stalled one is tried again) and reports its completion. It deletes the stored results in the sweep\'s scope that hold the claim the user already purged, and an unpaid result in that scope that alone cannot be read within the statement budget, unread, whether or not it holds the claim (unpaid results are derived again from the page at no cost; a paid one is never deleted unread). Run it for each request id listed until its completion is complete.' } }
: { fix_unavailable_reason: 'operator_judgement' as const }),
});
return checks;
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 44a9018a47..823ebda673 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1078,6 +1078,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ 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).' },
{ since: 'TBD', text: 'A fact purge\'s sweep of stored link, mention, timeline and fence results no longer stops for good on large results: a batch that runs past its 5-second statement budget is retried in half as many results, down to one, and a single result that still runs past it is deleted without being read (stored results are rebuilt from the page). Only when even that delete runs past the budget does the sweep stop; its receipt then says `derivation_sweep: stalled`, and other sweeps in the source go on. A purge now sweeps for its own claim first, so an earlier slow sweep no longer holds it back. `gbrain forget --purge --status --request-id <id> --continue` (new) continues a pending or stalled sweep after the fact is gone, and the receipt\'s `next` names it. Before a sweep ends it walks the stored results again until a walk deletes nothing, and walks again the pages where a result entered its scope meanwhile (a segment replaced, a page deleted), so no result holding the claim is left behind. While a sweep is pending, paid atom, synopsis and fact extraction makes no call on a page it covers (receipts say `purge_sweep_pending`), instead of paying again for results the sweep would refuse to store.' },
{ since: 'TBD', text: 'A fact purge now returns once it has recorded the sweep of stored link, mention, timeline and fence results and run it for up to 5 seconds, instead of up to two minutes; when the sweep has not finished by then, the receipt says `derivation_sweep: pending` (exit 75) and `gbrain forget --purge --status --request-id <id> --continue` finishes it. A sweep never deletes a stored atom, synopsis or conversation-fact result without reading it: when one alone runs past the statement budget, the sweep stops with `derivation_sweep: stalled` and `derivation_sweep_reason: paid_row_unreadable`; a result whose page was restored while the sweep was deleting it unread is kept. A sweep no longer ends while a page delete or segment replacement that brought a result into its scope is still uncommitted; it checks that page after the write commits. When the receipt\'s check of stored results runs out of time after the purge\'s own sweep finished verified, the store reports the sweep\'s result (`reason: verified_by_sweep`, with `probe` naming the deadline) instead of `unverified`. New doctor check `derivation_purge_sweeps` names each pending or stalled sweep with its request id and the command that continues it. Doctor `extraction_input_truncated` reports atom, synopsis and fact receipts a pending sweep blocked as `purge_sweep_pending`, pointing at that check instead of `derive.max_usd_per_page`, and a per-chunk synopsis re-embed job a sweep blocked no longer reports `ok`.' },
+ { since: 'TBD', text: 'When a fact purge\'s receipt check counts a stored link, mention, timeline or fence result still holding the claim, it now reports it even if it then runs out of time: a result the sweep covers makes `page_segment_derivations` `incomplete` (with `probe` naming where it stopped) instead of `verified_by_sweep`. A result found after the purge\'s sweep had already ended records that sweep again, so the receipt says `derivation_sweep: pending` and `gbrain forget --purge --status --request-id <id> --continue` deletes it. A sweep that reaches its end while a page delete or segment replacement in the source is still uncommitted no longer starts its walk over: it waits up to 1.5 seconds for those writes (writes that arrive meanwhile wait behind it, briefly), then ends after checking only the pages they touched; when they are still open after that, a later call tries again, so steady imports no longer keep a sweep from ending. A sweep also waits for writes that were already open when the purge recorded it before it starts its verifying walk, so one that commits during that walk can no longer leave a result holding the claim behind. Doctor `derivation_purge_sweeps` now says that continuing a sweep can also delete, without reading it, an unpaid stored result in its scope that is too large to read within the statement budget.' },
// GBRA-159 visibility hotfix.
{ since: '0.60.341.0', text: 'Nothing derived from a private page is stored wider than the page. Facts extracted from a `visibility: private` page are private even when `facts.default_visibility` is world (before, a fact with no fence page was then returned to remote callers by recall and the entity card), and a page marked private only by `access: private|restricted|confidential` or `confidentiality: confidential|secret|private|restricted` counts as private for its facts, chronicle events, timeline rows and remember saves. `remember` without a `visibility` now saves private when its target page is private or `facts.default_visibility` is explicitly private; otherwise the default stays world. Google Calendar events marked private or confidential sync as `visibility: private` pages, and a connector re-render keeps a page\'s private label. Remote page reads honor the privacy aliases only after `gbrain config set visibility.honor_aliases true`.' },
{ since: '0.60.341.0', text: 'Doctor `derived_visibility` also reports pages that carry a privacy alias but no `visibility`, chronicle events of a private origin, and world facts held in or extracted from a private page (fact ids a remote caller can read today are listed). `gbrain repair visibility` previews all of them and, with `--apply` only, makes them private; nothing runs on upgrade.' },
diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.ts
index 23ce637128..d2871475be 100644
--- a/src/core/facts/purge-verify.ts
+++ b/src/core/facts/purge-verify.ts
@@ -130,19 +130,27 @@ async function segmentTextReport(engine: BrainEngine, sourceId: string, needles:
* 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; a
* statement that outruns it is read again in half as many rows, down to one row, and a single row that still outruns it
- * leaves the store unverified. When the purge's own sweep already ended verified (`sweepVerified`: its record is gone,
- * removed only after a walk that deleted nothing), a probe stopped by a deadline reports the sweep's result instead,
- * with the deadline it hit as `probe`.
+ * leaves the store unverified. A probe that stops (a deadline or its row bound) after a statement counted a row holding
+ * the claim reports what it found, the stop as `probe`: a row the sweep covers makes the store `incomplete`, a row of a
+ * live segment of another page `out_of_scope`. Only when no statement that ran counted one and the purge's own sweep
+ * already ended verified (`sweepVerified`: its record is gone, removed only after a walk that deleted nothing) does a
+ * probe stopped by a deadline report the sweep's result instead, with the deadline it hit as `probe`.
*/
async function derivationTextReport(engine: BrainEngine, sourceId: string, pageIds: readonly number[], claims: readonly string[], removed: number,
deadline: number, sweepVerified: boolean): Promise<StoreReport> {
const { needles, patterns } = await derivationNeedles(engine, claims);
if (!needles.length) return { store: 'page_segment_derivations', status: removed ? 'deleted' : 'not_present', removed };
- const unverified = (reason: string): StoreReport => sweepVerified && reason !== 'row_bound'
- ? { store: 'page_segment_derivations', status: removed ? 'deleted' : 'not_present', removed, reason: 'verified_by_sweep', probe: reason,
- detail: `The receipt's probe stopped at its deadline (${reason}); the purge's sweep had already verified that no stored result it covers holds the claim. Results of live segments of other pages that still state it are listed under pages.` }
- : { store: 'page_segment_derivations', status: 'unverified', reason, removed };
let swept = 0, kept = 0;
+ const unverified = (reason: string): StoreReport => {
+ if (swept) return { store: 'page_segment_derivations', status: 'incomplete', remaining: swept, removed, probe: reason,
+ detail: `The receipt's probe stopped (${reason}) after it counted ${swept} stored result(s) the sweep covers still holding the claim; there may be more.` };
+ if (kept) return { store: 'page_segment_derivations', status: 'out_of_scope', reason: 'source_prose', remaining: kept, removed, probe: reason,
+ detail: `The receipt's probe stopped (${reason}) after it counted ${kept} derivation(s) of live segments of pages the purge did not rewrite that hold the text their prose still states; they are listed under pages.` };
+ return sweepVerified && reason !== 'row_bound'
+ ? { store: 'page_segment_derivations', status: removed ? 'deleted' : 'not_present', removed, reason: 'verified_by_sweep', probe: reason,
+ detail: `The receipt's probe stopped at its deadline (${reason}) before any statement that ran counted a stored result holding the claim; the purge's sweep had already verified that no stored result it covers holds it. Results of live segments of other pages that still state it are listed under pages.` }
+ : { store: 'page_segment_derivations', status: 'unverified', reason, removed };
+ };
let cursor: DerivationKey | null = null;
let rows = derivationBatchRows();
for (;;) {
diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.ts
index 6f1fe68d60..1f3194d8d7 100644
--- a/src/core/facts/purge.ts
+++ b/src/core/facts/purge.ts
@@ -594,8 +594,12 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Rec
appendPurgeCommitted(row.id);
counts.page_segment_derivations = (counts.page_segment_derivations ?? 0) + await continueDerivationPurges(ctx.engine, p.sourceId, { first: row.id, inline: true });
if (beliefReport.appended || ledger?.derived_hidden) await markBeliefCommits(ctx.engine, [row.id]).catch(() => undefined);
+ const sweepVerified = !await derivationPurgeState(ctx.engine, row.id);
const receipt: PurgeReceipt = await verifyFactPurge(ctx.engine, { target, plan: committedPlan, dryRun: false, removed: counts, prose,
- vacuum: params.vacuum === true, ledger, sweepVerified: !await derivationPurgeState(ctx.engine, row.id) });
+ vacuum: params.vacuum === true, ledger, sweepVerified });
+ if (sweepVerified && receipt.stores.some(s => s.store === 'page_segment_derivations' && s.status === 'incomplete')) {
+ await recordDerivationPurge(ctx.engine, row.id, p.sourceId, committedPlan.pages.map(page => page.page_id), [target.fact, escapeFenceCell(target.fact)]);
+ }
return { ...receipt, purge: (row.outcome as { purge?: unknown } | null)?.purge, request_id: row.request_id, state: row.state, similar_active: similar,
...await purgeCompletion(ctx.engine, row as WriteRequest, receipt) };
}
diff --git a/src/core/page-body/schema.ts b/src/core/page-body/schema.ts
index 67fe89be20..b73fba75d4 100644
--- a/src/core/page-body/schema.ts
+++ b/src/core/page-body/schema.ts
@@ -228,9 +228,10 @@ export function derivationSweepScopeSql(d: string, p: string, pageIds: string):
/**
* SQL: the advisory lock key that serializes a write bringing a row into a derivation sweep's scope with the end of the
* source's sweeps. The scope-entry trigger takes it shared in the writer's transaction every time it fires, a sweep
- * recorded or not, and a sweep ends (deletes its record) only under it taken exclusively without waiting: while such a
- * writer is open, including one that fired before the sweep was recorded and so left no note, the sweep walks again
- * instead of ending, and the walk after the writer commits sees its rows.
+ * recorded or not. A sweep moves from its first walk to its verify walks, and ends (deletes its record), only under it
+ * held exclusively: so every writer that fired before the sweep was recorded, and left no note, has committed before a
+ * verify walk starts, and every later writer's note is visible when the record ends. The sweep tries it without waiting
+ * and otherwise waits a bounded time in a transaction that holds no other lock (segment-derive.ts continueDerivationPurges).
*/
export function derivationScopeLockSql(sourceId: string): string {
return `hashtextextended('gbrain:derivation-scope:' || ${sourceId}, 0)`;
diff --git a/src/core/page-body/segment-derive.ts b/src/core/page-body/segment-derive.ts
index 2a02123946..e1b54d4336 100644
--- a/src/core/page-body/segment-derive.ts
+++ b/src/core/page-body/segment-derive.ts
@@ -370,10 +370,11 @@ export async function derivationNeedles(engine: Pick<BrainEngine, 'executeRaw'>,
* the source, walking them in primary-key order (so the rows it normalizes are bounded too), fewer after a statement
* outran `statementMs` (the batch halves, down to one row); a sweep statement runs in a transaction of its own under
* `statementMs`; one continueDerivationPurges call starts no new batch past `totalMs` (`inlineMs` for the call a
- * purge makes before it returns; it runs at least one), and the next call resumes from the stored cursor.
+ * purge makes before it returns; it runs at least one), and the next call resumes from the stored cursor. A walk that
+ * ends while a writer holds the source's scope lock waits at most `finalizeWaitMs` for it before leaving it to a later call.
*/
-export const DERIVATION_SWEEP_LIMITS = { batchRows: 500, totalMs: 120_000, statementMs: 5_000, inlineMs: 5_000 } as const;
-let sweepLimits: { batchRows: number; totalMs: number; statementMs: number; inlineMs: number } = { ...DERIVATION_SWEEP_LIMITS };
+export const DERIVATION_SWEEP_LIMITS = { batchRows: 500, totalMs: 120_000, statementMs: 5_000, inlineMs: 5_000, finalizeWaitMs: 1_500 } as const;
+let sweepLimits: { batchRows: number; totalMs: number; statementMs: number; inlineMs: number; finalizeWaitMs: 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; }
@@ -476,11 +477,19 @@ type SweepRecord = { request_id: string; needles: string[]; patterns: string[];
* record is skipped from then on, so it blocks no other sweep, until `opts.retry` names it.
*
* At the end of the source the first walk (`sweep`) is followed by a `verify` walk, repeated until one deletes nothing;
- * then the pages that entered the scope meanwhile (page_segment_derivation_purge_pages) are walked again (`recheck`)
- * until none are noted, and only then is the record deleted: under the source's scope lock (derivationScopeLockSql),
- * taken without waiting. While a write that brings rows into the scope is still open (the trigger holds the lock shared,
- * also when it fired before the sweep was recorded and left no note), the record goes back to a fresh `verify` walk
- * for a later call, which sees the writer's rows once it commits. No batch starts past DERIVATION_SWEEP_LIMITS.totalMs (the lower `inlineMs` for the
+ * then the pages that entered the scope meanwhile (page_segment_derivation_purge_pages) are checked again, and only
+ * when none of their rows the sweep covers holds the claim is the record deleted. A writer that brings rows into the
+ * scope holds the source's scope lock (derivationScopeLockSql) shared from the trigger's first firing to its commit,
+ * and leaves no note when it fired before the sweep was recorded. So both the move from the first walk to `verify`
+ * (every writer open when the sweep was recorded has ended, and every verify walk sees its rows) and the end of the
+ * record (every noted page is visible) happen under that lock held exclusively. It is tried without waiting at the end
+ * of a walk; when a writer holds it, the record waits at the end of its walk (its cursor kept) and the call waits for
+ * the lock at most DERIVATION_SWEEP_LIMITS.finalizeWaitMs in a transaction of its own that holds no other lock, so no
+ * deadlock is possible and writers that arrive meanwhile queue behind it. Holding it, the rest of the walk is read
+ * without deleting (a row lock is never awaited under it) and, when none of it holds the claim, the walk ends there;
+ * the noted pages are read the same way, and walked again (`recheck`) only when one holds the claim or they hold more
+ * than a batch of rows. A wait that times out leaves the record where it is for a later call; no walk restarts.
+ * No batch starts past DERIVATION_SWEEP_LIMITS.totalMs (the lower `inlineMs` for the
* purge's own call, `opts.inline`, so a purge returns `pending` soon after it recorded the sweep); the next call resumes
* from the cursor. Returns the rows deleted.
*/
@@ -490,27 +499,68 @@ export async function continueDerivationPurges(engine: BrainEngine, sourceId: st
const pages = new Map<number, { scanned: number; normalized: number; deleted: number }>();
if (opts.retry) await engine.executeRaw('UPDATE page_segment_derivation_purges SET stalled_at = NULL, stalled_reason = NULL WHERE request_id=$1::uuid', [opts.retry]);
const skip: string[] = [];
- const endWalk = async (tx: BrainEngine, purge: SweepRecord, found: number) => {
- const restart = 'cursor_page = NULL, cursor_pipeline = NULL, cursor_occurrence = NULL, found = 0';
- if (purge.phase === 'sweep' || (purge.phase === 'verify' && found > 0)) {
- await tx.executeRaw('DELETE FROM page_segment_derivation_purge_pages WHERE request_id=$1::uuid', [purge.request_id]);
- await tx.executeRaw(`UPDATE page_segment_derivation_purges SET phase = 'verify', recheck = NULL, ${restart} WHERE request_id=$1::uuid`, [purge.request_id]);
- return;
- }
- const [lock] = await tx.executeRaw<{ held: boolean }>(`SELECT pg_try_advisory_xact_lock(${derivationScopeLockSql('$1::text')}) AS held`, [sourceId]);
- if (!lock?.held) {
- await tx.executeRaw(`UPDATE page_segment_derivation_purges SET phase = 'verify', recheck = NULL, ${restart} WHERE request_id=$1::uuid`, [purge.request_id]);
- skip.push(purge.request_id);
- return;
- }
+ const restart = 'cursor_page = NULL, cursor_pipeline = NULL, cursor_occurrence = NULL, found = 0';
+ const toVerify = async (tx: BrainEngine, purge: SweepRecord) => {
+ await tx.executeRaw('DELETE FROM page_segment_derivation_purge_pages WHERE request_id=$1::uuid', [purge.request_id]);
+ await tx.executeRaw(`UPDATE page_segment_derivation_purges SET phase = 'verify', recheck = NULL, ${restart} WHERE request_id=$1::uuid`, [purge.request_id]);
+ };
+ /** Read-only: whether at most the record's batch size of rows after `at` (on `onPages`; every page when null) are all there are, and how many the sweep covers hold the claim. */
+ const unswept = async (tx: BrainEngine, purge: SweepRecord, at: [number | null, string | null, string | null], onPages: number[] | null) => {
+ const [row] = await tx.executeRaw<{ scanned: number; hits: number }>(`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'])} AND ($9::int[] IS NULL OR d.page_id = ANY($9::int[]))
+ ORDER BY d.page_id, d.pipeline, d.occurrence_id LIMIT $8
+ ) SELECT (SELECT count(*)::int FROM batch) AS scanned, count(*) FILTER (WHERE CASE WHEN ${derivationClaimCandidateSql('d', '$4')}
+ THEN ${derivationHoldsClaimSql('d', '$3', '$4')} ELSE false END)::int AS hits
+ 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`,
+ [sourceId, purge.page_ids, purge.needles, purge.patterns, ...at, purge.batch_rows, onPages]);
+ return { all: Number(row?.scanned ?? 0) < Number(purge.batch_rows), hits: Number(row?.hits ?? 0) };
+ };
+ /** The end of a walk, under the source's scope lock held exclusively. */
+ const finish = async (tx: BrainEngine, purge: SweepRecord) => {
+ if (purge.phase === 'sweep') return toVerify(tx, purge);
const noted = (await tx.executeRaw<{ page_id: number }>('DELETE FROM page_segment_derivation_purge_pages WHERE request_id=$1::uuid RETURNING page_id',
[purge.request_id])).map(row => Number(row.page_id));
- if (noted.length) await tx.executeRaw(`UPDATE page_segment_derivation_purges SET phase = 'recheck', recheck = $2::int[], ${restart} WHERE request_id=$1::uuid`,
- [purge.request_id, noted]);
- else {
- await tx.executeRaw('DELETE FROM page_segment_derivation_purges WHERE request_id=$1::uuid', [purge.request_id]);
- await tx.executeRaw(`DELETE FROM page_segment_derivation_purge_pages n WHERE NOT EXISTS (SELECT 1 FROM page_segment_derivation_purges x
- WHERE x.request_id = n.request_id)`);
+ if (noted.length) {
+ const check = await unswept(tx, purge, [null, null, null], noted);
+ if (!check.all || check.hits) {
+ await tx.executeRaw(`UPDATE page_segment_derivation_purges SET phase = 'recheck', recheck = $2::int[], ${restart} WHERE request_id=$1::uuid`, [purge.request_id, noted]);
+ return;
+ }
+ }
+ await tx.executeRaw('DELETE FROM page_segment_derivation_purges WHERE request_id=$1::uuid', [purge.request_id]);
+ await tx.executeRaw(`DELETE FROM page_segment_derivation_purge_pages n WHERE NOT EXISTS (SELECT 1 FROM page_segment_derivation_purges x
+ WHERE x.request_id = n.request_id)`);
+ };
+ let parked: string | null = null;
+ const endWalk = async (tx: BrainEngine, purge: SweepRecord, found: number, last: [number, string, string] | null) => {
+ if (purge.phase === 'verify' && found > 0) return toVerify(tx, purge);
+ const [lock] = await tx.executeRaw<{ held: boolean }>(`SELECT pg_try_advisory_xact_lock(${derivationScopeLockSql('$1::text')}) AS held`, [sourceId]);
+ if (lock?.held) return finish(tx, purge);
+ await tx.executeRaw(`UPDATE page_segment_derivation_purges SET cursor_page = COALESCE($2::int, cursor_page), cursor_pipeline = COALESCE($3::text, cursor_pipeline),
+ cursor_occurrence = COALESCE($4::bigint, cursor_occurrence), found = $5 WHERE request_id=$1::uuid`, [purge.request_id, ...(last ?? [null, null, null]), found]);
+ parked = purge.request_id;
+ };
+ /** A record waiting at the end of its walk: wait for the scope lock (holding no other), then end the walk if the rest of it holds nothing to sweep. */
+ const finishParked = async (requestId: string) => {
+ try {
+ await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('statement_timeout',$1,true), set_config('lock_timeout',$2,true)", [`${statementMs}ms`, `${sweepLimits.finalizeWaitMs}ms`]);
+ await tx.executeRaw(`SELECT pg_advisory_xact_lock(${derivationScopeLockSql('$1::text')})`, [sourceId]);
+ const [purge] = await tx.executeRaw<SweepRecord>(`SELECT request_id::text AS request_id, needles, patterns, page_ids, phase, recheck, found, cursor_page,
+ cursor_pipeline, cursor_occurrence::text AS cursor_occurrence, LEAST(COALESCE(batch_rows, $2), $2) AS batch_rows
+ FROM page_segment_derivation_purges WHERE request_id=$1::uuid AND stalled_at IS NULL FOR UPDATE SKIP LOCKED`, [requestId, maxRows]);
+ if (!purge) {
+ skip.push(requestId);
+ return;
+ }
+ const rest = await unswept(tx, purge, [purge.cursor_page, purge.cursor_pipeline, purge.cursor_occurrence], purge.recheck);
+ if (rest.all && !rest.hits) await finish(tx, purge);
+ });
+ } catch (error) {
+ const code = (error as { code?: unknown } | null)?.code;
+ if (code !== '55P03' && code !== '57014') throw error;
+ skip.push(requestId);
}
};
const timedOut = (error: unknown) => (error as { code?: unknown } | null)?.code === '57014';
@@ -520,6 +570,7 @@ export async function continueDerivationPurges(engine: BrainEngine, sourceId: st
};
for (let batches = 0; batches === 0 || performance.now() <= deadline; batches++) {
let picked: SweepRecord | null = null;
+ parked = null;
type Row = { page_id: number | null; swept: number; normalized: number; deleted: number; scanned: number; last_page: number; last_pipeline: string; last_occurrence: string };
let rows: Row[] | 'paid' | null;
try {
@@ -558,7 +609,9 @@ export async function continueDerivationPurges(engine: BrainEngine, sourceId: st
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, purge.batch_rows, purge.recheck]);
const found = Number(purge.found) + batch.reduce((n, row) => n + Number(row.deleted), 0);
- if (Number(batch[0]?.scanned ?? 0) < Number(purge.batch_rows)) await endWalk(tx, purge, found);
+ if (Number(batch[0]?.scanned ?? 0) < Number(purge.batch_rows)) {
+ await endWalk(tx, purge, found, batch[0]?.last_page == null ? null : [Number(batch[0].last_page), batch[0].last_pipeline, String(batch[0].last_occurrence)]);
+ }
else await tx.executeRaw(`UPDATE page_segment_derivation_purges SET cursor_page=$2, cursor_pipeline=$3, cursor_occurrence=$4::bigint, found=$5
WHERE request_id=$1::uuid`, [purge.request_id, Number(batch[0]!.last_page), batch[0]!.last_pipeline, String(batch[0]!.last_occurrence), found]);
return batch;
@@ -580,7 +633,7 @@ export async function continueDerivationPurges(engine: BrainEngine, sourceId: st
ORDER BY d.page_id, d.pipeline, d.occurrence_id LIMIT 1`,
[sourceId, purge.page_ids, purge.cursor_page, purge.cursor_pipeline, purge.cursor_occurrence, purge.recheck]);
if (!next) {
- await endWalk(tx, purge, Number(purge.found));
+ await endWalk(tx, purge, Number(purge.found), null);
return [];
}
if (next.swept && !UNPAID_PIPELINES.includes(next.pipeline)) return 'paid' as const;
@@ -612,6 +665,7 @@ export async function continueDerivationPurges(engine: BrainEngine, sourceId: st
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 (parked) await finishParked(parked);
}
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/test/helpers/derivation-purge-cases.ts b/test/helpers/derivation-purge-cases.ts
index 37ea5284d3..910ee81d94 100644
--- a/test/helpers/derivation-purge-cases.ts
+++ b/test/helpers/derivation-purge-cases.ts
@@ -7,12 +7,12 @@
*
* test/large-pages/derivation-purge.test.ts runs them on PGLite; test/e2e/derivation-purge-postgres.test.ts on PostgreSQL.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, 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 { __setAfterDerivationSweepBatchForTests, __setBeforeDerivationWriteForTests, __setBeforeUnreadDerivationDeleteForTests, __setDerivationSweepLimitsForTests,
- __setDerivationSweepWorkForTests, continueDerivationPurges, DERIVATION_SWEEP_LIMITS, derivationPurgeState, derivationSweepStatements, derivationSweepWork,
+ __setDerivationSweepWorkForTests, continueDerivationPurges, derivationPurgeState, derivationSweepStatements, derivationSweepWork,
segmentDeriveWork } from '../../src/core/page-body/segment-derive.ts';
import { installFaultHook } from '../../src/core/persistence/fault-points.ts';
import { __setPurgeProbeLimitsForTests } from '../../src/core/facts/purge-verify.ts';
@@ -78,11 +78,12 @@ async function unbackedRows(engine: BrainEngine, pattern = '%'): Promise<Map<num
export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): void {
describe(`purge leaves no derivation row holding the claim (${kind})`, () => {
let brain: AppendBrain;
- beforeAll(async () => {
+ // A brain of its own per test: no test's sweep walks, or waits on, rows and sweeps an earlier test left in the source.
+ beforeEach(async () => {
brain = await openAppendBrain(kind);
await brain.engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Alice Example fixture.', timeline: '', frontmatter: {} }, { sourceId: SOURCE });
}, 600_000);
- afterAll(() => brain.close(), 120_000);
+ afterEach(() => brain.close(), 120_000);
const seed = async (slug: string, claim: string) => {
await brain.seed(slug, purgePage(claim));
@@ -346,9 +347,39 @@ export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): void
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() };
};
+ /** Continues purge request `requestId`'s derivation sweep through --status --continue until it is no longer pending (each call runs at least one batch); the last status. */
+ const continueToEnd = async (requestId: string) => {
+ let status: Record<string, any> = {};
+ for (let calls = 0; calls < 1000; calls++) {
+ status = (await brain.call('purge_fact', { status: true, request_id: requestId, continue: true })).body;
+ if (status.derivation_sweep !== 'pending') break;
+ }
+ return status;
+ };
+ /**
+ * Derivation rows of the source holding `text` byte for byte that a sweep of a purge of page `purged` covers: rows of that page, of a soft-deleted
+ * page, or that no live segment backs.
+ */
+ const sweptHolders = async (text: string, purged: string) => 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 AND (strpos(COALESCE(d.output::text,''),$2)>0 OR strpos(COALESCE(d.receipt::text,''),$2)>0)
+ AND (p.slug=$3 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))`, [SOURCE, text, purged]))[0]!.n);
+ /**
+ * A purge of page `purged` whose derivation sweep --continue finished (`status`, continueToEnd): no store of its receipt is incomplete but the
+ * sweep's own (the derivations and the sweep's record, while it was pending), the sweep ended with the purge's completion not incomplete, and no
+ * derivation row the sweep covers holds `claim`.
+ */
+ const completeAfterSweep = async (receipt: Record<string, any>, status: Record<string, any>, claim: string, purged: string) => {
+ expect((receipt.stores as Array<{ store: string; status: string }>).filter(s => s.status === 'incomplete'
+ && !['page_segment_derivations', 'page_segment_derivation_purges'].includes(s.store))).toEqual([]);
+ expect({ sweep: status.derivation_sweep, completion: status.completion === 'incomplete' ? 'incomplete' : 'settled', holders: await sweptHolders(claim, purged) })
+ .toEqual({ sweep: undefined, completion: 'settled', holders: 0 });
+ };
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;
+ // A batch of rows ahead of the holders in key order, so the first call's one batch leaves them for a replay.
+ await candidateRowsPage('notes/sweep-budget-pad', 'Purge Example padding row is 0006', batch, 0);
const rows = await candidateRowsPage('notes/sweep-budget-rows', claim, 600, holding);
const id = await seed('notes/sweep-budget-purge', claim);
const params = await confirmed(id);
@@ -398,8 +429,11 @@ export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): void
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 {
+ let receipt: Record<string, any>, status: Record<string, any>;
+ try {
+ receipt = await purge(id);
+ status = await continueToEnd(receipt.request_id);
+ } finally {
__setAfterDerivationSweepBatchForTests(null);
__setDerivationSweepLimitsForTests(null);
__setDerivationSweepWorkForTests(false);
@@ -407,8 +441,7 @@ export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): void
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();
+ await completeAfterSweep(receipt!, status!, claim, 'notes/sweep-behind-purge');
}, 600_000);
test('writes to other pages of the source commit while a sweep walks a large source', async () => {
@@ -424,8 +457,12 @@ export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): void
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 = derivationSweepStatements.filter(s => s.phase !== 'probe').length; } finally {
+ let receipt: Record<string, any>, status: Record<string, any>, statements = 0;
+ try {
+ receipt = await purge(id);
+ status = await continueToEnd(receipt.request_id);
+ statements = derivationSweepStatements.filter(s => s.phase !== 'probe').length;
+ } finally {
__setAfterDerivationSweepBatchForTests(null);
__setDerivationSweepLimitsForTests(null);
__setDerivationSweepWorkForTests(false);
@@ -435,7 +472,7 @@ export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): void
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!);
+ await completeAfterSweep(receipt!, status!, claim, 'notes/sweep-writer-purge');
}, 600_000);
test('a sweep call starts no batch past its deadline, also after the last short batch of a sweep', async () => {
@@ -482,13 +519,14 @@ export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): void
__setDerivationSweepWorkForTests(true);
try {
const receipt = await purge(id);
+ const status = await continueToEnd(receipt.request_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);
+ await completeAfterSweep(receipt, status, claim, 'notes/sweep-bounded-purge');
} finally {
__setDerivationSweepLimitsForTests(null);
__setDerivationSweepWorkForTests(false);
@@ -518,18 +556,15 @@ export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): void
rounds.push(Number(detail.round));
if (Number(detail.round) > fits) throw timeout();
});
- // The purge's own call gets the full sweep budget here, so the halving runs to the end within it.
- __setDerivationSweepLimitsForTests({ inlineMs: DERIVATION_SWEEP_LIMITS.totalMs });
- let receipt: Record<string, any>;
- try { receipt = await purge(id); } finally {
- installFaultHook(undefined);
- __setDerivationSweepLimitsForTests(null);
- }
+ let receipt: Record<string, any>, status: Record<string, any>;
+ try {
+ receipt = await purge(id);
+ status = await continueToEnd(receipt.request_id);
+ } finally { installFaultHook(undefined); }
expect(rounds.slice(0, 7)).toEqual([500, 250, 125, 62, 31, 15, 7]);
expect(rounds.slice(7).every(r => r <= 7)).toBe(true);
- expect({ rows: await exactHolders(brain.engine, rows, claim), sweep: receipt!.derivation_sweep, completion: receipt!.completion, recorded: await sweepsRecorded() })
- .toEqual({ rows: [], sweep: undefined, completion: receipt!.completion === 'complete' ? 'complete' : 'committed', recorded: 0 });
- complete(receipt!);
+ expect({ rows: await exactHolders(brain.engine, rows, claim), recorded: await sweepsRecorded() }).toEqual({ rows: [], recorded: 0 });
+ await completeAfterSweep(receipt!, status!, claim, 'notes/sweep-big-purge');
}, 600_000);
test('a row that alone outruns the budget stalls its sweep without blocking a later purge, and --status --continue finishes it once it fits', async () => {
@@ -583,17 +618,19 @@ export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): void
const res = await brain.call('append_page', { slug: 'notes/sweep-enter-live', text: 'Appended note: nothing more.\n', region: 'truth', request_id: randomUUID() });
expect(res).toMatchObject({ isError: false });
});
- let receipt: Record<string, any>;
- try { receipt = await purge(id); } finally {
+ let receipt: Record<string, any>, status: Record<string, any>;
+ try {
+ receipt = await purge(id);
+ status = await continueToEnd(receipt.request_id);
+ } finally {
__setAfterDerivationSweepBatchForTests(null);
__setDerivationSweepLimitsForTests(null);
}
expect(appended).toBe(true);
const occurrences = await liveOccurrences(brain.engine, live.id);
expect(held.filter(row => occurrences.has(row.occurrence_id))).toEqual([]);
- expect({ rows: await exactHolders(brain.engine, live.id, planted), sweep: receipt!.derivation_sweep, recorded: await sweepsRecorded() })
- .toEqual({ rows: [], sweep: undefined, recorded: 0 });
- complete(receipt!);
+ expect({ rows: await exactHolders(brain.engine, live.id, planted), recorded: await sweepsRecorded() }).toEqual({ rows: [], recorded: 0 });
+ await completeAfterSweep(receipt!, status!, claim, 'notes/sweep-enter-purge');
}, 600_000);
test('a paid pipeline makes no call on a page a pending purge sweep covers, so a second run repeats no paid window', async () => {
@@ -798,5 +835,179 @@ export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): void
const [clear] = await derivationPurgeSweepsEntry.run({ engine: brain.engine } as never) as Array<Record<string, any>>;
expect(clear!.status).toBe('ok');
}, 600_000);
+
+ test('a row holding the claim that the receipt probe counts after the sweep ended is reported, never covered by the sweep\'s verification, and --continue sweeps it', async () => {
+ const claim = 'Purge Example vault code is 7716', planted = 'Late: Purge Example vault code is 7716';
+ const late = await candidateRowsPage('notes/probe-late-rows', 'Purge Example padding row is 0003', 30, 0);
+ await candidateRowsPage('notes/probe-late-pad', 'Purge Example padding row is 0004', 30, 0);
+ const params = await confirmed(await seed('notes/probe-late-purge', claim));
+ let plantedRows = 0, probes = 0;
+ // Once the sweep has ended (its record is gone) a writer stores a row holding the claim first in key order, so the probe's first statement counts it.
+ __setAfterDerivationSweepBatchForTests(async () => {
+ if (plantedRows || await sweepsRecorded()) return;
+ plantedRows = (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', 0, 1, decode(repeat('00', 32), 'hex'), decode(repeat('00', 32), 'hex'), 'done',
+ jsonb_build_object('candidates', jsonb_build_array(jsonb_build_object('context', $2::text))), NULL) RETURNING 1`, [late, planted])).length;
+ });
+ // Every later probe statement outruns its budget, down to a single row: the probe stops at statement_deadline.
+ installFaultHook(point => { if (point === 'purge:derivation_probe' && probes++ > 0) throw timeout(); });
+ __setDerivationSweepLimitsForTests({ batchRows: 10 });
+ let first: Record<string, any>;
+ try { first = (await brain.call('purge_fact', params)).body; } finally {
+ installFaultHook(undefined);
+ __setAfterDerivationSweepBatchForTests(null);
+ __setDerivationSweepLimitsForTests(null);
+ }
+ const store = derivationStore(first!)! as Record<string, any>;
+ expect({ planted: plantedRows, status: store.status, remaining: store.remaining, probe: store.probe, sweep: first!.derivation_sweep, completion: first!.completion })
+ .toEqual({ planted: 1, status: 'incomplete', remaining: 1, probe: 'statement_deadline', sweep: 'pending', completion: 'incomplete' });
+ expect((first!.next as string[]).some(n => n.includes(`gbrain forget --purge --status --request-id ${params.request_id} --continue`))).toBe(true);
+ const done = await continueToEnd(params.request_id);
+ expect({ sweep: done.derivation_sweep, rows: await exactHolders(brain.engine, late, planted), recorded: await sweepsRecorded() }).toEqual({ sweep: undefined, rows: [], recorded: 0 });
+ }, 600_000);
+
+ test('a sweep ends while writers bringing pages into its scope keep committing: it waits for the scope lock instead of walking again', async () => {
+ const claim = 'Purge Example barn code is 2284';
+ const rows = await candidateRowsPage('notes/steady-rows', claim, 300, 1);
+ const fillers: number[] = [];
+ for (const k of [0, 1]) {
+ await brain.engine.putPage(`notes/steady-filler-${k}`, { type: 'note', title: 'Steady Filler', compiled_truth: 'Steady filler.', timeline: '', frontmatter: {} }, { sourceId: SOURCE });
+ fillers.push(Number((await brain.engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [SOURCE, `notes/steady-filler-${k}`]))[0]!.id));
+ }
+ const params = await confirmed(await seed('notes/steady-purge', claim));
+ __setDerivationSweepLimitsForTests({ batchRows: 100, totalMs: 0 });
+ try { expect((await brain.call('purge_fact', params)).body.derivation_sweep).toBe('pending'); } finally { __setDerivationSweepLimitsForTests(null); }
+ // Each write soft-deletes a page of the source (the trigger takes the scope lock shared and notes the page) and restores it after it commits. On
+ // Postgres two writers overlap, each holding the lock 300 ms, so one always holds it; PGLite has one connection, so one write runs after each batch.
+ let running = true, commits = 0;
+ const errors: unknown[] = [];
+ const write = async (tx: { unsafe: (q: string, p?: unknown[]) => Promise<unknown> }, page: number) => {
+ await tx.unsafe('UPDATE pages SET deleted_at = now() WHERE id = $1', [page]);
+ if (kind === 'postgres') await tx.unsafe('SELECT pg_sleep(0.3)');
+ };
+ const writers: Promise<void>[] = [];
+ if (kind === 'postgres') {
+ const sql = (brain.engine as any).sql;
+ for (const [i, page] of fillers.entries()) writers.push((async () => {
+ await Bun.sleep(150 * i);
+ while (running) {
+ try {
+ await sql.begin((tx: any) => write(tx, page));
+ await sql.unsafe('UPDATE pages SET deleted_at = NULL WHERE id = $1', [page]);
+ commits++;
+ } catch (error) { errors.push(error); return; }
+ }
+ })());
+ while (commits < 2) await Bun.sleep(50);
+ } else {
+ __setAfterDerivationSweepBatchForTests(async () => {
+ await write({ unsafe: (q, p) => brain.engine.executeRaw(q, p as unknown[]) }, fillers[commits % 2]!);
+ await brain.engine.executeRaw('UPDATE pages SET deleted_at = NULL WHERE id = $1', [fillers[commits % 2]]);
+ commits++;
+ });
+ }
+ const before = commits;
+ let status: Record<string, any> = {}, calls = 0, during = 0;
+ __setDerivationSweepLimitsForTests({ batchRows: 100, totalMs: 2_000 });
+ try {
+ do {
+ status = (await brain.call('purge_fact', { status: true, request_id: params.request_id, continue: true })).body;
+ calls++;
+ } while (status.derivation_sweep === 'pending' && calls < 10);
+ during = commits - before;
+ } finally {
+ running = false;
+ await Promise.all(writers);
+ __setAfterDerivationSweepBatchForTests(null);
+ __setDerivationSweepLimitsForTests(null);
+ }
+ expect({ errors, sweep: status.derivation_sweep, wrote: during > 0 }).toEqual({ errors: [], sweep: undefined, wrote: true });
+ expect({ rows: await exactHolders(brain.engine, rows, claim), recorded: await sweepsRecorded() }).toEqual({ rows: [], recorded: 0 });
+ }, 600_000);
+
+ if (kind === 'postgres') {
+ const scopeKey = `hashtextextended('gbrain:derivation-scope:' || '${SOURCE}', 0)`;
+ const advisoryLocks = (sql: any, mode: string) => sql.unsafe(`SELECT pid FROM pg_locks WHERE locktype = 'advisory' AND mode = $1 AND NOT granted
+ AND database = (SELECT oid FROM pg_database WHERE datname = current_database())`, [mode]) as Promise<Array<{ pid: number }>>;
+
+ test('a sweep waiting for the scope lock holds no other lock, and writes that arrive meanwhile queue behind it', async () => {
+ const claim = 'Purge Example mill code is 6630';
+ const rows = await candidateRowsPage('notes/wait-rows', claim, 50, 1);
+ const params = await confirmed(await seed('notes/wait-purge', claim));
+ __setDerivationSweepLimitsForTests({ totalMs: 0 });
+ try { expect((await brain.call('purge_fact', params)).body.derivation_sweep).toBe('pending'); } finally { __setDerivationSweepLimitsForTests(null); }
+ const sql = (brain.engine as any).sql;
+ const opened = Promise.withResolvers<void>(), release = Promise.withResolvers<void>();
+ const writer = sql.begin(async (tx: any) => { await tx.unsafe(`SELECT pg_advisory_xact_lock_shared(${scopeKey})`); opened.resolve(); await release.promise; });
+ await opened.promise;
+ // The wait is long enough here for the test to look at it; the call still stops at its sweep deadline otherwise.
+ __setDerivationSweepLimitsForTests({ totalMs: 5_000, finalizeWaitMs: 60_000 });
+ let resumed: Promise<{ body: Record<string, any> }> | undefined, late: Promise<unknown> | undefined;
+ let waiter: { pid: number } | undefined, held: unknown[] = ['not looked at'], queued = false;
+ try {
+ resumed = brain.call('purge_fact', { status: true, request_id: params.request_id, continue: true });
+ for (let i = 0; i < 300 && !waiter; i++) {
+ [waiter] = await advisoryLocks(sql, 'ExclusiveLock');
+ if (!waiter) await Bun.sleep(100);
+ }
+ if (waiter) {
+ held = await sql.unsafe(`SELECT locktype, mode FROM pg_locks WHERE pid = $1 AND granted AND locktype <> 'virtualxid'`, [waiter.pid]);
+ late = sql.begin((tx: any) => tx.unsafe(`SELECT pg_advisory_xact_lock_shared(${scopeKey})`));
+ for (let i = 0; i < 300 && !queued; i++) {
+ queued = (await advisoryLocks(sql, 'ShareLock')).length > 0;
+ if (!queued) await Bun.sleep(50);
+ }
+ }
+ } finally {
+ release.resolve();
+ await writer;
+ }
+ const done = (await resumed!).body;
+ await late;
+ __setDerivationSweepLimitsForTests(null);
+ expect({ waiting: waiter !== undefined, held, queued, sweep: done.derivation_sweep }).toEqual({ waiting: true, held: [], queued: true, sweep: undefined });
+ expect({ rows: await exactHolders(brain.engine, rows, claim), recorded: await sweepsRecorded() }).toEqual({ rows: [], recorded: 0 });
+ }, 600_000);
+
+ test('an import that retired an occurrence before the purge recorded its sweep and commits after the last walk passed its page leaves no holder', async () => {
+ const claim = 'Purge Example mine code is 5829', planted = 'Alice Example said Purge Example mine code is 5829';
+ await brain.seed('notes/sweep-late-commit-live', prosePage(planted, 69));
+ const live = await storedPage(brain.engine, 'notes/sweep-late-commit-live');
+ await deriveAll(brain.engine, live);
+ expect((await exactHolders(brain.engine, live.id, planted)).length).toBeGreaterThan(0);
+ await candidateRowsPage('notes/sweep-late-commit-pad', 'Purge Example padding row is 0005', 600, 0);
+ const params = await confirmed(await seed('notes/sweep-late-commit-purge', claim));
+ const sql = (brain.engine as any).sql;
+ const opened = Promise.withResolvers<void>(), release = Promise.withResolvers<void>();
+ let open = true;
+ const held = sql.begin(async (tx: any) => {
+ await tx.unsafe('UPDATE page_body_manifest SET gen_to = gen_from + 1000000 WHERE page_id = $1 AND gen_to IS NULL AND staging_id IS NULL', [live.id]);
+ opened.resolve();
+ await release.promise;
+ });
+ await opened.promise;
+ const commit = async () => { if (!open) return; open = false; release.resolve(); await held; };
+ let phase: string | null = null;
+ __setDerivationSweepLimitsForTests({ batchRows: 100, totalMs: 0 });
+ try { expect((await brain.call('purge_fact', params)).body.derivation_sweep).toBe('pending'); } finally { __setDerivationSweepLimitsForTests(null); }
+ // The import commits as soon as a verify walk is past the page, so that walk never sees the rows it brought into the scope.
+ __setDerivationSweepLimitsForTests({ batchRows: 100 });
+ __setAfterDerivationSweepBatchForTests(async () => {
+ const [record] = await brain.engine.executeRaw<{ cursor_page: number | null; phase: string }>('SELECT cursor_page, phase FROM page_segment_derivation_purges');
+ if (open && record?.phase === 'verify' && record.cursor_page !== null && Number(record.cursor_page) > live.id) await commit();
+ });
+ try {
+ await brain.call('purge_fact', { status: true, request_id: params.request_id, continue: true });
+ if (open) [{ phase }] = await brain.engine.executeRaw<{ phase: string }>('SELECT phase FROM page_segment_derivation_purges');
+ } finally {
+ await commit();
+ __setAfterDerivationSweepBatchForTests(null);
+ }
+ const done = await continueToEnd(params.request_id);
+ __setDerivationSweepLimitsForTests(null);
+ expect({ phase, sweep: done.derivation_sweep, rows: await exactHolders(brain.engine, live.id, planted), recorded: await sweepsRecorded() })
+ .toEqual({ phase: 'sweep', sweep: undefined, rows: [], recorded: 0 });
+ }, 600_000);
+ }
});
}