Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(schema): add page revision columns nullable, resumable batched backfill, revision_backfill_pending fence (#5216)

garrytan61ae59fe5dae
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index 42c4b63f99..83d3000118 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -88,7 +88,8 @@ src/core/output/writer.ts 6 engine_guard Canonical table SQL trigger requires co
src/core/page-state/materialize.ts 1 coordinator Publication is transaction-scoped under admitted authority, source/page guards and revision checks.
src/core/page-state/projection-schema.ts 1 schema Schema installation and forward-reference DDL; coordinated activation quiesces canonical writers.
src/core/page-state/projections.ts 2 projection Derived indexing, retrieval telemetry, or source settings; canonical fields remain guarded by SQL triggers.
-src/core/page-state/schema.ts 2 schema Schema installation and forward-reference DDL; coordinated activation quiesces canonical writers.
+src/core/page-state/schema.ts 3 schema Schema installation and forward-reference DDL; coordinated activation quiesces canonical writers. The pages DO block constrains an empty pages table only; populated tables are finalized by revision-backfill.ts.
+src/core/page-state/revision-backfill.ts 2 schema Migration-pass backfill of pages.knowledge_revision for rows written before the column (#5216): only NULL revisions are assigned, in committed id batches; canonical content is never written, and the revision trigger treats a NULL old revision without reading bodies.
src/core/page-state/tags.ts 3 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication. The frontmatter-claim and explicit-add inserts are two branches of one guarded statement.
src/core/persistence/memory-mutations.ts 1 coordinator Publication is transaction-scoped under admitted authority, source/page guards and revision checks.
src/core/persistence/memory-prepare.ts 3 coordinator Publication is transaction-scoped under admitted authority, source/page guards and revision checks.
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.md
index 4d49487eb2..a72540e8e1 100644
--- a/docs/architecture/key-files/engines-1.md
+++ b/docs/architecture/key-files/engines-1.md
@@ -29,7 +29,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/engine.ts` — Pluggable engine interface (BrainEngine). `clampSearchLimit(limit, default, cap)` takes an explicit cap so per-operation caps can be tighter than `MAX_SEARCH_LIMIT`. Exports `LinkBatchInput`/`TimelineBatchInput` for the bulk-insert API (`addLinksBatch`/`addTimelineEntriesBatch`). `readonly kind: 'postgres' | 'pglite'` discriminator lets `src/core/migrate.ts` and others branch without `instanceof` + dynamic imports. Methods: `batchLoadEmotionalInputs(slugs?)` (CTE-shaped read with per-table aggregates so page × N tags × M takes never produces N×M rows), `setEmotionalWeightBatch(rows)` (`UPDATE FROM unnest($1::text[],$2::text[],$3::real[])` composite-keyed on `(slug, source_id)`), `getRecentSalience(opts)`, `findAnomalies(opts)`. `PageFilters` has `sort?: 'updated_desc'|'updated_asc'|'created_desc'|'slug'` + `PAGE_SORT_SQL` whitelist consumed by both engines. `listAllPageRefs(): Promise<Array<{slug, source_id}>>` ordered by `(source_id, slug)` — cheap cross-source enumeration instead of a `getAllSlugs()→getPage(slug)` N+1 (which would silently default to `source_id='default'`); parity across postgres-engine.ts + pglite-engine.ts; Pinned by `test/e2e/multi-source-bug-class.test.ts`. `SearchOpts`+`PageFilters` add `sourceIds?: string[]` (federated read axis; both engines apply `WHERE source_id = ANY($N::text[])` when set, preserve scalar `sourceId` fast path when unset); `traverseGraph(slug, depth, opts?)` and `traversePaths(slug, opts?)` accept `opts.sourceId`/`opts.sourceIds`. `traversePathsDetailed(slug, opts?)` returns `{ paths: GraphPath[], truncated }` — the final SELECT of the path-enumerating recursive CTE is bounded at `TRAVERSE_PATH_ROW_CAP + 1` rows on both engines (the probe row signals overflow; `ORDER BY depth` means the deepest edges are dropped, so a truncated result is still the complete shallow neighbourhood; the cap counts raw rows before the in-memory edge dedup, so `paths.length` alone cannot reveal truncation) and `traversePaths` is its `.paths` projection. Each `GraphPath` carries `from_source_id`/`to_source_id` and the edge dedup keys on page ids; each `traverseGraph` `GraphNode` carries `source_id` (DISTINCT per page), so the same slug in two sources stays two edges or nodes. `resolveSlugWithAliasDetailed(slug, sourceOrSources)` returns `{ canonical_slug, source_id } | null` — the winning alias row AND its owning source under the same scope/precedence rules (`ORDER BY array_position(scope, source_id), id`; null when nothing matches or the `slug_aliases` table does not exist yet); `resolveSlugWithAlias` is its canonical-slug projection (falls back to the input slug). A consumer that goes on to read the canonical page must scope that read to `source_id`. The by-slug read methods carry the same federated axis: `getTags`/`getLinks`/`getBacklinks`/`getChunks` opts and `TimelineOpts` (consumed by `getTimeline`) accept `sourceIds?: string[]` taking precedence over the scalar `sourceId` (`source_id = ANY($::text[])` scoping the slug→page-id lookup); `getChunks` falls back to the `'default'` source when neither is set (importCodeFile's incremental-embedding reuse relies on it) and SELECTs an explicit non-vector column list — embedding vectors never ride the payload since rowToChunk discards them (`getChunksWithEmbeddings` stays scalar-only by design: engine-internal, zero remote-reachable callers); the link reads (`getLinks`/`getBacklinks`) scope ALL THREE endpoints (from/to/origin) on the federated branch while the scalar branch scopes only the near endpoint for trusted internal cross-source callers. `traverseGraph` opts has `frontierCap?: number` (per-iteration recursive-CTE cap, approx per-BFS-layer); return type `Promise<GraphNode[]>` for MCP wire stability; export `TraverseGraphOpts`; Postgres uses parenthesized `LIMIT N ORDER BY (slug, id)` inside the recursive term, PGLite mirrors with positional params; Pinned by `test/regressions/v0_36_frontier_cap.test.ts`. Phantom-redirect methods: `refreshPageBody(slug, sourceId, compiled_truth, timeline, content_hash)` narrow-UPDATEs three columns + updated_at, skipping soft-deleted rows (content_hash refresh required so `gbrain sync` sees the canonical as unchanged after fence merge); `migrateFactsToCanonical(phantomSlug, canonicalSlug, sourceId)` UPDATEs `entity_slug`+`source_markdown_slug` on every active fact row keyed on the phantom, preserving embedding/validUntil/kind/status/source_session/confidence and offsetting `row_num` past the canonical page's current MAX(row_num) (all rows incl. expired — the partial `idx_facts_fence_key` only excludes NULL; NULL stays NULL) so overlapping fence rows never collide; parity at `test/phantom-redirect-engine-parity.test.ts`. `getAdjacencyBoosts(pageIds): Promise<Map<number, AdjacencyRow>>` powers the per-query graph-signals stage — one SQL query returning inbound-link counts among top-K plus a cross-source count (links from differing `source_id`); `COALESCE(p.source_id,'default')` null safety, `HAVING >= 1`, cross-source CASE-WHEN excludes the target's own source; parity SQL across both engines; `SearchResult` gains optional `base_score`, `backlink_boost`, `salience_boost`, `recency_boost`, `exact_match_boost`, `graph_adjacency_boost`, `graph_cross_source_boost`, `session_demote_factor`, `reranker_delta` + internal staging fields; Pinned by `test/e2e/graph-signals-engine.test.ts`. Two REQUIRED methods: `deletePages(slugs, {sourceId}): Promise<string[]>` (single-batch primitive returning slugs actually deleted) and `resolveSlugsByPaths(paths, {sourceId}): Promise<Map<path,slug>>` (batch path→slug lookup); `sourceId` REQUIRED on both at the type level (asymmetric with single-row `deletePage` which keeps optional/'default'); both short-circuit on empty input and throw when `> DELETE_BATCH_SIZE`. `softDeletePages(slugs, {sourceId}): Promise<string[]>` is the batch soft-delete twin, mirroring `deletePages`' contract exactly (required `sourceId`, `> DELETE_BATCH_SIZE` throws, empty input short-circuits, caller owns chunking + decompose-to-one-element-batches on failure): one `UPDATE … SET deleted_at = now() … AND deleted_at IS NULL … RETURNING slug` round-trip returning only the slugs that actually flipped active→soft-deleted — the `deleted_at IS NULL` predicate is load-bearing so a re-run never refreshes an already-soft-deleted row's 72h purge clock — and NOTHING cascades (chunks/links/timeline stay behind the read-side `deleted_at` filters; the autopilot purge phase hard-deletes after 72h; a re-import within the window revives via `putPage`'s upsert; `deletePage`/`deletePages` remain the purge/teardown primitives). `getStats(opts?)` / `getHealth(opts?)` take an optional `{sourceId?, sourceIds?}` scope (same shape as `sourceScopeOpts` output): omitted = brain-wide; scoped = EVERY counter/coverage/degree confines to the grant, including derived-table counts via their page joins, and link-derived numbers count only edges with BOTH endpoints in scope — so an excluded source's numbers can't be recovered by subtraction. Consumer is the remote-caller ladder in `src/core/ops/admin.ts`. Embedding-signature stale-detection quartet: `countStaleChunks(opts?)` gains optional `signature?: string` widening the stale predicate from `embedding IS NULL` to ALSO include chunks whose JOINed page `embedding_signature IS NOT NULL AND <> $signature` (NULL signature is GRANDFATHERED, never counted; omit `signature` for the legacy NULL-only count); `sumStaleChunkChars(opts?: {sourceId?, signature?}): Promise<number>` = `SUM(LENGTH(chunk_text))` over stale chunks (same predicate + embed_skip filter + optional sourceId scope), used by `gbrain sync --all` cost preview via `estimateCostFromChars`; `setPageEmbeddingSignature(slug, {sourceId?, signature})` stamps `pages.embedding_signature` after a page's chunks (re)embed, idempotent no-op when page absent; `invalidateStaleSignatureEmbeddings({signature, sourceId?}): Promise<number>` NULLs `embedding`+`embedded_at` on every chunk whose page signature is set AND differs, returning the count, called BEFORE `listStaleChunks` so signature-drift pages flow through the NULL-embedding keyset cursor unchanged (NULL never invalidated). Widens `findOrphanPages(opts?: {sourceId?, sourceIds?})` (candidate-side scoping only; inbound links counted from any source). Pinned by `test/sum-stale-chunk-chars.test.ts`, `test/embedding-signature-stale.test.ts`, `test/e2e/engine-parity.test.ts`. Free-text alias layer: `resolveAliases(aliasNorms, opts?): Promise<Map<string, Array<{slug, source_id}>>>` (READ; maps each normalized alias to declaring `(slug, source_id)` pairs, source-scoped) and `setPageAliases(slug, sourceId, aliasNorms)` (WRITE; replaces the full alias set, delete-then-insert, empty clears, idempotent on the unique triple), called by the `importFromContent` ingest projection and the `reindex --aliases` backfill; parity across both engines, Pinned by `test/search/page-aliases-engine.test.ts`. `searchVector` in both engines injects the shared `buildBestPerPagePoolCte` per-page max-pool so a page surfaces on its strongest chunk. `executeRawDirect(sql, params?, opts?)` is the lock-hot-path sibling of `executeRaw`: same single-statement contract, but routes to the direct session-mode pool when dual-pool is active (Postgres/Supabase port 5432) so a long-held lock heartbeat survives the transaction pooler's per-transaction connection recycling; PGLite delegates straight to `executeRaw` (no pooler). Both engines implement it; the Minion lock path (`claim`/`renewLock`) is the consumer. `reconnect(ctx?: {error?})` is a REQUIRED lifecycle method on BOTH engines: it recovers a dropped connection using the config captured at the last `connect()`, so callers (autopilot health probe, `batchRetry`) never `disconnect()` + bare `connect()` (which loses the config and throws `database_url undefined` forever, and opens a null-connection window). PostgresEngine rebuilds its pool with a `_reconnecting` reentrancy guard and emits pool-recovery audit; PGLite is single-writer in-process so it just restores the saved data dir for parity. Plus two interface members: (1) optional `findDuplicatePage?(sourceId, {hash, frontmatterId?}): Promise<{slug, id} | null>` (identity precedence is content_hash OR frontmatter->>'id', both with `deleted_at IS NULL`); (2) `resolveSlugs(partial, opts?)` extended with `{sourceId?, sourceIds?}` so the MCP fuzzy `get_page` path scopes by source (field names match `sourceScopeOpts(ctx)` output so handlers spread directly; no opts gives the unscoped behavior). Plus a stable tiebreaker `ORDER BY score DESC, page_id ASC, chunk_id ASC` in `searchVector` in both engines: on a score tie (basis-vector eval fixtures) older `page_id` wins, so a new index on `pages` cannot flip ranking on tied scores.
-- `src/core/migrate.ts` — schema-migration runner. Re-exports `MIGRATIONS` from the generated registry `src/core/schema-migrations/registry.generated.ts`; each migration is one file `src/core/schema-migrations/v<NNN>-<name>.ts` (the source of truth for schema DDL history), with the `Migration` type in `schema-migrations/types.ts` and shared handler helpers (`migrationNotice`, `dropInvalidConcurrentIndex`, the fresh-install quiet flag) in `schema-migrations/helpers.ts`, a leaf that never imports `migrate.ts`. `Migration` carries `sqlFor?: { postgres?, pglite? }` (engine-specific SQL overrides `sql`) and `transaction?: boolean` (false for `CREATE INDEX CONCURRENTLY`, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches on `engine.kind` for CONCURRENTLY-on-Postgres with invalid-remnant pre-drop via `pg_index.indisvalid`, plain `CREATE INDEX` on PGLite); v15 (`minion_jobs.max_stalled` default 1→5 + backfill non-terminal rows); v24 `rls_backfill_missing_tables` (`sqlFor: { pglite: '' }` no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30 `dream_verdicts (file_path TEXT, content_hash TEXT, worth_processing BOOL, reasons JSONB, judged_at TIMESTAMPTZ, PK(file_path, content_hash))` (RLS-enabled under BYPASSRLS; synthesize reads/writes to avoid re-judging); v35 auto-RLS event trigger `auto_rls_on_create_table` fires on `ddl_command_end` for `WHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO')` running `ALTER TABLE … ENABLE ROW LEVEL SECURITY` on new `public.*` tables (no FORCE) + one-time backfill on every existing `public.*` base table whose comment doesn't match `^GBRAIN:RLS_EXEMPT\s+reason=\S.{3,}` (per-table failure aborts the offending CREATE TABLE; no EXCEPTION wrap; PGLite no-op via `sqlFor.pglite: ''`; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40 `pages_emotional_weight` (`pages.emotional_weight REAL NOT NULL DEFAULT 0.0`, column-only metadata-only); v46 `mcp_request_log_params_jsonb_normalize` (`UPDATE ... SET params = params::text::jsonb WHERE jsonb_typeof(params) = 'string'`, idempotent); v60-v65 six-migration chain wiring source-scoping into `oauth_clients` — v60 (`oauth_clients_source_id_fk`: `source_id TEXT` NULL→`'default'` backfill + FK to `sources(id) ON DELETE SET NULL`), v61 (`federated_read TEXT[] NOT NULL DEFAULT '{}'`), v62 (explicit-CASE backfill so `source_id IS NULL` → `'{}'`), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped to `ON DELETE RESTRICT`), v65 (GIN index for array-containment); v68 `eval_candidates_embedding_column` (`eval_candidates.embedding_column TEXT NULL` per-row provenance for `gbrain eval replay` to reproduce the same retrieval space; NULL-tolerant); v108 `pages_embedding_signature` (`pages.embedding_signature TEXT NULL` = `<provider:model>:<dims>` stamped via `setPageEmbeddingSignature`; GRANDFATHER — stale predicate is `embedding_signature IS NOT NULL AND embedding_signature <> $current` so NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109 `sources_newest_content_at` (`sources.newest_content_at TIMESTAMPTZ` durable newest-COMMIT HEAD committer time written by `writeSyncAnchor`, read by the REMOTE staleness path instead of shelling to git; fresh-install column in `src/schema.sql`, generated into both blobs, plus a bootstrap probe); v110 `page_aliases` (`(id, source_id, alias_norm, slug, ...)` with `UNIQUE (source_id, alias_norm, slug)` + lookup indexes on `(source_id, alias_norm)` and `(source_id, slug)`; `alias_norm` is `normalizeAlias()` output so WRITE/READ key on the same form; also in `src/core/pglite-schema.ts`); v111 `search_telemetry_rank1_columns` (`ADD COLUMN IF NOT EXISTS` on both engines: `sum_rank1_score`, `count_rank1`, three buckets `rank1_lt_solid`/`rank1_solid`/`rank1_high` on `search_telemetry` — aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114 `links_link_source_check_kebab_regex` (opens `link_source` from the closed allowlist to a kebab-case format gate `^[a-z][a-z0-9]*(-[a-z0-9]+)*$` + `char_length<=64`; Postgres branch uses `NOT VALID` + `VALIDATE CONSTRAINT` with `transaction:false`, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116 `code_edges_source_backfill_and_callee_index` (idempotent: backfills NULL `code_edges_symbol`/`code_edges_chunk` `source_id` from each edge's `from_chunk` page — a NULL never matches a scoped `AND source_id = …` filter, so scoped `code-callers`/`code-callees` would return 0 rows on multi-source brains — plus plain `CREATE INDEX` on `from_symbol_qualified` for both edge tables, which had no index and seq-scanned per BFS node); v129 `dream_verdicts_triage_v1_columns` (additive `ADD COLUMN IF NOT EXISTS` widening `dream_verdicts` into a scored triage record — `score`, `content_type`, `segments`, `entities`, `model`, `triage_version`; legacy rows keep `score` NULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines since `dream_verdicts` is migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route in `test/schema-bootstrap-coverage.test.ts` rather than bootstrap probes); v143 `dream_verdicts_ttl` (30-day `expires_at` TTL: nullable `ADD COLUMN` + `SET DEFAULT` run BEFORE the `judged_at`-derived backfill — statement order is load-bearing so a legacy writer racing the upgrade window picks up the default instead of inserting a NULL that would fail `SET NOT NULL` on every retry; on Postgres the schema blob's `dream_verdicts_expires_idx` forward-references the column, so `forward-reference-bootstrap.ts` probes + ALTERs it before the blob replays, and both engines' `getDreamVerdict` read predicate is NULL-tolerant — `expires_at IS NULL OR expires_at > now()` — so a pre-backfill row reads as a hit instead of silently re-judging the corpus). Three shape-keyed self-heals run on EVERY `runMigrations` pass, including the no-pending early-return path, because a merge-renumbered migration or a drifted restore can leave the version counter past a schema change while the live shape stays old: `repairTimelineDedupIndex` (`timeline_dedup_index`, see `timeline-dedup-repair.ts`) and `repairPagesUpsertArbiter` (`pages_source_slug_key`, see `pages-upsert-arbiter.ts`) are not version-gated at all; `repairLinkSourceCheck` (`links_link_source_check`, see `link-source-check-repair.ts`) runs only when the ledger is already >= `LINK_SOURCE_GATE_MIGRATION_VERSION` (114), because below it the pending loop replays v114 itself (running the repair first would rewrite the constraint twice, and a pre-v11 brain has no `link_source` column). All three are best-effort + idempotent; `doctor` surfaces each drift independently. `retry-matcher.ts` and `timeline-dedup-repair.ts` are static dependencies because `runMigrations()` executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95: `pages_dedup_partial_index` adds `CREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL`. Postgres uses `CREATE INDEX CONCURRENTLY` with `transaction: false` + pre-drops any invalid remnant; PGLite uses plain `CREATE INDEX`. Powers `findDuplicatePage` hot path (O(log n) instead of O(n)). v74 `mcp_spend_log` uses BTREE on `(client_id, created_at)` + `(token_name, created_at)` — `date_trunc('day', TIMESTAMPTZ)` is NOT IMMUTABLE so can't appear in index expressions; a `created_at` range scan covers the per-day rollup. v75 `embedding_multimodal_column` is column-only (no HNSW index — deferred to post-reindex per pgvector best practice).
+- `src/core/migrate.ts` — schema-migration runner. Re-exports `MIGRATIONS` from the generated registry `src/core/schema-migrations/registry.generated.ts`; each migration is one file `src/core/schema-migrations/v<NNN>-<name>.ts` (the source of truth for schema DDL history), with the `Migration` type in `schema-migrations/types.ts` and shared handler helpers (`migrationNotice`, `dropInvalidConcurrentIndex`, the fresh-install quiet flag) in `schema-migrations/helpers.ts`, a leaf that never imports `migrate.ts`. `Migration` carries `sqlFor?: { postgres?, pglite? }` (engine-specific SQL overrides `sql`) and `transaction?: boolean` (false for `CREATE INDEX CONCURRENTLY`, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches on `engine.kind` for CONCURRENTLY-on-Postgres with invalid-remnant pre-drop via `pg_index.indisvalid`, plain `CREATE INDEX` on PGLite); v15 (`minion_jobs.max_stalled` default 1→5 + backfill non-terminal rows); v24 `rls_backfill_missing_tables` (`sqlFor: { pglite: '' }` no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30 `dream_verdicts (file_path TEXT, content_hash TEXT, worth_processing BOOL, reasons JSONB, judged_at TIMESTAMPTZ, PK(file_path, content_hash))` (RLS-enabled under BYPASSRLS; synthesize reads/writes to avoid re-judging); v35 auto-RLS event trigger `auto_rls_on_create_table` fires on `ddl_command_end` for `WHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO')` running `ALTER TABLE … ENABLE ROW LEVEL SECURITY` on new `public.*` tables (no FORCE) + one-time backfill on every existing `public.*` base table whose comment doesn't match `^GBRAIN:RLS_EXEMPT\s+reason=\S.{3,}` (per-table failure aborts the offending CREATE TABLE; no EXCEPTION wrap; PGLite no-op via `sqlFor.pglite: ''`; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40 `pages_emotional_weight` (`pages.emotional_weight REAL NOT NULL DEFAULT 0.0`, column-only metadata-only); v46 `mcp_request_log_params_jsonb_normalize` (`UPDATE ... SET params = params::text::jsonb WHERE jsonb_typeof(params) = 'string'`, idempotent); v60-v65 six-migration chain wiring source-scoping into `oauth_clients` — v60 (`oauth_clients_source_id_fk`: `source_id TEXT` NULL→`'default'` backfill + FK to `sources(id) ON DELETE SET NULL`), v61 (`federated_read TEXT[] NOT NULL DEFAULT '{}'`), v62 (explicit-CASE backfill so `source_id IS NULL` → `'{}'`), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped to `ON DELETE RESTRICT`), v65 (GIN index for array-containment); v68 `eval_candidates_embedding_column` (`eval_candidates.embedding_column TEXT NULL` per-row provenance for `gbrain eval replay` to reproduce the same retrieval space; NULL-tolerant); v108 `pages_embedding_signature` (`pages.embedding_signature TEXT NULL` = `<provider:model>:<dims>` stamped via `setPageEmbeddingSignature`; GRANDFATHER — stale predicate is `embedding_signature IS NOT NULL AND embedding_signature <> $current` so NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109 `sources_newest_content_at` (`sources.newest_content_at TIMESTAMPTZ` durable newest-COMMIT HEAD committer time written by `writeSyncAnchor`, read by the REMOTE staleness path instead of shelling to git; fresh-install column in `src/schema.sql`, generated into both blobs, plus a bootstrap probe); v110 `page_aliases` (`(id, source_id, alias_norm, slug, ...)` with `UNIQUE (source_id, alias_norm, slug)` + lookup indexes on `(source_id, alias_norm)` and `(source_id, slug)`; `alias_norm` is `normalizeAlias()` output so WRITE/READ key on the same form; also in `src/core/pglite-schema.ts`); v111 `search_telemetry_rank1_columns` (`ADD COLUMN IF NOT EXISTS` on both engines: `sum_rank1_score`, `count_rank1`, three buckets `rank1_lt_solid`/`rank1_solid`/`rank1_high` on `search_telemetry` — aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114 `links_link_source_check_kebab_regex` (opens `link_source` from the closed allowlist to a kebab-case format gate `^[a-z][a-z0-9]*(-[a-z0-9]+)*$` + `char_length<=64`; Postgres branch uses `NOT VALID` + `VALIDATE CONSTRAINT` with `transaction:false`, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116 `code_edges_source_backfill_and_callee_index` (idempotent: backfills NULL `code_edges_symbol`/`code_edges_chunk` `source_id` from each edge's `from_chunk` page — a NULL never matches a scoped `AND source_id = …` filter, so scoped `code-callers`/`code-callees` would return 0 rows on multi-source brains — plus plain `CREATE INDEX` on `from_symbol_qualified` for both edge tables, which had no index and seq-scanned per BFS node); v129 `dream_verdicts_triage_v1_columns` (additive `ADD COLUMN IF NOT EXISTS` widening `dream_verdicts` into a scored triage record — `score`, `content_type`, `segments`, `entities`, `model`, `triage_version`; legacy rows keep `score` NULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines since `dream_verdicts` is migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route in `test/schema-bootstrap-coverage.test.ts` rather than bootstrap probes); v143 `dream_verdicts_ttl` (30-day `expires_at` TTL: nullable `ADD COLUMN` + `SET DEFAULT` run BEFORE the `judged_at`-derived backfill — statement order is load-bearing so a legacy writer racing the upgrade window picks up the default instead of inserting a NULL that would fail `SET NOT NULL` on every retry; on Postgres the schema blob's `dream_verdicts_expires_idx` forward-references the column, so `forward-reference-bootstrap.ts` probes + ALTERs it before the blob replays, and both engines' `getDreamVerdict` read predicate is NULL-tolerant — `expires_at IS NULL OR expires_at > now()` — so a pre-backfill row reads as a hit instead of silently re-judging the corpus). Three shape-keyed self-heals run on EVERY `runMigrations` pass, including the no-pending early-return path, because a merge-renumbered migration or a drifted restore can leave the version counter past a schema change while the live shape stays old: `repairTimelineDedupIndex` (`timeline_dedup_index`, see `timeline-dedup-repair.ts`) and `repairPagesUpsertArbiter` (`pages_source_slug_key`, see `pages-upsert-arbiter.ts`) are not version-gated at all; `repairLinkSourceCheck` (`links_link_source_check`, see `link-source-check-repair.ts`) runs only when the ledger is already >= `LINK_SOURCE_GATE_MIGRATION_VERSION` (114), because below it the pending loop replays v114 itself (running the repair first would rewrite the constraint twice, and a pre-v11 brain has no `link_source` column). All three are best-effort + idempotent; `doctor` surfaces each drift independently. `retry-matcher.ts` and `timeline-dedup-repair.ts` are static dependencies because `runMigrations()` executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95: `pages_dedup_partial_index` adds `CREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL`. Postgres uses `CREATE INDEX CONCURRENTLY` with `transaction: false` + pre-drops any invalid remnant; PGLite uses plain `CREATE INDEX`. Powers `findDuplicatePage` hot path (O(log n) instead of O(n)). v74 `mcp_spend_log` uses BTREE on `(client_id, created_at)` + `(token_name, created_at)` — `date_trunc('day', TIMESTAMPTZ)` is NOT IMMUTABLE so can't appear in index expressions; a `created_at` range scan covers the per-day rollup. v75 `embedding_multimodal_column` is column-only (no HNSW index — deferred to post-reindex per pgvector best practice). Every pass (including one with nothing pending) ends with `page-state/revision-backfill.ts:resumePageRevisionBackfill` while `pages.knowledge_revision` is nullable (#5216): the page-state schema adds `sources.incarnation` and `pages.knowledge_revision` nullable with a separate default (no volatile-default table rewrite on replay; an empty `pages` is constrained at once), rows are backfilled in committed id batches with a config cursor (`page_state.revision_backfill`), a failing row is isolated and retried at most three passes, and the column becomes NOT NULL via CHECK NOT VALID → VALIDATE → SET NOT NULL. The revision trigger handles a NULL old revision without reading bodies; snapshots report such a row's revision as `backfill_pending` and `assertPageRevision` refuses revision-bound writes with `revision_backfill_pending` (`page-revision-backfill-5216.test.ts`).
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The runner (ordering, retry, verify, repair-handler hooks and the static helper imports engine-live paths require) has a plain ratchet ceiling; migrations no longer live in this file.
- `src/core/pglite-embedded-assets.ts` + `src/core/pglite-embedded-asset-paths.ts` — PGLite runtime-asset supply for every run mode (compiled binary, source checkout, bun-global install). `pglite-embedded-asset-paths.ts` is the bundler ANCHOR: five literal `with { type: 'file' }` imports of the wasm/data/extension-tarball assets via repo-relative node_modules paths (the package's `exports` map hides `./dist/*`) — keep the specifiers literal and byte-stable, an expression or indirection silently stops the bytes embedding and the compiled binary falls into the Bun-vfs ENOENT failure. `resolvePgliteAssetPaths()` in `pglite-embedded-assets.ts` is the tiered resolver: tier 1 dynamically `import()`s the anchor (the rejection under a hoisted install — bun-global upgrades dedupe `@electric-sql/pglite` to the global root, making the anchor's specifiers unresolvable — is EXPECTED and routes to tier 2, which is why the anchor is not a static import); tier 2 derives the dist dir via module resolution of `@electric-sql/pglite` (`import.meta.resolve` then `createRequire` — the SAME specifier the engine imports, so assets can never come from a different pglite copy than the loaded JS); tier 3 throws one actionable error naming everything tried, with the canonical GitHub reinstall command (never the npm-registry name, which is squatted — see the README install warning). `getEmbeddedPgliteOptions()` memoizes one build per process and hands PGLite compiled `WebAssembly.Module`s + fs-bundle Blob + materialized extension tarballs via `PGliteOptions`. Pinned by `test/pglite-embedded-assets.test.ts` + `test/pglite-hoisted-install.serial.test.ts` (real `bun add -g`-shaped hoisted layout).
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 50b9f037e7..c8f901f5d5 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -73,6 +73,7 @@ a receipt can report has a row here.
| `writer_pool_capacity` | `writer_pool_capacity` | The canonical owner has no free publication slot right now; the write stays queued. | Wait and poll the receipt (`gbrain write-request <id>`). If it persists, check `gbrain sources writer status <source>`. |
| `revision_required` | `revision_required` | The operation must be bound to a revision you reviewed (for example `--if-version` or `expected_revision`), and none was given. | Preview first, then repeat with the revision the preview printed. |
| `revision_conflict` | `revision_conflict` | The page changed after the revision this write was bound to. Nothing was overwritten. | Re-read the page, merge your change, and save with the new revision. |
+| `revision_backfill_pending` | `revision_backfill_pending` | The page was written before page revisions existed (an upgrade from below schema v150) and the resumable revision backfill has not reached it, so it has no revision to bind to. Its revision reads as `backfill_pending`, never a UUID. Nothing was written. | Resume the backfill with `gbrain apply-migrations --yes` (it prints its progress). If it reports rows it could not update, run `gbrain repair orphan-children` to preview orphaned child rows and torn page bodies ([orphan children](repair.md#orphan-children)). |
| `idempotency_conflict` | `idempotency_conflict` | The `request_id` was already used for a different target, content or protocol. | Use a new `request_id` for a different write; reuse an ID only to replay the same write. |
| `write_pending` | `write_pending` | The write was accepted but has not committed yet, or its acknowledgment was lost. It keeps its request ID. | Poll `gbrain write-request <id>`, or repeat the same command with the same options to resume. |
| `storage_error` | `storage_error` | The write did not commit for a reason with no more specific code. | Inspect the durable request with `gbrain write-request <id>` on the source host and follow its message. |
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 2118ec43c0..64348c33a6 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -18,7 +18,7 @@ src/core/cycle/synthesize.ts 3291 ratchet +26 System One v1 S7/S8: triage and gr
src/core/cycle/extract-atoms.ts 1834 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize
src/core/engine.ts 2674 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option
src/core/import-file.ts 2230 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode)
-src/core/migrate.ts 599 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3)
+src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 331 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration
src/core/pglite-engine.ts 3225 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166)
src/core/postgres-engine.ts 3252 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156)
diff --git a/src/core/migrate.ts b/src/core/migrate.ts
index 191a973af9..54c35182e0 100644
--- a/src/core/migrate.ts
+++ b/src/core/migrate.ts
@@ -9,6 +9,7 @@ import {
isRetryableConnError,
} from './retry-matcher.ts';
import { repairTimelineDedupIndex } from './timeline-dedup-repair.ts';
+import { resumePageRevisionBackfill } from './page-state/revision-backfill.ts';
import { repairPagesUpsertArbiter } from './pages-upsert-arbiter.ts';
import { repairLinkSourceCheck, LINK_SOURCE_GATE_MIGRATION_VERSION } from './link-source-check-repair.ts';
@@ -464,7 +465,9 @@ export async function runMigrations(engine: BrainEngine): Promise<{ applied: num
}
}
+ const backfill = () => resumePageRevisionBackfill(engine).catch(e => console.error(`[migrate] page revision backfill paused (#5216): ${e instanceof Error ? e.message : String(e)}`));
if (pending.length === 0) {
+ await backfill();
return { applied: 0, current };
}
@@ -519,7 +522,7 @@ export async function runMigrations(engine: BrainEngine): Promise<{ applied: num
// covers every exit path from here on (incl. the pre-flight probe).
setQuietMigrationNotices(false);
}
-
+ await backfill();
return { applied, current: LATEST_VERSION };
}
diff --git a/src/core/page-state/revision-backfill.ts b/src/core/page-state/revision-backfill.ts
new file mode 100644
index 0000000000..d9f1b4e92b
--- /dev/null
+++ b/src/core/page-state/revision-backfill.ts
@@ -0,0 +1,107 @@
+/**
+ * #5216: resumable `pages.knowledge_revision` backfill. The page-state schema
+ * adds the column nullable (a NOT NULL volatile default rewrites the table and
+ * reads every TOAST value), so rows written before it carry NULL until this
+ * pass assigns them a revision. Runs at the end of every migration pass while
+ * the column is still nullable; a NOT NULL column costs one catalog probe.
+ *
+ * Rows are updated in committed id-ordered batches; the cursor is kept in the
+ * config row `page_state.revision_backfill`, so an interrupted pass resumes and
+ * never reassigns a revision it already gave. A batch that fails is retried row
+ * by row; a row that still fails (for example a torn TOAST value) is isolated,
+ * reported and retried on at most MAX_ATTEMPTS later passes, never forever.
+ * When no NULL row remains the column becomes NOT NULL through a CHECK added
+ * NOT VALID, validated without blocking writes, then SET NOT NULL and dropped,
+ * so the final constraints equal a fresh install.
+ */
+import type { BrainEngine } from '../engine.ts';
+
+export const REVISION_BACKFILL_STATE_KEY = 'page_state.revision_backfill';
+export const REVISION_BACKFILL_RESUME_COMMAND = 'gbrain apply-migrations --yes';
+const MAX_ATTEMPTS = 3;
+const CHECK_NAME = 'pages_knowledge_revision_backfilled';
+
+interface FailedRow { id: number; attempts: number; error: string }
+interface BackfillState { cursor: number; backfilled: number; failed: FailedRow[] }
+
+export interface RevisionBackfillResult {
+ status: 'not_needed' | 'complete' | 'pending';
+ backfilled: number;
+ failed: FailedRow[];
+}
+
+async function readState(engine: BrainEngine): Promise<BackfillState> {
+ try {
+ const parsed = JSON.parse((await engine.getConfig(REVISION_BACKFILL_STATE_KEY)) ?? 'null') as BackfillState | null;
+ if (parsed && Number.isSafeInteger(parsed.cursor) && Array.isArray(parsed.failed)) return parsed;
+ } catch { /* a corrupt cursor restarts from the first id; assigned revisions are never reassigned */ }
+ return { cursor: 0, backfilled: 0, failed: [] };
+}
+
+async function assignRow(engine: BrainEngine, id: number): Promise<void> {
+ await engine.executeRaw('UPDATE pages SET knowledge_revision = gen_random_uuid() WHERE id = $1 AND knowledge_revision IS NULL', [id]);
+}
+
+export async function resumePageRevisionBackfill(
+ engine: BrainEngine,
+ opts: { batchSize?: number; log?: (line: string) => void } = {},
+): Promise<RevisionBackfillResult> {
+ const log = opts.log ?? ((line: string) => process.stderr.write(line + '\n'));
+ const column = await engine.executeRaw<{ notnull: boolean }>(
+ `SELECT attnotnull AS notnull FROM pg_attribute
+ WHERE attrelid = to_regclass('pages') AND attname = 'knowledge_revision' AND NOT attisdropped`);
+ if (column.length === 0 || column[0]!.notnull) return { status: 'not_needed', backfilled: 0, failed: [] };
+
+ const batchSize = opts.batchSize ?? 1000;
+ const state = await readState(engine);
+ const save = () => engine.setConfig(REVISION_BACKFILL_STATE_KEY, JSON.stringify(state));
+ let announced = false;
+ for (;;) {
+ const ids = (await engine.executeRaw<{ id: number }>(
+ 'SELECT id FROM pages WHERE id > $1 AND knowledge_revision IS NULL ORDER BY id LIMIT $2', [state.cursor, batchSize])).map(r => Number(r.id));
+ if (ids.length === 0) break;
+ if (!announced) {
+ log(`[migrate] backfilling page revisions in batches of ${batchSize} (resumable; resume with: ${REVISION_BACKFILL_RESUME_COMMAND})`);
+ announced = true;
+ }
+ try {
+ await engine.executeRaw('UPDATE pages SET knowledge_revision = gen_random_uuid() WHERE id = ANY($1::bigint[]) AND knowledge_revision IS NULL', [ids]);
+ state.backfilled += ids.length;
+ } catch {
+ for (const id of ids) {
+ try { await assignRow(engine, id); state.backfilled++; }
+ catch (error) {
+ state.failed.push({ id, attempts: 1, error: (error instanceof Error ? error.message : String(error)).slice(0, 200) });
+ }
+ }
+ }
+ state.cursor = ids[ids.length - 1]!;
+ await save();
+ log(`[migrate] page revision backfill: ${state.backfilled} row(s) done, through page id ${state.cursor}`);
+ }
+
+ const failed: FailedRow[] = [];
+ for (const row of state.failed) {
+ const [still] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE id = $1 AND knowledge_revision IS NULL', [row.id]);
+ if (!still) continue;
+ if (row.attempts >= MAX_ATTEMPTS) { failed.push(row); continue; }
+ try { await assignRow(engine, row.id); state.backfilled++; }
+ catch (error) { failed.push({ id: row.id, attempts: row.attempts + 1, error: (error instanceof Error ? error.message : String(error)).slice(0, 200) }); }
+ }
+ state.failed = failed;
+ if (failed.length > 0) {
+ await save();
+ log(`[migrate] page revision backfill: ${failed.length} row(s) could not be updated (page ids ${failed.slice(0, 10).map(f => f.id).join(', ')}${failed.length > 10 ? ', …' : ''}). `
+ + `Writes that name a revision for them are refused with revision_backfill_pending. Diagnose with: gbrain repair orphan-children (preview, includes the torn-TOAST probe). See docs/guides/repair.md#orphan-children`);
+ return { status: 'pending', backfilled: state.backfilled, failed };
+ }
+
+ await engine.executeRaw(`ALTER TABLE pages DROP CONSTRAINT IF EXISTS ${CHECK_NAME}`);
+ await engine.executeRaw(`ALTER TABLE pages ADD CONSTRAINT ${CHECK_NAME} CHECK (knowledge_revision IS NOT NULL) NOT VALID`);
+ await engine.executeRaw(`ALTER TABLE pages VALIDATE CONSTRAINT ${CHECK_NAME}`);
+ await engine.executeRaw('ALTER TABLE pages ALTER COLUMN knowledge_revision SET NOT NULL');
+ await engine.executeRaw(`ALTER TABLE pages DROP CONSTRAINT ${CHECK_NAME}`);
+ await engine.unsetConfig(REVISION_BACKFILL_STATE_KEY);
+ if (announced) log(`[migrate] page revision backfill complete: ${state.backfilled} row(s)`);
+ return { status: 'complete', backfilled: state.backfilled, failed: [] };
+}
diff --git a/src/core/page-state/schema.ts b/src/core/page-state/schema.ts
index dc8c46ccda..26a38df194 100644
--- a/src/core/page-state/schema.ts
+++ b/src/core/page-state/schema.ts
@@ -1,11 +1,42 @@
/** NULL marks a legacy snapshot whose deletion state was not recorded. */
export const PAGE_VERSION_DELETION_SCHEMA_SQL = `ALTER TABLE page_versions ADD COLUMN IF NOT EXISTS is_deleted BOOLEAN;`;
-/** Shared by migration 150 and both schema blobs. Statements stay idempotent. */
+/**
+ * Shared by migration 150 and both schema blobs, so Postgres also replays it
+ * before pending migrations. Statements stay idempotent. #5216: a column with
+ * a volatile default added NOT NULL rewrites the whole table (and reads every
+ * TOAST value, failing on a torn one), so both UUID columns are added
+ * nullable, get their default separately, and become NOT NULL only when no
+ * row needs a value: `sources` is backfilled here (a handful of rows), an
+ * empty `pages` (fresh install) is constrained here, and existing pages are
+ * backfilled in committed batches by page-state/revision-backfill.ts.
+ */
export const PAGE_STATE_SCHEMA_STATEMENTS = [
- `ALTER TABLE sources ADD COLUMN IF NOT EXISTS incarnation UUID NOT NULL DEFAULT gen_random_uuid()`,
+ `DO $do$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'sources'::regclass AND attname = 'incarnation' AND NOT attisdropped) THEN
+ ALTER TABLE sources ADD COLUMN IF NOT EXISTS incarnation UUID;
+ END IF;
+ IF NOT EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'sources'::regclass AND attname = 'incarnation' AND atthasdef) THEN
+ ALTER TABLE sources ALTER COLUMN incarnation SET DEFAULT gen_random_uuid();
+ END IF;
+ IF EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'sources'::regclass AND attname = 'incarnation' AND NOT attnotnull) THEN
+ UPDATE sources SET incarnation = gen_random_uuid() WHERE incarnation IS NULL;
+ ALTER TABLE sources ALTER COLUMN incarnation SET NOT NULL;
+ END IF;
+ END $do$`,
`CREATE UNIQUE INDEX IF NOT EXISTS sources_incarnation_key ON sources(incarnation)`,
- `ALTER TABLE pages ADD COLUMN IF NOT EXISTS knowledge_revision UUID NOT NULL DEFAULT gen_random_uuid()`,
+ `DO $do$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'pages'::regclass AND attname = 'knowledge_revision' AND NOT attisdropped) THEN
+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS knowledge_revision UUID;
+ END IF;
+ IF NOT EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'pages'::regclass AND attname = 'knowledge_revision' AND atthasdef) THEN
+ ALTER TABLE pages ALTER COLUMN knowledge_revision SET DEFAULT gen_random_uuid();
+ END IF;
+ IF EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'pages'::regclass AND attname = 'knowledge_revision' AND NOT attnotnull)
+ AND NOT EXISTS (SELECT 1 FROM pages) THEN
+ ALTER TABLE pages ALTER COLUMN knowledge_revision SET NOT NULL;
+ END IF;
+ END $do$`,
`ALTER TABLE pages ADD COLUMN IF NOT EXISTS text_projection_revision UUID`,
`ALTER TABLE page_versions ADD COLUMN IF NOT EXISTS knowledge_revision UUID`,
`ALTER TABLE page_versions ADD COLUMN IF NOT EXISTS timeline TEXT`,
@@ -20,6 +51,11 @@ export const PAGE_STATE_SCHEMA_STATEMENTS = [
)`,
`CREATE OR REPLACE FUNCTION gbrain_advance_page_revision() RETURNS trigger LANGUAGE plpgsql AS $fn$
BEGIN
+ IF OLD.knowledge_revision IS NULL THEN
+ NEW.knowledge_revision := COALESCE(NEW.knowledge_revision, gen_random_uuid());
+ NEW.text_projection_revision := NULL;
+ RETURN NEW;
+ END IF;
IF (NEW.source_id, NEW.slug, NEW.type, NEW.page_kind, NEW.title, NEW.compiled_truth,
NEW.timeline, NEW.frontmatter, NEW.deleted_at)
IS DISTINCT FROM
diff --git a/src/core/page-state/snapshot.ts b/src/core/page-state/snapshot.ts
index 2949e96bb3..f552219feb 100644
--- a/src/core/page-state/snapshot.ts
+++ b/src/core/page-state/snapshot.ts
@@ -3,7 +3,7 @@ import { privatePagesFilterFragment } from '../search/private-visibility.ts';
import type { ReadQuery } from '../search/read-enrichment.ts';
import { rowToPage } from '../utils.ts';
import type { PageSnapshot, PageSnapshotOptions, PageWithdrawal } from './types.ts';
-import { PageSnapshotAmbiguousError } from './types.ts';
+import { PageSnapshotAmbiguousError, REVISION_BACKFILL_PENDING } from './types.ts';
/** Normalize filesystem bytes with the exact ledger fingerprint rules before comparing them. */
export async function overlayCanonicalBodies(query: ReadQuery, body: string, timeline: string, withdrawals: PageWithdrawal[]): Promise<{ compiled_truth: string; timeline: string }> {
@@ -60,6 +60,6 @@ export async function readPageSnapshot(query: ReadQuery, slug: string, opts?: Pa
const withdrawals = row.snapshot_withdrawals as PageWithdrawal[];
page.compiled_truth = overlayWithdrawalBody(page.compiled_truth, String(row.fingerprint_body ?? ''), withdrawals);
page.timeline = overlayWithdrawalBody(page.timeline, String(row.fingerprint_timeline ?? ''), withdrawals);
- return { page, tags: row.snapshot_tags as string[], revision: String(row.knowledge_revision),
+ return { page, tags: row.snapshot_tags as string[], revision: row.knowledge_revision == null ? REVISION_BACKFILL_PENDING : String(row.knowledge_revision),
sourceIncarnation: String(row.source_incarnation), withdrawals };
}
diff --git a/src/core/page-state/types.ts b/src/core/page-state/types.ts
index a08f764469..36f6e731c1 100644
--- a/src/core/page-state/types.ts
+++ b/src/core/page-state/types.ts
@@ -39,7 +39,7 @@ export interface PageSnapshot {
}
export class PageRevisionConflictError extends Error {
- readonly code = 'revision_conflict';
+ readonly code: 'revision_conflict' | 'revision_backfill_pending' = 'revision_conflict';
constructor(readonly expectedRevision: string | null, readonly currentRevision: string | null) {
super(currentRevision === null ? 'The page no longer exists at the expected revision.'
: expectedRevision === null ? 'The page already exists; an expected revision is required.'
@@ -48,6 +48,20 @@ export class PageRevisionConflictError extends Error {
}
}
+/** #5216: the snapshot revision of a row written before the column existed and not yet backfilled. Never a UUID. */
+export const REVISION_BACKFILL_PENDING = 'backfill_pending';
+
+/** A revision-bound write to a row whose revision is still being backfilled. A conflict to every retry loop. */
+export class RevisionBackfillPendingError extends PageRevisionConflictError {
+ override readonly code = 'revision_backfill_pending' as const;
+ constructor(expectedRevision: string | null) {
+ super(expectedRevision, REVISION_BACKFILL_PENDING);
+ this.message = 'This page has no revision yet: the revision backfill for pages written before the upgrade has not reached it. '
+ + 'Resume it with: gbrain apply-migrations --yes (see docs/guides/write-refusals.md#other-error-codes).';
+ this.name = 'RevisionBackfillPendingError';
+ }
+}
+
/** Call after locking the exact source/page key, including absent pages. */
export function assertPageRevision(snapshot: Pick<PageSnapshot, 'revision'> | null, precondition: PageMutationPrecondition = {}): void {
const { expectedRevision, force } = precondition;
@@ -57,6 +71,7 @@ export function assertPageRevision(snapshot: Pick<PageSnapshot, 'revision'> | nu
}
if (force && expectedRevision !== undefined) throw new TypeError('force and expectedRevision are mutually exclusive');
if (force) return;
+ if (snapshot?.revision === REVISION_BACKFILL_PENDING) throw new RevisionBackfillPendingError(expectedRevision ?? null);
const current = snapshot?.revision ?? null;
if (current !== (expectedRevision?.toLowerCase() ?? null)) throw new PageRevisionConflictError(expectedRevision ?? null, current);
}
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index 43e58690e3..605f3baaeb 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -994,9 +994,31 @@ CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON minion_jobs
FOR EACH ROW EXECUTE FUNCTION enforce_minion_queue_protocol();
-- Canonical page state (migration 150).
-ALTER TABLE sources ADD COLUMN IF NOT EXISTS incarnation UUID NOT NULL DEFAULT gen_random_uuid();
+DO \$do\$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'sources'::regclass AND attname = 'incarnation' AND NOT attisdropped) THEN
+ ALTER TABLE sources ADD COLUMN IF NOT EXISTS incarnation UUID;
+ END IF;
+ IF NOT EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'sources'::regclass AND attname = 'incarnation' AND atthasdef) THEN
+ ALTER TABLE sources ALTER COLUMN incarnation SET DEFAULT gen_random_uuid();
+ END IF;
+ IF EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'sources'::regclass AND attname = 'incarnation' AND NOT attnotnull) THEN
+ UPDATE sources SET incarnation = gen_random_uuid() WHERE incarnation IS NULL;
+ ALTER TABLE sources ALTER COLUMN incarnation SET NOT NULL;
+ END IF;
+ END \$do\$;
CREATE UNIQUE INDEX IF NOT EXISTS sources_incarnation_key ON sources(incarnation);
-ALTER TABLE pages ADD COLUMN IF NOT EXISTS knowledge_revision UUID NOT NULL DEFAULT gen_random_uuid();
+DO \$do\$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'pages'::regclass AND attname = 'knowledge_revision' AND NOT attisdropped) THEN
+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS knowledge_revision UUID;
+ END IF;
+ IF NOT EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'pages'::regclass AND attname = 'knowledge_revision' AND atthasdef) THEN
+ ALTER TABLE pages ALTER COLUMN knowledge_revision SET DEFAULT gen_random_uuid();
+ END IF;
+ IF EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'pages'::regclass AND attname = 'knowledge_revision' AND NOT attnotnull)
+ AND NOT EXISTS (SELECT 1 FROM pages) THEN
+ ALTER TABLE pages ALTER COLUMN knowledge_revision SET NOT NULL;
+ END IF;
+ END \$do\$;
ALTER TABLE pages ADD COLUMN IF NOT EXISTS text_projection_revision UUID;
ALTER TABLE page_versions ADD COLUMN IF NOT EXISTS knowledge_revision UUID;
ALTER TABLE page_versions ADD COLUMN IF NOT EXISTS timeline TEXT;
@@ -1011,6 +1033,11 @@ CREATE TABLE IF NOT EXISTS page_write_guards (
);
CREATE OR REPLACE FUNCTION gbrain_advance_page_revision() RETURNS trigger LANGUAGE plpgsql AS \$fn\$
BEGIN
+ IF OLD.knowledge_revision IS NULL THEN
+ NEW.knowledge_revision := COALESCE(NEW.knowledge_revision, gen_random_uuid());
+ NEW.text_projection_revision := NULL;
+ RETURN NEW;
+ END IF;
IF (NEW.source_id, NEW.slug, NEW.type, NEW.page_kind, NEW.title, NEW.compiled_truth,
NEW.timeline, NEW.frontmatter, NEW.deleted_at)
IS DISTINCT FROM
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index 67b1e1109d..4a7dab6e42 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -1697,9 +1697,31 @@ END \$\$;
-- Canonical page state (migration 150).
-- BEGIN GENERATED from src/core/page-state/schema.ts (PAGE_STATE_SCHEMA_SQL). Edit that file, then run: bun run build:schema
-ALTER TABLE sources ADD COLUMN IF NOT EXISTS incarnation UUID NOT NULL DEFAULT gen_random_uuid();
+DO \$do\$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'sources'::regclass AND attname = 'incarnation' AND NOT attisdropped) THEN
+ ALTER TABLE sources ADD COLUMN IF NOT EXISTS incarnation UUID;
+ END IF;
+ IF NOT EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'sources'::regclass AND attname = 'incarnation' AND atthasdef) THEN
+ ALTER TABLE sources ALTER COLUMN incarnation SET DEFAULT gen_random_uuid();
+ END IF;
+ IF EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'sources'::regclass AND attname = 'incarnation' AND NOT attnotnull) THEN
+ UPDATE sources SET incarnation = gen_random_uuid() WHERE incarnation IS NULL;
+ ALTER TABLE sources ALTER COLUMN incarnation SET NOT NULL;
+ END IF;
+ END \$do\$;
CREATE UNIQUE INDEX IF NOT EXISTS sources_incarnation_key ON sources(incarnation);
-ALTER TABLE pages ADD COLUMN IF NOT EXISTS knowledge_revision UUID NOT NULL DEFAULT gen_random_uuid();
+DO \$do\$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'pages'::regclass AND attname = 'knowledge_revision' AND NOT attisdropped) THEN
+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS knowledge_revision UUID;
+ END IF;
+ IF NOT EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'pages'::regclass AND attname = 'knowledge_revision' AND atthasdef) THEN
+ ALTER TABLE pages ALTER COLUMN knowledge_revision SET DEFAULT gen_random_uuid();
+ END IF;
+ IF EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'pages'::regclass AND attname = 'knowledge_revision' AND NOT attnotnull)
+ AND NOT EXISTS (SELECT 1 FROM pages) THEN
+ ALTER TABLE pages ALTER COLUMN knowledge_revision SET NOT NULL;
+ END IF;
+ END \$do\$;
ALTER TABLE pages ADD COLUMN IF NOT EXISTS text_projection_revision UUID;
ALTER TABLE page_versions ADD COLUMN IF NOT EXISTS knowledge_revision UUID;
ALTER TABLE page_versions ADD COLUMN IF NOT EXISTS timeline TEXT;
@@ -1714,6 +1736,11 @@ CREATE TABLE IF NOT EXISTS page_write_guards (
);
CREATE OR REPLACE FUNCTION gbrain_advance_page_revision() RETURNS trigger LANGUAGE plpgsql AS \$fn\$
BEGIN
+ IF OLD.knowledge_revision IS NULL THEN
+ NEW.knowledge_revision := COALESCE(NEW.knowledge_revision, gen_random_uuid());
+ NEW.text_projection_revision := NULL;
+ RETURN NEW;
+ END IF;
IF (NEW.source_id, NEW.slug, NEW.type, NEW.page_kind, NEW.title, NEW.compiled_truth,
NEW.timeline, NEW.frontmatter, NEW.deleted_at)
IS DISTINCT FROM
diff --git a/src/core/utils.ts b/src/core/utils.ts
index db114c51d5..0a70ac96e5 100644
--- a/src/core/utils.ts
+++ b/src/core/utils.ts
@@ -222,7 +222,7 @@ export function rowToPage(row: Record<string, unknown>): Page {
frontmatter: (typeof row.frontmatter === 'string' ? JSON.parse(row.frontmatter) : row.frontmatter) as Record<string, unknown>,
content_hash: row.content_hash as string | undefined,
...(row.source_path !== undefined && { source_path: row.source_path as string | null }),
- ...(row.knowledge_revision !== undefined && { knowledge_revision: String(row.knowledge_revision) }),
+ ...(row.knowledge_revision != null && { knowledge_revision: String(row.knowledge_revision) }),
...(row.text_projection_revision !== undefined && { text_projection_revision: row.text_projection_revision as string | null }),
// v0.29 (column added in migration v40). Old brains pre-migration return undefined.
emotional_weight: row.emotional_weight == null ? undefined : Number(row.emotional_weight),
diff --git a/src/schema.sql b/src/schema.sql
index 5b0eb10313..771576639a 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -1693,9 +1693,31 @@ END $$;
-- Canonical page state (migration 150).
-- BEGIN GENERATED from src/core/page-state/schema.ts (PAGE_STATE_SCHEMA_SQL). Edit that file, then run: bun run build:schema
-ALTER TABLE sources ADD COLUMN IF NOT EXISTS incarnation UUID NOT NULL DEFAULT gen_random_uuid();
+DO $do$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'sources'::regclass AND attname = 'incarnation' AND NOT attisdropped) THEN
+ ALTER TABLE sources ADD COLUMN IF NOT EXISTS incarnation UUID;
+ END IF;
+ IF NOT EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'sources'::regclass AND attname = 'incarnation' AND atthasdef) THEN
+ ALTER TABLE sources ALTER COLUMN incarnation SET DEFAULT gen_random_uuid();
+ END IF;
+ IF EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'sources'::regclass AND attname = 'incarnation' AND NOT attnotnull) THEN
+ UPDATE sources SET incarnation = gen_random_uuid() WHERE incarnation IS NULL;
+ ALTER TABLE sources ALTER COLUMN incarnation SET NOT NULL;
+ END IF;
+ END $do$;
CREATE UNIQUE INDEX IF NOT EXISTS sources_incarnation_key ON sources(incarnation);
-ALTER TABLE pages ADD COLUMN IF NOT EXISTS knowledge_revision UUID NOT NULL DEFAULT gen_random_uuid();
+DO $do$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'pages'::regclass AND attname = 'knowledge_revision' AND NOT attisdropped) THEN
+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS knowledge_revision UUID;
+ END IF;
+ IF NOT EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'pages'::regclass AND attname = 'knowledge_revision' AND atthasdef) THEN
+ ALTER TABLE pages ALTER COLUMN knowledge_revision SET DEFAULT gen_random_uuid();
+ END IF;
+ IF EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'pages'::regclass AND attname = 'knowledge_revision' AND NOT attnotnull)
+ AND NOT EXISTS (SELECT 1 FROM pages) THEN
+ ALTER TABLE pages ALTER COLUMN knowledge_revision SET NOT NULL;
+ END IF;
+ END $do$;
ALTER TABLE pages ADD COLUMN IF NOT EXISTS text_projection_revision UUID;
ALTER TABLE page_versions ADD COLUMN IF NOT EXISTS knowledge_revision UUID;
ALTER TABLE page_versions ADD COLUMN IF NOT EXISTS timeline TEXT;
@@ -1710,6 +1732,11 @@ CREATE TABLE IF NOT EXISTS page_write_guards (
);
CREATE OR REPLACE FUNCTION gbrain_advance_page_revision() RETURNS trigger LANGUAGE plpgsql AS $fn$
BEGIN
+ IF OLD.knowledge_revision IS NULL THEN
+ NEW.knowledge_revision := COALESCE(NEW.knowledge_revision, gen_random_uuid());
+ NEW.text_projection_revision := NULL;
+ RETURN NEW;
+ END IF;
IF (NEW.source_id, NEW.slug, NEW.type, NEW.page_kind, NEW.title, NEW.compiled_truth,
NEW.timeline, NEW.frontmatter, NEW.deleted_at)
IS DISTINCT FROM
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 60478f21d8..fb9affb10c 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -289,7 +289,7 @@
"bump_page_generation_clock_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d3359bcd09cccd881585abd9eee81c3dcf4161d935164f7953f2e9fdef73ed3e",
"bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=78059745996cfbb72586a2e0e161635b96a62a5db9d0be5c710f4d437d994431",
"enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e0b3db944d3b4281b9483ce77aa734e0c9aa5b0d46bb5dcb5284b6469441a1b8",
- "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=227a4224dc8cfbe73fec58fdee0c3054a96f3dce748598e5491f50627c7f3513",
+ "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88",
"gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5",
"gbrain_clear_atom_page_state()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=7db0ef05d1220a579e64428b2dd7cf5183191da186fbe64b6496433a7a713d11",
"gbrain_fact_fingerprint(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=666cc212d15431ede62a3d1e8932676a950705717852262f86df6d836d526ab4",
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 9cfdfb9eba..d4b53f4143 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -289,7 +289,7 @@
"bump_page_generation_clock_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d3359bcd09cccd881585abd9eee81c3dcf4161d935164f7953f2e9fdef73ed3e",
"bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=78059745996cfbb72586a2e0e161635b96a62a5db9d0be5c710f4d437d994431",
"enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e0b3db944d3b4281b9483ce77aa734e0c9aa5b0d46bb5dcb5284b6469441a1b8",
- "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=227a4224dc8cfbe73fec58fdee0c3054a96f3dce748598e5491f50627c7f3513",
+ "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88",
"gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5",
"gbrain_clear_atom_page_state()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=7db0ef05d1220a579e64428b2dd7cf5183191da186fbe64b6496433a7a713d11",
"gbrain_fact_fingerprint(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=666cc212d15431ede62a3d1e8932676a950705717852262f86df6d836d526ab4",
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 e290681008..c2c7b5dcaa 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -289,7 +289,7 @@
"bump_page_generation_clock_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d3359bcd09cccd881585abd9eee81c3dcf4161d935164f7953f2e9fdef73ed3e",
"bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=78059745996cfbb72586a2e0e161635b96a62a5db9d0be5c710f4d437d994431",
"enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e0b3db944d3b4281b9483ce77aa734e0c9aa5b0d46bb5dcb5284b6469441a1b8",
- "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=227a4224dc8cfbe73fec58fdee0c3054a96f3dce748598e5491f50627c7f3513",
+ "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88",
"gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5",
"gbrain_clear_atom_page_state()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=7db0ef05d1220a579e64428b2dd7cf5183191da186fbe64b6496433a7a713d11",
"gbrain_fact_fingerprint(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=666cc212d15431ede62a3d1e8932676a950705717852262f86df6d836d526ab4",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
index 1df1435835..1528e86c10 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
@@ -231,7 +231,7 @@
"bump_page_generation_clock_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c40a0a3b86e640b6c8979976173dd93ae92c8c1b9a9e3595cae2af1e265328fe",
"bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c4135ae3f74177aa71313a6c73f22bda7a298bbf12435a8def390212ae11466a",
"enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e0b3db944d3b4281b9483ce77aa734e0c9aa5b0d46bb5dcb5284b6469441a1b8",
- "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=227a4224dc8cfbe73fec58fdee0c3054a96f3dce748598e5491f50627c7f3513",
+ "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88",
"gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47",
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 9ef54603ca..b7dd37a682 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
@@ -231,7 +231,7 @@
"bump_page_generation_clock_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c40a0a3b86e640b6c8979976173dd93ae92c8c1b9a9e3595cae2af1e265328fe",
"bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c4135ae3f74177aa71313a6c73f22bda7a298bbf12435a8def390212ae11466a",
"enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e0b3db944d3b4281b9483ce77aa734e0c9aa5b0d46bb5dcb5284b6469441a1b8",
- "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=227a4224dc8cfbe73fec58fdee0c3054a96f3dce748598e5491f50627c7f3513",
+ "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88",
"gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47",
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 88aa7a6f30..3b010dbae5 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
@@ -231,7 +231,7 @@
"bump_page_generation_clock_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c40a0a3b86e640b6c8979976173dd93ae92c8c1b9a9e3595cae2af1e265328fe",
"bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c4135ae3f74177aa71313a6c73f22bda7a298bbf12435a8def390212ae11466a",
"enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e0b3db944d3b4281b9483ce77aa734e0c9aa5b0d46bb5dcb5284b6469441a1b8",
- "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=227a4224dc8cfbe73fec58fdee0c3054a96f3dce748598e5491f50627c7f3513",
+ "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88",
"gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47",
diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.json
index 8bc1fc8c86..0a41d2d827 100644
--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json
+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json
@@ -240,7 +240,7 @@
"bump_page_generation_clock_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c40a0a3b86e640b6c8979976173dd93ae92c8c1b9a9e3595cae2af1e265328fe",
"bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c4135ae3f74177aa71313a6c73f22bda7a298bbf12435a8def390212ae11466a",
"enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e0b3db944d3b4281b9483ce77aa734e0c9aa5b0d46bb5dcb5284b6469441a1b8",
- "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=227a4224dc8cfbe73fec58fdee0c3054a96f3dce748598e5491f50627c7f3513",
+ "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88",
"gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=f27354966c25d961fcecbffebba0e45747ad3de23575351319f6aee4f9aefd47",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 6456eba8d2..5be7e48d9e 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -295,7 +295,7 @@
"bump_page_generation_clock_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d3359bcd09cccd881585abd9eee81c3dcf4161d935164f7953f2e9fdef73ed3e",
"bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=78059745996cfbb72586a2e0e161635b96a62a5db9d0be5c710f4d437d994431",
"enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e0b3db944d3b4281b9483ce77aa734e0c9aa5b0d46bb5dcb5284b6469441a1b8",
- "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=227a4224dc8cfbe73fec58fdee0c3054a96f3dce748598e5491f50627c7f3513",
+ "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88",
"gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5",
"gbrain_clear_atom_page_state()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=7db0ef05d1220a579e64428b2dd7cf5183191da186fbe64b6496433a7a713d11",
"gbrain_fact_fingerprint(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=666cc212d15431ede62a3d1e8932676a950705717852262f86df6d836d526ab4",
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 c3b6aae34b..5ab9e3162d 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -295,7 +295,7 @@
"bump_page_generation_clock_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d3359bcd09cccd881585abd9eee81c3dcf4161d935164f7953f2e9fdef73ed3e",
"bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=78059745996cfbb72586a2e0e161635b96a62a5db9d0be5c710f4d437d994431",
"enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e0b3db944d3b4281b9483ce77aa734e0c9aa5b0d46bb5dcb5284b6469441a1b8",
- "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=227a4224dc8cfbe73fec58fdee0c3054a96f3dce748598e5491f50627c7f3513",
+ "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88",
"gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5",
"gbrain_clear_atom_page_state()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=7db0ef05d1220a579e64428b2dd7cf5183191da186fbe64b6496433a7a713d11",
"gbrain_fact_fingerprint(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=666cc212d15431ede62a3d1e8932676a950705717852262f86df6d836d526ab4",
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 b2515727af..455b3e9bb5 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -295,7 +295,7 @@
"bump_page_generation_clock_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d3359bcd09cccd881585abd9eee81c3dcf4161d935164f7953f2e9fdef73ed3e",
"bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=78059745996cfbb72586a2e0e161635b96a62a5db9d0be5c710f4d437d994431",
"enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e0b3db944d3b4281b9483ce77aa734e0c9aa5b0d46bb5dcb5284b6469441a1b8",
- "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=227a4224dc8cfbe73fec58fdee0c3054a96f3dce748598e5491f50627c7f3513",
+ "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88",
"gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5",
"gbrain_clear_atom_page_state()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=7db0ef05d1220a579e64428b2dd7cf5183191da186fbe64b6496433a7a713d11",
"gbrain_fact_fingerprint(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=666cc212d15431ede62a3d1e8932676a950705717852262f86df6d836d526ab4",
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 331e21e9d5..a31488293e 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -890,6 +890,12 @@
"name": "facts_health",
"status": "ok"
},
+ {
+ "category": "ops",
+ "message": "Brain-wide maintenance jobs are finishing within their deadline.",
+ "name": "global_maintenance_timeouts",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/page-revision-backfill-5216.test.ts b/test/page-revision-backfill-5216.test.ts
new file mode 100644
index 0000000000..6eaf853b43
--- /dev/null
+++ b/test/page-revision-backfill-5216.test.ts
@@ -0,0 +1,137 @@
+/**
+ * #5216: adding `pages.knowledge_revision` NOT NULL with a volatile default
+ * rewrote the whole pages table during schema replay / migration 150, reading
+ * every TOAST value (a torn one blocked the upgrade). The column is now added
+ * nullable with a separate default, existing rows are backfilled in committed
+ * batches that resume after an interruption, a row still awaiting its revision
+ * is never reported as revision "null", and the final constraints equal a
+ * fresh install.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { PAGE_STATE_SCHEMA_STATEMENTS } from '../src/core/page-state/schema.ts';
+import { REVISION_BACKFILL_STATE_KEY, resumePageRevisionBackfill } from '../src/core/page-state/revision-backfill.ts';
+import { assertPageRevision, REVISION_BACKFILL_PENDING } from '../src/core/page-state/types.ts';
+
+let engine: PGLiteEngine;
+const SLUGS = ['notes/rev-a', 'notes/rev-b', 'notes/rev-c'];
+const quiet = { log: () => {} };
+
+const columnFlags = (e: PGLiteEngine) => e.executeRaw<{ notnull: boolean; hasdef: boolean; def: string | null }>(
+ `SELECT a.attnotnull AS notnull, a.atthasdef AS hasdef, pg_get_expr(d.adbin, d.adrelid) AS def
+ FROM pg_attribute a LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum
+ WHERE a.attrelid = 'pages'::regclass AND a.attname = 'knowledge_revision'`);
+const revisions = async () => Object.fromEntries((await engine.executeRaw<{ slug: string; r: string | null }>(
+ 'SELECT slug, knowledge_revision::text AS r FROM pages ORDER BY id')).map(row => [row.slug, row.r]));
+
+/** Recreate the pre-v150 shape: populated pages without the revision column, then replay the page-state schema. */
+async function preV150ThenReplay(): Promise<{ rewritten: boolean }> {
+ await engine.executeRaw('ALTER TABLE pages DROP COLUMN IF EXISTS knowledge_revision CASCADE');
+ const [before] = await engine.executeRaw<{ f: number }>("SELECT relfilenode AS f FROM pg_class WHERE relname = 'pages'");
+ for (const statement of PAGE_STATE_SCHEMA_STATEMENTS) await engine.executeRaw(statement);
+ const [after] = await engine.executeRaw<{ f: number }>("SELECT relfilenode AS f FROM pg_class WHERE relname = 'pages'");
+ return { rewritten: before!.f !== after!.f };
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+afterAll(async () => { await engine.disconnect(); });
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM pages');
+ await engine.unsetConfig(REVISION_BACKFILL_STATE_KEY);
+ for (const slug of SLUGS) await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `${'body '.repeat(2000)}${slug}` }, { sourceId: 'default' });
+});
+
+describe('page revision rollout (#5216)', () => {
+ test('replaying the page-state schema on a populated pre-v150 table adds the column without a table rewrite', async () => {
+ const { rewritten } = await preV150ThenReplay();
+ expect(rewritten).toBe(false);
+ const [flags] = await columnFlags(engine);
+ expect(flags).toMatchObject({ notnull: false, hasdef: true, def: 'gen_random_uuid()' });
+ expect(Object.values(await revisions())).toEqual([null, null, null]);
+ });
+
+ test('a row awaiting its revision never reports "null"; revision-bound writes get revision_backfill_pending', async () => {
+ await preV150ThenReplay();
+ const snapshot = await engine.readPageSnapshot('notes/rev-a', { sourceId: 'default' });
+ expect(snapshot!.revision).toBe(REVISION_BACKFILL_PENDING);
+ expect(snapshot!.revision).not.toBe('null');
+ expect((await engine.getPage('notes/rev-a', { sourceId: 'default' }))!.knowledge_revision).toBeUndefined();
+ let code: string | undefined;
+ try { assertPageRevision(snapshot, { expectedRevision: '00000000-0000-4000-8000-000000000000' }); } catch (e) { code = (e as { code?: string }).code; }
+ expect(code).toBe('revision_backfill_pending');
+ });
+
+ test('an interrupted backfill resumes without reassigning revisions, keeps a concurrent write, and ends with fresh-install constraints', async () => {
+ await preV150ThenReplay();
+ let killAfter = 1;
+ const dying = new Proxy(engine, { get(target, prop, receiver) {
+ if (prop === 'executeRaw') return (sql: string, params?: unknown[]) => {
+ if (/^SELECT id FROM pages WHERE id > \$1/.test(sql) && killAfter-- <= 0) return Promise.reject(new Error('process killed'));
+ return target.executeRaw(sql, params as never);
+ };
+ return Reflect.get(target, prop, receiver);
+ } }) as PGLiteEngine;
+ await expect(resumePageRevisionBackfill(dying, { batchSize: 1, ...quiet })).rejects.toThrow();
+ const partial = await revisions();
+ expect(partial['notes/rev-a']).toMatch(/^[0-9a-f-]{36}$/);
+ expect(partial['notes/rev-b']).toBeNull();
+
+ await engine.executeRaw("UPDATE pages SET title = 'edited during the pause' WHERE slug = 'notes/rev-c'");
+ const written = (await revisions())['notes/rev-c'];
+ expect(written).toMatch(/^[0-9a-f-]{36}$/);
+
+ const result = await resumePageRevisionBackfill(engine, { batchSize: 1, ...quiet });
+ expect(result.status).toBe('complete');
+ const final = await revisions();
+ expect(final['notes/rev-a']).toBe(partial['notes/rev-a']!);
+ expect(final['notes/rev-c']).toBe(written!);
+ expect(final['notes/rev-b']).toMatch(/^[0-9a-f-]{36}$/);
+
+ const fresh = new PGLiteEngine();
+ await fresh.connect({});
+ await fresh.initSchema();
+ try {
+ expect(await columnFlags(engine)).toEqual(await columnFlags(fresh));
+ expect((await columnFlags(engine))[0]!.notnull).toBe(true);
+ } finally { await fresh.disconnect(); }
+ expect(await engine.executeRaw("SELECT conname FROM pg_constraint WHERE conname = 'pages_knowledge_revision_backfilled'")).toEqual([]);
+ expect(await engine.getConfig(REVISION_BACKFILL_STATE_KEY)).toBeNull();
+ expect((await resumePageRevisionBackfill(engine, quiet)).status).toBe('not_needed');
+ });
+
+ test('a row that keeps failing is isolated and reported, retried a bounded number of times, and the rest completes later', async () => {
+ await preV150ThenReplay();
+ const [{ id: badId }] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE slug = 'notes/rev-b'");
+ let failing = true;
+ const torn = new Proxy(engine, { get(target, prop, receiver) {
+ if (prop === 'executeRaw') return (sql: string, params?: unknown[]) => {
+ const touchesBad = /^UPDATE pages SET knowledge_revision/.test(sql) && JSON.stringify(params).includes(String(badId));
+ if (failing && touchesBad) return Promise.reject(new Error('unexpected chunk number 21 (expected 1) for toast value 141869'));
+ return target.executeRaw(sql, params as never);
+ };
+ return Reflect.get(target, prop, receiver);
+ } }) as PGLiteEngine;
+ const logs: string[] = [];
+ const first = await resumePageRevisionBackfill(torn, { batchSize: 10, log: line => logs.push(line) });
+ expect(first.status).toBe('pending');
+ expect(first.failed.map(f => f.id)).toEqual([Number(badId)]);
+ expect(logs.join('\n')).toContain('gbrain repair orphan-children');
+ const after = await revisions();
+ expect(after['notes/rev-a']).toMatch(/^[0-9a-f-]{36}$/);
+ expect(after['notes/rev-b']).toBeNull();
+ for (let i = 0; i < 4; i++) await resumePageRevisionBackfill(torn, quiet);
+ const capped = await resumePageRevisionBackfill(torn, quiet);
+ expect(capped.failed[0]!.attempts).toBe(3);
+ expect((await columnFlags(engine))[0]!.notnull).toBe(false);
+
+ failing = false;
+ await engine.executeRaw('DELETE FROM pages WHERE id = $1', [badId]);
+ expect((await resumePageRevisionBackfill(engine, quiet)).status).toBe('complete');
+ expect((await columnFlags(engine))[0]!.notnull).toBe(true);
+ });
+});