Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
lane 4a round 10: a sweep blocked by an open scope writer says scope_lock_busy
garrytan353f348b4af9
diff --git a/src/commands/doctor/checks/derivation-purge-sweeps.ts b/src/commands/doctor/checks/derivation-purge-sweeps.tsindex 79108a1c66..9aeca8b74e 100644--- a/src/commands/doctor/checks/derivation-purge-sweeps.ts+++ b/src/commands/doctor/checks/derivation-purge-sweeps.ts@@ -16,9 +16,9 @@ export const continueSweepArgv = (requestId: string): string[] => ['gbrain', 'foasync 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 }>;+ let rows: Array<{ request_id: string | null; source_id: string; stalled: boolean; reason: string | null; pending_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,+ 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.pending_reason,x.created_at::text AS created_atFROM 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) {@@ -30,14 +30,16 @@ async function runDerivationPurgeSweeps(ctx: DoctorContext): Promise<Check[]> {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.stalled ? { reason: row.reason ?? 'statement_timeout' } : row.pending_reason ? { reason: row.pending_reason } : {}), 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;+ const busy = sweeps.some(s => s.reason === 'scope_lock_busy');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). '+ + (busy ? 'A sweep marked scope_lock_busy has walked to its end and waits only for a write in its source that is still open (an import, sync or page edit): let that write finish, then continue it. ' : '')+ `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 the stored results in the sweep\'s scope that hold the claim the user already purged, and an unpaid result in that scope that alone cannot be read within the statement budget, unread, whether or not it holds the claim (unpaid results are derived again from the page at no cost; a paid one is never deleted unread). Run it for each request id listed until its completion is complete.' } }diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex b0c3dd8e1a..89fb972bbc 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1079,6 +1079,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: 'TBD', text: 'A fact purge\'s sweep of stored link, mention, timeline and fence results no longer stops for good on large results: a batch that runs past its 5-second statement budget is retried in half as many results, down to one, and a single result that still runs past it is deleted without being read (stored results are rebuilt from the page). Only when even that delete runs past the budget does the sweep stop; its receipt then says `derivation_sweep: stalled`, and other sweeps in the source go on. A purge now sweeps for its own claim first, so an earlier slow sweep no longer holds it back. `gbrain forget --purge --status --request-id <id> --continue` (new) continues a pending or stalled sweep after the fact is gone, and the receipt\'s `next` names it. Before a sweep ends it walks the stored results again until a walk deletes nothing, and walks again the pages where a result entered its scope meanwhile (a segment replaced, a page deleted), so no result holding the claim is left behind. While a sweep is pending, paid atom, synopsis and fact extraction makes no call on a page it covers (receipts say `purge_sweep_pending`), instead of paying again for results the sweep would refuse to store.' },{ since: 'TBD', text: 'A fact purge now returns once it has recorded the sweep of stored link, mention, timeline and fence results and run it for up to 5 seconds, instead of up to two minutes; when the sweep has not finished by then, the receipt says `derivation_sweep: pending` (exit 75) and `gbrain forget --purge --status --request-id <id> --continue` finishes it. A sweep never deletes a stored atom, synopsis or conversation-fact result without reading it: when one alone runs past the statement budget, the sweep stops with `derivation_sweep: stalled` and `derivation_sweep_reason: paid_row_unreadable`; a result whose page was restored while the sweep was deleting it unread is kept. A sweep no longer ends while a page delete or segment replacement that brought a result into its scope is still uncommitted; it checks that page after the write commits. When the receipt\'s check of stored results runs out of time after the purge\'s own sweep finished verified, the store reports the sweep\'s result (`reason: verified_by_sweep`, with `probe` naming the deadline) instead of `unverified`. New doctor check `derivation_purge_sweeps` names each pending or stalled sweep with its request id and the command that continues it. Doctor `extraction_input_truncated` reports atom, synopsis and fact receipts a pending sweep blocked as `purge_sweep_pending`, pointing at that check instead of `derive.max_usd_per_page`, and a per-chunk synopsis re-embed job a sweep blocked no longer reports `ok`.' },{ since: 'TBD', text: 'When a fact purge\'s receipt check counts a stored link, mention, timeline or fence result still holding the claim, it now reports it even if it then runs out of time: a result the sweep covers makes `page_segment_derivations` `incomplete` (with `probe` naming where it stopped) instead of `verified_by_sweep`. A result found after the purge\'s sweep had already ended records that sweep again, so the receipt says `derivation_sweep: pending` and `gbrain forget --purge --status --request-id <id> --continue` deletes it. A sweep that reaches its end while a page delete or segment replacement in the source is still uncommitted no longer starts its walk over: it waits up to 1.5 seconds for those writes (writes that arrive meanwhile wait behind it, briefly), then ends after checking only the pages they touched; when they are still open after that, a later call tries again, so steady imports no longer keep a sweep from ending. A sweep also waits for writes that were already open when the purge recorded it before it starts its verifying walk, so one that commits during that walk can no longer leave a result holding the claim behind. Doctor `derivation_purge_sweeps` now says that continuing a sweep can also delete, without reading it, an unpaid stored result in its scope that is too large to read within the statement budget.' },+ { since: 'TBD', text: 'When a fact purge\'s sweep of stored link, mention, timeline and fence results has walked to its end but cannot finish because a write in the source (an import, sync or page edit) is still open past its 1.5-second wait, the receipt now says `derivation_sweep_reason: scope_lock_busy` and its `next` says to let that write finish before continuing with `gbrain forget --purge --status --request-id <id> --continue`, instead of only saying to continue again. Doctor `derivation_purge_sweeps` lists the same reason for that sweep. The reason clears once the sweep moves on.' },// 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/deletion-inventory.ts b/src/core/deletion-inventory.tsindex 76847d4c0c..3f2d28436c 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 stalled_reason'],+ ['page_segment_derivation_purges', 'swept', 'segment_derivations', 'source_id needles patterns page_ids phase recheck cursor_pipeline stalled_reason pending_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/facts/purge-verify.ts b/src/core/facts/purge-verify.tsindex d2871475be..5979c5aaba 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 DerivationStallReason, type DerivationSweepState } from '../page-body/segment-derive.ts';+ type DerivationKey, type DerivationPendingReason, 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';@@ -703,7 +703,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; derivation_sweep_reason?: DerivationStallReason; next?: string[] }> {+ derivation_sweep?: DerivationSweepState; derivation_sweep_reason?: DerivationStallReason | DerivationPendingReason; 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]);@@ -723,7 +723,9 @@ export async function purgeCompletion(engine: BrainEngine, row: Pick<WriteRequesconst 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 } : {}),- ...(sweep ? { derivation_sweep: sweep.state, ...(sweep.reason ? { derivation_sweep_reason: sweep.reason } : {}), next: [sweep.state === 'pending'+ ...(sweep ? { derivation_sweep: sweep.state, ...(sweep.reason ? { derivation_sweep_reason: sweep.reason } : {}), next: [sweep.reason === 'scope_lock_busy'+ ? `The sweep of stored derivation results has walked to its end, but a write in the source that brings stored results into its scope (an import, sync or page edit) is still open and held the source's scope lock past the sweep's wait (derivation_sweep: pending, scope_lock_busy). Let that write finish, then continue the sweep with gbrain forget --purge --status --request-id ${row.request_id} --continue.`+ : 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.`: 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.`diff --git a/src/core/page-body/schema.ts b/src/core/page-body/schema.tsindex b73fba75d4..b6e28e0904 100644--- a/src/core/page-body/schema.ts+++ b/src/core/page-body/schema.ts@@ -248,7 +248,8 @@ export function derivationScopeLockSql(sourceId: string): string {** page_segment_derivation_purges holds a fact purge's derivation sweep from the purge's commit until it is verified* (segment-derive.ts continueDerivationPurges): the claim's normalized forms, the pages the purge rewrote, the walk's- * phase and cursor, its adaptive batch size and, once a row alone outran the statement budget, when it stalled. While it+ * phase and cursor, its adaptive batch size, once a row alone outran the statement budget, when it stalled and, while a+ * write still open in the source keeps it from ending past its bounded wait, that it waits on one (`pending_reason`). While it* is there, the trigger on page_segment_derivations drops a write of a row of the source that the sweep would delete (in* its scope, derivationSweepScopeSql, and holding the claim; returns NULL: the row is not stored and the pipeline derives* it again after the sweep; a paid pipeline makes no call on such a page meanwhile, page-embedding-budget.ts@@ -301,6 +302,7 @@ CREATE TABLE IF NOT EXISTS page_segment_derivation_purges (batch_rows INTEGER CHECK (batch_rows >= 1),stalled_at TIMESTAMPTZ,stalled_reason TEXT CHECK (stalled_reason IN ('statement_timeout','paid_row_unreadable')),+ pending_reason TEXT CHECK (pending_reason IN ('scope_lock_busy')),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);diff --git a/src/core/page-body/segment-derive.ts b/src/core/page-body/segment-derive.tsindex e1b54d4336..e3fdf4db46 100644--- a/src/core/page-body/segment-derive.ts+++ b/src/core/page-body/segment-derive.ts@@ -434,18 +434,23 @@ export async function recordDerivationPurge(engine: Pick<BrainEngine, 'executeRa/** 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';+/**+ * Why a pending sweep has not ended: `scope_lock_busy`, it walked to its end but a write in the source that brings+ * stored results into its scope (an import or sync still open) held the scope lock past the bounded wait.+ */+export type DerivationPendingReason = 'scope_lock_busy';/*** 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. */+/** The state of a purge request's derivation sweep (with why it stalled, or why a pending one has not ended), 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;+ Promise<{ state: DerivationSweepState; reason: DerivationStallReason | DerivationPendingReason | null } | null> {+ const [row] = await engine.executeRaw<{ stalled: boolean; reason: DerivationStallReason | null; pending: DerivationPendingReason | null }>(+ 'SELECT stalled_at IS NOT NULL AS stalled, stalled_reason AS reason, pending_reason AS pending 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' : row.pending ?? null } : null;}/**@@ -488,7 +493,8 @@ type SweepRecord = { request_id: string; needles: string[]; patterns: string[];* deadlock is possible and writers that arrive meanwhile queue behind it. Holding it, the rest of the walk is read* without deleting (a row lock is never awaited under it) and, when none of it holds the claim, the walk ends there;* the noted pages are read the same way, and walked again (`recheck`) only when one holds the claim or they hold more- * than a batch of rows. A wait that times out leaves the record where it is for a later call; no walk restarts.+ * than a batch of rows. A wait that times out leaves the record where it is for a later call, marked `scope_lock_busy`+ * (cleared as the sweep moves on); no walk restarts.* No batch starts past DERIVATION_SWEEP_LIMITS.totalMs (the lower `inlineMs` for the* purge's own call, `opts.inline`, so a purge returns `pending` soon after it recorded the sweep); the next call resumes* from the cursor. Returns the rows deleted.@@ -499,7 +505,7 @@ export async function continueDerivationPurges(engine: BrainEngine, sourceId: stconst pages = new Map<number, { scanned: number; normalized: number; deleted: number }>();if (opts.retry) await engine.executeRaw('UPDATE page_segment_derivation_purges SET stalled_at = NULL, stalled_reason = NULL WHERE request_id=$1::uuid', [opts.retry]);const skip: string[] = [];- const restart = 'cursor_page = NULL, cursor_pipeline = NULL, cursor_occurrence = NULL, found = 0';+ const restart = 'cursor_page = NULL, cursor_pipeline = NULL, cursor_occurrence = NULL, found = 0, pending_reason = NULL';const toVerify = async (tx: BrainEngine, purge: SweepRecord) => {await tx.executeRaw('DELETE FROM page_segment_derivation_purge_pages WHERE request_id=$1::uuid', [purge.request_id]);await tx.executeRaw(`UPDATE page_segment_derivation_purges SET phase = 'verify', recheck = NULL, ${restart} WHERE request_id=$1::uuid`, [purge.request_id]);@@ -535,10 +541,14 @@ export async function continueDerivationPurges(engine: BrainEngine, sourceId: stlet parked: string | null = null;const endWalk = async (tx: BrainEngine, purge: SweepRecord, found: number, last: [number, string, string] | null) => {if (purge.phase === 'verify' && found > 0) return toVerify(tx, purge);- const [lock] = await tx.executeRaw<{ held: boolean }>(`SELECT pg_try_advisory_xact_lock(${derivationScopeLockSql('$1::text')}) AS held`, [sourceId]);- if (lock?.held) return finish(tx, purge);+ const held = await faultPoint('purge:derivation_scope_lock', { sourceId, requestId: purge.request_id }).then(async () => (await tx.executeRaw<{ held: boolean }>(+ `SELECT pg_try_advisory_xact_lock(${derivationScopeLockSql('$1::text')}) AS held`, [sourceId]))[0]?.held === true, error => {+ if ((error as { code?: unknown } | null)?.code === '55P03') return false;+ throw error;+ });+ if (held) return finish(tx, purge);await tx.executeRaw(`UPDATE page_segment_derivation_purges SET cursor_page = COALESCE($2::int, cursor_page), cursor_pipeline = COALESCE($3::text, cursor_pipeline),- cursor_occurrence = COALESCE($4::bigint, cursor_occurrence), found = $5 WHERE request_id=$1::uuid`, [purge.request_id, ...(last ?? [null, null, null]), found]);+ cursor_occurrence = COALESCE($4::bigint, cursor_occurrence), found = $5, pending_reason = NULL WHERE request_id=$1::uuid`, [purge.request_id, ...(last ?? [null, null, null]), found]);parked = purge.request_id;};/** A record waiting at the end of its walk: wait for the scope lock (holding no other), then end the walk if the rest of it holds nothing to sweep. */@@ -546,6 +556,7 @@ export async function continueDerivationPurges(engine: BrainEngine, sourceId: sttry {await engine.transaction(async tx => {await tx.executeRaw("SELECT set_config('statement_timeout',$1,true), set_config('lock_timeout',$2,true)", [`${statementMs}ms`, `${sweepLimits.finalizeWaitMs}ms`]);+ await faultPoint('purge:derivation_scope_lock', { sourceId, requestId });await tx.executeRaw(`SELECT pg_advisory_xact_lock(${derivationScopeLockSql('$1::text')})`, [sourceId]);const [purge] = await tx.executeRaw<SweepRecord>(`SELECT request_id::text AS request_id, needles, patterns, page_ids, phase, recheck, found, cursor_page,cursor_pipeline, cursor_occurrence::text AS cursor_occurrence, LEAST(COALESCE(batch_rows, $2), $2) AS batch_rows@@ -560,6 +571,7 @@ export async function continueDerivationPurges(engine: BrainEngine, sourceId: st} catch (error) {const code = (error as { code?: unknown } | null)?.code;if (code !== '55P03' && code !== '57014') throw error;+ if (code === '55P03') await engine.executeRaw("UPDATE page_segment_derivation_purges SET pending_reason = 'scope_lock_busy' WHERE request_id=$1::uuid", [requestId]);skip.push(requestId);}};@@ -612,7 +624,7 @@ export async function continueDerivationPurges(engine: BrainEngine, sourceId: stif (Number(batch[0]?.scanned ?? 0) < Number(purge.batch_rows)) {await endWalk(tx, purge, found, batch[0]?.last_page == null ? null : [Number(batch[0].last_page), batch[0].last_pipeline, String(batch[0].last_occurrence)]);}- else await tx.executeRaw(`UPDATE page_segment_derivation_purges SET cursor_page=$2, cursor_pipeline=$3, cursor_occurrence=$4::bigint, found=$5+ else await tx.executeRaw(`UPDATE page_segment_derivation_purges SET cursor_page=$2, cursor_pipeline=$3, cursor_occurrence=$4::bigint, found=$5, pending_reason = NULLWHERE request_id=$1::uuid`, [purge.request_id, Number(batch[0]!.last_page), batch[0]!.last_pipeline, String(batch[0]!.last_occurrence), found]);return batch;});@@ -641,7 +653,7 @@ export async function continueDerivationPurges(engine: BrainEngine, sourceId: stconst deleted = next.swept ? (await tx.executeRaw(`DELETE FROM page_segment_derivations d USING pages p WHERE d.page_id=$1 AND d.pipeline=$2AND 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 + $5+ await tx.executeRaw(`UPDATE page_segment_derivation_purges SET cursor_page=$2, cursor_pipeline=$3, cursor_occurrence=$4::bigint, found=found + $5, pending_reason = NULLWHERE 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,last_occurrence: next.occurrence_id }];diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.tsindex 4dd88c8e00..0b57406b50 100644--- a/src/core/persistence/fault-points.ts+++ b/src/core/persistence/fault-points.ts@@ -55,6 +55,9 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect| 'purge:derivation_unread'// Inside each batch transaction of the purge receipt's derivation probe (purge-verify.ts derivationTextReport), with the batch size as `round`; a 57014 models a batch outrunning the probe's statement budget.| 'purge:derivation_probe'+ // Before a purge's derivation sweep takes the source's scope lock at the end of a walk (segment-derive.ts continueDerivationPurges): tried without+ // waiting, then waited for a bounded time. A 55P03 from the hook models a write in the source holding it: the try fails, the wait times out.+ | 'purge:derivation_scope_lock'// #6712 PR 4b: after a page-row deletion of a managed Git source wrote its origin's deletion marker (sync-markers.ts), before the row goes.| 'purge:marker_written'// #6712 PR 4b: before each round of a pass reads its level (`round`), and after it read it (`level`: its statements and itsdiff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex 76b6c9e339..0de82ceb10 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -1428,6 +1428,7 @@ CREATE TABLE IF NOT EXISTS page_segment_derivation_purges (batch_rows INTEGER CHECK (batch_rows >= 1),stalled_at TIMESTAMPTZ,stalled_reason TEXT CHECK (stalled_reason IN ('statement_timeout','paid_row_unreadable')),+ pending_reason TEXT CHECK (pending_reason IN ('scope_lock_busy')),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);diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex 8c137a356a..dadc9cbc8b 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -2172,6 +2172,7 @@ CREATE TABLE IF NOT EXISTS page_segment_derivation_purges (batch_rows INTEGER CHECK (batch_rows >= 1),stalled_at TIMESTAMPTZ,stalled_reason TEXT CHECK (stalled_reason IN ('statement_timeout','paid_row_unreadable')),+ pending_reason TEXT CHECK (pending_reason IN ('scope_lock_busy')),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);diff --git a/src/schema.sql b/src/schema.sqlindex 4cfebe1374..6cf988fdd5 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -2168,6 +2168,7 @@ CREATE TABLE IF NOT EXISTS page_segment_derivation_purges (batch_rows INTEGER CHECK (batch_rows >= 1),stalled_at TIMESTAMPTZ,stalled_reason TEXT CHECK (stalled_reason IN ('statement_timeout','paid_row_unreadable')),+ pending_reason TEXT CHECK (pending_reason IN ('scope_lock_busy')),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);diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex f09215e991..7d8b9d2be2 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -267,6 +267,7 @@"page_segment_derivation_purge_pages.page_segment_derivation_purge_pages_pkey": "p PRIMARY KEY (request_id, page_id)","page_segment_derivation_purges.page_segment_derivation_purges_batch_rows_check": "c CHECK ((batch_rows >= 1))","page_segment_derivation_purges.page_segment_derivation_purges_found_check": "c CHECK ((found >= 0))",+ "page_segment_derivation_purges.page_segment_derivation_purges_pending_reason_check": "c CHECK ((pending_reason = 'scope_lock_busy'::text))","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",@@ -3013,7 +3014,8 @@"12 batch_rows integer/int4 NULL","13 stalled_at timestamp with time zone/timestamptz NULL","14 stalled_reason text/text NULL",- "15 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "15 pending_reason text/text NULL",+ "16 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 c40110b824..fedf21c0d3 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -267,6 +267,7 @@"page_segment_derivation_purge_pages.page_segment_derivation_purge_pages_pkey": "p PRIMARY KEY (request_id, page_id)","page_segment_derivation_purges.page_segment_derivation_purges_batch_rows_check": "c CHECK ((batch_rows >= 1))","page_segment_derivation_purges.page_segment_derivation_purges_found_check": "c CHECK ((found >= 0))",+ "page_segment_derivation_purges.page_segment_derivation_purges_pending_reason_check": "c CHECK ((pending_reason = 'scope_lock_busy'::text))","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",@@ -3013,7 +3014,8 @@"12 batch_rows integer/int4 NULL","13 stalled_at timestamp with time zone/timestamptz NULL","14 stalled_reason text/text NULL",- "15 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "15 pending_reason text/text NULL",+ "16 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 65ed90df9c..035e91497c 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -267,6 +267,7 @@"page_segment_derivation_purge_pages.page_segment_derivation_purge_pages_pkey": "p PRIMARY KEY (request_id, page_id)","page_segment_derivation_purges.page_segment_derivation_purges_batch_rows_check": "c CHECK ((batch_rows >= 1))","page_segment_derivation_purges.page_segment_derivation_purges_found_check": "c CHECK ((found >= 0))",+ "page_segment_derivation_purges.page_segment_derivation_purges_pending_reason_check": "c CHECK ((pending_reason = 'scope_lock_busy'::text))","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",@@ -3009,7 +3010,8 @@"12 batch_rows integer/int4 NULL","13 stalled_at timestamp with time zone/timestamptz NULL","14 stalled_reason text/text NULL",- "15 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "15 pending_reason text/text NULL",+ "16 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 594e0ee445..7816c1ac38 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json@@ -194,6 +194,7 @@"page_segment_derivation_purge_pages.page_segment_derivation_purge_pages_pkey": "p PRIMARY KEY (request_id, page_id)","page_segment_derivation_purges.page_segment_derivation_purges_batch_rows_check": "c CHECK ((batch_rows >= 1))","page_segment_derivation_purges.page_segment_derivation_purges_found_check": "c CHECK ((found >= 0))",+ "page_segment_derivation_purges.page_segment_derivation_purges_pending_reason_check": "c CHECK ((pending_reason = 'scope_lock_busy'::text))","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",@@ -2275,7 +2276,8 @@"12 batch_rows integer/int4 NULL","13 stalled_at timestamp with time zone/timestamptz NULL","14 stalled_reason text/text NULL",- "15 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "15 pending_reason text/text NULL",+ "16 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 812c869dac..9e342f1172 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json@@ -194,6 +194,7 @@"page_segment_derivation_purge_pages.page_segment_derivation_purge_pages_pkey": "p PRIMARY KEY (request_id, page_id)","page_segment_derivation_purges.page_segment_derivation_purges_batch_rows_check": "c CHECK ((batch_rows >= 1))","page_segment_derivation_purges.page_segment_derivation_purges_found_check": "c CHECK ((found >= 0))",+ "page_segment_derivation_purges.page_segment_derivation_purges_pending_reason_check": "c CHECK ((pending_reason = 'scope_lock_busy'::text))","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",@@ -2275,7 +2276,8 @@"12 batch_rows integer/int4 NULL","13 stalled_at timestamp with time zone/timestamptz NULL","14 stalled_reason text/text NULL",- "15 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "15 pending_reason text/text NULL",+ "16 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 f0a7d5c092..bb1ce87ab7 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json@@ -194,6 +194,7 @@"page_segment_derivation_purge_pages.page_segment_derivation_purge_pages_pkey": "p PRIMARY KEY (request_id, page_id)","page_segment_derivation_purges.page_segment_derivation_purges_batch_rows_check": "c CHECK ((batch_rows >= 1))","page_segment_derivation_purges.page_segment_derivation_purges_found_check": "c CHECK ((found >= 0))",+ "page_segment_derivation_purges.page_segment_derivation_purges_pending_reason_check": "c CHECK ((pending_reason = 'scope_lock_busy'::text))","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",@@ -2274,7 +2275,8 @@"12 batch_rows integer/int4 NULL","13 stalled_at timestamp with time zone/timestamptz NULL","14 stalled_reason text/text NULL",- "15 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "15 pending_reason text/text NULL",+ "16 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 1b2f0b6c96..4d883a444d 100644--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json@@ -205,6 +205,7 @@"page_segment_derivation_purge_pages.page_segment_derivation_purge_pages_pkey": "p PRIMARY KEY (request_id, page_id)","page_segment_derivation_purges.page_segment_derivation_purges_batch_rows_check": "c CHECK ((batch_rows >= 1))","page_segment_derivation_purges.page_segment_derivation_purges_found_check": "c CHECK ((found >= 0))",+ "page_segment_derivation_purges.page_segment_derivation_purges_pending_reason_check": "c CHECK ((pending_reason = 'scope_lock_busy'::text))","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",@@ -2343,7 +2344,8 @@"12 batch_rows integer/int4 NULL","13 stalled_at timestamp with time zone/timestamptz NULL","14 stalled_reason text/text NULL",- "15 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "15 pending_reason text/text NULL",+ "16 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 d46be365b3..861d579d8a 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -271,6 +271,7 @@"page_segment_derivation_purge_pages.page_segment_derivation_purge_pages_pkey": "p PRIMARY KEY (request_id, page_id)","page_segment_derivation_purges.page_segment_derivation_purges_batch_rows_check": "c CHECK ((batch_rows >= 1))","page_segment_derivation_purges.page_segment_derivation_purges_found_check": "c CHECK ((found >= 0))",+ "page_segment_derivation_purges.page_segment_derivation_purges_pending_reason_check": "c CHECK ((pending_reason = 'scope_lock_busy'::text))","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",@@ -3025,7 +3026,8 @@"12 batch_rows integer/int4 NULL","13 stalled_at timestamp with time zone/timestamptz NULL","14 stalled_reason text/text NULL",- "15 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "15 pending_reason text/text NULL",+ "16 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 e101b0a1ce..4c499650fc 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -271,6 +271,7 @@"page_segment_derivation_purge_pages.page_segment_derivation_purge_pages_pkey": "p PRIMARY KEY (request_id, page_id)","page_segment_derivation_purges.page_segment_derivation_purges_batch_rows_check": "c CHECK ((batch_rows >= 1))","page_segment_derivation_purges.page_segment_derivation_purges_found_check": "c CHECK ((found >= 0))",+ "page_segment_derivation_purges.page_segment_derivation_purges_pending_reason_check": "c CHECK ((pending_reason = 'scope_lock_busy'::text))","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",@@ -3025,7 +3026,8 @@"12 batch_rows integer/int4 NULL","13 stalled_at timestamp with time zone/timestamptz NULL","14 stalled_reason text/text NULL",- "15 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "15 pending_reason text/text NULL",+ "16 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 508731ee72..7664cfd1a3 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -271,6 +271,7 @@"page_segment_derivation_purge_pages.page_segment_derivation_purge_pages_pkey": "p PRIMARY KEY (request_id, page_id)","page_segment_derivation_purges.page_segment_derivation_purges_batch_rows_check": "c CHECK ((batch_rows >= 1))","page_segment_derivation_purges.page_segment_derivation_purges_found_check": "c CHECK ((found >= 0))",+ "page_segment_derivation_purges.page_segment_derivation_purges_pending_reason_check": "c CHECK ((pending_reason = 'scope_lock_busy'::text))","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",@@ -3021,7 +3022,8 @@"12 batch_rows integer/int4 NULL","13 stalled_at timestamp with time zone/timestamptz NULL","14 stalled_reason text/text NULL",- "15 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "15 pending_reason text/text NULL",+ "16 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 4a31245a4e..51850ffaee 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: 1330 column(s) verified against live schema",+ " [OK] schema_columns: 1331 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).",diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.jsonindex 69abfa699d..2bf99d0141 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": "1330 column(s) verified against live schema",+ "message": "1331 column(s) verified against live schema","name": "schema_columns","status": "ok"},diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.jsonindex c126a686e8..fd77f87bfb 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": "1330 column(s) verified against live schema",+ "message": "1331 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -5648,7 +5648,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "1330 column(s) verified against live schema",+ "message": "1331 column(s) verified against live schema","name": "schema_columns","status": "ok"},diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex 1d7cf636fb..d525a2bdcb 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": "1336 column(s) verified against live schema",+ "message": "1337 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -5645,7 +5645,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "1336 column(s) verified against live schema",+ "message": "1337 column(s) verified against live schema","name": "schema_columns","status": "ok"},diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 9ba203740c..a06da9919d 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": "1330 column(s) verified against live schema",+ "message": "1331 column(s) verified against live schema","name": "schema_columns","status": "ok"},diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex ab3fae182e..1c0c6adc4a 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": "1330 column(s) verified against live schema",+ "message": "1331 column(s) verified against live schema","name": "schema_columns","status": "ok"},diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex c4aefcfebe..3b4da582c8 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": "1336 column(s) verified against live schema",+ "message": "1337 column(s) verified against live schema","name": "schema_columns","status": "ok"},diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 4772de2ea7..80eb118c5e 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": 6474,- "sha256": "fee0b9c881be6d8ce99a370e0adaee8e77ba121a80bb9bd5492e3ca930e9cf6f"+ "length": 6551,+ "sha256": "ef3a87c79cfcc26453bbd616c57a5285eeea7b7dd7f0a63cb1eb3bf72d15c69b"},"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 65017ffb86..f5474eec61 100644--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json@@ -267,6 +267,7 @@"page_segment_derivation_purge_pages.page_segment_derivation_purge_pages_pkey": "p PRIMARY KEY (request_id, page_id)","page_segment_derivation_purges.page_segment_derivation_purges_batch_rows_check": "c CHECK ((batch_rows >= 1))","page_segment_derivation_purges.page_segment_derivation_purges_found_check": "c CHECK ((found >= 0))",+ "page_segment_derivation_purges.page_segment_derivation_purges_pending_reason_check": "c CHECK ((pending_reason = 'scope_lock_busy'::text))","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",@@ -3013,7 +3014,8 @@"12 batch_rows integer/int4 NULL","13 stalled_at timestamp with time zone/timestamptz NULL","14 stalled_reason text/text NULL",- "15 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "15 pending_reason text/text NULL",+ "16 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 910ee81d94..4ebddbc71b 100644--- a/test/helpers/derivation-purge-cases.ts+++ b/test/helpers/derivation-purge-cases.ts@@ -12,7 +12,7 @@ import { randomUUID } from 'node:crypto';import type { BrainEngine } from '../../src/core/engine.ts';import { runExtractFacts } from '../../src/core/cycle/extract-facts.ts';import { __setAfterDerivationSweepBatchForTests, __setBeforeDerivationWriteForTests, __setBeforeUnreadDerivationDeleteForTests, __setDerivationSweepLimitsForTests,- __setDerivationSweepWorkForTests, continueDerivationPurges, derivationPurgeState, derivationSweepStatements, derivationSweepWork,+ __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';@@ -925,11 +925,73 @@ export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): voidexpect({ rows: await exactHolders(brain.engine, rows, claim), recorded: await sweepsRecorded() }).toEqual({ rows: [], recorded: 0 });}, 600_000);+ /** A sweep's receipt while a write holds the scope lock past its wait, and doctor's view of it: the named reason, \`next\` and the doctor record. */+ const busyView = async (requestId: string, body: Record<string, any>) => {+ const [check] = await derivationPurgeSweepsEntry.run({ engine: brain.engine } as never) as Array<Record<string, any>>;+ return { sweep: body.derivation_sweep, reason: body.derivation_sweep_reason ?? null,+ next: (body.next as string[] | undefined ?? []).some(n => n.includes('Let that write finish, then continue') && n.includes(`--request-id ${requestId} --continue`)),+ doctor: (check!.details.records as Array<Record<string, any>> | undefined)?.find(r => r.request_id === requestId)?.reason ?? null,+ message: String(check!.message).includes('scope_lock_busy') && String(check!.message).includes('let that write finish') };+ };+ const busy = { sweep: 'pending', reason: 'scope_lock_busy', next: true, doctor: 'scope_lock_busy', message: true };++ test('a sweep whose end waits past its bound on a write holding the scope lock says so (scope_lock_busy) until the write ends and the sweep finishes', async () => {+ const claim = 'Purge Example quarry code is 3371';+ const rows = await candidateRowsPage('notes/busy-hook-rows', claim, 50, 1);+ const params = await confirmed(await seed('notes/busy-hook-purge', claim));+ __setDerivationSweepLimitsForTests({ totalMs: 0 });+ try { expect((await brain.call('purge_fact', params)).body.derivation_sweep).toBe('pending'); } finally { __setDerivationSweepLimitsForTests(null); }+ // The hook models a write in the source holding the scope lock (55P03: the try fails, the bounded wait times out); PGLite has one connection.+ let open = true, tried = 0;+ installFaultHook(point => {+ if (point !== 'purge:derivation_scope_lock' || !open) return;+ tried++;+ throw Object.assign(new Error('canceling statement due to lock timeout'), { code: '55P03' });+ });+ try {+ const held = (await brain.call('purge_fact', { status: true, request_id: params.request_id, continue: true })).body;+ expect({ tried: tried >= 2, ...await busyView(params.request_id, held) }).toEqual({ tried: true, ...busy });+ const again = (await brain.call('purge_fact', { status: true, request_id: params.request_id }).then(r => r.body));+ expect(await busyView(params.request_id, again)).toEqual(busy);+ open = false;+ const done = (await brain.call('purge_fact', { status: true, request_id: params.request_id, continue: true })).body;+ const [clear] = await derivationPurgeSweepsEntry.run({ engine: brain.engine } as never) as Array<Record<string, any>>;+ expect({ sweep: done.derivation_sweep, reason: done.derivation_sweep_reason, doctor: clear!.status }).toEqual({ sweep: undefined, reason: undefined, doctor: 'ok' });+ } finally { installFaultHook(undefined); }+ expect({ rows: await exactHolders(brain.engine, rows, claim), recorded: await sweepsRecorded() }).toEqual({ rows: [], recorded: 0 });+ }, 600_000);+if (kind === 'postgres') {const scopeKey = `hashtextextended('gbrain:derivation-scope:' || '${SOURCE}', 0)`;const advisoryLocks = (sql: any, mode: string) => sql.unsafe(`SELECT pid FROM pg_locks WHERE locktype = 'advisory' AND mode = $1 AND NOT grantedAND database = (SELECT oid FROM pg_database WHERE datname = current_database())`, [mode]) as Promise<Array<{ pid: number }>>;+ test('a write holding the scope lock longer than the sweep\'s wait leaves it pending with scope_lock_busy; once the write commits the sweep finishes and the reason is gone', async () => {+ const claim = 'Purge Example forge code is 8142';+ const rows = await candidateRowsPage('notes/busy-lock-rows', claim, 50, 1);+ const params = await confirmed(await seed('notes/busy-lock-purge', claim));+ __setDerivationSweepLimitsForTests({ totalMs: 0 });+ try { expect((await brain.call('purge_fact', params)).body.derivation_sweep).toBe('pending'); } finally { __setDerivationSweepLimitsForTests(null); }+ const sql = (brain.engine as any).sql;+ const opened = Promise.withResolvers<void>(), release = Promise.withResolvers<void>();+ const writer = sql.begin(async (tx: any) => { await tx.unsafe(`SELECT pg_advisory_xact_lock_shared(${scopeKey})`); opened.resolve(); await release.promise; });+ await opened.promise;+ let held: Record<string, any> = {}, waited = 0;+ try {+ const t0 = performance.now();+ held = (await brain.call('purge_fact', { status: true, request_id: params.request_id, continue: true })).body;+ waited = performance.now() - t0;+ expect({ waited: waited >= DERIVATION_SWEEP_LIMITS.finalizeWaitMs, ...await busyView(params.request_id, held) }).toEqual({ waited: true, ...busy });+ } finally {+ release.resolve();+ await writer;+ }+ const done = (await brain.call('purge_fact', { status: true, request_id: params.request_id, continue: true })).body;+ const [clear] = await derivationPurgeSweepsEntry.run({ engine: brain.engine } as never) as Array<Record<string, any>>;+ expect({ sweep: done.derivation_sweep, reason: done.derivation_sweep_reason, doctor: clear!.status }).toEqual({ sweep: undefined, reason: undefined, doctor: 'ok' });+ expect({ rows: await exactHolders(brain.engine, rows, claim), recorded: await sweepsRecorded() }).toEqual({ rows: [], recorded: 0 });+ }, 600_000);+test('a sweep waiting for the scope lock holds no other lock, and writes that arrive meanwhile queue behind it', async () => {const claim = 'Purge Example mill code is 6630';const rows = await candidateRowsPage('notes/wait-rows', claim, 50, 1);