Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

lane 4a round 7: adaptive, verified and continuable derivation sweeps; no paid calls a pending sweep would refuse

garrytanf4399405e366
diff --git a/src/commands/forget-purge.ts b/src/commands/forget-purge.ts
index 883e48c7db..bc3ecef5e5 100644
--- a/src/commands/forget-purge.ts
+++ b/src/commands/forget-purge.ts
@@ -5,7 +5,7 @@
* gbrain forget <id> --purge [--dry-run] [--yes --request-id <uuid>] [--reason <text>]
* [--all-subjects] [--vacuum] [--source <id>] [--json]
* gbrain forget --purge --match "<text>" # list candidate ids; never purges
- * gbrain forget --purge --status --request-id <uuid> # completion of an earlier purge
+ * gbrain forget --purge --status --request-id <uuid> [--continue] # completion of an earlier purge; --continue resumes its derivation sweep
*
* It always runs the dry run first. On a terminal it prints that receipt
* (residuals first) and asks the user to type the fact's 8-character token;
@@ -37,7 +37,7 @@ const USAGE = `Usage: gbrain forget <fact-id> [--reason <text>] [--source <id>]
(withdraws the fact: it expires and cannot be re-saved; the text stays in history and backups)
gbrain forget <fact-id> --purge [--dry-run] [--yes --request-id <uuid>] [--reason <text>] [--all-subjects] [--vacuum] [--source <id>] [--json]
gbrain forget --purge --match "<text>"
- gbrain forget --purge --status --request-id <uuid>
+ gbrain forget --purge --status --request-id <uuid> [--continue]
${PURGE_FAMILY_HELP}`;
@@ -115,8 +115,8 @@ export async function runForgetPurge(engine: BrainEngine | (() => Promise<BrainE
const invoke = invoker(engine, flagValue(args, '--source') ?? null);
if (args.includes('--status')) {
if (!requestId) throw opError('invalid_params', '--status needs --request-id.', 'Pass the request id the purge printed.');
- const status = await invoke({ status: true, request_id: requestId });
- out(status, `Purge ${requestId}: ${status.completion} (${status.state})\n${((status.effects as Array<{ kind: string; state: string }>) ?? []).map(e => ` effect ${e.kind}: ${e.state}`).join('\n')}\n`);
+ const status = await invoke({ status: true, request_id: requestId, ...(args.includes('--continue') ? { continue: true } : {}) });
+ out(status, `Purge ${requestId}: ${status.completion} (${status.state})\n${((status.effects as Array<{ kind: string; state: string }>) ?? []).map(e => ` effect ${e.kind}: ${e.state}`).join('\n')}\n${((status.next as string[] | undefined) ?? []).map(n => `Next: ${n}\n`).join('')}`);
setCliExitVerdict(Number(status.exit_code ?? 0));
return;
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index f595ef7ac5..84fdbd999e 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1076,6 +1076,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: 'TBD', text: 'A fact purge now also finds stored link, mention, timeline and fence results that spell a Greek claim with a final sigma (ς) where the claim has σ or Σ, or the other way round, or a Turkish dotted capital İ the way JavaScript lowercases it (i̇). It normalizes only the results that contain the claim\'s words in order, so the search costs about what the plain substring search did. When that search still runs past the purge transaction\'s statement budget, the purge fails with `purge_lookup_timeout` and nothing is purged, instead of being retried until the transaction gives up.' },
{ since: 'TBD', text: 'A fact purge now searches stored link, mention, timeline and fence results in batches of 500 rows per statement, and its receipt checks them the same way, so a claim whose words appear in tens of thousands of stored results can be purged instead of always failing with `purge_lookup_timeout`. The purge still commits all at once. It fails with `purge_lookup_timeout`, purging nothing, only when the search runs past two minutes.' },
{ 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.' },
// 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/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 30b2ab188f..8eaa8ff8b1 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -66,7 +66,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'features': ['--all', '--apply', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--embedding-model', '--expect', '--explain', '--facts', '--force', '--from-meetings', '--held', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--max-cost', '--max-usd', '--ner', '--non-interactive', '--only', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--retry-held', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--trust', '--type', '--verbose', '--workers', '--yes'],
'feedback': ['--brain', '--help', '--json', '--page', '--source'],
'files': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--no-pointer', '--page', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--source', '--timeout', '--timings', '--type', '--wait', '--yes'],
- 'forget': ['--all-subjects', '--brain', '--dry-run', '--help', '--json', '--match', '--purge', '--reason', '--request-id', '--source', '--status', '--vacuum', '--yes'],
+ 'forget': ['--all-subjects', '--brain', '--continue', '--dry-run', '--help', '--json', '--match', '--purge', '--reason', '--request-id', '--source', '--status', '--vacuum', '--yes'],
'founder': ['--brain', '--help', '--json', '--mcp-only', '--request-id', '--since', '--source', '--until'],
'friction': ['--agent', '--base', '--brain', '--compare', '--help', '--hint', '--json', '--kind', '--message', '--no-redact', '--phase', '--run-id', '--severity', '--source', '--transcript-path', '--transcripts'],
'frontmatter': ['--allow-catch-all', '--batch', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fix', '--force', '--full-name', '--get', '--git-common-dir', '--help', '--importable', '--include-ambiguous', '--include-catch-all', '--json', '--literal-pathspecs', '--name-only', '--no-verify', '--others', '--path', '--show-prefix', '--show-toplevel', '--source', '--stage', '--staged', '--stdin', '--type', '--uninstall'],
@@ -101,7 +101,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],
'quarantine': ['--accept-all', '--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--body', '--brain', '--break-lock', '--client', '--confirm-relocated-root', '--db-url', '--dir', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--help', '--http', '--id', '--include-flagged', '--json', '--kind', '--legacy-lock', '--limit', '--manifest', '--no-accept-pending', '--no-embed', '--path', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--remove', '--resume', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--timings', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],
'questions': ['--brain', '--defer', '--entity', '--fail-fast', '--full', '--help', '--id', '--include-archived', '--json', '--prefix', '--probe', '--publish', '--source', '--tools-json', '--wait-ms', '--yes'],
- 'recall': ['--accept-pending', '--access', '--add', '--all', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--group-by', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--timings', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],
+ 'recall': ['--accept-pending', '--access', '--add', '--all', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--continue', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--group-by', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--timings', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],
'reconcile-links': ['--accept-pending', '--background', '--body', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],
'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--all-drifted', '--apply', '--background', '--body', '--brain', '--class', '--close', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--held', '--help', '--include-ambiguous', '--json', '--keep', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--oversized', '--path', '--plan', '--prefer', '--progress-interval', '--progress-json', '--quiet', '--repo', '--request', '--request-id', '--segmented', '--self-transfer', '--side', '--since', '--skip', '--slug', '--source', '--stale', '--state', '--status', '--supabase', '--timeout', '--timings', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],
'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--client', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--id', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--scopes', '--source', '--status', '--timeout', '--timings', '--trust', '--wait', '--workers', '--yes'],
diff --git a/src/core/contextual-retrieval-service.ts b/src/core/contextual-retrieval-service.ts
index 62880bc227..63cac1bbf4 100644
--- a/src/core/contextual-retrieval-service.ts
+++ b/src/core/contextual-retrieval-service.ts
@@ -580,7 +580,7 @@ async function reembedSegmentedPage(args: ReembedPageArgs, initial: Page): Promi
});
unpricedModel = metered.unpricedModel ?? unpricedModel;
if ('refused' in metered) {
- await derivation(segment, 'partial', anchors, { reason: unpricedModel ? 'unpriced_model' : 'budget_limited', ...(unpricedModel ? { model: unpricedModel } : {}),
+ 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' };
}
diff --git a/src/core/cycle/extract-atoms-segments.ts b/src/core/cycle/extract-atoms-segments.ts
index 66ff929a2f..d7e11d7e15 100644
--- a/src/core/cycle/extract-atoms-segments.ts
+++ b/src/core/cycle/extract-atoms-segments.ts
@@ -71,7 +71,7 @@ async function planPage(engine: BrainEngine, sourceId: string, page: AtomPageInp
const states = new Map<number, OccurrenceState>();
const items: AtomPageInput[] = [];
let unread = false;
- let stop: 'cap_reached' | null = null;
+ let stop: 'cap_reached' | 'purge_sweep_pending' | null = null;
let unpricedModel: string | null = null;
let open = 0;
const todo = new Map(plan.todo.map(segment => [segment.occurrenceId, segment]));
@@ -119,7 +119,7 @@ async function planPage(engine: BrainEngine, sourceId: string, page: AtomPageInp
estimateChatCallUsd(model, text.length, maxOutputTokens, pricingOverrides), call, { pricingOverrides });
unpricedModel = metered.unpricedModel ?? unpricedModel;
if (!('refused' in metered)) return metered;
- stop = 'cap_reached';
+ stop = metered.refused.reason === 'purge_sweep_pending' ? 'purge_sweep_pending' : 'cap_reached';
const unfinished = [...states.values()].filter(s => s.done.size < s.total);
if (unfinished.length) await engine.upsertSegmentDerivations(unfinished.map(row));
return null;
diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.ts
index 7137c1a930..17b4158637 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 cursor_pipeline'],
+ ['page_segment_derivation_purges', 'swept', 'segment_derivations', 'source_id needles patterns page_ids phase recheck cursor_pipeline'],
['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/engine-sql/page-body.ts b/src/core/engine-sql/page-body.ts
index 60bd8f9a2f..95af6b37a5 100644
--- a/src/core/engine-sql/page-body.ts
+++ b/src/core/engine-sql/page-body.ts
@@ -35,7 +35,7 @@ import type { LegacyUnscopedRead } from './brands.ts';
import { joinFragments, sqlFragment, trustedSql, type SqlFragment } from './fragment.ts';
import { compileRowNormalizer } from './normalize.ts';
import { stagingNeedsTextSql } from '../page-body/schema.ts';
-import type { SegmentDerivationInput, SegmentDerivationKind, SegmentDerivationRow, SegmentDerivationState } from '../page-body/derivations.ts';
+import { DerivationWriteRefused, type SegmentDerivationInput, type SegmentDerivationKind, type SegmentDerivationRow, type SegmentDerivationState } from '../page-body/derivations.ts';
import { RELEASE_STAGED_CTE } from '../persistence/limits.ts';
export const LIVE_STAGING_STATES = ['open', 'sealed', 'prepared'];
@@ -489,7 +489,8 @@ export async function readSegmentDerivations(exec: LegacyUnscopedRead, pageId: n
/**
* Insert or replace rows keyed (page, kind, occurrence), in statements bounded like manifest rows. A replaced row
* keeps its created_at and moves updated_at. Outputs and receipts travel inside the batch's JSON text, never as a
- * `::jsonb` bind of a stringified value.
+ * `::jsonb` bind of a stringified value. A row a fact purge's sweep refuses (it holds the purged claim; page-body/schema.ts)
+ * is not stored, and the call throws DerivationWriteRefused after storing the others.
*/
export async function upsertSegmentDerivations(exec: SqlExecutor, rows: readonly SegmentDerivationInput[]): Promise<void> {
const batches = jsonRowBatches(rows, row => ({
@@ -497,8 +498,9 @@ export async function upsertSegmentDerivations(exec: SqlExecutor, rows: readonly
segment_sha256: hex(row.segmentSha256), context_hash: hex(row.contextHash), state: row.state,
output: row.output ?? null, receipt: row.receipt ?? null,
}), stageBatchBytes(exec));
+ let stored = 0;
for (const json of batches) {
- await exec.run(sqlFragment`INSERT INTO page_segment_derivations (page_id, pipeline, occurrence_id, pipeline_version, segment_sha256,
+ const { affectedRows } = await exec.run(sqlFragment`INSERT INTO page_segment_derivations (page_id, pipeline, occurrence_id, pipeline_version, segment_sha256,
context_hash, state, output, receipt)
SELECT d.page_id, d.pipeline, d.occurrence_id, d.pipeline_version, decode(d.segment_sha256, 'hex'), decode(d.context_hash, 'hex'),
d.state, d.output, d.receipt
@@ -507,8 +509,10 @@ export async function upsertSegmentDerivations(exec: SqlExecutor, rows: readonly
ON CONFLICT (page_id, pipeline, occurrence_id) DO UPDATE SET pipeline_version = EXCLUDED.pipeline_version,
segment_sha256 = EXCLUDED.segment_sha256, context_hash = EXCLUDED.context_hash, state = EXCLUDED.state,
output = EXCLUDED.output, receipt = EXCLUDED.receipt, updated_at = now()`);
+ stored += affectedRows;
await yieldTurn();
}
+ if (stored < rows.length) throw new DerivationWriteRefused(rows.length - stored);
}
/** Delete a page's rows (every kind, or `kind`) whose occurrence is not in `liveOccurrenceIds`; returns the count. */
diff --git a/src/core/facts/backstop-segments.ts b/src/core/facts/backstop-segments.ts
index de7d0af4f1..d885fa6f0f 100644
--- a/src/core/facts/backstop-segments.ts
+++ b/src/core/facts/backstop-segments.ts
@@ -67,7 +67,7 @@ export interface SegmentedBackstopRun<R extends { inserted: number; skipped_reas
* or a window is skipped. Returns each window's pipeline result, in call order, and why the run stopped (null: done).
*/
export async function runSegmentedBackstop<R extends { inserted: number; skipped_reason?: unknown }>(run: SegmentedBackstopRun<R>):
- Promise<{ results: R[]; stop: 'cap_reached' | 'skipped' | null }> {
+ Promise<{ results: R[]; stop: 'cap_reached' | 'purge_sweep_pending' | 'skipped' | null }> {
// PR 4 (Wave B incremental derivation, transcripts)
const { engine, page } = run;
const { body, occurrences } = await readConversationOccurrences(engine, page.id);
@@ -85,7 +85,7 @@ export async function runSegmentedBackstop<R extends { inserted: number; skipped
const pricingOverrides = plan.todo.length ? await loadPricingOverrides(engine) : undefined;
const results: R[] = [];
const touched: Array<{ segment: (typeof plan.todo)[number]; windows: string[]; done: Map<number, WindowRecord> }> = [];
- let stop: 'cap_reached' | 'skipped' | 'interrupted' | null = null;
+ let stop: 'cap_reached' | 'purge_sweep_pending' | 'skipped' | 'interrupted' | null = null;
let unpricedModel: string | null = null;
const rowsOf = (): SegmentDerivationInput[] => touched.map(({ segment, windows, done }) => {
const kept = windows.flatMap((text, ordinal) => done.get(ordinal)?.sha === sha(text) ? [done.get(ordinal)!] : []);
@@ -113,7 +113,7 @@ export async function runSegmentedBackstop<R extends { inserted: number; skipped
const metered = await meterPaidCall(engine, page, `facts:${run.model}`, estimateFactsExtractionUsd(run.model, text.length, maxTokens, pricingOverrides),
() => run.extract(text), { pricingOverrides });
unpricedModel = metered.unpricedModel ?? unpricedModel;
- if ('refused' in metered) { stop = 'cap_reached'; break; }
+ if ('refused' in metered) { stop = metered.refused.reason === 'purge_sweep_pending' ? 'purge_sweep_pending' : 'cap_reached'; break; }
const result = metered.value;
results.push(result);
if (result.skipped_reason) { stop = 'skipped'; break; }
diff --git a/src/core/facts/conversation-incremental.ts b/src/core/facts/conversation-incremental.ts
index 9cedf2a24a..c35ca4aa8d 100644
--- a/src/core/facts/conversation-incremental.ts
+++ b/src/core/facts/conversation-incremental.ts
@@ -100,7 +100,7 @@ interface RowOutput { windows: WindowRecord[]; starts_group?: boolean; prev?: nu
/** One window of the stream: `reused` (an earlier run's facts stand), `todo`, `extracted` by this run, or `failed` past the limit. */
interface StreamWindow { owner: number; seg: ConversationSegment; text: string | null; window: SourceWindow;
state: 'reused' | 'todo' | 'extracted' | 'failed'; facts: number; failed?: WindowFailure }
-type Stop = 'segment_limit' | 'cap_reached' | 'interrupted' | null;
+type Stop = 'segment_limit' | 'cap_reached' | 'purge_sweep_pending' | 'interrupted' | null;
/** The bounded output a conversation_facts row stores (window anchors and counts; never text). */
function rowOutput(row: SegmentDerivationInput | undefined): RowOutput {
@@ -370,7 +370,7 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
continue;
}
unpricedModel = metered.unpricedModel ?? unpricedModel;
- if ('refused' in metered) { stop = 'cap_reached'; break; }
+ if ('refused' in metered) { stop = metered.refused.reason === 'purge_sweep_pending' ? 'purge_sweep_pending' : 'cap_reached'; break; }
const out = metered.value;
w.state = 'extracted';
w.facts = out.extracted;
diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.ts
index 36d9baa063..a2deb17a7d 100644
--- a/src/core/facts/purge-verify.ts
+++ b/src/core/facts/purge-verify.ts
@@ -27,8 +27,9 @@ import { DELETION_INVENTORY, OUT_OF_REACH_RESIDUALS, type InventoryEntry } from
import type { PurgePlan, PurgeTarget } from './purge.ts';
import { gitChildEnv } from '../git-env.ts';
import { segmentedBodyContains } from '../page-body/segment-rewrite.ts';
-import { derivationAfterSql, derivationBatchRows, derivationNeedles, derivationPurgePending, recordDerivationStatement,
- type DerivationKey } from '../page-body/segment-derive.ts';
+import { derivationAfterSql, derivationBatchRows, derivationNeedles, derivationPurgeState, recordDerivationStatement,
+ type DerivationKey, 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';
import { CARRYING_FIELDS } from '../belief/keys.ts';
@@ -127,7 +128,9 @@ async function segmentTextReport(engine: BrainEngine, sourceId: string, needles:
* Derivation rows holding the claim, matched and scoped as the purge sweeps them (segment-derive.ts
* derivationHoldsClaimSql, derivationSweepScopeSql): a row the sweep covers is a residual (`incomplete`); a row of a
* live segment of a page the purge did not rewrite is that page's prose, reported with it. The source's rows are walked
- * in primary-key order, segment-derive.ts derivationBatchRows() per statement, each under the probe's statement bound.
+ * 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.
*/
async function derivationTextReport(engine: BrainEngine, sourceId: string, pageIds: readonly number[], claims: readonly string[], removed: number,
deadline: number): Promise<StoreReport> {
@@ -136,12 +139,14 @@ async function derivationTextReport(engine: BrainEngine, sourceId: string, pageI
const unverified = (reason: string): StoreReport => ({ store: 'page_segment_derivations', status: 'unverified', reason, removed });
let swept = 0, kept = 0;
let cursor: DerivationKey | null = null;
+ let rows = derivationBatchRows();
for (;;) {
if (performance.now() > deadline) return unverified('verification_deadline');
let row: { scanned: number; normalized: number; swept: number; kept: number; last_page: number | null; last_pipeline: string | null; last_occurrence: string | null };
try {
row = await engine.transaction(async tx => {
await tx.executeRaw("SELECT set_config('statement_timeout',$1,true)", [`${probeLimits.statementMs}ms`]);
+ await faultPoint('purge:derivation_probe', { sourceId, round: rows });
const [counted] = await tx.executeRaw<typeof row>(`WITH batch AS MATERIALIZED (
SELECT d.page_id, d.pipeline, d.occurrence_id, ${derivationSweepScopeSql('d', 'p', '$3')} AS swept FROM page_segment_derivations d
JOIN pages p ON p.id=d.page_id WHERE p.source_id=$1 AND ${derivationAfterSql('d', ['$5', '$6', '$7'])}
@@ -155,18 +160,20 @@ async function derivationTextReport(engine: BrainEngine, sourceId: string, pageI
) SELECT (SELECT count(*)::int FROM batch) AS scanned, count(*) FILTER (WHERE candidate)::int AS normalized,
count(*) FILTER (WHERE hit AND swept)::int AS swept, count(*) FILTER (WHERE hit AND NOT swept)::int AS kept,
(SELECT page_id FROM last) AS last_page, (SELECT pipeline FROM last) AS last_pipeline, (SELECT occurrence_id FROM last) AS last_occurrence
- FROM checked`, [sourceId, needles, [...pageIds], patterns, cursor?.[0] ?? null, cursor?.[1] ?? null, cursor?.[2] ?? null, derivationBatchRows()]);
+ FROM checked`, [sourceId, needles, [...pageIds], patterns, cursor?.[0] ?? null, cursor?.[1] ?? null, cursor?.[2] ?? null, rows]);
return counted!;
});
} catch (error) {
- if (getCode(error) === '57014') return unverified('statement_deadline');
- throw error;
+ if (getCode(error) !== '57014') throw error;
+ if (rows === 1) return unverified('statement_deadline');
+ rows = Math.floor(rows / 2);
+ continue;
}
recordDerivationStatement({ phase: 'probe', scanned: Number(row.scanned), normalized: Number(row.normalized) });
swept += Number(row.swept);
kept += Number(row.kept);
if (swept > probeLimits.rows || kept > probeLimits.rows) return unverified('row_bound');
- if (Number(row.scanned) < derivationBatchRows()) break;
+ if (Number(row.scanned) < rows) break;
cursor = [Number(row.last_page), row.last_pipeline!, String(row.last_occurrence)];
}
if (swept) return { store: 'page_segment_derivations', status: 'incomplete', remaining: swept, removed };
@@ -664,7 +671,7 @@ export async function verifyPagePurge(engine: BrainEngine, input: { sourceId: st
if (source?.local_path && context?.paths.length && needles.length) residuals.push(await gitResidualCommits(source.local_path, context.paths, needles[0]!));
residuals.push(...outOfReach(engine).filter(r => !(r.store === 'git_history' && residuals.length)));
residuals.push(...stores.filter(s => s.reason === 'source_prose' || s.reason === 'probed_reported'));
- const [row] = await engine.executeRaw<Pick<WriteRequest, 'id' | 'state' | 'source_id' | 'outcome'>>(`SELECT id,state,source_id,outcome FROM persistence_requests
+ const [row] = await engine.executeRaw<Pick<WriteRequest, 'id' | 'request_id' | 'state' | 'source_id' | 'outcome'>>(`SELECT id,request_id,state,source_id,outcome FROM persistence_requests
WHERE source_id=$1 AND request_id=$2::uuid AND operation='delete_page' ORDER BY created_at DESC LIMIT 1`, [src, input.requestId]);
return { summary: 'Removed from live stores. Residuals below are copies purge cannot reach; this is not physical erasure.',
residuals, stores, page_tombstones: Number(tombstones?.n ?? 0),
@@ -680,9 +687,9 @@ export async function verifyPagePurge(engine: BrainEngine, input: { sourceId: st
* residual, `incomplete` when an effect failed or parked or a swept store
* still holds the claim. Out-of-reach residuals never make it incomplete.
*/
-export async function purgeCompletion(engine: BrainEngine, row: Pick<WriteRequest, 'id' | 'state' | 'source_id' | 'outcome'>, receipt?: Pick<PurgeReceipt, 'stores'>):
+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?: 'pending' }> {
+ derivation_sweep?: DerivationSweepState; 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]);
@@ -696,11 +703,13 @@ export async function purgeCompletion(engine: BrainEngine, row: Pick<WriteReques
fingerprint = { facts: Number(probe?.facts ?? 0), takes: Number(probe?.takes ?? 0) };
}
const failed = effects.some(e => e.state === 'failed' || e.parked);
- const sweeping = await derivationPurgePending(engine, row.id);
+ const sweeping = await derivationPurgeState(engine, row.id);
const sweptResidual = sweeping || 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: 'pending' as const } : {}) };
+ ...(sweeping ? { derivation_sweep: sweeping, next: [sweeping === '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.`] } : {}) };
}
diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.ts
index 4d42a9d258..affb03c0cf 100644
--- a/src/core/facts/purge.ts
+++ b/src/core/facts/purge.ts
@@ -406,12 +406,16 @@ async function matchCandidates(engine: BrainEngine, sourceId: string, text: stri
next: rows.length ? 'Pick one id and run gbrain forget <id> --purge; --match never purges.' : 'No fact in this source contains that text.' };
}
-/** `--status`: the stored receipt and the current completion of an earlier purge request. Never re-reads claim text. */
-async function purgeStatus(ctx: OperationContext, requestId: string): Promise<Record<string, unknown>> {
+/**
+ * `--status`: the stored receipt and the current completion of an earlier purge request. Never re-reads claim text. With
+ * `--continue` it first continues the request's derivation sweep (a stalled one is tried again), then the source's others.
+ */
+async function purgeStatus(ctx: OperationContext, requestId: string, resume: boolean): Promise<Record<string, unknown>> {
const principal = await requestPrincipalForContext(ctx);
const row = await getWriteRequest(ctx.engine, principal, requestId);
if (!row || row.operation !== PURGE_OPERATION) throw opError('not_found', `No purge request ${requestId} for this caller.`,
'Pass the --request-id a purge printed. Status reads only purges this CLI submitted.');
+ if (resume && row.state === 'committed') await continueDerivationPurges(ctx.engine, row.source_id, { first: row.id, retry: row.id });
return { ...(row.outcome ?? {}), request_id: row.request_id, state: row.state, ...await purgeCompletion(ctx.engine, row) };
}
@@ -430,7 +434,7 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Rec
if (params.status === true) {
const requestId = parseWriteRequestId(params.request_id);
if (!requestId) throw opError('invalid_params', '--status needs --request-id.', 'Pass the request id the purge printed with --request-id, together with --status.');
- return purgeStatus(ctx, requestId);
+ return purgeStatus(ctx, requestId, params.continue === true);
}
const sourceIdForMatch = typeof params.source_id === 'string' ? params.source_id : ctx.sourceId ?? 'default';
if (typeof params.match === 'string') return matchCandidates(ctx.engine, sourceIdForMatch, params.match);
@@ -443,7 +447,7 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Rec
const prior = await getWriteRequest(ctx.engine, principal, p.requestId);
if (prior) {
assertReplayIntent(prior, intentDigest({ operation: PURGE_OPERATION, sourceId: p.sourceId, slug: prior.slug, callerIntent }));
- if (prior.state === 'committed') await continueDerivationPurges(ctx.engine, prior.source_id);
+ if (prior.state === 'committed') await continueDerivationPurges(ctx.engine, prior.source_id, { first: prior.id });
return { ...(prior.outcome ?? {}), request_id: prior.request_id, state: prior.state, replayed: true, ...await purgeCompletion(ctx.engine, prior) };
}
}
@@ -588,7 +592,7 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Rec
for (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);
+ counts.page_segment_derivations = (counts.page_segment_derivations ?? 0) + await continueDerivationPurges(ctx.engine, p.sourceId, { first: row.id });
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 });
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
index 37985096a7..1edd771782 100644
--- a/src/core/operation-manifest.generated.ts
+++ b/src/core/operation-manifest.generated.ts
@@ -5696,6 +5696,10 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"type": "boolean",
"description": "Report the stored receipt and completion of the purge named by request_id."
},
+ "continue": {
+ "type": "boolean",
+ "description": "With status: first continue the purge's sweep of stored derivation results (derivation_sweep pending or stalled), then report."
+ },
"vacuum": {
"type": "boolean",
"description": "PGLite only: VACUUM the touched tables after the purge."
diff --git a/src/core/ops/purge.ts b/src/core/ops/purge.ts
index 9a3677e380..e1be578869 100644
--- a/src/core/ops/purge.ts
+++ b/src/core/ops/purge.ts
@@ -23,6 +23,7 @@ const purge_fact: Operation = {
expected_revision: { type: 'string', description: 'The expected_revision from the dry run; refuses when the target set changed since.' },
match: { type: 'string', description: 'List candidate fact ids whose text contains this; never purges.' },
status: { type: 'boolean', description: 'Report the stored receipt and completion of the purge named by request_id.' },
+ continue: { type: 'boolean', description: 'With status: first continue the purge\'s sweep of stored derivation results (derivation_sweep pending or stalled), then report.' },
vacuum: { type: 'boolean', description: 'PGLite only: VACUUM the touched tables after the purge.' },
source_id: { type: 'string', description: 'Source holding the fact (default: the routed source).' },
},
diff --git a/src/core/page-body/derivations.ts b/src/core/page-body/derivations.ts
index 84d29dea0e..2866b9b951 100644
--- a/src/core/page-body/derivations.ts
+++ b/src/core/page-body/derivations.ts
@@ -124,3 +124,11 @@ export function parseSourceWindow(value: unknown): SourceWindow | null {
}
return { occurrence_id: w.occurrence_id as number, window_ordinal: w.window_ordinal as number, window_text_sha: w.window_text_sha };
}
+
+/** Derivation rows a fact purge's recorded sweep refused (they hold its claim); the caller's step did not settle. */
+export class DerivationWriteRefused extends Error {
+ readonly code = 'derivation_purge_pending';
+ constructor(readonly refused: number) {
+ super(`${refused} derivation row(s) were not stored: a fact purge's sweep of stored derivation results is still running and they hold its claim.`);
+ }
+}
diff --git a/src/core/page-body/schema.ts b/src/core/page-body/schema.ts
index 4139a9c845..eeab547d49 100644
--- a/src/core/page-body/schema.ts
+++ b/src/core/page-body/schema.ts
@@ -234,13 +234,17 @@ export function derivationSweepScopeSql(d: string, p: string, pageIds: string):
* fence rewrite; demotion to inline deletes the page's rows, a fact purge the rows holding the claim, and a page
* delete cascades. The output holds link context and window anchors, so the table gets the segment tables' RLS posture.
*
- * page_segment_derivation_purges holds a fact purge's derivation sweep from the purge's commit until a walk of the
- * source's rows has deleted every row in its scope holding the claim (segment-derive.ts continueDerivationPurges): the
- * claim's normalized forms, the pages the purge rewrote and the walk's cursor. 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), so a row the walk has passed cannot come back behind it. A derivation write that read a purged
- * page before the purge committed is refused by its own generation guard instead.
+ * 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
+ * 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
+ * meterPaidCall), so a row the walk has passed cannot come back behind it. A derivation write that read a purged page
+ * before the purge committed is refused by its own generation guard instead. A row can also enter the scope without a
+ * write, when its occurrence is retired or its page soft-deleted: the triggers on page_body_manifest and pages note the
+ * page in page_segment_derivation_purge_pages for every sweep of the source, and the sweep checks those pages again
+ * before it ends.
*
* PR 4 (Wave B incremental derivation, transcripts): page_derivation_spend is the per-page lifetime spend ledger of each
* paid derivation family (`facts`, `atoms`, `synopsis`; page-spend.ts), each capped by `derive.max_usd_per_page` on its own,
@@ -276,12 +280,43 @@ CREATE TABLE IF NOT EXISTS page_segment_derivation_purges (
needles TEXT[] NOT NULL,
patterns TEXT[] NOT NULL,
page_ids INTEGER[] NOT NULL DEFAULT '{}',
+ phase TEXT NOT NULL DEFAULT 'sweep' CHECK (phase IN ('sweep','verify','recheck')),
+ recheck INTEGER[],
+ found INTEGER NOT NULL DEFAULT 0 CHECK (found >= 0),
cursor_page INTEGER,
cursor_pipeline TEXT,
cursor_occurrence BIGINT,
+ batch_rows INTEGER CHECK (batch_rows >= 1),
+ stalled_at TIMESTAMPTZ,
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);
+CREATE TABLE IF NOT EXISTS page_segment_derivation_purge_pages (
+ request_id UUID NOT NULL,
+ page_id INTEGER NOT NULL,
+ 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$
+BEGIN
+ IF 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;
+ 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;
+ END IF;
+ RETURN NULL;
+END
+$func$ LANGUAGE plpgsql;
+DROP TRIGGER IF EXISTS page_body_manifest_derivation_scope_retire ON page_body_manifest;
+CREATE TRIGGER page_body_manifest_derivation_scope_retire AFTER UPDATE OF gen_to ON page_body_manifest
+ FOR EACH ROW WHEN (OLD.gen_to IS NULL AND NEW.gen_to IS NOT NULL AND OLD.staging_id IS NULL) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry();
+DROP TRIGGER IF EXISTS page_body_manifest_derivation_scope_delete ON page_body_manifest;
+CREATE TRIGGER page_body_manifest_derivation_scope_delete AFTER DELETE ON page_body_manifest
+ FOR EACH ROW WHEN (OLD.gen_to IS NULL AND OLD.staging_id IS NULL) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry();
+DROP TRIGGER IF EXISTS pages_derivation_scope_delete ON pages;
+CREATE TRIGGER pages_derivation_scope_delete AFTER UPDATE OF deleted_at ON pages
+ FOR EACH ROW WHEN (OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry();
CREATE OR REPLACE FUNCTION gbrain_refuse_purging_derivation() RETURNS trigger SET search_path = pg_catalog, public AS $func$
BEGIN
IF EXISTS (SELECT 1 FROM page_segment_derivation_purges x JOIN pages p ON p.source_id = x.source_id
@@ -308,7 +343,7 @@ CREATE TRIGGER page_segment_derivations_refuse_purging BEFORE INSERT OR UPDATE O
* bootstrap enables RLS on no core table either. Source-scoped policies are operator SQL (docs/ENGINES.md).
*/
export const PAGE_BODY_RLS_TABLES = ['page_segment_texts', 'page_body_manifest', 'page_body_stagings', 'page_body_staging_parts', 'page_view_digests', 'page_body_staging_texts', 'page_segment_derivations',
- 'page_segment_derivation_purges'] as const;
+ 'page_segment_derivation_purges', 'page_segment_derivation_purge_pages'] as const;
export const PAGE_BODY_RLS_SQL = `DO $rls$
DECLARE target TEXT;
BEGIN
diff --git a/src/core/page-body/segment-derive.ts b/src/core/page-body/segment-derive.ts
index 366484b6e1..16a96496f4 100644
--- a/src/core/page-body/segment-derive.ts
+++ b/src/core/page-body/segment-derive.ts
@@ -18,6 +18,7 @@ import type { BrainEngine } from '../engine.ts';
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 { bodyBlocks, type BodyBlock } from './segment-blocks.ts';
import { ledgerApplies, readBodyLedger } from './segment-ledger.ts';
@@ -366,9 +367,10 @@ 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); 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.
+ * 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.
*/
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 };
@@ -391,12 +393,13 @@ export function derivationAfterSql(d: string, at: [string, string, string]): str
}
/**
- * @internal For the work-volume tests (counts, not time): per page, the derivation rows each sweep read, normalized and
- * deleted; per statement of a sweep or a receipt probe, the rows it read and normalized. Recorded only while
+ * @internal For the work-volume tests (counts, not time): per page, the derivation rows each sweep's first walk read,
+ * normalized and deleted; per statement of a sweep's first walk, of its verify and recheck walks (`verify`) or of a
+ * receipt probe, the rows it read and normalized. Recorded only while
* __setDerivationSweepWorkForTests(true) is in effect.
*/
export const derivationSweepWork: Array<{ pageId: number; scanned: number; normalized: number; deleted: number }> = [];
-export const derivationSweepStatements: Array<{ phase: 'sweep' | 'probe'; scanned: number; normalized: number }> = [];
+export const derivationSweepStatements: Array<{ phase: 'sweep' | 'verify' | 'probe'; scanned: number; normalized: number }> = [];
let recordSweepWork = false;
/** @internal Test seam: start (clearing what is there) or stop recording derivationSweepWork and derivationSweepStatements. */
export function __setDerivationSweepWorkForTests(on: boolean): void {
@@ -405,7 +408,7 @@ export function __setDerivationSweepWorkForTests(on: boolean): void {
derivationSweepStatements.length = 0;
}
/** @internal Records one statement's rows while a test records sweep work. */
-export function recordDerivationStatement(entry: { phase: 'sweep' | 'probe'; scanned: number; normalized: number }): void {
+export function recordDerivationStatement(entry: { phase: 'sweep' | 'verify' | 'probe'; scanned: number; normalized: number }): void {
if (recordSweepWork) derivationSweepStatements.push(entry);
}
@@ -423,38 +426,90 @@ export async function recordDerivationPurge(engine: Pick<BrainEngine, 'executeRa
VALUES ($1::uuid, $2, $3::text[], $4::text[], $5::int[]) ON CONFLICT (request_id) DO NOTHING`, [requestId, sourceId, needles, patterns, [...pageIds]]);
}
-/** Whether a purge request's derivation sweep is still recorded, so its rows are not all deleted yet. */
-export async function derivationPurgePending(engine: Pick<BrainEngine, 'executeRaw'>, requestId: string): Promise<boolean> {
- return (await engine.executeRaw('SELECT 1 FROM page_segment_derivation_purges WHERE request_id=$1::uuid', [requestId])).length > 0;
+/** A recorded derivation sweep of a purge request: still walking (`pending`) or stopped on a row that alone outran 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;
}
/**
- * Continue the recorded derivation sweeps of a source, oldest first: each batch is a transaction of its own that locks
- * the sweep's record (a sweep another caller is walking is left to it), reads the next DERIVATION_SWEEP_LIMITS.batchRows
- * rows of the source after the stored cursor, deletes those in the sweep's scope (derivationSweepScopeSql over its
- * pages) that hold the claim (derivationHoldsClaimSql; only rows passing the prefilter, derivationClaimCandidateSql, are
- * normalized) and stores the cursor, or deletes the record after the source's last row. No batch locks the source or a
- * page, so writes go on during a sweep. A batch is not started past DERIVATION_SWEEP_LIMITS.totalMs, and a statement
- * timeout ends the call with its batch rolled back; either way the next call (a later purge of the source, a replay of the
- * purge request) resumes from the cursor. Returns the rows deleted.
+ * Whether a recorded sweep covers page `pageId` (a page its purge rewrote, or a soft-deleted page of its source): the
+ * trigger drops a derivation write there that holds the claim, so a paid pipeline makes no call for it until the sweep ends.
*/
-export async function continueDerivationPurges(engine: BrainEngine, sourceId: string): Promise<number> {
- const { batchRows, totalMs, statementMs } = sweepLimits;
+export async function derivationSweepCoversPage(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number): Promise<boolean> {
+ return (await engine.executeRaw(`SELECT 1 FROM page_segment_derivation_purges x JOIN pages p ON p.source_id = x.source_id
+ WHERE p.id = $1 AND (p.id = ANY(x.page_ids) OR p.deleted_at IS NOT NULL) LIMIT 1`, [pageId])).length > 0;
+}
+
+type SweepRecord = { request_id: string; needles: string[]; patterns: string[]; page_ids: number[]; phase: 'sweep' | 'verify' | 'recheck'; recheck: number[] | null;
+ found: number; cursor_page: number | null; cursor_pipeline: string | null; cursor_occurrence: string | null; batch_rows: number };
+
+/**
+ * Continue the recorded derivation sweeps of a source: the sweep of request `opts.first` first, then the others oldest
+ * first, skipping a stalled one (`opts.retry` names one to try again). Each batch is a transaction of its own that locks
+ * the sweep's record (one another caller is walking is left to it), reads the next rows of the source after its cursor,
+ * the record's batch size of them (DERIVATION_SWEEP_LIMITS.batchRows at first), deletes those in the sweep's scope
+ * (derivationSweepScopeSql over its pages) that hold the claim (derivationHoldsClaimSql; only rows passing the
+ * prefilter, derivationClaimCandidateSql, are normalized) and stores the cursor. No batch locks the source or a page, so
+ * 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.
+ *
+ * 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.
+ */
+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;
const pages = new Map<number, { scanned: number; normalized: number; deleted: number }>();
- try {
- for (let batches = 0; batches === 0 || performance.now() <= deadline; batches++) {
- type Row = { page_id: number | null; swept: number; normalized: number; deleted: number; scanned: number; last_page: number; last_pipeline: string; last_occurrence: string };
- const rows = await engine.transaction(async tx => {
+ if (opts.retry) await engine.executeRaw('UPDATE page_segment_derivation_purges SET stalled_at = NULL WHERE request_id=$1::uuid', [opts.retry]);
+ const endWalk = async (tx: BrainEngine, purge: SweepRecord, found: number) => {
+ const restart = 'cursor_page = NULL, cursor_pipeline = NULL, cursor_occurrence = NULL, found = 0';
+ if (purge.phase === 'sweep' || (purge.phase === 'verify' && found > 0)) {
+ await tx.executeRaw('DELETE FROM page_segment_derivation_purge_pages WHERE request_id=$1::uuid', [purge.request_id]);
+ await tx.executeRaw(`UPDATE page_segment_derivation_purges SET phase = 'verify', recheck = NULL, ${restart} WHERE request_id=$1::uuid`, [purge.request_id]);
+ return;
+ }
+ const noted = (await tx.executeRaw<{ page_id: number }>('DELETE FROM page_segment_derivation_purge_pages WHERE request_id=$1::uuid RETURNING page_id',
+ [purge.request_id])).map(row => Number(row.page_id));
+ if (noted.length) await tx.executeRaw(`UPDATE page_segment_derivation_purges SET phase = 'recheck', recheck = $2::int[], ${restart} WHERE request_id=$1::uuid`,
+ [purge.request_id, noted]);
+ else {
+ await tx.executeRaw('DELETE FROM page_segment_derivation_purges WHERE request_id=$1::uuid', [purge.request_id]);
+ await tx.executeRaw(`DELETE FROM page_segment_derivation_purge_pages n WHERE NOT EXISTS (SELECT 1 FROM page_segment_derivation_purges x
+ WHERE x.request_id = n.request_id)`);
+ }
+ };
+ const timedOut = (error: unknown) => (error as { code?: unknown } | null)?.code === '57014';
+ const stalled: string[] = [];
+ 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;
+ try {
+ rows = await engine.transaction(async tx => {
await tx.executeRaw("SELECT set_config('statement_timeout',$1,true)", [`${statementMs}ms`]);
- const [purge] = await tx.executeRaw<{ request_id: string; needles: string[]; patterns: string[]; page_ids: number[]; cursor_page: number | null;
- cursor_pipeline: string | null; cursor_occurrence: string | null }>(`SELECT request_id::text AS request_id, needles, patterns, page_ids, cursor_page,
- cursor_pipeline, cursor_occurrence::text AS cursor_occurrence FROM page_segment_derivation_purges WHERE source_id=$1
- ORDER BY created_at, request_id LIMIT 1 FOR UPDATE SKIP LOCKED`, [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, $4), $4) AS batch_rows
+ FROM 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]);
if (!purge) return null;
+ picked = purge;
+ await faultPoint('purge:derivation_batch', { sourceId, requestId: purge.request_id, round: Number(purge.batch_rows),
+ read: purge.cursor_page === null ? '' : `${purge.cursor_page}/${purge.cursor_pipeline}/${purge.cursor_occurrence}` });
const batch = await tx.executeRaw<Row>(`WITH batch AS MATERIALIZED (
SELECT d.page_id, d.pipeline, d.occurrence_id, ${derivationSweepScopeSql('d', 'p', '$2')} AS swept FROM page_segment_derivations d
JOIN pages p ON p.id = d.page_id WHERE p.source_id = $1 AND ${derivationAfterSql('d', ['$5', '$6', '$7'])}
+ AND ($9::int[] IS NULL OR d.page_id = ANY($9::int[]))
ORDER BY d.page_id, d.pipeline, d.occurrence_id LIMIT $8
), scope AS MATERIALIZED (
SELECT d.page_id, d.pipeline, d.occurrence_id, d.output, d.receipt, ${derivationClaimCandidateSql('d', '$4')} AS candidate
@@ -473,24 +528,56 @@ export async function continueDerivationPurges(engine: BrainEngine, sourceId: st
) SELECT pp.page_id, COALESCE(pp.swept, 0) AS swept, COALESCE(pp.normalized, 0) AS normalized, COALESCE(pp.deleted, 0) AS deleted,
(SELECT count(*)::int FROM batch) AS scanned, l.page_id AS last_page, l.pipeline AS last_pipeline, l.occurrence_id AS last_occurrence
FROM (SELECT 1) one LEFT JOIN last l ON true LEFT JOIN per_page pp ON true ORDER BY pp.page_id`,
- [sourceId, purge.page_ids, purge.needles, purge.patterns, purge.cursor_page, purge.cursor_pipeline, purge.cursor_occurrence, batchRows]);
- const scanned = Number(batch[0]?.scanned ?? 0);
- if (scanned < batchRows) await tx.executeRaw('DELETE FROM page_segment_derivation_purges WHERE request_id=$1::uuid', [purge.request_id]);
- else await tx.executeRaw(`UPDATE page_segment_derivation_purges SET cursor_page=$2, cursor_pipeline=$3, cursor_occurrence=$4::bigint
- WHERE request_id=$1::uuid`, [purge.request_id, Number(batch[0]!.last_page), batch[0]!.last_pipeline, String(batch[0]!.last_occurrence)]);
+ [sourceId, purge.page_ids, purge.needles, purge.patterns, purge.cursor_page, purge.cursor_pipeline, purge.cursor_occurrence, purge.batch_rows, purge.recheck]);
+ const found = Number(purge.found) + batch.reduce((n, row) => n + Number(row.deleted), 0);
+ if (Number(batch[0]?.scanned ?? 0) < Number(purge.batch_rows)) await endWalk(tx, purge, found);
+ else await tx.executeRaw(`UPDATE page_segment_derivation_purges SET cursor_page=$2, cursor_pipeline=$3, cursor_occurrence=$4::bigint, found=$5
+ WHERE request_id=$1::uuid`, [purge.request_id, Number(batch[0]!.last_page), batch[0]!.last_pipeline, String(batch[0]!.last_occurrence), found]);
return batch;
});
- if (!rows) break;
- recordDerivationStatement({ phase: 'sweep', scanned: Number(rows[0]?.scanned ?? 0), normalized: rows.reduce((n, row) => n + Number(row.normalized), 0) });
- for (const row of rows) {
- if (row.page_id === null) continue;
- const page = pages.get(Number(row.page_id)) ?? { scanned: 0, normalized: 0, deleted: 0 };
- pages.set(Number(row.page_id), { scanned: page.scanned + Number(row.swept), normalized: page.normalized + Number(row.normalized), deleted: page.deleted + Number(row.deleted) });
+ } catch (error) {
+ const purge = picked as SweepRecord | null;
+ if (!timedOut(error) || !purge) throw error;
+ if (Number(purge.batch_rows) > 1) {
+ await engine.executeRaw('UPDATE page_segment_derivation_purges SET batch_rows=$2 WHERE request_id=$1::uuid', [purge.request_id, Math.floor(Number(purge.batch_rows) / 2)]);
+ continue;
+ }
+ try {
+ rows = await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('statement_timeout',$1,true)", [`${statementMs}ms`]);
+ await faultPoint('purge:derivation_unread', { sourceId, requestId: purge.request_id });
+ const [next] = await tx.executeRaw<{ page_id: number; pipeline: string; occurrence_id: string; swept: boolean }>(`SELECT d.page_id, d.pipeline,
+ d.occurrence_id::text AS occurrence_id, ${derivationSweepScopeSql('d', 'p', '$2')} AS swept FROM page_segment_derivations d
+ JOIN pages p ON p.id = d.page_id WHERE p.source_id = $1 AND ${derivationAfterSql('d', ['$3', '$4', '$5'])} AND ($6::int[] IS NULL OR d.page_id = ANY($6::int[]))
+ ORDER BY d.page_id, d.pipeline, d.occurrence_id LIMIT 1`,
+ [sourceId, purge.page_ids, purge.cursor_page, purge.cursor_pipeline, purge.cursor_occurrence, purge.recheck]);
+ if (!next) {
+ await endWalk(tx, purge, Number(purge.found));
+ 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;
+ await tx.executeRaw(`UPDATE page_segment_derivation_purges SET cursor_page=$2, cursor_pipeline=$3, cursor_occurrence=$4::bigint, found=found + $5
+ WHERE 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 }];
+ });
+ } 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);
+ continue;
}
- await afterSweepBatch?.();
}
- } catch (error) {
- if ((error as { code?: unknown } | null)?.code !== '57014') throw error;
+ if (!rows) break;
+ const walk = (picked as SweepRecord | null)?.phase === 'sweep' ? 'sweep' : 'verify';
+ recordDerivationStatement({ phase: walk, scanned: Number(rows[0]?.scanned ?? 0), normalized: rows.reduce((n, row) => n + Number(row.normalized), 0) });
+ if (walk === 'sweep') for (const row of rows) {
+ if (row.page_id === null) continue;
+ const page = pages.get(Number(row.page_id)) ?? { scanned: 0, normalized: 0, deleted: 0 };
+ pages.set(Number(row.page_id), { scanned: page.scanned + Number(row.swept), normalized: page.normalized + Number(row.normalized), deleted: page.deleted + Number(row.deleted) });
+ }
+ await afterSweepBatch?.();
}
const sorted = [...pages].sort((a, b) => a[0] - b[0]);
if (recordSweepWork) for (const [pageId, work] of sorted) derivationSweepWork.push({ pageId, ...work });
diff --git a/src/core/page-embedding-budget.ts b/src/core/page-embedding-budget.ts
index d5876d1a9f..10d2c64611 100644
--- a/src/core/page-embedding-budget.ts
+++ b/src/core/page-embedding-budget.ts
@@ -36,6 +36,7 @@ import type { BrainEngine } from './engine.ts';
import { JUNK_SAMPLE_CHARS, assessJunkWindows, assessSampledJunk } from './content-sanity.ts';
import type { BodyStorage, ManifestRow } from './page-body/types.ts';
import { isSegmentedPage, pageBodyBytes } from './page-body/page-shape.ts';
+import { derivationSweepCoversPage } from './page-body/segment-derive.ts';
import { estimateCostFromChars } from './embedding-pricing.ts';
import { reservationCostUsd, usageCostUsd } from './budget/reservation-cost.ts';
import { BudgetTracker, type PricingOverrides } from './budget/budget-tracker.ts';
@@ -296,10 +297,14 @@ class MeteredStepTracker extends BudgetTracker {
* model books the reservation; a step with no billed attempt books nothing. The attempts are reserved and recorded on
* the caller's tracker too, so the caller's cap bounds them. `unpricedModel` names the model when the step was refused
* under an unpriced model's ceiling estimate or booked its reservation because the model has no price: the caller's
- * receipt then says `unpriced_model` (unpricedModelReceipt) and doctor derivation_unpriced_model names the fix.
+ * receipt then says `unpriced_model` (unpricedModelReceipt) and doctor derivation_unpriced_model names the fix. While a fact
+ * purge's derivation sweep covers the page (segment-derive.ts derivationSweepCoversPage) the step is refused with
+ * `purge_sweep_pending` before anything is reserved or called.
*/
export async function meterPaidCall<T>(engine: BrainEngine, page: BudgetPage, signature: PageSpendSignature, estimateUsd: number,
call: () => Promise<T>, opts: { pricingOverrides?: PricingOverrides } = {}): Promise<({ refused: Extract<PageSpendDecision, { kind: 'refused' }> } | { value: T }) & { unpricedModel?: string }> {
+ // A purge sweep covering the page would drop the step's checkpoint, so the step is not paid for until the sweep ends.
+ if (await derivationSweepCoversPage(engine, page.id)) return { refused: { kind: 'refused', reason: 'purge_sweep_pending', capUsd: 0, spentUsd: 0, reservedUsd: 0, estimateUsd } };
const decision = await reservePageSpend(engine, page, signature, estimateUsd);
// PR 4 (Wave B incremental derivation, transcripts): an unpriced model reserves the ceiling estimate, so a refusal under it is the missing price's.
const model = signature.slice(signature.indexOf(':') + 1);
diff --git a/src/core/page-spend.ts b/src/core/page-spend.ts
index 8b2f07717f..b5265a89b9 100644
--- a/src/core/page-spend.ts
+++ b/src/core/page-spend.ts
@@ -36,7 +36,7 @@ export interface PageSpendGrant {
/** `refused`: the estimate does not fit what the cap leaves (`cap_reached`), or an embedding waits for approval (`held`); nothing was reserved. */
export type PageSpendDecision =
| { kind: 'unmetered' }
- | { kind: 'refused'; reason: 'cap_reached' | 'held'; capUsd: number; spentUsd: number; reservedUsd: number; estimateUsd: number }
+ | { kind: 'refused'; reason: 'cap_reached' | 'held' | 'purge_sweep_pending'; capUsd: number; spentUsd: number; reservedUsd: number; estimateUsd: number }
| { kind: 'grant'; grant: PageSpendGrant };
const RESERVED_EPSILON_USD = 1e-9;
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index e99345e85e..4dd88c8e00 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -49,6 +49,12 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect
| 'purge:ledger_redaction'
// Before a fact purge records its derivation sweep in its transaction (segment-derive.ts recordDerivationPurge); a 57014 from the hook models its statement timeout.
| 'purge:derivation_sweep'
+ // Inside each batch transaction of a purge's derivation sweep (segment-derive.ts continueDerivationPurges), with the batch size as `round` and the cursor as `read`; a 57014 from the hook models the batch outrunning its statement budget.
+ | 'purge:derivation_batch'
+ // Before the sweep deletes, unread, the one row that alone outran its statement budget; a 57014 from the hook models that statement outrunning it too.
+ | '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'
// #6712 PR 4b: after a page-row deletion of a managed Git source wrote its origin's deletion marker (sync-markers.ts), before the row goes.
| 'purge:marker_written'
// #6712 PR 4b: before each round of a pass reads its level (`round`), and after it read it (`level`: its statements and its
diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.ts
index c45b46929a..ee026b434b 100644
--- a/src/core/persistence/graduation-inventory.ts
+++ b/src/core/persistence/graduation-inventory.ts
@@ -122,6 +122,7 @@ export const GRADUATION_INVENTORY: Inventory = {
carry('page_purges', 'user_data', 'Text-free page purge tombstones (#5575); dropping them would let purged pages re-import.'),
carry('page_retrievals', 'operational', 'Retrieval telemetry: when a user-facing read last surfaced each page (stale-page bias, volunteer usage stats).'),
carry('page_segment_derivations', 'operational', 'Per-segment derivation watermarks (links, mentions, timeline, fences, conversation facts, atoms, backstop, synopsis) keyed by manifest occurrence; without them the next pass re-derives every segment, including paid conversation-facts windows.'),
+ carry('page_segment_derivation_purge_pages', 'operational', 'Pages whose derivation rows entered a recorded purge sweep\'s scope while it ran (an occurrence retired, a page soft-deleted); without them a graduated brain finishes a sweep without checking those pages again.'),
carry('page_segment_derivation_purges', 'operational', 'Recorded purge sweeps of segment derivation rows still in progress, with their cursor and claim; without them a graduated brain stops refusing claimed text and never finishes sweeping it out of copied derivation rows.'),
carry('page_segment_texts', 'user_data', 'Segment texts of segmented page bodies, stored once per source; without them a large page has no body.'),
carry('page_versions', 'user_data', 'Page revision history with attribution.'),
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index ea03e6223e..edb7474138 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -1419,12 +1419,43 @@ CREATE TABLE IF NOT EXISTS page_segment_derivation_purges (
needles TEXT[] NOT NULL,
patterns TEXT[] NOT NULL,
page_ids INTEGER[] NOT NULL DEFAULT '{}',
+ phase TEXT NOT NULL DEFAULT 'sweep' CHECK (phase IN ('sweep','verify','recheck')),
+ recheck INTEGER[],
+ found INTEGER NOT NULL DEFAULT 0 CHECK (found >= 0),
cursor_page INTEGER,
cursor_pipeline TEXT,
cursor_occurrence BIGINT,
+ batch_rows INTEGER CHECK (batch_rows >= 1),
+ stalled_at TIMESTAMPTZ,
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);
+CREATE TABLE IF NOT EXISTS page_segment_derivation_purge_pages (
+ request_id UUID NOT NULL,
+ page_id INTEGER NOT NULL,
+ 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\$
+BEGIN
+ IF 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;
+ 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;
+ END IF;
+ RETURN NULL;
+END
+\$func\$ LANGUAGE plpgsql;
+DROP TRIGGER IF EXISTS page_body_manifest_derivation_scope_retire ON page_body_manifest;
+CREATE TRIGGER page_body_manifest_derivation_scope_retire AFTER UPDATE OF gen_to ON page_body_manifest
+ FOR EACH ROW WHEN (OLD.gen_to IS NULL AND NEW.gen_to IS NOT NULL AND OLD.staging_id IS NULL) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry();
+DROP TRIGGER IF EXISTS page_body_manifest_derivation_scope_delete ON page_body_manifest;
+CREATE TRIGGER page_body_manifest_derivation_scope_delete AFTER DELETE ON page_body_manifest
+ FOR EACH ROW WHEN (OLD.gen_to IS NULL AND OLD.staging_id IS NULL) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry();
+DROP TRIGGER IF EXISTS pages_derivation_scope_delete ON pages;
+CREATE TRIGGER pages_derivation_scope_delete AFTER UPDATE OF deleted_at ON pages
+ FOR EACH ROW WHEN (OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry();
CREATE OR REPLACE FUNCTION gbrain_refuse_purging_derivation() RETURNS trigger SET search_path = pg_catalog, public AS \$func\$
BEGIN
IF EXISTS (SELECT 1 FROM page_segment_derivation_purges x JOIN pages p ON p.source_id = x.source_id
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index 2475505558..8b0dc85f35 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -2163,12 +2163,43 @@ CREATE TABLE IF NOT EXISTS page_segment_derivation_purges (
needles TEXT[] NOT NULL,
patterns TEXT[] NOT NULL,
page_ids INTEGER[] NOT NULL DEFAULT '{}',
+ phase TEXT NOT NULL DEFAULT 'sweep' CHECK (phase IN ('sweep','verify','recheck')),
+ recheck INTEGER[],
+ found INTEGER NOT NULL DEFAULT 0 CHECK (found >= 0),
cursor_page INTEGER,
cursor_pipeline TEXT,
cursor_occurrence BIGINT,
+ batch_rows INTEGER CHECK (batch_rows >= 1),
+ stalled_at TIMESTAMPTZ,
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);
+CREATE TABLE IF NOT EXISTS page_segment_derivation_purge_pages (
+ request_id UUID NOT NULL,
+ page_id INTEGER NOT NULL,
+ 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\$
+BEGIN
+ IF 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;
+ 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;
+ END IF;
+ RETURN NULL;
+END
+\$func\$ LANGUAGE plpgsql;
+DROP TRIGGER IF EXISTS page_body_manifest_derivation_scope_retire ON page_body_manifest;
+CREATE TRIGGER page_body_manifest_derivation_scope_retire AFTER UPDATE OF gen_to ON page_body_manifest
+ FOR EACH ROW WHEN (OLD.gen_to IS NULL AND NEW.gen_to IS NOT NULL AND OLD.staging_id IS NULL) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry();
+DROP TRIGGER IF EXISTS page_body_manifest_derivation_scope_delete ON page_body_manifest;
+CREATE TRIGGER page_body_manifest_derivation_scope_delete AFTER DELETE ON page_body_manifest
+ FOR EACH ROW WHEN (OLD.gen_to IS NULL AND OLD.staging_id IS NULL) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry();
+DROP TRIGGER IF EXISTS pages_derivation_scope_delete ON pages;
+CREATE TRIGGER pages_derivation_scope_delete AFTER UPDATE OF deleted_at ON pages
+ FOR EACH ROW WHEN (OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry();
CREATE OR REPLACE FUNCTION gbrain_refuse_purging_derivation() RETURNS trigger SET search_path = pg_catalog, public AS \$func\$
BEGIN
IF EXISTS (SELECT 1 FROM page_segment_derivation_purges x JOIN pages p ON p.source_id = x.source_id
@@ -2194,7 +2225,7 @@ DO \$rls\$
DECLARE target TEXT;
BEGIN
IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN
- FOREACH target IN ARRAY ARRAY['page_segment_texts','page_body_manifest','page_body_stagings','page_body_staging_parts','page_view_digests','page_body_staging_texts','page_segment_derivations','page_segment_derivation_purges'] LOOP
+ FOREACH target IN ARRAY ARRAY['page_segment_texts','page_body_manifest','page_body_stagings','page_body_staging_parts','page_view_digests','page_body_staging_texts','page_segment_derivations','page_segment_derivation_purges','page_segment_derivation_purge_pages'] LOOP
IF EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = current_schema() AND c.relname = target AND c.relkind = 'r' AND NOT c.relrowsecurity) THEN
EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', target);
diff --git a/src/schema.sql b/src/schema.sql
index 178b94e01f..969ac29d71 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -2159,12 +2159,43 @@ CREATE TABLE IF NOT EXISTS page_segment_derivation_purges (
needles TEXT[] NOT NULL,
patterns TEXT[] NOT NULL,
page_ids INTEGER[] NOT NULL DEFAULT '{}',
+ phase TEXT NOT NULL DEFAULT 'sweep' CHECK (phase IN ('sweep','verify','recheck')),
+ recheck INTEGER[],
+ found INTEGER NOT NULL DEFAULT 0 CHECK (found >= 0),
cursor_page INTEGER,
cursor_pipeline TEXT,
cursor_occurrence BIGINT,
+ batch_rows INTEGER CHECK (batch_rows >= 1),
+ stalled_at TIMESTAMPTZ,
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);
+CREATE TABLE IF NOT EXISTS page_segment_derivation_purge_pages (
+ request_id UUID NOT NULL,
+ page_id INTEGER NOT NULL,
+ 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$
+BEGIN
+ IF 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;
+ 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;
+ END IF;
+ RETURN NULL;
+END
+$func$ LANGUAGE plpgsql;
+DROP TRIGGER IF EXISTS page_body_manifest_derivation_scope_retire ON page_body_manifest;
+CREATE TRIGGER page_body_manifest_derivation_scope_retire AFTER UPDATE OF gen_to ON page_body_manifest
+ FOR EACH ROW WHEN (OLD.gen_to IS NULL AND NEW.gen_to IS NOT NULL AND OLD.staging_id IS NULL) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry();
+DROP TRIGGER IF EXISTS page_body_manifest_derivation_scope_delete ON page_body_manifest;
+CREATE TRIGGER page_body_manifest_derivation_scope_delete AFTER DELETE ON page_body_manifest
+ FOR EACH ROW WHEN (OLD.gen_to IS NULL AND OLD.staging_id IS NULL) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry();
+DROP TRIGGER IF EXISTS pages_derivation_scope_delete ON pages;
+CREATE TRIGGER pages_derivation_scope_delete AFTER UPDATE OF deleted_at ON pages
+ FOR EACH ROW WHEN (OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry();
CREATE OR REPLACE FUNCTION gbrain_refuse_purging_derivation() RETURNS trigger SET search_path = pg_catalog, public AS $func$
BEGIN
IF EXISTS (SELECT 1 FROM page_segment_derivation_purges x JOIN pages p ON p.source_id = x.source_id
@@ -2190,7 +2221,7 @@ DO $rls$
DECLARE target TEXT;
BEGIN
IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN
- FOREACH target IN ARRAY ARRAY['page_segment_texts','page_body_manifest','page_body_stagings','page_body_staging_parts','page_view_digests','page_body_staging_texts','page_segment_derivations','page_segment_derivation_purges'] LOOP
+ FOREACH target IN ARRAY ARRAY['page_segment_texts','page_body_manifest','page_body_stagings','page_body_staging_parts','page_view_digests','page_body_staging_texts','page_segment_derivations','page_segment_derivation_purges','page_segment_derivation_purge_pages'] LOOP
IF EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = current_schema() AND c.relname = target AND c.relkind = 'r' AND NOT c.relrowsecurity) THEN
EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', target);
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 5f0fa3b761..34b1767008 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -264,6 +264,10 @@
"page_purges.page_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_purges.trust_generation_insert": "t TRIGGER DEFERRABLE INITIALLY DEFERRED",
"page_retrievals.page_retrievals_pkey": "p PRIMARY KEY (page_id)",
+ "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_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_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))",
@@ -532,6 +536,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_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",
@@ -814,6 +819,9 @@
"page_retrievals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_segment_derivation_purge_pages": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_segment_derivation_purges": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1322,6 +1330,7 @@
"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)",
"page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)",
"page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)",
+ "page_segment_derivation_purge_pages_pkey": "CREATE UNIQUE INDEX page_segment_derivation_purge_pages_pkey ON public.page_segment_derivation_purge_pages USING btree (request_id, page_id)",
"page_segment_derivation_purges_pkey": "CREATE UNIQUE INDEX page_segment_derivation_purges_pkey ON public.page_segment_derivation_purges USING btree (request_id)",
"page_segment_derivation_purges_source": "CREATE INDEX page_segment_derivation_purges_source ON public.page_segment_derivation_purges USING btree (source_id, created_at)",
"page_segment_derivations_pkey": "CREATE UNIQUE INDEX page_segment_derivations_pkey ON public.page_segment_derivations USING btree (page_id, pipeline, occurrence_id)",
@@ -2980,6 +2989,13 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_segment_derivation_purge_pages": {
+ "columns": [
+ "1 request_id uuid/uuid NOT NULL",
+ "2 page_id integer/int4 NOT NULL"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_segment_derivation_purges": {
"columns": [
"1 request_id uuid/uuid NOT NULL",
@@ -2987,10 +3003,15 @@
"3 needles ARRAY/_text NOT NULL",
"4 patterns ARRAY/_text NOT NULL",
"5 page_ids ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]",
- "6 cursor_page integer/int4 NULL",
- "7 cursor_pipeline text/text NULL",
- "8 cursor_occurrence bigint/int8 NULL",
- "9 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "6 phase text/text NOT NULL DEFAULT 'sweep'::text",
+ "7 recheck ARRAY/_int4 NULL",
+ "8 found integer/int4 NOT NULL DEFAULT 0",
+ "9 cursor_page integer/int4 NULL",
+ "10 cursor_pipeline text/text NULL",
+ "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()"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -4157,6 +4178,8 @@
"oauth_clients.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.oauth_clients DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.min_trust IS DISTINCT FROM new.min_trust)) EXECUTE FUNCTION gbrain_bump_trust_generation()",
"page_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"page_body_manifest.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_body_manifest FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
+ "page_body_manifest.page_body_manifest_derivation_scope_delete": "CREATE TRIGGER page_body_manifest_derivation_scope_delete AFTER DELETE ON public.page_body_manifest FOR EACH ROW WHEN (((old.gen_to IS NULL) AND (old.staging_id IS NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
+ "page_body_manifest.page_body_manifest_derivation_scope_retire": "CREATE TRIGGER page_body_manifest_derivation_scope_retire AFTER UPDATE OF gen_to ON public.page_body_manifest FOR EACH ROW WHEN (((old.gen_to IS NULL) AND (new.gen_to IS NOT NULL) AND (old.staging_id IS NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
"page_purges.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.page_purges DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()",
"page_segment_derivations.page_segment_derivations_refuse_purging": "CREATE TRIGGER page_segment_derivations_refuse_purging BEFORE INSERT OR UPDATE OF output, receipt ON public.page_segment_derivations FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purging_derivation()",
"page_segment_texts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_segment_texts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
@@ -4166,6 +4189,7 @@
"pages.bump_page_generation_trg": "CREATE TRIGGER bump_page_generation_trg BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION bump_page_generation_fn()",
"pages.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"pages.pages_clear_atom_scan_state": "CREATE TRIGGER pages_clear_atom_scan_state AFTER UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_clear_atom_page_state()",
+ "pages.pages_derivation_scope_delete": "CREATE TRIGGER pages_derivation_scope_delete AFTER UPDATE OF deleted_at ON public.pages FOR EACH ROW WHEN (((old.deleted_at IS NULL) AND (new.deleted_at IS NOT NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
"pages.pages_forget_retrievals": "CREATE TRIGGER pages_forget_retrievals AFTER DELETE ON public.pages REFERENCING OLD TABLE AS gbrain_deleted_pages FOR EACH STATEMENT EXECUTE FUNCTION gbrain_forget_page_retrievals()",
"pages.pages_knowledge_revision": "CREATE TRIGGER pages_knowledge_revision BEFORE UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_advance_page_revision()",
"pages.pages_projection_queue": "CREATE TRIGGER pages_projection_queue AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_queue_page_projection()",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index bb57466049..9c75c846c3 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -264,6 +264,10 @@
"page_purges.page_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_purges.trust_generation_insert": "t TRIGGER DEFERRABLE INITIALLY DEFERRED",
"page_retrievals.page_retrievals_pkey": "p PRIMARY KEY (page_id)",
+ "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_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_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))",
@@ -532,6 +536,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_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",
@@ -814,6 +819,9 @@
"page_retrievals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_segment_derivation_purge_pages": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_segment_derivation_purges": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1322,6 +1330,7 @@
"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)",
"page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)",
"page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)",
+ "page_segment_derivation_purge_pages_pkey": "CREATE UNIQUE INDEX page_segment_derivation_purge_pages_pkey ON public.page_segment_derivation_purge_pages USING btree (request_id, page_id)",
"page_segment_derivation_purges_pkey": "CREATE UNIQUE INDEX page_segment_derivation_purges_pkey ON public.page_segment_derivation_purges USING btree (request_id)",
"page_segment_derivation_purges_source": "CREATE INDEX page_segment_derivation_purges_source ON public.page_segment_derivation_purges USING btree (source_id, created_at)",
"page_segment_derivations_pkey": "CREATE UNIQUE INDEX page_segment_derivations_pkey ON public.page_segment_derivations USING btree (page_id, pipeline, occurrence_id)",
@@ -2980,6 +2989,13 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_segment_derivation_purge_pages": {
+ "columns": [
+ "1 request_id uuid/uuid NOT NULL",
+ "2 page_id integer/int4 NOT NULL"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_segment_derivation_purges": {
"columns": [
"1 request_id uuid/uuid NOT NULL",
@@ -2987,10 +3003,15 @@
"3 needles ARRAY/_text NOT NULL",
"4 patterns ARRAY/_text NOT NULL",
"5 page_ids ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]",
- "6 cursor_page integer/int4 NULL",
- "7 cursor_pipeline text/text NULL",
- "8 cursor_occurrence bigint/int8 NULL",
- "9 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "6 phase text/text NOT NULL DEFAULT 'sweep'::text",
+ "7 recheck ARRAY/_int4 NULL",
+ "8 found integer/int4 NOT NULL DEFAULT 0",
+ "9 cursor_page integer/int4 NULL",
+ "10 cursor_pipeline text/text NULL",
+ "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()"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -4157,6 +4178,8 @@
"oauth_clients.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.oauth_clients DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.min_trust IS DISTINCT FROM new.min_trust)) EXECUTE FUNCTION gbrain_bump_trust_generation()",
"page_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"page_body_manifest.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_body_manifest FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
+ "page_body_manifest.page_body_manifest_derivation_scope_delete": "CREATE TRIGGER page_body_manifest_derivation_scope_delete AFTER DELETE ON public.page_body_manifest FOR EACH ROW WHEN (((old.gen_to IS NULL) AND (old.staging_id IS NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
+ "page_body_manifest.page_body_manifest_derivation_scope_retire": "CREATE TRIGGER page_body_manifest_derivation_scope_retire AFTER UPDATE OF gen_to ON public.page_body_manifest FOR EACH ROW WHEN (((old.gen_to IS NULL) AND (new.gen_to IS NOT NULL) AND (old.staging_id IS NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
"page_purges.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.page_purges DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()",
"page_segment_derivations.page_segment_derivations_refuse_purging": "CREATE TRIGGER page_segment_derivations_refuse_purging BEFORE INSERT OR UPDATE OF output, receipt ON public.page_segment_derivations FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purging_derivation()",
"page_segment_texts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_segment_texts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
@@ -4166,6 +4189,7 @@
"pages.bump_page_generation_trg": "CREATE TRIGGER bump_page_generation_trg BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION bump_page_generation_fn()",
"pages.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"pages.pages_clear_atom_scan_state": "CREATE TRIGGER pages_clear_atom_scan_state AFTER UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_clear_atom_page_state()",
+ "pages.pages_derivation_scope_delete": "CREATE TRIGGER pages_derivation_scope_delete AFTER UPDATE OF deleted_at ON public.pages FOR EACH ROW WHEN (((old.deleted_at IS NULL) AND (new.deleted_at IS NOT NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
"pages.pages_forget_retrievals": "CREATE TRIGGER pages_forget_retrievals AFTER DELETE ON public.pages REFERENCING OLD TABLE AS gbrain_deleted_pages FOR EACH STATEMENT EXECUTE FUNCTION gbrain_forget_page_retrievals()",
"pages.pages_knowledge_revision": "CREATE TRIGGER pages_knowledge_revision BEFORE UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_advance_page_revision()",
"pages.pages_projection_queue": "CREATE TRIGGER pages_projection_queue AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_queue_page_projection()",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index a6ee7367d4..4fbfad255d 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -264,6 +264,10 @@
"page_purges.page_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_purges.trust_generation_insert": "t TRIGGER DEFERRABLE INITIALLY DEFERRED",
"page_retrievals.page_retrievals_pkey": "p PRIMARY KEY (page_id)",
+ "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_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_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))",
@@ -532,6 +536,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_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",
@@ -814,6 +819,9 @@
"page_retrievals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_segment_derivation_purge_pages": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_segment_derivation_purges": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1318,6 +1326,7 @@
"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)",
"page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)",
"page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)",
+ "page_segment_derivation_purge_pages_pkey": "CREATE UNIQUE INDEX page_segment_derivation_purge_pages_pkey ON public.page_segment_derivation_purge_pages USING btree (request_id, page_id)",
"page_segment_derivation_purges_pkey": "CREATE UNIQUE INDEX page_segment_derivation_purges_pkey ON public.page_segment_derivation_purges USING btree (request_id)",
"page_segment_derivation_purges_source": "CREATE INDEX page_segment_derivation_purges_source ON public.page_segment_derivation_purges USING btree (source_id, created_at)",
"page_segment_derivations_pkey": "CREATE UNIQUE INDEX page_segment_derivations_pkey ON public.page_segment_derivations USING btree (page_id, pipeline, occurrence_id)",
@@ -2976,6 +2985,13 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_segment_derivation_purge_pages": {
+ "columns": [
+ "1 request_id uuid/uuid NOT NULL",
+ "2 page_id integer/int4 NOT NULL"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_segment_derivation_purges": {
"columns": [
"1 request_id uuid/uuid NOT NULL",
@@ -2983,10 +2999,15 @@
"3 needles ARRAY/_text NOT NULL",
"4 patterns ARRAY/_text NOT NULL",
"5 page_ids ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]",
- "6 cursor_page integer/int4 NULL",
- "7 cursor_pipeline text/text NULL",
- "8 cursor_occurrence bigint/int8 NULL",
- "9 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "6 phase text/text NOT NULL DEFAULT 'sweep'::text",
+ "7 recheck ARRAY/_int4 NULL",
+ "8 found integer/int4 NOT NULL DEFAULT 0",
+ "9 cursor_page integer/int4 NULL",
+ "10 cursor_pipeline text/text NULL",
+ "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()"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -4153,6 +4174,8 @@
"oauth_clients.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.oauth_clients DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.min_trust IS DISTINCT FROM new.min_trust)) EXECUTE FUNCTION gbrain_bump_trust_generation()",
"page_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"page_body_manifest.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_body_manifest FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
+ "page_body_manifest.page_body_manifest_derivation_scope_delete": "CREATE TRIGGER page_body_manifest_derivation_scope_delete AFTER DELETE ON public.page_body_manifest FOR EACH ROW WHEN (((old.gen_to IS NULL) AND (old.staging_id IS NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
+ "page_body_manifest.page_body_manifest_derivation_scope_retire": "CREATE TRIGGER page_body_manifest_derivation_scope_retire AFTER UPDATE OF gen_to ON public.page_body_manifest FOR EACH ROW WHEN (((old.gen_to IS NULL) AND (new.gen_to IS NOT NULL) AND (old.staging_id IS NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
"page_purges.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.page_purges DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()",
"page_segment_derivations.page_segment_derivations_refuse_purging": "CREATE TRIGGER page_segment_derivations_refuse_purging BEFORE INSERT OR UPDATE OF output, receipt ON public.page_segment_derivations FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purging_derivation()",
"page_segment_texts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_segment_texts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
@@ -4162,6 +4185,7 @@
"pages.bump_page_generation_trg": "CREATE TRIGGER bump_page_generation_trg BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION bump_page_generation_fn()",
"pages.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"pages.pages_clear_atom_scan_state": "CREATE TRIGGER pages_clear_atom_scan_state AFTER UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_clear_atom_page_state()",
+ "pages.pages_derivation_scope_delete": "CREATE TRIGGER pages_derivation_scope_delete AFTER UPDATE OF deleted_at ON public.pages FOR EACH ROW WHEN (((old.deleted_at IS NULL) AND (new.deleted_at IS NOT NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
"pages.pages_forget_retrievals": "CREATE TRIGGER pages_forget_retrievals AFTER DELETE ON public.pages REFERENCING OLD TABLE AS gbrain_deleted_pages FOR EACH STATEMENT EXECUTE FUNCTION gbrain_forget_page_retrievals()",
"pages.pages_knowledge_revision": "CREATE TRIGGER pages_knowledge_revision BEFORE UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_advance_page_revision()",
"pages.pages_projection_queue": "CREATE TRIGGER pages_projection_queue AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_queue_page_projection()",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
index 4acfaf9e46..da02fde4b7 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
@@ -191,6 +191,10 @@
"page_purges.page_purges_pkey": "p PRIMARY KEY (source_id, content_hash)",
"page_purges.page_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_retrievals.page_retrievals_pkey": "p PRIMARY KEY (page_id)",
+ "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_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_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))",
@@ -394,6 +398,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_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",
@@ -606,6 +611,9 @@
"page_retrievals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_segment_derivation_purge_pages": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_segment_derivation_purges": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -977,6 +985,7 @@
"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)",
"page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)",
"page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)",
+ "page_segment_derivation_purge_pages_pkey": "CREATE UNIQUE INDEX page_segment_derivation_purge_pages_pkey ON public.page_segment_derivation_purge_pages USING btree (request_id, page_id)",
"page_segment_derivation_purges_pkey": "CREATE UNIQUE INDEX page_segment_derivation_purges_pkey ON public.page_segment_derivation_purges USING btree (request_id)",
"page_segment_derivation_purges_source": "CREATE INDEX page_segment_derivation_purges_source ON public.page_segment_derivation_purges USING btree (source_id, created_at)",
"page_segment_derivations_pkey": "CREATE UNIQUE INDEX page_segment_derivations_pkey ON public.page_segment_derivations USING btree (page_id, pipeline, occurrence_id)",
@@ -2242,6 +2251,13 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_segment_derivation_purge_pages": {
+ "columns": [
+ "1 request_id uuid/uuid NOT NULL",
+ "2 page_id integer/int4 NOT NULL"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_segment_derivation_purges": {
"columns": [
"1 request_id uuid/uuid NOT NULL",
@@ -2249,10 +2265,15 @@
"3 needles ARRAY/_text NOT NULL",
"4 patterns ARRAY/_text NOT NULL",
"5 page_ids ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]",
- "6 cursor_page integer/int4 NULL",
- "7 cursor_pipeline text/text NULL",
- "8 cursor_occurrence bigint/int8 NULL",
- "9 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "6 phase text/text NOT NULL DEFAULT 'sweep'::text",
+ "7 recheck ARRAY/_int4 NULL",
+ "8 found integer/int4 NOT NULL DEFAULT 0",
+ "9 cursor_page integer/int4 NULL",
+ "10 cursor_pipeline text/text NULL",
+ "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()"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -3124,11 +3145,14 @@
"minion_jobs.minion_queue_protocol": "CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON public.minion_jobs FOR EACH ROW EXECUTE FUNCTION enforce_minion_queue_protocol()",
"page_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"page_body_manifest.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_body_manifest FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
+ "page_body_manifest.page_body_manifest_derivation_scope_delete": "CREATE TRIGGER page_body_manifest_derivation_scope_delete AFTER DELETE ON public.page_body_manifest FOR EACH ROW WHEN (((old.gen_to IS NULL) AND (old.staging_id IS NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
+ "page_body_manifest.page_body_manifest_derivation_scope_retire": "CREATE TRIGGER page_body_manifest_derivation_scope_retire AFTER UPDATE OF gen_to ON public.page_body_manifest FOR EACH ROW WHEN (((old.gen_to IS NULL) AND (new.gen_to IS NOT NULL) AND (old.staging_id IS NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
"page_segment_derivations.page_segment_derivations_refuse_purging": "CREATE TRIGGER page_segment_derivations_refuse_purging BEFORE INSERT OR UPDATE OF output, receipt ON public.page_segment_derivations FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purging_derivation()",
"page_segment_texts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_segment_texts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"pages.bump_page_generation_clock_trg": "CREATE TRIGGER bump_page_generation_clock_trg AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH STATEMENT EXECUTE FUNCTION bump_page_generation_clock_fn()",
"pages.bump_page_generation_trg": "CREATE TRIGGER bump_page_generation_trg BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION bump_page_generation_fn()",
"pages.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
+ "pages.pages_derivation_scope_delete": "CREATE TRIGGER pages_derivation_scope_delete AFTER UPDATE OF deleted_at ON public.pages FOR EACH ROW WHEN (((old.deleted_at IS NULL) AND (new.deleted_at IS NOT NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
"pages.pages_forget_retrievals": "CREATE TRIGGER pages_forget_retrievals AFTER DELETE ON public.pages REFERENCING OLD TABLE AS gbrain_deleted_pages FOR EACH STATEMENT EXECUTE FUNCTION gbrain_forget_page_retrievals()",
"pages.pages_knowledge_revision": "CREATE TRIGGER pages_knowledge_revision BEFORE UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_advance_page_revision()",
"pages.pages_projection_queue": "CREATE TRIGGER pages_projection_queue AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_queue_page_projection()",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
index d791089e5d..4ce51b489c 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
@@ -191,6 +191,10 @@
"page_purges.page_purges_pkey": "p PRIMARY KEY (source_id, content_hash)",
"page_purges.page_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_retrievals.page_retrievals_pkey": "p PRIMARY KEY (page_id)",
+ "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_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_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))",
@@ -394,6 +398,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_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",
@@ -606,6 +611,9 @@
"page_retrievals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_segment_derivation_purge_pages": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_segment_derivation_purges": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -977,6 +985,7 @@
"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)",
"page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)",
"page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)",
+ "page_segment_derivation_purge_pages_pkey": "CREATE UNIQUE INDEX page_segment_derivation_purge_pages_pkey ON public.page_segment_derivation_purge_pages USING btree (request_id, page_id)",
"page_segment_derivation_purges_pkey": "CREATE UNIQUE INDEX page_segment_derivation_purges_pkey ON public.page_segment_derivation_purges USING btree (request_id)",
"page_segment_derivation_purges_source": "CREATE INDEX page_segment_derivation_purges_source ON public.page_segment_derivation_purges USING btree (source_id, created_at)",
"page_segment_derivations_pkey": "CREATE UNIQUE INDEX page_segment_derivations_pkey ON public.page_segment_derivations USING btree (page_id, pipeline, occurrence_id)",
@@ -2242,6 +2251,13 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_segment_derivation_purge_pages": {
+ "columns": [
+ "1 request_id uuid/uuid NOT NULL",
+ "2 page_id integer/int4 NOT NULL"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_segment_derivation_purges": {
"columns": [
"1 request_id uuid/uuid NOT NULL",
@@ -2249,10 +2265,15 @@
"3 needles ARRAY/_text NOT NULL",
"4 patterns ARRAY/_text NOT NULL",
"5 page_ids ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]",
- "6 cursor_page integer/int4 NULL",
- "7 cursor_pipeline text/text NULL",
- "8 cursor_occurrence bigint/int8 NULL",
- "9 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "6 phase text/text NOT NULL DEFAULT 'sweep'::text",
+ "7 recheck ARRAY/_int4 NULL",
+ "8 found integer/int4 NOT NULL DEFAULT 0",
+ "9 cursor_page integer/int4 NULL",
+ "10 cursor_pipeline text/text NULL",
+ "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()"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -3124,11 +3145,14 @@
"minion_jobs.minion_queue_protocol": "CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON public.minion_jobs FOR EACH ROW EXECUTE FUNCTION enforce_minion_queue_protocol()",
"page_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"page_body_manifest.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_body_manifest FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
+ "page_body_manifest.page_body_manifest_derivation_scope_delete": "CREATE TRIGGER page_body_manifest_derivation_scope_delete AFTER DELETE ON public.page_body_manifest FOR EACH ROW WHEN (((old.gen_to IS NULL) AND (old.staging_id IS NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
+ "page_body_manifest.page_body_manifest_derivation_scope_retire": "CREATE TRIGGER page_body_manifest_derivation_scope_retire AFTER UPDATE OF gen_to ON public.page_body_manifest FOR EACH ROW WHEN (((old.gen_to IS NULL) AND (new.gen_to IS NOT NULL) AND (old.staging_id IS NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
"page_segment_derivations.page_segment_derivations_refuse_purging": "CREATE TRIGGER page_segment_derivations_refuse_purging BEFORE INSERT OR UPDATE OF output, receipt ON public.page_segment_derivations FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purging_derivation()",
"page_segment_texts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_segment_texts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"pages.bump_page_generation_clock_trg": "CREATE TRIGGER bump_page_generation_clock_trg AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH STATEMENT EXECUTE FUNCTION bump_page_generation_clock_fn()",
"pages.bump_page_generation_trg": "CREATE TRIGGER bump_page_generation_trg BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION bump_page_generation_fn()",
"pages.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
+ "pages.pages_derivation_scope_delete": "CREATE TRIGGER pages_derivation_scope_delete AFTER UPDATE OF deleted_at ON public.pages FOR EACH ROW WHEN (((old.deleted_at IS NULL) AND (new.deleted_at IS NOT NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
"pages.pages_forget_retrievals": "CREATE TRIGGER pages_forget_retrievals AFTER DELETE ON public.pages REFERENCING OLD TABLE AS gbrain_deleted_pages FOR EACH STATEMENT EXECUTE FUNCTION gbrain_forget_page_retrievals()",
"pages.pages_knowledge_revision": "CREATE TRIGGER pages_knowledge_revision BEFORE UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_advance_page_revision()",
"pages.pages_projection_queue": "CREATE TRIGGER pages_projection_queue AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_queue_page_projection()",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
index cc1d5ad3d5..0b024b8e0e 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
@@ -191,6 +191,10 @@
"page_purges.page_purges_pkey": "p PRIMARY KEY (source_id, content_hash)",
"page_purges.page_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_retrievals.page_retrievals_pkey": "p PRIMARY KEY (page_id)",
+ "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_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_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))",
@@ -394,6 +398,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_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",
@@ -606,6 +611,9 @@
"page_retrievals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_segment_derivation_purge_pages": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_segment_derivation_purges": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -976,6 +984,7 @@
"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)",
"page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)",
"page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)",
+ "page_segment_derivation_purge_pages_pkey": "CREATE UNIQUE INDEX page_segment_derivation_purge_pages_pkey ON public.page_segment_derivation_purge_pages USING btree (request_id, page_id)",
"page_segment_derivation_purges_pkey": "CREATE UNIQUE INDEX page_segment_derivation_purges_pkey ON public.page_segment_derivation_purges USING btree (request_id)",
"page_segment_derivation_purges_source": "CREATE INDEX page_segment_derivation_purges_source ON public.page_segment_derivation_purges USING btree (source_id, created_at)",
"page_segment_derivations_pkey": "CREATE UNIQUE INDEX page_segment_derivations_pkey ON public.page_segment_derivations USING btree (page_id, pipeline, occurrence_id)",
@@ -2241,6 +2250,13 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_segment_derivation_purge_pages": {
+ "columns": [
+ "1 request_id uuid/uuid NOT NULL",
+ "2 page_id integer/int4 NOT NULL"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_segment_derivation_purges": {
"columns": [
"1 request_id uuid/uuid NOT NULL",
@@ -2248,10 +2264,15 @@
"3 needles ARRAY/_text NOT NULL",
"4 patterns ARRAY/_text NOT NULL",
"5 page_ids ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]",
- "6 cursor_page integer/int4 NULL",
- "7 cursor_pipeline text/text NULL",
- "8 cursor_occurrence bigint/int8 NULL",
- "9 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "6 phase text/text NOT NULL DEFAULT 'sweep'::text",
+ "7 recheck ARRAY/_int4 NULL",
+ "8 found integer/int4 NOT NULL DEFAULT 0",
+ "9 cursor_page integer/int4 NULL",
+ "10 cursor_pipeline text/text NULL",
+ "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()"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -3123,11 +3144,14 @@
"minion_jobs.minion_queue_protocol": "CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON public.minion_jobs FOR EACH ROW EXECUTE FUNCTION enforce_minion_queue_protocol()",
"page_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"page_body_manifest.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_body_manifest FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
+ "page_body_manifest.page_body_manifest_derivation_scope_delete": "CREATE TRIGGER page_body_manifest_derivation_scope_delete AFTER DELETE ON public.page_body_manifest FOR EACH ROW WHEN (((old.gen_to IS NULL) AND (old.staging_id IS NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
+ "page_body_manifest.page_body_manifest_derivation_scope_retire": "CREATE TRIGGER page_body_manifest_derivation_scope_retire AFTER UPDATE OF gen_to ON public.page_body_manifest FOR EACH ROW WHEN (((old.gen_to IS NULL) AND (new.gen_to IS NOT NULL) AND (old.staging_id IS NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
"page_segment_derivations.page_segment_derivations_refuse_purging": "CREATE TRIGGER page_segment_derivations_refuse_purging BEFORE INSERT OR UPDATE OF output, receipt ON public.page_segment_derivations FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purging_derivation()",
"page_segment_texts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_segment_texts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"pages.bump_page_generation_clock_trg": "CREATE TRIGGER bump_page_generation_clock_trg AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH STATEMENT EXECUTE FUNCTION bump_page_generation_clock_fn()",
"pages.bump_page_generation_trg": "CREATE TRIGGER bump_page_generation_trg BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION bump_page_generation_fn()",
"pages.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
+ "pages.pages_derivation_scope_delete": "CREATE TRIGGER pages_derivation_scope_delete AFTER UPDATE OF deleted_at ON public.pages FOR EACH ROW WHEN (((old.deleted_at IS NULL) AND (new.deleted_at IS NOT NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
"pages.pages_forget_retrievals": "CREATE TRIGGER pages_forget_retrievals AFTER DELETE ON public.pages REFERENCING OLD TABLE AS gbrain_deleted_pages FOR EACH STATEMENT EXECUTE FUNCTION gbrain_forget_page_retrievals()",
"pages.pages_knowledge_revision": "CREATE TRIGGER pages_knowledge_revision BEFORE UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_advance_page_revision()",
"pages.pages_projection_queue": "CREATE TRIGGER pages_projection_queue AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_queue_page_projection()",
diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.json
index 1df4aa97d6..876a7d39a3 100644
--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json
+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json
@@ -202,6 +202,10 @@
"page_purges.page_purges_pkey": "p PRIMARY KEY (source_id, content_hash)",
"page_purges.page_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_retrievals.page_retrievals_pkey": "p PRIMARY KEY (page_id)",
+ "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_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_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))",
@@ -403,6 +407,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_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",
@@ -623,6 +628,9 @@
"page_retrievals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_segment_derivation_purge_pages": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_segment_derivation_purges": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1005,6 +1013,7 @@
"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)",
"page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)",
"page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)",
+ "page_segment_derivation_purge_pages_pkey": "CREATE UNIQUE INDEX page_segment_derivation_purge_pages_pkey ON public.page_segment_derivation_purge_pages USING btree (request_id, page_id)",
"page_segment_derivation_purges_pkey": "CREATE UNIQUE INDEX page_segment_derivation_purges_pkey ON public.page_segment_derivation_purges USING btree (request_id)",
"page_segment_derivation_purges_source": "CREATE INDEX page_segment_derivation_purges_source ON public.page_segment_derivation_purges USING btree (source_id, created_at)",
"page_segment_derivations_pkey": "CREATE UNIQUE INDEX page_segment_derivations_pkey ON public.page_segment_derivations USING btree (page_id, pipeline, occurrence_id)",
@@ -2310,6 +2319,13 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_segment_derivation_purge_pages": {
+ "columns": [
+ "1 request_id uuid/uuid NOT NULL",
+ "2 page_id integer/int4 NOT NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_segment_derivation_purges": {
"columns": [
"1 request_id uuid/uuid NOT NULL",
@@ -2317,10 +2333,15 @@
"3 needles ARRAY/_text NOT NULL",
"4 patterns ARRAY/_text NOT NULL",
"5 page_ids ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]",
- "6 cursor_page integer/int4 NULL",
- "7 cursor_pipeline text/text NULL",
- "8 cursor_occurrence bigint/int8 NULL",
- "9 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "6 phase text/text NOT NULL DEFAULT 'sweep'::text",
+ "7 recheck ARRAY/_int4 NULL",
+ "8 found integer/int4 NOT NULL DEFAULT 0",
+ "9 cursor_page integer/int4 NULL",
+ "10 cursor_pipeline text/text NULL",
+ "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()"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -3186,11 +3207,14 @@
"minion_jobs.minion_job_notify": "CREATE TRIGGER minion_job_notify AFTER INSERT OR UPDATE OF status ON public.minion_jobs FOR EACH ROW EXECUTE FUNCTION notify_minion_job_change()",
"minion_jobs.minion_queue_protocol": "CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON public.minion_jobs FOR EACH ROW EXECUTE FUNCTION enforce_minion_queue_protocol()",
"page_body_manifest.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_body_manifest FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
+ "page_body_manifest.page_body_manifest_derivation_scope_delete": "CREATE TRIGGER page_body_manifest_derivation_scope_delete AFTER DELETE ON public.page_body_manifest FOR EACH ROW WHEN (((old.gen_to IS NULL) AND (old.staging_id IS NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
+ "page_body_manifest.page_body_manifest_derivation_scope_retire": "CREATE TRIGGER page_body_manifest_derivation_scope_retire AFTER UPDATE OF gen_to ON public.page_body_manifest FOR EACH ROW WHEN (((old.gen_to IS NULL) AND (new.gen_to IS NOT NULL) AND (old.staging_id IS NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
"page_segment_derivations.page_segment_derivations_refuse_purging": "CREATE TRIGGER page_segment_derivations_refuse_purging BEFORE INSERT OR UPDATE OF output, receipt ON public.page_segment_derivations FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purging_derivation()",
"page_segment_texts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_segment_texts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"pages.bump_page_generation_clock_trg": "CREATE TRIGGER bump_page_generation_clock_trg AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH STATEMENT EXECUTE FUNCTION bump_page_generation_clock_fn()",
"pages.bump_page_generation_trg": "CREATE TRIGGER bump_page_generation_trg BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION bump_page_generation_fn()",
"pages.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
+ "pages.pages_derivation_scope_delete": "CREATE TRIGGER pages_derivation_scope_delete AFTER UPDATE OF deleted_at ON public.pages FOR EACH ROW WHEN (((old.deleted_at IS NULL) AND (new.deleted_at IS NOT NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
"pages.pages_forget_retrievals": "CREATE TRIGGER pages_forget_retrievals AFTER DELETE ON public.pages REFERENCING OLD TABLE AS gbrain_deleted_pages FOR EACH STATEMENT EXECUTE FUNCTION gbrain_forget_page_retrievals()",
"pages.pages_knowledge_revision": "CREATE TRIGGER pages_knowledge_revision BEFORE UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_advance_page_revision()",
"pages.pages_projection_queue": "CREATE TRIGGER pages_projection_queue AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_queue_page_projection()",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 927e3c7473..d694b1ce30 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -268,6 +268,10 @@
"page_purges.page_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_purges.trust_generation_insert": "t TRIGGER DEFERRABLE INITIALLY DEFERRED",
"page_retrievals.page_retrievals_pkey": "p PRIMARY KEY (page_id)",
+ "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_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_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))",
@@ -535,6 +539,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_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",
@@ -821,6 +826,9 @@
"page_retrievals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_segment_derivation_purge_pages": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_segment_derivation_purges": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1326,6 +1334,7 @@
"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)",
"page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)",
"page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)",
+ "page_segment_derivation_purge_pages_pkey": "CREATE UNIQUE INDEX page_segment_derivation_purge_pages_pkey ON public.page_segment_derivation_purge_pages USING btree (request_id, page_id)",
"page_segment_derivation_purges_pkey": "CREATE UNIQUE INDEX page_segment_derivation_purges_pkey ON public.page_segment_derivation_purges USING btree (request_id)",
"page_segment_derivation_purges_source": "CREATE INDEX page_segment_derivation_purges_source ON public.page_segment_derivation_purges USING btree (source_id, created_at)",
"page_segment_derivations_pkey": "CREATE UNIQUE INDEX page_segment_derivations_pkey ON public.page_segment_derivations USING btree (page_id, pipeline, occurrence_id)",
@@ -2992,6 +3001,13 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "page_segment_derivation_purge_pages": {
+ "columns": [
+ "1 request_id uuid/uuid NOT NULL",
+ "2 page_id integer/int4 NOT NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_segment_derivation_purges": {
"columns": [
"1 request_id uuid/uuid NOT NULL",
@@ -2999,10 +3015,15 @@
"3 needles ARRAY/_text NOT NULL",
"4 patterns ARRAY/_text NOT NULL",
"5 page_ids ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]",
- "6 cursor_page integer/int4 NULL",
- "7 cursor_pipeline text/text NULL",
- "8 cursor_occurrence bigint/int8 NULL",
- "9 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "6 phase text/text NOT NULL DEFAULT 'sweep'::text",
+ "7 recheck ARRAY/_int4 NULL",
+ "8 found integer/int4 NOT NULL DEFAULT 0",
+ "9 cursor_page integer/int4 NULL",
+ "10 cursor_pipeline text/text NULL",
+ "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()"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -4144,6 +4165,8 @@
"oauth_clients.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.oauth_clients DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.min_trust IS DISTINCT FROM new.min_trust)) EXECUTE FUNCTION gbrain_bump_trust_generation()",
"page_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"page_body_manifest.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_body_manifest FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
+ "page_body_manifest.page_body_manifest_derivation_scope_delete": "CREATE TRIGGER page_body_manifest_derivation_scope_delete AFTER DELETE ON public.page_body_manifest FOR EACH ROW WHEN (((old.gen_to IS NULL) AND (old.staging_id IS NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
+ "page_body_manifest.page_body_manifest_derivation_scope_retire": "CREATE TRIGGER page_body_manifest_derivation_scope_retire AFTER UPDATE OF gen_to ON public.page_body_manifest FOR EACH ROW WHEN (((old.gen_to IS NULL) AND (new.gen_to IS NOT NULL) AND (old.staging_id IS NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
"page_purges.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.page_purges DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()",
"page_segment_derivations.page_segment_derivations_refuse_purging": "CREATE TRIGGER page_segment_derivations_refuse_purging BEFORE INSERT OR UPDATE OF output, receipt ON public.page_segment_derivations FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purging_derivation()",
"page_segment_texts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_segment_texts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
@@ -4153,6 +4176,7 @@
"pages.bump_page_generation_trg": "CREATE TRIGGER bump_page_generation_trg BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION bump_page_generation_fn()",
"pages.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"pages.pages_clear_atom_scan_state": "CREATE TRIGGER pages_clear_atom_scan_state AFTER UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_clear_atom_page_state()",
+ "pages.pages_derivation_scope_delete": "CREATE TRIGGER pages_derivation_scope_delete AFTER UPDATE OF deleted_at ON public.pages FOR EACH ROW WHEN (((old.deleted_at IS NULL) AND (new.deleted_at IS NOT NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
"pages.pages_forget_retrievals": "CREATE TRIGGER pages_forget_retrievals AFTER DELETE ON public.pages REFERENCING OLD TABLE AS gbrain_deleted_pages FOR EACH STATEMENT EXECUTE FUNCTION gbrain_forget_page_retrievals()",
"pages.pages_knowledge_revision": "CREATE TRIGGER pages_knowledge_revision BEFORE UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_advance_page_revision()",
"pages.pages_projection_queue": "CREATE TRIGGER pages_projection_queue AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_queue_page_projection()",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
index b2ccbd4156..42483c2612 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -268,6 +268,10 @@
"page_purges.page_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_purges.trust_generation_insert": "t TRIGGER DEFERRABLE INITIALLY DEFERRED",
"page_retrievals.page_retrievals_pkey": "p PRIMARY KEY (page_id)",
+ "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_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_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))",
@@ -535,6 +539,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_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",
@@ -821,6 +826,9 @@
"page_retrievals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_segment_derivation_purge_pages": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_segment_derivation_purges": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1326,6 +1334,7 @@
"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)",
"page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)",
"page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)",
+ "page_segment_derivation_purge_pages_pkey": "CREATE UNIQUE INDEX page_segment_derivation_purge_pages_pkey ON public.page_segment_derivation_purge_pages USING btree (request_id, page_id)",
"page_segment_derivation_purges_pkey": "CREATE UNIQUE INDEX page_segment_derivation_purges_pkey ON public.page_segment_derivation_purges USING btree (request_id)",
"page_segment_derivation_purges_source": "CREATE INDEX page_segment_derivation_purges_source ON public.page_segment_derivation_purges USING btree (source_id, created_at)",
"page_segment_derivations_pkey": "CREATE UNIQUE INDEX page_segment_derivations_pkey ON public.page_segment_derivations USING btree (page_id, pipeline, occurrence_id)",
@@ -2992,6 +3001,13 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "page_segment_derivation_purge_pages": {
+ "columns": [
+ "1 request_id uuid/uuid NOT NULL",
+ "2 page_id integer/int4 NOT NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_segment_derivation_purges": {
"columns": [
"1 request_id uuid/uuid NOT NULL",
@@ -2999,10 +3015,15 @@
"3 needles ARRAY/_text NOT NULL",
"4 patterns ARRAY/_text NOT NULL",
"5 page_ids ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]",
- "6 cursor_page integer/int4 NULL",
- "7 cursor_pipeline text/text NULL",
- "8 cursor_occurrence bigint/int8 NULL",
- "9 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "6 phase text/text NOT NULL DEFAULT 'sweep'::text",
+ "7 recheck ARRAY/_int4 NULL",
+ "8 found integer/int4 NOT NULL DEFAULT 0",
+ "9 cursor_page integer/int4 NULL",
+ "10 cursor_pipeline text/text NULL",
+ "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()"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -4144,6 +4165,8 @@
"oauth_clients.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.oauth_clients DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.min_trust IS DISTINCT FROM new.min_trust)) EXECUTE FUNCTION gbrain_bump_trust_generation()",
"page_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"page_body_manifest.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_body_manifest FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
+ "page_body_manifest.page_body_manifest_derivation_scope_delete": "CREATE TRIGGER page_body_manifest_derivation_scope_delete AFTER DELETE ON public.page_body_manifest FOR EACH ROW WHEN (((old.gen_to IS NULL) AND (old.staging_id IS NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
+ "page_body_manifest.page_body_manifest_derivation_scope_retire": "CREATE TRIGGER page_body_manifest_derivation_scope_retire AFTER UPDATE OF gen_to ON public.page_body_manifest FOR EACH ROW WHEN (((old.gen_to IS NULL) AND (new.gen_to IS NOT NULL) AND (old.staging_id IS NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
"page_purges.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.page_purges DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()",
"page_segment_derivations.page_segment_derivations_refuse_purging": "CREATE TRIGGER page_segment_derivations_refuse_purging BEFORE INSERT OR UPDATE OF output, receipt ON public.page_segment_derivations FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purging_derivation()",
"page_segment_texts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_segment_texts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
@@ -4153,6 +4176,7 @@
"pages.bump_page_generation_trg": "CREATE TRIGGER bump_page_generation_trg BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION bump_page_generation_fn()",
"pages.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"pages.pages_clear_atom_scan_state": "CREATE TRIGGER pages_clear_atom_scan_state AFTER UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_clear_atom_page_state()",
+ "pages.pages_derivation_scope_delete": "CREATE TRIGGER pages_derivation_scope_delete AFTER UPDATE OF deleted_at ON public.pages FOR EACH ROW WHEN (((old.deleted_at IS NULL) AND (new.deleted_at IS NOT NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
"pages.pages_forget_retrievals": "CREATE TRIGGER pages_forget_retrievals AFTER DELETE ON public.pages REFERENCING OLD TABLE AS gbrain_deleted_pages FOR EACH STATEMENT EXECUTE FUNCTION gbrain_forget_page_retrievals()",
"pages.pages_knowledge_revision": "CREATE TRIGGER pages_knowledge_revision BEFORE UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_advance_page_revision()",
"pages.pages_projection_queue": "CREATE TRIGGER pages_projection_queue AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_queue_page_projection()",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
index e42768b33b..27a554598a 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -268,6 +268,10 @@
"page_purges.page_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_purges.trust_generation_insert": "t TRIGGER DEFERRABLE INITIALLY DEFERRED",
"page_retrievals.page_retrievals_pkey": "p PRIMARY KEY (page_id)",
+ "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_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_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))",
@@ -535,6 +539,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_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",
@@ -821,6 +826,9 @@
"page_retrievals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_segment_derivation_purge_pages": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_segment_derivation_purges": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1322,6 +1330,7 @@
"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)",
"page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)",
"page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)",
+ "page_segment_derivation_purge_pages_pkey": "CREATE UNIQUE INDEX page_segment_derivation_purge_pages_pkey ON public.page_segment_derivation_purge_pages USING btree (request_id, page_id)",
"page_segment_derivation_purges_pkey": "CREATE UNIQUE INDEX page_segment_derivation_purges_pkey ON public.page_segment_derivation_purges USING btree (request_id)",
"page_segment_derivation_purges_source": "CREATE INDEX page_segment_derivation_purges_source ON public.page_segment_derivation_purges USING btree (source_id, created_at)",
"page_segment_derivations_pkey": "CREATE UNIQUE INDEX page_segment_derivations_pkey ON public.page_segment_derivations USING btree (page_id, pipeline, occurrence_id)",
@@ -2988,6 +2997,13 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "page_segment_derivation_purge_pages": {
+ "columns": [
+ "1 request_id uuid/uuid NOT NULL",
+ "2 page_id integer/int4 NOT NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_segment_derivation_purges": {
"columns": [
"1 request_id uuid/uuid NOT NULL",
@@ -2995,10 +3011,15 @@
"3 needles ARRAY/_text NOT NULL",
"4 patterns ARRAY/_text NOT NULL",
"5 page_ids ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]",
- "6 cursor_page integer/int4 NULL",
- "7 cursor_pipeline text/text NULL",
- "8 cursor_occurrence bigint/int8 NULL",
- "9 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "6 phase text/text NOT NULL DEFAULT 'sweep'::text",
+ "7 recheck ARRAY/_int4 NULL",
+ "8 found integer/int4 NOT NULL DEFAULT 0",
+ "9 cursor_page integer/int4 NULL",
+ "10 cursor_pipeline text/text NULL",
+ "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()"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -4140,6 +4161,8 @@
"oauth_clients.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.oauth_clients DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.min_trust IS DISTINCT FROM new.min_trust)) EXECUTE FUNCTION gbrain_bump_trust_generation()",
"page_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"page_body_manifest.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_body_manifest FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
+ "page_body_manifest.page_body_manifest_derivation_scope_delete": "CREATE TRIGGER page_body_manifest_derivation_scope_delete AFTER DELETE ON public.page_body_manifest FOR EACH ROW WHEN (((old.gen_to IS NULL) AND (old.staging_id IS NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
+ "page_body_manifest.page_body_manifest_derivation_scope_retire": "CREATE TRIGGER page_body_manifest_derivation_scope_retire AFTER UPDATE OF gen_to ON public.page_body_manifest FOR EACH ROW WHEN (((old.gen_to IS NULL) AND (new.gen_to IS NOT NULL) AND (old.staging_id IS NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
"page_purges.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.page_purges DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()",
"page_segment_derivations.page_segment_derivations_refuse_purging": "CREATE TRIGGER page_segment_derivations_refuse_purging BEFORE INSERT OR UPDATE OF output, receipt ON public.page_segment_derivations FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purging_derivation()",
"page_segment_texts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_segment_texts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
@@ -4149,6 +4172,7 @@
"pages.bump_page_generation_trg": "CREATE TRIGGER bump_page_generation_trg BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION bump_page_generation_fn()",
"pages.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"pages.pages_clear_atom_scan_state": "CREATE TRIGGER pages_clear_atom_scan_state AFTER UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_clear_atom_page_state()",
+ "pages.pages_derivation_scope_delete": "CREATE TRIGGER pages_derivation_scope_delete AFTER UPDATE OF deleted_at ON public.pages FOR EACH ROW WHEN (((old.deleted_at IS NULL) AND (new.deleted_at IS NOT NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
"pages.pages_forget_retrievals": "CREATE TRIGGER pages_forget_retrievals AFTER DELETE ON public.pages REFERENCING OLD TABLE AS gbrain_deleted_pages FOR EACH STATEMENT EXECUTE FUNCTION gbrain_forget_page_retrievals()",
"pages.pages_knowledge_revision": "CREATE TRIGGER pages_knowledge_revision BEFORE UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_advance_page_revision()",
"pages.pages_projection_queue": "CREATE TRIGGER pages_projection_queue AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_queue_page_projection()",
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index 94efec5f1b..bcebdf28e1 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 254763,
- "stdoutSha256": "f6d6005ad68241f8e95fac4a2f61f62b074fd5a0a76206e8e410a02d425692df",
+ "stdoutBytes": 255009,
+ "stdoutSha256": "9aafe2eedddce06f81e84e22147fc7ac51db5459e9c5d20e1b297cb73c2daac2",
"toolNames": [
"remember",
"entity",
@@ -6700,6 +6700,7 @@
"parameters": {
"all_subjects": "boolean?",
"confirm": "string?",
+ "continue": "boolean?",
"dry_run": "boolean?",
"expected_revision": "string?",
"id": "number?",
@@ -6721,6 +6722,10 @@
"description": "The confirmation token from the dry run (first 8 hex of the claim fingerprint).",
"type": "string"
},
+ "continue": {
+ "description": "With status: first continue the purge's sweep of stored derivation results (derivation_sweep pending or stalled), then report.",
+ "type": "boolean"
+ },
"dry_run": {
"description": "Return the receipt with would-remove counts and the confirmation token; changes nothing.",
"type": "boolean"
diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
index 7d30ab18af..0701d9bb9a 100644
--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
@@ -1089,7 +1089,7 @@
{
"category": "ops",
"elapsed_ms": "<volatile>",
- "message": "RLS enabled on 151/151 public tables",
+ "message": "RLS enabled on 155/155 public tables",
"name": "rls",
"status": "ok"
},
@@ -1103,14 +1103,14 @@
{
"category": "meta",
"elapsed_ms": "<volatile>",
- "message": "1302 column(s) verified against live schema",
+ "message": "1335 column(s) verified against live schema",
"name": "schema_columns",
"status": "ok"
},
{
"category": "meta",
"elapsed_ms": "<volatile>",
- "message": "All 151 table(s) the applied migrations create exist.",
+ "message": "All 155 table(s) the applied migrations create exist.",
"name": "schema_missing_tables",
"status": "ok"
},
@@ -3347,6 +3347,16 @@
"name": "extraction_input_truncated",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "models": []
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No segmented page derivation is held back by a model without a price.",
+ "name": "derivation_unpriced_model",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
@@ -5600,7 +5610,7 @@
{
"category": "ops",
"elapsed_ms": "<volatile>",
- "message": "RLS enabled on 151/151 public tables",
+ "message": "RLS enabled on 155/155 public tables",
"name": "rls",
"status": "ok"
},
@@ -5614,14 +5624,14 @@
{
"category": "meta",
"elapsed_ms": "<volatile>",
- "message": "1302 column(s) verified against live schema",
+ "message": "1335 column(s) verified against live schema",
"name": "schema_columns",
"status": "ok"
},
{
"category": "meta",
"elapsed_ms": "<volatile>",
- "message": "All 151 table(s) the applied migrations create exist.",
+ "message": "All 155 table(s) the applied migrations create exist.",
"name": "schema_missing_tables",
"status": "ok"
},
@@ -7858,6 +7868,16 @@
"name": "extraction_input_truncated",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "models": []
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No segmented page derivation is held back by a model without a price.",
+ "name": "derivation_unpriced_model",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 0c642b1259..8ccdd54f11 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -949,14 +949,14 @@
{
"category": "meta",
"elapsed_ms": "<volatile>",
- "message": "1307 column(s) verified against live schema",
+ "message": "1329 column(s) verified against live schema",
"name": "schema_columns",
"status": "ok"
},
{
"category": "meta",
"elapsed_ms": "<volatile>",
- "message": "All 152 table(s) the applied migrations create exist.",
+ "message": "All 156 table(s) the applied migrations create exist.",
"name": "schema_missing_tables",
"status": "ok"
},
@@ -2862,6 +2862,16 @@
"name": "extraction_input_truncated",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "models": []
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No segmented page derivation is held back by a model without a price.",
+ "name": "derivation_unpriced_model",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 6ddfd91f86..09f7dafe58 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -996,14 +996,14 @@
{
"category": "meta",
"elapsed_ms": "<volatile>",
- "message": "1307 column(s) verified against live schema",
+ "message": "1329 column(s) verified against live schema",
"name": "schema_columns",
"status": "ok"
},
{
"category": "meta",
"elapsed_ms": "<volatile>",
- "message": "All 152 table(s) the applied migrations create exist.",
+ "message": "All 156 table(s) the applied migrations create exist.",
"name": "schema_missing_tables",
"status": "ok"
},
@@ -2906,6 +2906,16 @@
"name": "extraction_input_truncated",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "models": []
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No segmented page derivation is held back by a model without a price.",
+ "name": "derivation_unpriced_model",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 850fc01148..5ac110d6e8 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -978,7 +978,7 @@
{
"category": "ops",
"elapsed_ms": "<volatile>",
- "message": "RLS enabled on 154/154 public tables",
+ "message": "RLS enabled on 155/155 public tables",
"name": "rls",
"status": "ok"
},
@@ -992,14 +992,14 @@
{
"category": "meta",
"elapsed_ms": "<volatile>",
- "message": "1328 column(s) verified against live schema",
+ "message": "1335 column(s) verified against live schema",
"name": "schema_columns",
"status": "ok"
},
{
"category": "meta",
"elapsed_ms": "<volatile>",
- "message": "All 153 table(s) the applied migrations create exist.",
+ "message": "All 155 table(s) the applied migrations create exist.",
"name": "schema_missing_tables",
"status": "ok"
},
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 41e2a621dc..068c8fd2ad 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": 4350,
- "sha256": "6c01a9815f271235fd70c6214c315eda0035e9bacfe814dee98b04f9de00e56a"
+ "length": 6369,
+ "sha256": "1334aad47cf3eb04efe03ab06d8c68f924ec1a389a158d63d7cd8168046c0dda"
},
"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.json
index 89808f4176..144e9dcee8 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -264,6 +264,10 @@
"page_purges.page_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_purges.trust_generation_insert": "t TRIGGER DEFERRABLE INITIALLY DEFERRED",
"page_retrievals.page_retrievals_pkey": "p PRIMARY KEY (page_id)",
+ "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_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_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))",
@@ -532,6 +536,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_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",
@@ -814,6 +819,9 @@
"page_retrievals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_segment_derivation_purge_pages": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_segment_derivation_purges": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1322,6 +1330,7 @@
"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)",
"page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)",
"page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)",
+ "page_segment_derivation_purge_pages_pkey": "CREATE UNIQUE INDEX page_segment_derivation_purge_pages_pkey ON public.page_segment_derivation_purge_pages USING btree (request_id, page_id)",
"page_segment_derivation_purges_pkey": "CREATE UNIQUE INDEX page_segment_derivation_purges_pkey ON public.page_segment_derivation_purges USING btree (request_id)",
"page_segment_derivation_purges_source": "CREATE INDEX page_segment_derivation_purges_source ON public.page_segment_derivation_purges USING btree (source_id, created_at)",
"page_segment_derivations_pkey": "CREATE UNIQUE INDEX page_segment_derivations_pkey ON public.page_segment_derivations USING btree (page_id, pipeline, occurrence_id)",
@@ -2980,6 +2989,13 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_segment_derivation_purge_pages": {
+ "columns": [
+ "1 request_id uuid/uuid NOT NULL",
+ "2 page_id integer/int4 NOT NULL"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_segment_derivation_purges": {
"columns": [
"1 request_id uuid/uuid NOT NULL",
@@ -2987,10 +3003,15 @@
"3 needles ARRAY/_text NOT NULL",
"4 patterns ARRAY/_text NOT NULL",
"5 page_ids ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]",
- "6 cursor_page integer/int4 NULL",
- "7 cursor_pipeline text/text NULL",
- "8 cursor_occurrence bigint/int8 NULL",
- "9 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "6 phase text/text NOT NULL DEFAULT 'sweep'::text",
+ "7 recheck ARRAY/_int4 NULL",
+ "8 found integer/int4 NOT NULL DEFAULT 0",
+ "9 cursor_page integer/int4 NULL",
+ "10 cursor_pipeline text/text NULL",
+ "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()"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -4157,6 +4178,8 @@
"oauth_clients.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.oauth_clients DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.min_trust IS DISTINCT FROM new.min_trust)) EXECUTE FUNCTION gbrain_bump_trust_generation()",
"page_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"page_body_manifest.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_body_manifest FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
+ "page_body_manifest.page_body_manifest_derivation_scope_delete": "CREATE TRIGGER page_body_manifest_derivation_scope_delete AFTER DELETE ON public.page_body_manifest FOR EACH ROW WHEN (((old.gen_to IS NULL) AND (old.staging_id IS NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
+ "page_body_manifest.page_body_manifest_derivation_scope_retire": "CREATE TRIGGER page_body_manifest_derivation_scope_retire AFTER UPDATE OF gen_to ON public.page_body_manifest FOR EACH ROW WHEN (((old.gen_to IS NULL) AND (new.gen_to IS NOT NULL) AND (old.staging_id IS NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
"page_purges.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.page_purges DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()",
"page_segment_derivations.page_segment_derivations_refuse_purging": "CREATE TRIGGER page_segment_derivations_refuse_purging BEFORE INSERT OR UPDATE OF output, receipt ON public.page_segment_derivations FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purging_derivation()",
"page_segment_texts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_segment_texts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
@@ -4166,6 +4189,7 @@
"pages.bump_page_generation_trg": "CREATE TRIGGER bump_page_generation_trg BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION bump_page_generation_fn()",
"pages.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"pages.pages_clear_atom_scan_state": "CREATE TRIGGER pages_clear_atom_scan_state AFTER UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_clear_atom_page_state()",
+ "pages.pages_derivation_scope_delete": "CREATE TRIGGER pages_derivation_scope_delete AFTER UPDATE OF deleted_at ON public.pages FOR EACH ROW WHEN (((old.deleted_at IS NULL) AND (new.deleted_at IS NOT NULL))) EXECUTE FUNCTION gbrain_mark_derivation_scope_entry()",
"pages.pages_forget_retrievals": "CREATE TRIGGER pages_forget_retrievals AFTER DELETE ON public.pages REFERENCING OLD TABLE AS gbrain_deleted_pages FOR EACH STATEMENT EXECUTE FUNCTION gbrain_forget_page_retrievals()",
"pages.pages_knowledge_revision": "CREATE TRIGGER pages_knowledge_revision BEFORE UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_advance_page_revision()",
"pages.pages_projection_queue": "CREATE TRIGGER pages_projection_queue AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_queue_page_projection()",
diff --git a/test/fixtures/goldens/pglite-upgrade-replay/repeat-boot-recreated-objects.json b/test/fixtures/goldens/pglite-upgrade-replay/repeat-boot-recreated-objects.json
index 08cf91cd40..ca9607c45f 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/repeat-boot-recreated-objects.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/repeat-boot-recreated-objects.json
@@ -4,11 +4,14 @@
"trg:minion_jobs.minion_queue_protocol",
"trg:page_aliases.managed_writer_guard",
"trg:page_body_manifest.managed_writer_guard",
+ "trg:page_body_manifest.page_body_manifest_derivation_scope_delete",
+ "trg:page_body_manifest.page_body_manifest_derivation_scope_retire",
"trg:page_segment_derivations.page_segment_derivations_refuse_purging",
"trg:page_segment_texts.managed_writer_guard",
"trg:pages.bump_page_generation_clock_trg",
"trg:pages.bump_page_generation_trg",
"trg:pages.managed_writer_guard",
+ "trg:pages.pages_derivation_scope_delete",
"trg:pages.pages_forget_retrievals",
"trg:pages.pages_knowledge_revision",
"trg:pages.pages_projection_queue",
diff --git a/test/graduation-inventory.test.ts b/test/graduation-inventory.test.ts
index 9ca39bbb35..3f07ec2f79 100644
--- a/test/graduation-inventory.test.ts
+++ b/test/graduation-inventory.test.ts
@@ -60,7 +60,7 @@ describe('graduation inventory', () => {
expect(new Set(names).size).toBe(names.length);
const counts: Record<string, number> = {};
for (const e of GRADUATION_INVENTORY.entries) counts[e.class] = (counts[e.class] ?? 0) + 1;
- expect(counts).toEqual({ carry: 139, rebind: 2, rebuild: 3, discard: 9, schema_owned: 4 });
+ expect(counts).toEqual({ carry: 140, rebind: 2, rebuild: 3, discard: 9, schema_owned: 4 });
for (const e of GRADUATION_INVENTORY.entries) {
expect({ relation: e.relation, reason: e.reason.length > 5, present: e.engines.pglite || e.engines.postgres })
.toEqual({ relation: e.relation, reason: true, present: true });
diff --git a/test/helpers/derivation-purge-cases.ts b/test/helpers/derivation-purge-cases.ts
index 25d0ce001b..1c1f175b96 100644
--- a/test/helpers/derivation-purge-cases.ts
+++ b/test/helpers/derivation-purge-cases.ts
@@ -16,6 +16,10 @@ import { __setAfterDerivationSweepBatchForTests, __setBeforeDerivationWriteForTe
import { installFaultHook } from '../../src/core/persistence/fault-points.ts';
import { incrementalFactsFenceView, segmentedFactsFenceView } from '../../src/core/page-body/segment-facts.ts';
import { forgetFactInFence } from '../../src/core/facts/forget.ts';
+import { PAGE_EMBED_CAP_KEY } from '../../src/core/page-embedding-budget.ts';
+import { PAGE_DERIVATION_CAP_KEY } from '../../src/core/page-spend.ts';
+import type { ChatOpts, ChatResult } from '../../src/core/ai/gateway.ts';
+import { runPhaseExtractAtoms } from '../../src/core/cycle/extract-atoms.ts';
import { deriveAll, KINDS, liveOccurrences, resetDeriveWork, storedPage } from './derivation-equivalence-cases.ts';
import { conversationBody } from './conversation-page.ts';
import { openAppendBrain, type AppendBrain } from './append-brain.ts';
@@ -357,11 +361,13 @@ export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): void
last = await brain.call('purge_fact', params);
calls++;
}
- const sweeps = sweepStatements();
+ const sweeps = sweepStatements(), verifies = derivationSweepStatements.filter(s => s.phase === 'verify');
expect(calls).toBeGreaterThan(2);
- expect(sweeps.length).toBe(calls);
+ expect(sweeps.length + verifies.length).toBe(calls);
expect(sweeps.slice(0, -1).every(s => s.scanned === batch) && sweeps.at(-1)!.scanned < batch).toBe(true);
expect(sweeps.reduce((n, s) => n + s.scanned, 0)).toBe(await sourceRows() + derivationSweepWork.reduce((n, w) => n + w.deleted, 0));
+ expect(verifies.slice(0, -1).every(s => s.scanned === batch) && verifies.at(-1)!.scanned < batch).toBe(true);
+ expect(verifies.reduce((n, s) => n + s.scanned, 0)).toBe(await sourceRows());
expect({ replayed: last.body.replayed, sweep: last.body.derivation_sweep }).toEqual({ replayed: true, sweep: undefined });
} finally {
__setDerivationSweepLimitsForTests(null);
@@ -414,7 +420,7 @@ export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): void
results.push({ isError: res.isError, code: res.body.error ?? res.body.code ?? null });
});
let receipt: Record<string, any>, statements = 0;
- try { receipt = await purge(id); statements = sweepStatements().length; } finally {
+ try { receipt = await purge(id); statements = derivationSweepStatements.filter(s => s.phase !== 'probe').length; } finally {
__setAfterDerivationSweepBatchForTests(null);
__setDerivationSweepLimitsForTests(null);
__setDerivationSweepWorkForTests(false);
@@ -441,12 +447,13 @@ export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): void
__setDerivationSweepWorkForTests(true);
const b = await purge(idB);
const sweeps = sweepStatements();
- expect({ statements: sweeps.length, short: sweeps[0]!.scanned < 1_000_000, sweep: b.derivation_sweep, recorded: await sweepsRecorded() })
- .toEqual({ statements: 1, short: true, sweep: 'pending', recorded: 1 });
- expect(await exactHolders(brain.engine, rows, claimA)).toEqual([]);
+ expect({ statements: derivationSweepStatements.filter(s => s.phase !== 'probe').length, short: sweeps[0]!.scanned < 1_000_000, sweep: b.derivation_sweep,
+ recorded: await sweepsRecorded() }).toEqual({ statements: 1, short: true, sweep: 'pending', recorded: 2 });
+ expect(await exactHolders(brain.engine, rows, claimA)).toHaveLength(1);
+ __setDerivationSweepLimitsForTests(null);
const replay = await brain.call('purge_fact', a);
- expect({ replayed: replay.body.replayed, sweep: replay.body.derivation_sweep, statements: sweepStatements().length, recorded: await sweepsRecorded() })
- .toEqual({ replayed: true, sweep: undefined, statements: 2, recorded: 0 });
+ expect({ replayed: replay.body.replayed, sweep: replay.body.derivation_sweep, recorded: await sweepsRecorded() })
+ .toEqual({ replayed: true, sweep: undefined, recorded: 0 });
} finally {
__setDerivationSweepLimitsForTests(null);
__setDerivationSweepWorkForTests(false);
@@ -479,5 +486,133 @@ export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): void
__setDerivationSweepWorkForTests(false);
}
}, 600_000);
+
+ /** An inline page whose `n` derivation rows (no live segment backs them) each state `claim` inside about `bytes` of text. */
+ const bigRowsPage = async (slug: string, claim: string, n: number, bytes: number) => {
+ await brain.engine.putPage(slug, { type: 'note', title: 'Big Rows', compiled_truth: 'Big rows fixture.', timeline: '', frontmatter: {} }, { sourceId: SOURCE });
+ const [row] = await brain.engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [SOURCE, slug]);
+ await brain.engine.executeRaw(`INSERT INTO page_segment_derivations (page_id, pipeline, occurrence_id, pipeline_version, segment_sha256, context_hash, state, output, receipt)
+ SELECT $1, 'links', g, 1, decode(repeat('00', 32), 'hex'), decode(repeat('00', 32), 'hex'), 'done',
+ jsonb_build_object('candidates', jsonb_build_array(jsonb_build_object('context', repeat('journal line text ', $4::int / 18) || ' Note: ' || $3 || ' today'))), NULL
+ FROM generate_series(1, $2::int) g `, [Number(row!.id), n, claim, bytes]);
+ expect(await exactHolders(brain.engine, Number(row!.id), claim)).toHaveLength(n);
+ return Number(row!.id);
+ };
+ const timeout = () => Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' });
+
+ test('a sweep whose batch outruns its statement budget halves the batch until it fits and completes (30 rows of about 730 KB)', async () => {
+ const claim = 'Purge Example kiln code is 4410', fits = 8;
+ const rows = await bigRowsPage('notes/sweep-big-rows', claim, 30, 730_000);
+ const id = await seed('notes/sweep-big-purge', claim);
+ const rounds: number[] = [];
+ installFaultHook((point, detail) => {
+ if (point !== 'purge:derivation_batch') return;
+ rounds.push(Number(detail.round));
+ if (Number(detail.round) > fits) throw timeout();
+ });
+ let receipt: Record<string, any>;
+ try { receipt = await purge(id); } finally { installFaultHook(undefined); }
+ expect(rounds.slice(0, 7)).toEqual([500, 250, 125, 62, 31, 15, 7]);
+ expect(rounds.slice(7).every(r => r <= 7)).toBe(true);
+ expect({ rows: await exactHolders(brain.engine, rows, claim), sweep: receipt!.derivation_sweep, completion: receipt!.completion, recorded: await sweepsRecorded() })
+ .toEqual({ rows: [], sweep: undefined, completion: receipt!.completion === 'complete' ? 'complete' : 'committed', recorded: 0 });
+ complete(receipt!);
+ }, 600_000);
+
+ test('a row that alone outruns the budget stalls its sweep without blocking a later purge, and --status --continue finishes it once it fits', async () => {
+ const claimA = 'Purge Example furnace code is 5521', claimB = 'Purge Example rarely seen chimney code 9930';
+ const rowsA = await bigRowsPage('notes/sweep-stall-rows', claimA, 30, 730_000);
+ const a = await confirmed(await seed('notes/sweep-stall-a', claimA));
+ const idB = await seed('notes/sweep-stall-b', claimB);
+ let stalledId: string | undefined, blocked = true, unread = 0;
+ installFaultHook((point, detail) => {
+ if (point !== 'purge:derivation_batch' && point !== 'purge:derivation_unread') return;
+ stalledId ??= detail.requestId;
+ if (!blocked || detail.requestId !== stalledId) return;
+ if (point === 'purge:derivation_unread') unread++;
+ throw timeout();
+ });
+ try {
+ const first = await brain.call('purge_fact', a);
+ expect({ state: first.body.state, completion: first.body.completion, exit: first.body.exit_code, sweep: first.body.derivation_sweep, unread })
+ .toEqual({ state: 'committed', completion: 'incomplete', exit: 75, sweep: 'stalled', unread: 1 });
+ expect((first.body.next as string[]).some(n => n.includes(`gbrain forget --purge --status --request-id ${a.request_id} --continue`))).toBe(true);
+ const b = await purge(idB);
+ expect({ completion: b.completion, sweep: b.derivation_sweep }).toEqual({ completion: b.completion === 'complete' ? 'complete' : 'committed', sweep: undefined });
+ complete(b);
+ const still = await brain.call('purge_fact', { status: true, request_id: a.request_id });
+ expect({ sweep: still.body.derivation_sweep, completion: still.body.completion }).toEqual({ sweep: 'stalled', completion: 'incomplete' });
+ expect((await exactHolders(brain.engine, rowsA, claimA)).length).toBeGreaterThan(0);
+ blocked = false;
+ const resumed = await brain.call('purge_fact', { status: true, request_id: a.request_id, continue: true });
+ expect({ sweep: resumed.body.derivation_sweep, completion: resumed.body.completion === 'incomplete' ? 'incomplete' : 'done' }).toEqual({ sweep: undefined, completion: 'done' });
+ } finally { installFaultHook(undefined); }
+ expect({ rows: await exactHolders(brain.engine, rowsA, claimA), recorded: await sweepsRecorded() }).toEqual({ rows: [], recorded: 0 });
+ }, 600_000);
+
+ test('a row that enters the sweep\'s scope behind its cursor (its occurrence retired during the last walk) is deleted before the sweep ends', async () => {
+ const claim = 'Purge Example cistern code is 6077', planted = 'Alice Example said Purge Example cistern code is 6077';
+ await brain.seed('notes/sweep-enter-live', prosePage(planted, 66));
+ const live = await storedPage(brain.engine, 'notes/sweep-enter-live');
+ await deriveAll(brain.engine, live);
+ const held = await exactHolders(brain.engine, live.id, planted);
+ expect(held.length).toBeGreaterThan(0);
+ await candidateRowsPage('notes/sweep-enter-rows', claim, 300, 0);
+ const id = await seed('notes/sweep-enter-purge', claim);
+ let appended = false;
+ __setDerivationSweepLimitsForTests({ batchRows: 50 });
+ __setAfterDerivationSweepBatchForTests(async () => {
+ if (appended) return;
+ const [record] = await brain.engine.executeRaw<{ cursor_page: number | null; phase: string | null }>(
+ "SELECT cursor_page, to_jsonb(x)->>'phase' AS phase FROM page_segment_derivation_purges x");
+ if (!record || record.cursor_page === null || Number(record.cursor_page) <= live.id || (record.phase !== null && record.phase !== 'verify')) return;
+ appended = true;
+ const res = await brain.call('append_page', { slug: 'notes/sweep-enter-live', text: 'Appended note: nothing more.\n', region: 'truth', request_id: randomUUID() });
+ expect(res).toMatchObject({ isError: false });
+ });
+ let receipt: Record<string, any>;
+ try { receipt = await purge(id); } finally {
+ __setAfterDerivationSweepBatchForTests(null);
+ __setDerivationSweepLimitsForTests(null);
+ }
+ expect(appended).toBe(true);
+ const occurrences = await liveOccurrences(brain.engine, live.id);
+ expect(held.filter(row => occurrences.has(row.occurrence_id))).toEqual([]);
+ expect({ rows: await exactHolders(brain.engine, live.id, planted), sweep: receipt!.derivation_sweep, recorded: await sweepsRecorded() })
+ .toEqual({ rows: [], sweep: undefined, recorded: 0 });
+ complete(receipt!);
+ }, 600_000);
+
+ test('a paid pipeline makes no call on a page a pending purge sweep covers, so a second run repeats no paid window', async () => {
+ const slug = 'notes/sweep-atoms-purge', claim = 'Purge Example oven code is 3184';
+ await candidateRowsPage('notes/sweep-atoms-rows', claim, 300, 0);
+ await brain.seed(slug, purgePage(claim).replace('type: person', 'type: meeting'));
+ await runExtractFacts(brain.engine, { slugs: [slug] });
+ const [fact] = await brain.engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND fact=$3 AND expired_at IS NULL', [SOURCE, slug, claim]);
+ const params = await confirmed(Number(fact!.id));
+ await brain.engine.setConfig(PAGE_EMBED_CAP_KEY, 'off');
+ await brain.engine.setConfig(PAGE_DERIVATION_CAP_KEY, 'off');
+ let prompts: string[] = [];
+ const chat = async (o: ChatOpts): Promise<ChatResult> => {
+ prompts.push(o.messages.map(m => typeof m.content === 'string' ? m.content : JSON.stringify(m.content)).join('\n'));
+ const text = JSON.stringify({ atoms: [{ title: `${claim} ${prompts.length}`, atom_type: 'insight', body: `Body: ${claim}.`, source_quote: null, lesson: null, concepts: null,
+ virality_score: null, emotional_register: null }] });
+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end', model: 'test:stub', providerId: 'test',
+ usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 } };
+ };
+ const run = async () => {
+ prompts = [];
+ await runPhaseExtractAtoms(brain.engine, { sourceId: SOURCE, _chat: chat, _transcripts: [] });
+ return prompts.filter(p => p.includes('Source: ' + slug + '\n')).length;
+ };
+ __setDerivationSweepLimitsForTests({ batchRows: 50, totalMs: 0 });
+ try {
+ expect((await brain.call('purge_fact', params)).body.derivation_sweep).toBe('pending');
+ expect({ first: await run(), second: await run() }).toEqual({ first: 0, second: 0 });
+ } finally { __setDerivationSweepLimitsForTests(null); }
+ const resumed = await brain.call('purge_fact', { status: true, request_id: params.request_id, continue: true });
+ expect(resumed.body.derivation_sweep).toBeUndefined();
+ expect(await run()).toBeGreaterThan(0);
+ }, 600_000);
});
}