Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
lane 4a round 7b: serialized sweep end, scoped unread deletes, sweep doctor check, early pending return
garrytan769a83133e09
diff --git a/src/commands/doctor/checks/derivation-purge-sweeps.ts b/src/commands/doctor/checks/derivation-purge-sweeps.tsnew file mode 100644index 0000000000..8666817785--- /dev/null+++ b/src/commands/doctor/checks/derivation-purge-sweeps.ts@@ -0,0 +1,49 @@+/**+ * Wave B PR 4 (lane 4a): doctor `derivation_purge_sweeps`. A fact purge records a sweep of the stored derivation+ * results holding its claim and deletes them after it commits (segment-derive.ts continueDerivationPurges). While a+ * sweep is recorded, paid atom, synopsis and fact extraction makes no call on the pages it covers (receipts say+ * `purge_sweep_pending`), so a sweep left pending or stalled holds that work back. This check names each one with its+ * purge request id and the command that continues it.+ */+import type { Check } from '../../doctor.ts';+import { checkError, doctorVerify } from '../check-fix.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';++const SAMPLE = 20;++/** The command that continues the sweep of purge request `requestId` (the id the purge printed). */+export const continueSweepArgv = (requestId: string): string[] => ['gbrain', 'forget', '--purge', '--status', '--request-id', requestId, '--continue'];++async function runDerivationPurgeSweeps(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ let rows: Array<{ request_id: string | null; source_id: string; stalled: boolean; reason: string | null; created_at: string }>;+ try {+ rows = await connectedEngine(ctx).executeRaw(`SELECT r.request_id::text AS request_id, x.source_id, x.stalled_at IS NOT NULL AS stalled, x.stalled_reason AS reason,+ x.created_at::text AS created_at+ FROM page_segment_derivation_purges x LEFT JOIN persistence_requests r ON r.id = x.request_id ORDER BY x.created_at, x.request_id`);+ } catch (error) {+ checks.push(checkError('derivation_purge_sweeps', 'read the recorded derivation sweeps', error));+ return checks;+ }+ if (!rows.length) {+ checks.push({ name: 'derivation_purge_sweeps', status: 'ok', message: 'No fact purge has a sweep of stored derivation results pending or stalled.', details: { sweeps: 0 } });+ return checks;+ }+ const sweeps = rows.slice(0, SAMPLE).map(row => ({ request_id: row.request_id, source_id: row.source_id, state: row.stalled ? 'stalled' : 'pending',+ ...(row.stalled ? { reason: row.reason ?? 'statement_timeout' } : {}), created_at: row.created_at,+ ...(row.request_id ? { command: continueSweepArgv(row.request_id).join(' ') } : {}) }));+ const listed = sweeps.map(s => `${s.request_id ?? '(request missing)'} in source ${s.source_id} (${s.state}${s.reason ? `, ${s.reason}` : ''})`).join(', ');+ const first = sweeps.find(s => s.request_id)?.request_id;+ checks.push({+ name: 'derivation_purge_sweeps', status: 'warn', details: { sweeps: rows.length, truncated: rows.length > sweeps.length, records: sweeps },+ message: `${rows.length} fact purge sweep(s) of stored derivation results are not finished: ${listed}${rows.length > sweeps.length ? ` (first ${sweeps.length} of ${rows.length} shown)` : ''}. `+ + '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.' } }+ : { fix_unavailable_reason: 'operator_judgement' as const }),+ });+ return checks;+}++export const derivationPurgeSweepsEntry: DoctorEntry = { name: 'derivation_purge_sweeps', emits: ['derivation_purge_sweeps'], run: runDerivationPurgeSweeps };diff --git a/src/commands/doctor/checks/extraction-input.ts b/src/commands/doctor/checks/extraction-input.tsindex d7bff6c6af..926fca4d56 100644--- a/src/commands/doctor/checks/extraction-input.ts+++ b/src/commands/doctor/checks/extraction-input.ts@@ -19,7 +19,10 @@* are read; a page counts once per pipeline and receipt kind. A derivation receipt* without a `kind` (the synopsis pass's tier fallback or refused reservation), or of* kind `unpriced_model` (doctor derivation_unpriced_model), is not an input-truncation- * receipt and is not counted.+ * receipt and is not counted. A receipt whose reason is `purge_sweep_pending` (atoms,+ * synopsis or fact extraction made no paid call because a fact purge's sweep covers the+ * page) counts under that kind, whatever its own: its remedy is finishing the sweep+ * (doctor derivation_purge_sweeps), not a higher spend cap.*/import type { Check } from '../../doctor.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';@@ -39,9 +42,11 @@ const UNREAD_WINDOWS = 'unread_windows';const UNREAD_REMEDY = `the run stopped before every window of the page was read (the receipt's reason: the per-page spend cap, a window limit or a skipped window); the next run resumes where it stopped, and when the cap stopped it: gbrain config set ${PAGE_DERIVATION_CAP_KEY} <usd>`;const FAILED_WINDOWS = 'failed_windows';const FAILED_REMEDY = 'a conversation window failed to extract in run after run and is skipped, so the older windows still get extracted (the sample names the window, its receipt the last error); fix the cause, then gbrain extract-conversation-facts --slug <slug> --force tries it again';+const PURGE_SWEEP = 'purge_sweep_pending';+const PURGE_SWEEP_REMEDY = 'a fact purge\'s sweep of stored derivation results covers the page, so the run made no paid call there; gbrain doctor --only derivation_purge_sweeps names the purge, gbrain forget --purge --status --request-id <request_id> --continue finishes its sweep, and the next run resumes where it stopped';const NO_MESSAGES = 'no_messages';const NO_MESSAGES_REMEDY = 'the page reads as a transcript format over its whole text, yet no message parsed under that format (a conversation parser fault), so the last run changed nothing and kept its facts; rerunning repeats this, so report it with gbrain doctor --json and the page\'s format (a page that is not a transcript settles as non-extractable instead)';-const remedy = (g: ReceiptGroup): string | null => g.kind === UNREAD_WINDOWS ? UNREAD_REMEDY : g.kind === FAILED_WINDOWS ? FAILED_REMEDY+const remedy = (g: ReceiptGroup): string | null => g.kind === PURGE_SWEEP ? PURGE_SWEEP_REMEDY : g.kind === UNREAD_WINDOWS ? UNREAD_REMEDY : g.kind === FAILED_WINDOWS ? FAILED_REMEDY: g.kind === NO_MESSAGES ? NO_MESSAGES_REMEDY : REMEDY[g.pipeline] ?? null;const describe = (g: ReceiptGroup): string =>@@ -55,9 +60,11 @@ async function runExtractionInputTruncatedCheck(ctx: DoctorContext): Promise<CheSELECT s.page_id, s.pipeline, COALESCE(s.input_truncated->>'kind', 'unknown') AS kind, s.updated_at, NULL::text AS detailFROM page_extraction_state s WHERE s.input_truncated IS NOT NULLUNION ALL- SELECT d.page_id, d.pipeline, COALESCE(d.receipt->>'kind', 'unknown') AS kind, max(d.updated_at) AS updated_at,+ SELECT d.page_id, d.pipeline, CASE WHEN d.receipt->>'reason' = '${PURGE_SWEEP}' THEN '${PURGE_SWEEP}' ELSE COALESCE(d.receipt->>'kind', 'unknown') END AS kind,+ max(d.updated_at) AS updated_at,min(CASE WHEN d.receipt->>'kind' = '${FAILED_WINDOWS}' THEN ' window ' || (d.receipt->'windows'->0->>'ordinal') || ' of occurrence ' || d.occurrence_id END) AS detail- FROM page_segment_derivations d WHERE d.receipt->>'kind' IS NOT NULL AND d.receipt->>'kind' <> 'unpriced_model' GROUP BY 1, 2, 3)+ FROM page_segment_derivations d+ WHERE (d.receipt->>'kind' IS NOT NULL AND d.receipt->>'kind' <> 'unpriced_model') OR d.receipt->>'reason' = '${PURGE_SWEEP}' GROUP BY 1, 2, 3)SELECT r.pipeline, r.kind, count(DISTINCT r.page_id)::int AS pages,(array_agg(p.source_id || ':' || p.slug || COALESCE(r.detail, '') ORDER BY r.updated_at DESC))[1:3] AS samplesFROM receipts r JOIN pages p ON p.id = r.page_id AND p.deleted_at IS NULL@@ -69,13 +76,14 @@ async function runExtractionInputTruncatedCheck(ctx: DoctorContext): Promise<Chereturn checks;}const summary = `Page extractions that read only part of their input: ${groups.map(describe).join('. ')}.`;- const actionable = groups.filter(g => g.pipeline !== 'facts_backstop' || g.kind === UNREAD_WINDOWS);+ const actionable = groups.filter(g => g.pipeline !== 'facts_backstop' || g.kind === UNREAD_WINDOWS || g.kind === PURGE_SWEEP);if (!actionable.length) {checks.push({ name: 'extraction_input_truncated', status: 'ok', severity: 'info', readiness_state: 'degraded', message: summary, details });return checks;}- const atoms = actionable.find(g => g.pipeline === 'extract_atoms' && g.kind !== UNREAD_WINDOWS);+ const atoms = actionable.find(g => g.pipeline === 'extract_atoms' && g.kind !== UNREAD_WINDOWS && g.kind !== PURGE_SWEEP);const capped = actionable.some(g => g.kind === UNREAD_WINDOWS);+ const sweeping = actionable.some(g => g.kind === PURGE_SWEEP);checks.push({ name: 'extraction_input_truncated', status: 'warn', message: summary, details,...(atoms? { fix: agentFix(['gbrain', 'config', 'set', EXTRACT_MAX_INPUT_CHARS_KEY, '<n>'],@@ -85,7 +93,10 @@ async function runExtractionInputTruncatedCheck(ctx: DoctorContext): Promise<Che? { fix: agentFix(['gbrain', 'config', 'set', PAGE_DERIVATION_CAP_KEY, '<USD>'],'A higher per-page cap lets the next run read the windows the cap stopped; it raises model spend, so the value is the user\'s call.', 'extraction_input_truncated',{ ask_user: true, consent: ['paid'], inputs: [{ name: 'USD', how: 'a per-page dollar cap chosen with the user' }] }) }- : { fix_unavailable_reason: 'operator_judgement' as const }) });+ : sweeping+ ? { fix: agentFix(['gbrain', 'doctor', '--only', 'derivation_purge_sweeps', '--json'],+ 'Names each unfinished fact purge sweep and the command that continues it; paid extraction resumes on the pages once the sweep ends. It changes nothing.', 'extraction_input_truncated') }+ : { fix_unavailable_reason: 'operator_judgement' as const }) });} catch (error) {checks.push(checkError('extraction_input_truncated', 'read the extraction receipts', error, { details: { health: 'unknown' } }));}diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex cd599736ca..ceb0fa3db1 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -124,6 +124,7 @@ import { renameIdentityDowngradesEntry } from './checks/rename-identity-downgradimport { unindexedFilesEntry } from './checks/unindexed-files.ts';import { syncLandingGapsEntry } from './checks/landing-gaps.ts';import { purgeParkedPagesEntry } from './checks/purge-parks.ts';+import { derivationPurgeSweepsEntry } from './checks/derivation-purge-sweeps.ts';import { missingRecordedFilesEntry } from './checks/missing-recorded-files.ts';import { uncommittedSyncDeletionsEntry } from './checks/uncommitted-sync-deletions.ts';import { overwrittenEditsEntry } from './checks/overwritten-edits.ts';@@ -266,6 +267,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [originTwinsEntry,renameIdentityDowngradesEntry,purgeParkedPagesEntry,+ derivationPurgeSweepsEntry,missingRecordedFilesEntry,uncommittedSyncDeletionsEntry,unindexedFilesEntry,diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 94b6893972..a59ca2baa4 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1077,6 +1077,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: 'TBD', text: 'A fact purge now searches stored link, mention, timeline and fence results in batches of 500 rows per statement, and its receipt checks them the same way, so a claim whose words appear in tens of thousands of stored results can be purged instead of always failing with `purge_lookup_timeout`. The purge still commits all at once. It fails with `purge_lookup_timeout`, purging nothing, only when the search runs past two minutes.' },{ since: 'TBD', text: 'A fact purge no longer searches stored link, mention, timeline and fence results inside its transaction, so other writes to the source are no longer blocked while it walks them. The purge records the claim and commits; it then deletes the results holding the claim in batches of 500 stored results, each in a short transaction of its own, for up to two minutes. From the commit on, a result holding the claim cannot be written back into what the purge covers. When the walk does not finish in that time, the purge still commits, but its receipt reports `page_segment_derivations` as `incomplete`, `completion: incomplete` (exit 75) and `derivation_sweep: pending`. Running the same purge again with its request id, or purging another fact in the source, continues from where the walk stopped. The walk no longer fails a purge with `purge_lookup_timeout` (this replaces the two-minute failure above).' },{ 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`.' },// 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/contextual-retrieval-service.ts b/src/core/contextual-retrieval-service.tsindex 63cac1bbf4..3fe60cc3a1 100644--- a/src/core/contextual-retrieval-service.ts+++ b/src/core/contextual-retrieval-service.ts@@ -238,7 +238,7 @@ export type ReembedPageResult =}| {kind: 'skipped';- reason: 'mode_none' | 'no_chunks' | 'page_missing' | 'soft_deleted' | 'budget_limited' | 'page_body_segmented';+ reason: 'mode_none' | 'no_chunks' | 'page_missing' | 'soft_deleted' | 'budget_limited' | 'purge_sweep_pending' | 'page_body_segmented';}| {kind: 'page_fallback';@@ -501,7 +501,8 @@ export const SYNOPSIS_DERIVATION_VERSION = 1;* spends on the newest text, as the embedding path's grants do.** Each window with work reserves its synopsis calls and their embedding against the page's spend cap- * (`synopsis:<model>`) first: a held page or a refused reservation leaves the title tier in place (`budget_limited`), the+ * (`synopsis:<model>`) first: a held page or a refused reservation leaves the title tier in place (`budget_limited`, or+ * `purge_sweep_pending` when a fact purge's pending derivation sweep covers the page), the* segment `partial` and the windows already installed kept. A window whose synopsis is refused, empty or malformed* embeds at the title tier, which a synopsis page accepts (page_fallback; the segment is settled with the fallback in* its receipt, so it is not paid for again until its inputs change). Each segment runs under the page's embedding lease:@@ -582,7 +583,7 @@ async function reembedSegmentedPage(args: ReembedPageArgs, initial: Page): Promiif ('refused' in metered) {await derivation(segment, 'partial', anchors, { reason: unpricedModel ? 'unpriced_model' : metered.refused.reason === 'purge_sweep_pending' ? 'purge_sweep_pending' : 'budget_limited', ...(unpricedModel ? { model: unpricedModel } : {}),cap_usd: metered.refused.capUsd, estimate_usd: metered.refused.estimateUsd });- return { kind: 'skipped', reason: 'budget_limited' };+ return { kind: 'skipped', reason: metered.refused.reason === 'purge_sweep_pending' ? 'purge_sweep_pending' : 'budget_limited' };}const built = metered.value;if (built.kind !== 'built') {diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.tsindex 17b4158637..76847d4c0c 100644--- a/src/core/deletion-inventory.ts+++ b/src/core/deletion-inventory.ts@@ -120,7 +120,7 @@ const ROWS: readonly Row[] = [['page_projection_jobs', 'out_of_scope', 'no_memory_text', 'slug reason'],['page_purges', 'out_of_scope', 'text_free_ledger', 'source_id content_hash slug'],['page_segment_derivations', 'swept', 'segment_derivations', 'pipeline segment_sha256 context_hash state output receipt', 'output receipt'],- ['page_segment_derivation_purges', 'swept', 'segment_derivations', 'source_id needles patterns page_ids phase recheck cursor_pipeline'],+ ['page_segment_derivation_purges', 'swept', 'segment_derivations', 'source_id needles patterns page_ids phase recheck cursor_pipeline stalled_reason'],['page_segment_texts', 'swept', 'segment_texts', 'source_id sha256 body', 'body'],['page_view_digests', 'out_of_scope', 'no_memory_text', 'revision view audience sha256'],['page_versions', 'swept', 'page_versions', 'compiled_truth frontmatter timeline title type tags source_path write_principal_kind write_principal_id archived_principal_kind archived_principal_id trust_tier write_origin body_storage content_hash'],diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex a372a1766c..af73d634f1 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -165,6 +165,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['parked_effects',// #6741: managed purges parked after repeated failures (doctor/checks/purge-parks.ts).'purge_parked_pages',+ // Wave B PR 4: fact purge sweeps of stored derivation results still pending or stalled (doctor/checks/derivation-purge-sweeps.ts).+ 'derivation_purge_sweeps','partial_embedding','pglite_scratch_probe','quarantined_pages',diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.tsindex a2deb17a7d..23ce637128 100644--- a/src/core/facts/purge-verify.ts+++ b/src/core/facts/purge-verify.ts@@ -28,7 +28,7 @@ import type { PurgePlan, PurgeTarget } from './purge.ts';import { gitChildEnv } from '../git-env.ts';import { segmentedBodyContains } from '../page-body/segment-rewrite.ts';import { derivationAfterSql, derivationBatchRows, derivationNeedles, derivationPurgeState, recordDerivationStatement,- type DerivationKey, type DerivationSweepState } from '../page-body/segment-derive.ts';+ type DerivationKey, type DerivationStallReason, type DerivationSweepState } from '../page-body/segment-derive.ts';import { faultPoint } from '../persistence/fault-points.ts';import { derivationClaimCandidateSql, derivationHoldsClaimSql, derivationSweepScopeSql, stagingNeedsTextSql } from '../page-body/schema.ts';import { claimForms, quotes, type LedgerPurgeReport } from '../belief/purge.ts';@@ -37,7 +37,7 @@ import { relationExists } from '../persistence/rebuildable-cache.ts';export type StoreCount = Record<string, number>;export type StoreStatus = 'deleted' | 'would_remove' | 'retained_inactive' | 'unverified' | 'out_of_reach' | 'out_of_scope' | 'not_present' | 'incomplete';-export interface StoreReport { store: string; status: StoreStatus; removed?: number; remaining?: number; reason?: string; detail?: string; items?: unknown[] }+export interface StoreReport { store: string; status: StoreStatus; removed?: number; remaining?: number; reason?: string; detail?: string; items?: unknown[]; probe?: string }export type PurgeCompletion = 'committed' | 'complete' | 'incomplete';export interface PurgeReceipt {summary: string;@@ -130,13 +130,18 @@ 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.+ * 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`.*/async function derivationTextReport(engine: BrainEngine, sourceId: string, pageIds: readonly number[], claims: readonly string[], removed: number,- deadline: number): Promise<StoreReport> {+ 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 => ({ store: 'page_segment_derivations', status: 'unverified', reason, 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;let cursor: DerivationKey | null = null;let rows = derivationBatchRows();@@ -459,7 +464,7 @@ async function vectorProbe(engine: BrainEngine, target: PurgeTarget): Promise<Re/** Build the receipt: swept-store verification (or would-remove counts on a dry run), probes, residuals first. */export async function verifyFactPurge(engine: BrainEngine, input: { target: PurgeTarget; plan: PurgePlan; dryRun: boolean; removed?: StoreCount;- prose?: Array<{ slug: string; version_id: number }>; vacuum?: boolean; ledger?: LedgerPurgeReport | null }): Promise<PurgeReceipt> {+ prose?: Array<{ slug: string; version_id: number }>; vacuum?: boolean; ledger?: LedgerPurgeReport | null; sweepVerified?: boolean }): Promise<PurgeReceipt> {const { target, plan, dryRun } = input;const deadline = performance.now() + probeLimits.totalMs;const claim = target.fact, needle = claim.toLowerCase(), src = target.source_id;@@ -508,7 +513,8 @@ export async function verifyFactPurge(engine: BrainEngine, input: { target: Purgdetail: `${legacy.n} model-derived page(s) in this source predate derivation edges, so purge cannot tell whether they restate the claim in other words.` });if (!dryRun) {stores.push(await segmentTextReport(engine, src, [...new Set([claim, escapeFenceCell(claim)])], removed.page_segment_texts ?? 0, deadline));- stores.push(await derivationTextReport(engine, src, plan.pages.map(page => page.page_id), [claim, escapeFenceCell(claim)], removed.page_segment_derivations ?? 0, deadline));+ stores.push(await derivationTextReport(engine, src, plan.pages.map(page => page.page_id), [claim, escapeFenceCell(claim)], removed.page_segment_derivations ?? 0, deadline,+ input.sweepVerified === true));stores.push(...await ledgerReports(engine, src, [claim], input.ledger, deadline));stores.push(await effectPayloadReport(engine, src, [claim], deadline, removed.persistence_effects ?? 0));}@@ -689,7 +695,7 @@ export async function verifyPagePurge(engine: BrainEngine, input: { sourceId: st*/export async function purgeCompletion(engine: BrainEngine, row: Pick<WriteRequest, 'id' | 'request_id' | 'state' | 'source_id' | 'outcome'>, receipt?: Pick<PurgeReceipt, 'stores'>):Promise<{ completion: PurgeCompletion; effects: Array<{ kind: string; state: string; error_code: string | null }>; exit_code: number; fingerprint_probe?: Record<string, number>;- derivation_sweep?: DerivationSweepState; next?: string[] }> {+ derivation_sweep?: DerivationSweepState; derivation_sweep_reason?: DerivationStallReason; next?: string[] }> {if (row.state !== 'committed') return { completion: 'incomplete', effects: [], exit_code: 75 };const effects = await engine.executeRaw<{ kind: string; state: string; error_code: string | null; parked: boolean }>(`SELECT kind,state,error_code,jsonb_array_length(COALESCE(data->'parked','[]'::jsonb))>0 AS parked FROM persistence_effects WHERE request_id=$1::uuid ORDER BY kind`, [row.id]);@@ -703,13 +709,15 @@ export async function purgeCompletion(engine: BrainEngine, row: Pick<WriteRequesfingerprint = { facts: Number(probe?.facts ?? 0), takes: Number(probe?.takes ?? 0) };}const failed = effects.some(e => e.state === 'failed' || e.parked);- const sweeping = await derivationPurgeState(engine, row.id);- const sweptResidual = sweeping || receipt?.stores.some(s => s.status === 'incomplete') || (fingerprint && (fingerprint.facts || fingerprint.takes));+ const sweep = await derivationPurgeState(engine, row.id);+ const sweptResidual = sweep || receipt?.stores.some(s => s.status === 'incomplete') || (fingerprint && (fingerprint.facts || fingerprint.takes));const pending = effects.some(e => e.state !== 'committed');const completion: PurgeCompletion = failed || sweptResidual ? 'incomplete' : pending ? 'committed' : 'complete';return { completion, effects: effects.map(({ kind, state, error_code }) => ({ kind, state, error_code })),exit_code: completion === 'complete' ? 0 : completion === 'committed' ? 10 : 75, ...(fingerprint ? { fingerprint_probe: fingerprint } : {}),- ...(sweeping ? { derivation_sweep: sweeping, next: [sweeping === 'pending'+ ...(sweep ? { derivation_sweep: sweep.state, ...(sweep.reason ? { derivation_sweep_reason: sweep.reason } : {}), next: [sweep.state === 'pending'? `Stored derivation results are still being swept for the claim (derivation_sweep: pending). Continue the sweep with gbrain forget --purge --status --request-id ${row.request_id} --continue until completion is complete.`- : `The sweep of stored derivation results stopped on a result it could not read or delete within its statement budget (derivation_sweep: stalled); other sweeps go on. Retry it with gbrain forget --purge --status --request-id ${row.request_id} --continue; if it stalls again, report it with the output of gbrain doctor --json.`] } : {}) };+ : sweep.reason === 'paid_row_unreadable'+ ? `The sweep of stored derivation results stopped on a paid result (atoms, synopsis or conversation facts) it could not read within its statement budget (derivation_sweep: stalled, paid_row_unreadable); paid results are never deleted unread, and other sweeps go on. Retry it with gbrain forget --purge --status --request-id ${row.request_id} --continue; if it stalls again, report it with the output of gbrain doctor --json.`+ : `The sweep of stored derivation results stopped on a result it could not read or delete within its statement budget (derivation_sweep: stalled); other sweeps go on. Retry it with gbrain forget --purge --status --request-id ${row.request_id} --continue; if it stalls again, report it with the output of gbrain doctor --json.`] } : {}) };}diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.tsindex affb03c0cf..6f1fe68d60 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 { continueDerivationPurges, recordDerivationPurge } from '../page-body/segment-derive.ts';+import { continueDerivationPurges, derivationPurgeState, recordDerivationPurge } from '../page-body/segment-derive.ts';import { discoverWithdrawalTargets, withdrawalDiscoveryFailure } from './withdrawal-discovery.ts';import { dropPurgedFenceRows } from './purge-overlay.ts';import { derivedRowsFrom, hideDerivedRows, type DerivationRef } from './derivation-inputs.ts';@@ -592,10 +592,10 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Recfor (const slug of unsealed) await buildSegmentedProjection(ctx.engine, { sourceId: p.sourceId, slug }).catch(() => undefined);if (row.state !== 'committed') return { ...(row.outcome ?? {}), request_id: row.request_id, state: row.state, error: row.error_code };appendPurgeCommitted(row.id);- counts.page_segment_derivations = (counts.page_segment_derivations ?? 0) + await continueDerivationPurges(ctx.engine, p.sourceId, { first: 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 receipt: PurgeReceipt = await verifyFactPurge(ctx.engine, { target, plan: committedPlan, dryRun: false, removed: counts, prose,- vacuum: params.vacuum === true, ledger });+ vacuum: params.vacuum === true, ledger, sweepVerified: !await derivationPurgeState(ctx.engine, row.id) });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/minions/handlers/contextual-reindex-per-chunk.ts b/src/core/minions/handlers/contextual-reindex-per-chunk.tsindex 600548baf6..21cf30c697 100644--- a/src/core/minions/handlers/contextual-reindex-per-chunk.ts+++ b/src/core/minions/handlers/contextual-reindex-per-chunk.ts@@ -129,7 +129,7 @@ export function makeContextualReindexHandler(opts: MakeContextualReindexHandlerOreturn async function contextualReindexHandler(ctx: MinionJobContext,- ): Promise<{ ok: true; mode_applied: string; chunks_embedded: number; skip_reason?: string }> {+ ): Promise<{ ok: boolean; mode_applied: string; chunks_embedded: number; skip_reason?: string; next?: string }> {const data = parseJobData(ctx.data);// Load page row to derive the authoritative source_id (D27 P2-1).@@ -281,7 +281,7 @@ function abortError(): Error {function classifyResult(pageSlug: string,result: ReembedPageResult,-): { ok: true; mode_applied: string; chunks_embedded: number; skip_reason?: string } {+): { ok: boolean; mode_applied: string; chunks_embedded: number; skip_reason?: string; next?: string } {switch (result.kind) {case 'success':return {@@ -299,6 +299,9 @@ function classifyResult(chunks_embedded: result.chunks_embedded,};case 'skipped':+ // A fact purge's pending derivation sweep blocks the page's paid synopsis: not done, and not a cap to raise.+ if (result.reason === 'purge_sweep_pending') return { ok: false, mode_applied: 'skipped', chunks_embedded: 0, skip_reason: result.reason,+ next: 'A fact purge\'s sweep of stored derivation results covers this page, so no synopsis was paid for. gbrain doctor --only derivation_purge_sweeps names the purge and the command that finishes its sweep (gbrain forget --purge --status --request-id <request_id> --continue); then run the reindex again.' };return { ok: true, mode_applied: 'skipped', chunks_embedded: 0, skip_reason: result.reason };case 'transient_error':// Throw so Minion retries. The queue's backoff policy handlesdiff --git a/src/core/page-body/schema.ts b/src/core/page-body/schema.tsindex eeab547d49..c8e2ebb42c 100644--- a/src/core/page-body/schema.ts+++ b/src/core/page-body/schema.ts@@ -225,6 +225,15 @@ 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))`;}+/**+ * SQL: the advisory lock key that serializes the note of a page entering 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, and a sweep ends (deletes its+ * record) only under it exclusively, so a note written by a transaction still open is never missed.+ */+export function derivationScopeLockSql(sourceId: string): string {+ return `hashtextextended('gbrain:derivation-scope:' || ${sourceId}, 0)`;+}+/*** Per-segment derivation watermarks (migration v265): one row per page, pipeline and manifest occurrence, recording* the segment text and the context (`context_hash`: entry state plus the page-level inputs the pipeline reads) it was@@ -288,6 +297,7 @@ CREATE TABLE IF NOT EXISTS page_segment_derivation_purges (cursor_occurrence BIGINT,batch_rows INTEGER CHECK (batch_rows >= 1),stalled_at TIMESTAMPTZ,+ stalled_reason TEXT CHECK (stalled_reason IN ('statement_timeout','paid_row_unreadable')),created_at TIMESTAMPTZ NOT NULL DEFAULT now());CREATE INDEX IF NOT EXISTS page_segment_derivation_purges_source ON page_segment_derivation_purges (source_id, created_at);@@ -297,14 +307,23 @@ CREATE TABLE IF NOT EXISTS page_segment_derivation_purge_pages (PRIMARY KEY (request_id, page_id));CREATE OR REPLACE FUNCTION gbrain_mark_derivation_scope_entry() RETURNS trigger SET search_path = pg_catalog, public AS $func$+DECLARE+ src TEXT;+ page INTEGER;BEGINIF TG_TABLE_NAME = 'pages' THEN- INSERT INTO page_segment_derivation_purge_pages (request_id, page_id)- SELECT x.request_id, NEW.id FROM page_segment_derivation_purges x WHERE x.source_id = NEW.source_id ON CONFLICT DO NOTHING;+ src := NEW.source_id;+ page := NEW.id;ELSE- INSERT INTO page_segment_derivation_purge_pages (request_id, page_id)- SELECT x.request_id, OLD.page_id FROM page_segment_derivation_purges x WHERE x.source_id = OLD.source_id ON CONFLICT DO NOTHING;+ src := OLD.source_id;+ page := OLD.page_id;+ END IF;+ IF NOT EXISTS (SELECT 1 FROM page_segment_derivation_purges x WHERE x.source_id = src) THEN+ RETURN NULL;END IF;+ PERFORM pg_advisory_xact_lock_shared(${derivationScopeLockSql('src')});+ INSERT INTO page_segment_derivation_purge_pages (request_id, page_id)+ SELECT x.request_id, page FROM page_segment_derivation_purges x WHERE x.source_id = src ON CONFLICT DO NOTHING;RETURN NULL;END$func$ LANGUAGE plpgsql;diff --git a/src/core/page-body/segment-derive.ts b/src/core/page-body/segment-derive.tsindex 16a96496f4..d119774c96 100644--- a/src/core/page-body/segment-derive.ts+++ b/src/core/page-body/segment-derive.ts@@ -19,7 +19,7 @@ import { canonicalJson } from '../belief/keys.ts';import { planSegmentDerivations, segmentDerivationContextHash, type LiveSegment, type SegmentDerivationKind,type SegmentDerivationRow } from './derivations.ts';import { faultPoint } from '../persistence/fault-points.ts';-import { derivationClaimCandidateSql, derivationHoldsClaimSql, derivationSweepScopeSql, foldSql } from './schema.ts';+import { derivationClaimCandidateSql, derivationHoldsClaimSql, derivationScopeLockSql, derivationSweepScopeSql, foldSql } from './schema.ts';import { bodyBlocks, type BodyBlock } from './segment-blocks.ts';import { ledgerApplies, readBodyLedger } from './segment-ledger.ts';import { SEGMENTER_VERSION } from './segmenter.ts';@@ -369,14 +369,19 @@ export async function derivationNeedles(engine: Pick<BrainEngine, 'executeRaw'>,* Bounds of a fact purge's derivation sweep and of its receipt probe: each statement reads at most `batchRows` rows of* the source, walking them in primary-key order (so the rows it normalizes are bounded too), 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` (it runs at least one), and the- * next call resumes from the stored cursor.+ * `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.*/-export const DERIVATION_SWEEP_LIMITS = { batchRows: 500, totalMs: 120_000, statementMs: 5_000 } as const;-let sweepLimits: { batchRows: number; totalMs: number; statementMs: number } = { ...DERIVATION_SWEEP_LIMITS };+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 };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; }+let beforeUnreadDelete: ((tx: BrainEngine) => Promise<void>) | null = null;+/** @internal Test seam: run `fn` in a sweep's unread-delete transaction, after it picked the row and before it deletes it (null removes it). */+export function __setBeforeUnreadDerivationDeleteForTests(fn: ((tx: BrainEngine) => Promise<void>) | null): void { beforeUnreadDelete = fn; }+/** The pipelines whose rows a sweep may delete unread: unpaid, so rederiving them costs nothing. */+const UNPAID_PIPELINES: readonly string[] = Object.keys(SEGMENT_PIPELINE_VERSIONS);/** @internal Test seam: shrink the sweep's bounds (null restores them). */export function __setDerivationSweepLimitsForTests(limits: Partial<typeof sweepLimits> | null): void {sweepLimits = { ...DERIVATION_SWEEP_LIMITS, ...(limits ?? {}) };@@ -426,13 +431,20 @@ export async function recordDerivationPurge(engine: Pick<BrainEngine, 'executeRaVALUES ($1::uuid, $2, $3::text[], $4::text[], $5::int[]) ON CONFLICT (request_id) DO NOTHING`, [requestId, sourceId, needles, patterns, [...pageIds]]);}-/** A recorded derivation sweep of a purge request: still walking (`pending`) or stopped on a row that alone outran its statement budget (`stalled`). */+/** A recorded derivation sweep of a purge request: still walking (`pending`) or stopped on a row it could not sweep within its statement budget (`stalled`). */export type DerivationSweepState = 'pending' | 'stalled';--/** The state of a purge request's derivation sweep, or null once it is verified and its record is gone. */-export async function derivationPurgeState(engine: Pick<BrainEngine, 'executeRaw'>, requestId: string): Promise<DerivationSweepState | null> {- const [row] = await engine.executeRaw<{ stalled: boolean }>('SELECT stalled_at IS NOT NULL AS stalled FROM page_segment_derivation_purges WHERE request_id=$1::uuid', [requestId]);- return row ? (row.stalled ? 'stalled' : 'pending') : null;+/**+ * Why a sweep stalled: `statement_timeout`, even deleting a single unpaid row unread outran the budget;+ * `paid_row_unreadable`, a row of a paid pipeline alone outran it (paid rows are never deleted unread).+ */+export type DerivationStallReason = 'statement_timeout' | 'paid_row_unreadable';++/** The state of a purge request's derivation sweep (with why it stalled), or null once it is verified and its record is gone. */+export async function derivationPurgeState(engine: Pick<BrainEngine, 'executeRaw'>, requestId: string):+ Promise<{ state: DerivationSweepState; reason: DerivationStallReason | null } | null> {+ const [row] = await engine.executeRaw<{ stalled: boolean; reason: DerivationStallReason | null }>(+ 'SELECT stalled_at IS NOT NULL AS stalled, stalled_reason AS reason FROM page_segment_derivation_purges WHERE request_id=$1::uuid', [requestId]);+ return row ? { state: row.stalled ? 'stalled' : 'pending', reason: row.stalled ? row.reason ?? 'statement_timeout' : null } : null;}/**@@ -457,20 +469,26 @@ type SweepRecord = { request_id: string; needles: string[]; patterns: string[];* writes go on during a sweep.** A batch that outruns DERIVATION_SWEEP_LIMITS.statementMs rolls back and halves the record's batch size, down to one- * row. A single row that still outruns it is deleted unread when it is in scope: derivation rows are rederived from the- * segments, and a row no live segment backs serves nothing. When even that statement outruns its budget, the record is- * marked stalled: it is skipped from then on, so it blocks no other sweep, until `opts.retry` names it.+ * row. A single row of an unpaid pipeline that still outruns it is deleted unread when it is in scope, the scope+ * predicate repeated in the DELETE itself (a page restored meanwhile keeps its row): unpaid rows are rederived from the+ * segments for free. A paid pipeline's row is never deleted unread: the record is marked stalled+ * (`paid_row_unreadable`), as it is when even the unread delete outruns its budget (`statement_timeout`). A stalled+ * 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. No batch starts past DERIVATION_SWEEP_LIMITS.totalMs; the- * next call resumes from the cursor. Returns the rows deleted.+ * until none are noted, and only then is the record deleted: under the source's scope lock (derivationScopeLockSql),+ * taken without waiting, so a page noted by a transaction still open is checked after it commits; while one is open the+ * record is left for a later call. 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.*/-export async function continueDerivationPurges(engine: BrainEngine, sourceId: string, opts: { first?: string; retry?: string } = {}): Promise<number> {- const { batchRows: maxRows, totalMs, statementMs } = sweepLimits;- const deadline = performance.now() + totalMs;+export async function continueDerivationPurges(engine: BrainEngine, sourceId: string, opts: { first?: string; retry?: string; inline?: boolean } = {}): Promise<number> {+ const { batchRows: maxRows, statementMs } = sweepLimits;+ const deadline = performance.now() + (opts.inline ? Math.min(sweepLimits.inlineMs, sweepLimits.totalMs) : sweepLimits.totalMs);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 WHERE request_id=$1::uuid', [opts.retry]);+ 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)) {@@ -478,6 +496,11 @@ export async function continueDerivationPurges(engine: BrainEngine, sourceId: stawait 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) {+ skip.push(purge.request_id);+ return;+ }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`,@@ -489,11 +512,14 @@ export async function continueDerivationPurges(engine: BrainEngine, sourceId: st}};const timedOut = (error: unknown) => (error as { code?: unknown } | null)?.code === '57014';- const stalled: string[] = [];+ const stall = async (requestId: string, reason: DerivationStallReason) => {+ await engine.executeRaw('UPDATE page_segment_derivation_purges SET stalled_at = now(), stalled_reason = $2 WHERE request_id=$1::uuid', [requestId, reason]);+ skip.push(requestId);+ };for (let batches = 0; batches === 0 || performance.now() <= deadline; batches++) {let picked: SweepRecord | null = 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[] | null;+ let rows: Row[] | 'paid' | null;try {rows = await engine.transaction(async tx => {await tx.executeRaw("SELECT set_config('statement_timeout',$1,true)", [`${statementMs}ms`]);@@ -501,7 +527,7 @@ export async function continueDerivationPurges(engine: BrainEngine, sourceId: stcursor_pipeline, cursor_occurrence::text AS cursor_occurrence, LEAST(COALESCE(batch_rows, $4), $4) AS batch_rowsFROM page_segment_derivation_purges WHERE source_id=$1 AND stalled_at IS NULL AND NOT (request_id = ANY($3::uuid[]))ORDER BY COALESCE(request_id = $2::uuid, false) DESC, created_at, request_id LIMIT 1 FOR UPDATE SKIP LOCKED`,- [sourceId, opts.first ?? null, stalled, maxRows]);+ [sourceId, opts.first ?? null, skip, maxRows]);if (!purge) return null;picked = purge;await faultPoint('purge:derivation_batch', { sourceId, requestId: purge.request_id, round: Number(purge.batch_rows),@@ -555,8 +581,11 @@ export async function continueDerivationPurges(engine: BrainEngine, sourceId: stawait endWalk(tx, purge, Number(purge.found));return [];}- const deleted = next.swept ? (await tx.executeRaw('DELETE FROM page_segment_derivations WHERE page_id=$1 AND pipeline=$2 AND occurrence_id=$3::bigint RETURNING 1',- [Number(next.page_id), next.pipeline, next.occurrence_id])).length : 0;+ if (next.swept && !UNPAID_PIPELINES.includes(next.pipeline)) return 'paid' as const;+ await beforeUnreadDelete?.(tx);+ const deleted = next.swept ? (await tx.executeRaw(`DELETE FROM page_segment_derivations d USING pages p WHERE d.page_id=$1 AND d.pipeline=$2+ AND d.occurrence_id=$3::bigint AND p.id = d.page_id AND p.source_id = $4 AND d.pipeline = ANY($6::text[]) AND ${derivationSweepScopeSql('d', 'p', '$5')} RETURNING 1`,+ [Number(next.page_id), next.pipeline, next.occurrence_id, sourceId, purge.page_ids, UNPAID_PIPELINES])).length : 0;await tx.executeRaw(`UPDATE page_segment_derivation_purges SET cursor_page=$2, cursor_pipeline=$3, cursor_occurrence=$4::bigint, found=found + $5WHERE request_id=$1::uuid`, [purge.request_id, Number(next.page_id), next.pipeline, next.occurrence_id, deleted]);return [{ page_id: Number(next.page_id), swept: next.swept ? 1 : 0, normalized: 0, deleted, scanned: 1, last_page: Number(next.page_id), last_pipeline: next.pipeline,@@ -564,8 +593,11 @@ export async function continueDerivationPurges(engine: BrainEngine, sourceId: st});} catch (unread) {if (!timedOut(unread)) throw unread;- await engine.executeRaw('UPDATE page_segment_derivation_purges SET stalled_at = now() WHERE request_id=$1::uuid', [purge.request_id]);- stalled.push(purge.request_id);+ await stall(purge.request_id, 'statement_timeout');+ continue;+ }+ if (rows === 'paid') {+ await stall(purge.request_id, 'paid_row_unreadable');continue;}}diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex edb7474138..f038b6e6ff 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -1427,6 +1427,7 @@ CREATE TABLE IF NOT EXISTS page_segment_derivation_purges (cursor_occurrence BIGINT,batch_rows INTEGER CHECK (batch_rows >= 1),stalled_at TIMESTAMPTZ,+ stalled_reason TEXT CHECK (stalled_reason IN ('statement_timeout','paid_row_unreadable')),created_at TIMESTAMPTZ NOT NULL DEFAULT now());CREATE INDEX IF NOT EXISTS page_segment_derivation_purges_source ON page_segment_derivation_purges (source_id, created_at);@@ -1436,14 +1437,23 @@ CREATE TABLE IF NOT EXISTS page_segment_derivation_purge_pages (PRIMARY KEY (request_id, page_id));CREATE OR REPLACE FUNCTION gbrain_mark_derivation_scope_entry() RETURNS trigger SET search_path = pg_catalog, public AS \$func\$+DECLARE+ src TEXT;+ page INTEGER;BEGINIF TG_TABLE_NAME = 'pages' THEN- INSERT INTO page_segment_derivation_purge_pages (request_id, page_id)- SELECT x.request_id, NEW.id FROM page_segment_derivation_purges x WHERE x.source_id = NEW.source_id ON CONFLICT DO NOTHING;+ src := NEW.source_id;+ page := NEW.id;ELSE- INSERT INTO page_segment_derivation_purge_pages (request_id, page_id)- SELECT x.request_id, OLD.page_id FROM page_segment_derivation_purges x WHERE x.source_id = OLD.source_id ON CONFLICT DO NOTHING;+ src := OLD.source_id;+ page := OLD.page_id;+ END IF;+ IF NOT EXISTS (SELECT 1 FROM page_segment_derivation_purges x WHERE x.source_id = src) THEN+ RETURN NULL;END IF;+ PERFORM pg_advisory_xact_lock_shared(hashtextextended('gbrain:derivation-scope:' || src, 0));+ INSERT INTO page_segment_derivation_purge_pages (request_id, page_id)+ SELECT x.request_id, page FROM page_segment_derivation_purges x WHERE x.source_id = src ON CONFLICT DO NOTHING;RETURN NULL;END\$func\$ LANGUAGE plpgsql;diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex 8b0dc85f35..eaea32aafc 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -2171,6 +2171,7 @@ CREATE TABLE IF NOT EXISTS page_segment_derivation_purges (cursor_occurrence BIGINT,batch_rows INTEGER CHECK (batch_rows >= 1),stalled_at TIMESTAMPTZ,+ stalled_reason TEXT CHECK (stalled_reason IN ('statement_timeout','paid_row_unreadable')),created_at TIMESTAMPTZ NOT NULL DEFAULT now());CREATE INDEX IF NOT EXISTS page_segment_derivation_purges_source ON page_segment_derivation_purges (source_id, created_at);@@ -2180,14 +2181,23 @@ CREATE TABLE IF NOT EXISTS page_segment_derivation_purge_pages (PRIMARY KEY (request_id, page_id));CREATE OR REPLACE FUNCTION gbrain_mark_derivation_scope_entry() RETURNS trigger SET search_path = pg_catalog, public AS \$func\$+DECLARE+ src TEXT;+ page INTEGER;BEGINIF TG_TABLE_NAME = 'pages' THEN- INSERT INTO page_segment_derivation_purge_pages (request_id, page_id)- SELECT x.request_id, NEW.id FROM page_segment_derivation_purges x WHERE x.source_id = NEW.source_id ON CONFLICT DO NOTHING;+ src := NEW.source_id;+ page := NEW.id;ELSE- INSERT INTO page_segment_derivation_purge_pages (request_id, page_id)- SELECT x.request_id, OLD.page_id FROM page_segment_derivation_purges x WHERE x.source_id = OLD.source_id ON CONFLICT DO NOTHING;+ src := OLD.source_id;+ page := OLD.page_id;+ END IF;+ IF NOT EXISTS (SELECT 1 FROM page_segment_derivation_purges x WHERE x.source_id = src) THEN+ RETURN NULL;END IF;+ PERFORM pg_advisory_xact_lock_shared(hashtextextended('gbrain:derivation-scope:' || src, 0));+ INSERT INTO page_segment_derivation_purge_pages (request_id, page_id)+ SELECT x.request_id, page FROM page_segment_derivation_purges x WHERE x.source_id = src ON CONFLICT DO NOTHING;RETURN NULL;END\$func\$ LANGUAGE plpgsql;diff --git a/src/schema.sql b/src/schema.sqlindex 969ac29d71..e90db4484a 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -2167,6 +2167,7 @@ CREATE TABLE IF NOT EXISTS page_segment_derivation_purges (cursor_occurrence BIGINT,batch_rows INTEGER CHECK (batch_rows >= 1),stalled_at TIMESTAMPTZ,+ stalled_reason TEXT CHECK (stalled_reason IN ('statement_timeout','paid_row_unreadable')),created_at TIMESTAMPTZ NOT NULL DEFAULT now());CREATE INDEX IF NOT EXISTS page_segment_derivation_purges_source ON page_segment_derivation_purges (source_id, created_at);@@ -2176,14 +2177,23 @@ CREATE TABLE IF NOT EXISTS page_segment_derivation_purge_pages (PRIMARY KEY (request_id, page_id));CREATE OR REPLACE FUNCTION gbrain_mark_derivation_scope_entry() RETURNS trigger SET search_path = pg_catalog, public AS $func$+DECLARE+ src TEXT;+ page INTEGER;BEGINIF TG_TABLE_NAME = 'pages' THEN- INSERT INTO page_segment_derivation_purge_pages (request_id, page_id)- SELECT x.request_id, NEW.id FROM page_segment_derivation_purges x WHERE x.source_id = NEW.source_id ON CONFLICT DO NOTHING;+ src := NEW.source_id;+ page := NEW.id;ELSE- INSERT INTO page_segment_derivation_purge_pages (request_id, page_id)- SELECT x.request_id, OLD.page_id FROM page_segment_derivation_purges x WHERE x.source_id = OLD.source_id ON CONFLICT DO NOTHING;+ src := OLD.source_id;+ page := OLD.page_id;+ END IF;+ IF NOT EXISTS (SELECT 1 FROM page_segment_derivation_purges x WHERE x.source_id = src) THEN+ RETURN NULL;END IF;+ PERFORM pg_advisory_xact_lock_shared(hashtextextended('gbrain:derivation-scope:' || src, 0));+ INSERT INTO page_segment_derivation_purge_pages (request_id, page_id)+ SELECT x.request_id, page FROM page_segment_derivation_purges x WHERE x.source_id = src ON CONFLICT DO NOTHING;RETURN NULL;END$func$ LANGUAGE plpgsql;diff --git a/test/contextual-reindex-purge-sweep.test.ts b/test/contextual-reindex-purge-sweep.test.tsnew file mode 100644index 0000000000..19df8b36a6--- /dev/null+++ b/test/contextual-reindex-purge-sweep.test.ts@@ -0,0 +1,25 @@+/**+ * Wave B PR 4 (lane 4a, G4): a per-chunk synopsis re-embed that a fact purge's pending derivation sweep blocked+ * (the page's paid synopsis was refused with purge_sweep_pending) is not reported `ok`, and its `next` points at the+ * sweep (doctor derivation_purge_sweeps and the continue command) instead of a spend cap. A spend cap's skip stays ok.+ */+import { describe, expect, test } from 'bun:test';+import { makeContextualReindexHandler } from '../src/core/minions/handlers/contextual-reindex-per-chunk.ts';+import type { ReembedPageResult } from '../src/core/contextual-retrieval-service.ts';++const engine = { async getPage() { return { source_id: 'default' }; }, async getConfig() { return null; } };+const job = { id: 7, data: { page_slug: 'notes/example' }, signal: new AbortController().signal } as never;+const handlerFor = (result: ReembedPageResult) => makeContextualReindexHandler({ engine: engine as never, reembedPage: async () => result });++describe('contextual_reindex_per_chunk: a synopsis blocked by a pending purge sweep', () => {+ test('is not ok, and next names the sweep check and the continue command', async () => {+ const out = await handlerFor({ kind: 'skipped', reason: 'purge_sweep_pending' })(job) as Record<string, any>;+ expect({ ok: out.ok, skip: out.skip_reason, check: String(out.next).includes('gbrain doctor --only derivation_purge_sweeps'),+ command: String(out.next).includes('gbrain forget --purge --status --request-id <request_id> --continue'), cap: String(out.next).includes('max_usd_per_page') })+ .toEqual({ ok: false, skip: 'purge_sweep_pending', check: true, command: true, cap: false });+ });++ test('a spend cap\'s skip stays ok', async () => {+ expect(await handlerFor({ kind: 'skipped', reason: 'budget_limited' })(job)).toEqual({ ok: true, mode_applied: 'skipped', chunks_embedded: 0, skip_reason: 'budget_limited' });+ });+});diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex 34b1767008..60be9d255e 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -270,6 +270,7 @@"page_segment_derivation_purges.page_segment_derivation_purges_phase_check": "c CHECK ((phase = ANY (ARRAY['sweep'::text, 'verify'::text, 'recheck'::text])))","page_segment_derivation_purges.page_segment_derivation_purges_pkey": "p PRIMARY KEY (request_id)","page_segment_derivation_purges.page_segment_derivation_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_segment_derivation_purges.page_segment_derivation_purges_stalled_reason_check": "c CHECK ((stalled_reason = ANY (ARRAY['statement_timeout'::text, 'paid_row_unreadable'::text])))","page_segment_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))","page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",@@ -536,7 +537,7 @@"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2","gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9","gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",- "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5675b060d5ba382f77ce7d4209ba2d035931cf50a94005241be5691bba750a7c",+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=a0c4dcd7282f771765e1328670e44a04dd28934ed88f5a51c42cc31f6bf4cc50","gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c","gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1",@@ -3011,7 +3012,8 @@"11 cursor_occurrence bigint/int8 NULL","12 batch_rows integer/int4 NULL","13 stalled_at timestamp with time zone/timestamptz NULL",- "14 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "14 stalled_reason text/text NULL",+ "15 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex 9c75c846c3..3de0e32171 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -270,6 +270,7 @@"page_segment_derivation_purges.page_segment_derivation_purges_phase_check": "c CHECK ((phase = ANY (ARRAY['sweep'::text, 'verify'::text, 'recheck'::text])))","page_segment_derivation_purges.page_segment_derivation_purges_pkey": "p PRIMARY KEY (request_id)","page_segment_derivation_purges.page_segment_derivation_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_segment_derivation_purges.page_segment_derivation_purges_stalled_reason_check": "c CHECK ((stalled_reason = ANY (ARRAY['statement_timeout'::text, 'paid_row_unreadable'::text])))","page_segment_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))","page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",@@ -536,7 +537,7 @@"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2","gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9","gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",- "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5675b060d5ba382f77ce7d4209ba2d035931cf50a94005241be5691bba750a7c",+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=a0c4dcd7282f771765e1328670e44a04dd28934ed88f5a51c42cc31f6bf4cc50","gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c","gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1",@@ -3011,7 +3012,8 @@"11 cursor_occurrence bigint/int8 NULL","12 batch_rows integer/int4 NULL","13 stalled_at timestamp with time zone/timestamptz NULL",- "14 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "14 stalled_reason text/text NULL",+ "15 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex 4fbfad255d..be62c98aa3 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -270,6 +270,7 @@"page_segment_derivation_purges.page_segment_derivation_purges_phase_check": "c CHECK ((phase = ANY (ARRAY['sweep'::text, 'verify'::text, 'recheck'::text])))","page_segment_derivation_purges.page_segment_derivation_purges_pkey": "p PRIMARY KEY (request_id)","page_segment_derivation_purges.page_segment_derivation_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_segment_derivation_purges.page_segment_derivation_purges_stalled_reason_check": "c CHECK ((stalled_reason = ANY (ARRAY['statement_timeout'::text, 'paid_row_unreadable'::text])))","page_segment_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))","page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",@@ -536,7 +537,7 @@"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2","gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9","gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",- "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5675b060d5ba382f77ce7d4209ba2d035931cf50a94005241be5691bba750a7c",+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=a0c4dcd7282f771765e1328670e44a04dd28934ed88f5a51c42cc31f6bf4cc50","gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c","gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1",@@ -3007,7 +3008,8 @@"11 cursor_occurrence bigint/int8 NULL","12 batch_rows integer/int4 NULL","13 stalled_at timestamp with time zone/timestamptz NULL",- "14 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "14 stalled_reason text/text NULL",+ "15 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.jsonindex da02fde4b7..6855bc7cd4 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json@@ -197,6 +197,7 @@"page_segment_derivation_purges.page_segment_derivation_purges_phase_check": "c CHECK ((phase = ANY (ARRAY['sweep'::text, 'verify'::text, 'recheck'::text])))","page_segment_derivation_purges.page_segment_derivation_purges_pkey": "p PRIMARY KEY (request_id)","page_segment_derivation_purges.page_segment_derivation_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_segment_derivation_purges.page_segment_derivation_purges_stalled_reason_check": "c CHECK ((stalled_reason = ANY (ARRAY['statement_timeout'::text, 'paid_row_unreadable'::text])))","page_segment_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))","page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",@@ -398,7 +399,7 @@"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2","gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9","gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",- "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5675b060d5ba382f77ce7d4209ba2d035931cf50a94005241be5691bba750a7c",+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=a0c4dcd7282f771765e1328670e44a04dd28934ed88f5a51c42cc31f6bf4cc50","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c","gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0d0afb3e61857f1668f2e7996da1c6aaf269aecaa1bf3763ce90df90e2d66fd3","gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859",@@ -2273,7 +2274,8 @@"11 cursor_occurrence bigint/int8 NULL","12 batch_rows integer/int4 NULL","13 stalled_at timestamp with time zone/timestamptz NULL",- "14 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "14 stalled_reason text/text NULL",+ "15 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.jsonindex 4ce51b489c..ff04e9a7c5 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json@@ -197,6 +197,7 @@"page_segment_derivation_purges.page_segment_derivation_purges_phase_check": "c CHECK ((phase = ANY (ARRAY['sweep'::text, 'verify'::text, 'recheck'::text])))","page_segment_derivation_purges.page_segment_derivation_purges_pkey": "p PRIMARY KEY (request_id)","page_segment_derivation_purges.page_segment_derivation_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_segment_derivation_purges.page_segment_derivation_purges_stalled_reason_check": "c CHECK ((stalled_reason = ANY (ARRAY['statement_timeout'::text, 'paid_row_unreadable'::text])))","page_segment_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))","page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",@@ -398,7 +399,7 @@"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2","gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9","gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",- "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5675b060d5ba382f77ce7d4209ba2d035931cf50a94005241be5691bba750a7c",+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=a0c4dcd7282f771765e1328670e44a04dd28934ed88f5a51c42cc31f6bf4cc50","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c","gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0d0afb3e61857f1668f2e7996da1c6aaf269aecaa1bf3763ce90df90e2d66fd3","gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859",@@ -2273,7 +2274,8 @@"11 cursor_occurrence bigint/int8 NULL","12 batch_rows integer/int4 NULL","13 stalled_at timestamp with time zone/timestamptz NULL",- "14 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "14 stalled_reason text/text NULL",+ "15 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.jsonindex 0b024b8e0e..fcb3c303ad 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json@@ -197,6 +197,7 @@"page_segment_derivation_purges.page_segment_derivation_purges_phase_check": "c CHECK ((phase = ANY (ARRAY['sweep'::text, 'verify'::text, 'recheck'::text])))","page_segment_derivation_purges.page_segment_derivation_purges_pkey": "p PRIMARY KEY (request_id)","page_segment_derivation_purges.page_segment_derivation_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_segment_derivation_purges.page_segment_derivation_purges_stalled_reason_check": "c CHECK ((stalled_reason = ANY (ARRAY['statement_timeout'::text, 'paid_row_unreadable'::text])))","page_segment_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))","page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",@@ -398,7 +399,7 @@"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2","gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9","gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",- "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5675b060d5ba382f77ce7d4209ba2d035931cf50a94005241be5691bba750a7c",+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=a0c4dcd7282f771765e1328670e44a04dd28934ed88f5a51c42cc31f6bf4cc50","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c","gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0d0afb3e61857f1668f2e7996da1c6aaf269aecaa1bf3763ce90df90e2d66fd3","gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859",@@ -2272,7 +2273,8 @@"11 cursor_occurrence bigint/int8 NULL","12 batch_rows integer/int4 NULL","13 stalled_at timestamp with time zone/timestamptz NULL",- "14 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "14 stalled_reason text/text NULL",+ "15 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.jsonindex 876a7d39a3..dfcca411b7 100644--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json@@ -208,6 +208,7 @@"page_segment_derivation_purges.page_segment_derivation_purges_phase_check": "c CHECK ((phase = ANY (ARRAY['sweep'::text, 'verify'::text, 'recheck'::text])))","page_segment_derivation_purges.page_segment_derivation_purges_pkey": "p PRIMARY KEY (request_id)","page_segment_derivation_purges.page_segment_derivation_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_segment_derivation_purges.page_segment_derivation_purges_stalled_reason_check": "c CHECK ((stalled_reason = ANY (ARRAY['statement_timeout'::text, 'paid_row_unreadable'::text])))","page_segment_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))","page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",@@ -407,7 +408,7 @@"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2","gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9","gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",- "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5675b060d5ba382f77ce7d4209ba2d035931cf50a94005241be5691bba750a7c",+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=a0c4dcd7282f771765e1328670e44a04dd28934ed88f5a51c42cc31f6bf4cc50","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c","gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0d0afb3e61857f1668f2e7996da1c6aaf269aecaa1bf3763ce90df90e2d66fd3","gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859",@@ -2341,7 +2342,8 @@"11 cursor_occurrence bigint/int8 NULL","12 batch_rows integer/int4 NULL","13 stalled_at timestamp with time zone/timestamptz NULL",- "14 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "14 stalled_reason text/text NULL",+ "15 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex d694b1ce30..2f6c64c1b7 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -274,6 +274,7 @@"page_segment_derivation_purges.page_segment_derivation_purges_phase_check": "c CHECK ((phase = ANY (ARRAY['sweep'::text, 'verify'::text, 'recheck'::text])))","page_segment_derivation_purges.page_segment_derivation_purges_pkey": "p PRIMARY KEY (request_id)","page_segment_derivation_purges.page_segment_derivation_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_segment_derivation_purges.page_segment_derivation_purges_stalled_reason_check": "c CHECK ((stalled_reason = ANY (ARRAY['statement_timeout'::text, 'paid_row_unreadable'::text])))","page_segment_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))","page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",@@ -539,7 +540,7 @@"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2","gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9","gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",- "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5675b060d5ba382f77ce7d4209ba2d035931cf50a94005241be5691bba750a7c",+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=a0c4dcd7282f771765e1328670e44a04dd28934ed88f5a51c42cc31f6bf4cc50","gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c","gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1",@@ -3023,7 +3024,8 @@"11 cursor_occurrence bigint/int8 NULL","12 batch_rows integer/int4 NULL","13 stalled_at timestamp with time zone/timestamptz NULL",- "14 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "14 stalled_reason text/text NULL",+ "15 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex 42483c2612..b7b197e273 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -274,6 +274,7 @@"page_segment_derivation_purges.page_segment_derivation_purges_phase_check": "c CHECK ((phase = ANY (ARRAY['sweep'::text, 'verify'::text, 'recheck'::text])))","page_segment_derivation_purges.page_segment_derivation_purges_pkey": "p PRIMARY KEY (request_id)","page_segment_derivation_purges.page_segment_derivation_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_segment_derivation_purges.page_segment_derivation_purges_stalled_reason_check": "c CHECK ((stalled_reason = ANY (ARRAY['statement_timeout'::text, 'paid_row_unreadable'::text])))","page_segment_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))","page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",@@ -539,7 +540,7 @@"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2","gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9","gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",- "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5675b060d5ba382f77ce7d4209ba2d035931cf50a94005241be5691bba750a7c",+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=a0c4dcd7282f771765e1328670e44a04dd28934ed88f5a51c42cc31f6bf4cc50","gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c","gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1",@@ -3023,7 +3024,8 @@"11 cursor_occurrence bigint/int8 NULL","12 batch_rows integer/int4 NULL","13 stalled_at timestamp with time zone/timestamptz NULL",- "14 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "14 stalled_reason text/text NULL",+ "15 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex 27a554598a..cdbb3fbe48 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -274,6 +274,7 @@"page_segment_derivation_purges.page_segment_derivation_purges_phase_check": "c CHECK ((phase = ANY (ARRAY['sweep'::text, 'verify'::text, 'recheck'::text])))","page_segment_derivation_purges.page_segment_derivation_purges_pkey": "p PRIMARY KEY (request_id)","page_segment_derivation_purges.page_segment_derivation_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_segment_derivation_purges.page_segment_derivation_purges_stalled_reason_check": "c CHECK ((stalled_reason = ANY (ARRAY['statement_timeout'::text, 'paid_row_unreadable'::text])))","page_segment_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))","page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",@@ -539,7 +540,7 @@"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2","gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9","gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",- "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5675b060d5ba382f77ce7d4209ba2d035931cf50a94005241be5691bba750a7c",+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=a0c4dcd7282f771765e1328670e44a04dd28934ed88f5a51c42cc31f6bf4cc50","gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c","gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1",@@ -3019,7 +3020,8 @@"11 cursor_occurrence bigint/int8 NULL","12 batch_rows integer/int4 NULL","13 stalled_at timestamp with time zone/timestamptz NULL",- "14 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "14 stalled_reason text/text NULL",+ "15 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.jsonindex 9fdaaeae36..948d41a303 100644--- a/test/fixtures/goldens/doctor/content-pglite-human.json+++ b/test/fixtures/goldens/doctor/content-pglite-human.json@@ -78,7 +78,7 @@" [OK] pglite_scale: PGLite at 5 pages — comfortable below the 1000-page threshold"," [OK] rls: Skipped (PGLite — no PostgREST exposure, RLS not applicable)"," [OK] schema_version: Version <latest> (latest: <latest>)",- " [OK] schema_columns: 1329 column(s) verified against live schema",+ " [OK] schema_columns: 1330 column(s) verified against live schema"," [OK] schema_missing_tables: All 156 table(s) the applied migrations create exist."," [OK] rls_event_trigger: Skipped (PGLite — no event trigger support)"," [INFO] embeddings: Not applicable: embeddings are disabled on this brain (keyword search keeps working).",@@ -215,6 +215,7 @@" [OK] origin_twins: pages_live_origin_key is present: no two live pages can record one file."," [OK] rename_identity_downgrades: No rename that lost its page identity is waiting for a disposition."," [OK] purge_parked_pages: No soft-deleted page is parked by the managed purge.",+ " [OK] derivation_purge_sweeps: No fact purge has a sweep of stored derivation results pending or stalled."," [INFO] missing_recorded_files: Not applicable: no source is a classic checkout on this host (managed sources are checked by ghost_pages)."," [OK] uncommitted_sync_deletions: No soft-deleted page was removed by a sync while Git never held its file (0 tombstone(s) checked)."," [INFO] unindexed_files: Unindexed files are not known for default (not computed yet), notes (not computed yet). The maintenance phase unindexed_files computes them on each run and continues an incomplete scan; to compute them now, run gbrain sources retry-held <id> --unindexed.",diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.jsonindex f7a9cfa08a..483e095089 100644--- a/test/fixtures/goldens/doctor/content-pglite-json.json+++ b/test/fixtures/goldens/doctor/content-pglite-json.json@@ -1036,7 +1036,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "1329 column(s) verified against live schema",+ "message": "1330 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -3212,6 +3212,16 @@"name": "purge_parked_pages","status": "ok"},+ {+ "category": "brain",+ "details": {+ "sweeps": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "No fact purge has a sweep of stored derivation results pending or stalled.",+ "name": "derivation_purge_sweeps",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.jsonindex 03017c51c5..7cd23e0eb2 100644--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json@@ -1107,7 +1107,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "1329 column(s) verified against live schema",+ "message": "1330 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -3420,6 +3420,16 @@"name": "purge_parked_pages","status": "ok"},+ {+ "category": "brain",+ "details": {+ "sweeps": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "No fact purge has a sweep of stored derivation results pending or stalled.",+ "name": "derivation_purge_sweeps",+ "status": "ok"+ },{"category": "brain","details": {@@ -5627,7 +5637,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "1329 column(s) verified against live schema",+ "message": "1330 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -7940,6 +7950,16 @@"name": "purge_parked_pages","status": "ok"},+ {+ "category": "brain",+ "details": {+ "sweeps": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "No fact purge has a sweep of stored derivation results pending or stalled.",+ "name": "derivation_purge_sweeps",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex 0701d9bb9a..c1fc26dc9e 100644--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json@@ -1103,7 +1103,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "1335 column(s) verified against live schema",+ "message": "1336 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -3423,6 +3423,16 @@"name": "purge_parked_pages","status": "ok"},+ {+ "category": "brain",+ "details": {+ "sweeps": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "No fact purge has a sweep of stored derivation results pending or stalled.",+ "name": "derivation_purge_sweeps",+ "status": "ok"+ },{"category": "brain","details": {@@ -5624,7 +5634,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "1335 column(s) verified against live schema",+ "message": "1336 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -7944,6 +7954,16 @@"name": "purge_parked_pages","status": "ok"},+ {+ "category": "brain",+ "details": {+ "sweeps": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "No fact purge has a sweep of stored derivation results pending or stalled.",+ "name": "derivation_purge_sweeps",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 8ccdd54f11..6e3dba9060 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -949,7 +949,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "1329 column(s) verified against live schema",+ "message": "1330 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -2928,6 +2928,16 @@"name": "purge_parked_pages","status": "ok"},+ {+ "category": "brain",+ "details": {+ "sweeps": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "No fact purge has a sweep of stored derivation results pending or stalled.",+ "name": "derivation_purge_sweeps",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 09f7dafe58..eae3cb499a 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -996,7 +996,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "1329 column(s) verified against live schema",+ "message": "1330 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -2972,6 +2972,16 @@"name": "purge_parked_pages","status": "ok"},+ {+ "category": "brain",+ "details": {+ "sweeps": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "No fact purge has a sweep of stored derivation results pending or stalled.",+ "name": "derivation_purge_sweeps",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 5ac110d6e8..a5014cbe15 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -992,7 +992,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "1335 column(s) verified against live schema",+ "message": "1336 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -2975,6 +2975,16 @@"name": "purge_parked_pages","status": "ok"},+ {+ "category": "brain",+ "details": {+ "sweeps": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "No fact purge has a sweep of stored derivation results pending or stalled.",+ "name": "derivation_purge_sweeps",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex 7925ba98b5..2acc8ab7fd 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -909,6 +909,10 @@"category": "brain","name": "purge_parked_pages"},+ {+ "category": "brain",+ "name": "derivation_purge_sweeps"+ },{"category": "brain","name": "missing_recorded_files"diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 068c8fd2ad..8177090edd 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -4218,8 +4218,8 @@"idempotent": true,"name": "segment_derivations","sql": {- "length": 6369,- "sha256": "1334aad47cf3eb04efe03ab06d8c68f924ec1a389a158d63d7cd8168046c0dda"+ "length": 6595,+ "sha256": "d666eb4f6eab38464426254377470c3f8d4c33107e6368147280d71dada69e65"},"sqlFor": "absent","transaction": false,diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.jsonindex 144e9dcee8..7cea47c4e6 100644--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json@@ -270,6 +270,7 @@"page_segment_derivation_purges.page_segment_derivation_purges_phase_check": "c CHECK ((phase = ANY (ARRAY['sweep'::text, 'verify'::text, 'recheck'::text])))","page_segment_derivation_purges.page_segment_derivation_purges_pkey": "p PRIMARY KEY (request_id)","page_segment_derivation_purges.page_segment_derivation_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_segment_derivation_purges.page_segment_derivation_purges_stalled_reason_check": "c CHECK ((stalled_reason = ANY (ARRAY['statement_timeout'::text, 'paid_row_unreadable'::text])))","page_segment_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))","page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",@@ -536,7 +537,7 @@"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=12baf1d365a8aa3009ac0fe6605497e6433304e8d5915a3fc0b0b39ad748f6c2","gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9","gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",- "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5675b060d5ba382f77ce7d4209ba2d035931cf50a94005241be5691bba750a7c",+ "gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=a0c4dcd7282f771765e1328670e44a04dd28934ed88f5a51c42cc31f6bf4cc50","gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c","gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1",@@ -3011,7 +3012,8 @@"11 cursor_occurrence bigint/int8 NULL","12 batch_rows integer/int4 NULL","13 stalled_at timestamp with time zone/timestamptz NULL",- "14 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "14 stalled_reason text/text NULL",+ "15 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/helpers/derivation-purge-cases.ts b/test/helpers/derivation-purge-cases.tsindex 1c1f175b96..1373d224a0 100644--- a/test/helpers/derivation-purge-cases.ts+++ b/test/helpers/derivation-purge-cases.ts@@ -11,9 +11,14 @@ 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 { __setAfterDerivationSweepBatchForTests, __setBeforeDerivationWriteForTests, __setDerivationSweepLimitsForTests, __setDerivationSweepWorkForTests, derivationSweepStatements, derivationSweepWork,+import { __setAfterDerivationSweepBatchForTests, __setBeforeDerivationWriteForTests, __setBeforeUnreadDerivationDeleteForTests, __setDerivationSweepLimitsForTests,+ __setDerivationSweepWorkForTests, continueDerivationPurges, DERIVATION_SWEEP_LIMITS, 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';+import { derivationPurgeSweepsEntry } from '../../src/commands/doctor/checks/derivation-purge-sweeps.ts';+import { extractionInputTruncatedEntry } from '../../src/commands/doctor/checks/extraction-input.ts';+import { categorizeCheck } from '../../src/core/doctor-categories.ts';import { incrementalFactsFenceView, segmentedFactsFenceView } from '../../src/core/page-body/segment-facts.ts';import { forgetFactInFence } from '../../src/core/facts/forget.ts';import { PAGE_EMBED_CAP_KEY } from '../../src/core/page-embedding-budget.ts';@@ -435,6 +440,8 @@ export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): voidtest('a sweep call starts no batch past its deadline, also after the last short batch of a sweep', async () => {const claimA = 'Purge Example cellar code is 5307', claimB = 'Purge Example attic code is 6418';+ // Rows ahead of the holder in key order, so the first 100-row batch never reaches it, even when this test runs alone.+ await candidateRowsPage('notes/sweep-deadline-pad', 'Purge Example padding row is 0001', 150, 0);const rows = await candidateRowsPage('notes/sweep-deadline-rows', claimA, 300, 1);const a = await confirmed(await seed('notes/sweep-deadline-a', claimA));const idB = await seed('notes/sweep-deadline-b', claimB);@@ -454,6 +461,7 @@ export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): voidconst replay = await brain.call('purge_fact', a);expect({ replayed: replay.body.replayed, sweep: replay.body.derivation_sweep, recorded: await sweepsRecorded() }).toEqual({ replayed: true, sweep: undefined, recorded: 0 });+ expect(await exactHolders(brain.engine, rows, claimA)).toEqual([]);} finally {__setDerivationSweepLimitsForTests(null);__setDerivationSweepWorkForTests(false);@@ -510,8 +518,13 @@ export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): voidrounds.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); }+ try { receipt = await purge(id); } finally {+ installFaultHook(undefined);+ __setDerivationSweepLimitsForTests(null);+ }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() })@@ -614,5 +627,147 @@ export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): voidexpect(resumed.body.derivation_sweep).toBeUndefined();expect(await run()).toBeGreaterThan(0);}, 600_000);++ test('a page entering a sweep\'s scope in a transaction still open as the sweep would end is swept after it commits, leaving no row holding the claim', async () => {+ const claim = 'Purge Example well code is 4821', planted = 'Alice Example said Purge Example well code is 4821';+ await brain.seed('notes/sweep-race-live', prosePage(planted, 67));+ const live = await storedPage(brain.engine, 'notes/sweep-race-live');+ await deriveAll(brain.engine, live);+ expect((await exactHolders(brain.engine, live.id, planted)).length).toBeGreaterThan(0);+ const params = await confirmed(await seed('notes/sweep-race-purge', claim));+ __setDerivationSweepLimitsForTests({ totalMs: 0 });+ try { expect((await brain.call('purge_fact', params)).body.derivation_sweep).toBe('pending'); } finally { __setDerivationSweepLimitsForTests(null); }+ // The import soft-deletes the page, so its rows enter the sweep's scope; on Postgres it stays open while the sweep runs to its end.+ const softDelete = 'UPDATE pages SET deleted_at = now() WHERE id = $1';+ let commit = async () => {};+ if (kind === 'postgres') {+ const opened = Promise.withResolvers<void>(), release = Promise.withResolvers<void>();+ const held = (brain.engine as any).sql.begin(async (tx: any) => { await tx.unsafe(softDelete, [live.id]); opened.resolve(); await release.promise; });+ await opened.promise;+ commit = async () => { release.resolve(); await held; };+ } else await brain.engine.executeRaw(softDelete, [live.id]);+ let open: Record<string, any>;+ try { open = (await brain.call('purge_fact', { status: true, request_id: params.request_id, continue: true })).body; } finally { await commit(); }+ expect(open!.derivation_sweep).toBe(kind === 'postgres' ? 'pending' : undefined);+ const done = (await brain.call('purge_fact', { status: true, request_id: params.request_id, continue: true })).body;+ expect({ sweep: done.derivation_sweep, rows: await exactHolders(brain.engine, live.id, planted), recorded: await sweepsRecorded() })+ .toEqual({ sweep: undefined, rows: [], recorded: 0 });+ }, 600_000);++ /**+ * A source of its own with one page holding one `pipeline` row, the page soft-deleted (so the row is in a sweep's scope), and a sweep recorded for+ * it. `backed`: a live manifest occurrence backs the row, so only the soft delete puts it in the scope.+ */+ const unreadFixture = async (source: string, pipeline: string, backed: boolean) => {+ await brain.engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1) ON CONFLICT DO NOTHING', [source]);+ await brain.engine.putPage('notes/unread-fixture', { type: 'note', title: 'Unread Fixture', compiled_truth: 'Unread 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, 'notes/unread-fixture']);+ const page = Number(row!.id);+ if (backed) {+ await brain.engine.executeRaw(`INSERT INTO page_segment_texts (source_id, sha256, byte_len, line_count, body) VALUES ($1, decode(repeat('00', 32), 'hex'), 1, 1, convert_to('x', 'UTF8'))`, [source]);+ await brain.engine.executeRaw(`INSERT INTO page_body_manifest (page_id, occurrence_id, gen_from, seq, region, source_id, sha256, byte_start, byte_len, line_start, line_count, cut_kind,+ entry_state, static_proj_bytes, static_proj_lines, hash_state)+ VALUES ($1, 1, 1, 0, 'truth', $2, decode(repeat('00', 32), 'hex'), 0, 1, 0, 1, 'eof', '{}'::jsonb, 0, 0, decode(repeat('00', 32), 'hex'))`, [page, source]);+ }+ 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, $2, 1, 1, decode(repeat('00', 32), 'hex'), decode(repeat('00', 32), 'hex'), 'done', '{"note":"a paid or unpaid result"}'::jsonb, NULL)`, [page, pipeline]);+ await brain.engine.executeRaw('UPDATE pages SET deleted_at = now() WHERE id = $1', [page]);+ const requestId = randomUUID();+ await brain.engine.executeRaw(`INSERT INTO page_segment_derivation_purges (request_id, source_id, needles, patterns) VALUES ($1::uuid, $2, ARRAY[' purge example never stated '], ARRAY['%purge%example%never%stated%'])`,+ [requestId, source]);+ return { page, requestId, rows: async () => (await brain.engine.readSegmentDerivations(page)).length };+ };++ test('an unread delete keeps the row of a page restored after the sweep picked it (the scope is checked in the DELETE)', async () => {+ const fixture = await unreadFixture('unread-restore', 'links', true);+ installFaultHook(point => { if (point === 'purge:derivation_batch') throw timeout(); });+ __setBeforeUnreadDerivationDeleteForTests(async tx => { await tx.executeRaw('UPDATE pages SET deleted_at = NULL WHERE id = $1', [fixture.page]); });+ try { await continueDerivationPurges(brain.engine, 'unread-restore', { first: fixture.requestId }); } finally {+ installFaultHook(undefined);+ __setBeforeUnreadDerivationDeleteForTests(null);+ }+ expect({ rows: await fixture.rows(), sweep: await derivationPurgeState(brain.engine, fixture.requestId) }).toEqual({ rows: 1, sweep: null });+ }, 600_000);++ test('a paid row that alone outruns the budget is never deleted unread: the sweep stalls with a named reason, and a retry that fits sweeps it', async () => {+ const fixture = await unreadFixture('unread-paid', 'extract_atoms', false);+ installFaultHook(point => { if (point === 'purge:derivation_batch') throw timeout(); });+ try { await continueDerivationPurges(brain.engine, 'unread-paid', { first: fixture.requestId }); } finally { installFaultHook(undefined); }+ expect({ rows: await fixture.rows(), sweep: await derivationPurgeState(brain.engine, fixture.requestId) })+ .toEqual({ rows: 1, sweep: { state: 'stalled', reason: 'paid_row_unreadable' } });+ await continueDerivationPurges(brain.engine, 'unread-paid', { first: fixture.requestId, retry: fixture.requestId });+ expect({ rows: await fixture.rows(), sweep: await derivationPurgeState(brain.engine, fixture.requestId) }).toEqual({ rows: 1, sweep: null });+ }, 600_000);++ test('a purge returns pending once it recorded its sweep and its own bounded call ran, and --status --continue finishes it', async () => {+ const claim = 'Purge Example gate code is 7302';+ const rows = await candidateRowsPage('notes/sweep-inline-rows', claim, 300, 1);+ const params = await confirmed(await seed('notes/sweep-inline-purge', claim));+ __setDerivationSweepLimitsForTests({ batchRows: 100, inlineMs: 0 });+ __setDerivationSweepWorkForTests(true);+ try {+ const first = (await brain.call('purge_fact', params)).body;+ expect({ sweep: first.derivation_sweep, completion: first.completion, exit: first.exit_code, statements: sweepStatements().length })+ .toEqual({ sweep: 'pending', completion: 'incomplete', exit: 75, statements: 1 });+ expect((first.next as string[]).some(n => n.includes(`gbrain forget --purge --status --request-id ${params.request_id} --continue`))).toBe(true);+ const done = (await brain.call('purge_fact', { status: true, request_id: params.request_id, continue: true })).body;+ expect(done.derivation_sweep).toBeUndefined();+ } finally {+ __setDerivationSweepLimitsForTests(null);+ __setDerivationSweepWorkForTests(false);+ }+ expect({ rows: await exactHolders(brain.engine, rows, claim), recorded: await sweepsRecorded() }).toEqual({ rows: [], recorded: 0 });+ }, 600_000);++ test('a receipt probe stopped by its deadline reports a verified, finished sweep\'s result and says so; with the sweep pending it is unverified and next continues it', async () => {+ const claimA = 'Purge Example dock code is 5190', claimB = 'Purge Example pier code is 6203';+ const rowsA = await candidateRowsPage('notes/sweep-probe-rows-a', claimA, 20, 2);+ const idA = await seed('notes/sweep-probe-a', claimA);+ __setPurgeProbeLimitsForTests({ totalMs: 0 });+ let verified: Record<string, any>;+ try { verified = await purge(idA); } finally { __setPurgeProbeLimitsForTests(null); }+ const store = derivationStore(verified!)! as Record<string, any>;+ expect({ sweep: verified!.derivation_sweep, status: store.status, reason: store.reason, probe: store.probe, rows: await exactHolders(brain.engine, rowsA, claimA) })+ .toEqual({ sweep: undefined, status: 'deleted', reason: 'verified_by_sweep', probe: 'verification_deadline', rows: [] });+ complete(verified!);+ await candidateRowsPage('notes/sweep-probe-rows-b', claimB, 20, 2);+ const params = await confirmed(await seed('notes/sweep-probe-b', claimB));+ __setPurgeProbeLimitsForTests({ totalMs: 0 });+ __setDerivationSweepLimitsForTests({ totalMs: 0 });+ let pending: Record<string, any>;+ try { pending = (await brain.call('purge_fact', params)).body; } finally {+ __setPurgeProbeLimitsForTests(null);+ __setDerivationSweepLimitsForTests(null);+ }+ const open = derivationStore(pending!)! as Record<string, any>;+ expect({ sweep: pending!.derivation_sweep, status: open.status, reason: open.reason }).toEqual({ sweep: 'pending', status: 'unverified', reason: 'verification_deadline' });+ expect((pending!.next as string[]).some(n => n.includes(`gbrain forget --purge --status --request-id ${params.request_id} --continue`))).toBe(true);+ const done = (await brain.call('purge_fact', { status: true, request_id: params.request_id, continue: true })).body;+ expect({ sweep: done.derivation_sweep, recorded: await sweepsRecorded() }).toEqual({ sweep: undefined, recorded: 0 });+ }, 600_000);++ test('doctor names a pending sweep with its request id and the command that continues it, and atom receipts it blocked point there, not at the spend cap', async () => {+ const claim = 'Purge Example loft code is 8461';+ await candidateRowsPage('notes/sweep-doctor-rows', claim, 300, 0);+ const params = await confirmed(await seed('notes/sweep-doctor-purge', claim));+ __setDerivationSweepLimitsForTests({ batchRows: 50, totalMs: 0 });+ try { expect((await brain.call('purge_fact', params)).body.derivation_sweep).toBe('pending'); } finally { __setDerivationSweepLimitsForTests(null); }+ const [check] = await derivationPurgeSweepsEntry.run({ engine: brain.engine } as never) as Array<Record<string, any>>;+ const command = `gbrain forget --purge --status --request-id ${params.request_id} --continue`;+ expect({ status: check!.status, named: check!.message.includes(params.request_id), argv: check!.fix?.argv, category: categorizeCheck('derivation_purge_sweeps') })+ .toEqual({ status: 'warn', named: true, argv: command.split(' '), category: 'brain' });+ expect(check!.details.records).toContainEqual(expect.objectContaining({ request_id: params.request_id, state: 'pending', command }));+ const page = await storedPage(brain.engine, 'notes/sweep-doctor-purge');+ 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, 'extract_atoms', 999999, 1, decode(repeat('00', 32), 'hex'), decode(repeat('00', 32), 'hex'), 'partial', '{"windows":[]}'::jsonb,+ jsonb_build_object('kind', 'unread_windows', 'pipeline', 'extract_atoms', 'reason', 'purge_sweep_pending', 'windows_read', 0, 'windows_total', 2))`, [page.id]);+ const [truncated] = (await extractionInputTruncatedEntry.run({ engine: brain.engine } as never) as Array<Record<string, any>>).filter(c => c.name === 'extraction_input_truncated');+ const group = (truncated!.details.groups as Array<Record<string, any>>).find(g => g.pipeline === 'extract_atoms' && g.kind === 'purge_sweep_pending');+ expect({ remedy: group?.remedy.includes('derivation_purge_sweeps'), cap: group?.remedy.includes(PAGE_DERIVATION_CAP_KEY) }).toEqual({ remedy: true, cap: false });+ await brain.engine.executeRaw("DELETE FROM page_segment_derivations WHERE page_id=$1 AND pipeline='extract_atoms' AND occurrence_id=999999", [page.id]);+ expect((await brain.call('purge_fact', { status: true, request_id: params.request_id, continue: true })).body.derivation_sweep).toBeUndefined();+ const [clear] = await derivationPurgeSweepsEntry.run({ engine: brain.engine } as never) as Array<Record<string, any>>;+ expect(clear!.status).toBe('ok');+ }, 600_000);});}diff --git a/test/helpers/synopsis-segment-hash-cases.ts b/test/helpers/synopsis-segment-hash-cases.tsindex 8dc56e3d5f..c52d5cb769 100644--- a/test/helpers/synopsis-segment-hash-cases.ts+++ b/test/helpers/synopsis-segment-hash-cases.ts@@ -447,6 +447,30 @@ export function defineSynopsisSegmentHashCases(opts: { getBrain: () => AppendBraexpect(check.status).not.toBe('warn');}, 300_000);+ test('a pending fact purge sweep covering the page skips its synopsis as purge_sweep_pending (no call), and doctor points at the sweep, not the cap', async () => {+ const brain = opts.getBrain();+ await roomyCap();+ const slug = 'notes/synopsis-purge-sweep';+ await brain.seed(slug, page(days(1_300_000).body + '\nPurge sweep fixture.\n'));+ const { id } = await pageRow(slug);+ const requestId = randomUUID();+ await brain.engine.executeRaw(`INSERT INTO page_segment_derivation_purges (request_id, source_id, needles, patterns, page_ids)+ VALUES ($1::uuid, 'default', ARRAY[' purge example never stated '], ARRAY['%purge%example%never%stated%'], ARRAY[$2::int])`, [requestId, id]);+ try {+ reset();+ expect(await run(slug)).toEqual({ kind: 'skipped', reason: 'purge_sweep_pending' });+ expect(calls.length).toBe(0);+ const check = (await extractionInputTruncatedEntry.run({ engine: brain.engine } as unknown as DoctorContext) as Check[]).find(c => c.name === 'extraction_input_truncated')!;+ const group = (check.details as { groups: Array<{ pipeline: string; kind: string; remedy: string | null }> }).groups.find(g => g.pipeline === 'synopsis');+ expect({ kind: group?.kind, sweep: group?.remedy?.includes('derivation_purge_sweeps'), cap: group?.remedy?.includes(PAGE_DERIVATION_CAP_KEY), fix: check.fix?.argv })+ .toEqual({ kind: 'purge_sweep_pending', sweep: true, cap: false, fix: ['gbrain', 'doctor', '--only', 'derivation_purge_sweeps', '--json'] });+ } finally {+ await brain.engine.executeRaw('DELETE FROM page_segment_derivation_purges WHERE request_id = $1::uuid', [requestId]);+ }+ reset();+ expect(await run(slug)).toMatchObject({ kind: 'success', mode_applied: 'per_chunk_synopsis' });+ }, 300_000);+const ledger = async (pageId: number, table: 'page_derivation_spend' | 'page_embedding_budget') => (await opts.getBrain().engine.executeRaw<{ spent: number | string; reserved: number | string }>(`SELECT spent_usd AS spent, reserved_usd AS reserved FROM ${table} WHERE page_id = $1${table === 'page_derivation_spend' ? " AND family = 'synopsis'" : ''}`, [pageId])).map(r => ({ spent: Number(r.spent), reserved: Number(r.reserved) }))[0] ?? null;