Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(purge): snapshots carry a '*' purge marker and resolve global tombstones lazily per overlaid fence (GBRA-69)

garrytanf3155533efea
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.md
index bab3a8b265..924f73f93d 100644
--- a/docs/architecture/key-files/memory-purge.md
+++ b/docs/architecture/key-files/memory-purge.md
@@ -7,7 +7,8 @@ User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#pu
- `src/core/facts/purge.ts` — `submitPurgeFactMutation`, the handler of the owner-only `purge_fact` op (`gbrain forget <id> --purge`). Refuses every caller whose `ctx.remote !== false` with `trusted_local_only` (`purgeHostOnly`, actor user, the exact host command). `planFactPurge` (read-only) computes the scope: every fact row with the same `gbrain_fact_fingerprint` in the fact's source, visibility and subject (the fact's `entity_slug`, `'*'` with `all_subjects`), verbatim takes (`facts.consolidated_into` plus same-fingerprint takes on the subject's page), affected pages from `discoverWithdrawalTargets`, page_versions carrying the text, terminal request intents carrying it, derived rows from `derivation_inputs`, the fact's P8 review rows, and a `revision` digest. A dry run returns the receipt, `confirm_token` (fingerprint's first 8 hex) and `expected_revision`; a real run requires `confirm === token` and, when given, an unchanged revision. The journaled intent is `{id, reason, all_subjects, fact_hash}`, never claim text; replay by request id returns the stored outcome. One transaction in the global lock order: source `FOR UPDATE` (serializes with the guards' `FOR SHARE`), counters for the purge and every redacted request, admission, then inside `withCoordinatedWrite`: pending-publication refusal (`purge_blocked_pending_recovery`), intent redaction, page locks, derived rows hidden before evidence goes, `fact_purges`/`take_purges` tombstones, deletes (takes, review rows, open loops by fact id, take proposals by fingerprint, facts), core-notice base text nulled, page bodies rewritten through the purge overlay, chunks deleted, versions redacted in place, legacy `query_cache` cleared, and `withdrawal-mirror`/`git`/`embedding` effects with `mode: 'purge'` and `commit_subject: gbrain: purge fact <hash8>`. Chunks are rebuilt before acknowledging; `similar_active` is computed before deletion. Pinned by `test/purge-fact.test.ts` (both engines) and `test/forget-purge-cli.test.ts`.
- `src/core/facts/purge-verify.ts` — receipts and verification. `verifyFactPurge` runs one bounded adapter per store (row bound, per-statement `statement_timeout`, a total deadline; `__setPurgeProbeLimitsForTests`): swept stores report `deleted`, `incomplete` (still holds the claim) or `unverified` (bound hit); page-text stores report remaining text as `out_of_scope: source_prose`; every `probed_reported` inventory table is probed and listed; derived rows are `retained_inactive`; model-derived pages without edges are `derived_legacy: unverified`. On-disk: page files (`canonical_markdown`), a quarantined `<file>.tmp` carrying the claim is deleted, the facts write-failure log is reported. `gitResidualCommits` scans `git log --all -p -- <page paths>` output in-process (the pattern never enters argv; byte and time bounded) and lists commits; `OUT_OF_REACH_RESIDUALS` lead every receipt. The vector probe returns same-model neighbours as paraphrase candidates and is never a gate. `purgeCompletion` derives `committed | complete | incomplete` from effects (failed or parked = incomplete), a fingerprint probe and the receipt, with exit codes 10/0/75.
- `src/core/facts/purge-overlay.ts` — purge mode of the import overlay: `dropPurgedFenceRows` drops facts-fence rows matching `fact_purges` and takes-fence rows matching `take_purges` (the takes fence re-renders with its reservation rows plus the dropped numbers reserved, so a purged number is never reused; pinned by `test/purge-overlay-reservations.test.ts`) (subject = page slug; malformed fences left to the withdrawal diagnostics, which refuse a purged claim inside one). Called first by `preserveWithdrawnFenceRows`, so `import-file.ts` needs no change; the snapshot overlay (`page-state/snapshot.ts`) and export (`export-snapshot.ts`) carry purge tombstones as `PageWithdrawal.purged`, which `overlayWithdrawalBody` drops instead of striking.
-- `src/core/facts/purge-schema.ts` — `MEMORY_PURGE_SCHEMA_SQL` (schema.sql fragment: `fact_purges`, `take_purges`, `page_purges` keyed `(source_id, content_hash)`, `derivation_inputs`, `needs_rederive`) and `MEMORY_PURGE_GUARD_SQL` (migration only): `facts_refuse_purged`, `takes_refuse_purged` and `pages_refuse_purged` raise `P0001 purged_content: …` (mapped to typed `purged_content` by `persistence/publication-failure.ts`) instead of skipping the row, whatever `expired_at` says. The pages guard has no column list so it never pins columns.
+- `src/core/facts/purge-schema.ts` — `MEMORY_PURGE_SCHEMA_SQL` (schema.sql fragment: `fact_purges`, `take_purges`, `page_purges` keyed `(source_id, content_hash)`, `derivation_inputs`, `needs_rederive`) and `MEMORY_PURGE_GUARD_SQL` (migration only): `facts_refuse_purged`, `takes_refuse_purged` and `pages_refuse_purged` raise `P0001 purged_content: …` (mapped to typed `purged_content` by `persistence/publication-failure.ts`) instead of skipping the row, whatever `expired_at` says. The pages guard has no column list so it never pins columns. `FACT_PURGE_LOOKUP_INDEX_SQL` (migration v231, CONCURRENTLY on Postgres) adds `fact_purges_subject_idx` (a page's own tombstones, the '*' lookup by fingerprint) and the partial `fact_purges_all_subjects_idx` (subject '*' only, for the snapshot marker count).
+- `src/core/page-state/snapshot.ts` (purge part) — a page snapshot lists only the page's own `fact_purges` tombstones; subject-'*' ones come back as `PageSnapshot.globalPurges` (count, latest `purged_at`, world-only flag; absent at count 0). `resolveGlobalPurges` turns the marker into purge withdrawals for the fence rows of whatever text is overlaid (stored page, incoming file in `page-prepare.ts`, `overlayCanonicalBodies`), on the caller's query. Reconcile pins/preimages and extract-atoms page-state hashing carry the marker, so a new '*' purge invalidates them and an artifact without it reads stale.
- `src/core/facts/derivation-inputs.ts` — `recordDerivationInputs(tx, {table, id, sourceId}, inputs)`: complete derived-row → input edges, written by derivers in the deriving transaction (`write_origin` keeps only a display sample). `derivedRowsFrom` walks edges breadth-first (bounded, reports `truncated`); `hideDerivedRows` expires facts, deactivates takes, soft-deletes pages and upserts `needs_rederive`.
- `src/core/deletion-inventory.ts` — the deletion-target registry: every table with a text, JSON, bytes, array, lexeme or vector column, classed `swept`, `retained_inactive` or `out_of_scope` (`probed_reported` with probe columns, `text_free_ledger`, `secret_material`, `no_memory_text`), plus on-disk stores and out-of-reach residuals. `test/deletion-inventory.test.ts` fails on any unlisted text-bearing column of a fresh schema and pins the AGENTS.md "never promise physical erasure" line.
- `src/core/persistence/intent-redaction.ts` — accounting-aware intent redaction: `findRequestsCarrying` (intent, outcome, error detail or message, compacted rows included) / `findRequestsForSlugs`, `redactRequestIntents` locks counters then request rows, refuses on a non-terminal or recovering request (unless `skipPending`), nulls `intent`/`error_message` and replaces every outcome or error-detail string carrying a needle with `"[purged]"` (`redactJson`), with compaction's terminal-byte accounting, so replay keeps returning the (redacted) stored outcome.
diff --git a/scripts/bench-purge-tombstones.ts b/scripts/bench-purge-tombstones.ts
new file mode 100644
index 0000000000..59c590dc37
--- /dev/null
+++ b/scripts/bench-purge-tombstones.ts
@@ -0,0 +1,113 @@
+/**
+ * Purge tombstone write-path benchmark (GBRA-69 setup): a brain of 50,000
+ * pages, then 1,000 page / 10,000 fact / 1,000 take purge tombstones, a third
+ * of the fact and take ones subject '*'. Reports p50/p95 of a page snapshot
+ * read, an import of one changed page (importFromContent) and a put_page
+ * operation, with and without the tombstones, so a run shows how far the
+ * tombstones move the write path off the no-tombstone line.
+ *
+ * Usage: bun scripts/bench-purge-tombstones.ts [--pages 50000] [--iterations 40] [--json]
+ * DATABASE_URL=postgres://... bun scripts/bench-purge-tombstones.ts --engine postgres
+ * The Postgres run creates and drops its own schema-isolated database objects on the target: use a scratch database.
+ */
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { operationsByName, type OperationContext } from '../src/core/operations.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import type { WriteAttribution } from '../src/core/persistence/attribution.ts';
+
+const arg = (name: string, fallback: string) => {
+ const i = process.argv.indexOf(`--${name}`);
+ return i >= 0 && process.argv[i + 1] ? process.argv[i + 1]! : fallback;
+};
+const PAGES = Number(arg('pages', '50000'));
+const ITERATIONS = Number(arg('iterations', '40'));
+const ENGINE = arg('engine', 'pglite');
+const ATTRIBUTION: WriteAttribution = { requestId: null, principal: { kind: 'application', id: 'bench:purge-tombstones' } };
+
+const fence = (n: number) => `<!--- gbrain:facts:begin -->
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|
+| 1 | Bench claim ${n} for the measured page | fact | 1.0 | world | medium | 2026-01-01 | | chat | |
+| 2 | Bench preference ${n} | preference | 1.0 | world | medium | 2026-01-01 | | chat | |
+<!--- gbrain:facts:end -->`;
+const pageContent = (slug: string, n: number) => `---\ntitle: Bench ${slug}\ntype: person\n---\n# Bench\n\nEdit ${n}.\n\n## Facts\n\n${fence(n)}\n`;
+
+async function connect(): Promise<BrainEngine> {
+ if (ENGINE === 'postgres') {
+ const { PostgresEngine } = await import('../src/core/postgres-engine.ts');
+ const engine = new PostgresEngine();
+ await engine.connect({ database_url: process.env.DATABASE_URL! } as never);
+ await engine.initSchema();
+ return engine;
+ }
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ return engine;
+}
+
+async function seedPages(engine: BrainEngine): Promise<void> {
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(`INSERT INTO pages (source_id, slug, type, title, compiled_truth, timeline, frontmatter)
+ SELECT 'default', 'bench/page-' || g, 'note', 'Bench page ' || g, 'Bench body ' || g || ' with some prose about example topics.', '', '{}'::jsonb
+ FROM generate_series(1, $1::int) AS g ON CONFLICT DO NOTHING`, [PAGES]), ATTRIBUTION));
+}
+
+async function seedTombstones(engine: BrainEngine): Promise<void> {
+ await engine.executeRaw(`INSERT INTO fact_purges (source_id, visibility, subject, fact_hash)
+ SELECT 'default', CASE WHEN g % 2 = 0 THEN 'world' ELSE 'private' END,
+ CASE WHEN g % 3 = 0 THEN '*' ELSE 'bench/page-' || (1 + g % $1::int) END, encode(sha256(('fact-' || g)::bytea), 'hex')
+ FROM generate_series(1, 10000) AS g ON CONFLICT DO NOTHING`, [PAGES]);
+ await engine.executeRaw(`INSERT INTO take_purges (source_id, subject, claim_hash)
+ SELECT 'default', CASE WHEN g % 3 = 0 THEN '*' ELSE 'bench/page-' || (1 + g % $1::int) END, encode(sha256(('take-' || g)::bytea), 'hex')
+ FROM generate_series(1, 1000) AS g ON CONFLICT DO NOTHING`, [PAGES]);
+ await engine.executeRaw(`INSERT INTO page_purges (source_id, content_hash, slug)
+ SELECT 'default', encode(sha256(('page-' || g)::bytea), 'hex'), 'bench/purged-' || g FROM generate_series(1, 1000) AS g ON CONFLICT DO NOTHING`);
+ await engine.executeRaw('ANALYZE fact_purges');
+}
+
+const pct = (xs: number[], p: number) => { const s = [...xs].sort((a, b) => a - b); return s[Math.min(s.length - 1, Math.floor(p * s.length))]!; };
+
+async function measure(engine: BrainEngine, label: string) {
+ const ctx = { engine, config: { engine: engine.kind }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId: 'default' } as OperationContext;
+ const put = operationsByName.put_page!;
+ const slug = `people/bench-${label}`;
+ await importFromContent(engine, slug, pageContent(slug, 0), { noEmbed: true, sourceId: 'default' });
+ const snapshot: number[] = [], imported: number[] = [], putPage: number[] = [];
+ for (let i = 0; i < 5; i++) await engine.readPageSnapshot(slug, { sourceId: 'default' });
+ for (let i = 1; i <= ITERATIONS; i++) {
+ let t = performance.now();
+ await engine.readPageSnapshot(slug, { sourceId: 'default' });
+ snapshot.push(performance.now() - t);
+ t = performance.now();
+ await importFromContent(engine, slug, pageContent(slug, i), { noEmbed: true, sourceId: 'default' });
+ imported.push(performance.now() - t);
+ t = performance.now();
+ await put.handler(ctx, { slug: `${slug}-put`, content: pageContent(`${slug}-put`, i), request_id: randomUUID(), force: true });
+ putPage.push(performance.now() - t);
+ }
+ const row = (xs: number[]) => ({ p50: Number(pct(xs, 0.5).toFixed(2)), p95: Number(pct(xs, 0.95).toFixed(2)) });
+ return { label, snapshot_ms: row(snapshot), import_one_page_ms: row(imported), put_page_ms: row(putPage) };
+}
+
+async function main() {
+ const engine = await connect();
+ await seedPages(engine);
+ const before = await measure(engine, 'no-tombstones');
+ await seedTombstones(engine);
+ const after = await measure(engine, 'tombstones');
+ const [counts] = await engine.executeRaw<Record<string, number>>(`SELECT (SELECT count(*)::int FROM pages) AS pages,
+ (SELECT count(*)::int FROM fact_purges) AS fact_purges, (SELECT count(*)::int FROM fact_purges WHERE subject='*') AS fact_purges_all_subjects,
+ (SELECT count(*)::int FROM take_purges) AS take_purges, (SELECT count(*)::int FROM page_purges) AS page_purges`);
+ const result = { engine: engine.kind, iterations: ITERATIONS, counts, runs: [before, after] };
+ if (process.argv.includes('--json')) console.log(JSON.stringify(result));
+ else {
+ console.log(`${engine.kind}: ${JSON.stringify(counts)}`);
+ for (const r of result.runs) console.log(`${r.label.padEnd(14)} snapshot p50 ${r.snapshot_ms.p50} ms (p95 ${r.snapshot_ms.p95}) | import one page p50 ${r.import_one_page_ms.p50} ms (p95 ${r.import_one_page_ms.p95}) | put_page p50 ${r.put_page_ms.p50} ms (p95 ${r.put_page_ms.p95})`);
+ }
+ await engine.disconnect();
+}
+
+await main();
diff --git a/scripts/build-schema.ts b/scripts/build-schema.ts
index 28916f3e3c..8913f1d684 100644
--- a/scripts/build-schema.ts
+++ b/scripts/build-schema.ts
@@ -41,7 +41,7 @@ import { SHARED_SKILLS_SCHEMA_SQL } from '../src/core/shared-skills/schema-all.t
import { DECIDE_SCHEMA_SQL } from '../src/core/ai/decide/schema.ts';
import { FACT_RELINK_SCHEMA_SQL } from '../src/core/facts/relink-schema.ts';
import { CORE_EDIT_NOTICES_SCHEMA_SQL } from '../src/core/core-memory-schema.ts';
-import { MEMORY_PURGE_SCHEMA_SQL } from '../src/core/facts/purge-schema.ts';
+import { FACT_PURGE_LOOKUP_INDEX_SQL, MEMORY_PURGE_SCHEMA_SQL } from '../src/core/facts/purge-schema.ts';
import { WRITE_GATE_SCHEMA_SQL } from '../src/core/write-gate-schema.ts';
const REPO = resolve(import.meta.dir, '..');
@@ -102,6 +102,7 @@ export const FRAGMENTS: readonly Fragment[] = [
{ source: 'src/core/link-temporal-schema.ts', expr: 'LINK_TEMPORAL_SCHEMA_SQL', postgres: LINK_TEMPORAL_SCHEMA_SQL, pglite: LINK_TEMPORAL_SCHEMA_SQL },
{ source: 'src/core/core-memory-schema.ts', expr: 'CORE_EDIT_NOTICES_SCHEMA_SQL', postgres: CORE_EDIT_NOTICES_SCHEMA_SQL, pglite: CORE_EDIT_NOTICES_SCHEMA_SQL },
{ source: 'src/core/facts/purge-schema.ts', expr: 'MEMORY_PURGE_SCHEMA_SQL', postgres: MEMORY_PURGE_SCHEMA_SQL, pglite: MEMORY_PURGE_SCHEMA_SQL },
+ { source: 'src/core/facts/purge-schema.ts', expr: 'FACT_PURGE_LOOKUP_INDEX_SQL', postgres: FACT_PURGE_LOOKUP_INDEX_SQL, pglite: FACT_PURGE_LOOKUP_INDEX_SQL },
{ source: 'src/core/write-gate-schema.ts', expr: 'WRITE_GATE_SCHEMA_SQL', postgres: WRITE_GATE_SCHEMA_SQL, pglite: WRITE_GATE_SCHEMA_SQL },
];
diff --git a/src/core/cycle/extract-atoms-page-state.ts b/src/core/cycle/extract-atoms-page-state.ts
index 929365e7c8..9bbc88af9c 100644
--- a/src/core/cycle/extract-atoms-page-state.ts
+++ b/src/core/cycle/extract-atoms-page-state.ts
@@ -111,7 +111,8 @@ export async function transferLegacyAtomPageState(engine: SqlEngine, before: Pag
for (const key of LEGACY_KEYS) delete frontmatter[key];
return { sourceId: snapshot.page.source_id, slug: snapshot.page.slug, type: snapshot.page.type,
title: snapshot.page.title, body: snapshot.page.compiled_truth,
- timeline: snapshot.page.timeline, frontmatter, tags: [...snapshot.tags].sort(), withdrawals: snapshot.withdrawals };
+ timeline: snapshot.page.timeline, frontmatter, tags: [...snapshot.tags].sort(), withdrawals: snapshot.withdrawals,
+ global_purges: snapshot.globalPurges ?? null };
};
if (stableJson(canonical(before)) !== stableJson(canonical(after))) return false;
const [existing] = await engine.executeRaw<{ fail_count: number; tombstoned: boolean }>(
diff --git a/src/core/facts/purge-schema.ts b/src/core/facts/purge-schema.ts
index 3b5ff61e57..d185cd6961 100644
--- a/src/core/facts/purge-schema.ts
+++ b/src/core/facts/purge-schema.ts
@@ -90,6 +90,29 @@ ${RLS('needs_rederive')}
* lock on the source row, which the purge holds FOR UPDATE while it writes the
* ledger and deletes the rows.
*/
+/**
+ * Page snapshot reads (page-state/snapshot.ts) look up a page's own fact purge
+ * tombstones (subject = the slug), the subject-'*' marker (count and latest
+ * purged_at) and, lazily, the '*' tombstones naming a fence row's fingerprint.
+ * The primary key leads with visibility, so each of those scanned every
+ * tombstone of the source (GBRA-69: 4-5 ms per snapshot at 10,000 fact
+ * tombstones, about 7 snapshots per import). `fact_purges_subject_idx` serves
+ * a page's own tombstones and the lazy '*' lookup by fingerprint;
+ * `fact_purges_all_subjects_idx` holds only the '*' rows the marker counts.
+ * The import probes that match a fence row against `subject='*' OR
+ * subject=slug` (facts/purge-overlay.ts, eligibility/fence-overlay.ts) become
+ * a bitmap OR over the pair. Migration v231 builds both (CONCURRENTLY on
+ * Postgres).
+ */
+export const FACT_PURGES_SUBJECT_INDEX = { name: 'fact_purges_subject_idx', table: 'fact_purges',
+ sql: 'CREATE INDEX IF NOT EXISTS fact_purges_subject_idx ON fact_purges (source_id, subject, fact_hash) INCLUDE (visibility, purged_at)' } as const;
+export const FACT_PURGES_ALL_SUBJECTS_INDEX = { name: 'fact_purges_all_subjects_idx', table: 'fact_purges',
+ sql: "CREATE INDEX IF NOT EXISTS fact_purges_all_subjects_idx ON fact_purges (source_id, purged_at) WHERE subject = '*'" } as const;
+export const FACT_PURGE_LOOKUP_INDEX_SQL = `
+${FACT_PURGES_SUBJECT_INDEX.sql};
+${FACT_PURGES_ALL_SUBJECTS_INDEX.sql};
+`;
+
export const MEMORY_PURGE_GUARD_SQL = `
CREATE OR REPLACE FUNCTION gbrain_refuse_purged_fact() RETURNS trigger
LANGUAGE plpgsql SET search_path = pg_catalog, public AS $fn$
diff --git a/src/core/facts/withdrawal-overlay.ts b/src/core/facts/withdrawal-overlay.ts
index a76f9405ea..623cb95370 100644
--- a/src/core/facts/withdrawal-overlay.ts
+++ b/src/core/facts/withdrawal-overlay.ts
@@ -110,6 +110,21 @@ export function hasAmbiguousWithdrawalFence(body: string): boolean {
return ambiguousWithdrawalFenceSegments(body).length > 0;
}
+/** Both fingerprints `overlayWithdrawalBody` looks a fence row's claim up by: the normalized claim and the raw normalized-line claim. */
+export function fenceClaimHashes(normalizedTexts: readonly string[]): string[] {
+ const hashes = new Set<string>();
+ for (const text of normalizedTexts) {
+ if (!text.includes('gbrain:facts:begin')) continue;
+ for (const block of withdrawalFenceBlocks(text)) {
+ for (const f of block.parsed.facts) {
+ hashes.add(createHash('sha256').update(normalizeLoweredClaim(f.claim)).digest('hex'));
+ hashes.add(createHash('sha256').update(f.claim).digest('hex'));
+ }
+ }
+ }
+ return [...hashes];
+}
+
/** Apply hashes from DB-normalized companion text to the original Markdown. */
export function overlayWithdrawalBody(body: string, normalizedBody: string, withdrawals: PageWithdrawal[]): string {
if (!withdrawals.length || !body.includes('gbrain:facts:begin')) return body;
diff --git a/src/core/page-state/snapshot.ts b/src/core/page-state/snapshot.ts
index 6df421530b..b57a203597 100644
--- a/src/core/page-state/snapshot.ts
+++ b/src/core/page-state/snapshot.ts
@@ -1,20 +1,52 @@
-import { overlayWithdrawalBody } from '../facts/withdrawal-overlay.ts';
+import { fenceClaimHashes, overlayWithdrawalBody } from '../facts/withdrawal-overlay.ts';
import { privatePagesFilterFragment } from '../search/private-visibility.ts';
import type { ReadQuery } from '../search/read-enrichment.ts';
import { rowToPage } from '../utils.ts';
-import type { PageSnapshot, PageSnapshotOptions, PageWithdrawal } from './types.ts';
+import type { GlobalPurgeMarker, PageSnapshot, PageSnapshotOptions, PageWithdrawal } from './types.ts';
import { PageSnapshotAmbiguousError, REVISION_BACKFILL_PENDING } from './types.ts';
-/** Normalize filesystem bytes with the exact ledger fingerprint rules before comparing them. */
-export async function overlayCanonicalBodies(query: ReadQuery, body: string, timeline: string, withdrawals: PageWithdrawal[]): Promise<{ compiled_truth: string; timeline: string }> {
- if (!withdrawals.length) return { compiled_truth: body, timeline };
+/**
+ * Subject-'*' fact purges that name a fence row of the given DB-normalized
+ * text, as purge withdrawals. Snapshot reads carry only a marker for them
+ * (GlobalPurgeMarker), because listing every '*' tombstone of a source made
+ * each snapshot aggregate the whole ledger. The lookup runs on the caller's
+ * `query`, so inside a transaction it reads that transaction's ledger; nothing
+ * runs when the source has no '*' tombstone or the text has no fence row.
+ * Purging only adds tombstones (unpurge removes a page's own, and changes the
+ * marker), so a later read finds the same rows or more: a stale caller drops
+ * at most fewer rows than a fresh one, and the import path re-checks the
+ * ledger itself (facts/purge-overlay.ts) before anything is published.
+ */
+export async function resolveGlobalPurges(query: ReadQuery, sourceId: string, marker: GlobalPurgeMarker | undefined,
+ normalizedTexts: readonly string[]): Promise<PageWithdrawal[]> {
+ if (!marker || marker.count <= 0) return [];
+ const hashes = fenceClaimHashes(normalizedTexts);
+ if (!hashes.length) return [];
+ const rows = await query<{ w: PageWithdrawal }>(`SELECT jsonb_build_object('visibility',visibility,'fact_hash',fact_hash,
+ 'withdrawn_at',min(purged_at),'purged',true) AS w
+ FROM fact_purges WHERE source_id=$1 AND subject='*' AND fact_hash=ANY($2::text[]) ${marker.world_only ? "AND visibility='world'" : ''}
+ GROUP BY visibility,fact_hash ORDER BY visibility,fact_hash`, [sourceId, hashes]);
+ return rows.map(r => typeof r.w === 'string' ? JSON.parse(r.w) as PageWithdrawal : r.w);
+}
+
+/**
+ * Normalize filesystem bytes with the exact ledger fingerprint rules before comparing them. `global` names the
+ * snapshot's source and '*' purge marker, resolved against this text's fence rows (not the stored page's).
+ */
+export async function overlayCanonicalBodies(query: ReadQuery, body: string, timeline: string, withdrawals: PageWithdrawal[],
+ global?: { sourceId: string; marker?: GlobalPurgeMarker }): Promise<{ compiled_truth: string; timeline: string }> {
+ const pending = global?.marker && global.marker.count > 0 ? global : undefined;
+ if (!withdrawals.length && !pending) return { compiled_truth: body, timeline };
+ if (!body.includes('gbrain:facts:begin') && !timeline.includes('gbrain:facts:begin')) return { compiled_truth: body, timeline };
const [normalized] = await query<{ body: string; timeline: string }>(`SELECT
(SELECT string_agg(regexp_replace(lower(line),'[[:space:]]+',' ','g'),chr(10) ORDER BY ord)
FROM unnest(string_to_array($1::text,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS body,
(SELECT string_agg(regexp_replace(lower(line),'[[:space:]]+',' ','g'),chr(10) ORDER BY ord)
FROM unnest(string_to_array($2::text,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS timeline`, [body, timeline]);
- return { compiled_truth: overlayWithdrawalBody(body, normalized.body ?? '', withdrawals),
- timeline: overlayWithdrawalBody(timeline, normalized.timeline ?? '', withdrawals) };
+ const resolved = pending ? await resolveGlobalPurges(query, pending.sourceId, pending.marker, [normalized.body ?? '', normalized.timeline ?? '']) : [];
+ const all = resolved.length ? [...withdrawals, ...resolved] : withdrawals;
+ return { compiled_truth: overlayWithdrawalBody(body, normalized.body ?? '', all),
+ timeline: overlayWithdrawalBody(timeline, normalized.timeline ?? '', all) };
}
/**
@@ -65,10 +97,10 @@ async function readSnapshotStatement(query: ReadQuery, slug: string, opts?: Page
) SELECT p.*,
(SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation,
COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags,
- wd.snapshot_withdrawals,
- CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord)
+ wd.snapshot_withdrawals, wd.snapshot_global_purges,
+ CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord)
FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_body,
- CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord)
+ CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord)
FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_timeline
FROM chosen p
CROSS JOIN LATERAL (SELECT COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at)
@@ -77,15 +109,20 @@ async function readSnapshotStatement(query: ReadQuery, slug: string, opts?: Page
${opts?.excludePrivate ? "AND visibility='world'" : ''} GROUP BY visibility,fact_hash) w), '[]'::jsonb)
|| COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true)
ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at
- FROM fact_purges WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug)
- ${opts?.excludePrivate ? "AND visibility='world'" : ''} GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals) wd`, params);
+ FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug
+ ${opts?.excludePrivate ? "AND visibility='world'" : ''} GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals,
+ (SELECT jsonb_build_object('count',count(*),'latest',max(g.purged_at)) FROM fact_purges g WHERE g.source_id=p.source_id AND g.subject='*'
+ ${opts?.excludePrivate ? "AND g.visibility='world'" : ''}) AS snapshot_global_purges) wd`, params);
if (!rows.length) return null;
const row = rows[0];
if (opts?.requireUnambiguous && Number(row.snapshot_matches) > 1) throw new PageSnapshotAmbiguousError();
const page = rowToPage(row);
- const withdrawals = row.snapshot_withdrawals as PageWithdrawal[];
+ const raw = (typeof row.snapshot_global_purges === 'string' ? JSON.parse(row.snapshot_global_purges) : row.snapshot_global_purges) as { count?: unknown; latest?: unknown } | null;
+ const globalPurges: GlobalPurgeMarker = { count: Number(raw?.count ?? 0), latest: raw?.latest == null ? null : String(raw.latest), world_only: opts?.excludePrivate === true };
+ const withdrawals = [...row.snapshot_withdrawals as PageWithdrawal[], ...await resolveGlobalPurges(query, page.source_id, globalPurges,
+ [String(row.fingerprint_body ?? ''), String(row.fingerprint_timeline ?? '')])];
page.compiled_truth = overlayWithdrawalBody(page.compiled_truth, String(row.fingerprint_body ?? ''), withdrawals);
page.timeline = overlayWithdrawalBody(page.timeline, String(row.fingerprint_timeline ?? ''), withdrawals);
return { page, tags: row.snapshot_tags as string[], revision: row.knowledge_revision == null ? REVISION_BACKFILL_PENDING : String(row.knowledge_revision),
- sourceIncarnation: String(row.source_incarnation), withdrawals };
+ sourceIncarnation: String(row.source_incarnation), withdrawals, ...(globalPurges.count > 0 ? { globalPurges } : {}) };
}
diff --git a/src/core/page-state/types.ts b/src/core/page-state/types.ts
index c905bcc644..18da5d0902 100644
--- a/src/core/page-state/types.ts
+++ b/src/core/page-state/types.ts
@@ -47,12 +47,28 @@ export interface PageWithdrawal {
/** A purge tombstone (fact_purges): the overlay drops the row instead of striking it. */
purged?: boolean;
}
+/**
+ * The source's subject-'*' fact purge tombstones under the read's visibility
+ * filter, as a marker instead of a list: they apply to every page, so each
+ * overlay resolves them against the fence rows of the text it overlays
+ * (page-state/snapshot.ts `resolveGlobalPurges`). Count and latest purged_at
+ * change when a '*' tombstone is added or removed, so a digest that carries
+ * the marker goes stale on either.
+ */
+export interface GlobalPurgeMarker {
+ count: number;
+ latest: string | null;
+ /** The read kept world rows only (excludePrivate); the lookup applies the same filter. */
+ world_only: boolean;
+}
export interface PageSnapshot {
page: Page;
tags: string[];
revision: string;
sourceIncarnation: string;
withdrawals: PageWithdrawal[];
+ /** Subject-'*' purges, listed in `withdrawals` only when the stored text names them. Absent when the source has none under the read's filter. */
+ globalPurges?: GlobalPurgeMarker;
}
export class PageRevisionConflictError extends Error {
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 315c8daf8a..53bf7a892f 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -140,7 +140,7 @@ export async function fileMatchesSnapshot(engine: BrainEngine, slug: string, byt
// Withdrawal overlays intentionally precede physical mirroring. The ledger
// is applied by the import preparation and cannot be undone by this check.
const actual = canonical({ ...parsed, type, ...await overlayCanonicalBodies(engine.executeRaw.bind(engine),
- parsed.compiled_truth, parsed.timeline ?? '', snapshot.withdrawals) }, parsed.tags);
+ parsed.compiled_truth, parsed.timeline ?? '', snapshot.withdrawals, { sourceId: snapshot.page.source_id, marker: snapshot.globalPurges }) }, parsed.tags);
return digest(actual) === digest(canonical(snapshot.page, snapshot.tags));
}
export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequest, 'source_id' | 'worktree_id' | 'slug'>, snapshot: PageSnapshot | null,
diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.ts
index bf7a43140f..995c307bb6 100644
--- a/src/core/persistence/reconcile-state.ts
+++ b/src/core/persistence/reconcile-state.ts
@@ -187,7 +187,7 @@ export async function readReconcileState(engine: BrainEngine, sourceId: string,
const pins: ReconcilePins = { brain_id: brain.brain_id, source_id: sourceId, source_incarnation: snapshot.sourceIncarnation, slug,
page_id: snapshot.page.id, worktree_id: binding.worktree_id, binding_digest: digest({ binding, root, path: canonicalPath }), owner_epoch: String(binding.owner_epoch),
revision: snapshot.revision, raw_file_hash: sha256(raw), relative_path: relative(root, path),
- policy_digest: await reconcilePolicyDigest(engine, sourceId), withdrawals_digest: digest(snapshot.withdrawals), assessment_at: assessmentAt };
+ policy_digest: await reconcilePolicyDigest(engine, sourceId), withdrawals_digest: digest({ withdrawals: snapshot.withdrawals, global_purges: snapshot.globalPurges ?? null }), assessment_at: assessmentAt };
return { binding, root, path, raw, snapshot, storedPage, file: reconcileCanonical(parsed, parsed.tags), pins, origin, originSourcePath: derived?.sourcePath ?? null };
}
export function assertReconcilePins(expected: ReconcilePins, actual: ReconcilePins): void {
@@ -214,7 +214,10 @@ export function validateReconcileArtifact(value: unknown): ReconcileArtifact {
strictReconcileKeys(value.preconditions, ['brain_id', 'source_id', 'source_incarnation', 'slug', 'page_id', 'worktree_id', 'binding_digest',
'owner_epoch', 'revision', 'raw_file_hash', 'relative_path', 'policy_digest', 'withdrawals_digest', 'assessment_at']);
strictReconcileKeys(value.preimages, ['file_base64', 'database', 'stored_page']);
- strictReconcileKeys(value.preimages.database, ['page', 'tags', 'revision', 'sourceIncarnation', 'withdrawals']);
+ // globalPurges is optional here so an artifact written before the '*' purge marker validates and then reads stale (assertPreimages).
+ strictReconcileKeys(value.preimages.database, ['page', 'tags', 'revision', 'sourceIncarnation', 'withdrawals', 'globalPurges'],
+ ['page', 'tags', 'revision', 'sourceIncarnation', 'withdrawals']);
+ if (value.preimages.database.globalPurges !== undefined) strictReconcileKeys(value.preimages.database.globalPurges, ['count', 'latest', 'world_only']);
strictReconcileKeys(value.preimages.database.page, ['id', 'slug', 'source_id', 'type', 'title', 'compiled_truth', 'timeline', 'frontmatter',
'content_hash', 'source_path', 'knowledge_revision', 'text_projection_revision', 'emotional_weight', 'created_at', 'updated_at', 'updated_at_iso',
'deleted_at', 'effective_date', 'effective_date_source', 'import_filename', 'salience_touched_at', 'source_kind', 'source_uri', 'ingested_via',
diff --git a/src/core/persistence/reconcile.ts b/src/core/persistence/reconcile.ts
index b31afbe7fe..d8690852c9 100644
--- a/src/core/persistence/reconcile.ts
+++ b/src/core/persistence/reconcile.ts
@@ -57,7 +57,7 @@ async function authorize(engine: BrainEngine, sourceId: unknown, slug: unknown)
function assertPreimages(artifact: ReconcileArtifact, state: ReconcileState): void {
assertReconcilePins(artifact.preconditions, state.pins);
const canonical = (snapshot: typeof state.snapshot) => ({ page: reconcileCanonical(snapshot.page, snapshot.tags), revision: snapshot.revision,
- sourceIncarnation: snapshot.sourceIncarnation, withdrawals: snapshot.withdrawals,
+ sourceIncarnation: snapshot.sourceIncarnation, withdrawals: snapshot.withdrawals, global_purges: snapshot.globalPurges ?? null,
provenance: Object.fromEntries(['id', 'slug', 'source_id', 'source_path', 'source_kind', 'source_uri', 'ingested_via', 'ingested_at',
'knowledge_revision', 'deleted_at'].map(key => [key, snapshot.page[key as keyof typeof snapshot.page]])) });
if (artifact.preimages.file_base64 !== state.raw.toString('base64') || digest(canonical(artifact.preimages.database)) !== digest(canonical(state.snapshot)) ||
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index ea1b4e6cd4..e0e76a11e7 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -2163,6 +2163,9 @@ DO \$rls\$ BEGIN
END IF;
END \$rls\$;
+CREATE INDEX IF NOT EXISTS fact_purges_subject_idx ON fact_purges (source_id, subject, fact_hash) INCLUDE (visibility, purged_at);
+CREATE INDEX IF NOT EXISTS fact_purges_all_subjects_idx ON fact_purges (source_id, purged_at) WHERE subject = '*';
+
-- #5575 blocking write gate: verdict receipts and held facts/takes.
CREATE TABLE IF NOT EXISTS write_gate_receipts (
id BIGSERIAL PRIMARY KEY,
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index 5d6ab0ad5b..c815c62cb4 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -2911,6 +2911,11 @@ DO \$rls\$ BEGIN
END \$rls\$;
-- END GENERATED from src/core/facts/purge-schema.ts (MEMORY_PURGE_SCHEMA_SQL)
+-- BEGIN GENERATED from src/core/facts/purge-schema.ts (FACT_PURGE_LOOKUP_INDEX_SQL). Edit that file, then run: bun run build:schema
+CREATE INDEX IF NOT EXISTS fact_purges_subject_idx ON fact_purges (source_id, subject, fact_hash) INCLUDE (visibility, purged_at);
+CREATE INDEX IF NOT EXISTS fact_purges_all_subjects_idx ON fact_purges (source_id, purged_at) WHERE subject = '*';
+-- END GENERATED from src/core/facts/purge-schema.ts (FACT_PURGE_LOOKUP_INDEX_SQL)
+
-- #5575 blocking write gate: verdict receipts and held facts/takes.
-- BEGIN GENERATED from src/core/write-gate-schema.ts (WRITE_GATE_SCHEMA_SQL). Edit that file, then run: bun run build:schema
CREATE TABLE IF NOT EXISTS write_gate_receipts (
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index 06c6931011..f08dfeeffd 100644
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -4,4 +4,4 @@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
-export const LATEST_SCHEMA_VERSION = 230;
+export const LATEST_SCHEMA_VERSION = 231;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index 1337474597..7b020ce4dc 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -231,6 +231,7 @@ import { v227 } from './v227-write-gate.ts';
import { v228 } from './v228-memory-purge.ts';
import { v229 } from './v229-trust-allow-rules.ts';
import { v230 } from './v230-trust-generation.ts';
+import { v231 } from './v231-fact-purge-lookup-indexes.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -460,4 +461,5 @@ export const MIGRATIONS: Migration[] = [
v228,
v229,
v230,
+ v231,
];
diff --git a/src/core/schema-migrations/v231-fact-purge-lookup-indexes.ts b/src/core/schema-migrations/v231-fact-purge-lookup-indexes.ts
new file mode 100644
index 0000000000..d55c5eba96
--- /dev/null
+++ b/src/core/schema-migrations/v231-fact-purge-lookup-indexes.ts
@@ -0,0 +1,24 @@
+import type { Migration } from './types.ts';
+import { FACT_PURGES_ALL_SUBJECTS_INDEX, FACT_PURGES_SUBJECT_INDEX } from '../facts/purge-schema.ts';
+import { buildIndexOnline, migrationNotice } from './helpers.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// Page snapshots stopped aggregating every subject-'*' fact purge tombstone
+// (page-state/snapshot.ts): they read a page's own tombstones, a count/latest
+// marker for the '*' ones and, only for a text with fence rows, the '*'
+// tombstones naming those rows. fact_purges' primary key leads with
+// visibility, so all three scanned the source's whole ledger. These indexes
+// make them index probes (facts/purge-schema.ts). Postgres builds them
+// CONCURRENTLY, one at a time; PGLite inline. Tombstone ledgers are small.
+export const v231: Migration = {
+ version: 231,
+ name: 'fact_purge_lookup_indexes',
+ idempotent: true,
+ sql: '',
+ handler: async engine => {
+ await buildIndexOnline(engine, 231, FACT_PURGES_SUBJECT_INDEX, { notice: migrationNotice });
+ await buildIndexOnline(engine, 231, FACT_PURGES_ALL_SUBJECTS_INDEX, { notice: migrationNotice });
+ },
+};
diff --git a/src/schema.sql b/src/schema.sql
index d6040a6e50..61285eccc9 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -2907,6 +2907,11 @@ DO $rls$ BEGIN
END $rls$;
-- END GENERATED from src/core/facts/purge-schema.ts (MEMORY_PURGE_SCHEMA_SQL)
+-- BEGIN GENERATED from src/core/facts/purge-schema.ts (FACT_PURGE_LOOKUP_INDEX_SQL). Edit that file, then run: bun run build:schema
+CREATE INDEX IF NOT EXISTS fact_purges_subject_idx ON fact_purges (source_id, subject, fact_hash) INCLUDE (visibility, purged_at);
+CREATE INDEX IF NOT EXISTS fact_purges_all_subjects_idx ON fact_purges (source_id, purged_at) WHERE subject = '*';
+-- END GENERATED from src/core/facts/purge-schema.ts (FACT_PURGE_LOOKUP_INDEX_SQL)
+
-- #5575 blocking write gate: verdict receipts and held facts/takes.
-- BEGIN GENERATED from src/core/write-gate-schema.ts (WRITE_GATE_SCHEMA_SQL). Edit that file, then run: bun run build:schema
CREATE TABLE IF NOT EXISTS write_gate_receipts (
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index aa2d8cac49..e7d9d1a1a8 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -938,7 +938,9 @@
"extract_atoms_transcript_state_pkey": "CREATE UNIQUE INDEX extract_atoms_transcript_state_pkey ON public.extract_atoms_transcript_state USING btree (source_id, file_path, content_hash)",
"extract_atoms_transcript_state_tombstoned_idx": "CREATE INDEX extract_atoms_transcript_state_tombstoned_idx ON public.extract_atoms_transcript_state USING btree (source_id, content_hash) WHERE tombstoned",
"extract_rollup_7d_pkey": "CREATE UNIQUE INDEX extract_rollup_7d_pkey ON public.extract_rollup_7d USING btree (kind, source_id, day)",
+ "fact_purges_all_subjects_idx": "CREATE INDEX fact_purges_all_subjects_idx ON public.fact_purges USING btree (source_id, purged_at) WHERE (subject = '*'::text)",
"fact_purges_pkey": "CREATE UNIQUE INDEX fact_purges_pkey ON public.fact_purges USING btree (source_id, visibility, subject, fact_hash)",
+ "fact_purges_subject_idx": "CREATE INDEX fact_purges_subject_idx ON public.fact_purges USING btree (source_id, subject, fact_hash) INCLUDE (visibility, purged_at)",
"fact_relink_attempts_outcome_idx": "CREATE INDEX fact_relink_attempts_outcome_idx ON public.fact_relink_attempts USING btree (source_id, outcome, attempted_at)",
"fact_relink_attempts_pkey": "CREATE UNIQUE INDEX fact_relink_attempts_pkey ON public.fact_relink_attempts USING btree (source_id, fact_id)",
"fact_withdrawals_pkey": "CREATE UNIQUE INDEX fact_withdrawals_pkey ON public.fact_withdrawals USING btree (source_id, visibility, subject, fact_hash)",
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 662b4d2097..15fbc1cf0c 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -938,7 +938,9 @@
"extract_atoms_transcript_state_pkey": "CREATE UNIQUE INDEX extract_atoms_transcript_state_pkey ON public.extract_atoms_transcript_state USING btree (source_id, file_path, content_hash)",
"extract_atoms_transcript_state_tombstoned_idx": "CREATE INDEX extract_atoms_transcript_state_tombstoned_idx ON public.extract_atoms_transcript_state USING btree (source_id, content_hash) WHERE tombstoned",
"extract_rollup_7d_pkey": "CREATE UNIQUE INDEX extract_rollup_7d_pkey ON public.extract_rollup_7d USING btree (kind, source_id, day)",
+ "fact_purges_all_subjects_idx": "CREATE INDEX fact_purges_all_subjects_idx ON public.fact_purges USING btree (source_id, purged_at) WHERE (subject = '*'::text)",
"fact_purges_pkey": "CREATE UNIQUE INDEX fact_purges_pkey ON public.fact_purges USING btree (source_id, visibility, subject, fact_hash)",
+ "fact_purges_subject_idx": "CREATE INDEX fact_purges_subject_idx ON public.fact_purges USING btree (source_id, subject, fact_hash) INCLUDE (visibility, purged_at)",
"fact_relink_attempts_outcome_idx": "CREATE INDEX fact_relink_attempts_outcome_idx ON public.fact_relink_attempts USING btree (source_id, outcome, attempted_at)",
"fact_relink_attempts_pkey": "CREATE UNIQUE INDEX fact_relink_attempts_pkey ON public.fact_relink_attempts USING btree (source_id, fact_id)",
"fact_withdrawals_pkey": "CREATE UNIQUE INDEX fact_withdrawals_pkey ON public.fact_withdrawals USING btree (source_id, visibility, subject, fact_hash)",
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 d33a00db65..60b2f16aef 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -938,7 +938,9 @@
"extract_atoms_transcript_state_pkey": "CREATE UNIQUE INDEX extract_atoms_transcript_state_pkey ON public.extract_atoms_transcript_state USING btree (source_id, file_path, content_hash)",
"extract_atoms_transcript_state_tombstoned_idx": "CREATE INDEX extract_atoms_transcript_state_tombstoned_idx ON public.extract_atoms_transcript_state USING btree (source_id, content_hash) WHERE tombstoned",
"extract_rollup_7d_pkey": "CREATE UNIQUE INDEX extract_rollup_7d_pkey ON public.extract_rollup_7d USING btree (kind, source_id, day)",
+ "fact_purges_all_subjects_idx": "CREATE INDEX fact_purges_all_subjects_idx ON public.fact_purges USING btree (source_id, purged_at) WHERE (subject = '*'::text)",
"fact_purges_pkey": "CREATE UNIQUE INDEX fact_purges_pkey ON public.fact_purges USING btree (source_id, visibility, subject, fact_hash)",
+ "fact_purges_subject_idx": "CREATE INDEX fact_purges_subject_idx ON public.fact_purges USING btree (source_id, subject, fact_hash) INCLUDE (visibility, purged_at)",
"fact_relink_attempts_outcome_idx": "CREATE INDEX fact_relink_attempts_outcome_idx ON public.fact_relink_attempts USING btree (source_id, outcome, attempted_at)",
"fact_relink_attempts_pkey": "CREATE UNIQUE INDEX fact_relink_attempts_pkey ON public.fact_relink_attempts USING btree (source_id, fact_id)",
"fact_withdrawals_pkey": "CREATE UNIQUE INDEX fact_withdrawals_pkey ON public.fact_withdrawals USING btree (source_id, visibility, subject, fact_hash)",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
index e61dcbeae0..4e015857cb 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
@@ -687,7 +687,9 @@
"extract_atoms_page_state_tombstoned_idx": "CREATE INDEX extract_atoms_page_state_tombstoned_idx ON public.extract_atoms_page_state USING btree (source_incarnation, content_hash, page_id) WHERE tombstoned",
"extract_atoms_transcript_state_pkey": "CREATE UNIQUE INDEX extract_atoms_transcript_state_pkey ON public.extract_atoms_transcript_state USING btree (source_id, file_path, content_hash)",
"extract_atoms_transcript_state_tombstoned_idx": "CREATE INDEX extract_atoms_transcript_state_tombstoned_idx ON public.extract_atoms_transcript_state USING btree (source_id, content_hash) WHERE tombstoned",
+ "fact_purges_all_subjects_idx": "CREATE INDEX fact_purges_all_subjects_idx ON public.fact_purges USING btree (source_id, purged_at) WHERE (subject = '*'::text)",
"fact_purges_pkey": "CREATE UNIQUE INDEX fact_purges_pkey ON public.fact_purges USING btree (source_id, visibility, subject, fact_hash)",
+ "fact_purges_subject_idx": "CREATE INDEX fact_purges_subject_idx ON public.fact_purges USING btree (source_id, subject, fact_hash) INCLUDE (visibility, purged_at)",
"fact_relink_attempts_outcome_idx": "CREATE INDEX fact_relink_attempts_outcome_idx ON public.fact_relink_attempts USING btree (source_id, outcome, attempted_at)",
"fact_relink_attempts_pkey": "CREATE UNIQUE INDEX fact_relink_attempts_pkey ON public.fact_relink_attempts USING btree (source_id, fact_id)",
"fact_withdrawals_pkey": "CREATE UNIQUE INDEX fact_withdrawals_pkey ON public.fact_withdrawals USING btree (source_id, visibility, subject, fact_hash)",
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 5f1494556b..ce1e3a8e1f 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
@@ -687,7 +687,9 @@
"extract_atoms_page_state_tombstoned_idx": "CREATE INDEX extract_atoms_page_state_tombstoned_idx ON public.extract_atoms_page_state USING btree (source_incarnation, content_hash, page_id) WHERE tombstoned",
"extract_atoms_transcript_state_pkey": "CREATE UNIQUE INDEX extract_atoms_transcript_state_pkey ON public.extract_atoms_transcript_state USING btree (source_id, file_path, content_hash)",
"extract_atoms_transcript_state_tombstoned_idx": "CREATE INDEX extract_atoms_transcript_state_tombstoned_idx ON public.extract_atoms_transcript_state USING btree (source_id, content_hash) WHERE tombstoned",
+ "fact_purges_all_subjects_idx": "CREATE INDEX fact_purges_all_subjects_idx ON public.fact_purges USING btree (source_id, purged_at) WHERE (subject = '*'::text)",
"fact_purges_pkey": "CREATE UNIQUE INDEX fact_purges_pkey ON public.fact_purges USING btree (source_id, visibility, subject, fact_hash)",
+ "fact_purges_subject_idx": "CREATE INDEX fact_purges_subject_idx ON public.fact_purges USING btree (source_id, subject, fact_hash) INCLUDE (visibility, purged_at)",
"fact_relink_attempts_outcome_idx": "CREATE INDEX fact_relink_attempts_outcome_idx ON public.fact_relink_attempts USING btree (source_id, outcome, attempted_at)",
"fact_relink_attempts_pkey": "CREATE UNIQUE INDEX fact_relink_attempts_pkey ON public.fact_relink_attempts USING btree (source_id, fact_id)",
"fact_withdrawals_pkey": "CREATE UNIQUE INDEX fact_withdrawals_pkey ON public.fact_withdrawals USING btree (source_id, visibility, subject, fact_hash)",
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 f79349709e..7eee0739b9 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
@@ -687,7 +687,9 @@
"extract_atoms_page_state_tombstoned_idx": "CREATE INDEX extract_atoms_page_state_tombstoned_idx ON public.extract_atoms_page_state USING btree (source_incarnation, content_hash, page_id) WHERE tombstoned",
"extract_atoms_transcript_state_pkey": "CREATE UNIQUE INDEX extract_atoms_transcript_state_pkey ON public.extract_atoms_transcript_state USING btree (source_id, file_path, content_hash)",
"extract_atoms_transcript_state_tombstoned_idx": "CREATE INDEX extract_atoms_transcript_state_tombstoned_idx ON public.extract_atoms_transcript_state USING btree (source_id, content_hash) WHERE tombstoned",
+ "fact_purges_all_subjects_idx": "CREATE INDEX fact_purges_all_subjects_idx ON public.fact_purges USING btree (source_id, purged_at) WHERE (subject = '*'::text)",
"fact_purges_pkey": "CREATE UNIQUE INDEX fact_purges_pkey ON public.fact_purges USING btree (source_id, visibility, subject, fact_hash)",
+ "fact_purges_subject_idx": "CREATE INDEX fact_purges_subject_idx ON public.fact_purges USING btree (source_id, subject, fact_hash) INCLUDE (visibility, purged_at)",
"fact_relink_attempts_outcome_idx": "CREATE INDEX fact_relink_attempts_outcome_idx ON public.fact_relink_attempts USING btree (source_id, outcome, attempted_at)",
"fact_relink_attempts_pkey": "CREATE UNIQUE INDEX fact_relink_attempts_pkey ON public.fact_relink_attempts USING btree (source_id, fact_id)",
"fact_withdrawals_pkey": "CREATE UNIQUE INDEX fact_withdrawals_pkey ON public.fact_withdrawals USING btree (source_id, visibility, subject, fact_hash)",
diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.json
index 46760d1e7b..82a0863b19 100644
--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json
+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json
@@ -707,7 +707,9 @@
"extract_atoms_page_state_tombstoned_idx": "CREATE INDEX extract_atoms_page_state_tombstoned_idx ON public.extract_atoms_page_state USING btree (source_incarnation, content_hash, page_id) WHERE tombstoned",
"extract_atoms_transcript_state_pkey": "CREATE UNIQUE INDEX extract_atoms_transcript_state_pkey ON public.extract_atoms_transcript_state USING btree (source_id, file_path, content_hash)",
"extract_atoms_transcript_state_tombstoned_idx": "CREATE INDEX extract_atoms_transcript_state_tombstoned_idx ON public.extract_atoms_transcript_state USING btree (source_id, content_hash) WHERE tombstoned",
+ "fact_purges_all_subjects_idx": "CREATE INDEX fact_purges_all_subjects_idx ON public.fact_purges USING btree (source_id, purged_at) WHERE (subject = '*'::text)",
"fact_purges_pkey": "CREATE UNIQUE INDEX fact_purges_pkey ON public.fact_purges USING btree (source_id, visibility, subject, fact_hash)",
+ "fact_purges_subject_idx": "CREATE INDEX fact_purges_subject_idx ON public.fact_purges USING btree (source_id, subject, fact_hash) INCLUDE (visibility, purged_at)",
"fact_relink_attempts_outcome_idx": "CREATE INDEX fact_relink_attempts_outcome_idx ON public.fact_relink_attempts USING btree (source_id, outcome, attempted_at)",
"fact_relink_attempts_pkey": "CREATE UNIQUE INDEX fact_relink_attempts_pkey ON public.fact_relink_attempts USING btree (source_id, fact_id)",
"fact_withdrawals_pkey": "CREATE UNIQUE INDEX fact_withdrawals_pkey ON public.fact_withdrawals USING btree (source_id, visibility, subject, fact_hash)",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 2f639c7f72..5d4182e0ba 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -939,7 +939,9 @@
"extract_atoms_transcript_state_pkey": "CREATE UNIQUE INDEX extract_atoms_transcript_state_pkey ON public.extract_atoms_transcript_state USING btree (source_id, file_path, content_hash)",
"extract_atoms_transcript_state_tombstoned_idx": "CREATE INDEX extract_atoms_transcript_state_tombstoned_idx ON public.extract_atoms_transcript_state USING btree (source_id, content_hash) WHERE tombstoned",
"extract_rollup_7d_pkey": "CREATE UNIQUE INDEX extract_rollup_7d_pkey ON public.extract_rollup_7d USING btree (kind, source_id, day)",
+ "fact_purges_all_subjects_idx": "CREATE INDEX fact_purges_all_subjects_idx ON public.fact_purges USING btree (source_id, purged_at) WHERE (subject = '*'::text)",
"fact_purges_pkey": "CREATE UNIQUE INDEX fact_purges_pkey ON public.fact_purges USING btree (source_id, visibility, subject, fact_hash)",
+ "fact_purges_subject_idx": "CREATE INDEX fact_purges_subject_idx ON public.fact_purges USING btree (source_id, subject, fact_hash) INCLUDE (visibility, purged_at)",
"fact_relink_attempts_outcome_idx": "CREATE INDEX fact_relink_attempts_outcome_idx ON public.fact_relink_attempts USING btree (source_id, outcome, attempted_at)",
"fact_relink_attempts_pkey": "CREATE UNIQUE INDEX fact_relink_attempts_pkey ON public.fact_relink_attempts USING btree (source_id, fact_id)",
"fact_withdrawals_pkey": "CREATE UNIQUE INDEX fact_withdrawals_pkey ON public.fact_withdrawals USING btree (source_id, visibility, subject, fact_hash)",
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 73848111eb..9d3449d39a 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -939,7 +939,9 @@
"extract_atoms_transcript_state_pkey": "CREATE UNIQUE INDEX extract_atoms_transcript_state_pkey ON public.extract_atoms_transcript_state USING btree (source_id, file_path, content_hash)",
"extract_atoms_transcript_state_tombstoned_idx": "CREATE INDEX extract_atoms_transcript_state_tombstoned_idx ON public.extract_atoms_transcript_state USING btree (source_id, content_hash) WHERE tombstoned",
"extract_rollup_7d_pkey": "CREATE UNIQUE INDEX extract_rollup_7d_pkey ON public.extract_rollup_7d USING btree (kind, source_id, day)",
+ "fact_purges_all_subjects_idx": "CREATE INDEX fact_purges_all_subjects_idx ON public.fact_purges USING btree (source_id, purged_at) WHERE (subject = '*'::text)",
"fact_purges_pkey": "CREATE UNIQUE INDEX fact_purges_pkey ON public.fact_purges USING btree (source_id, visibility, subject, fact_hash)",
+ "fact_purges_subject_idx": "CREATE INDEX fact_purges_subject_idx ON public.fact_purges USING btree (source_id, subject, fact_hash) INCLUDE (visibility, purged_at)",
"fact_relink_attempts_outcome_idx": "CREATE INDEX fact_relink_attempts_outcome_idx ON public.fact_relink_attempts USING btree (source_id, outcome, attempted_at)",
"fact_relink_attempts_pkey": "CREATE UNIQUE INDEX fact_relink_attempts_pkey ON public.fact_relink_attempts USING btree (source_id, fact_id)",
"fact_withdrawals_pkey": "CREATE UNIQUE INDEX fact_withdrawals_pkey ON public.fact_withdrawals USING btree (source_id, visibility, subject, fact_hash)",
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 fda4a6067d..423b644953 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -939,7 +939,9 @@
"extract_atoms_transcript_state_pkey": "CREATE UNIQUE INDEX extract_atoms_transcript_state_pkey ON public.extract_atoms_transcript_state USING btree (source_id, file_path, content_hash)",
"extract_atoms_transcript_state_tombstoned_idx": "CREATE INDEX extract_atoms_transcript_state_tombstoned_idx ON public.extract_atoms_transcript_state USING btree (source_id, content_hash) WHERE tombstoned",
"extract_rollup_7d_pkey": "CREATE UNIQUE INDEX extract_rollup_7d_pkey ON public.extract_rollup_7d USING btree (kind, source_id, day)",
+ "fact_purges_all_subjects_idx": "CREATE INDEX fact_purges_all_subjects_idx ON public.fact_purges USING btree (source_id, purged_at) WHERE (subject = '*'::text)",
"fact_purges_pkey": "CREATE UNIQUE INDEX fact_purges_pkey ON public.fact_purges USING btree (source_id, visibility, subject, fact_hash)",
+ "fact_purges_subject_idx": "CREATE INDEX fact_purges_subject_idx ON public.fact_purges USING btree (source_id, subject, fact_hash) INCLUDE (visibility, purged_at)",
"fact_relink_attempts_outcome_idx": "CREATE INDEX fact_relink_attempts_outcome_idx ON public.fact_relink_attempts USING btree (source_id, outcome, attempted_at)",
"fact_relink_attempts_pkey": "CREATE UNIQUE INDEX fact_relink_attempts_pkey ON public.fact_relink_attempts USING btree (source_id, fact_id)",
"fact_withdrawals_pkey": "CREATE UNIQUE INDEX fact_withdrawals_pkey ON public.fact_withdrawals USING btree (source_id, visibility, subject, fact_hash)",
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 600960543c..fa0d1eb2af 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -3661,6 +3661,7 @@
{
"kind": "interface",
"members": [
+ "globalPurges?: GlobalPurgeMarker | undefined",
"page: Page",
"revision: string",
"sourceIncarnation: string",
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 221dc2fe35..054d9a14a5 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,6 +1,6 @@
{
"golden": {
- "count": 225,
+ "count": 226,
"gaps": [
17,
18,
@@ -9,6 +9,8 @@
],
"helpers": {
"ALIAS_TABLES": "cddd37c636af42d862c08ca7754a57dfe9d12576b769fa8f74a5f02c803f67a0",
+ "FACT_PURGES_ALL_SUBJECTS_INDEX": "99e2eb6c24134b539cb4cfd6e5ff66a724463525d09e9ba1fdde3c13f5787b6c",
+ "FACT_PURGES_SUBJECT_INDEX": "f4fba07082f2e26da3fa51b0b689f3fe78a3d09afd20c1924dbc2fbe6b1560f1",
"FACT_RELINK_TABLE_SQL": "1fdde4b99d0077365274096f294be64a992961c7b4544af794224de238b03630",
"FACT_UNLINKED_INDEX_SQL": "87dcf23c3fa570d93bfb214b6bbb024faa9ff9bff227aa78869a29580be03298",
"ISSUANCE_CLOCK_SLACK_SECONDS": "8f36c80392df6f9b9c754826289b63969d9d41ca8955213291e4413d614dce35",
@@ -39,7 +41,7 @@
"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5",
"verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"
},
- "latest": 230,
+ "latest": 231,
"records": [
{
"handler": {
@@ -3429,6 +3431,30 @@
"transaction": "absent",
"verify": "absent",
"version": 230
+ },
+ {
+ "handler": {
+ "form": "arrow",
+ "helpers": [
+ "FACT_PURGES_ALL_SUBJECTS_INDEX",
+ "FACT_PURGES_SUBJECT_INDEX",
+ "buildIndexOnline",
+ "dropInvalidConcurrentIndex",
+ "migrationNotice",
+ "quietMigrationNotices"
+ ],
+ "sha256": "13e51e81b20b251087af7c0e7b59f1dac434dbde7eedebc0f8312b346932f3f6"
+ },
+ "idempotent": true,
+ "name": "fact_purge_lookup_indexes",
+ "sql": {
+ "length": 0,
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 231
}
],
"versions": [
@@ -3656,7 +3682,8 @@
227,
228,
229,
- 230
+ 230,
+ 231
]
},
"normalizer": "migrations-record-v1"
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 caef96ba9c..314db54966 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -938,7 +938,9 @@
"extract_atoms_transcript_state_pkey": "CREATE UNIQUE INDEX extract_atoms_transcript_state_pkey ON public.extract_atoms_transcript_state USING btree (source_id, file_path, content_hash)",
"extract_atoms_transcript_state_tombstoned_idx": "CREATE INDEX extract_atoms_transcript_state_tombstoned_idx ON public.extract_atoms_transcript_state USING btree (source_id, content_hash) WHERE tombstoned",
"extract_rollup_7d_pkey": "CREATE UNIQUE INDEX extract_rollup_7d_pkey ON public.extract_rollup_7d USING btree (kind, source_id, day)",
+ "fact_purges_all_subjects_idx": "CREATE INDEX fact_purges_all_subjects_idx ON public.fact_purges USING btree (source_id, purged_at) WHERE (subject = '*'::text)",
"fact_purges_pkey": "CREATE UNIQUE INDEX fact_purges_pkey ON public.fact_purges USING btree (source_id, visibility, subject, fact_hash)",
+ "fact_purges_subject_idx": "CREATE INDEX fact_purges_subject_idx ON public.fact_purges USING btree (source_id, subject, fact_hash) INCLUDE (visibility, purged_at)",
"fact_relink_attempts_outcome_idx": "CREATE INDEX fact_relink_attempts_outcome_idx ON public.fact_relink_attempts USING btree (source_id, outcome, attempted_at)",
"fact_relink_attempts_pkey": "CREATE UNIQUE INDEX fact_relink_attempts_pkey ON public.fact_relink_attempts USING btree (source_id, fact_id)",
"fact_withdrawals_pkey": "CREATE UNIQUE INDEX fact_withdrawals_pkey ON public.fact_withdrawals USING btree (source_id, visibility, subject, fact_hash)",
diff --git a/test/fixtures/goldens/sql-text/chunks.json b/test/fixtures/goldens/sql-text/chunks.json
index 405d119bb7..8167d01ac3 100644
--- a/test/fixtures/goldens/sql-text/chunks.json
+++ b/test/fixtures/goldens/sql-text/chunks.json
@@ -980,8 +980,8 @@
"string",
"string"
],
- "sql": "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 AND p.deleted_at IS NULL ORDER BY (p.slug=$3) DESC, (p.source_id=$4) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_timeline FROM chosen p",
- "textSha256": "ce6044166b86d622eaf359ba7f7f9f2d943d075d0f813333ad3c6a9c2822b7e0"
+ "sql": "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 AND p.deleted_at IS NULL ORDER BY (p.slug=$3) DESC, (p.source_id=$4) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',count(*),'latest',max(g.purged_at)) FROM fact_purges g WHERE g.source_id=p.source_id AND g.subject='*' ) AS snapshot_global_purges, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_timeline FROM chosen p",
+ "textSha256": "993cf797541baa80446a98742479bda89242e72eb54f9e8907bb93abc6a33f52"
},
{
"lane": "tx",
diff --git a/test/fixtures/goldens/sql-text/links.json b/test/fixtures/goldens/sql-text/links.json
index 08eff7888a..3d098a5ea8 100644
--- a/test/fixtures/goldens/sql-text/links.json
+++ b/test/fixtures/goldens/sql-text/links.json
@@ -340,8 +340,8 @@
"string",
"string"
],
- "sql": "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 AND p.deleted_at IS NULL ORDER BY (p.slug=$3) DESC, (p.source_id=$4) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_timeline FROM chosen p",
- "textSha256": "ce6044166b86d622eaf359ba7f7f9f2d943d075d0f813333ad3c6a9c2822b7e0"
+ "sql": "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 AND p.deleted_at IS NULL ORDER BY (p.slug=$3) DESC, (p.source_id=$4) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',count(*),'latest',max(g.purged_at)) FROM fact_purges g WHERE g.source_id=p.source_id AND g.subject='*' ) AS snapshot_global_purges, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_timeline FROM chosen p",
+ "textSha256": "993cf797541baa80446a98742479bda89242e72eb54f9e8907bb93abc6a33f52"
},
{
"lane": "tx",
diff --git a/test/fixtures/goldens/sql-text/pages.json b/test/fixtures/goldens/sql-text/pages.json
index 05740f72e8..37f1148639 100644
--- a/test/fixtures/goldens/sql-text/pages.json
+++ b/test/fixtures/goldens/sql-text/pages.json
@@ -93,8 +93,8 @@
"string",
"string"
],
- "sql": "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 ORDER BY (p.slug=$3) DESC, (p.source_id=$4) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_timeline FROM chosen p",
- "textSha256": "373c5c9807f187e86e8367f6f5fd5f41f4bed3b454338972690891d52b1a8cf4"
+ "sql": "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 ORDER BY (p.slug=$3) DESC, (p.source_id=$4) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',count(*),'latest',max(g.purged_at)) FROM fact_purges g WHERE g.source_id=p.source_id AND g.subject='*' ) AS snapshot_global_purges, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_timeline FROM chosen p",
+ "textSha256": "818a857b11f36b6dd452a9c541a48c528ac9076678913130a00476598ccdbfbb"
},
{
"lane": "tx",
@@ -236,8 +236,8 @@
"string",
"string"
],
- "sql": "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.deleted_at IS NULL ORDER BY (p.slug=$2) DESC, (p.source_id=$3) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_timeline FROM chosen p",
- "textSha256": "c41012f9d1bcd636b94c7833af88684d0ea0646cb21dd764b112da50fe56cf13"
+ "sql": "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.deleted_at IS NULL ORDER BY (p.slug=$2) DESC, (p.source_id=$3) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',count(*),'latest',max(g.purged_at)) FROM fact_purges g WHERE g.source_id=p.source_id AND g.subject='*' ) AS snapshot_global_purges, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_timeline FROM chosen p",
+ "textSha256": "9132150173cc13f593f6673d1cf47d7cc85aee05f1ddb189cc7f5db92aace083"
}
],
"includeDeleted": [
@@ -248,8 +248,8 @@
"string",
"string"
],
- "sql": "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 ORDER BY (p.slug=$2) DESC, (p.source_id=$3) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_timeline FROM chosen p",
- "textSha256": "166f9934dad1afde257347e839ca0e6d1c2fcc21df871c55ffd14ebea1f673d9"
+ "sql": "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 ORDER BY (p.slug=$2) DESC, (p.source_id=$3) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',count(*),'latest',max(g.purged_at)) FROM fact_purges g WHERE g.source_id=p.source_id AND g.subject='*' ) AS snapshot_global_purges, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_timeline FROM chosen p",
+ "textSha256": "3865c9b875a969b6589067ccb5ebb2306dd32ec7278fba37a7de413a52970d3f"
}
],
"sourceId": [
@@ -261,8 +261,8 @@
"string",
"string"
],
- "sql": "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 AND p.deleted_at IS NULL ORDER BY (p.slug=$3) DESC, (p.source_id=$4) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_timeline FROM chosen p",
- "textSha256": "ce6044166b86d622eaf359ba7f7f9f2d943d075d0f813333ad3c6a9c2822b7e0"
+ "sql": "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 AND p.deleted_at IS NULL ORDER BY (p.slug=$3) DESC, (p.source_id=$4) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',count(*),'latest',max(g.purged_at)) FROM fact_purges g WHERE g.source_id=p.source_id AND g.subject='*' ) AS snapshot_global_purges, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_timeline FROM chosen p",
+ "textSha256": "993cf797541baa80446a98742479bda89242e72eb54f9e8907bb93abc6a33f52"
}
],
"sourceIds": [
@@ -274,8 +274,8 @@
"string",
"string"
],
- "sql": "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=ANY($2::text[]) AND p.deleted_at IS NULL ORDER BY (p.slug=$3) DESC, (p.source_id=$4) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_timeline FROM chosen p",
- "textSha256": "89af341a426c4c1da0e774a29c4a8de4fa8d8dd5d63245b7d3c6f89481c7fef9"
+ "sql": "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=ANY($2::text[]) AND p.deleted_at IS NULL ORDER BY (p.slug=$3) DESC, (p.source_id=$4) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',count(*),'latest',max(g.purged_at)) FROM fact_purges g WHERE g.source_id=p.source_id AND g.subject='*' ) AS snapshot_global_purges, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_timeline FROM chosen p",
+ "textSha256": "1dd267cd5a7595e0ec56808babd291c43ce6f47ed148e62a92442747102c2a47"
}
]
},
@@ -948,8 +948,8 @@
"string",
"string"
],
- "sql": "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 ORDER BY (p.slug=$3) DESC, (p.source_id=$4) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_timeline FROM chosen p",
- "textSha256": "373c5c9807f187e86e8367f6f5fd5f41f4bed3b454338972690891d52b1a8cf4"
+ "sql": "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 ORDER BY (p.slug=$3) DESC, (p.source_id=$4) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',count(*),'latest',max(g.purged_at)) FROM fact_purges g WHERE g.source_id=p.source_id AND g.subject='*' ) AS snapshot_global_purges, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_timeline FROM chosen p",
+ "textSha256": "818a857b11f36b6dd452a9c541a48c528ac9076678913130a00476598ccdbfbb"
},
{
"lane": "tx",
@@ -991,8 +991,8 @@
"string",
"string"
],
- "sql": "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.deleted_at IS NULL ORDER BY (p.slug=$2) DESC, (p.source_id=$3) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_timeline FROM chosen p",
- "textSha256": "c41012f9d1bcd636b94c7833af88684d0ea0646cb21dd764b112da50fe56cf13"
+ "sql": "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.deleted_at IS NULL ORDER BY (p.slug=$2) DESC, (p.source_id=$3) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',count(*),'latest',max(g.purged_at)) FROM fact_purges g WHERE g.source_id=p.source_id AND g.subject='*' ) AS snapshot_global_purges, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_timeline FROM chosen p",
+ "textSha256": "9132150173cc13f593f6673d1cf47d7cc85aee05f1ddb189cc7f5db92aace083"
}
],
"sourceId": [
@@ -1004,8 +1004,8 @@
"string",
"string"
],
- "sql": "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 AND p.deleted_at IS NULL ORDER BY (p.slug=$3) DESC, (p.source_id=$4) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_timeline FROM chosen p",
- "textSha256": "ce6044166b86d622eaf359ba7f7f9f2d943d075d0f813333ad3c6a9c2822b7e0"
+ "sql": "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 AND p.deleted_at IS NULL ORDER BY (p.slug=$3) DESC, (p.source_id=$4) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',count(*),'latest',max(g.purged_at)) FROM fact_purges g WHERE g.source_id=p.source_id AND g.subject='*' ) AS snapshot_global_purges, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_timeline FROM chosen p",
+ "textSha256": "993cf797541baa80446a98742479bda89242e72eb54f9e8907bb93abc6a33f52"
}
]
},
diff --git a/test/persistence-reconcile.test.ts b/test/persistence-reconcile.test.ts
index d3fbb66d0d..a6b8f913da 100644
--- a/test/persistence-reconcile.test.ts
+++ b/test/persistence-reconcile.test.ts
@@ -752,6 +752,37 @@ test('a fact withdrawn between reconciliation preparation and publication leaves
}
}), 120_000);
+// Subject-'*' purges ride the preview as a count/latest marker (page-state/types.ts GlobalPurgeMarker), not a list:
+// a '*' tombstone added after the preview, for a claim in the page or any other, makes the preview stale; an artifact
+// written before the marker existed reads stale too, never trusted.
+test("a subject-'*' purge recorded after the preview makes it stale; an artifact without the purge marker is stale", async () => isolated(async engine => {
+ const claim = 'purged after the reconciliation preview';
+ const fence = renderFactsTable([{ rowNum: 1, claim, kind: 'fact', confidence: 1, visibility: 'world', notability: 'medium', active: true, context: 'test evidence' }]);
+ const purgeAll = (sourceId: string, text: string) => engine.executeRaw(
+ "INSERT INTO fact_purges(source_id,visibility,subject,fact_hash) VALUES($1,'world','*',gbrain_fact_fingerprint($2))", [sourceId, text]);
+ for (const target of [claim, 'an unrelated claim purged everywhere']) {
+ const f = await fixture(engine, false, `Facts: ${fence}`), originalBytes = readFileSync(f.file);
+ await local(engine, f.registration, async () => {
+ const { preview } = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });
+ expect(preview.preimages.database).not.toHaveProperty('globalPurges');
+ await purgeAll(f.id, target);
+ await expect(runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview, request_id: randomUUID() })).rejects.toMatchObject({ code: 'source_changed' });
+ expect(readFileSync(f.file)).toEqual(originalBytes);
+ expect((await engine.readPageSnapshot(f.slug, { sourceId: f.id }))?.revision).toBe(f.snapshot.revision);
+ const fresh = (await runReconcilePreview(engine, { source_id: f.id, slug: f.slug })).preview;
+ expect(fresh.preimages.database.globalPurges).toMatchObject({ count: 1 });
+ // The purged row is still in the file but no longer in the database view, so that preview needs a decision.
+ if (target === claim) { expect(fresh.status).toBe('needs_resolution'); return; }
+ expect(fresh.status).toBe('ready');
+ const { globalPurges: _marker, ...legacyDatabase } = fresh.preimages.database;
+ const legacy = { ...fresh, preimages: { ...fresh.preimages, database: legacyDatabase } };
+ await expect(runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview: legacy as typeof fresh, request_id: randomUUID() }))
+ .rejects.toMatchObject({ code: 'source_changed' });
+ expect(readFileSync(f.file)).toEqual(originalBytes);
+ });
+ }
+}), 120_000);
+
// #6137: private fact rows are identified by (row number, claim), never by claim text alone.
type FenceRow = { rowNum: number; claim: string; visibility: 'private' | 'world'; context?: string; source?: string; confidence?: number; forgotten?: boolean };
const LONG_PRIVATE_CONTEXT = 'Told in confidence at the example offsite';
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 4f6310289b..0f06ed112f 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -97,6 +97,7 @@ test/persistence-sync-holds.test.ts
test/persistence-write-stall.test.ts
test/persistence-writer-fences.test.ts
test/purge-fact.test.ts
+test/purge-global-marker.test.ts
test/remediation-manual-only.test.ts
test/repair-embedding-effects.test.ts
test/repair-failed-writes-drift-w411.test.ts
diff --git a/test/purge-global-marker.test.ts b/test/purge-global-marker.test.ts
new file mode 100644
index 0000000000..5f1c862fbf
--- /dev/null
+++ b/test/purge-global-marker.test.ts
@@ -0,0 +1,143 @@
+/**
+ * Subject-'*' fact purges (purge_fact with all_subjects): the page snapshot
+ * carries a count/latest marker instead of aggregating the whole '*' ledger
+ * (GBRA-69: 4-5 ms per snapshot at 3,333 tombstones), and every overlay
+ * resolves '*' tombstones against the fence rows of the text it overlays.
+ *
+ * Protects: the snapshot drops a '*'-purged row still in stored text and
+ * lists it; a stale file that still carries a '*'-purged claim matches the
+ * snapshot (the page-prepare overlay of incoming bytes), so a coordinated
+ * write is not refused as drift; a stale import drops the row; remember of
+ * the claim under another entity refuses with purged_content and put_page
+ * drops its row; the marker follows the read's visibility filter. Real PGLite; Postgres too when
+ * DATABASE_URL is set. The reconcile-plan invalidation probe lives in
+ * test/persistence-reconcile.test.ts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { operations } from '../src/core/operations.ts';
+import { fileMatchesSnapshot } from '../src/core/persistence/page-prepare.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const TEA = 'Likes green tea';
+/** Each test purges its own claim: a '*' tombstone from one test would drop the next test's seed row. */
+const claimOf = (slug: string) => `Gate code of ${slug.split('/')[1]} is 7731`;
+const home = mkdtempSync(join(tmpdir(), 'gbrain-purge-global-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+
+const fence = (rows: string[]) => `<!--- gbrain:facts:begin -->
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|
+${rows.join('\n')}
+<!--- gbrain:facts:end -->`;
+const rowOf = (claim: string) => `| 1 | ${claim} | fact | 1.0 | world | medium | 2026-01-01 | | chat | |`;
+const ROW_TEA = `| 2 | ${TEA} | preference | 1.0 | world | medium | 2026-01-01 | | chat | |`;
+const pageBody = (slug: string) => {
+ const title = slug.split('/')[1]!;
+ return `---\ntitle: ${title}\ntype: person\n---\n# ${title}\n\nProse about ${title}.\n\n## Facts\n\n${fence([rowOf(claimOf(slug)), ROW_TEA])}\n`;
+};
+
+const ctx = (engine: BrainEngine): OperationContext => ({ engine, sourceId: 'default', remote: false, dryRun: false,
+ config: { engine: engine.kind }, logger: { info() {}, warn() {}, error() {} } } as OperationContext);
+const op = (name: string) => operations.find(o => o.name === name)!;
+
+async function codeOf(p: Promise<unknown>): Promise<string> {
+ try { await p; return 'ok'; } catch (e) { return e instanceof OperationError ? e.canonical ?? e.code : String((e as Error).message); }
+}
+
+/** Seed a page whose fence holds its claim and TEA, then purge the claim for every subject. */
+async function purgedEverywhere(engine: BrainEngine, slug: string): Promise<string> {
+ const claim = claimOf(slug);
+ await importFromContent(engine, slug, pageBody(slug), { noEmbed: true, sourceId: 'default' });
+ await runExtractFacts(engine, { slugs: [slug] });
+ const [row] = await engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE fact=$1 AND entity_slug=$2', [claim, slug]);
+ const purge = op('purge_fact');
+ const dry = await purge.handler(ctx(engine), { id: Number(row!.id), all_subjects: true, dry_run: true }) as Record<string, any>;
+ const done = await purge.handler(ctx(engine), { id: Number(row!.id), all_subjects: true, confirm: dry.confirm_token,
+ expected_revision: dry.expected_revision, request_id: randomUUID() }) as Record<string, any>;
+ expect(done.state).toBe('committed');
+ expect(done.purge.subject).toBe('*');
+ return claim;
+}
+
+beforeAll(async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+ for (const engine of engines) await registerLocalWriter(engine, 'cli');
+}), 120_000);
+afterAll(async () => { await engines[0]?.disconnect(); await closePostgres?.(); rmSync(home, { recursive: true, force: true }); });
+
+describe("subject-'*' purges resolve per overlay", () => {
+ test('the snapshot carries a marker, lists no unrelated tombstone, and drops a purged row still in stored text', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ await engine.executeRaw('DELETE FROM fact_purges');
+ const slug = 'people/dana-example';
+ const claim = await purgedEverywhere(engine, slug);
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;
+ expect(snapshot.globalPurges).toMatchObject({ count: 1, world_only: false });
+ expect(typeof snapshot.globalPurges!.latest).toBe('string');
+ expect(snapshot.withdrawals.filter(w => w.purged)).toEqual([]);
+ expect(snapshot.page.compiled_truth).not.toContain(claim);
+ expect((await engine.readPageSnapshot(slug, { sourceId: 'default', excludePrivate: true }))!.globalPurges).toMatchObject({ count: 1, world_only: true });
+
+ // A '*' tombstone naming a claim the stored text still holds: the snapshot drops the row and lists the tombstone.
+ await engine.executeRaw(`INSERT INTO fact_purges(source_id,visibility,subject,fact_hash) VALUES ('default','world','*',gbrain_fact_fingerprint($1))`, [TEA]);
+ try {
+ const after = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;
+ expect(after.globalPurges).toMatchObject({ count: 2 });
+ expect(after.page.compiled_truth).not.toContain(TEA);
+ expect(after.withdrawals.filter(w => w.purged)).toHaveLength(1);
+ const [stored] = await engine.executeRaw<{ compiled_truth: string }>(`SELECT compiled_truth FROM pages WHERE source_id='default' AND slug=$1`, [slug]);
+ expect(stored!.compiled_truth).toContain(TEA);
+ } finally {
+ await engine.executeRaw(`DELETE FROM fact_purges WHERE fact_hash=gbrain_fact_fingerprint($1)`, [TEA]);
+ }
+ }
+ }), 60_000);
+
+ test('a stale file still carrying the claim matches the snapshot (page-prepare overlay of incoming bytes); new prose does not', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const slug = 'people/erin-example';
+ await purgedEverywhere(engine, slug);
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;
+ expect(snapshot.withdrawals.filter(w => w.purged)).toEqual([]);
+ expect(await fileMatchesSnapshot(engine, slug, pageBody(slug), snapshot)).toBe(true);
+ expect(await fileMatchesSnapshot(engine, slug, pageBody(slug) + '\nAn uncoordinated local edit.\n', snapshot)).toBe(false);
+ }
+ }), 60_000);
+
+ test('a stale import drops the row; remember of the claim under another entity refuses with purged_content and put_page drops it', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const slug = 'people/finn-example';
+ const claim = await purgedEverywhere(engine, slug);
+ await importFromContent(engine, slug, pageBody(slug) + '\nEdited.\n', { noEmbed: true, sourceId: 'default' });
+ const [page] = await engine.executeRaw<{ compiled_truth: string }>(`SELECT compiled_truth FROM pages WHERE source_id='default' AND slug=$1`, [slug]);
+ expect(page!.compiled_truth).not.toContain(claim);
+ expect(page!.compiled_truth).toContain(TEA);
+ expect(await codeOf(op('remember').handler(ctx(engine), { fact: claim, entity: 'people/other-example', provenance: 'test', request_id: randomUUID() })))
+ .toBe('purged_content');
+ const put = await codeOf(op('put_page').handler(ctx(engine), { slug: 'people/other-example', request_id: randomUUID(),
+ content: `---\ntitle: Other\ntype: person\n---\n# Other\n\n## Facts\n\n${fence([rowOf(claim)])}\n` }));
+ const [other] = await engine.executeRaw<{ compiled_truth: string }>(`SELECT compiled_truth FROM pages WHERE source_id='default' AND slug='people/other-example'`);
+ // put_page saves the page with the purged row dropped by the import overlay; the claim never lands.
+ expect(put).toBe('ok');
+ expect(other!.compiled_truth).not.toContain(claim);
+ expect(await engine.executeRaw('SELECT 1 FROM facts WHERE fact=$1', [claim])).toHaveLength(0);
+ }
+ }), 60_000);
+});