Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(large-pages): chunk retirement walks occurrences on a v253 index instead of a per-row subquery (PR2 fix lane I)
garrytan26707b5e6bae
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 77b39ff41b..592b82a325 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -656,6 +656,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: 'TBD', text: '`remember` whose entity page (named, or inferred from the fact) is stored in segments over 24 MiB refuses with code `page_body_segmented` (wire error `invalid_params`, not retryable) and a fix that saves the claim without an entity, instead of `unavailable` / `storage_error`, or of silently saving an inferred subject without its entity. A segmented entity up to 24 MiB now links when it is inferred, as it does when named.' },{ since: 'TBD', text: '`get_page` with `body: "full"` (or `include_content`) on a page stored in segments refuses with `page_body_segmented` for local and MCP callers alike (MCP callers got `invalid_params` / `page_too_large_for_inline`; gbrain\'s thin client keeps paging on that one), and every `page_body_segmented` fix now reads the page with `body: "auto"` instead of `body: "none"`. `grammar_diagnostics` on such a page returns `line_grammar: {state: "skipped", reason: "page_body_segmented"}` instead of failing the read, and the `entity` card is built from the page\'s first 64 KiB.' },{ since: 'TBD', text: '`gbrain import` of a Markdown file over 24 MiB from outside its source root now says in the error itself to move the file into the source root and import it there, naming the target path.' },+ { since: 'TBD', text: 'Upgrading builds the index `content_chunks_occurrence_generation_idx` (migration v253): on Postgres online (`CREATE INDEX CONCURRENTLY`; reads and writes go on while it builds), on PGLite as a plain build that holds writes until it ends. It took 0.8 s for 1M chunk rows on Postgres and 0.35 s on a PGLite brain holding a 100 MB page. With it, rebuilding the search projection of a page stored in segments (after a crash, for embedding readiness, by the projection job or `gbrain projections drain`) reads in proportion to the chunk rows it retires and the page\'s segments instead of every chunk row times its newer rows: a 26 MB page half rewritten by a replace read 2.2M buffers to select its stale rows, now 1.8k.' },{ since: 'TBD', text: 'Maintenance on pages stored in segments: `gbrain repair timeline` (and `repair --all`) no longer crashes on one; it repairs inline pages and reports segmented pages carrying timeline rows as `segmented_pages` / `segmented_rows` with their slugs, and doctor `timeline_history` counts them separately without recommending a repair for them. `repair timeline-comments`, `connector-fences`, `split-facts` and `conversation-labels` report the segmented pages they do not handle instead of skipping them silently, and a repair item refused with `page_body_segmented` is listed in `failed[]` while the run goes on. `gbrain integrity check` / `integrity auto` and `gbrain reconcile-links` read a segmented page block by block and give the results its text gives inline; `gbrain reindex --aliases` derives its aliases as its import did; `gbrain quarantine scan` lists it under `skipped` (not re-checked). A page one of these commands cannot read is listed under `skipped` and the run goes on.' },{ since: 'TBD', text: '`delete_page` (soft and `purge: true`), `restore_page`, `gbrain delete` and `gbrain restore` now work on a page over 24 MiB on a source backed by files: the file is compared with the page by digest, streamed, and a file edited on disk still refuses as before. Restoring such a page clears its deletion without re-importing it and writes its file back from the database; the 25 MiB pre-push scan cap on written files still applies, and a core page or an external_untrusted writer still refuses.' },{ since: 'TBD', text: 'A write that stores a page in segments says in its receipt whether search sees it: `searchable: true` when it commits (every new page up to 4 MiB and every rewrite), or `searchable: "pending"` for a larger new page while its chunks are built after commit, with `searchable_retry_after_ms` and a `searchable_fix` that reads the receipt again (`get_write_request`) until it says `searchable: true`. A new page up to 4 MiB was previously searchable only once a post-commit build finished.' },diff --git a/src/core/page-body/ingest.ts b/src/core/page-body/ingest.tsindex 3a97098c50..f3eda2e0f7 100644--- a/src/core/page-body/ingest.ts+++ b/src/core/page-body/ingest.ts@@ -343,14 +343,17 @@ async function stageBody(engine: BrainEngine, input: SegmentedBodyInput, staging/*** The rows of `rows` whose occurrence has no live chunk row at `generation`: new- * occurrences, and kept ones a crashed or deferred projection never chunked.+ * occurrences, and kept ones a crashed or deferred projection never chunked. One+ * index probe per occurrence (content_chunks_occurrence_generation_idx), never a+ * scan of the page's chunk rows.*/export async function occurrencesWithoutChunks(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number, generation: number,rows: readonly ManifestRowInput[]): Promise<ManifestRowInput[]> {if (!rows.length) return [];- const chunked = new Set((await engine.executeRaw<{ occurrence_id: number }>(`SELECT DISTINCT occurrence_id FROM content_chunks- -- chunk-visibility-ok: write path; the generation predicate is explicit, at the generation the caller diffed against- WHERE page_id=$1 AND occurrence_id=ANY($2::bigint[]) AND body_generation<=$3`,+ const chunked = new Set((await engine.executeRaw<{ occurrence_id: number }>(`SELECT o AS occurrence_id FROM unnest($2::bigint[]) AS o+ WHERE EXISTS (SELECT 1 FROM content_chunks c+ -- chunk-visibility-ok: write path; the generation predicate is explicit, at the generation the caller diffed against+ WHERE c.page_id=$1 AND c.occurrence_id=o AND c.body_generation<=$3::bigint)`,[pageId, rows.map(row => row.occurrenceId), generation])).map(row => Number(row.occurrence_id)));return rows.filter(row => !chunked.has(row.occurrenceId));}diff --git a/src/core/page-body/projection.ts b/src/core/page-body/projection.tsindex 6024193e91..a6cc382c8b 100644--- a/src/core/page-body/projection.ts+++ b/src/core/page-body/projection.ts@@ -46,13 +46,27 @@ async function readProjectionPage(engine: Pick<BrainEngine, 'executeRaw'>, ref:return page ?? null;}-/** Chunk rows of page $1 that generation $2 (live occurrences $3) does not hold: other occurrences, inline rows, older duplicates. */-const STALE_CHUNKS_SQL = `SELECT s.id FROM content_chunks s -- chunk-visibility-ok: retirement selects the rows the live generation does not hold- WHERE s.page_id=$1- AND (s.body_generation IS NULL- OR (s.body_generation<=$2 AND NOT (s.occurrence_id=ANY($3::bigint[])))- OR (s.body_generation<=$2 AND EXISTS (SELECT 1 FROM content_chunks n WHERE n.page_id=s.page_id AND n.occurrence_id=s.occurrence_id- AND n.body_generation>s.body_generation AND n.body_generation<=$2)))`;+/**+ * Chunk rows of page $1 that generation $2 (live occurrences $3) does not hold: inline rows, rows of other occurrences,+ * and older duplicates of a live occurrence (any row of it below its newest generation at or below $2). Walks the page's+ * occurrences on content_chunks_occurrence_generation_idx (v253), one index probe per occurrence plus the stale rows it+ * returns, so the work is the page's occurrence count and the rows it retires, never its chunk count times anything: the+ * earlier form tested each row for a newer duplicate with a per-row subquery, which scanned every newer row of the page.+ */+export const STALE_CHUNKS_SQL = `WITH RECURSIVE occ(o) AS (+ SELECT (SELECT c.occurrence_id FROM content_chunks c WHERE c.page_id=$1 AND c.occurrence_id IS NOT NULL ORDER BY c.occurrence_id LIMIT 1)+ UNION ALL+ SELECT (SELECT c.occurrence_id FROM content_chunks c WHERE c.page_id=$1 AND c.occurrence_id>occ.o ORDER BY c.occurrence_id LIMIT 1)+ FROM occ WHERE occ.o IS NOT NULL)+ SELECT s.id FROM occ CROSS JOIN LATERAL (SELECT CASE WHEN occ.o=ANY($3::bigint[])+ THEN (SELECT max(n.body_generation) FROM content_chunks n WHERE n.page_id=$1 AND n.occurrence_id=occ.o AND n.body_generation<=$2::bigint)+ ELSE $2::bigint+1 END AS bound) b+ CROSS JOIN LATERAL (SELECT c.id FROM content_chunks c WHERE c.page_id=$1 AND c.occurrence_id=occ.o AND c.body_generation<b.bound+ UNION ALL SELECT c.id FROM content_chunks c WHERE c.page_id=$1 AND c.occurrence_id=occ.o AND c.body_generation IS NULL) s+ WHERE occ.o IS NOT NULL+ UNION ALL+ SELECT c.id FROM content_chunks c -- chunk-visibility-ok: retirement selects the rows the live generation does not hold+ WHERE c.page_id=$1 AND c.occurrence_id IS NULL AND (c.body_generation IS NULL OR (cardinality($3::bigint[])=0 AND c.body_generation<=$2::bigint))`;/** The page still stores a chunk row its live generation does not hold (a deferred retirement): sealing it would show the row. */export async function hasStaleChunks(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number, generation: number, live: readonly number[]): Promise<boolean> {@@ -72,7 +86,7 @@ async function retireStaleChunks(engine: BrainEngine, ref: { sourceId: string; sawait tx.lockPageKeys([ref]);const [page] = await tx.executeRaw<{ body_generation: number | string; body_storage: string }>('SELECT body_generation, body_storage FROM pages WHERE id=$1', [pageId]);if (page?.body_storage !== 'segmented' || Number(page.body_generation) !== generation) return null;- return (await tx.executeRaw<{ id: number }>(`DELETE FROM content_chunks c WHERE c.id IN (${STALE_CHUNKS_SQL} LIMIT $4) RETURNING c.id`,+ return (await tx.executeRaw<{ id: number }>(`DELETE FROM content_chunks c WHERE c.id=ANY(ARRAY(${STALE_CHUNKS_SQL} LIMIT $4)) RETURNING c.id`,[pageId, generation, live, DEFAULT_FLIP_RETIRE_MAX_ROWS])).length;});if (deleted === null) return { retired, moved: true };diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex f080963903..0137c9489b 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -350,7 +350,8 @@ CREATE TABLE IF NOT EXISTS content_chunks (-- (segmented-page chunks; NULL for inline pages) and-- content_chunks_occurrence_idx are added the same way, and so is v248's-- retired_generation, which nothing writes or reads but released chunk readers- -- still select (v249 keeps it and adds content_chunks_generation_idx).+ -- still select (v249 keeps it and adds content_chunks_generation_idx; v253+ -- adds content_chunks_occurrence_generation_idx for chunk retirement).-- #4246 (v133): md5(chunk_text) at embed time. NULL = no embedding or-- pre-v133 row (grandfathered by invalidateContentDriftEmbeddings).embedded_text_hash TEXT,diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex 283f2ed684..4e9f52b0de 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 252;+export const LATEST_SCHEMA_VERSION = 253;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex d636d11e67..e2feb3f9a7 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -253,6 +253,7 @@ import { v249 } from './v249-segmented-chunk-gc-index.ts';import { v250 } from './v250-page-view-digests.ts';import { v251 } from './v251-segment-reader-marks.ts';import { v252 } from './v252-page-body-staging-texts.ts';+import { v253 } from './v253-chunk-retirement-index.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -504,4 +505,5 @@ export const MIGRATIONS: Migration[] = [v250,v251,v252,+ v253,];diff --git a/src/core/schema-migrations/v253-chunk-retirement-index.ts b/src/core/schema-migrations/v253-chunk-retirement-index.tsnew file mode 100644index 0000000000..ca312158a4--- /dev/null+++ b/src/core/schema-migrations/v253-chunk-retirement-index.ts@@ -0,0 +1,40 @@+import type { Migration } from './types.ts';+import { buildIndexOnline, migrationNotice } from './helpers.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// Segmented page storage (Wave B PR 2) follow-up:+// - content_chunks_occurrence_generation_idx serves the projection's chunk+// retirement (page-body/projection.ts STALE_CHUNKS_SQL: hasStaleChunks and+// each bounded retire batch) and occurrencesWithoutChunks. Retirement walks a+// page's occurrences on it (one probe each), reads each live occurrence's+// newest generation at or below the live one from it, and returns only the+// rows below that generation (or of an occurrence no longer live). The earlier+// statement tested every chunk row of the page with a per-row subquery for a+// newer duplicate, which read every newer row of the page (on+// content_chunks_generation_idx) or every row of the occurrence (on+// content_chunks_occurrence_idx) for each row: 2.2M buffers to select one+// batch on a 26 MB page half rewritten by a replace and 420k to find nothing+// on a 100 MB page, against 1.8k and 3.8k on this index.+// - Not partial: a promotion's deferred inline rows (occurrence_id and+// body_generation NULL) are retired from the same index, as one range at the+// end of the page's entries. Built online (CONCURRENTLY on Postgres; writes+// to content_chunks keep running); an interrupted build leaves an INVALID+// index that the next initSchema drops and rebuilds.+const CONTENT_CHUNKS_OCCURRENCE_GENERATION_INDEX = {+ name: 'content_chunks_occurrence_generation_idx',+ table: 'content_chunks',+ sql: 'CREATE INDEX IF NOT EXISTS content_chunks_occurrence_generation_idx ON content_chunks (page_id, occurrence_id, body_generation)',+};++export const v253: Migration = {+ version: 253,+ name: 'chunk_retirement_index',+ idempotent: true,+ transaction: false,+ sql: '',+ handler: async engine => {+ await buildIndexOnline(engine, 253, CONTENT_CHUNKS_OCCURRENCE_GENERATION_INDEX, { notice: migrationNotice });+ },+};diff --git a/src/schema.sql b/src/schema.sqlindex 1dfa437bf2..8fe0f7825a 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -346,7 +346,8 @@ CREATE TABLE IF NOT EXISTS content_chunks (-- (segmented-page chunks; NULL for inline pages) and-- content_chunks_occurrence_idx are added the same way, and so is v248's-- retired_generation, which nothing writes or reads but released chunk readers- -- still select (v249 keeps it and adds content_chunks_generation_idx).+ -- still select (v249 keeps it and adds content_chunks_generation_idx; v253+ -- adds content_chunks_occurrence_generation_idx for chunk retirement).-- #4246 (v133): md5(chunk_text) at embed time. NULL = no embedding or-- pre-v133 row (grandfathered by invalidateContentDriftEmbeddings).embedded_text_hash TEXT,diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex fa0910c3f2..1d3bec8d15 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -969,6 +969,7 @@"code_traversal_cache_source_idx": "CREATE INDEX code_traversal_cache_source_idx ON public.code_traversal_cache USING btree (source_id)","config_pkey": "CREATE UNIQUE INDEX config_pkey ON public.config USING btree (key)","content_chunks_generation_idx": "CREATE INDEX content_chunks_generation_idx ON public.content_chunks USING btree (page_id, body_generation) WHERE (body_generation IS NOT NULL)",+ "content_chunks_occurrence_generation_idx": "CREATE INDEX content_chunks_occurrence_generation_idx ON public.content_chunks USING btree (page_id, occurrence_id, body_generation)","content_chunks_occurrence_idx": "CREATE INDEX content_chunks_occurrence_idx ON public.content_chunks USING btree (page_id, occurrence_id) WHERE (occurrence_id IS NOT NULL)","content_chunks_pkey": "CREATE UNIQUE INDEX content_chunks_pkey ON public.content_chunks USING btree (id)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex 0f04e2efab..fbfacba5ef 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -969,6 +969,7 @@"code_traversal_cache_source_idx": "CREATE INDEX code_traversal_cache_source_idx ON public.code_traversal_cache USING btree (source_id)","config_pkey": "CREATE UNIQUE INDEX config_pkey ON public.config USING btree (key)","content_chunks_generation_idx": "CREATE INDEX content_chunks_generation_idx ON public.content_chunks USING btree (page_id, body_generation) WHERE (body_generation IS NOT NULL)",+ "content_chunks_occurrence_generation_idx": "CREATE INDEX content_chunks_occurrence_generation_idx ON public.content_chunks USING btree (page_id, occurrence_id, body_generation)","content_chunks_occurrence_idx": "CREATE INDEX content_chunks_occurrence_idx ON public.content_chunks USING btree (page_id, occurrence_id) WHERE (occurrence_id IS NOT NULL)","content_chunks_pkey": "CREATE UNIQUE INDEX content_chunks_pkey ON public.content_chunks USING btree (id)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex e80e78f518..2180e46507 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -969,6 +969,7 @@"code_traversal_cache_source_idx": "CREATE INDEX code_traversal_cache_source_idx ON public.code_traversal_cache USING btree (source_id)","config_pkey": "CREATE UNIQUE INDEX config_pkey ON public.config USING btree (key)","content_chunks_generation_idx": "CREATE INDEX content_chunks_generation_idx ON public.content_chunks USING btree (page_id, body_generation) WHERE (body_generation IS NOT NULL)",+ "content_chunks_occurrence_generation_idx": "CREATE INDEX content_chunks_occurrence_generation_idx ON public.content_chunks USING btree (page_id, occurrence_id, body_generation)","content_chunks_occurrence_idx": "CREATE INDEX content_chunks_occurrence_idx ON public.content_chunks USING btree (page_id, occurrence_id) WHERE (occurrence_id IS NOT NULL)","content_chunks_pkey": "CREATE UNIQUE INDEX content_chunks_pkey ON public.content_chunks USING btree (id)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex 3f165612e4..e3b35bbfcd 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -970,6 +970,7 @@"code_traversal_cache_source_idx": "CREATE INDEX code_traversal_cache_source_idx ON public.code_traversal_cache USING btree (source_id)","config_pkey": "CREATE UNIQUE INDEX config_pkey ON public.config USING btree (key)","content_chunks_generation_idx": "CREATE INDEX content_chunks_generation_idx ON public.content_chunks USING btree (page_id, body_generation) WHERE (body_generation IS NOT NULL)",+ "content_chunks_occurrence_generation_idx": "CREATE INDEX content_chunks_occurrence_generation_idx ON public.content_chunks USING btree (page_id, occurrence_id, body_generation)","content_chunks_occurrence_idx": "CREATE INDEX content_chunks_occurrence_idx ON public.content_chunks USING btree (page_id, occurrence_id) WHERE (occurrence_id IS NOT NULL)","content_chunks_pkey": "CREATE UNIQUE INDEX content_chunks_pkey ON public.content_chunks USING btree (id)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex 6edef6702b..7ed14d30e0 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -970,6 +970,7 @@"code_traversal_cache_source_idx": "CREATE INDEX code_traversal_cache_source_idx ON public.code_traversal_cache USING btree (source_id)","config_pkey": "CREATE UNIQUE INDEX config_pkey ON public.config USING btree (key)","content_chunks_generation_idx": "CREATE INDEX content_chunks_generation_idx ON public.content_chunks USING btree (page_id, body_generation) WHERE (body_generation IS NOT NULL)",+ "content_chunks_occurrence_generation_idx": "CREATE INDEX content_chunks_occurrence_generation_idx ON public.content_chunks USING btree (page_id, occurrence_id, body_generation)","content_chunks_occurrence_idx": "CREATE INDEX content_chunks_occurrence_idx ON public.content_chunks USING btree (page_id, occurrence_id) WHERE (occurrence_id IS NOT NULL)","content_chunks_pkey": "CREATE UNIQUE INDEX content_chunks_pkey ON public.content_chunks USING btree (id)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex 92be14498f..d2dda02fb0 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -970,6 +970,7 @@"code_traversal_cache_source_idx": "CREATE INDEX code_traversal_cache_source_idx ON public.code_traversal_cache USING btree (source_id)","config_pkey": "CREATE UNIQUE INDEX config_pkey ON public.config USING btree (key)","content_chunks_generation_idx": "CREATE INDEX content_chunks_generation_idx ON public.content_chunks USING btree (page_id, body_generation) WHERE (body_generation IS NOT NULL)",+ "content_chunks_occurrence_generation_idx": "CREATE INDEX content_chunks_occurrence_generation_idx ON public.content_chunks USING btree (page_id, occurrence_id, body_generation)","content_chunks_occurrence_idx": "CREATE INDEX content_chunks_occurrence_idx ON public.content_chunks USING btree (page_id, occurrence_id) WHERE (occurrence_id IS NOT NULL)","content_chunks_pkey": "CREATE UNIQUE INDEX content_chunks_pkey ON public.content_chunks USING btree (id)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)",diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex e49e6744f4..7a35d8ebb7 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 247,+ "count": 248,"gaps": [17,18,@@ -12,6 +12,7 @@"BOUNDED_TIMELINE_CHECKPOINT": "385c4da3e28732343148795d6e9a86670813a7a7cfa1e52f8a5bb494680a3c0d","CHECKPOINT": "3c6ff909363c4ba1c9d730e748654ab90aa07549ddf4bf36b8f93c5f4ea3680b","CONTENT_CHUNKS_GENERATION_INDEX": "c434b3a4acdad499cf3b9f170d9f9967b8e3e8218c829db99f3ecba3b53c8b5d",+ "CONTENT_CHUNKS_OCCURRENCE_GENERATION_INDEX": "b4f73db97ad878ef7256128ddef83fd11e2e08fd215e389d9e921a0daf04853d","CONTENT_CHUNKS_OCCURRENCE_INDEX": "7b692ba777b30399ab5a3b100eb40b3b9d1b3fb2322dc4dc808ba8a4d667912c","FACT_PURGES_ALL_SUBJECTS_INDEX": "99e2eb6c24134b539cb4cfd6e5ff66a724463525d09e9ba1fdde3c13f5787b6c","FACT_PURGES_SUBJECT_INDEX": "f4fba07082f2e26da3fa51b0b689f3fe78a3d09afd20c1924dbc2fbe6b1560f1",@@ -59,7 +60,7 @@"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5","verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"},- "latest": 252,+ "latest": 253,"records": [{"handler": {@@ -3871,6 +3872,29 @@"transaction": "absent","verify": "absent","version": 252+ },+ {+ "handler": {+ "form": "arrow",+ "helpers": [+ "CONTENT_CHUNKS_OCCURRENCE_GENERATION_INDEX",+ "buildIndexOnline",+ "dropInvalidConcurrentIndex",+ "migrationNotice",+ "quietMigrationNotices"+ ],+ "sha256": "9e2d0b4acff7a58c986f569e842abbb4272f34dd39721cf557cb223342b2c81d"+ },+ "idempotent": true,+ "name": "chunk_retirement_index",+ "sql": {+ "length": 0,+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+ },+ "sqlFor": "absent",+ "transaction": false,+ "verify": "absent",+ "version": 253}],"versions": [@@ -4120,7 +4144,8 @@249,250,251,- 252+ 252,+ 253]},"normalizer": "migrations-record-v1"diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.jsonindex a622838d6e..6191cf8431 100644--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json@@ -969,6 +969,7 @@"code_traversal_cache_source_idx": "CREATE INDEX code_traversal_cache_source_idx ON public.code_traversal_cache USING btree (source_id)","config_pkey": "CREATE UNIQUE INDEX config_pkey ON public.config USING btree (key)","content_chunks_generation_idx": "CREATE INDEX content_chunks_generation_idx ON public.content_chunks USING btree (page_id, body_generation) WHERE (body_generation IS NOT NULL)",+ "content_chunks_occurrence_generation_idx": "CREATE INDEX content_chunks_occurrence_generation_idx ON public.content_chunks USING btree (page_id, occurrence_id, body_generation)","content_chunks_occurrence_idx": "CREATE INDEX content_chunks_occurrence_idx ON public.content_chunks USING btree (page_id, occurrence_id) WHERE (occurrence_id IS NOT NULL)","content_chunks_pkey": "CREATE UNIQUE INDEX content_chunks_pkey ON public.content_chunks USING btree (id)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)",diff --git a/test/large-pages/chunk-retirement-plan.test.ts b/test/large-pages/chunk-retirement-plan.test.tsnew file mode 100644index 0000000000..f62487287d--- /dev/null+++ b/test/large-pages/chunk-retirement-plan.test.ts@@ -0,0 +1,162 @@+/**+ * Chunk retirement plan cost (Wave B PR 2, lane I): the projection's retirement of stale chunk rows+ * (page-body/projection.ts retireStaleChunks, hasStaleChunks) and its occurrencesWithoutChunks probe.+ *+ * 1. Protects: on an unsealed segmented page whose replace deferred its retirement, every statement the+ * projection rebuild issues against content_chunks examines rows in proportion to the rows it retires plus+ * the page's occurrences, never to its chunk rows times anything; the probe after retirement (nothing stale+ * left) examines a bounded number of rows per occurrence. It still deletes exactly the rows the live+ * generation does not hold: rows of closed occurrences, a promotion's inline rows, older duplicates of a+ * live occurrence, and never a row staged above the live generation.+ * 2. Fails when: the stale-row test is a per-row subquery for a newer duplicate (it read every newer chunk row+ * of the page, or every row of the occurrence, for each row: a 26 MB page half rewritten by a replace read+ * 2.2M buffers in one retire batch), the batch delete hash-joins a scan of the whole content_chunks table,+ * or occurrencesWithoutChunks scans the page's chunk rows.+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set. Work is EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)+ * of each statement as issued (a DELETE inside a savepoint rolled back before the real statement runs):+ * rows produced plus rows removed by filters, times loops, summed over plan nodes. Two page sizes, 4x apart.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { buildSegmentedProjection, hasStaleChunks } from '../../src/core/page-body/projection.ts';+import { flipInput, publishSegmentedPage, segmentText, stageGeneration } from '../helpers/page-body-fixtures.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';++interface PlanNode { 'Actual Rows'?: number; 'Actual Loops'?: number; 'Rows Removed by Filter'?: number;+ 'Rows Removed by Index Recheck'?: number; 'Shared Hit Blocks'?: number; 'Shared Read Blocks'?: number; Plans?: PlanNode[] }+interface StatementWork { sql: string; rows: number; buffers: number }++function rowsExamined(node: PlanNode): number {+ const loops = node['Actual Loops'] ?? 1;+ const own = ((node['Actual Rows'] ?? 0) + (node['Rows Removed by Filter'] ?? 0) + (node['Rows Removed by Index Recheck'] ?? 0)) * loops;+ return own + (node.Plans ?? []).reduce((n, child) => n + rowsExamined(child), 0);+}++/** `engine` with every content_chunks statement it (or a transaction it opens) issues measured first. */+function measured(engine: BrainEngine, log: StatementWork[], inTx = false): BrainEngine {+ const explain = async (exec: BrainEngine, sql: string, params?: unknown[]) => {+ const [row] = await exec.executeRaw<Record<string, unknown>>(`EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${sql}`, params);+ const raw = Object.values(row!)[0];+ const plan = (typeof raw === 'string' ? JSON.parse(raw) : raw) as Array<{ Plan: PlanNode }>;+ log.push({ sql, rows: rowsExamined(plan[0]!.Plan), buffers: (plan[0]!.Plan['Shared Hit Blocks'] ?? 0) + (plan[0]!.Plan['Shared Read Blocks'] ?? 0) });+ };+ return new Proxy(engine, {+ get(target, prop) {+ if (prop === 'executeRaw') {+ return async (sql: string, params?: unknown[]) => {+ if (/content_chunks/.test(sql)) {+ if (!/^\s*DELETE/i.test(sql)) await explain(target, sql, params);+ else if (inTx) {+ await target.executeRaw('SAVEPOINT plan_probe');+ await explain(target, sql, params);+ await target.executeRaw('ROLLBACK TO SAVEPOINT plan_probe');+ } else throw new Error(`unmeasured DELETE outside a transaction: ${sql.slice(0, 80)}`);+ }+ return target.executeRaw(sql, params);+ };+ }+ if (prop === 'transaction') return (fn: (tx: BrainEngine) => Promise<unknown>) => target.transaction(tx => fn(measured(tx, log, true)));+ const value = Reflect.get(target, prop, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+}++interface ChunkRow { id: number; occurrence_id: number | null; body_generation: number | null }++/** The rows the live generation does not hold, by the retirement's definition (projection.ts STALE_CHUNKS_SQL). */+function expectedStale(rows: readonly ChunkRow[], generation: number, live: ReadonlySet<number>): number[] {+ const latest = new Map<number, number>();+ for (const r of rows) {+ if (r.occurrence_id === null || r.body_generation === null || r.body_generation > generation) continue;+ latest.set(r.occurrence_id, Math.max(latest.get(r.occurrence_id) ?? -Infinity, r.body_generation));+ }+ return rows.filter(r => r.body_generation === null || (r.occurrence_id !== null && r.body_generation <= generation+ && (!live.has(r.occurrence_id) || r.body_generation < latest.get(r.occurrence_id)!))).map(r => r.id).sort((a, b) => a - b);+}++/**+ * A segmented page at generation 2 left unsealed by a replace that deferred its retirement: `half` occurrences kept+ * from generation 1, `half` closed and replaced by new ones, `perOccurrence` chunk rows each. Plus one kept+ * occurrence with a newer duplicate row set at generation 2 (a projection that raced a flip), inline rows a+ * promotion deferred, and rows a pending staging holds at generation 3 for a closed occurrence.+ */+async function deferredPage(engine: BrainEngine, slug: string, half: number, perOccurrence: number) {+ const v1 = Array.from({ length: 2 * half }, (_, i) => segmentText(`## Part ${i}\n\nFirst body of ${slug}, part ${i}.\n`));+ const page = await publishSegmentedPage(engine, slug, v1);+ const kept = page.occurrences.slice(0, half), closed = page.occurrences.slice(half);+ const v2 = Array.from({ length: half }, (_, i) => segmentText(`## Part ${half + i}\n\nSecond body of ${slug}, part ${i}.\n`));+ const staged = await stageGeneration(engine, { pageId: page.pageId, slug, genFrom: 2, texts: v2 });+ await engine.executeRaw('UPDATE page_body_manifest SET seq = seq + $2 WHERE staging_id = $1::uuid', [staged.stagingId, half]);+ let next = 0;+ const insert = async (occurrences: readonly (number | null)[], generation: number | null) => {+ await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, occurrence_id, local_ordinal, raw_byte_start, raw_byte_end, body_generation)+ SELECT $1, $2 + g, 'retirement probe chunk ' || g, 'compiled_truth', ($3::bigint[])[1 + g / $4], g % $4, 0, 10, $5::bigint+ FROM generate_series(0, $6::int - 1) AS g`, [page.pageId, next, occurrences, perOccurrence, generation, occurrences.length * perOccurrence]);+ next += occurrences.length * perOccurrence;+ };+ await insert([null], null);+ await insert(page.occurrences, 1);+ await insert(staged.occurrences, 2);+ await insert([kept[0]!], 2);+ await insert([closed[0]!], 3);+ const flip = await engine.transaction(async tx => {+ const result = await tx.flipBodyGeneration(flipInput(page.pageId, 1, staged.stagingId, [...v1.slice(0, half), ...v2],+ { closeOccurrences: closed, retireChunkOccurrences: closed, retireMaxRows: 1 }));+ await tx.setBodyStagingState(staged.stagingId, 'committed');+ return result;+ });+ expect(flip.retireDeferred).toBe(true);+ await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE id=$1', [page.pageId]);+ return { pageId: page.pageId, occurrences: 3 * half, live: [...kept, ...staged.occurrences] };+}++const SIZES = [{ half: 6, perOccurrence: 30 }, { half: 24, perOccurrence: 30 }] as const;+/** Rows (or buffers) a statement may examine per row it retires or per occurrence of the page. */+const ROWS_PER_UNIT = 12;+/** Rows occurrencesWithoutChunks may examine per occurrence: one index probe each. */+const PROBE_ROWS_PER_OCCURRENCE = 4;++for (const kind of testBackends()) describe(`chunk retirement plan cost (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); close = () => engine.disconnect(); }+ }, 120_000);+ afterAll(async () => { await close?.(); });++ test('a deferred retirement deletes exactly the stale rows, in work bounded by those rows and the page\'s occurrences, at two sizes', async () => {+ const perUnit: number[] = [];+ for (const [i, size] of SIZES.entries()) {+ const slug = `notes/retire-plan-${kind}-${i}`;+ const page = await deferredPage(engine, slug, size.half, size.perOccurrence);+ const before = (await engine.executeRaw<ChunkRow>('SELECT id, occurrence_id::int AS occurrence_id, body_generation::int AS body_generation FROM content_chunks WHERE page_id=$1',+ [page.pageId])).map(r => ({ id: Number(r.id), occurrence_id: r.occurrence_id === null ? null : Number(r.occurrence_id), body_generation: r.body_generation === null ? null : Number(r.body_generation) }));+ const stale = expectedStale(before, 2, new Set(page.live));+ expect(stale.length).toBe(size.perOccurrence * (2 + size.half));+ await engine.executeRaw('ANALYZE content_chunks');++ const log: StatementWork[] = [];+ const built = await buildSegmentedProjection(measured(engine, log), { sourceId: 'default', slug });+ expect(built).toEqual({ chunks: 0, retired: stale.length, sealed: true });+ const after = new Set((await engine.executeRaw<{ id: number }>('SELECT id FROM content_chunks WHERE page_id=$1', [page.pageId])).map(r => Number(r.id)));+ expect(before.filter(r => !after.has(r.id)).map(r => r.id).sort((a, b) => a - b)).toEqual(stale);+ const retire = log.filter(statement => /^\s*DELETE/i.test(statement.sql));+ const probes = log.filter(statement => !/^\s*DELETE/i.test(statement.sql));+ expect([retire.length, probes.length]).toEqual([1, 1]);+ expect(retire[0]!.rows).toBeLessThanOrEqual(ROWS_PER_UNIT * (stale.length + page.occurrences));+ expect(probes[0]!.rows).toBeLessThanOrEqual(PROBE_ROWS_PER_OCCURRENCE * page.occurrences);+ for (const statement of log) expect(statement.buffers).toBeLessThanOrEqual(ROWS_PER_UNIT * (stale.length + page.occurrences));++ const probe: StatementWork[] = [];+ expect(await hasStaleChunks(measured(engine, probe), page.pageId, 2, page.live)).toBe(false);+ expect(probe.length).toBe(1);+ expect(probe[0]!.rows).toBeLessThanOrEqual(ROWS_PER_UNIT * page.occurrences);+ perUnit.push(Math.max(retire[0]!.rows / (stale.length + page.occurrences), probe[0]!.rows / page.occurrences));+ }+ expect(perUnit[1]!).toBeLessThanOrEqual(perUnit[0]! * 1.5);+ }, 300_000);+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex c988f9609f..e8cdef16b5 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -63,6 +63,7 @@ test/import-inline-chunk-keep.test.tstest/import-revision-concurrency.test.tstest/keyword-statement-timeout-knob-6495.test.tstest/lane-apply-pipelining.test.ts+test/large-pages/chunk-retirement-plan.test.tstest/large-pages/chunk-visibility.test.tstest/large-pages/contextual-reembed-segmented.test.tstest/large-pages/credential-reseal-segments.test.ts