Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
segmented publication: drop stale staged chunks through a key only one index carries (v258), so the DELETE reads the generation whatever the statistics
garrytanf3a291083aac
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 59d4aee5df..65df7afa4b 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -893,6 +893,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: 'TBD', text: 'With `pages.segmented_storage` on, a withdrawal (`forget`, `forget_fact`, `purge_fact`) now rewrites the canonical file of a page stored in segments on a source backed by files, as it rewrites an inline page\'s: the file loses the withdrawn or purged row, its bytes are those `gbrain export` writes for the page, and the withdrawal\'s Git effect commits it. The file is streamed from the segments into its staging file one segment at a time, and its recovery record names that staging file by path and SHA-256 instead of holding the file; the file\'s prior bytes are read in pieces too. A streamed staging file (this mirror\'s, or `restore_page`\'s for a page over 24 MiB) is written under an in-progress name and renamed once complete, so one a crash cut short is discarded and written again instead of blocking the source\'s worktree with `unexpected_staging_bytes`. Before, the withdrawal-mirror and Git effects passed such a page by (`skipped` reason `page_body_segmented`) and its file kept the withdrawn text. The content gate\'s markers (`embed_skip`, `content_flag`, `quarantine`), which the database stores and the file does not, are now set aside when a page stored in segments is compared with its file, as they are for an inline page; before, any rewrite of a marked page\'s file (a withdrawal, delete, restore or tag change) was skipped or refused as `file_database_drift`.' },{ since: 'TBD', text: 'A managed write whose statements the database ends with a statement timeout or cancel (SQLSTATE 57014, at preparation or inside its publication transaction) now counts each such interruption against `persistence.max_preparation_attempts` (default 2), together with preparations cut off at their deadline, and at the limit ends `failed` with `write_interrupted` (the receipt names the attempts, the limit and the SQLSTATE; a worktree-backed write restores its file first) instead of being released as `database_contention` and prepared again without limit. A single interruption still re-prepares and commits; a lock timeout, serialization failure or deadlock (contention with other writers), a dropped connection or a restarting database is never counted. A foreground write needs a new `request_id`; a managed sync re-freezes the file in place, and a run that stops on it is resumable (`gbrain sync status` shows class `connection`, safe action `retry`, no person needed; a rerun on the same entry ending it again names the read-only `gbrain sources writer status`). `persistence.preparation_deadlines false` turns the counting off with the deadlines.' },{ since: 'TBD', text: 'Upgrading builds the index `ingest_log_marked_idx` (migration v257): 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.4 s for 1M `ingest_log` rows on Postgres and 0.5 s on PGLite. The segmented storage writer hold now judges every recent import, sync or connector run and resident process by its version, including those of a gbrain that already records reading segmented pages (v0.60.290.0), and the index keeps that read to the last 7 days of the log: 600 buffers on a 1M-row log, where a scan reads the whole table.' },+ { since: 'TBD', text: 'Upgrading builds the index `content_chunks_staged_generation_idx` (migration v258) on the segmented chunk rows: 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. Built on a 1M-row two-column stand-in table it took 0.3 s on Postgres and 0.5 s on PGLite. A segmented write\'s publication now drops a dead preparation\'s chunk rows through it, so the statement reads only the new generation\'s rows on a page created after the table\'s last ANALYZE, where it walked every chunk row of the page (2.4k rows for an 8 MiB page, against about 100).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/persistence/segmented-apply.ts b/src/core/persistence/segmented-apply.tsindex 0a878f88b7..598b283757 100644--- a/src/core/persistence/segmented-apply.ts+++ b/src/core/persistence/segmented-apply.ts@@ -172,7 +172,9 @@ export async function applySegmentedBody(tx: BrainEngine, input: SegmentedApplyIconst flip = await tx.flipBodyGeneration({ pageId, expectedGeneration: prepared.expectedGeneration, newGeneration: prepared.newGeneration,stagingId: prepared.stagingId, closeOccurrences: prepared.closeOccurrences, retireChunkOccurrences: prepared.retireChunkOccurrences,retireInlineChunks: input.promotion, retireMaxRows: input.retireMaxRows, body: prepared.body, meta: input.meta });- if (!prepared.createRows) await tx.executeRaw('DELETE FROM content_chunks WHERE page_id=$1 AND body_generation=$2 AND NOT (chunk_index = ANY($3::int[]))',+ // The cast addresses content_chunks_staged_generation_idx (v258) alone: on a page newer than the table's statistics a plain+ // page_id lookup ties every page_id index at one row and walks the page's chunks on the smallest.+ if (!prepared.createRows) await tx.executeRaw('DELETE FROM content_chunks WHERE page_id::bigint=$1 AND body_generation=$2 AND NOT (chunk_index = ANY($3::int[]))',[pageId, prepared.newGeneration, prepared.stagedChunkIndexes]);const createChunks = prepared.createChunks?.slug === input.slug ? prepared.createChunks.chunks : null;if (createChunks?.length) await tx.stageSegmentChunks(pageId, prepared.newGeneration, createChunks);diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex d769ca9622..eccb95f764 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 = 257;+export const LATEST_SCHEMA_VERSION = 258;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 84adda2632..2e8f3ca51b 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -258,6 +258,7 @@ import { v254 } from './v254-segment-reader-marks.ts';import { v255 } from './v255-page-body-staging-texts.ts';import { v256 } from './v256-chunk-retirement-index.ts';import { v257 } from './v257-ingest-log-marked-index.ts';+import { v258 } from './v258-staged-generation-chunk-index.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -514,4 +515,5 @@ export const MIGRATIONS: Migration[] = [v255,v256,v257,+ v258,];diff --git a/src/core/schema-migrations/v258-staged-generation-chunk-index.ts b/src/core/schema-migrations/v258-staged-generation-chunk-index.tsnew file mode 100644index 0000000000..9a16c6258b--- /dev/null+++ b/src/core/schema-migrations/v258-staged-generation-chunk-index.ts@@ -0,0 +1,35 @@+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.+//+// Large pages flip lane C: a segmented write's publication drops the chunk rows+// a dead preparation staged under its new generation (persistence/segmented-apply.ts,+// `page_id::bigint = $1 AND body_generation = $2`). Every other content_chunks+// index leads with page_id, so for a page created after the table's last ANALYZE+// (its page_id is in no statistic) the planner estimates one row on each of them+// and picks the smallest, idx_chunks_page, walking every chunk row of the page+// inside the publication transaction: 2.4k rows for an 8 MiB page, against the+// ~100 the generation holds. The statement names the page through a cast that only+// this index carries, so it is the one index that can answer it whatever the+// statistics; a plain `page_id =` lookup never uses it. Partial like+// content_chunks_generation_idx (inline chunks have no generation). Built online+// (CONCURRENTLY on Postgres); an interrupted build leaves an INVALID index that+// the next initSchema drops and rebuilds.+export const CONTENT_CHUNKS_STAGED_GENERATION_INDEX = {+ name: 'content_chunks_staged_generation_idx',+ table: 'content_chunks',+ sql: 'CREATE INDEX IF NOT EXISTS content_chunks_staged_generation_idx ON content_chunks ((page_id::bigint), body_generation) WHERE body_generation IS NOT NULL',+};++export const v258: Migration = {+ version: 258,+ name: 'staged_generation_chunk_index',+ idempotent: true,+ transaction: false,+ sql: '',+ handler: async engine => {+ await buildIndexOnline(engine, 257, CONTENT_CHUNKS_STAGED_GENERATION_INDEX, { notice: migrationNotice });+ },+};diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex 042f4cfd3f..de07232582 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -1018,6 +1018,7 @@"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_staged_generation_idx": "CREATE INDEX content_chunks_staged_generation_idx ON public.content_chunks USING btree (((page_id)::bigint), body_generation) WHERE (body_generation IS NOT NULL)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)","context_volunteer_events_pkey": "CREATE UNIQUE INDEX context_volunteer_events_pkey ON public.context_volunteer_events USING btree (id)","context_volunteer_events_src_slug_idx": "CREATE INDEX context_volunteer_events_src_slug_idx ON public.context_volunteer_events USING btree (source_id, slug)",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex bff844dbbd..181651733b 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -1018,6 +1018,7 @@"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_staged_generation_idx": "CREATE INDEX content_chunks_staged_generation_idx ON public.content_chunks USING btree (((page_id)::bigint), body_generation) WHERE (body_generation IS NOT NULL)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)","context_volunteer_events_pkey": "CREATE UNIQUE INDEX context_volunteer_events_pkey ON public.context_volunteer_events USING btree (id)","context_volunteer_events_src_slug_idx": "CREATE INDEX context_volunteer_events_src_slug_idx ON public.context_volunteer_events USING btree (source_id, slug)",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex f6b70b56d0..381f39ce6a 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -1018,6 +1018,7 @@"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_staged_generation_idx": "CREATE INDEX content_chunks_staged_generation_idx ON public.content_chunks USING btree (((page_id)::bigint), body_generation) WHERE (body_generation IS NOT NULL)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)","context_volunteer_events_pkey": "CREATE UNIQUE INDEX context_volunteer_events_pkey ON public.context_volunteer_events USING btree (id)","context_volunteer_events_src_slug_idx": "CREATE INDEX context_volunteer_events_src_slug_idx ON public.context_volunteer_events USING btree (source_id, slug)",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex e8391545b0..5090062935 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -1019,6 +1019,7 @@"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_staged_generation_idx": "CREATE INDEX content_chunks_staged_generation_idx ON public.content_chunks USING btree (((page_id)::bigint), body_generation) WHERE (body_generation IS NOT NULL)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)","context_volunteer_events_pkey": "CREATE UNIQUE INDEX context_volunteer_events_pkey ON public.context_volunteer_events USING btree (id)","context_volunteer_events_src_slug_idx": "CREATE INDEX context_volunteer_events_src_slug_idx ON public.context_volunteer_events USING btree (source_id, slug)",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex 3a54feede2..d262264bc6 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -1019,6 +1019,7 @@"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_staged_generation_idx": "CREATE INDEX content_chunks_staged_generation_idx ON public.content_chunks USING btree (((page_id)::bigint), body_generation) WHERE (body_generation IS NOT NULL)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)","context_volunteer_events_pkey": "CREATE UNIQUE INDEX context_volunteer_events_pkey ON public.context_volunteer_events USING btree (id)","context_volunteer_events_src_slug_idx": "CREATE INDEX context_volunteer_events_src_slug_idx ON public.context_volunteer_events USING btree (source_id, slug)",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex 867d8b12e2..ecd0511c45 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -1019,6 +1019,7 @@"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_staged_generation_idx": "CREATE INDEX content_chunks_staged_generation_idx ON public.content_chunks USING btree (((page_id)::bigint), body_generation) WHERE (body_generation IS NOT NULL)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)","context_volunteer_events_pkey": "CREATE UNIQUE INDEX context_volunteer_events_pkey ON public.context_volunteer_events USING btree (id)","context_volunteer_events_src_slug_idx": "CREATE INDEX context_volunteer_events_src_slug_idx ON public.context_volunteer_events USING btree (source_id, slug)",diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 333d2bbf20..f44e8e6068 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 252,+ "count": 253,"gaps": [17,18,@@ -15,6 +15,7 @@"CONTENT_CHUNKS_GENERATION_INDEX": "c434b3a4acdad499cf3b9f170d9f9967b8e3e8218c829db99f3ecba3b53c8b5d","CONTENT_CHUNKS_OCCURRENCE_GENERATION_INDEX": "b4f73db97ad878ef7256128ddef83fd11e2e08fd215e389d9e921a0daf04853d","CONTENT_CHUNKS_OCCURRENCE_INDEX": "7b692ba777b30399ab5a3b100eb40b3b9d1b3fb2322dc4dc808ba8a4d667912c",+ "CONTENT_CHUNKS_STAGED_GENERATION_INDEX": "a61c21ed8503803ce1a4a86401731ff121b5da51c763149bdb742b40a3da99ec","FACT_PURGES_ALL_SUBJECTS_INDEX": "99e2eb6c24134b539cb4cfd6e5ff66a724463525d09e9ba1fdde3c13f5787b6c","FACT_PURGES_SUBJECT_INDEX": "f4fba07082f2e26da3fa51b0b689f3fe78a3d09afd20c1924dbc2fbe6b1560f1","FACT_RELINK_TABLE_SQL": "1fdde4b99d0077365274096f294be64a992961c7b4544af794224de238b03630",@@ -66,7 +67,7 @@"tableRows": "906d2413b13d76a06d5910885e47ed5c544be4ff3a2266e83146715721b24270","verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"},- "latest": 257,+ "latest": 258,"records": [{"handler": {@@ -4031,6 +4032,32 @@"transaction": false,"verify": "absent","version": 257+ },+ {+ "handler": {+ "form": "arrow",+ "helpers": [+ "CONTENT_CHUNKS_STAGED_GENERATION_INDEX",+ "PLANNER_REPAIR_TABLES",+ "analyzeAfterIndexBuild",+ "buildIndexOnline",+ "dropInvalidConcurrentIndex",+ "migrationNotice",+ "quietMigrationNotices",+ "tableRows"+ ],+ "sha256": "c9670cf7e236d49616742c52be992a319557f974dcd30f1e7b4bbe0e45537bec"+ },+ "idempotent": true,+ "name": "staged_generation_chunk_index",+ "sql": {+ "length": 0,+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+ },+ "sqlFor": "absent",+ "transaction": false,+ "verify": "absent",+ "version": 258}],"versions": [@@ -4285,7 +4312,8 @@254,255,256,- 257+ 257,+ 258]},"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 2fcf71b041..24c56c777f 100644--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json@@ -1018,6 +1018,7 @@"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_staged_generation_idx": "CREATE INDEX content_chunks_staged_generation_idx ON public.content_chunks USING btree (((page_id)::bigint), body_generation) WHERE (body_generation IS NOT NULL)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)","context_volunteer_events_pkey": "CREATE UNIQUE INDEX context_volunteer_events_pkey ON public.context_volunteer_events USING btree (id)","context_volunteer_events_src_slug_idx": "CREATE INDEX context_volunteer_events_src_slug_idx ON public.context_volunteer_events USING btree (source_id, slug)",diff --git a/test/large-pages/publication-seal-bounded.test.ts b/test/large-pages/publication-seal-bounded.test.tsindex 15b8ef3748..1c1879c1e4 100644--- a/test/large-pages/publication-seal-bounded.test.ts+++ b/test/large-pages/publication-seal-bounded.test.ts@@ -5,17 +5,20 @@* chunk row stored) without reading the page: the stale-row probe (projection.ts STALE_CHUNKS_SQL, one index walk* over every occurrence of the page plus every row of each live one) and the live manifest read run in preparation,* and the publication transaction only reads what the write staged. A small edit near the end of a 2 MiB and an- * 8 MiB page still seals in its publication, and its new text is a keyword hit at once.+ * 8 MiB page still seals in its publication, and its new text is a keyword hit at once, whatever the planner statistics:+ * taken before the page existed (its page_id in no statistic) or taken after its first write.* 2. Fails when: the probe runs inside the publication transaction, where its cost grows with the page and* declareDurablePersistence's 5 s statement_timeout can end it on a loaded host (57014), so the whole write is* prepared again; or when the publication stops sealing (the post-commit projection is lost here, so only the- * publication can seal).+ * publication can seal); or when a statement's plan follows the statistics onto an index that walks the page (the+ * stale-row DELETE on idx_chunks_page when the page is newer than the last ANALYZE).* 3. Existing coverage: second-write-deferred-retire.test.ts keeps a page whose earlier write deferred its retirement* unsealed; chunk-retirement-plan.test.ts bounds the probe itself.* 4. Work is EXPLAIN (ANALYZE, FORMAT JSON) of each content_chunks / page_body_manifest statement the publication* transaction issues (inside a savepoint rolled back before the real statement runs): rows produced plus rows* removed by filters, times loops, summed over plan nodes. Counts, never time. Runs on PGLite, and on Postgres- * when DATABASE_URL is set.+ * when DATABASE_URL is set. Statistics are set by an explicit ANALYZE, with PGLite's row-delta ANALYZE and Postgres+ * autovacuum off for the table, so each state is the one the test names.*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';@@ -35,7 +38,7 @@ import { testBackends } from '../helpers/test-backends.ts';import { withEnv } from '../helpers/with-env.ts';const home = mkdtempSync(join(tmpdir(), 'gbrain-publication-seal-'));-const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined, GBRAIN_PLANNER_AUTO_ANALYZE: '0' };afterAll(() => { rmSync(home, { recursive: true, force: true }); });const PROJECTION_PAGE_READ = "FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL AND body_storage='segmented'";@@ -98,21 +101,25 @@ for (const kind of testBackends()) describe(`a segmented write's publication reaelse { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); close = () => engine.disconnect(); }await registerLocalWriter(engine, 'cli');await engine.setConfig('pages.segmented_storage', 'on');+ if (kind === 'postgres') await engine.executeRaw('ALTER TABLE content_chunks SET (autovacuum_enabled = false)');}), 120_000);afterAll(async () => withEnv(env, async () => { await disposePersistenceConsumer(engine); await close?.(); }));const found = async (slug: string, word: string) => (await engine.searchKeyword(word, { limit: 10 })).filter(r => r.slug === slug).length;- for (const mib of [2, 8]) test(`an edit near the end of a ${mib} MiB page seals in its publication, reading only what it staged`, async () => withEnv(env, async () => {+ for (const mib of [2, 8]) for (const stats of ['taken after its first write', 'taken before the page'] as const) test(`an edit near the end of a ${mib} MiB page seals in its publication, reading only what it staged (statistics ${stats})`, async () => withEnv(env, async () => {+ const before = stats === 'taken before the page';const v0 = conversationPage(mib * 1024 * 1024, { seed: 61, needles: [{ at: 0.95, word: 'tailmarkerquokka' }] });- const file = join(home, `page-${mib}.md`);- const slug = `notes/publication-seal-${mib}`;+ const file = join(home, `page-${mib}-${before ? 'before' : 'after'}.md`);+ const slug = `notes/publication-seal-${mib}-${before ? 'before' : 'after'}`;const write = async (on: BrainEngine) => expect(await importFromFile(on, file, `${slug}.md`, { noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) })).toMatchObject({ status: 'imported' });+ if (before) await engine.executeRaw('ANALYZE content_chunks');writeFileSync(file, v0);await write(engine);- const before = await segmentedPageRow(engine, slug);- expect(before.text_projection_revision).toBe(before.knowledge_revision);+ if (!before) await engine.executeRaw('ANALYZE content_chunks');+ const first = await segmentedPageRow(engine, slug);+ expect(first.text_projection_revision).toBe(first.knowledge_revision);writeFileSync(file, v0.replace('tailmarkerquokka', 'tailmarkerwalrus'));const publication: StatementWork[] = [];