Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Lane A: projection and chunk integrity fixes for segmented storage (Wave B PR 2)

garrytan32fc0640693e
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.md
index 0eb0888711..d59fe5d617 100644
--- a/docs/architecture/key-files/memory-purge.md
+++ b/docs/architecture/key-files/memory-purge.md
@@ -13,7 +13,7 @@ User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#pu
- `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; the fact purge's planning read) / `findRequestsForSlugs` (index-served by `persistence_requests_slug_intent`), the page purge's preparation-time journal census `sweepRequestsCarrying` (#6511: a keyset walk of the source's journal in `JOURNAL_SWEEP_CHUNK_ROWS` chunks, every needle in raw and JSON-escaped form against intent, outcome, error detail and message, compacted rows included, the purge's own row excluded, stopped by the claim clock between chunks and at `JOURNAL_SWEEP_MATCH_CAP`; returns the carrying ids, the ids pending at the scan, the `sequence` ceiling as text and `complete`) with `recheckRequestsCarrying` for the publication's bounded re-check of the tail past the ceiling and of the rows that were pending, `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. `findRequestsHoldingStagings` / `cancelRequestsHoldingStagings`: the queued requests whose `intent.body_ref.staging_id` names a staging a fact purge aborts are completed `cancelled` with `purged_content`.
- `src/core/persistence/purged-intent.ts` — `intentCarriesPurgedContent`: `completeWrite` (journal.ts) nulls the intent of any terminal request whose content (`fact`, `claim`, page fence rows, or the page's content hash) matches a subject-scoped purge tombstone, and of any refusal coded `purged_content`; a write refused for another reason, or committed as a no-op after the overlay dropped purged rows, keeps no copy. Only content-bearing intents are checked, and whether the source holds any tombstone is selected by completeWrite's terminal statement itself (`PURGE_PRESENCE_COLUMNS`), so the hook adds no statement to a write on a source without tombstones (#6007 budget). `purged_content` is a write error code, so receipts and the frozen verb path (wire `invalid_params`, canonical `purged_content`) keep it typed.
-- `src/core/persistence/page-purge.ts` — `purgePageInTransaction`, called by the `delete_page purge:true` apply in `page-prepare.ts`: records in `page_purges` the content hash of the page and of every retained version (up to 1000), each as imported and as purge-overlaid, so an older version is refused too; drops the decide rows, trust proposals, gate holds (by slug) and gate receipts naming the page or its rows and clears legacy `query_cache`; tombstones and deletes facts filed on the page, tombstones its takes, deletes take proposals, open loops, core notices and `files` rows, the page's `page_aliases` and the `slug_aliases` redirects whose `canonical_slug` is the page (#6619; a redirect from this slug to another page stays; counted in `removed` and checked by slug in the receipt), redacts finished intents for the slug and the carrying ids the preparation sweep found plus the publication's tail and pending re-check (#6511: `preparePagePurge` runs `readPurgeClaims` and `sweepRequestsCarrying` under the preparation budget at steps `purge_claims` / `purge_journal_sweep`, so the O(journal) substring scan is a charged `preparation_deadline` release and `preparation_stalled` at the attempt limit, never a transaction timeout; the lookups that stay inside the transaction go through `lookup`, which maps a 57014 to the terminal, non-retryable `purge_lookup_timeout` naming `gbrain repair request-indexes` only when `persistence_requests_slug_intent` is missing or INVALID; the receipt's `journal_sweep` reports `ceiling`, `scanned`, `tail`, `pending_rechecked` and `complete`), then deletes the page (FK cascades). `PURGE_RESIDUALS` names what stays out of reach. `finishPagePurge` deletes stored blobs after commit, lists any left by storage path, and attaches `receipt`, the store-by-store receipt from `verifyPagePurge` (same shape as the fact receipt: residuals first, every swept inventory store, other pages' prose naming a purged claim as `source_prose`); the page's claims used as needles live only in process memory, and a same-id replay returns the result built when the purge ran. `residuals` stays the prose string. `readPagePurgeTombstones` feeds `screenImportContent({ purgedPages })` from managed sync's freeze-time screen (`sync-screen.ts`, one read per run) and publication (`sync-prepare.ts`), which hold a matching file as `purged_content`; direct imports and `put_page` hit the pages guard instead; `listPagePurges` / `unpurgePage` (also clears the fact and take tombstones of the same request) back the owner-only ops. Pinned by `test/page-purge.test.ts` and `test/page-purge-journal-timeout-6511.test.ts` (both engines; seams `purge:*` in `fault-points.ts`). #6368: a purge of a tombstone whose file matches `sync.exclude` (discovery's globs via `syncExcludePatterns` in `sync-discovery.ts`, matched relative to the source root) owns no file: `prepareFileTarget`'s `excludeTombstone` option returns no target, the purge is database-only and the receipt says `write_through.skipped: 'sync_excluded'`; the file is neither compared nor removed (an unchanged excluded file used to be deleted, an edited one refused forever). The apply re-reads the exclusion inside the publication transaction and refuses `source_changed` if it was removed meanwhile. Live-page purges and soft deletes are unchanged. A segmented page or version is never loaded whole: its stored `content_hash` and the purge-overlaid hash streamed by `rewrittenContentHash` are tombstoned; its stagings (by slug or page id) and the segment texts only its manifests referenced are deleted in the purge transaction (`removed.page_body_manifest` / `page_body_stagings` / `page_segment_texts`).
+- `src/core/persistence/page-purge.ts` — `purgePageInTransaction`, called by the `delete_page purge:true` apply in `page-prepare.ts`: records in `page_purges` the content hash of the page and of every retained version (up to 1000), each as imported and as purge-overlaid, so an older version is refused too; drops the decide rows, trust proposals, gate holds (by slug) and gate receipts naming the page or its rows and clears legacy `query_cache`; tombstones and deletes facts filed on the page, tombstones its takes, deletes take proposals, open loops, core notices and `files` rows, the page's `page_aliases` and the `slug_aliases` redirects whose `canonical_slug` is the page (#6619; a redirect from this slug to another page stays; counted in `removed` and checked by slug in the receipt), redacts finished intents for the slug and the carrying ids the preparation sweep found plus the publication's tail and pending re-check (#6511: `preparePagePurge` runs `readPurgeClaims` and `sweepRequestsCarrying` under the preparation budget at steps `purge_claims` / `purge_journal_sweep`, so the O(journal) substring scan is a charged `preparation_deadline` release and `preparation_stalled` at the attempt limit, never a transaction timeout; the lookups that stay inside the transaction go through `lookup`, which maps a 57014 to the terminal, non-retryable `purge_lookup_timeout` naming `gbrain repair request-indexes` only when `persistence_requests_slug_intent` is missing or INVALID; the receipt's `journal_sweep` reports `ceiling`, `scanned`, `tail`, `pending_rechecked` and `complete`), then deletes the page (FK cascades). `PURGE_RESIDUALS` names what stays out of reach. `finishPagePurge` deletes stored blobs after commit, lists any left by storage path, and attaches `receipt`, the store-by-store receipt from `verifyPagePurge` (same shape as the fact receipt: residuals first, every swept inventory store, other pages' prose naming a purged claim as `source_prose`); the page's claims used as needles live only in process memory, and a same-id replay returns the result built when the purge ran. `residuals` stays the prose string. `readPagePurgeTombstones` feeds `screenImportContent({ purgedPages })` from managed sync's freeze-time screen (`sync-screen.ts`, one read per run) and publication (`sync-prepare.ts`), which hold a matching file as `purged_content`; direct imports and `put_page` hit the pages guard instead; `listPagePurges` / `unpurgePage` (also clears the fact and take tombstones of the same request) back the owner-only ops. Pinned by `test/page-purge.test.ts` and `test/page-purge-journal-timeout-6511.test.ts` (both engines; seams `purge:*` in `fault-points.ts`). #6368: a purge of a tombstone whose file matches `sync.exclude` (discovery's globs via `syncExcludePatterns` in `sync-discovery.ts`, matched relative to the source root) owns no file: `prepareFileTarget`'s `excludeTombstone` option returns no target, the purge is database-only and the receipt says `write_through.skipped: 'sync_excluded'`; the file is neither compared nor removed (an unchanged excluded file used to be deleted, an edited one refused forever). The apply re-reads the exclusion inside the publication transaction and refuses `source_changed` if it was removed meanwhile. Live-page purges and soft deletes are unchanged. A segmented page or version is never loaded whole: its stored `content_hash` and the purge-overlaid hash streamed by `rewrittenContentHash` are tombstoned; its stagings (by slug or page id) and the segment texts only its manifests referenced are deleted in the purge transaction (`removed.page_body_manifest` / `page_body_stagings` / `page_segment_texts`), except a text another page's live staging recorded in `page_body_staging_texts` (an unpublished create or replace still needs it; `stagingNeedsTextSql`, also applied by the 72-hour hard delete and the receipt's text probe).
- `src/core/ops/purge.ts` — `purge_fact`, `list_page_purges`, `unpurge_page`: admin scope, `cliOnly` (every MCP route gets `trusted_local_only`). The resident owner runs them only for its verified local CLI registration (`LOCAL_CLI_OWNER_OPERATIONS` in `persistence/ipc.ts`, checked in `persistence/provider.ts`).
- `src/commands/forget-purge.ts` + `src/commands/pages-purges.ts` — the CLI fronts. `runForgetPurge` always runs the dry run, then a typed token on a terminal or `--yes` plus `--request-id` without one; `--match` lists ids, `--status` polls completion; `PURGE_FAMILY_HELP` is the purge-family table shown by `gbrain forget --help`. `gbrain pages purges list` and `gbrain pages unpurge <slug>` run the page-tombstone ops as the trusted CLI.
diff --git a/scripts/check-engine-sql-dynamic.ts b/scripts/check-engine-sql-dynamic.ts
index d8a5b64357..3b2951c8bd 100644
--- a/scripts/check-engine-sql-dynamic.ts
+++ b/scripts/check-engine-sql-dynamic.ts
@@ -72,6 +72,7 @@ const VETTED_BUILDERS: Record<string, string> = {
privateSnapshotFilterFragment: 'src/core/search/private-visibility.ts: constant snapshot visibility predicate over a caller alias',
rederiveHiddenSql: 'src/core/eligibility/sql.ts: constant needs_rederive NOT EXISTS predicate over a literal table name and caller alias; no values',
privateProvenanceFilterFragment: 'src/core/search/private-visibility.ts: constant fact-provenance visibility predicate over a caller alias',
+ stagingNeedsTextSql: 'src/core/page-body/schema.ts: constant live-staging text-reference EXISTS predicate over a caller text alias; no values (Wave B purge)',
rankingLinkSql: 'src/core/link-ranking-policy.ts: constant non-ranking link-type predicate (code-constant type names) over a caller alias',
vectorLiteralSql: 'src/core/engine-sql/facts.ts: master\'s inlined vector literal; toPgVectorLiteral output (numbers joined by commas) + a ::vector/::halfvec constant',
temporalLinkJoinSql: 'src/core/link-validity.ts: constant LEFT JOIN onto link_relationships over a caller alias; scope is one of two literals',
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index af6c9e3b93..ccfcf7c698 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -660,6 +660,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: 'TBD', text: '`delete_page` (soft and `purge: true`), `restore_page`, `gbrain delete` and `gbrain restore` now work on a page over 24 MiB on a source backed by files: the file is compared with the page by digest, streamed, and a file edited on disk still refuses as before. Restoring such a page clears its deletion without re-importing it and writes its file back from the database; the 25 MiB pre-push scan cap on written files still applies, and a core page or an external_untrusted writer still refuses.' },
{ since: 'TBD', text: 'A write that stores a page in segments says in its receipt whether search sees it: `searchable: true` when it commits (every new page up to 4 MiB and every rewrite), or `searchable: "pending"` for a larger new page while its chunks are built after commit, with `searchable_retry_after_ms` and a `searchable_fix` that reads the receipt again (`get_write_request`) until it says `searchable: true`. A new page up to 4 MiB was previously searchable only once a post-commit build finished.' },
{ since: 'TBD', text: '`gbrain projections drain` now builds pages stored in segments whose post-commit build never ran or died, skipping one another process is still building (claim renewed within 60 s), so a brain with no resident writer can make a large new page searchable. A pending receipt\'s `searchable_fix` names it as the fallback after the re-read wait, and doctor `text_projection_readiness` counts such pages (`segmented_pending`) and points to it.' },
+ { since: 'TBD', text: 'A page purge (`delete_page` with `purge: true`, `gbrain delete --purge` and the 72-hour hard delete of soft-deleted pages) of a page stored in segments no longer breaks another page\'s write that is still being prepared with some of the same text: the purge keeps exactly the segment texts such a write staged, and still deletes every other text only the purged page used. `restore_page` of a page over 24 MiB whose old chunks were still waiting to be removed returns `projection: "pending"` and makes the page searchable once they are gone, instead of showing the old text in search.' },
{ since: 'TBD', text: 'Chunks of a page stored in segments keep a Markdown heading with the text after it, so a section appended after a full last chunk re-embeds only its own chunk (was two). Inline pages chunk as before.' },
];
diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.ts
index bf2deeb003..1b256b0946 100644
--- a/src/core/deletion-inventory.ts
+++ b/src/core/deletion-inventory.ts
@@ -107,6 +107,7 @@ const ROWS: readonly Row[] = [
['page_body_manifest', 'swept', 'segment_manifest', 'region source_id sha256 cut_kind entry_state protected_regions facts_slots outline hash_state'],
['page_body_staging_parts', 'swept', 'body_stagings', 'sha256 body', 'body'],
['page_body_stagings', 'swept', 'body_stagings', 'kind principal_kind principal_id source_id slug mode declared_sha256 state'],
+ ['page_body_staging_texts', 'swept', 'body_stagings', 'source_id sha256'],
['page_embedding_budget', 'out_of_scope', 'no_memory_text', 'state reason embedding_signature'],
['page_extraction_state', 'out_of_scope', 'no_memory_text', 'pipeline watermark_sha256 input_truncated'],
['page_facts_reconcile', 'out_of_scope', 'no_memory_text', 'outcome'],
diff --git a/src/core/engine-sql/page-body.ts b/src/core/engine-sql/page-body.ts
index 7055ec9c40..f7d09d087d 100644
--- a/src/core/engine-sql/page-body.ts
+++ b/src/core/engine-sql/page-body.ts
@@ -58,7 +58,13 @@ export async function allocateBodyOccurrenceIds(exec: SqlExecutor, count: number
return rows.map(row => Number(row.id));
}
-export async function stageSegmentTexts(exec: SqlExecutor, sourceId: string, texts: readonly SegmentTextInput[]): Promise<{ inserted: number }> {
+/**
+ * With `stagingId`, each batch first records its texts under the staging (page_body_staging_texts), so a page purge
+ * that runs while the write is unpublished keeps them; recorded before the upsert, a text a purge deleted in between is
+ * inserted again by it.
+ */
+export async function stageSegmentTexts(exec: SqlExecutor, sourceId: string, texts: readonly SegmentTextInput[],
+ opts: { stagingId?: string } = {}): Promise<{ inserted: number }> {
const maxBytes = stageBatchBytes(exec);
const maxRows = Math.floor(exec.capabilities.maxBindParamsPerStatement / 5);
let inserted = 0;
@@ -67,6 +73,8 @@ export async function stageSegmentTexts(exec: SqlExecutor, sourceId: string, tex
let batchBytes = 0;
const flush = async () => {
if (batch.length === 0) return;
+ if (opts.stagingId !== undefined) await exec.run(sqlFragment`INSERT INTO page_body_staging_texts (staging_id, source_id, sha256)
+ SELECT ${opts.stagingId}::uuid, ${sourceId}, decode(h, 'hex') FROM unnest(${[...batchShas]}::text[]) AS h ON CONFLICT DO NOTHING`);
const { rows } = await exec.run<{ inserted: boolean }>(sqlFragment`INSERT INTO page_segment_texts (source_id, sha256, byte_len, line_count, body)
VALUES ${joinFragments(batch, ', ')} ON CONFLICT (source_id, sha256) DO UPDATE SET created_at = now() RETURNING (xmax = 0) AS inserted`);
inserted += rows.filter(row => row.inserted).length;
@@ -191,7 +199,15 @@ export async function stageSegmentChunks(exec: SqlExecutor, pageId: number, gene
const { rows: pages } = await tx.run<{ body_generation: unknown; body_storage: string; slug: string }>(sqlFragment`
SELECT body_generation, body_storage, slug FROM pages WHERE id = ${pageId}`);
const live = Number(pages[0]?.body_generation);
- if (!pages[0] || generation < live || (generation === live && pages[0].body_storage !== 'segmented')) {
+ // At the live generation only occurrences its published manifest holds take rows: a preparation that lost the flip to
+ // another write of the same generation still holds its own (unpublished) occurrences, and a row of one would be
+ // searchable on the sealed page (chunkVisibleFilter reads the generation alone).
+ const unpublished = pages[0]?.body_storage === 'segmented' && generation === live && (await tx.run(sqlFragment`
+ SELECT 1 FROM unnest(${[...new Set(chunks.map(chunk => chunk.occurrence_id))]}::bigint[]) AS o(id)
+ WHERE NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.page_id = ${pageId} AND m.occurrence_id = o.id AND m.staging_id IS NULL
+ AND m.gen_from <= ${generation}::bigint AND (m.gen_to IS NULL OR m.gen_to > ${generation}::bigint))
+ LIMIT 1`)).rows.length > 0;
+ if (!pages[0] || generation < live || (generation === live && pages[0].body_storage !== 'segmented') || unpublished) {
throw opError('revision_changed', `Page ${pages[0]?.slug ?? pageId} moved to body generation ${pages[0] ? live : 'none'} while chunks for generation ${generation} were staged.`,
'Another write published first. Read the page again and repeat this write against its current revision.',
{ legacy_error: 'invalid_params', detail: JSON.stringify({ staged_generation: generation, current_generation: pages[0] ? live : null }) });
@@ -394,6 +410,14 @@ export async function sweepSegments(exec: SqlExecutor, opts: SegmentSweepOptions
WHERE c.page_id = p.id AND ${pageScope} AND c.body_generation IS NOT NULL AND c.body_generation > p.body_generation
AND NOT EXISTS (SELECT 1 FROM page_body_manifest m
WHERE m.page_id = c.page_id AND m.occurrence_id = c.occurrence_id AND m.staging_id::text IN ${liveStagingIds})`);
+ // Rows at or below the live generation of an occurrence that only a dead staging owns: a preparation that lost the flip
+ // to another write of its generation and staged a late batch before stageSegmentChunks refused one. Found through the
+ // dead staging's manifest rows (deleted next), so the sweep's cost is the garbage's, not the page's.
+ const { affectedRows: orphanedChunksDeleted } = await exec.run(sqlFragment`DELETE FROM content_chunks c USING page_body_manifest d, pages p
+ WHERE d.page_id = p.id AND ${pageScope} AND d.staging_id IS NOT NULL AND d.staging_id::text NOT IN ${liveStagingIds}
+ AND c.page_id = d.page_id AND c.occurrence_id = d.occurrence_id AND c.body_generation IS NOT NULL AND c.body_generation <= p.body_generation
+ AND NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.page_id = c.page_id AND m.occurrence_id = c.occurrence_id
+ AND (m.staging_id IS NULL OR m.staging_id::text IN ${liveStagingIds}))`);
const released = new Set<string>();
const returning = opts.pageId !== undefined ? sqlFragment`RETURNING encode(m.sha256, 'hex') AS sha` : sqlFragment``;
const { rows: stagedRows, affectedRows: stagedRowsDeleted } = await exec.run<{ sha: string }>(sqlFragment`DELETE FROM page_body_manifest m USING pages p
@@ -416,5 +440,5 @@ export async function sweepSegments(exec: SqlExecutor, opts: SegmentSweepOptions
AND NOT EXISTS (SELECT 1 FROM page_body_stagings s WHERE s.source_id = t.source_id AND s.created_at <= t.created_at
AND s.id::text IN ${liveStagingIds})
FOR UPDATE SKIP LOCKED)`)).affectedRows;
- return { retiredChunksDeleted, manifestRowsDeleted: stagedRowsDeleted + closedRowsDeleted, textsDeleted, stagingsExpired };
+ return { retiredChunksDeleted: retiredChunksDeleted + orphanedChunksDeleted, manifestRowsDeleted: stagedRowsDeleted + closedRowsDeleted, textsDeleted, stagingsExpired };
}
diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.ts
index 7767b850e4..ae0c9f9628 100644
--- a/src/core/engine-sql/pages.ts
+++ b/src/core/engine-sql/pages.ts
@@ -31,6 +31,7 @@ import { jsonbParam, type SqlExecutor } from './executor.ts';
import type { LegacyUnscopedRead, ScopedRead } from './brands.ts';
import type { ScopedReadRunner } from './cjk-search.ts';
import { compileRowNormalizer } from './normalize.ts';
+import { stagingNeedsTextSql } from '../page-body/schema.ts';
import { renderFragment, sqlFragment, trustedSql } from './fragment.ts';
import { quoteIdentifier, resolveWriteColumnFromConfigRows } from '../search/embedding-column.ts';
@@ -327,7 +328,8 @@ export async function purgeDeletedPages(
if (texts.length) await tx.run(sqlFragment`DELETE FROM page_segment_texts t
USING unnest(${texts.map(r => r.source_id)}::text[], ${texts.map(r => r.sha)}::text[]) AS d(source_id, sha)
WHERE t.source_id = d.source_id AND t.sha256 = decode(d.sha, 'hex')
- AND NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.source_id = t.source_id AND m.sha256 = t.sha256)`);
+ AND NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.source_id = t.source_id AND m.sha256 = t.sha256)
+ AND NOT ${trustedSql(stagingNeedsTextSql('t'))}`);
const slugs = rows.map((r) => r.slug);
return { slugs, count: slugs.length };
});
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 0f81c39c0a..2df117809b 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -2376,8 +2376,8 @@ export interface BrainEngine {
// Segmented page storage (Wave B; SQL in engine-sql/page-body.ts). Called only when pages.segmented_storage is on.
/** `count` fresh manifest occurrence ids from one sequence; never reused. */
allocateBodyOccurrenceIds(count: number): Promise<number[]>;
- /** Insert segment texts for one source, `ON CONFLICT DO NOTHING`, in statements bounded by STAGE_BATCH_BYTES. */
- stageSegmentTexts(sourceId: string, texts: readonly SegmentTextInput[]): Promise<{ inserted: number }>;
+ /** Insert segment texts for one source, `ON CONFLICT DO NOTHING`, in statements bounded by STAGE_BATCH_BYTES; with `stagingId`, record them as that staging's (a page purge keeps them while it is live). */
+ stageSegmentTexts(sourceId: string, texts: readonly SegmentTextInput[], opts?: { stagingId?: string }): Promise<{ inserted: number }>;
/** Segment texts by sha256 for one source, keyed by lowercase hex; missing shas are absent. */
readSegmentTexts(sourceId: string, sha256s: readonly Uint8Array[]): Promise<Map<string, Uint8Array>>;
/** Insert manifest rows (staged rows carry `stagingId`), in bounded statements. */
diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.ts
index 57386b119b..5e991f9d85 100644
--- a/src/core/facts/purge-verify.ts
+++ b/src/core/facts/purge-verify.ts
@@ -27,6 +27,7 @@ import { DELETION_INVENTORY, OUT_OF_REACH_RESIDUALS, type InventoryEntry } from
import type { PurgePlan, PurgeTarget } from './purge.ts';
import { gitChildEnv } from '../git-env.ts';
import { segmentedBodyContains } from '../page-body/segment-rewrite.ts';
+import { stagingNeedsTextSql } from '../page-body/schema.ts';
export type StoreCount = Record<string, number>;
export type StoreStatus = 'deleted' | 'would_remove' | 'retained_inactive' | 'unverified' | 'out_of_reach' | 'out_of_scope' | 'not_present' | 'incomplete';
@@ -390,7 +391,7 @@ export async function verifyPagePurge(engine: BrainEngine, input: { sourceId: st
await keyed('query_cache', 'SELECT 1 FROM query_cache WHERE $1::text IS NOT NULL', [src]);
if (context?.segmentShas.length) await keyed('page_segment_texts', `SELECT 1 FROM page_segment_texts t WHERE t.source_id=$1
AND t.sha256=ANY(SELECT decode(h,'hex') FROM unnest($2::text[]) AS h)
- AND NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.source_id=t.source_id AND m.sha256=t.sha256)`, [src, context.segmentShas]);
+ AND NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.source_id=t.source_id AND m.sha256=t.sha256) AND NOT ${stagingNeedsTextSql('t')}`, [src, context.segmentShas]);
if (context) {
const refs = context.factIds.map(String);
for (const table of ['decide_review_queue', 'decide_review_proposals']) await keyed(table, `SELECT 1 FROM ${table} WHERE source_id=$1 AND (a_ref=ANY($2::text[]) OR b_ref=ANY($2::text[]))`, [src, refs]);
diff --git a/src/core/page-body/ingest.ts b/src/core/page-body/ingest.ts
index 75e98159be..77c8f74e64 100644
--- a/src/core/page-body/ingest.ts
+++ b/src/core/page-body/ingest.ts
@@ -237,7 +237,7 @@ async function stageBody(engine: BrainEngine, input: SegmentedBodyInput, staging
const flushTexts = async () => {
if (!pending.length) return;
const batch = pending.splice(0);
- await writes(exec => exec.stageSegmentTexts(input.sourceId, batch));
+ await writes(exec => exec.stageSegmentTexts(input.sourceId, batch, { stagingId }));
collectBatchGarbage();
pendingBytes = 0;
if (engine.kind === 'pglite') await new Promise(resolve => setImmediate(resolve));
diff --git a/src/core/page-body/projection.ts b/src/core/page-body/projection.ts
index 187f36042f..6024193e91 100644
--- a/src/core/page-body/projection.ts
+++ b/src/core/page-body/projection.ts
@@ -46,21 +46,38 @@ async function readProjectionPage(engine: Pick<BrainEngine, 'executeRaw'>, ref:
return page ?? null;
}
-/** Delete, in bounded batches, chunk rows the live generation does not hold: other occurrences, inline rows, older duplicates. */
-async function retireStaleChunks(engine: Pick<BrainEngine, 'executeRaw' | 'kind'>, pageId: number, generation: number, live: readonly number[]): Promise<number> {
+/** Chunk rows of page $1 that generation $2 (live occurrences $3) does not hold: other occurrences, inline rows, older duplicates. */
+const STALE_CHUNKS_SQL = `SELECT s.id FROM content_chunks s -- chunk-visibility-ok: retirement selects the rows the live generation does not hold
+ WHERE s.page_id=$1
+ AND (s.body_generation IS NULL
+ OR (s.body_generation<=$2 AND NOT (s.occurrence_id=ANY($3::bigint[])))
+ OR (s.body_generation<=$2 AND EXISTS (SELECT 1 FROM content_chunks n WHERE n.page_id=s.page_id AND n.occurrence_id=s.occurrence_id
+ AND n.body_generation>s.body_generation AND n.body_generation<=$2)))`;
+
+/** The page still stores a chunk row its live generation does not hold (a deferred retirement): sealing it would show the row. */
+export async function hasStaleChunks(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number, generation: number, live: readonly number[]): Promise<boolean> {
+ return (await engine.executeRaw(`${STALE_CHUNKS_SQL} LIMIT 1`, [pageId, generation, live])).length > 0;
+}
+
+/**
+ * Delete, in bounded batches, chunk rows the live generation does not hold: other occurrences, inline rows, older
+ * duplicates. Each batch re-reads the page under its page lock and deletes only while the page is still segmented at
+ * `generation` (a demotion's inline rows are the page's live chunks); `moved` when it was not.
+ */
+async function retireStaleChunks(engine: BrainEngine, ref: { sourceId: string; slug: string }, pageId: number, generation: number,
+ live: readonly number[]): Promise<{ retired: number; moved: boolean }> {
let retired = 0;
for (;;) {
- const rows = await engine.executeRaw<{ id: number }>(`DELETE FROM content_chunks c
- WHERE c.id IN (SELECT s.id FROM content_chunks s -- chunk-visibility-ok: retirement selects the rows the live generation does not hold
- WHERE s.page_id=$1
- AND (s.body_generation IS NULL
- OR (s.body_generation<=$2 AND NOT (s.occurrence_id=ANY($3::bigint[])))
- OR (s.body_generation<=$2 AND EXISTS (SELECT 1 FROM content_chunks n WHERE n.page_id=s.page_id AND n.occurrence_id=s.occurrence_id
- AND n.body_generation>s.body_generation AND n.body_generation<=$2)))
- LIMIT $4)
- RETURNING c.id`, [pageId, generation, live, DEFAULT_FLIP_RETIRE_MAX_ROWS]);
- retired += rows.length;
- if (rows.length < DEFAULT_FLIP_RETIRE_MAX_ROWS) return retired;
+ const deleted = await engine.transaction(async tx => {
+ await tx.lockPageKeys([ref]);
+ const [page] = await tx.executeRaw<{ body_generation: number | string; body_storage: string }>('SELECT body_generation, body_storage FROM pages WHERE id=$1', [pageId]);
+ if (page?.body_storage !== 'segmented' || Number(page.body_generation) !== generation) return null;
+ return (await tx.executeRaw<{ id: number }>(`DELETE FROM content_chunks c WHERE c.id IN (${STALE_CHUNKS_SQL} LIMIT $4) RETURNING c.id`,
+ [pageId, generation, live, DEFAULT_FLIP_RETIRE_MAX_ROWS])).length;
+ });
+ if (deleted === null) return { retired, moved: true };
+ retired += deleted;
+ if (deleted < DEFAULT_FLIP_RETIRE_MAX_ROWS) return { retired, moved: false };
if (engine.kind === 'pglite') await new Promise(resolve => setImmediate(resolve));
}
}
@@ -94,7 +111,8 @@ async function buildClaimedProjection(engine: BrainEngine, ref: { sourceId: stri
const generation = Number(page.body_generation);
const pageId = Number(page.id);
const liveRows = await engine.readManifest(pageId);
- const retired = await retireStaleChunks(engine, pageId, generation, liveRows.map(row => Number(row.occurrenceId)));
+ const { retired, moved } = await retireStaleChunks(engine, ref, pageId, generation, liveRows.map(row => Number(row.occurrenceId)));
+ if (moved) return { chunks: 0, retired, sealed: false };
const frontmatter = page.frontmatter ?? {};
const quarantined = isQuarantined(frontmatter);
const unchunked = await occurrencesWithoutChunks(engine, pageId, generation, liveRows);
diff --git a/src/core/page-body/schema.ts b/src/core/page-body/schema.ts
index 7eb2ada6fa..220385c97f 100644
--- a/src/core/page-body/schema.ts
+++ b/src/core/page-body/schema.ts
@@ -46,6 +46,34 @@ BEGIN
END;
$func$ LANGUAGE plpgsql;`;
+/**
+ * The segment texts each staging staged or deduped onto (migration v252). A create keeps its manifest rows in memory
+ * until it publishes and a replace stages its texts before its manifest rows, so this is the only durable record of
+ * which texts a live staging still needs: a page purge keeps exactly those of the texts no manifest row references.
+ * Rows go with their staging; they hold hashes, never text.
+ */
+export const PAGE_BODY_STAGING_TEXTS_SQL = `CREATE TABLE IF NOT EXISTS page_body_staging_texts (
+ staging_id UUID NOT NULL REFERENCES page_body_stagings(id) ON DELETE CASCADE,
+ source_id TEXT NOT NULL,
+ sha256 BYTEA NOT NULL,
+ PRIMARY KEY (staging_id, sha256)
+);
+CREATE INDEX IF NOT EXISTS page_body_staging_texts_text ON page_body_staging_texts (source_id, sha256);`;
+
+/**
+ * A live staging (open, sealed or prepared, or named by a non-terminal persistence request's body_ref, the segment
+ * GC's roots) recorded the text `t` (a caller alias exposing source_id and sha256) in page_body_staging_texts: a write
+ * that has not published still needs it. Constant SQL over the alias, no values, for the purge statements that keep
+ * exactly those texts.
+ */
+export function stagingNeedsTextSql(t: string): string {
+ return `EXISTS (SELECT 1 FROM page_body_staging_texts r JOIN page_body_stagings rs ON rs.id = r.staging_id
+ WHERE r.source_id = ${t}.source_id AND r.sha256 = ${t}.sha256
+ AND (rs.state IN ('open','sealed','prepared')
+ OR EXISTS (SELECT 1 FROM persistence_requests rq WHERE rq.state IN ('queued','running','recovering')
+ AND rq.intent->'body_ref'->>'staging_id' = rs.id::text)))`;
+}
+
/**
* Segment texts (stored once per source and sha256), the generation-ranged
* manifest, body stagings and their raw upload parts, and the occurrence id
@@ -133,4 +161,5 @@ CREATE TABLE IF NOT EXISTS page_body_staging_parts (
sha256 BYTEA NOT NULL,
body BYTEA NOT NULL,
PRIMARY KEY (staging_id, part_no)
-);`;
+);
+${PAGE_BODY_STAGING_TEXTS_SQL}`;
diff --git a/src/core/page-body/segment-rewrite.ts b/src/core/page-body/segment-rewrite.ts
index 146262cdeb..e4b146a989 100644
--- a/src/core/page-body/segment-rewrite.ts
+++ b/src/core/page-body/segment-rewrite.ts
@@ -121,6 +121,13 @@ async function rewriteOwner(engine: BrainEngine): Promise<SegmentedStagingOwner>
/** The replaced rows' segment shas: texts the rewrite stopped referencing from this generation. */
const replacedShas = (rows: readonly ManifestRow[], units: readonly FenceUnit[]) => units.flatMap(unit => rows.slice(unit.from, unit.to + 1).map(row => row.sha256));
+/**
+ * The tier and corpus generation the page's stored vectors were embedded under (its contextual-retrieval stamp), so vector
+ * reuse admits them as an import of the same body would. A fence edit is not authorship: the stamp stays as it is.
+ */
+const rewriteTier = (page: { contextual_retrieval_mode: string | null; corpus_generation: string | null }) => page.contextual_retrieval_mode === 'title'
+ ? { tier: 'title' as const, corpusGeneration: page.corpus_generation } : { tier: 'none' as const, corpusGeneration: null };
+
export interface LiveFenceRewrite {
/** Segment shas the old generation referenced in place of the rewritten units. */
replaced: Uint8Array[];
@@ -138,8 +145,9 @@ export interface LiveFenceRewrite {
*/
export async function rewriteLiveSegmentedFences(tx: BrainEngine, pageId: number, transform: FenceTransform): Promise<LiveFenceRewrite | null> {
const [page] = await tx.executeRaw<{ id: number; slug: string; source_id: string; title: string; type: string; page_kind: string; frontmatter: JsonObject | null;
- body_generation: number | string; body_flags: JsonObject | null; body_storage: string; deleted_at: string | null; tags: string[] }>(`SELECT p.id,p.slug,p.source_id,p.title,
- p.type,p.page_kind,p.frontmatter,p.body_generation,p.body_flags,p.body_storage,p.deleted_at,
+ body_generation: number | string; body_flags: JsonObject | null; body_storage: string; deleted_at: string | null; tags: string[];
+ contextual_retrieval_mode: string | null; corpus_generation: string | null }>(`SELECT p.id,p.slug,p.source_id,p.title,
+ p.type,p.page_kind,p.frontmatter,p.body_generation,p.body_flags,p.body_storage,p.deleted_at,p.contextual_retrieval_mode,p.corpus_generation,
COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id),'[]'::jsonb) AS tags FROM pages p WHERE p.id=$1`, [pageId]);
if (page?.body_storage !== 'segmented') return null;
const sourceId = page.source_id, slug = page.slug, frontmatter = page.frontmatter ?? {};
@@ -151,7 +159,7 @@ export async function rewriteLiveSegmentedFences(tx: BrainEngine, pageId: number
live: { id: pageId, generation, storage: 'segmented', title: page.title, type: page.type, flags: page.body_flags },
truth: rewrittenRegion(tx, sourceId, rows, units, 'truth'), timeline: rewrittenRegion(tx, sourceId, rows, units, 'timeline'),
hasTimeline: rows.some(row => row.region === 'timeline'), flags: page.body_flags ?? {}, declaredBytes: bodyBytesOf(rows, units),
- owner: await rewriteOwner(tx), chunking: { quarantined: isQuarantined(frontmatter), corpusGeneration: null, tier: 'none' } });
+ owner: await rewriteOwner(tx), chunking: { quarantined: isQuarantined(frontmatter), ...rewriteTier(page) } });
const { flipRetireMaxRows } = await readPageBodyPolicy(tx);
const applied = await withPageTierKept(tx, { sourceId, slug }, () => applySegmentedBody(tx, { slug, sourceId, pageId, prepared, promotion: false,
retireMaxRows: flipRetireMaxRows, meta: { title: page.title, type: page.type as never, frontmatter, page_kind: page.page_kind as never } }));
diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.ts
index a17d552da1..18ab3b6bad 100644
--- a/src/core/persistence/graduation-inventory.ts
+++ b/src/core/persistence/graduation-inventory.ts
@@ -106,6 +106,7 @@ export const GRADUATION_INVENTORY: Inventory = {
carry('page_body_manifest', 'user_data', 'Segmented page bodies: which segment texts make each body generation, in order; without it a large page has no body.'),
carry('page_body_staging_parts', 'operational', 'Raw parts of open upload sessions; without them a client resuming an upload starts over.'),
carry('page_body_stagings', 'operational', 'Body stagings of segmented writes and upload sessions (idempotent begin and commit, expiry deadlines).'),
+ carry('page_body_staging_texts', 'operational', 'The segment texts each live body staging needs, so a page purge keeps an unpublished write\'s texts.'),
carry('page_embedding_budget', 'operational', 'Large-page embedding spend ledger: per-page spend, holds awaiting approval and caps; without it held pages would embed without consent.'),
carry('page_extraction_state', 'operational', 'Extraction watermarks and partial-input receipts per page and pipeline; without them the next extraction of a large page reads its head again and records the receipt anew.'),
carry('page_facts_reconcile', 'operational', 'Facts reconcile watermark: per-page revision extract_facts last reconciled; without it every page is due again.'),
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 405cc6b471..90e0388076 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -51,7 +51,7 @@ import { ledgerApplies, type BodyLedger } from '../page-body/segment-ledger.ts';
import { inferredHeadPrefix } from '../page-body/streamed-import.ts';
import { FRONTMATTER_HEAD_MAX_BYTES } from '../page-body/limits.ts';
import { occurrencesWithoutChunks } from '../page-body/ingest.ts';
-import { buildSegmentedProjection } from '../page-body/projection.ts';
+import { buildSegmentedProjection, hasStaleChunks } from '../page-body/projection.ts';
import { segmentedExportMarkdown } from '../export-snapshot.ts';
import { loadImportSanityConfig } from '../import-screen.ts';
import { DEFAULT_WRITE_GATE_CONFIG, writeGateApplies } from '../write-gate.ts';
@@ -460,7 +460,8 @@ async function prepareDeletePageMutation(engine: BrainEngine, row: WriteRequest,
/**
* Wave B: `restore_page` of a segmented page whose body was not read back (over the single-string ceiling). Soft
* delete only set `deleted_at` (its body, chunks, links and projections stay), so the restore clears it without
- * re-serializing or re-importing the body: version, clear, reseal (or queue the projection when chunks are missing).
+ * re-serializing or re-importing the body: version, clear, reseal (or queue the projection when chunks are missing or a
+ * deferred retirement left rows of retired occurrences).
* The canonical file is serializePageToMarkdown's bytes streamed from the segments by export's serializer into one
* buffer, never one string. The restore adds no text, so an agent-tier writer's advisory gate scan (flag only) is not
* re-run over the stored body; a step that needs the whole body refuses (`page_body_segmented`): a core page's budget
@@ -492,7 +493,10 @@ async function prepareUnreadRestore(engine: BrainEngine, row: WriteRequest, snap
await tx.restorePage(row.slug, source);
const lowered = storedTier ? await recordAgentPageLowering(tx, row, { tier: storedTier, revision: snapshot.revision }) : null;
const [page] = await tx.executeRaw<{ body_generation: number | string }>('SELECT body_generation FROM pages WHERE id=$1', [pageId]);
- complete = !(await occurrencesWithoutChunks(tx, pageId, Number(page!.body_generation), await tx.readManifest(pageId))).length;
+ const generation = Number(page!.body_generation), live = await tx.readManifest(pageId);
+ // Unsealed while an occurrence lacks chunks or a deferred retirement left rows of retired occurrences: the projection retires them first.
+ complete = !(await occurrencesWithoutChunks(tx, pageId, generation, live)).length
+ && !await hasStaleChunks(tx, pageId, generation, live.map(row => Number(row.occurrenceId)));
if (complete) await sealSegmentedPage(tx, pageId);
if (core) await core.record(tx, (await tx.readPageSnapshot(row.slug, source))?.revision ?? null);
return { ...pageNoopAdvisories(row), status: 'restored', slug: row.slug, source_id: row.source_id, chunks: 0, noop: false,
diff --git a/src/core/persistence/page-purge.ts b/src/core/persistence/page-purge.ts
index 3177d361ed..7c42fb1e94 100644
--- a/src/core/persistence/page-purge.ts
+++ b/src/core/persistence/page-purge.ts
@@ -42,6 +42,7 @@ import { derivedRowsFrom, hideDerivedRows } from '../facts/derivation-inputs.ts'
import { contentHash } from '../utils.ts';
import { isSegmentedPage } from '../page-body/page-shape.ts';
import { rewrittenContentHash } from '../page-body/segment-rewrite.ts';
+import { stagingNeedsTextSql } from '../page-body/schema.ts';
import type { PagePurgeContext } from '../facts/purge-verify.ts';
export const PURGE_RESIDUALS = 'Removed from live stores: the page row with its chunks, versions, takes, timeline, links and raw data, the facts filed on it (tombstoned), '
@@ -207,8 +208,10 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,
removed.page_body_manifest = (await tx.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_body_manifest WHERE page_id=$1', [page.id]))[0]?.n ?? 0;
removed.page_body_stagings = await count('DELETE FROM page_body_stagings WHERE source_id=$1 AND (slug=$2 OR page_id=$3) RETURNING 1', [sourceId, slug, page.id]);
await tx.deletePage(slug, { sourceId });
+ // A text another page still references stays, and so does one an unpublished write of another page staged or deduped
+ // onto (a create holds its manifest rows in memory until it publishes): that write's copy, not this page's.
removed.page_segment_texts = shas.length ? await count(`DELETE FROM page_segment_texts t WHERE t.source_id=$1 AND t.sha256=ANY(SELECT decode(h,'hex') FROM unnest($2::text[]) AS h)
- AND NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.source_id=t.source_id AND m.sha256=t.sha256) RETURNING 1`, [sourceId, shas]) : 0;
+ AND NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.source_id=t.source_id AND m.sha256=t.sha256) AND NOT ${stagingNeedsTextSql('t')} RETURNING 1`, [sourceId, shas]) : 0;
const key = `${sourceId}:${row.request_id}`;
purgeContext.delete(key);
purgeContext.set(key, { needles, factIds, pageId: page.id, paths, segmentShas: shas.slice(0, 4096) });
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 07bcb5e4d6..d0b152bf27 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -2509,7 +2509,7 @@ export class PGLiteEngine implements BrainEngine {
// Segmented page storage (Wave B): SQL in ./engine-sql/page-body.ts.
async allocateBodyOccurrenceIds(count: number): Promise<number[]> { return pageBodyImpl.allocateBodyOccurrenceIds(this.engineSql, count); }
- async stageSegmentTexts(sourceId: string, texts: readonly SegmentTextInput[]): Promise<{ inserted: number }> { return pageBodyImpl.stageSegmentTexts(this.engineSql, sourceId, texts); }
+ async stageSegmentTexts(sourceId: string, texts: readonly SegmentTextInput[], opts?: { stagingId?: string }): Promise<{ inserted: number }> { return pageBodyImpl.stageSegmentTexts(this.engineSql, sourceId, texts, opts); }
async readSegmentTexts(sourceId: string, sha256s: readonly Uint8Array[]): Promise<Map<string, Uint8Array>> {
return pageBodyImpl.readSegmentTexts(unscopedExecutor(this.engineSql, 'page-body: page-id keyed internal read'), sourceId, sha256s);
}
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index 292dafef19..da04f6d909 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -1369,6 +1369,13 @@ CREATE TABLE IF NOT EXISTS page_body_staging_parts (
body BYTEA NOT NULL,
PRIMARY KEY (staging_id, part_no)
);
+CREATE TABLE IF NOT EXISTS page_body_staging_texts (
+ staging_id UUID NOT NULL REFERENCES page_body_stagings(id) ON DELETE CASCADE,
+ source_id TEXT NOT NULL,
+ sha256 BYTEA NOT NULL,
+ PRIMARY KEY (staging_id, sha256)
+);
+CREATE INDEX IF NOT EXISTS page_body_staging_texts_text ON page_body_staging_texts (source_id, sha256);
-- Durable concurrent persistence (migration 151).
CREATE TABLE IF NOT EXISTS persistence_brain (
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 26366f8fe6..7be32b1fef 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -2301,7 +2301,7 @@ export class PostgresEngine implements BrainEngine {
// Segmented page storage (Wave B): SQL in ./engine-sql/page-body.ts.
async allocateBodyOccurrenceIds(count: number): Promise<number[]> { return pageBodyImpl.allocateBodyOccurrenceIds(this.engineSql, count); }
- async stageSegmentTexts(sourceId: string, texts: readonly SegmentTextInput[]): Promise<{ inserted: number }> { return pageBodyImpl.stageSegmentTexts(this.engineSql, sourceId, texts); }
+ async stageSegmentTexts(sourceId: string, texts: readonly SegmentTextInput[], opts?: { stagingId?: string }): Promise<{ inserted: number }> { return pageBodyImpl.stageSegmentTexts(this.engineSql, sourceId, texts, opts); }
async readSegmentTexts(sourceId: string, sha256s: readonly Uint8Array[]): Promise<Map<string, Uint8Array>> {
return pageBodyImpl.readSegmentTexts(unscopedExecutor(this.engineSql, 'page-body: page-id keyed internal read'), sourceId, sha256s);
}
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index 4a29aef8f6..a962e24291 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -348,8 +348,9 @@ CREATE TABLE IF NOT EXISTS content_chunks (
-- span in its source's read projection) are added the same way.
-- v248: occurrence_id, local_ordinal, raw_byte_start/end and body_generation
-- (segmented-page chunks; NULL for inline pages) and
- -- content_chunks_occurrence_idx are added the same way (v248's
- -- retired_generation is dropped by v249, which adds content_chunks_generation_idx).
+ -- content_chunks_occurrence_idx are added the same way, and so is v248's
+ -- retired_generation, which nothing writes or reads but released chunk readers
+ -- still select (v249 keeps it and adds content_chunks_generation_idx).
-- #4246 (v133): md5(chunk_text) at embed time. NULL = no embedding or
-- pre-v133 row (grandfathered by invalidateContentDriftEmbeddings).
embedded_text_hash TEXT,
@@ -2104,6 +2105,13 @@ CREATE TABLE IF NOT EXISTS page_body_staging_parts (
body BYTEA NOT NULL,
PRIMARY KEY (staging_id, part_no)
);
+CREATE TABLE IF NOT EXISTS page_body_staging_texts (
+ staging_id UUID NOT NULL REFERENCES page_body_stagings(id) ON DELETE CASCADE,
+ source_id TEXT NOT NULL,
+ sha256 BYTEA NOT NULL,
+ PRIMARY KEY (staging_id, sha256)
+);
+CREATE INDEX IF NOT EXISTS page_body_staging_texts_text ON page_body_staging_texts (source_id, sha256);
-- END GENERATED from src/core/page-body/schema.ts (PAGE_BODY_SCHEMA_SQL)
-- Durable concurrent persistence (migration 151).
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index a37b519c57..283f2ed684 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 = 250;
+export const LATEST_SCHEMA_VERSION = 252;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index 1ee0a2a347..2ecce21c43 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -251,6 +251,7 @@ import { v247 } from './v247-page-extraction-state.ts';
import { v248 } from './v248-segmented-page-storage.ts';
import { v249 } from './v249-segmented-chunk-gc-index.ts';
import { v250 } from './v250-page-view-digests.ts';
+import { v252 } from './v252-page-body-staging-texts.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -500,4 +501,5 @@ export const MIGRATIONS: Migration[] = [
v248,
v249,
v250,
+ v252,
];
diff --git a/src/core/schema-migrations/v249-segmented-chunk-gc-index.ts b/src/core/schema-migrations/v249-segmented-chunk-gc-index.ts
index 717f1f390f..f25ef93c2d 100644
--- a/src/core/schema-migrations/v249-segmented-chunk-gc-index.ts
+++ b/src/core/schema-migrations/v249-segmented-chunk-gc-index.ts
@@ -5,10 +5,14 @@ import { buildIndexOnline, migrationNotice } from './helpers.ts';
// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
//
// Segmented page storage (v248), follow-up:
-// - content_chunks.retired_generation is dropped. Nothing writes it: the flip
-// and the projection delete the rows they retire, and a row awaiting a
-// deferred retirement is hidden by its occurrence's closed manifest range
-// (chunkGenerationFilter), so the predicates that read it were always true.
+// - content_chunks.retired_generation (v248) stays. Nothing at this version
+// writes or reads it: the flip and the projection delete the rows they
+// retire, and a row awaiting a deferred retirement is hidden by its
+// occurrence's closed manifest range (chunkGenerationFilter). The released
+// binary's chunk readers still select it, so it is dropped only once the
+// writer floor excludes every binary that reads it
+// (test/large-pages/v249-master-reader-compat.test.ts). An earlier build of
+// this migration dropped it; v252 re-adds it on those (test) brains.
// - content_chunks_generation_idx serves segment GC's staged-chunk delete
// (`c.body_generation IS NOT NULL AND c.body_generation > p.body_generation`,
// engine-sql/page-body.ts sweepSegments), which the resident maintenance
@@ -26,7 +30,7 @@ export const v249: Migration = {
name: 'segmented_chunk_gc_index',
idempotent: true,
transaction: false,
- sql: 'ALTER TABLE content_chunks DROP COLUMN IF EXISTS retired_generation;',
+ sql: '',
handler: async engine => {
await buildIndexOnline(engine, 249, CONTENT_CHUNKS_GENERATION_INDEX, { notice: migrationNotice });
},
diff --git a/src/core/schema-migrations/v252-page-body-staging-texts.ts b/src/core/schema-migrations/v252-page-body-staging-texts.ts
new file mode 100644
index 0000000000..b5a1e47630
--- /dev/null
+++ b/src/core/schema-migrations/v252-page-body-staging-texts.ts
@@ -0,0 +1,28 @@
+import type { Migration } from './types.ts';
+import { PAGE_BODY_STAGING_TEXTS_SQL } from '../page-body/schema.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); the fresh-install
+// copy in src/schema.sql (PAGE_BODY_SCHEMA_SQL) carries the same table.
+//
+// Segmented page storage (Wave B PR 2) follow-up:
+// - page_body_staging_texts: the segment texts each body staging staged or
+// deduped onto. A segmented create keeps its manifest rows in memory until it
+// publishes, and a replace stages its texts before its manifest rows, so a
+// page purge that deleted every text no manifest row references killed such
+// a write (page_body_manifest_source_id_sha256_fkey). A purge now keeps the
+// texts a live staging recorded here, and only those. Hashes only, no text;
+// rows go with their staging (ON DELETE CASCADE). Nothing to backfill: a
+// staging opened before this migration records nothing and its write keeps
+// the old behavior until it ends.
+// - content_chunks.retired_generation is re-added where an earlier build of
+// v249 dropped it (test brains of that build only): the released binary's
+// chunk readers still select it (v249). A no-op everywhere else.
+export const v252: Migration = {
+ version: 252,
+ name: 'page_body_staging_texts',
+ idempotent: true,
+ sql: `
+ ${PAGE_BODY_STAGING_TEXTS_SQL}
+ ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS retired_generation BIGINT;
+ `,
+};
diff --git a/src/schema.sql b/src/schema.sql
index 58ce56ff50..f835495bf4 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -344,8 +344,9 @@ CREATE TABLE IF NOT EXISTS content_chunks (
-- span in its source's read projection) are added the same way.
-- v248: occurrence_id, local_ordinal, raw_byte_start/end and body_generation
-- (segmented-page chunks; NULL for inline pages) and
- -- content_chunks_occurrence_idx are added the same way (v248's
- -- retired_generation is dropped by v249, which adds content_chunks_generation_idx).
+ -- content_chunks_occurrence_idx are added the same way, and so is v248's
+ -- retired_generation, which nothing writes or reads but released chunk readers
+ -- still select (v249 keeps it and adds content_chunks_generation_idx).
-- #4246 (v133): md5(chunk_text) at embed time. NULL = no embedding or
-- pre-v133 row (grandfathered by invalidateContentDriftEmbeddings).
embedded_text_hash TEXT,
@@ -2100,6 +2101,13 @@ CREATE TABLE IF NOT EXISTS page_body_staging_parts (
body BYTEA NOT NULL,
PRIMARY KEY (staging_id, part_no)
);
+CREATE TABLE IF NOT EXISTS page_body_staging_texts (
+ staging_id UUID NOT NULL REFERENCES page_body_stagings(id) ON DELETE CASCADE,
+ source_id TEXT NOT NULL,
+ sha256 BYTEA NOT NULL,
+ PRIMARY KEY (staging_id, sha256)
+);
+CREATE INDEX IF NOT EXISTS page_body_staging_texts_text ON page_body_staging_texts (source_id, sha256);
-- END GENERATED from src/core/page-body/schema.ts (PAGE_BODY_SCHEMA_SQL)
-- Durable concurrent persistence (migration 151).
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 7bb7c75abe..1f29a6381e 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -214,6 +214,8 @@
"page_body_staging_parts.page_body_staging_parts_part_no_check": "c CHECK ((part_no >= 0))",
"page_body_staging_parts.page_body_staging_parts_pkey": "p PRIMARY KEY (staging_id, part_no)",
"page_body_staging_parts.page_body_staging_parts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",
+ "page_body_staging_texts.page_body_staging_texts_pkey": "p PRIMARY KEY (staging_id, sha256)",
+ "page_body_staging_texts.page_body_staging_texts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",
"page_body_stagings.page_body_stagings_declared_bytes_check": "c CHECK ((declared_bytes >= 0))",
"page_body_stagings.page_body_stagings_kind_check": "c CHECK ((kind = ANY (ARRAY['upload'::text, 'import'::text, 'sync'::text, 'put'::text, 'append'::text, 'edit'::text, 'resegment'::text])))",
"page_body_stagings.page_body_stagings_mode_check": "c CHECK ((mode = ANY (ARRAY['create'::text, 'replace'::text, 'append'::text])))",
@@ -723,6 +725,9 @@
"page_body_staging_parts": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_body_staging_texts": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_body_stagings": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1206,6 +1211,8 @@
"page_body_manifest_staging": "CREATE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id) WHERE (staging_id IS NOT NULL)",
"page_body_manifest_text": "CREATE INDEX page_body_manifest_text ON public.page_body_manifest USING btree (source_id, sha256)",
"page_body_staging_parts_pkey": "CREATE UNIQUE INDEX page_body_staging_parts_pkey ON public.page_body_staging_parts USING btree (staging_id, part_no)",
+ "page_body_staging_texts_pkey": "CREATE UNIQUE INDEX page_body_staging_texts_pkey ON public.page_body_staging_texts USING btree (staging_id, sha256)",
+ "page_body_staging_texts_text": "CREATE INDEX page_body_staging_texts_text ON public.page_body_staging_texts USING btree (source_id, sha256)",
"page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",
"page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",
"page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)",
@@ -1643,7 +1650,8 @@
"30 local_ordinal integer/int4 NULL",
"31 raw_byte_start bigint/int8 NULL",
"32 raw_byte_end bigint/int8 NULL",
- "33 body_generation bigint/int8 NULL"
+ "33 body_generation bigint/int8 NULL",
+ "34 retired_generation bigint/int8 NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -2649,6 +2657,14 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_body_staging_texts": {
+ "columns": [
+ "1 staging_id uuid/uuid NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 sha256 bytea/bytea NOT NULL"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_body_stagings": {
"columns": [
"1 id uuid/uuid NOT NULL",
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 b1ca140212..41b68bc3df 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -214,6 +214,8 @@
"page_body_staging_parts.page_body_staging_parts_part_no_check": "c CHECK ((part_no >= 0))",
"page_body_staging_parts.page_body_staging_parts_pkey": "p PRIMARY KEY (staging_id, part_no)",
"page_body_staging_parts.page_body_staging_parts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",
+ "page_body_staging_texts.page_body_staging_texts_pkey": "p PRIMARY KEY (staging_id, sha256)",
+ "page_body_staging_texts.page_body_staging_texts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",
"page_body_stagings.page_body_stagings_declared_bytes_check": "c CHECK ((declared_bytes >= 0))",
"page_body_stagings.page_body_stagings_kind_check": "c CHECK ((kind = ANY (ARRAY['upload'::text, 'import'::text, 'sync'::text, 'put'::text, 'append'::text, 'edit'::text, 'resegment'::text])))",
"page_body_stagings.page_body_stagings_mode_check": "c CHECK ((mode = ANY (ARRAY['create'::text, 'replace'::text, 'append'::text])))",
@@ -723,6 +725,9 @@
"page_body_staging_parts": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_body_staging_texts": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_body_stagings": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1206,6 +1211,8 @@
"page_body_manifest_staging": "CREATE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id) WHERE (staging_id IS NOT NULL)",
"page_body_manifest_text": "CREATE INDEX page_body_manifest_text ON public.page_body_manifest USING btree (source_id, sha256)",
"page_body_staging_parts_pkey": "CREATE UNIQUE INDEX page_body_staging_parts_pkey ON public.page_body_staging_parts USING btree (staging_id, part_no)",
+ "page_body_staging_texts_pkey": "CREATE UNIQUE INDEX page_body_staging_texts_pkey ON public.page_body_staging_texts USING btree (staging_id, sha256)",
+ "page_body_staging_texts_text": "CREATE INDEX page_body_staging_texts_text ON public.page_body_staging_texts USING btree (source_id, sha256)",
"page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",
"page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",
"page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)",
@@ -1643,7 +1650,8 @@
"30 local_ordinal integer/int4 NULL",
"31 raw_byte_start bigint/int8 NULL",
"32 raw_byte_end bigint/int8 NULL",
- "33 body_generation bigint/int8 NULL"
+ "33 body_generation bigint/int8 NULL",
+ "34 retired_generation bigint/int8 NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -2649,6 +2657,14 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_body_staging_texts": {
+ "columns": [
+ "1 staging_id uuid/uuid NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 sha256 bytea/bytea NOT NULL"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_body_stagings": {
"columns": [
"1 id uuid/uuid NOT NULL",
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 67a76a3a88..ed6c52a2f7 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -214,6 +214,8 @@
"page_body_staging_parts.page_body_staging_parts_part_no_check": "c CHECK ((part_no >= 0))",
"page_body_staging_parts.page_body_staging_parts_pkey": "p PRIMARY KEY (staging_id, part_no)",
"page_body_staging_parts.page_body_staging_parts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",
+ "page_body_staging_texts.page_body_staging_texts_pkey": "p PRIMARY KEY (staging_id, sha256)",
+ "page_body_staging_texts.page_body_staging_texts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",
"page_body_stagings.page_body_stagings_declared_bytes_check": "c CHECK ((declared_bytes >= 0))",
"page_body_stagings.page_body_stagings_kind_check": "c CHECK ((kind = ANY (ARRAY['upload'::text, 'import'::text, 'sync'::text, 'put'::text, 'append'::text, 'edit'::text, 'resegment'::text])))",
"page_body_stagings.page_body_stagings_mode_check": "c CHECK ((mode = ANY (ARRAY['create'::text, 'replace'::text, 'append'::text])))",
@@ -723,6 +725,9 @@
"page_body_staging_parts": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_body_staging_texts": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_body_stagings": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1202,6 +1207,8 @@
"page_body_manifest_staging": "CREATE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id) WHERE (staging_id IS NOT NULL)",
"page_body_manifest_text": "CREATE INDEX page_body_manifest_text ON public.page_body_manifest USING btree (source_id, sha256)",
"page_body_staging_parts_pkey": "CREATE UNIQUE INDEX page_body_staging_parts_pkey ON public.page_body_staging_parts USING btree (staging_id, part_no)",
+ "page_body_staging_texts_pkey": "CREATE UNIQUE INDEX page_body_staging_texts_pkey ON public.page_body_staging_texts USING btree (staging_id, sha256)",
+ "page_body_staging_texts_text": "CREATE INDEX page_body_staging_texts_text ON public.page_body_staging_texts USING btree (source_id, sha256)",
"page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",
"page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",
"page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)",
@@ -1639,7 +1646,8 @@
"30 local_ordinal integer/int4 NULL",
"31 raw_byte_start bigint/int8 NULL",
"32 raw_byte_end bigint/int8 NULL",
- "33 body_generation bigint/int8 NULL"
+ "33 body_generation bigint/int8 NULL",
+ "34 retired_generation bigint/int8 NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -2645,6 +2653,14 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_body_staging_texts": {
+ "columns": [
+ "1 staging_id uuid/uuid NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 sha256 bytea/bytea NOT NULL"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_body_stagings": {
"columns": [
"1 id uuid/uuid NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
index 83401c7a12..5222bd8403 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
@@ -149,6 +149,8 @@
"page_body_staging_parts.page_body_staging_parts_part_no_check": "c CHECK ((part_no >= 0))",
"page_body_staging_parts.page_body_staging_parts_pkey": "p PRIMARY KEY (staging_id, part_no)",
"page_body_staging_parts.page_body_staging_parts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",
+ "page_body_staging_texts.page_body_staging_texts_pkey": "p PRIMARY KEY (staging_id, sha256)",
+ "page_body_staging_texts.page_body_staging_texts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",
"page_body_stagings.page_body_stagings_declared_bytes_check": "c CHECK ((declared_bytes >= 0))",
"page_body_stagings.page_body_stagings_kind_check": "c CHECK ((kind = ANY (ARRAY['upload'::text, 'import'::text, 'sync'::text, 'put'::text, 'append'::text, 'edit'::text, 'resegment'::text])))",
"page_body_stagings.page_body_stagings_mode_check": "c CHECK ((mode = ANY (ARRAY['create'::text, 'replace'::text, 'append'::text])))",
@@ -526,6 +528,9 @@
"page_body_staging_parts": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_body_staging_texts": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_body_stagings": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -876,6 +881,8 @@
"page_body_manifest_staging": "CREATE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id) WHERE (staging_id IS NOT NULL)",
"page_body_manifest_text": "CREATE INDEX page_body_manifest_text ON public.page_body_manifest USING btree (source_id, sha256)",
"page_body_staging_parts_pkey": "CREATE UNIQUE INDEX page_body_staging_parts_pkey ON public.page_body_staging_parts USING btree (staging_id, part_no)",
+ "page_body_staging_texts_pkey": "CREATE UNIQUE INDEX page_body_staging_texts_pkey ON public.page_body_staging_texts USING btree (staging_id, sha256)",
+ "page_body_staging_texts_text": "CREATE INDEX page_body_staging_texts_text ON public.page_body_staging_texts USING btree (source_id, sha256)",
"page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",
"page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",
"page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)",
@@ -1954,6 +1961,14 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_body_staging_texts": {
+ "columns": [
+ "1 staging_id uuid/uuid NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 sha256 bytea/bytea NOT NULL"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_body_stagings": {
"columns": [
"1 id uuid/uuid NOT NULL",
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 bcf77c9d5f..554a9defda 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
@@ -149,6 +149,8 @@
"page_body_staging_parts.page_body_staging_parts_part_no_check": "c CHECK ((part_no >= 0))",
"page_body_staging_parts.page_body_staging_parts_pkey": "p PRIMARY KEY (staging_id, part_no)",
"page_body_staging_parts.page_body_staging_parts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",
+ "page_body_staging_texts.page_body_staging_texts_pkey": "p PRIMARY KEY (staging_id, sha256)",
+ "page_body_staging_texts.page_body_staging_texts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",
"page_body_stagings.page_body_stagings_declared_bytes_check": "c CHECK ((declared_bytes >= 0))",
"page_body_stagings.page_body_stagings_kind_check": "c CHECK ((kind = ANY (ARRAY['upload'::text, 'import'::text, 'sync'::text, 'put'::text, 'append'::text, 'edit'::text, 'resegment'::text])))",
"page_body_stagings.page_body_stagings_mode_check": "c CHECK ((mode = ANY (ARRAY['create'::text, 'replace'::text, 'append'::text])))",
@@ -526,6 +528,9 @@
"page_body_staging_parts": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_body_staging_texts": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_body_stagings": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -876,6 +881,8 @@
"page_body_manifest_staging": "CREATE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id) WHERE (staging_id IS NOT NULL)",
"page_body_manifest_text": "CREATE INDEX page_body_manifest_text ON public.page_body_manifest USING btree (source_id, sha256)",
"page_body_staging_parts_pkey": "CREATE UNIQUE INDEX page_body_staging_parts_pkey ON public.page_body_staging_parts USING btree (staging_id, part_no)",
+ "page_body_staging_texts_pkey": "CREATE UNIQUE INDEX page_body_staging_texts_pkey ON public.page_body_staging_texts USING btree (staging_id, sha256)",
+ "page_body_staging_texts_text": "CREATE INDEX page_body_staging_texts_text ON public.page_body_staging_texts USING btree (source_id, sha256)",
"page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",
"page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",
"page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)",
@@ -1954,6 +1961,14 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_body_staging_texts": {
+ "columns": [
+ "1 staging_id uuid/uuid NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 sha256 bytea/bytea NOT NULL"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_body_stagings": {
"columns": [
"1 id uuid/uuid NOT NULL",
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 29e0418b17..e2ee96b95b 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
@@ -149,6 +149,8 @@
"page_body_staging_parts.page_body_staging_parts_part_no_check": "c CHECK ((part_no >= 0))",
"page_body_staging_parts.page_body_staging_parts_pkey": "p PRIMARY KEY (staging_id, part_no)",
"page_body_staging_parts.page_body_staging_parts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",
+ "page_body_staging_texts.page_body_staging_texts_pkey": "p PRIMARY KEY (staging_id, sha256)",
+ "page_body_staging_texts.page_body_staging_texts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",
"page_body_stagings.page_body_stagings_declared_bytes_check": "c CHECK ((declared_bytes >= 0))",
"page_body_stagings.page_body_stagings_kind_check": "c CHECK ((kind = ANY (ARRAY['upload'::text, 'import'::text, 'sync'::text, 'put'::text, 'append'::text, 'edit'::text, 'resegment'::text])))",
"page_body_stagings.page_body_stagings_mode_check": "c CHECK ((mode = ANY (ARRAY['create'::text, 'replace'::text, 'append'::text])))",
@@ -526,6 +528,9 @@
"page_body_staging_parts": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_body_staging_texts": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_body_stagings": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -875,6 +880,8 @@
"page_body_manifest_staging": "CREATE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id) WHERE (staging_id IS NOT NULL)",
"page_body_manifest_text": "CREATE INDEX page_body_manifest_text ON public.page_body_manifest USING btree (source_id, sha256)",
"page_body_staging_parts_pkey": "CREATE UNIQUE INDEX page_body_staging_parts_pkey ON public.page_body_staging_parts USING btree (staging_id, part_no)",
+ "page_body_staging_texts_pkey": "CREATE UNIQUE INDEX page_body_staging_texts_pkey ON public.page_body_staging_texts USING btree (staging_id, sha256)",
+ "page_body_staging_texts_text": "CREATE INDEX page_body_staging_texts_text ON public.page_body_staging_texts USING btree (source_id, sha256)",
"page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",
"page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",
"page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)",
@@ -1953,6 +1960,14 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_body_staging_texts": {
+ "columns": [
+ "1 staging_id uuid/uuid NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 sha256 bytea/bytea NOT NULL"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_body_stagings": {
"columns": [
"1 id uuid/uuid NOT NULL",
diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.json
index 53dfba0d3c..93af710e7d 100644
--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json
+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json
@@ -160,6 +160,8 @@
"page_body_staging_parts.page_body_staging_parts_part_no_check": "c CHECK ((part_no >= 0))",
"page_body_staging_parts.page_body_staging_parts_pkey": "p PRIMARY KEY (staging_id, part_no)",
"page_body_staging_parts.page_body_staging_parts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",
+ "page_body_staging_texts.page_body_staging_texts_pkey": "p PRIMARY KEY (staging_id, sha256)",
+ "page_body_staging_texts.page_body_staging_texts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",
"page_body_stagings.page_body_stagings_declared_bytes_check": "c CHECK ((declared_bytes >= 0))",
"page_body_stagings.page_body_stagings_kind_check": "c CHECK ((kind = ANY (ARRAY['upload'::text, 'import'::text, 'sync'::text, 'put'::text, 'append'::text, 'edit'::text, 'resegment'::text])))",
"page_body_stagings.page_body_stagings_mode_check": "c CHECK ((mode = ANY (ARRAY['create'::text, 'replace'::text, 'append'::text])))",
@@ -546,6 +548,9 @@
"page_body_staging_parts": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_body_staging_texts": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_body_stagings": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -904,6 +909,8 @@
"page_body_manifest_staging": "CREATE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id) WHERE (staging_id IS NOT NULL)",
"page_body_manifest_text": "CREATE INDEX page_body_manifest_text ON public.page_body_manifest USING btree (source_id, sha256)",
"page_body_staging_parts_pkey": "CREATE UNIQUE INDEX page_body_staging_parts_pkey ON public.page_body_staging_parts USING btree (staging_id, part_no)",
+ "page_body_staging_texts_pkey": "CREATE UNIQUE INDEX page_body_staging_texts_pkey ON public.page_body_staging_texts USING btree (staging_id, sha256)",
+ "page_body_staging_texts_text": "CREATE INDEX page_body_staging_texts_text ON public.page_body_staging_texts USING btree (source_id, sha256)",
"page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",
"page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",
"page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)",
@@ -2023,6 +2030,14 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_body_staging_texts": {
+ "columns": [
+ "1 staging_id uuid/uuid NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 sha256 bytea/bytea NOT NULL"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_body_stagings": {
"columns": [
"1 id uuid/uuid NOT NULL",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 73c9dc4f02..66f90d981f 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -218,6 +218,8 @@
"page_body_staging_parts.page_body_staging_parts_part_no_check": "c CHECK ((part_no >= 0))",
"page_body_staging_parts.page_body_staging_parts_pkey": "p PRIMARY KEY (staging_id, part_no)",
"page_body_staging_parts.page_body_staging_parts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",
+ "page_body_staging_texts.page_body_staging_texts_pkey": "p PRIMARY KEY (staging_id, sha256)",
+ "page_body_staging_texts.page_body_staging_texts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",
"page_body_stagings.page_body_stagings_declared_bytes_check": "c CHECK ((declared_bytes >= 0))",
"page_body_stagings.page_body_stagings_kind_check": "c CHECK ((kind = ANY (ARRAY['upload'::text, 'import'::text, 'sync'::text, 'put'::text, 'append'::text, 'edit'::text, 'resegment'::text])))",
"page_body_stagings.page_body_stagings_mode_check": "c CHECK ((mode = ANY (ARRAY['create'::text, 'replace'::text, 'append'::text])))",
@@ -730,6 +732,9 @@
"page_body_staging_parts": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_body_staging_texts": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_body_stagings": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1210,6 +1215,8 @@
"page_body_manifest_staging": "CREATE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id) WHERE (staging_id IS NOT NULL)",
"page_body_manifest_text": "CREATE INDEX page_body_manifest_text ON public.page_body_manifest USING btree (source_id, sha256)",
"page_body_staging_parts_pkey": "CREATE UNIQUE INDEX page_body_staging_parts_pkey ON public.page_body_staging_parts USING btree (staging_id, part_no)",
+ "page_body_staging_texts_pkey": "CREATE UNIQUE INDEX page_body_staging_texts_pkey ON public.page_body_staging_texts USING btree (staging_id, sha256)",
+ "page_body_staging_texts_text": "CREATE INDEX page_body_staging_texts_text ON public.page_body_staging_texts USING btree (source_id, sha256)",
"page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",
"page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",
"page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)",
@@ -1644,7 +1651,8 @@
"30 local_ordinal integer/int4 NULL",
"31 raw_byte_start bigint/int8 NULL",
"32 raw_byte_end bigint/int8 NULL",
- "33 body_generation bigint/int8 NULL"
+ "33 body_generation bigint/int8 NULL",
+ "34 retired_generation bigint/int8 NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -2661,6 +2669,14 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "page_body_staging_texts": {
+ "columns": [
+ "1 staging_id uuid/uuid NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 sha256 bytea/bytea NOT NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_body_stagings": {
"columns": [
"1 id uuid/uuid NOT NULL",
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 84ae9371dd..c313655a89 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -218,6 +218,8 @@
"page_body_staging_parts.page_body_staging_parts_part_no_check": "c CHECK ((part_no >= 0))",
"page_body_staging_parts.page_body_staging_parts_pkey": "p PRIMARY KEY (staging_id, part_no)",
"page_body_staging_parts.page_body_staging_parts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",
+ "page_body_staging_texts.page_body_staging_texts_pkey": "p PRIMARY KEY (staging_id, sha256)",
+ "page_body_staging_texts.page_body_staging_texts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",
"page_body_stagings.page_body_stagings_declared_bytes_check": "c CHECK ((declared_bytes >= 0))",
"page_body_stagings.page_body_stagings_kind_check": "c CHECK ((kind = ANY (ARRAY['upload'::text, 'import'::text, 'sync'::text, 'put'::text, 'append'::text, 'edit'::text, 'resegment'::text])))",
"page_body_stagings.page_body_stagings_mode_check": "c CHECK ((mode = ANY (ARRAY['create'::text, 'replace'::text, 'append'::text])))",
@@ -730,6 +732,9 @@
"page_body_staging_parts": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_body_staging_texts": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_body_stagings": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1210,6 +1215,8 @@
"page_body_manifest_staging": "CREATE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id) WHERE (staging_id IS NOT NULL)",
"page_body_manifest_text": "CREATE INDEX page_body_manifest_text ON public.page_body_manifest USING btree (source_id, sha256)",
"page_body_staging_parts_pkey": "CREATE UNIQUE INDEX page_body_staging_parts_pkey ON public.page_body_staging_parts USING btree (staging_id, part_no)",
+ "page_body_staging_texts_pkey": "CREATE UNIQUE INDEX page_body_staging_texts_pkey ON public.page_body_staging_texts USING btree (staging_id, sha256)",
+ "page_body_staging_texts_text": "CREATE INDEX page_body_staging_texts_text ON public.page_body_staging_texts USING btree (source_id, sha256)",
"page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",
"page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",
"page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)",
@@ -1644,7 +1651,8 @@
"30 local_ordinal integer/int4 NULL",
"31 raw_byte_start bigint/int8 NULL",
"32 raw_byte_end bigint/int8 NULL",
- "33 body_generation bigint/int8 NULL"
+ "33 body_generation bigint/int8 NULL",
+ "34 retired_generation bigint/int8 NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -2661,6 +2669,14 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "page_body_staging_texts": {
+ "columns": [
+ "1 staging_id uuid/uuid NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 sha256 bytea/bytea NOT NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_body_stagings": {
"columns": [
"1 id uuid/uuid NOT NULL",
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 d0cebea7f3..2ee741dd4a 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -218,6 +218,8 @@
"page_body_staging_parts.page_body_staging_parts_part_no_check": "c CHECK ((part_no >= 0))",
"page_body_staging_parts.page_body_staging_parts_pkey": "p PRIMARY KEY (staging_id, part_no)",
"page_body_staging_parts.page_body_staging_parts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",
+ "page_body_staging_texts.page_body_staging_texts_pkey": "p PRIMARY KEY (staging_id, sha256)",
+ "page_body_staging_texts.page_body_staging_texts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",
"page_body_stagings.page_body_stagings_declared_bytes_check": "c CHECK ((declared_bytes >= 0))",
"page_body_stagings.page_body_stagings_kind_check": "c CHECK ((kind = ANY (ARRAY['upload'::text, 'import'::text, 'sync'::text, 'put'::text, 'append'::text, 'edit'::text, 'resegment'::text])))",
"page_body_stagings.page_body_stagings_mode_check": "c CHECK ((mode = ANY (ARRAY['create'::text, 'replace'::text, 'append'::text])))",
@@ -730,6 +732,9 @@
"page_body_staging_parts": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_body_staging_texts": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_body_stagings": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1206,6 +1211,8 @@
"page_body_manifest_staging": "CREATE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id) WHERE (staging_id IS NOT NULL)",
"page_body_manifest_text": "CREATE INDEX page_body_manifest_text ON public.page_body_manifest USING btree (source_id, sha256)",
"page_body_staging_parts_pkey": "CREATE UNIQUE INDEX page_body_staging_parts_pkey ON public.page_body_staging_parts USING btree (staging_id, part_no)",
+ "page_body_staging_texts_pkey": "CREATE UNIQUE INDEX page_body_staging_texts_pkey ON public.page_body_staging_texts USING btree (staging_id, sha256)",
+ "page_body_staging_texts_text": "CREATE INDEX page_body_staging_texts_text ON public.page_body_staging_texts USING btree (source_id, sha256)",
"page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",
"page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",
"page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)",
@@ -1640,7 +1647,8 @@
"30 local_ordinal integer/int4 NULL",
"31 raw_byte_start bigint/int8 NULL",
"32 raw_byte_end bigint/int8 NULL",
- "33 body_generation bigint/int8 NULL"
+ "33 body_generation bigint/int8 NULL",
+ "34 retired_generation bigint/int8 NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -2657,6 +2665,14 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "page_body_staging_texts": {
+ "columns": [
+ "1 staging_id uuid/uuid NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 sha256 bytea/bytea NOT NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_body_stagings": {
"columns": [
"1 id uuid/uuid NOT NULL",
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 0275d8e14f..9777a7bf9e 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -222,7 +222,7 @@
"softDeletePages: (slugs: string[], opts: { sourceId: string; }) => Promise<string[]>",
"stageManifestRows: (rows: readonly ManifestRowInput[]) => Promise<void>",
"stageSegmentChunks: (pageId: number, generation: number, chunks: readonly SegmentChunkInput[], opts?: { embeddingColumn?: ResolvedColumn; }) => Promise<number[]>",
- "stageSegmentTexts: (sourceId: string, texts: readonly SegmentTextInput[]) => Promise<{ inserted: number; }>",
+ "stageSegmentTexts: (sourceId: string, texts: readonly SegmentTextInput[], opts?: { stagingId?: string; }) => Promise<{ inserted: number; }>",
"stripStaleFrontmatterKeys: (opts: { sourceId: string; ids: number[]; }) => Promise<number>",
"sumStaleChunkChars: (opts?: { sourceId?: string; signature?: string; includeNullSignature?: boolean; }) => Promise<number>",
"supersedeTake: (pageId: number, oldRow: number, newRow: Omit<TakeBatchInput, \"page_id\" | \"row_num\" | \"superseded_by\">) => Promise<{ oldRow: number; newRow: number; }>",
@@ -1261,7 +1261,7 @@
"sql: postgres.Sql<{}>",
"stageManifestRows: (rows: readonly ManifestRowInput[]) => Promise<void>",
"stageSegmentChunks: (pageId: number, generation: number, chunks: readonly SegmentChunkInput[], opts?: { embeddingColumn?: ResolvedColumn; }) => Promise<number[]>",
- "stageSegmentTexts: (sourceId: string, texts: readonly SegmentTextInput[]) => Promise<{ inserted: number; }>",
+ "stageSegmentTexts: (sourceId: string, texts: readonly SegmentTextInput[], opts?: { stagingId?: string; }) => Promise<{ inserted: number; }>",
"stripStaleFrontmatterKeys: (opts: { sourceId: string; ids: number[]; }) => Promise<number>",
"sumStaleChunkChars: (opts?: { sourceId?: string; signature?: string; includeNullSignature?: boolean; }) => Promise<number>",
"supersedeTake: (pageId: number, oldRow: number, newRow: Omit<TakeBatchInput, \"page_id\" | \"row_num\" | \"superseded_by\">) => Promise<{ oldRow: number; newRow: number; }>",
@@ -3504,7 +3504,7 @@
"softDeletePages: (slugs: string[], opts: { sourceId: string; }) => Promise<string[]>",
"stageManifestRows: (rows: readonly ManifestRowInput[]) => Promise<void>",
"stageSegmentChunks: (pageId: number, generation: number, chunks: readonly SegmentChunkInput[], opts?: { embeddingColumn?: ResolvedColumn; }) => Promise<number[]>",
- "stageSegmentTexts: (sourceId: string, texts: readonly SegmentTextInput[]) => Promise<{ inserted: number; }>",
+ "stageSegmentTexts: (sourceId: string, texts: readonly SegmentTextInput[], opts?: { stagingId?: string; }) => Promise<{ inserted: number; }>",
"stripStaleFrontmatterKeys: (opts: { sourceId: string; ids: number[]; }) => Promise<number>",
"sumStaleChunkChars: (opts?: { sourceId?: string; signature?: string; includeNullSignature?: boolean; }) => Promise<number>",
"supersedeTake: (pageId: number, oldRow: number, newRow: Omit<TakeBatchInput, \"page_id\" | \"row_num\" | \"superseded_by\">) => Promise<{ oldRow: number; newRow: number; }>",
@@ -6785,7 +6785,7 @@
"softDeletePages: (slugs: string[], opts: { sourceId: string; }) => Promise<string[]>",
"stageManifestRows: (rows: readonly ManifestRowInput[]) => Promise<void>",
"stageSegmentChunks: (pageId: number, generation: number, chunks: readonly SegmentChunkInput[], opts?: { embeddingColumn?: ResolvedColumn; }) => Promise<number[]>",
- "stageSegmentTexts: (sourceId: string, texts: readonly SegmentTextInput[]) => Promise<{ inserted: number; }>",
+ "stageSegmentTexts: (sourceId: string, texts: readonly SegmentTextInput[], opts?: { stagingId?: string; }) => Promise<{ inserted: number; }>",
"stripStaleFrontmatterKeys: (opts: { sourceId: string; ids: number[]; }) => Promise<number>",
"sumStaleChunkChars: (opts?: { sourceId?: string; signature?: string; includeNullSignature?: boolean; }) => Promise<number>",
"supersedeTake: (pageId: number, oldRow: number, newRow: Omit<TakeBatchInput, \"page_id\" | \"row_num\" | \"superseded_by\">) => Promise<{ oldRow: number; newRow: number; }>",
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 46634a10c7..b1cc297992 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -214,6 +214,8 @@
"page_body_staging_parts.page_body_staging_parts_part_no_check": "c CHECK ((part_no >= 0))",
"page_body_staging_parts.page_body_staging_parts_pkey": "p PRIMARY KEY (staging_id, part_no)",
"page_body_staging_parts.page_body_staging_parts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",
+ "page_body_staging_texts.page_body_staging_texts_pkey": "p PRIMARY KEY (staging_id, sha256)",
+ "page_body_staging_texts.page_body_staging_texts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",
"page_body_stagings.page_body_stagings_declared_bytes_check": "c CHECK ((declared_bytes >= 0))",
"page_body_stagings.page_body_stagings_kind_check": "c CHECK ((kind = ANY (ARRAY['upload'::text, 'import'::text, 'sync'::text, 'put'::text, 'append'::text, 'edit'::text, 'resegment'::text])))",
"page_body_stagings.page_body_stagings_mode_check": "c CHECK ((mode = ANY (ARRAY['create'::text, 'replace'::text, 'append'::text])))",
@@ -723,6 +725,9 @@
"page_body_staging_parts": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_body_staging_texts": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_body_stagings": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1206,6 +1211,8 @@
"page_body_manifest_staging": "CREATE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id) WHERE (staging_id IS NOT NULL)",
"page_body_manifest_text": "CREATE INDEX page_body_manifest_text ON public.page_body_manifest USING btree (source_id, sha256)",
"page_body_staging_parts_pkey": "CREATE UNIQUE INDEX page_body_staging_parts_pkey ON public.page_body_staging_parts USING btree (staging_id, part_no)",
+ "page_body_staging_texts_pkey": "CREATE UNIQUE INDEX page_body_staging_texts_pkey ON public.page_body_staging_texts USING btree (staging_id, sha256)",
+ "page_body_staging_texts_text": "CREATE INDEX page_body_staging_texts_text ON public.page_body_staging_texts USING btree (source_id, sha256)",
"page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",
"page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",
"page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)",
@@ -1643,7 +1650,8 @@
"30 local_ordinal integer/int4 NULL",
"31 raw_byte_start bigint/int8 NULL",
"32 raw_byte_end bigint/int8 NULL",
- "33 body_generation bigint/int8 NULL"
+ "33 body_generation bigint/int8 NULL",
+ "34 retired_generation bigint/int8 NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -2649,6 +2657,14 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_body_staging_texts": {
+ "columns": [
+ "1 staging_id uuid/uuid NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 sha256 bytea/bytea NOT NULL"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_body_stagings": {
"columns": [
"1 id uuid/uuid NOT NULL",
diff --git a/test/graduation-inventory.test.ts b/test/graduation-inventory.test.ts
index 22807e6afe..685bdb0ca9 100644
--- a/test/graduation-inventory.test.ts
+++ b/test/graduation-inventory.test.ts
@@ -60,7 +60,7 @@ describe('graduation inventory', () => {
expect(new Set(names).size).toBe(names.length);
const counts: Record<string, number> = {};
for (const e of GRADUATION_INVENTORY.entries) counts[e.class] = (counts[e.class] ?? 0) + 1;
- expect(counts).toEqual({ carry: 128, rebind: 2, rebuild: 3, discard: 7, schema_owned: 4 });
+ expect(counts).toEqual({ carry: 129, rebind: 2, rebuild: 3, discard: 7, schema_owned: 4 });
for (const e of GRADUATION_INVENTORY.entries) {
expect({ relation: e.relation, reason: e.reason.length > 5, present: e.engines.pglite || e.engines.postgres })
.toEqual({ relation: e.relation, reason: true, present: true });
diff --git a/test/large-pages/projection-demotion-race.test.ts b/test/large-pages/projection-demotion-race.test.ts
new file mode 100644
index 0000000000..fd50674449
--- /dev/null
+++ b/test/large-pages/projection-demotion-race.test.ts
@@ -0,0 +1,83 @@
+/**
+ * A projection build racing a demotion of its page (Wave B PR 2, lane A).
+ *
+ * 1. Protects: a segmented projection that read its page at generation G and is overtaken by a demotion (an inline
+ * write onto the page, committed at G+1 with its own inline chunks and seal) deletes none of the inline page's
+ * chunks: its retirement re-reads the page under the page lock and stops when the page is no longer segmented
+ * at G, so the demoted page stays searchable.
+ * 2. Fails when: retirement deletes every body_generation IS NULL row before checking the page's generation and
+ * storage, so the demotion's new inline chunks are lost while the inline page stays sealed and unqueued.
+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set. The interleaving is forced: the projection's
+ * manifest read (its first statement after reading the page) runs the demotion before it returns.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+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 { buildSegmentedProjection } from '../../src/core/page-body/projection.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { segmentedPageRow } from '../helpers/segmented-page-checks.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+
+function sections(tag: string, n = 60): string {
+ const parts: string[] = [];
+ for (let i = 0; i < n; i++) parts.push(`## Section ${tag}${i}\n\n` + `Paragraph ${i} of ${tag} about widgets and gadgets number ${i}. `.repeat(400) + '\n\n');
+ return parts.join('');
+}
+const page = (body: string) => `---\ntitle: Demotion race\ntype: note\n---\n\n${body}`;
+
+/** The engine with readManifest running before(target) once, after its own read and before it returns. */
+function withManifestHook(engine: BrainEngine, before: (target: BrainEngine) => Promise<void>): BrainEngine {
+ let fired = false;
+ return new Proxy(engine, {
+ get(target, prop) {
+ if (prop === 'readManifest') {
+ return async (...args: Parameters<BrainEngine['readManifest']>) => {
+ const rows = await target.readManifest(...args);
+ if (!fired) { fired = true; await before(target); }
+ return rows;
+ };
+ }
+ const value = Reflect.get(target, prop, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+}
+
+for (const kind of testBackends()) {
+ describe(`projection racing a demotion (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ close = () => engine.disconnect();
+ }
+ }, 120_000);
+ afterAll(async () => { await close?.(); });
+ beforeEach(async () => { await engine.setConfig('pages.segmented_storage', 'on'); });
+
+ test('a demotion that commits while the projection reads its manifest keeps its inline chunks and stays searchable', async () => {
+ const slug = 'notes/demotion-race';
+ await importFromContent(engine, slug, page(sections('a')), { sourceId: 'default', noEmbed: true });
+ const { id } = await segmentedPageRow(engine, slug);
+ await engine.executeRaw('UPDATE pages SET text_projection_revision = NULL WHERE id = $1', [id]);
+ const racing = withManifestHook(engine, async target => {
+ expect(await importFromContent(target, slug, page('A short replacement body about lighthouses and harbours.\n'), { sourceId: 'default', noEmbed: true }))
+ .toMatchObject({ status: 'imported' });
+ });
+ const result = await buildSegmentedProjection(racing, { sourceId: 'default', slug });
+ expect(result.sealed).toBe(false);
+ const row = await segmentedPageRow(engine, slug);
+ expect(row.body_storage).toBe('inline');
+ expect(row.text_projection_revision).toBe(row.knowledge_revision);
+ const [inline] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM content_chunks WHERE page_id = $1 AND body_generation IS NULL', [id]);
+ expect(Number(inline!.n)).toBeGreaterThan(0);
+ expect((await engine.searchKeyword('lighthouses', { limit: 5 })).map(r => r.slug)).toContain(slug);
+ }, 180_000);
+ });
+}
diff --git a/test/large-pages/purge-inflight-create.test.ts b/test/large-pages/purge-inflight-create.test.ts
new file mode 100644
index 0000000000..58e4651b8e
--- /dev/null
+++ b/test/large-pages/purge-inflight-create.test.ts
@@ -0,0 +1,125 @@
+/**
+ * Page purge while another write of the same text is in flight (Wave B PR 2, lane A).
+ *
+ * 1. Protects: delete_page purge:true and the TTL hard delete (purgeDeletedPages) of a segmented page never delete a
+ * segment text that a live staging staged or deduped onto (an in-flight create keeps its manifest rows in memory
+ * until it publishes), so the create publishes with its own text; and both still delete, in the same
+ * transaction, every text only the purged page referenced, even while an unrelated staging opened before that
+ * text was written is still live.
+ * 2. Fails when: the purge deletes every text no manifest row references (the in-flight create dies on
+ * page_body_manifest_source_id_sha256_fkey, 23503), or keeps texts by GC's time window (a live staging older
+ * than the text keeps the purged page's private text until it ends).
+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set.
+ */
+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 { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { parseMarkdown } from '../../src/core/markdown.ts';
+import { operations } from '../../src/core/operations.ts';
+import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';
+import { materializeSegmentedBody } from '../../src/core/page-body/ingest.ts';
+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';
+import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { stageSegmentedImport } from '../../src/core/persistence/segmented-apply.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { segmentedPageRow } from '../helpers/segmented-page-checks.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { TEST_WRITE_ATTRIBUTION } from '../helpers/write-attribution.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-purge-inflight-'));
+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+const ctx = (engine: BrainEngine): OperationContext => ({ engine, sourceId: 'default', remote: false, dryRun: false,
+ config: { engine: engine.kind, embedding_disabled: true, storage: { backend: 'local', bucket: 'b', localPath: join(home, 'storage') } },
+ logger: { info() {}, warn() {}, error() {} } } as OperationContext);
+const op = (name: string) => operations.find(o => o.name === name)!;
+const coordinated = <T>(engine: BrainEngine, fn: (tx: BrainEngine) => Promise<T>) =>
+ engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => fn(tx), TEST_WRITE_ATTRIBUTION));
+
+function sections(tag: string, n = 60): string {
+ const parts: string[] = [];
+ for (let i = 0; i < n; i++) parts.push(`## Section ${tag}${i}\n\n` + `Paragraph ${i} of ${tag} about widgets and gadgets number ${i}. `.repeat(400) + '\n\n');
+ return parts.join('');
+}
+const page = (title: string, body: string) => `---\ntitle: ${title}\ntype: note\n---\n\n${body}`;
+const tail = (word: string) => `## Tail\n\n${`Only this page says ${word} in its last section. `.repeat(300)}\n`;
+
+afterAll(() => { rmSync(home, { recursive: true, force: true }); });
+
+for (const kind of testBackends()) {
+ describe(`page purge with a write of the same text in flight (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => withEnv(env, async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); close = () => engine.disconnect(); }
+ await registerLocalWriter(engine, 'cli');
+ await engine.setConfig('pages.segmented_storage', 'on');
+ }), 120_000);
+ afterAll(async () => withEnv(env, async () => { await disposePersistenceConsumer(engine); await close?.(); }));
+
+ const shasOf = async (pageId: number) => (await engine.executeRaw<{ sha: string }>(
+ "SELECT DISTINCT encode(sha256,'hex') AS sha FROM page_body_manifest WHERE page_id=$1", [pageId])).map(r => r.sha);
+ const textsLeft = async (shas: readonly string[]) => Number((await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_segment_texts
+ WHERE source_id='default' AND sha256=ANY(SELECT decode(h,'hex') FROM unnest($1::text[]) AS h)`, [shas]))[0]!.n);
+
+ /** A create of slug whose preparation finished (texts staged, manifest rows held in memory) and has not published. */
+ async function inFlightCreate(slug: string, content: string) {
+ const parsed = parseMarkdown(content, `${slug}.md`);
+ const staged = await stageSegmentedImport(engine, { slug, sourceId: 'default', existing: null,
+ page: { title: parsed.title, type: parsed.type, compiled_truth: parsed.compiled_truth, timeline: parsed.timeline, frontmatter: parsed.frontmatter, tags: parsed.tags },
+ policy: await readPageBodyPolicy(engine), chunking: { quarantined: false, corpusGeneration: null, tier: 'none' }, baseRevision: null });
+ return {
+ parsed,
+ publish: () => engine.transaction(tx => staged.apply(tx, { type: parsed.type, title: parsed.title, frontmatter: parsed.frontmatter, page_kind: 'markdown' },
+ { mode: 'none', corpusGeneration: null })),
+ };
+ }
+
+ /** A staging of another slug, opened (live) before the purged page is written: GC's time window would keep that page's texts. */
+ async function olderLiveStaging(slug: string) {
+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");
+ await coordinated(engine, tx => tx.openBodyStaging({ id: randomUUID(), kind: 'upload', principalKind: 'application', principalId: 'test:fixture',
+ clientRequestId: randomUUID(), sourceId: 'default', sourceIncarnation: source!.incarnation, slug, pageId: null, mode: 'create', baseRevision: null,
+ baseGeneration: null, declaredBytes: 16, declaredSha256: null, reservedBytes: 0,
+ idleExpiresAt: new Date(Date.now() + 3_600_000), hardExpiresAt: new Date(Date.now() + 7_200_000) }));
+ await engine.executeRaw("UPDATE page_body_stagings SET created_at = now() - interval '1 minute' WHERE slug = $1", [slug]);
+ }
+
+ for (const path of ['delete_page purge', 'TTL hard delete'] as const) {
+ test(`${path}: the in-flight create publishes with the shared texts and the purged page's own texts are gone`, async () => withEnv(env, async () => {
+ const tag = randomUUID().slice(0, 8);
+ const purged = `notes/purged-${tag}`, created = `notes/created-${tag}`;
+ await olderLiveStaging(`notes/upload-${tag}`);
+ await importFromContent(engine, purged, page('Purged', sections(tag) + tail('purgedonlyword')), { sourceId: 'default', noEmbed: true });
+ const victim = await segmentedPageRow(engine, purged);
+ expect(victim.body_storage).toBe('segmented');
+ const create = await inFlightCreate(created, page('Created', sections(tag) + tail('createdonlyword')));
+ if (path === 'delete_page purge') {
+ const snapshot = await engine.readPageSnapshot(purged, { sourceId: 'default', includeDeleted: true });
+ const result = await op('delete_page').handler(ctx(engine), { slug: purged, purge: true, request_id: randomUUID(), expected_revision: snapshot!.revision }) as Record<string, any>;
+ expect(result.status).toBe('purged');
+ const segmentStore = (result.receipt.stores as Array<{ store: string; status: string }>).find(s => s.store === 'page_segment_texts');
+ expect(segmentStore?.status).toBe('deleted');
+ } else {
+ await coordinated(engine, tx => tx.softDeletePage(purged, { sourceId: 'default' }));
+ await engine.executeRaw("UPDATE pages SET deleted_at = now() - interval '96 hours' WHERE source_id='default' AND slug=$1", [purged]);
+ expect((await engine.purgeDeletedPages(72)).slugs).toEqual([purged]);
+ }
+ expect(await engine.executeRaw("SELECT 1 FROM page_segment_texts WHERE source_id='default' AND strpos(convert_from(body,'UTF8'), 'purgedonlyword') > 0")).toHaveLength(0);
+ await create.publish();
+ const row = await segmentedPageRow(engine, created);
+ const body = await materializeSegmentedBody(engine, row.id, 'default');
+ expect(body.compiled_truth).toBe(create.parsed.compiled_truth);
+ expect(await textsLeft(await shasOf(row.id))).toBe((await shasOf(row.id)).length);
+ }), 240_000);
+ }
+ });
+}
diff --git a/test/large-pages/restore-deferred-retire.test.ts b/test/large-pages/restore-deferred-retire.test.ts
new file mode 100644
index 0000000000..076d9f61d5
--- /dev/null
+++ b/test/large-pages/restore-deferred-retire.test.ts
@@ -0,0 +1,105 @@
+/**
+ * restore_page of a segmented page over the single-string ceiling whose retirement was deferred (Wave B PR 2, lane A).
+ *
+ * 1. Protects: a page over PAGE_MAX_BYTES whose replace deferred its chunk retirement (more rows than
+ * pages.flip_retire_max_rows) and whose post-commit projection never ran, then was soft-deleted (as sync does
+ * when its file goes), is restored
+ * unsealed with its projection pending, and the restore's projection retires the old rows before it seals: the
+ * old body's text is never searchable after the restore.
+ * 2. Fails when: the restore seals once every live occurrence has chunks, ignoring rows of retired occurrences that
+ * are still stored (chunkVisibleFilter shows every row at or below the live generation of a sealed page).
+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set. The lost projection is forced: the replace runs on an
+ * engine whose projection page read throws (the import catches it, as a process death after commit leaves it).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } 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 { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { importFromFile } from '../../src/core/import-file.ts';
+import { operations } from '../../src/core/operations.ts';
+import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';
+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';
+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { conversationPage } from '../helpers/conversation-page.ts';
+import { segmentedPageRow } from '../helpers/segmented-page-checks.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';
+import { TEST_WRITE_ATTRIBUTION } from '../helpers/write-attribution.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-restore-deferred-'));
+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+
+const ctx = (engine: BrainEngine): OperationContext => ({ engine, sourceId: 'default', remote: false, dryRun: false,
+ config: { engine: engine.kind, embedding_disabled: true, storage: { backend: 'local', bucket: 'b', localPath: join(home, 'storage') } },
+ logger: { info() {}, warn() {}, error() {} } } as OperationContext);
+const op = (name: string) => operations.find(o => o.name === name)!;
+const PROJECTION_PAGE_READ = "FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL AND body_storage='segmented'";
+
+/** The engine with the segmented projection's page read failing: the post-commit projection is lost. */
+function projectionLost(engine: BrainEngine): BrainEngine {
+ return new Proxy(engine, {
+ get(target, prop) {
+ if (prop === 'executeRaw') {
+ return (sql: string, params?: unknown[]) => sql.includes(PROJECTION_PAGE_READ)
+ ? Promise.reject(new Error('projection lost (probe)')) : target.executeRaw(sql, params);
+ }
+ const value = Reflect.get(target, prop, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+}
+
+const before = conversationPage(PAGE_MAX_BYTES + 1024 * 1024, { seed: 97, needles: [{ at: 0.5, word: 'oldmarkerxylophone' }] });
+const after = before.replace('oldmarkerxylophone', 'newmarkerzeppelin');
+afterAll(() => { rmSync(home, { recursive: true, force: true }); });
+
+for (const kind of testBackends()) describe(`restore_page of a page whose retirement was deferred (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => withEnv(env, async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); close = () => engine.disconnect(); }
+ await registerLocalWriter(engine, 'cli');
+ await engine.setConfig('pages.segmented_storage', 'on');
+ }), 120_000);
+ afterAll(async () => withEnv(env, async () => { await disposePersistenceConsumer(engine); await close?.(); }));
+
+ test('the restore leaves the page unsealed until its projection retired the old rows', async () => withEnv(env, async () => {
+ {
+ const dir = join(home, `restore-${randomUUID().slice(0, 8)}`);
+ mkdirSync(dir, { recursive: true });
+ const file = join(dir, 'huge.md');
+ const slug = `notes/huge-${randomUUID().slice(0, 8)}`;
+ writeFileSync(file, before);
+ expect(await importFromFile(engine, file, `${slug}.md`, { noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) })).toMatchObject({ status: 'imported' });
+ await engine.setConfig('pages.flip_retire_max_rows', '1');
+ writeFileSync(file, after);
+ expect(await importFromFile(projectionLost(engine), file, `${slug}.md`, { noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) }))
+ .toMatchObject({ status: 'imported' });
+ await engine.setConfig('pages.flip_retire_max_rows', '20000');
+ const page = await segmentedPageRow(engine, slug);
+ expect(page.text_projection_revision).not.toBe(page.knowledge_revision);
+ const [stale] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM content_chunks WHERE page_id=$1 AND strpos(chunk_text, 'oldmarkerxylophone') > 0`, [page.id]);
+ expect(Number(stale!.n)).toBeGreaterThan(0);
+
+ // Soft-deleted as sync leaves a page whose file was removed (no write of its own drains the projection queue).
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.softDeletePage(slug, { sourceId: 'default' }), TEST_WRITE_ATTRIBUTION));
+ const restored = await op('restore_page').handler(ctx(engine), { slug, request_id: randomUUID(),
+ expected_revision: (await engine.readPageSnapshot(slug, { sourceId: 'default', includeDeleted: true }))!.revision }) as Record<string, unknown>;
+ expect(restored.status).toBe('restored');
+ const found = async (word: string) => (await engine.searchKeyword(word, { limit: 10 })).filter(r => r.slug === slug).length;
+ expect(await found('oldmarkerxylophone')).toBe(0);
+ expect(restored.projection).toBe('pending');
+ const row = await segmentedPageRow(engine, slug);
+ expect(row.text_projection_revision).toBe(row.knowledge_revision);
+ expect(await found('newmarkerzeppelin')).toBeGreaterThan(0);
+ }
+ }), 1_200_000);
+});
diff --git a/test/large-pages/segment-rewrite-cr-tier.test.ts b/test/large-pages/segment-rewrite-cr-tier.test.ts
new file mode 100644
index 0000000000..0df8d44786
--- /dev/null
+++ b/test/large-pages/segment-rewrite-cr-tier.test.ts
@@ -0,0 +1,98 @@
+/**
+ * A fence rewrite of a segmented page reuses vectors under the page's contextual-retrieval mode (Wave B PR 2, lane A).
+ *
+ * 1. Protects: on a page imported with contextual retrieval on (title tier, its corpus generation stamped), a
+ * withdrawal's fence rewrite (rewriteLiveSegmentedFences, also run by fact purge and reseal) carries each stored
+ * vector of an unchanged chunk in the rewritten segment onto its new row, as an import of the same body does.
+ * 2. Fails when: the rewrite stages its chunks under tier 'none' and no corpus generation, so no title-tier vector
+ * passes the input-hash gate and every chunk of the rewritten segment loses its vector until re-embedded.
+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set. Vectors are written as a completed embedding pass
+ * records them (constant vector, title-tier embedding_input_hash); no provider runs.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+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 { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { embeddingInputHash } from '../../src/core/embedding-input-hash.ts';
+import { embeddingInputContext, embeddingWriteTarget } from '../../src/core/page-state/projections.ts';
+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';
+import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';
+import { recordFactWithdrawal } from '../../src/core/facts/withdrawal.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { fakeEmbedPage, segmentedPageRow } from '../helpers/segmented-page-checks.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { TEST_WRITE_ATTRIBUTION } from '../helpers/write-attribution.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const CLAIM = 'Prefers the aisle seat';
+const home = mkdtempSync(join(tmpdir(), 'gbrain-rewrite-cr-tier-'));
+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: 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 row = (n: number, claim: string) => `| ${n} | ${claim} | preference | 1.0 | world | medium | 2026-01-01 | | chat | |`;
+function filler(tag: string, bytes: number): string {
+ const parts: string[] = [];
+ for (let i = 0, n = 0; n < bytes; i++) {
+ const part = `## ${tag} ${i}\n\n${`Meeting notes on hiring, budget and the design review, item ${i}. `.repeat(30)}\n\n`;
+ parts.push(part);
+ n += part.length;
+ }
+ return parts.join('');
+}
+const TITLE = 'Seating plan';
+const body = `---\ntitle: ${TITLE}\ntype: note\n---\n\n# ${TITLE}\n\n${filler('Part one', 700_000)}`
+ + `## Facts\n\n${fence([row(1, CLAIM), row(2, 'Walks to work')])}\n\n${filler('Part two', 700_000)}`;
+const coordinated = <T>(engine: BrainEngine, fn: (tx: BrainEngine) => Promise<T>) =>
+ engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => fn(tx), TEST_WRITE_ATTRIBUTION));
+
+afterAll(() => { rmSync(home, { recursive: true, force: true }); });
+
+for (const kind of testBackends()) {
+ describe(`fence rewrite vector reuse under contextual retrieval (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => withEnv(env, async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); close = () => engine.disconnect(); }
+ await registerLocalWriter(engine, 'cli');
+ await engine.setConfig('pages.segmented_storage', 'on');
+ await engine.executeRaw("UPDATE sources SET contextual_retrieval_mode = 'title' WHERE id = 'default'");
+ }), 120_000);
+ afterAll(async () => { await close?.(); });
+
+ test('a withdrawal keeps the title-tier vectors of unchanged chunks in the rewritten segment', async () => withEnv(env, async () => {
+ const slug = 'notes/seating-plan';
+ await importFromContent(engine, slug, body, { noEmbed: true, sourceId: 'default' });
+ const page = await segmentedPageRow(engine, slug);
+ expect(page.body_storage).toBe('segmented');
+ const [state] = await engine.executeRaw<{ mode: string | null; generation: string | null }>(
+ 'SELECT contextual_retrieval_mode AS mode, corpus_generation AS generation FROM pages WHERE id = $1', [page.id]);
+ expect(state).toMatchObject({ mode: 'title' });
+ expect(state!.generation).not.toBeNull();
+ await fakeEmbedPage(engine, page.id);
+ const provenance = embeddingInputContext(await embeddingWriteTarget(engine), TITLE, state!.generation, []);
+ const stored = await engine.executeRaw<{ id: number; chunk_text: string; chunk_source: string }>('SELECT id, chunk_text, chunk_source FROM content_chunks WHERE page_id = $1', [page.id]);
+ for (const chunk of stored) {
+ await engine.executeRaw('UPDATE content_chunks SET embedding_input_hash = $2, embedded_at = now(), embedded_text_hash = md5(chunk_text) WHERE id = $1',
+ [chunk.id, embeddingInputHash(provenance, 'title', chunk)]);
+ }
+ const [fact] = await coordinated(engine, tx => tx.executeRaw<{ id: number }>(`INSERT INTO facts(source_id,fact,entity_slug,visibility,source,source_markdown_slug,row_num)
+ VALUES ('default',$1,NULL,'world','test',$2,1) RETURNING id`, [CLAIM, slug]));
+ expect((await coordinated(engine, tx => recordFactWithdrawal(tx, Number(fact!.id), 'default'))).withdrawn).toBe(true);
+ const after = await segmentedPageRow(engine, slug);
+ expect(after.body_generation).toBe(page.body_generation + 1);
+ const [rewritten] = await engine.executeRaw<{ total: number; same_text: number; reused: number }>(`SELECT count(*)::int AS total,
+ count(*) FILTER (WHERE c.chunk_text = ANY($3::text[]))::int AS same_text,
+ count(*) FILTER (WHERE c.chunk_text = ANY($3::text[]) AND c.embedding IS NOT NULL)::int AS reused
+ FROM content_chunks c WHERE c.page_id = $1 AND c.body_generation = $2`, [page.id, after.body_generation, stored.map(chunk => chunk.chunk_text)]);
+ expect(rewritten!.same_text).toBeGreaterThan(0);
+ expect(rewritten!.reused).toBe(rewritten!.same_text);
+ }), 300_000);
+ });
+}
diff --git a/test/large-pages/segmented-loser-chunks.test.ts b/test/large-pages/segmented-loser-chunks.test.ts
new file mode 100644
index 0000000000..37915154aa
--- /dev/null
+++ b/test/large-pages/segmented-loser-chunks.test.ts
@@ -0,0 +1,130 @@
+/**
+ * Two preparations of one segmented page that both target generation G+1 (Wave B PR 2, lane A).
+ *
+ * 1. Protects: when preparation A flips to G+1 while preparation B is still staging, B's next chunk batch (whose
+ * occurrences only B's unpublished staging owns) refuses with revision_changed instead of landing at the page's
+ * live generation, so B's unpublished text never becomes searchable on the sealed page; and segment GC deletes
+ * chunk rows of occurrences that only a dead staging owned when an older binary left them at the live
+ * generation.
+ * 2. Fails when: stageSegmentChunks accepts a batch at the live generation without checking that its occurrences
+ * are in the published manifest of that generation, or the sweep deletes only chunk rows above the live
+ * generation.
+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set. The race is forced with the
+ * segmented:manifest_staged fault point: B pauses after staging its manifest rows, A imports and seals,
+ * then B resumes and stages its chunks. Search plans are untouched (chunkVisibleFilter keeps its row
+ * predicate; test/e2e/vector-chunk-statistics-postgres.test.ts holds the vector plan).
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+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 { parseMarkdown } from '../../src/core/markdown.ts';
+import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';
+import { installFaultHook } from '../../src/core/persistence/fault-points.ts';
+import { abortSegmentedStaging, stageSegmentedImport } from '../../src/core/persistence/segmented-apply.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { manifestRow, segmentText, stagingInput } from '../helpers/page-body-fixtures.ts';
+import { segmentedPageRow } from '../helpers/segmented-page-checks.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+
+function sections(tag: string, n = 60): string {
+ const parts: string[] = [];
+ for (let i = 0; i < n; i++) parts.push(`## Section ${tag}${i}\n\n` + `Paragraph ${i} of ${tag} about widgets and gadgets number ${i}. `.repeat(400) + '\n\n');
+ return parts.join('');
+}
+const page = (body: string) => `---\ntitle: Two preparers\ntype: note\n---\n\n${body}`;
+const LOSER = '## Loser\n\n' + 'UNPUBLISHED quixotic staged text that only the losing preparation wrote. '.repeat(200) + '\n\n';
+const WINNER = '## Winner\n\n' + 'Published zebracrossing section that the winning preparation wrote. '.repeat(200) + '\n\n';
+
+for (const kind of testBackends()) {
+ describe(`two preparations of one generation (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ close = () => engine.disconnect();
+ }
+ }, 120_000);
+ afterAll(async () => { await close?.(); });
+ beforeEach(async () => { await engine.setConfig('pages.segmented_storage', 'on'); });
+ afterEach(() => { installFaultHook(undefined); });
+
+ const quixoticRows = async (pageId: number) => Number((await engine.executeRaw<{ n: number }>(
+ "SELECT count(*)::int AS n FROM content_chunks WHERE page_id=$1 AND strpos(chunk_text, 'quixotic') > 0", [pageId]))[0]!.n);
+ const found = async (word: string, slug: string) => (await engine.searchKeyword(word, { limit: 20 })).filter(r => r.slug === slug).length;
+
+ test('the losing preparation cannot stage chunks at the generation the winner published', async () => {
+ const slug = `notes/two-preparers-${randomUUID().slice(0, 8)}`;
+ await importFromContent(engine, slug, page(sections('a')), { sourceId: 'default', noEmbed: true });
+ const { id } = await segmentedPageRow(engine, slug);
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ let paused!: () => void;
+ const pausedAt = new Promise<void>(resolve => { paused = resolve; });
+ let armed = true;
+ installFaultHook(async point => {
+ if (!armed || point !== 'segmented:manifest_staged') return;
+ armed = false;
+ paused();
+ await gate;
+ });
+ const loserContent = page(LOSER + sections('a'));
+ const parsed = parseMarkdown(loserContent, `${slug}.md`);
+ const loser = stageSegmentedImport(engine, { slug, sourceId: 'default', existing: await engine.getPage(slug, { sourceId: 'default' }),
+ page: { title: parsed.title, type: parsed.type, compiled_truth: parsed.compiled_truth, timeline: parsed.timeline, frontmatter: parsed.frontmatter, tags: parsed.tags },
+ policy: await readPageBodyPolicy(engine), chunking: { quarantined: false, corpusGeneration: null, tier: 'none' }, baseRevision: null })
+ .then(staged => ({ staged, error: null }), (error: unknown) => ({ staged: null, error: error as { canonical?: string } }));
+ await pausedAt;
+ expect(await importFromContent(engine, slug, page(WINNER + sections('a')), { sourceId: 'default', noEmbed: true })).toMatchObject({ status: 'imported' });
+ expect((await segmentedPageRow(engine, slug)).body_generation).toBe(2);
+ release();
+ const outcome = await loser;
+ if (outcome.staged) {
+ const applied = await engine.transaction(tx => outcome.staged!.apply(tx, { type: parsed.type, title: parsed.title, frontmatter: parsed.frontmatter, page_kind: 'markdown' },
+ { mode: 'none', corpusGeneration: null })).then(() => null, (error: unknown) => error as { canonical?: string });
+ expect(applied?.canonical).toBe('revision_changed');
+ await abortSegmentedStaging(engine, outcome.staged.prepared);
+ }
+ await engine.sweepSegments({ pageId: id });
+ await engine.sweepSegments({ sourceId: 'default', expireStagings: true });
+ const row = await segmentedPageRow(engine, slug);
+ expect(row.text_projection_revision).toBe(row.knowledge_revision);
+ expect(await found('zebracrossing', slug)).toBeGreaterThan(0);
+ expect(await found('quixotic', slug)).toBe(0);
+ expect(await quixoticRows(id)).toBe(0);
+ expect(outcome.error?.canonical).toBe('revision_changed');
+ }, 240_000);
+
+ test('segment GC deletes live-generation chunk rows of an occurrence only a dead staging owned', async () => {
+ const slug = `notes/orphaned-chunks-${randomUUID().slice(0, 8)}`;
+ await importFromContent(engine, slug, page(sections('b')), { sourceId: 'default', noEmbed: true });
+ const { id, body_generation: generation } = await segmentedPageRow(engine, slug);
+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");
+ const staging = stagingInput({ slug, pageId: id, mode: 'replace', kind: 'import', sourceIncarnation: source!.incarnation, baseGeneration: generation });
+ const text = segmentText('UNPUBLISHED quixotic orphan text a pre-fix preparation left behind.\n');
+ const [occurrence] = await engine.allocateBodyOccurrenceIds(1);
+ await engine.openBodyStaging(staging);
+ await engine.stageSegmentTexts('default', [text]);
+ await engine.stageManifestRows([manifestRow({ pageId: id, occurrenceId: occurrence!, genFrom: generation + 1, seq: 0, text, byteStart: 0, stagingId: staging.id })]);
+ // What a losing preparation's late batch left on an older binary: a row at the live generation, owned only by its staging.
+ await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, model, occurrence_id, local_ordinal,
+ raw_byte_start, raw_byte_end, body_generation)
+ SELECT $1, COALESCE(MAX(chunk_index), -1) + 1, $2, 'compiled_truth', 'unconfigured', $3, 0, 0, 10, $4 FROM content_chunks WHERE page_id = $1`,
+ [id, new TextDecoder().decode(text.body), occurrence, generation]);
+ await engine.setBodyStagingState(staging.id, 'aborted');
+ expect(await found('quixotic', slug)).toBe(1);
+ const rows = async () => Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM content_chunks WHERE page_id=$1', [id]))[0]!.n);
+ const before = await rows();
+ await engine.sweepSegments({ sourceId: 'default' });
+ expect(await quixoticRows(id)).toBe(0);
+ expect(await found('quixotic', slug)).toBe(0);
+ expect(await rows()).toBe(before - 1);
+ }, 120_000);
+ });
+}
diff --git a/test/large-pages/segmented-storage-visibility.test.ts b/test/large-pages/segmented-storage-visibility.test.ts
index bdc4f6120a..1d2a8e6a5d 100644
--- a/test/large-pages/segmented-storage-visibility.test.ts
+++ b/test/large-pages/segmented-storage-visibility.test.ts
@@ -9,14 +9,15 @@
* until publication references it; a page-scoped sweep collects only the
* texts its page released; chunks of a shifted occurrence keep stored
* spans that hold their text in the new body; segment GC's staged-chunk
- * delete reads an index, not the whole chunk table; v249 drops
- * content_chunks.retired_generation, which no reader still names.
+ * delete reads an index, not the whole chunk table; v249 keeps
+ * content_chunks.retired_generation for released readers, and no reader at
+ * this version names it.
* 2. Fails when: visibility trusts body_generation alone, stageSegmentChunks
* skips the page's current generation and storage, text staging leaves a
* deduped text unlocked and its grace unrefreshed, the text sweep ignores
* live stagings, a page sweep scans its source's texts, raw spans are
* absolute body offsets, content_chunks_generation_idx is missing, or
- * v249 leaves retired_generation behind or a chunk reader still names it.
+ * v249 drops retired_generation or a chunk reader at this version names it.
* 3. Runs on PGLite, and on Postgres when DATABASE_URL is set.
*/
import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
@@ -275,23 +276,28 @@ for (const kind of testBackends()) {
}
}, 180_000);
- test('v249 drops retired_generation from a v248 brain and builds the GC index; no chunk reader names the column', async () => {
+ test('v249 keeps retired_generation on a v248 brain and builds the GC index; no chunk reader names the column', async () => {
const columns = async () => (await engine.executeRaw<{ attname: string }>(
"SELECT attname FROM pg_attribute WHERE attrelid = 'content_chunks'::regclass AND attnum > 0 AND NOT attisdropped")).map(r => r.attname);
- expect(await columns()).not.toContain('retired_generation');
+ expect(await columns()).toContain('retired_generation');
await importFromContent(engine, 'notes/upgraded', page(sections('u')), { sourceId: 'default', noEmbed: true });
- await engine.executeRaw('ALTER TABLE content_chunks ADD COLUMN retired_generation BIGINT');
await engine.executeRaw('DROP INDEX content_chunks_generation_idx');
- await engine.executeRaw(v249.sql);
+ if (v249.sql) await engine.executeRaw(v249.sql);
await v249.handler!(engine);
- expect(await columns()).not.toContain('retired_generation');
+ expect(await columns()).toContain('retired_generation');
const [index] = await engine.executeRaw<{ indexdef: string }>("SELECT indexdef FROM pg_indexes WHERE indexname = 'content_chunks_generation_idx'");
expect(index?.indexdef).toContain('WHERE (body_generation IS NOT NULL)');
- for (const excludePrivate of [false, true]) {
- expect((await engine.searchKeyword('widgets', { limit: 5, excludePrivate, requireSafeChunks: false })).length).toBeGreaterThan(0);
- expect((await engine.getChunks('notes/upgraded', { sourceId: 'default', excludePrivate, requireSafeChunks: false })).length).toBeGreaterThan(0);
+ // The column stays for released readers (v249-master-reader-compat.test.ts); head's readers must not name it.
+ await engine.executeRaw('ALTER TABLE content_chunks RENAME COLUMN retired_generation TO retired_generation_hidden');
+ try {
+ for (const excludePrivate of [false, true]) {
+ expect((await engine.searchKeyword('widgets', { limit: 5, excludePrivate, requireSafeChunks: false })).length).toBeGreaterThan(0);
+ expect((await engine.getChunks('notes/upgraded', { sourceId: 'default', excludePrivate, requireSafeChunks: false })).length).toBeGreaterThan(0);
+ }
+ expect((await generationReaderTexts('notes/upgraded')).length).toBeGreaterThan(0);
+ } finally {
+ await engine.executeRaw('ALTER TABLE content_chunks RENAME COLUMN retired_generation_hidden TO retired_generation');
}
- expect((await generationReaderTexts('notes/upgraded')).length).toBeGreaterThan(0);
}, 120_000);
test('the unscoped staged-chunk GC reads content_chunks through an index, never a full scan', async () => {
diff --git a/test/large-pages/v249-master-reader-compat.test.ts b/test/large-pages/v249-master-reader-compat.test.ts
new file mode 100644
index 0000000000..7585dd5856
--- /dev/null
+++ b/test/large-pages/v249-master-reader-compat.test.ts
@@ -0,0 +1,84 @@
+/**
+ * The released chunk readers keep working on a schema this branch migrated (Wave B PR 2, mixed-version window).
+ *
+ * 1. Protects: a process still running the released binary (master's chunkGenerationFilter, which names
+ * content_chunks.retired_generation) reads chunks of a brain whose schema this branch migrated through v249,
+ * with segmented storage on or off; v249 keeps the column (nothing at head writes or reads it) and still
+ * builds the GC index.
+ * 2. Fails when: v249 drops retired_generation before the writer floor excludes every binary whose search,
+ * get_chunks or embed queue selects it (they fail with 42703 on ordinary search).
+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set. The filter text is copied verbatim from
+ * origin/master 3ed487d2 src/core/search/safe-chunks.ts, so the probe does not move when head's filter changes.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+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 { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { segmentedPageRow } from '../helpers/segmented-page-checks.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+
+function masterChunkGenerationFilter(page: string, chunk: string): string {
+ return `(${chunk}.body_generation IS NULL
+ OR (${chunk}.body_generation <= ${page}.body_generation
+ AND (${chunk}.retired_generation IS NULL OR ${chunk}.retired_generation > ${page}.body_generation)))`;
+}
+function masterChunkGenerationProbe(chunk: string): string {
+ return `(${chunk}.body_generation IS NULL
+ OR EXISTS (SELECT 1 FROM pages gp WHERE gp.id = ${chunk}.page_id AND ${masterChunkGenerationFilter('gp', chunk)}))`;
+}
+function masterChunkVisibleFilter(page: string, chunk: string): string {
+ return `((${page}.text_projection_revision = ${page}.knowledge_revision) IS TRUE AND ${masterChunkGenerationFilter(page, chunk)})`;
+}
+
+function sections(tag: string, n = 60): string {
+ const parts: string[] = [];
+ for (let i = 0; i < n; i++) parts.push(`## Section ${tag}${i}\n\n` + `Paragraph ${i} of ${tag} about widgets and gadgets number ${i}. `.repeat(400) + '\n\n');
+ return parts.join('');
+}
+const page = (body: string) => `---\ntitle: Mixed version\ntype: note\n---\n\n${body}`;
+
+for (const kind of testBackends()) {
+ describe(`v249 keeps the column master's chunk readers select (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ close = () => engine.disconnect();
+ }
+ }, 120_000);
+ afterAll(async () => { await close?.(); });
+
+ for (const storage of ['off', 'on'] as const) {
+ test(`master's search, chunk read and embed-queue predicates run on the migrated schema (segmented storage ${storage})`, async () => {
+ await engine.setConfig('pages.segmented_storage', storage);
+ const slug = `notes/mixed-${storage}`;
+ await importFromContent(engine, slug, page(sections(storage)), { sourceId: 'default', noEmbed: true });
+ const row = await segmentedPageRow(engine, slug);
+ expect(row.body_storage).toBe(storage === 'on' ? 'segmented' : 'inline');
+ const [visible] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM content_chunks c JOIN pages p ON p.id = c.page_id
+ WHERE p.id = $1 AND ${masterChunkVisibleFilter('p', 'c')}`, [row.id]);
+ expect(Number(visible!.n)).toBeGreaterThan(0);
+ const [probed] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM content_chunks c
+ WHERE c.page_id = $1 AND ${masterChunkGenerationProbe('c')}`, [row.id]);
+ expect(Number(probed!.n)).toBe(Number(visible!.n));
+ const [keyword] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM content_chunks c JOIN pages p ON p.id = c.page_id
+ WHERE p.id = $1 AND c.search_vector @@ plainto_tsquery('english', 'widgets') AND ${masterChunkVisibleFilter('p', 'c')}`, [row.id]);
+ expect(Number(keyword!.n)).toBeGreaterThan(0);
+ }, 120_000);
+ }
+
+ test('v249 builds the GC index and leaves retired_generation in place', async () => {
+ const [column] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM information_schema.columns
+ WHERE table_name = 'content_chunks' AND column_name = 'retired_generation'`);
+ expect(Number(column!.n)).toBe(1);
+ const [index] = await engine.executeRaw<{ indexdef: string }>("SELECT indexdef FROM pg_indexes WHERE indexname = 'content_chunks_generation_idx'");
+ expect(index?.indexdef).toContain('WHERE (body_generation IS NOT NULL)');
+ }, 60_000);
+ });
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 75dceb8de2..23da9dd0f2 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -73,11 +73,15 @@ test/large-pages/managed-sync-segmented-rename.test.ts
test/large-pages/managed-sync-streamed.test.ts
test/large-pages/oversized-backfill-segmented.test.ts
test/large-pages/page-purge-segments.test.ts
+test/large-pages/projection-demotion-race.test.ts
test/large-pages/projection-parity.test.ts
+test/large-pages/purge-inflight-create.test.ts
test/large-pages/purge-segments.test.ts
test/large-pages/remote-get-page-privacy.test.ts
test/large-pages/remote-window-privacy.test.ts
+test/large-pages/restore-deferred-retire.test.ts
test/large-pages/sealed-segmented-search.test.ts
+test/large-pages/segment-rewrite-cr-tier.test.ts
test/large-pages/segment-vector-reuse.test.ts
test/large-pages/segmented-append-reembed.test.ts
test/large-pages/segmented-body-unreachable.test.ts
@@ -95,6 +99,7 @@ test/large-pages/segmented-file-drift.test.ts
test/large-pages/segmented-get-cli.test.ts
test/large-pages/segmented-get-page-parity.test.ts
test/large-pages/segmented-leads.test.ts
+test/large-pages/segmented-loser-chunks.test.ts
test/large-pages/segmented-maintenance-commands.test.ts
test/large-pages/segmented-read-refusals.test.ts
test/large-pages/segmented-remember-refusal.test.ts
@@ -104,6 +109,7 @@ test/large-pages/segmented-shrink-below-ceiling.test.ts
test/large-pages/segmented-storage-visibility.test.ts
test/large-pages/segmented-switch.test.ts
test/large-pages/segmented-versions.test.ts
+test/large-pages/v249-master-reader-compat.test.ts
test/link-cross-source.test.ts
test/link-preparation-shared-index.test.ts
test/links-attendance-blocked.test.ts