Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Wave B PR 1: review fixes for the generation flip, staging and the facts-region key projection

garrytanfbfd44fc2419
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 6eb6084c69..0a4e348640 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -298,6 +298,14 @@ More: [docs/guides/in-agent-setup.md#6-back-up-the-complete-local-database](../.
|---|---|---|---|---|---|---|
| Benchmark rule check unknown op. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### body_staging_expired
+
+<a id="body_staging_expired"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The staged body of a large-page write expired before it was published, so nothing was published. | A segmented write stages its segments first and publishes them in one flip; a staging idle past its deadline is collected by maintenance, and publishing without its segments would leave the page missing text. | Send the same write again; it stages a fresh copy. | agent | `repeat the read that failed` | 1 | yes |
+
### bootstrap_empty
<a id="bootstrap_empty"></a>
diff --git a/src/core/engine-sql/page-body.ts b/src/core/engine-sql/page-body.ts
index a86995ccbf..68b37001d3 100644
--- a/src/core/engine-sql/page-body.ts
+++ b/src/core/engine-sql/page-body.ts
@@ -265,11 +265,19 @@ export async function flipBodyGeneration(exec: SqlExecutor, input: BodyFlipInput
fix: readFix('Returns the current revision and size.', { argv: ['gbrain', 'get', '--source', page.source_id, '--', page.slug],
mcp: { tool: 'get_page', arguments: { slug: page.slug, source_id: page.source_id, body: 'none' } } }) });
}
- const stagedOccurrences = sqlFragment`(SELECT s.occurrence_id FROM page_body_manifest s WHERE s.page_id = ${input.pageId} AND s.staging_id = ${input.stagingId}::uuid)`;
+ const { rows: stagings } = await tx.run<{ state: string }>(sqlFragment`SELECT state FROM page_body_stagings WHERE id = ${input.stagingId}::uuid FOR UPDATE`);
+ if (!LIVE_STAGING_STATES.includes(stagings[0]?.state ?? '')) {
+ throw opError('body_staging_expired', `The staged body of this write to ${page.slug} is ${stagings[0]?.state ?? 'gone'}, so nothing was published.`,
+ 'The write waited past its staging deadline and its staged segments were collected. Send the write again.',
+ { detail: JSON.stringify({ staging_id: input.stagingId, state: stagings[0]?.state ?? null }) });
+ }
+ const newLive = sqlFragment`(SELECT s.occurrence_id FROM page_body_manifest s WHERE s.page_id = ${input.pageId}
+ AND (s.staging_id = ${input.stagingId}::uuid
+ OR (s.staging_id IS NULL AND s.gen_to IS NULL AND NOT (s.occurrence_id = ANY(${[...input.closeOccurrences]}::bigint[])))))`;
const retire = sqlFragment`c.page_id = ${input.pageId} AND c.retired_generation IS NULL AND (
- c.occurrence_id = ANY(${[...input.retireChunkOccurrences]}::bigint[])
+ (c.occurrence_id = ANY(${[...input.retireChunkOccurrences]}::bigint[]) AND c.body_generation <= ${input.expectedGeneration}::bigint)
OR (${input.retireInlineChunks === true}::boolean AND c.body_generation IS NULL)
- OR (c.body_generation = ${input.newGeneration}::bigint AND c.occurrence_id NOT IN ${stagedOccurrences}))`;
+ OR (c.body_generation = ${input.newGeneration}::bigint AND c.occurrence_id NOT IN ${newLive}))`;
// chunk-visibility-ok: the flip itself selects the rows it retires, across generations
const { rows: counted } = await tx.run<{ n: unknown }>(sqlFragment`SELECT count(*)::bigint AS n FROM content_chunks c WHERE ${retire}`);
const toRetire = Number(counted[0]?.n ?? 0);
@@ -319,8 +327,9 @@ export async function setBodyStagingState(exec: SqlExecutor, id: string, state:
/**
* Garbage collection (spec 3.5). Roots: each segmented page's live generation,
* every generation a page_versions row references, and staged rows of live
- * stagings (`liveStagingIds`). Deletes retired chunk rows, staged chunk rows
- * no live staging owns, manifest rows outside every root, and unreferenced
+ * stagings (`liveStagingIds`). Deletes chunk rows marked retired at or below
+ * the live generation (the flip deletes the rows it retires, so none are
+ * marked today), staged chunk rows no live staging owns, manifest rows outside every root, and unreferenced
* texts older than the grace window (a text a concurrent writer is
* referencing is row-locked by its FK check and skipped). With
* `expireStagings`, stagings past a deadline (and not request-held) become
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 72caef5ce7..c71bdbea73 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -61,6 +61,7 @@ export const CODES = {
api_not_enabled: { class: 'host_only', summary: "Google connect credential error: api not enabled.", docs: 'docs/guides/google-connect.md#troubleshooting' },
approval_required: { class: 'consent', summary: "The change needs the owner's explicit approval before it can proceed." },
autopilot_job_owned_by_other_brain: { class: 'caller', summary: "The autopilot job is bound to a different brain." },
+ body_staging_expired: { class: 'retryable', summary: "The staged body of a large-page write expired before it was published, so nothing was published.", why: "A segmented write stages its segments first and publishes them in one flip; a staging idle past its deadline is collected by maintenance, and publishing without its segments would leave the page missing text.", suggestion: 'Send the same write again; it stages a fresh copy.' },
budget_below_recent_runtime: { class: 'unavailable', summary: "The cycle's remaining budget fits fewer reflections than dream patterns needs at the recorded runtime, so the in-cycle run was skipped before any spend.", why: 'An in-cycle patterns run is sized from dream.patterns.last_run; a run that cannot finish in the budget would spend tokens and be killed.', docs: 'docs/guides/dream-patterns.md#budget-sizing', suggestion: 'Run `gbrain dream --phase patterns` outside the cycle after the user agrees to the paid run (it is not budget-limited and records its cost), or reset the record with `gbrain config unset dream.patterns.last_run`.' },
backup_dump_failed: { class: 'host_only', summary: "`gbrain backup create` could not dump the PGLite data dir: an entry PGLite cannot read (a socket, FIFO or symlink that is not a dead gbrain socket) is still inside it.", why: "The backup removes only gbrain's own IPC sockets, and only when nothing listens on them; a live gbrain socket, a foreign socket or FIFO, or a symlink is left in place and named in the message, because the database lock proves no other PGLite owner, not who owns an arbitrary endpoint.", docs: 'docs/guides/in-agent-setup.md#6-back-up-the-complete-local-database', suggestion: 'Stop the process that uses each named entry (or move the entry out of the data dir), then rerun the same `gbrain backup create` command. Do not delete an entry something is still listening on.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: "Read-only: reports the brain's lock holders and storage state so the user can see what still runs against the data dir.", requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--json'] } } },
benchmark_duplicate_task_id: { class: 'caller', summary: "Benchmark duplicate task id." },
diff --git a/src/core/markdown.ts b/src/core/markdown.ts
index 2037674a6f..f9d2898100 100644
--- a/src/core/markdown.ts
+++ b/src/core/markdown.ts
@@ -584,12 +584,6 @@ export function classifyImportHold(parsed: ParsedMarkdown, ctx: {
return null;
}
-/**
- * Inspect raw content for the 7 frontmatter validation classes that gray-matter
- * silently accepts. Mutates `errors` in place. The order of checks is
- * deliberate: cheap byte-level checks first, then structural checks, then
- * YAML-parse-dependent checks.
- */
/** The NULL_BYTES finding for the first NUL on 1-based `line`. */
export function nullBytesError(line: number): ParseValidationError {
return { code: 'NULL_BYTES', message: 'Content contains null bytes (likely binary corruption)', line };
@@ -606,6 +600,12 @@ export function validatorFrontmatterFence(lines: readonly string[]): { firstNonE
return { firstNonEmpty, opens, closeLine: opens && closeLine < lines.length ? closeLine : -1 };
}
+/**
+ * Inspect raw content for the 7 frontmatter validation classes that gray-matter
+ * silently accepts. Mutates `errors` in place. The order of checks is
+ * deliberate: cheap byte-level checks first, then structural checks, then
+ * YAML-parse-dependent checks.
+ */
function collectValidationErrors(
content: string,
errors: ParseValidationError[],
diff --git a/src/core/page-body/ingest.ts b/src/core/page-body/ingest.ts
index bf5c5d1aa5..98b5b63382 100644
--- a/src/core/page-body/ingest.ts
+++ b/src/core/page-body/ingest.ts
@@ -225,7 +225,7 @@ async function stageBody(engine: BrainEngine, input: SegmentedBodyInput, staging
const rows: ManifestRowInput[] = [];
const used = new Set<ManifestRow>();
const matched: Array<ManifestRow | null> = [];
- let texts = 0, byteStart = 0, lineStart = 0, truthBytes = 0, lines = 0;
+ let texts = 0, byteStart = 0, lineStart = 0, truthBytes = 0;
const leads: Record<BodyRegion, string> = { truth: '', timeline: '' };
let hasProtected = false;
let truthExit: EntryState = initialEntryState({ region: 'truth' });
@@ -272,7 +272,6 @@ async function stageBody(engine: BrainEngine, input: SegmentedBodyInput, staging
rows.push(row);
byteStart += segment.bytes.length;
lineStart += segment.lineCount;
- lines += segment.lineCount;
if (region === 'truth') truthBytes += segment.bytes.length;
}
}
@@ -296,7 +295,7 @@ async function stageBody(engine: BrainEngine, input: SegmentedBodyInput, staging
const retireChunkOccurrences = liveRows.filter(row => !used.has(row)).map(row => Number(row.occurrenceId));
closeOccurrences.push(...retireChunkOccurrences);
const body: SegmentedBodyColumns = {
- content_hash: contentHash, body_bytes: byteStart, truth_bytes: truthBytes, body_lines: lines, segment_count: rows.length,
+ content_hash: contentHash, body_bytes: byteStart, truth_bytes: truthBytes, body_lines: lineStart, segment_count: rows.length,
segmenter_version: SEGMENTER_VERSION, truth_lead: leads.truth, timeline_lead: leads.timeline,
body_flags: { ...input.flags, has_protected: hasProtected },
};
@@ -342,7 +341,8 @@ export async function occurrencesWithoutChunks(engine: Pick<BrainEngine, 'execut
export async function stageOccurrenceChunks(engine: BrainEngine, input: { pageId: number; sourceId: string; slug: string; generation: number;
occurrences: readonly ManifestRowInput[]; title: string; frontmatter: JsonObject; flags: JsonObject; chunking: SegmentChunkingContext;
retiredOccurrences: readonly number[];
- /** Projection: each batch inserts under the page guard, after re-reading which occurrences still lack rows, so two projections never both chunk one. */
+ /** Projection: each batch inserts under the page guard, after re-reading which occurrences still lack rows, so two projections never both chunk one;
+ * a page whose generation moved past `generation` stops the projection before it inserts. */
guarded?: boolean }): Promise<{ rows: number; occurrences: number; indexes: number[] }> {
if (input.chunking.quarantined || !input.occurrences.length) return { rows: 0, occurrences: 0, indexes: [] };
const batchBytes = STAGE_BATCH_BYTES[engine.kind];
@@ -376,14 +376,18 @@ export async function stageOccurrenceChunks(engine: BrainEngine, input: { pageId
if (chunks.length && input.retiredOccurrences.length) await reuseSegmentChunkVectors(engine, { pageId: input.pageId,
retiredOccurrences: input.retiredOccurrences, chunks, title: input.title, corpusGeneration: input.chunking.corpusGeneration, tier: input.chunking.tier });
if (chunks.length && !input.guarded) indexes.push(...await engine.stageSegmentChunks(input.pageId, input.generation, chunks));
+ let moved = false;
if (chunks.length && input.guarded) rows -= chunks.length - await engine.transaction(async tx => {
await tx.lockPageKeys([{ sourceId: input.sourceId, slug: input.slug }]);
+ const [page] = await tx.executeRaw<{ body_generation: number | string }>('SELECT body_generation FROM pages WHERE id=$1 FOR UPDATE', [input.pageId]);
+ if (Number(page?.body_generation) !== input.generation) { moved = true; return 0; }
const open = new Set((await occurrencesWithoutChunks(tx, input.pageId, input.generation, batch)).map(row => row.occurrenceId));
const still = chunks.filter(chunk => open.has(chunk.occurrence_id));
if (still.length) await tx.stageSegmentChunks(input.pageId, input.generation, still);
return still.length;
});
rows += chunks.length;
+ if (moved) break;
done += batch.length;
if (engine.kind === 'pglite') await new Promise(resolve => setImmediate(resolve));
}
diff --git a/src/core/page-body/schema.ts b/src/core/page-body/schema.ts
index a0c5816f4a..24f2c52ea2 100644
--- a/src/core/page-body/schema.ts
+++ b/src/core/page-body/schema.ts
@@ -51,7 +51,9 @@ $func$ LANGUAGE plpgsql;`;
* manifest, body stagings and their raw upload parts, and the occurrence id
* sequence. The manifest's text FK is NO ACTION: a referenced text can't be
* deleted, and a source delete cascades through pages and texts in one
- * statement before the check runs.
+ * statement before the check runs. Published manifest rows are unique per
+ * (page, occurrence, gen_from) and staged rows per (staging, occurrence), so
+ * the rows of a staging that never flipped can't collide with the next write's.
*/
export const PAGE_BODY_SCHEMA_SQL = `CREATE SEQUENCE IF NOT EXISTS page_body_occurrence_id_seq;
CREATE TABLE IF NOT EXISTS page_segment_texts (
@@ -87,13 +89,13 @@ CREATE TABLE IF NOT EXISTS page_body_manifest (
date_max DATE,
hash_state BYTEA NOT NULL,
staging_id UUID,
- PRIMARY KEY (page_id, occurrence_id, gen_from),
FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)
);
+CREATE UNIQUE INDEX IF NOT EXISTS page_body_manifest_published ON page_body_manifest (page_id, occurrence_id, gen_from) WHERE staging_id IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS page_body_manifest_live_seq ON page_body_manifest (page_id, seq) WHERE gen_to IS NULL AND staging_id IS NULL;
CREATE INDEX IF NOT EXISTS page_body_manifest_live_bytes ON page_body_manifest (page_id, byte_start) WHERE gen_to IS NULL;
CREATE INDEX IF NOT EXISTS page_body_manifest_text ON page_body_manifest (source_id, sha256);
-CREATE INDEX IF NOT EXISTS page_body_manifest_staging ON page_body_manifest (staging_id) WHERE staging_id IS NOT NULL;
+CREATE UNIQUE INDEX IF NOT EXISTS page_body_manifest_staging ON page_body_manifest (staging_id, occurrence_id) WHERE staging_id IS NOT NULL;
CREATE TABLE IF NOT EXISTS page_body_stagings (
id UUID PRIMARY KEY,
kind TEXT NOT NULL CHECK (kind IN ('upload','import','sync','put','append','edit','resegment')),
diff --git a/src/core/page-body/segment-chunks.ts b/src/core/page-body/segment-chunks.ts
index b17ce7aced..c4a2dc9f0a 100644
--- a/src/core/page-body/segment-chunks.ts
+++ b/src/core/page-body/segment-chunks.ts
@@ -22,6 +22,7 @@ import { fencedCodeChunks, newFenceChunkBudget, type FenceChunkBudget } from '..
import { fenceTrustMarker, markFenceChunk, splitFenceOverlay, type FenceChunkOverlay } from '../eligibility/fence-overlay.ts';
import { isQuarantined } from '../quarantine.ts';
import { renderFactsRegion } from '../remote-body.ts';
+import { credentialSafeProjection } from '../credential-projection.ts';
import type { EntryState } from './entry-state.ts';
import type { SegmentChunkInput, BodyRegion } from './types.ts';
import { segmentProjectionParts, type StoredRegion } from './segmenter.ts';
@@ -70,7 +71,7 @@ export async function prepareSegmentChunks(segment: ChunkableSegment, opts: Segm
if (part.kind === 'text' || part.kind === 'pem') text = part.text;
else if (part.kind === 'facts' && part.region!.open_start === undefined) {
factsTexts.push(part.text);
- text = renderFactsRegion(splitFenceOverlay(part.text, opts.overlay).main);
+ text = credentialSafeProjection(renderFactsRegion(splitFenceOverlay(part.text, opts.overlay).main));
}
if (!text) continue;
const bytes = Buffer.byteLength(text, 'utf8');
diff --git a/src/core/page-body/types.ts b/src/core/page-body/types.ts
index 341b461d70..01145e5b5e 100644
--- a/src/core/page-body/types.ts
+++ b/src/core/page-body/types.ts
@@ -112,7 +112,7 @@ export interface BodyFlipInput {
stagingId: string;
/** Live manifest rows closed at newGeneration (retired and shifted occurrences). */
closeOccurrences: readonly number[];
- /** Occurrences whose chunk rows the flip deletes (retired, not shifted). */
+ /** Occurrences whose chunk rows at or below expectedGeneration the flip deletes (retired occurrences, and older duplicates of re-chunked kept ones). */
retireChunkOccurrences: readonly number[];
/** Promotion from inline: the page's inline chunk rows (body_generation NULL) are deleted too. */
retireInlineChunks?: boolean;
diff --git a/src/core/persistence/segmented-apply.ts b/src/core/persistence/segmented-apply.ts
index e439d85e60..a6068fdbfd 100644
--- a/src/core/persistence/segmented-apply.ts
+++ b/src/core/persistence/segmented-apply.ts
@@ -14,8 +14,8 @@
* and the flip retired its rows in the transaction.
* - Demotion (an inline write onto a segmented page): the page row becomes an
* inline row with an empty body in the same transaction as the inline write;
- * the live manifest rows close (versions keep theirs) and segmented chunk
- * rows go with the inline chunk replacement.
+ * the live manifest rows close (versions keep theirs) and the demotion
+ * deletes the segmented chunk rows before the inline write stages its own.
*/
import type { BrainEngine } from '../engine.ts';
import type { Page } from '../types.ts';
@@ -141,8 +141,8 @@ export async function applySegmentedBody(tx: BrainEngine, input: SegmentedApplyI
* Demotion: turn a segmented page row into an inline row with an empty body
* (the caller's inline write fills it in the same transaction). The live
* manifest rows close at the next generation, so versions that pin earlier
- * generations keep theirs; the segmented chunk rows are deleted with the
- * inline write's chunk replacement.
+ * generations keep theirs; the page's segmented chunk rows are deleted here,
+ * before the inline write stages its chunks.
*/
export async function demoteSegmentedPage(tx: Pick<BrainEngine, 'executeRaw'>, pageId: number): Promise<void> {
await tx.executeRaw(`UPDATE page_body_manifest SET gen_to=(SELECT body_generation+1 FROM pages WHERE id=$1)
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index 1386e33668..bab8469761 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -1314,13 +1314,13 @@ CREATE TABLE IF NOT EXISTS page_body_manifest (
date_max DATE,
hash_state BYTEA NOT NULL,
staging_id UUID,
- PRIMARY KEY (page_id, occurrence_id, gen_from),
FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)
);
+CREATE UNIQUE INDEX IF NOT EXISTS page_body_manifest_published ON page_body_manifest (page_id, occurrence_id, gen_from) WHERE staging_id IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS page_body_manifest_live_seq ON page_body_manifest (page_id, seq) WHERE gen_to IS NULL AND staging_id IS NULL;
CREATE INDEX IF NOT EXISTS page_body_manifest_live_bytes ON page_body_manifest (page_id, byte_start) WHERE gen_to IS NULL;
CREATE INDEX IF NOT EXISTS page_body_manifest_text ON page_body_manifest (source_id, sha256);
-CREATE INDEX IF NOT EXISTS page_body_manifest_staging ON page_body_manifest (staging_id) WHERE staging_id IS NOT NULL;
+CREATE UNIQUE INDEX IF NOT EXISTS page_body_manifest_staging ON page_body_manifest (staging_id, occurrence_id) WHERE staging_id IS NOT NULL;
CREATE TABLE IF NOT EXISTS page_body_stagings (
id UUID PRIMARY KEY,
kind TEXT NOT NULL CHECK (kind IN ('upload','import','sync','put','append','edit','resegment')),
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index 91789eb23e..6e16b44ba3 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -2046,13 +2046,13 @@ CREATE TABLE IF NOT EXISTS page_body_manifest (
date_max DATE,
hash_state BYTEA NOT NULL,
staging_id UUID,
- PRIMARY KEY (page_id, occurrence_id, gen_from),
FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)
);
+CREATE UNIQUE INDEX IF NOT EXISTS page_body_manifest_published ON page_body_manifest (page_id, occurrence_id, gen_from) WHERE staging_id IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS page_body_manifest_live_seq ON page_body_manifest (page_id, seq) WHERE gen_to IS NULL AND staging_id IS NULL;
CREATE INDEX IF NOT EXISTS page_body_manifest_live_bytes ON page_body_manifest (page_id, byte_start) WHERE gen_to IS NULL;
CREATE INDEX IF NOT EXISTS page_body_manifest_text ON page_body_manifest (source_id, sha256);
-CREATE INDEX IF NOT EXISTS page_body_manifest_staging ON page_body_manifest (staging_id) WHERE staging_id IS NOT NULL;
+CREATE UNIQUE INDEX IF NOT EXISTS page_body_manifest_staging ON page_body_manifest (staging_id, occurrence_id) WHERE staging_id IS NOT NULL;
CREATE TABLE IF NOT EXISTS page_body_stagings (
id UUID PRIMARY KEY,
kind TEXT NOT NULL CHECK (kind IN ('upload','import','sync','put','append','edit','resegment')),
diff --git a/src/schema.sql b/src/schema.sql
index 6cade7fc08..15132ae014 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -2042,13 +2042,13 @@ CREATE TABLE IF NOT EXISTS page_body_manifest (
date_max DATE,
hash_state BYTEA NOT NULL,
staging_id UUID,
- PRIMARY KEY (page_id, occurrence_id, gen_from),
FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)
);
+CREATE UNIQUE INDEX IF NOT EXISTS page_body_manifest_published ON page_body_manifest (page_id, occurrence_id, gen_from) WHERE staging_id IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS page_body_manifest_live_seq ON page_body_manifest (page_id, seq) WHERE gen_to IS NULL AND staging_id IS NULL;
CREATE INDEX IF NOT EXISTS page_body_manifest_live_bytes ON page_body_manifest (page_id, byte_start) WHERE gen_to IS NULL;
CREATE INDEX IF NOT EXISTS page_body_manifest_text ON page_body_manifest (source_id, sha256);
-CREATE INDEX IF NOT EXISTS page_body_manifest_staging ON page_body_manifest (staging_id) WHERE staging_id IS NOT NULL;
+CREATE UNIQUE INDEX IF NOT EXISTS page_body_manifest_staging ON page_body_manifest (staging_id, occurrence_id) WHERE staging_id IS NOT NULL;
CREATE TABLE IF NOT EXISTS page_body_stagings (
id UUID PRIMARY KEY,
kind TEXT NOT NULL CHECK (kind IN ('upload','import','sync','put','append','edit','resegment')),
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 7569436e44..d86d33b05d 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -207,7 +207,6 @@
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_body_manifest.page_body_manifest_cut_kind_check": "c CHECK ((cut_kind = ANY (ARRAY['heading'::text, 'day'::text, 'message'::text, 'blank'::text, 'forced'::text, 'region_end'::text, 'eof'::text])))",
"page_body_manifest.page_body_manifest_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
- "page_body_manifest.page_body_manifest_pkey": "p PRIMARY KEY (page_id, occurrence_id, gen_from)",
"page_body_manifest.page_body_manifest_region_check": "c CHECK ((region = ANY (ARRAY['truth'::text, 'timeline'::text])))",
"page_body_manifest.page_body_manifest_source_id_sha256_fkey": "f FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)",
"page_body_staging_parts.page_body_staging_parts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 4194304)))",
@@ -1192,8 +1191,8 @@
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
"page_body_manifest_live_bytes": "CREATE INDEX page_body_manifest_live_bytes ON public.page_body_manifest USING btree (page_id, byte_start) WHERE (gen_to IS NULL)",
"page_body_manifest_live_seq": "CREATE UNIQUE INDEX page_body_manifest_live_seq ON public.page_body_manifest USING btree (page_id, seq) WHERE ((gen_to IS NULL) AND (staging_id IS NULL))",
- "page_body_manifest_pkey": "CREATE UNIQUE INDEX page_body_manifest_pkey ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from)",
- "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_published": "CREATE UNIQUE INDEX page_body_manifest_published ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from) WHERE (staging_id IS NULL)",
+ "page_body_manifest_staging": "CREATE UNIQUE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id, occurrence_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_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]))",
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 64d4d741e8..4f4a49c7ac 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -207,7 +207,6 @@
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_body_manifest.page_body_manifest_cut_kind_check": "c CHECK ((cut_kind = ANY (ARRAY['heading'::text, 'day'::text, 'message'::text, 'blank'::text, 'forced'::text, 'region_end'::text, 'eof'::text])))",
"page_body_manifest.page_body_manifest_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
- "page_body_manifest.page_body_manifest_pkey": "p PRIMARY KEY (page_id, occurrence_id, gen_from)",
"page_body_manifest.page_body_manifest_region_check": "c CHECK ((region = ANY (ARRAY['truth'::text, 'timeline'::text])))",
"page_body_manifest.page_body_manifest_source_id_sha256_fkey": "f FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)",
"page_body_staging_parts.page_body_staging_parts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 4194304)))",
@@ -1192,8 +1191,8 @@
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
"page_body_manifest_live_bytes": "CREATE INDEX page_body_manifest_live_bytes ON public.page_body_manifest USING btree (page_id, byte_start) WHERE (gen_to IS NULL)",
"page_body_manifest_live_seq": "CREATE UNIQUE INDEX page_body_manifest_live_seq ON public.page_body_manifest USING btree (page_id, seq) WHERE ((gen_to IS NULL) AND (staging_id IS NULL))",
- "page_body_manifest_pkey": "CREATE UNIQUE INDEX page_body_manifest_pkey ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from)",
- "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_published": "CREATE UNIQUE INDEX page_body_manifest_published ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from) WHERE (staging_id IS NULL)",
+ "page_body_manifest_staging": "CREATE UNIQUE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id, occurrence_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_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]))",
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 a4efeda185..e9447d7445 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -207,7 +207,6 @@
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_body_manifest.page_body_manifest_cut_kind_check": "c CHECK ((cut_kind = ANY (ARRAY['heading'::text, 'day'::text, 'message'::text, 'blank'::text, 'forced'::text, 'region_end'::text, 'eof'::text])))",
"page_body_manifest.page_body_manifest_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
- "page_body_manifest.page_body_manifest_pkey": "p PRIMARY KEY (page_id, occurrence_id, gen_from)",
"page_body_manifest.page_body_manifest_region_check": "c CHECK ((region = ANY (ARRAY['truth'::text, 'timeline'::text])))",
"page_body_manifest.page_body_manifest_source_id_sha256_fkey": "f FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)",
"page_body_staging_parts.page_body_staging_parts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 4194304)))",
@@ -1188,8 +1187,8 @@
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
"page_body_manifest_live_bytes": "CREATE INDEX page_body_manifest_live_bytes ON public.page_body_manifest USING btree (page_id, byte_start) WHERE (gen_to IS NULL)",
"page_body_manifest_live_seq": "CREATE UNIQUE INDEX page_body_manifest_live_seq ON public.page_body_manifest USING btree (page_id, seq) WHERE ((gen_to IS NULL) AND (staging_id IS NULL))",
- "page_body_manifest_pkey": "CREATE UNIQUE INDEX page_body_manifest_pkey ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from)",
- "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_published": "CREATE UNIQUE INDEX page_body_manifest_published ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from) WHERE (staging_id IS NULL)",
+ "page_body_manifest_staging": "CREATE UNIQUE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id, occurrence_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_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]))",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
index b3c1d2b01e..969c866641 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
@@ -142,7 +142,6 @@
"page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)",
"page_body_manifest.page_body_manifest_cut_kind_check": "c CHECK ((cut_kind = ANY (ARRAY['heading'::text, 'day'::text, 'message'::text, 'blank'::text, 'forced'::text, 'region_end'::text, 'eof'::text])))",
"page_body_manifest.page_body_manifest_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
- "page_body_manifest.page_body_manifest_pkey": "p PRIMARY KEY (page_id, occurrence_id, gen_from)",
"page_body_manifest.page_body_manifest_region_check": "c CHECK ((region = ANY (ARRAY['truth'::text, 'timeline'::text])))",
"page_body_manifest.page_body_manifest_source_id_sha256_fkey": "f FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)",
"page_body_staging_parts.page_body_staging_parts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 4194304)))",
@@ -863,8 +862,8 @@
"page_aliases_uniq": "CREATE UNIQUE INDEX page_aliases_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug)",
"page_body_manifest_live_bytes": "CREATE INDEX page_body_manifest_live_bytes ON public.page_body_manifest USING btree (page_id, byte_start) WHERE (gen_to IS NULL)",
"page_body_manifest_live_seq": "CREATE UNIQUE INDEX page_body_manifest_live_seq ON public.page_body_manifest USING btree (page_id, seq) WHERE ((gen_to IS NULL) AND (staging_id IS NULL))",
- "page_body_manifest_pkey": "CREATE UNIQUE INDEX page_body_manifest_pkey ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from)",
- "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_published": "CREATE UNIQUE INDEX page_body_manifest_published ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from) WHERE (staging_id IS NULL)",
+ "page_body_manifest_staging": "CREATE UNIQUE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id, occurrence_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_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]))",
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 a6ce760ea4..e4a30b4e8b 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
@@ -142,7 +142,6 @@
"page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)",
"page_body_manifest.page_body_manifest_cut_kind_check": "c CHECK ((cut_kind = ANY (ARRAY['heading'::text, 'day'::text, 'message'::text, 'blank'::text, 'forced'::text, 'region_end'::text, 'eof'::text])))",
"page_body_manifest.page_body_manifest_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
- "page_body_manifest.page_body_manifest_pkey": "p PRIMARY KEY (page_id, occurrence_id, gen_from)",
"page_body_manifest.page_body_manifest_region_check": "c CHECK ((region = ANY (ARRAY['truth'::text, 'timeline'::text])))",
"page_body_manifest.page_body_manifest_source_id_sha256_fkey": "f FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)",
"page_body_staging_parts.page_body_staging_parts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 4194304)))",
@@ -863,8 +862,8 @@
"page_aliases_uniq": "CREATE UNIQUE INDEX page_aliases_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug)",
"page_body_manifest_live_bytes": "CREATE INDEX page_body_manifest_live_bytes ON public.page_body_manifest USING btree (page_id, byte_start) WHERE (gen_to IS NULL)",
"page_body_manifest_live_seq": "CREATE UNIQUE INDEX page_body_manifest_live_seq ON public.page_body_manifest USING btree (page_id, seq) WHERE ((gen_to IS NULL) AND (staging_id IS NULL))",
- "page_body_manifest_pkey": "CREATE UNIQUE INDEX page_body_manifest_pkey ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from)",
- "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_published": "CREATE UNIQUE INDEX page_body_manifest_published ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from) WHERE (staging_id IS NULL)",
+ "page_body_manifest_staging": "CREATE UNIQUE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id, occurrence_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_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]))",
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 ca99e95ebc..bf0e097542 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
@@ -142,7 +142,6 @@
"page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)",
"page_body_manifest.page_body_manifest_cut_kind_check": "c CHECK ((cut_kind = ANY (ARRAY['heading'::text, 'day'::text, 'message'::text, 'blank'::text, 'forced'::text, 'region_end'::text, 'eof'::text])))",
"page_body_manifest.page_body_manifest_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
- "page_body_manifest.page_body_manifest_pkey": "p PRIMARY KEY (page_id, occurrence_id, gen_from)",
"page_body_manifest.page_body_manifest_region_check": "c CHECK ((region = ANY (ARRAY['truth'::text, 'timeline'::text])))",
"page_body_manifest.page_body_manifest_source_id_sha256_fkey": "f FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)",
"page_body_staging_parts.page_body_staging_parts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 4194304)))",
@@ -862,8 +861,8 @@
"page_aliases_uniq": "CREATE UNIQUE INDEX page_aliases_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug)",
"page_body_manifest_live_bytes": "CREATE INDEX page_body_manifest_live_bytes ON public.page_body_manifest USING btree (page_id, byte_start) WHERE (gen_to IS NULL)",
"page_body_manifest_live_seq": "CREATE UNIQUE INDEX page_body_manifest_live_seq ON public.page_body_manifest USING btree (page_id, seq) WHERE ((gen_to IS NULL) AND (staging_id IS NULL))",
- "page_body_manifest_pkey": "CREATE UNIQUE INDEX page_body_manifest_pkey ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from)",
- "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_published": "CREATE UNIQUE INDEX page_body_manifest_published ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from) WHERE (staging_id IS NULL)",
+ "page_body_manifest_staging": "CREATE UNIQUE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id, occurrence_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_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]))",
diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.json
index 4d3a3ca94e..65c9efd319 100644
--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json
+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json
@@ -153,7 +153,6 @@
"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))",
"page_body_manifest.page_body_manifest_cut_kind_check": "c CHECK ((cut_kind = ANY (ARRAY['heading'::text, 'day'::text, 'message'::text, 'blank'::text, 'forced'::text, 'region_end'::text, 'eof'::text])))",
"page_body_manifest.page_body_manifest_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
- "page_body_manifest.page_body_manifest_pkey": "p PRIMARY KEY (page_id, occurrence_id, gen_from)",
"page_body_manifest.page_body_manifest_region_check": "c CHECK ((region = ANY (ARRAY['truth'::text, 'timeline'::text])))",
"page_body_manifest.page_body_manifest_source_id_sha256_fkey": "f FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)",
"page_body_staging_parts.page_body_staging_parts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 4194304)))",
@@ -891,8 +890,8 @@
"open_loops_thread_idx": "CREATE INDEX open_loops_thread_idx ON public.open_loops USING btree (source_id, thread_id) WHERE (status = 'open'::text)",
"page_body_manifest_live_bytes": "CREATE INDEX page_body_manifest_live_bytes ON public.page_body_manifest USING btree (page_id, byte_start) WHERE (gen_to IS NULL)",
"page_body_manifest_live_seq": "CREATE UNIQUE INDEX page_body_manifest_live_seq ON public.page_body_manifest USING btree (page_id, seq) WHERE ((gen_to IS NULL) AND (staging_id IS NULL))",
- "page_body_manifest_pkey": "CREATE UNIQUE INDEX page_body_manifest_pkey ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from)",
- "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_published": "CREATE UNIQUE INDEX page_body_manifest_published ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from) WHERE (staging_id IS NULL)",
+ "page_body_manifest_staging": "CREATE UNIQUE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id, occurrence_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_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]))",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 46e6132036..e1a40624e4 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -211,7 +211,6 @@
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_body_manifest.page_body_manifest_cut_kind_check": "c CHECK ((cut_kind = ANY (ARRAY['heading'::text, 'day'::text, 'message'::text, 'blank'::text, 'forced'::text, 'region_end'::text, 'eof'::text])))",
"page_body_manifest.page_body_manifest_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
- "page_body_manifest.page_body_manifest_pkey": "p PRIMARY KEY (page_id, occurrence_id, gen_from)",
"page_body_manifest.page_body_manifest_region_check": "c CHECK ((region = ANY (ARRAY['truth'::text, 'timeline'::text])))",
"page_body_manifest.page_body_manifest_source_id_sha256_fkey": "f FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)",
"page_body_staging_parts.page_body_staging_parts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 4194304)))",
@@ -1196,8 +1195,8 @@
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
"page_body_manifest_live_bytes": "CREATE INDEX page_body_manifest_live_bytes ON public.page_body_manifest USING btree (page_id, byte_start) WHERE (gen_to IS NULL)",
"page_body_manifest_live_seq": "CREATE UNIQUE INDEX page_body_manifest_live_seq ON public.page_body_manifest USING btree (page_id, seq) WHERE ((gen_to IS NULL) AND (staging_id IS NULL))",
- "page_body_manifest_pkey": "CREATE UNIQUE INDEX page_body_manifest_pkey ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from)",
- "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_published": "CREATE UNIQUE INDEX page_body_manifest_published ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from) WHERE (staging_id IS NULL)",
+ "page_body_manifest_staging": "CREATE UNIQUE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id, occurrence_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_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]))",
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 af1c3d501c..1439be4e0c 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -211,7 +211,6 @@
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_body_manifest.page_body_manifest_cut_kind_check": "c CHECK ((cut_kind = ANY (ARRAY['heading'::text, 'day'::text, 'message'::text, 'blank'::text, 'forced'::text, 'region_end'::text, 'eof'::text])))",
"page_body_manifest.page_body_manifest_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
- "page_body_manifest.page_body_manifest_pkey": "p PRIMARY KEY (page_id, occurrence_id, gen_from)",
"page_body_manifest.page_body_manifest_region_check": "c CHECK ((region = ANY (ARRAY['truth'::text, 'timeline'::text])))",
"page_body_manifest.page_body_manifest_source_id_sha256_fkey": "f FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)",
"page_body_staging_parts.page_body_staging_parts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 4194304)))",
@@ -1196,8 +1195,8 @@
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
"page_body_manifest_live_bytes": "CREATE INDEX page_body_manifest_live_bytes ON public.page_body_manifest USING btree (page_id, byte_start) WHERE (gen_to IS NULL)",
"page_body_manifest_live_seq": "CREATE UNIQUE INDEX page_body_manifest_live_seq ON public.page_body_manifest USING btree (page_id, seq) WHERE ((gen_to IS NULL) AND (staging_id IS NULL))",
- "page_body_manifest_pkey": "CREATE UNIQUE INDEX page_body_manifest_pkey ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from)",
- "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_published": "CREATE UNIQUE INDEX page_body_manifest_published ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from) WHERE (staging_id IS NULL)",
+ "page_body_manifest_staging": "CREATE UNIQUE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id, occurrence_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_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]))",
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 dec2358fb9..4c3748fe55 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -211,7 +211,6 @@
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_body_manifest.page_body_manifest_cut_kind_check": "c CHECK ((cut_kind = ANY (ARRAY['heading'::text, 'day'::text, 'message'::text, 'blank'::text, 'forced'::text, 'region_end'::text, 'eof'::text])))",
"page_body_manifest.page_body_manifest_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
- "page_body_manifest.page_body_manifest_pkey": "p PRIMARY KEY (page_id, occurrence_id, gen_from)",
"page_body_manifest.page_body_manifest_region_check": "c CHECK ((region = ANY (ARRAY['truth'::text, 'timeline'::text])))",
"page_body_manifest.page_body_manifest_source_id_sha256_fkey": "f FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)",
"page_body_staging_parts.page_body_staging_parts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 4194304)))",
@@ -1192,8 +1191,8 @@
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
"page_body_manifest_live_bytes": "CREATE INDEX page_body_manifest_live_bytes ON public.page_body_manifest USING btree (page_id, byte_start) WHERE (gen_to IS NULL)",
"page_body_manifest_live_seq": "CREATE UNIQUE INDEX page_body_manifest_live_seq ON public.page_body_manifest USING btree (page_id, seq) WHERE ((gen_to IS NULL) AND (staging_id IS NULL))",
- "page_body_manifest_pkey": "CREATE UNIQUE INDEX page_body_manifest_pkey ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from)",
- "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_published": "CREATE UNIQUE INDEX page_body_manifest_published ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from) WHERE (staging_id IS NULL)",
+ "page_body_manifest_staging": "CREATE UNIQUE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id, occurrence_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_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]))",
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 c983fe923f..6dbc6222fb 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -207,7 +207,6 @@
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_body_manifest.page_body_manifest_cut_kind_check": "c CHECK ((cut_kind = ANY (ARRAY['heading'::text, 'day'::text, 'message'::text, 'blank'::text, 'forced'::text, 'region_end'::text, 'eof'::text])))",
"page_body_manifest.page_body_manifest_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
- "page_body_manifest.page_body_manifest_pkey": "p PRIMARY KEY (page_id, occurrence_id, gen_from)",
"page_body_manifest.page_body_manifest_region_check": "c CHECK ((region = ANY (ARRAY['truth'::text, 'timeline'::text])))",
"page_body_manifest.page_body_manifest_source_id_sha256_fkey": "f FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)",
"page_body_staging_parts.page_body_staging_parts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 4194304)))",
@@ -1192,8 +1191,8 @@
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
"page_body_manifest_live_bytes": "CREATE INDEX page_body_manifest_live_bytes ON public.page_body_manifest USING btree (page_id, byte_start) WHERE (gen_to IS NULL)",
"page_body_manifest_live_seq": "CREATE UNIQUE INDEX page_body_manifest_live_seq ON public.page_body_manifest USING btree (page_id, seq) WHERE ((gen_to IS NULL) AND (staging_id IS NULL))",
- "page_body_manifest_pkey": "CREATE UNIQUE INDEX page_body_manifest_pkey ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from)",
- "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_published": "CREATE UNIQUE INDEX page_body_manifest_published ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from) WHERE (staging_id IS NULL)",
+ "page_body_manifest_staging": "CREATE UNIQUE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id, occurrence_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_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]))",
diff --git a/test/large-pages/segment-chunks.test.ts b/test/large-pages/segment-chunks.test.ts
index 3b614de4e8..05fa3672c3 100644
--- a/test/large-pages/segment-chunks.test.ts
+++ b/test/large-pages/segment-chunks.test.ts
@@ -24,7 +24,7 @@ import { initialEntryState } from '../../src/core/page-body/entry-state.ts';
import { segmentString, type SegmentOut } from '../../src/core/page-body/segmenter.ts';
import { prepareSegmentChunks, type SegmentChunk } from '../../src/core/page-body/segment-chunks.ts';
import { mulberry32 } from '../helpers/seeded-random.ts';
-import { bigPage, FACTS_BLOCK, joinedProjection, PEM_BLOCK, segmentOptions } from '../helpers/segment-bodies.ts';
+import { bigPage, FACTS_BLOCK, joinedProjection, KEY_BODY, PEM_BEGIN_RSA, PEM_BLOCK, PEM_END_RSA, segmentOptions } from '../helpers/segment-bodies.ts';
const trustOf = (body: string) => markdownFenceTrusted(stripMaterializedMarkers(body)) ? 'trusted' as const : 'void' as const;
const squash = (s: string) => s.replace(/\s+/g, '');
@@ -53,6 +53,17 @@ describe('prepareSegmentChunks', () => {
expect(got.map(c => c.chunk_text).join('\n')).not.toContain('private thing');
});
+ test('a key inside a world facts row is redacted as prepareMarkdownChunks redacts it', async () => {
+ const facts = FACTS_BLOCK.replace('| 1 | likes tea |', `| 1 | deploy key ${PEM_BEGIN_RSA} ${KEY_BODY} ${PEM_END_RSA} |`);
+ const body = '# Notes\n\nIntro paragraph.\n\n' + facts + '\nAfter the facts.\n\n' + 'filler words here. '.repeat(200) + '\n';
+ const [seg, ...rest] = segment(body);
+ expect(rest).toEqual([]);
+ const got = await prepareSegmentChunks(seg!, { fenceTrust: 'trusted' });
+ const want = await prepareMarkdownChunks({ compiled_truth: body });
+ expect(got.map(c => [c.chunk_text, c.chunk_source])).toEqual(want.map(c => [c.chunk_text, c.chunk_source]));
+ expect(got.map(c => c.chunk_text).join('\n')).not.toContain(KEY_BODY);
+ });
+
test('chunks stay inside their segment and their spans hold their text', async () => {
const body = bigPage(mulberry32(3), 2_500_000);
const bytes = Buffer.from(body, 'utf8');
diff --git a/test/large-pages/segmented-write-races.test.ts b/test/large-pages/segmented-write-races.test.ts
new file mode 100644
index 0000000000..9e22a856b8
--- /dev/null
+++ b/test/large-pages/segmented-write-races.test.ts
@@ -0,0 +1,121 @@
+/**
+ * Wave B segmented writes under crashes, expiry and concurrent writers, on PGLite.
+ *
+ * 1. Protects: a flip whose staging expired (and was swept) refuses with
+ * `body_staging_expired` and leaves the published body as it was; a replace
+ * of a page whose post-create projection never ran chunks every live
+ * occurrence before it seals; a preparation that died before its flip does
+ * not block the next write of the page; a projection that prepared at a
+ * generation a flip has since moved past stages no chunk rows.
+ * 2. Fails when: the flip publishes without its staged manifest rows, the flip
+ * deletes chunk rows its own preparation staged, staged manifest rows of an
+ * abandoned staging collide with the retry's, or a stale projection inserts
+ * rows of an occurrence the newer generation retired.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+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 { stageOccurrenceChunks } from '../../src/core/page-body/ingest.ts';
+import { stageSegmentedImport } from '../../src/core/persistence/segmented-apply.ts';
+import { reconstructedPage, segmentedPageRow } from '../helpers/segmented-page-checks.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 120_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM pages');
+ await engine.setConfig('pages.segmented_storage', 'on');
+});
+
+/** ~1.4 MB of sections, each its own segment. */
+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: Races\ntype: note\n---\n\n${body}`;
+
+async function stageReplace(slug: string, content: string) {
+ const existing = await engine.getPage(slug, { sourceId: 'default' });
+ const parsed = parseMarkdown(content, `${slug}.md`);
+ const staged = await stageSegmentedImport(engine, { slug, sourceId: 'default', existing,
+ 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 { staged, parsed };
+}
+
+/** Live manifest occurrences of the page that have no chunk row the page's generation can see. */
+async function liveOccurrencesWithoutChunks(pageId: number): Promise<number> {
+ const [row] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_body_manifest m JOIN pages p ON p.id=m.page_id
+ WHERE m.page_id=$1 AND m.staging_id IS NULL AND m.gen_from<=p.body_generation AND (m.gen_to IS NULL OR m.gen_to>p.body_generation)
+ AND NOT EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=m.page_id AND c.occurrence_id=m.occurrence_id AND c.body_generation<=p.body_generation)`, [pageId]);
+ return Number(row!.n);
+}
+
+describe('segmented writes: crash, expiry, concurrency', () => {
+ test('a flip whose staging expired and was swept refuses, and the published body is unchanged', async () => {
+ const slug = 'notes/expired-staging';
+ await importFromContent(engine, slug, page(sections('a')), { sourceId: 'default', noEmbed: true });
+ const before = await reconstructedPage(engine, slug);
+ const { staged, parsed } = await stageReplace(slug, page('## Intro\n\nA new first paragraph.\n\n' + sections('a')));
+ await engine.sweepSegments({ expireStagings: true, now: new Date(Date.now() + 2 * 3_600_000) });
+ const err = await engine.transaction(tx => staged.apply(tx, { type: parsed.type, title: parsed.title, frontmatter: parsed.frontmatter, page_kind: 'markdown' },
+ { mode: 'none', corpusGeneration: null })).then(() => null, (e: unknown) => e);
+ expect((err as { code?: string } | null)?.code).toBe('body_staging_expired');
+ const after = await reconstructedPage(engine, slug);
+ expect(after.page.body_generation).toBe(before.page.body_generation);
+ expect(after.body).toEqual(before.body);
+ expect(after.page.content_hash).toBe(after.hash);
+ }, 120_000);
+
+ test('a replace of a page whose post-create projection never ran chunks every live occurrence before it seals', async () => {
+ const slug = 'notes/unprojected-create';
+ await importFromContent(engine, slug, page(sections('a')), { sourceId: 'default', noEmbed: true });
+ const { id } = await segmentedPageRow(engine, slug);
+ await engine.executeRaw('DELETE FROM content_chunks WHERE page_id=$1', [id]);
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE id=$1', [id]);
+ const result = await importFromContent(engine, slug, page(sections('a') + '## Tail\n\nAppended tail paragraph.\n'), { sourceId: 'default', noEmbed: true });
+ expect(result.status).toBe('imported');
+ const row = await segmentedPageRow(engine, slug);
+ expect(row.body_generation).toBe(2);
+ expect(await liveOccurrencesWithoutChunks(id)).toBe(0);
+ }, 120_000);
+
+ test('a preparation that died before its flip does not block the next write of the page', async () => {
+ const slug = 'notes/abandoned-staging';
+ await importFromContent(engine, slug, page(sections('a')), { sourceId: 'default', noEmbed: true });
+ const next = page('## Intro\n\nA new first paragraph.\n\n' + sections('a'));
+ await stageReplace(slug, next);
+ const result = await importFromContent(engine, slug, next, { sourceId: 'default', noEmbed: true });
+ expect(result.status).toBe('imported');
+ const after = await reconstructedPage(engine, slug);
+ expect(after.page.body_generation).toBe(2);
+ expect(after.body.compiled_truth).toBe(parseMarkdown(next, `${slug}.md`).compiled_truth);
+ }, 120_000);
+
+ test('a projection that prepared at a generation a flip moved past stages no rows', async () => {
+ const slug = 'notes/stale-projection';
+ await importFromContent(engine, slug, page(sections('a')), { sourceId: 'default', noEmbed: true });
+ const { id } = await segmentedPageRow(engine, slug);
+ const genOne = await engine.readManifest(id);
+ await importFromContent(engine, slug, page(sections('b')), { sourceId: 'default', noEmbed: true });
+ expect((await segmentedPageRow(engine, slug)).body_generation).toBe(2);
+ const staged = await stageOccurrenceChunks(engine, { pageId: id, sourceId: 'default', slug, generation: 1, occurrences: genOne.slice(0, 3),
+ title: 'Races', frontmatter: {}, flags: {}, chunking: { quarantined: false, corpusGeneration: null, tier: 'none' }, retiredOccurrences: [], guarded: true });
+ expect(staged.rows).toBe(0);
+ const [stale] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM content_chunks WHERE page_id=$1 AND occurrence_id=ANY($2::bigint[])',
+ [id, genOne.slice(0, 3).map(row => row.occurrenceId)]);
+ expect(Number(stale!.n)).toBe(0);
+ }, 120_000);
+});