Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(#7172): keep moved passages, bound a publication's chunk row writes, stop re-embedding pages with a stale signature

garrytanb67239c89148
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5de143dbc7..80163e0254 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,34 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**A timeline entry no longer rewrites the passages it didn't change, and a big passage replacement can't time out the write that carries it (#7172).** A managed write replaced its page's passages inside its publication, under the publication's 5 s statement bound. A passage whose index moved (a long entry near the top of a descending timeline adds a passage above the others) was deleted and inserted again with its vector, and on a large index each inserted row can cost about half a second, so the write ended `write_interrupted` (SQLSTATE 57014) on every attempt. Separately, a page whose stored embedding signature was missing or in an older format had every passage re-embedded after each write, which looked the same from outside: every passage got a new embedding time.
+
+### What changed
+
+| Situation | Before | Now |
+|---|---|---|
+| An entry shifts unchanged passages to new indexes | each moved passage deleted and re-inserted (vector copied) | the row keeps its id and vector and changes index in place |
+| A write whose passages need more than 5 inserted or renumbered rows | all of them in one statement inside the publication; on a slow index, 57014 on every attempt, then `write_interrupted` | the page commits first; its passages finish in post-commit transactions of at most 5 row writes each, then the projection is sealed |
+| Search during those steps | n/a | the page's passages are hidden until the seal (as for any pending projection); the receipt says `searchable: "pending"` and turns `true` when sealed |
+| The embedding step after a write, page signature missing or older format | every passage re-embedded (paid) | passages whose recorded embedding input is current keep their vectors; the page signature is restamped |
+
+The 5-row bound is derived in `src/core/page-state/chunk-moves.ts` (`CHUNK_ROW_WRITE_BUDGET`): each inserted row version adds an entry to every index of `content_chunks` (the search-vector GIN, the HNSW index when it carries a vector, the b-trees), the slowest reported rate on a large index is about 0.5 s per row, and half of the 5 s statement bound is left for the rest of the write. No timeout, retry or deadline is raised, and nothing is configurable.
+
+### What to watch for after you upgrade
+
+- A write that was blocked by repeated `write_interrupted` (57014) on a large page can be submitted again; it commits and finishes its passages right after.
+- If a page's receipt stays `searchable: "pending"` for more than a minute, no process is finishing it: run `gbrain projections drain`.
+- When a top entry changes the text of every passage below it (the chunker packs about 300 words with a 50-word overlap, so a short entry can shift every boundary), those passages are new text and are embedded again; this release does not change the chunker.
+
+### Itemized changes
+
+- `reuseStoredChunkVectors` matches a stored row by source and text at any index (its own index first), so a kept row can move.
+- New `src/core/page-state/chunk-moves.ts`: the row-write bound and the move planner (one UPDATE per wave; a cycle parks one row at a negative index).
+- `continueDeferredProjection` runs the bounded steps after commit; the projection drain resumes a page whose steps were interrupted (queue reason `chunk_replacement_deferred`).
+- `readEmbeddingEffectProjection` accepts a vector whose recorded input hash is one the current page accepts, whatever the page-level signature says, and restamps the page.
+
## [0.60.328.0] - 2026-10-20
**A Google API that's disabled in your OAuth project is now reported as itself, all at once, instead of looking like a different account.** When Gmail, Calendar or People was disabled (or a scope wasn't granted), a managed Google source could not read the account, so the sync failed or refused with `connector_account_changed`, and setup only found out one API at a time. The account now resolves through Google's sign-in identity, the services that work keep syncing, and setup, `gbrain google status` and doctor name every disabled API with its project and enable link in one report.
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index 0cbd6801a1..808840fe3d 100644
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@ -7,6 +7,7 @@ The page-state concurrency foundation under `src/core/page-state/` and the share
- `src/core/page-state/` — Canonical page concurrency foundation shared by both engines. `schema.ts` (migration 150) adds source incarnation UUIDs, logical page revisions, text-projection revisions, and persistent guards for absent pages. `guards.ts` locks sorted sources then page identities in an existing transaction; a transaction or savepoint never re-acquires a key it holds, which covers absent pages because the only pages INSERT runs after `putPage` takes the same guard (`test/e2e/page-guards-postgres.test.ts`); callers lock sources before authority/request/fact rows. `snapshot.ts` computes the normalized body/timeline fingerprints only for a page with fact withdrawals, page-subject purges or a source '*' purge marker (they feed only the withdrawal overlay), as `page-snapshot-batch.ts` does. `snapshot.ts` reads page/tags/withdrawals in one MVCC statement and applies withdrawals using database-normalized text. `transactions.ts` makes helper transaction APIs compose through savepoints. `versions.ts` records the complete canonical snapshot; `rename-alias.ts` records `slug_aliases(old -> new)` inside both engines' `updateSlug` transaction, repoints aliases that named the old slug and drops one spelled like the new slug; `moveSlugBindings` moves the page's facts (`entity_slug`, `source_markdown_slug`) and `page_aliases` in the same transaction, letting a purged page's leftovers at the new slug yield (`test/rename-slug-alias.test.ts`); `movePageIdReferences` (#5431) moves the page-id-keyed rows of a stale rename row onto the surviving row (`links` from/to/origin, `timeline_entries` page and event, `page_versions`), dropping stale-side duplicates on the `links` composite key and the timeline dedup indexes (`test/rename-slug-alias.test.ts`); `materialize.ts` persists only verified canonical overlay bytes without another logical revision. `types.ts` defines revision preconditions: no revision is create-only (an existing page refuses `revision_required`, #5385, its own code since the omission is the caller's and not a race), a stale revision or a page another writer created where an internal writer asserted none (`expectedRevision: null`) is `revision_conflict`, explicit force overwrites. Plain legacy `putPage` calls keep compatibility until their owning operation adopts the managed write protocol. `projection-schema.ts` (migration 153) invalidates unverified prior projections once and queues durable work; `projections.ts` rebuilds Markdown without a worktree/provider and installs only matching canonical revisions. Embedding installs also compare exact chunk identities/text. Source importers seal code/image projections; all read arms hide unsealed projections.
- `src/core/page-state/projections.ts` — `sealPageTextProjection` and `sealImportedPage` write the page keyword vector through `pageSearchVectorSql` (`fts-language.ts`: title weight A, sanitized timeline weight C, both through `gbrain_fts_input`), the same expression `search-vector-backfill.ts` uses. Captures canonical revision, source incarnation, page identity, the complete raw chunk inventory and resolved indexing inputs before preparing derived work. Embedding reads require a current text seal; healing/rebuild capture can explicitly include unsealed pages. Projection installation compares its originating seal, chunk identities/text/source/completion state, chunker version and indexing context (including stored corpus generation) under the page guard before replacing any row. A same-revision re-chunk may replace the snapshot it actually captured; a delayed older installation cannot discard newer chunks or vectors. Rebuild also rechecks its queued job before capture so a completed job from an old listing stays completed. Chunkless healing sanitizes complete body/timeline fences before splitting, preserving withdrawn history in direct page reads while excluding it from retrieval. Tests: `page-projection-origin.test.ts`, `page-projection-vector-preservation.test.ts` (PGLite and isolated Postgres), `embed-stale-chunkless-pages.serial.test.ts` (public healing entry). Shared `markdown-chunks.ts` and `code-chunks.ts` preserve fenced code and source-language metadata. A preserving rebuild keeps a vector only when its `content_chunks.embedding_input_hash` (`src/core/embedding-input-hash.ts`) equals one recomputed from the current page, or, with no recorded hash, when the page is non-contextual and the legacy model/text-hash checks pass; a contextual chunk without provenance is nulled once. `installPageEmbeddings` records the hash in the vector's UPDATE (the plain re-embed tier by default, or the caller's `built` tier and corpus generation), and returns `{ installed, complete }`: it matches each offered vector to the page's current chunk by source and exact text (not index) and writes it only when its input hash for the captured context is one the current context accepts, in batched `jsonb_to_recordset` UPDATEs, so a page that changed under the provider call keeps the vectors of its unchanged chunks; the embedding signature is stamped only when `complete` (same chunk sequence, nothing dropped). A preserving rebuild likewise keys kept vectors by chunk content, so a top insert shifts vectors with their chunks (tests: `page-embedding-content-validity.test.ts`). Also `stampEmbeddingInputs` does the same for full imports. `resealSafeChunks` re-seals a page below the safe-chunk fence from its unchanged body with no canonical write; `projectionBelowSafeFence` is its predicate. Tests add `projection-embedding-input-hash.test.ts` and `safe-chunk-reseal.test.ts`. It replaces outgoing code edges without deleting incoming edges to retained chunks and clears backfill watermarks. Failed jobs rotate with a retained diagnostic; successful drain refreshes planner statistics. `rebuildPendingPageProjections(engine, limit, { deadlineMs, now, notAfter, retryCooldown, onFailure })` (#5401) checks an injectable clock between pages, bounds a run to rows queued at or before its start (`notAfter`, cast from text in SQL so microseconds survive the driver), applies the 30 s `rebuild_failed` cooldown for the resident, and treats a lock or snapshot error as that page's failure instead of aborting the batch; `projectionBacklog` returns counts only (pending, failed, oldest age) for the drain command and the resident's `projection_status` IPC reply. A same-revision conflict throws `PageProjectionConflictError` naming the fields that changed (`text_projection_revision`, `chunk_digest`, `indexing_context`), the slug and source; `retryProjectionConflict(attempt)` re-runs an attempt that captures a fresh snapshot at most three more times with jitter, then rethrows (`page_projection_conflict` on the wire). Tests: `page-projection-origin.test.ts` (resident rebuild race, two-writer progress, exhausted-retry CLI/JSON output).
+- `src/core/page-state/chunk-moves.ts` — #7172: `CHUNK_ROW_WRITE_BUDGET` (5), the most new `content_chunks` row versions (inserts, and non-HOT updates of `chunk_index`, text or vector) one transaction of a managed chunk replacement makes, with its derivation from the publication's 5 s statement bound; `planMoveWaves` plans the in-place renumbering of kept rows within a budget (one UPDATE per wave, a cycle parks one row at `-1 - target`), `applyMoveWaves` runs it. `import-file.ts` (with `boundedChunkWrites`, set by page-prepare, import-prepare and sync-prepare) commits a page whose replacement exceeds the budget with its projection pending (queue reason `chunk_replacement_deferred`), and `projections.ts` `continueDeferredProjection` finishes it after commit in steps of at most the budget; `rebuildPendingPageProjections` resumes an interrupted one.
- `src/core/page-state/projection-class.ts` — #6803: `projectionClassSql(p, s)`, the one CASE that puts each queued page in exactly one class (`archived`, `text` for Markdown/code and segmented pages, `protected` for a protected fence, `sealable` per `sealableImageSql`, else `reimport`), shared by `projectionBacklog`, the drain probe, search readiness and `embed --stale --images`. `sealableImageSql`: an image page at or after the safe-chunk fence whose one chunk (index 0, `image_asset`) carries the page's own text.
- `src/core/page-state/image-seal.ts` — #6803: `sealImageProjections` restores the importer's seal on `sealable` images in groups of 500: a primary-key window of queue rows probed by each page's unique key (a statistics-less PGLite planner otherwise probes through `pages_dedup_idx`), then under the page guard a revision compare-and-set with the class rechecked; no chunk write, the visual vector untouched, a text vector whose recorded input no longer matches nulled for `embed --stale`. `IMAGE_SEAL_PAGES_PER_SECOND` is the measured rate (its comment names the run); `projectionDrainLimit(textPending)` sizes doctor's `--limit` to half `AGENT_TOOL_LIMIT_MS` at that rate, or at the measured `TEXT_REBUILD_PAGES_PER_SECOND` while queued text waits (the drain takes text first).
- `src/core/page-state/projection-window.ts` — #6803: the resident's bounded queue read: per pass at most `RESIDENT_PROBE_BUDGET` (500) rows, the 100 newest by `updated_at` plus a primary-key window from a per-engine cursor that starts at a random key and wraps; a negative cache (100k keys) skips image rows the resident never builds. The consumer's idle probe walks the same window and advances the same cursor. Tests: `projection-resident-window.test.ts`.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 4e49446ea9..b53b4f66d9 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1023,6 +1023,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.327.0', text: 'Fact extraction no longer rewrites the facts it stores: the prompt-injection filter used to delete words such as "System" before a parenthesis, so "Business System (ABS)" was saved as "Business [redacted](ABS)". Injection phrases are now neutralized only where stored facts are rendered into a model prompt (standing questions, turn context, proactive briefs). `gbrain doctor --only facts_redaction_marker` counts facts damaged earlier; `gbrain repair redacted-facts` previews what a source page can prove and changes nothing until you apply the printed `--apply --expect <hash>` command.' },
{ since: '0.60.327.0', text: 'The embed sweep that finds chunks whose text changed after they were embedded now runs in 5,000-chunk batches, keeps its place between runs (at most 60 seconds per run) and starts a new pass once a day (`embed.content_drift.pass_interval_hours`, default 24); before, one statement covered the whole brain and a large brain cancelled it on every run. `gbrain doctor --only content_drift_sweep` shows each pass and any error.' },
{ since: '0.60.328.0', id: 'google_api_access_probe', text: 'A managed Google source whose enabled services cannot name the account (an API disabled for the OAuth project, a scope not granted) now resolves it through the OAuth userinfo endpoint: the account pins, the services that work keep syncing, the run is `partial`, and the disabled API is reported as `api_not_enabled` instead of failing the whole sync. `connector_account_changed` is raised only when an account resolved and differs from the pin; when nothing can name the account (userinfo also failing), the sync fails with the underlying error, a network failure included, instead of refusing as an account change. `gbrain google setup` now probes every requested service before registering a source and stops (exit 2, `status: api_access_blocked`) naming each disabled API with its Google Cloud project and enable link, or each scope not granted, in one report. `gbrain google status` adds `accounts[].api_access` and exits 1 while a problem remains, and doctor adds `google_api_access`, read from what the last sync recorded. A Google 403 for insufficient authentication scopes is now `scope_missing` (before: `upstream`, and a calendar read named it `calendar_unreadable`).' },
+ // #7172. `since` is restamped at the merge slot.
+ { since: 'TBD', text: 'A managed write (put_page, add_timeline_entry, a managed import or sync) whose passages need more than 5 inserted or renumbered rows commits the page first and finishes its passages in post-commit transactions of at most 5 row writes each, instead of writing them all inside the publication, where a slow index could end it 57014 `write_interrupted`. Search sees the page once the last step seals it; until then its receipt says `searchable: "pending"`, and `gbrain projections drain` finishes a page whose writer stopped. A passage whose text is unchanged keeps its row and vector when an entry above it moves it to another index.' },
+ { since: 'TBD', text: 'The embedding step after a managed write no longer re-embeds every passage of a page whose stored embedding signature is missing or in an older format: a passage whose recorded embedding input is still current keeps its vector and the page signature is restamped, so only passages whose text changed reach the embedding provider.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/import-chunk-reuse.ts b/src/core/import-chunk-reuse.ts
index 4e87688b79..f576cff754 100644
--- a/src/core/import-chunk-reuse.ts
+++ b/src/core/import-chunk-reuse.ts
@@ -13,21 +13,26 @@ import { quoteIdentifier } from './search/embedding-column.ts';
import { chunkGenerationFilter } from './search/safe-chunks.ts';
import { parseEmbedding } from './utils.ts';
+/** A stored row an import keeps: its id and the index it holds now (a kept row whose new chunk sits elsewhere moves there). */
+export interface KeptChunkRow { id: number; chunk_index: number }
+
/**
* A13 reuse for one page import: copies each stored vector the reuse gate
* admits onto its matching new chunk in `into`, and maps the chunk's index to
- * the stored row id when that row already holds exactly what the chunk would
- * insert (so an import can keep it in place), else to null. With
- * `keepUnembedded` (the in-transaction pass), an identical stored row with no
- * vector also maps to its id when the new chunk carries no vector. A
- * prepared import reuses nothing from a page stored under per-chunk synopsis.
+ * the stored row when that row already holds exactly what the chunk would
+ * insert, at any index (#7172: an entry inserted above it shifts its index, not
+ * its content), so an import can keep it, else to null. A stored row at the
+ * chunk's own index is matched first. With `keepUnembedded` (the
+ * in-transaction pass), an identical stored row with no vector at the same
+ * index also maps to its row when the new chunk carries no vector. A prepared
+ * import reuses nothing from a page stored under per-chunk synopsis.
*/
export async function reuseStoredChunkVectors(
exec: BrainEngine,
into: ChunkInput[],
{ slug, sourceId, title, corpusGeneration, tier, prepared, keepUnembedded = false }: { slug: string; sourceId: string; title: string; corpusGeneration: string | null; tier: 'title' | 'none'; prepared: boolean; keepUnembedded?: boolean },
-): Promise<Map<number, number | null>> {
- const reused = new Map<number, number | null>();
+): Promise<Map<number, KeptChunkRow | null>> {
+ const reused = new Map<number, KeptChunkRow | null>();
const target = await embeddingWriteTarget(exec);
const provenance = embeddingInputContext(target, title, corpusGeneration, into);
const rows = await exec.executeRaw<{ chunk_index: number; embedding_input_hash: string | null; contextual_retrieval_mode: string | null; text_only: boolean; unembedded: boolean }>(
@@ -46,19 +51,26 @@ export async function reuseStoredChunkVectors(
// Reuse is keyed on chunk source + text, so a stored chunk's current-input
// hash is the hash its matching new chunk would record.
const all = await exec.getChunks(slug, { sourceId, includeEmbedding: true, requireSafeChunks: true });
- const stored = all.filter(chunk => canReuseMarkdownVector(recorded.get(chunk.chunk_index), rows[0]!.contextual_retrieval_mode, tier, provenance, chunk));
- const identity = (chunk: ChunkInput | Chunk) => JSON.stringify([chunk.chunk_index, chunk.chunk_text, chunk.chunk_source,
+ const stored = all.filter(chunk => chunk.embedding && canReuseMarkdownVector(recorded.get(chunk.chunk_index), rows[0]!.contextual_retrieval_mode, tier, provenance, chunk));
+ const identity = (chunk: ChunkInput | Chunk) => JSON.stringify([chunk.chunk_text, chunk.chunk_source,
chunk.language ?? null, chunk.symbol_name ?? null, chunk.symbol_type ?? null, chunk.start_line ?? null, chunk.end_line ?? null,
chunk.parent_symbol_path ?? null, chunk.doc_comment ?? null, chunk.symbol_name_qualified ?? null, chunk.modality ?? 'text']);
- for (const [i, matched] of planEmbeddingReuse(stored, into, c => `${c.chunk_source}\0${c.chunk_text}`).reuse) {
- into[i].embedding = matched.embedding as Float32Array;
- into[i].token_count = matched.token_count ?? undefined;
- if (matched.model) into[i].model = matched.model;
- // The stored row already holds exactly what this chunk would insert (same
- // index, identity, vector, recorded input and text hash, no image or
- // multimodal vector the insert would drop), so it can stay in place.
- const row = matched as Chunk;
- reused.set(i, recorded.get(row.chunk_index) != null && textOnly.has(row.chunk_index) && identity(row) === identity(into[i]) ? row.id : null);
+ const key = (chunk: { chunk_source?: string | null; chunk_text: string }) => `${chunk.chunk_source}\0${chunk.chunk_text}`;
+ // A stored row at the chunk's own index first, then FIFO by source + text: one page can hold two identical chunks.
+ const atIndex = new Map(stored.map(chunk => [chunk.chunk_index, chunk]));
+ const matches = new Map<number, Chunk>();
+ into.forEach((chunk, i) => { const row = atIndex.get(chunk.chunk_index); if (row && key(row) === key(chunk)) matches.set(i, row); });
+ const taken = new Set([...matches.values()].map(row => row.id));
+ const byKey = new Map<string, Chunk[]>();
+ for (const row of stored) if (!taken.has(row.id)) byKey.set(key(row), [...(byKey.get(key(row)) ?? []), row]);
+ into.forEach((chunk, i) => { const row = matches.has(i) ? undefined : byKey.get(key(chunk))?.shift(); if (row) matches.set(i, row); });
+ for (const [i, row] of matches) {
+ into[i].embedding = row.embedding as Float32Array;
+ into[i].token_count = row.token_count ?? undefined;
+ if (row.model) into[i].model = row.model;
+ // The stored row already holds exactly what this chunk would insert (identity, vector, recorded input and text
+ // hash, no image or multimodal vector the insert would drop), so it can stay, moved to this chunk's index.
+ reused.set(i, recorded.get(row.chunk_index) != null && textOnly.has(row.chunk_index) && identity(row) === identity(into[i]) ? { id: row.id, chunk_index: row.chunk_index } : null);
}
// A stored row that never got a vector stays in place under a new chunk that
// will not get one either (a --no-embed or deferred write): the same upsert
@@ -69,7 +81,7 @@ export async function reuseStoredChunkVectors(
for (const row of all) {
const i = byIndex.get(row.chunk_index);
if (i === undefined || reused.has(i) || into[i]!.embedding || !unembedded.has(row.chunk_index)) continue;
- if (identity(row) === identity(into[i]!)) reused.set(i, row.id);
+ if (identity(row) === identity(into[i]!)) reused.set(i, { id: row.id, chunk_index: row.chunk_index });
}
}
return reused;
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 1bfa1a4f21..c81f5d94dd 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -23,12 +23,13 @@ import { prepareFenceAwareMarkdownChunks } from './markdown-chunks.ts';
import { prepareCodeChunks, installCodeChunkEdges, mapCodeEdges } from './code-chunks.ts';
import { detectCodeLanguage, CHUNKER_VERSION, GRAMMAR_REVISIONS, type SupportedCodeLanguage } from './chunkers/code.ts';
import { sanitizeRemoteBody } from './remote-body.ts';
-import { installPageEmbeddings, installPageProjection, preparePageProjection, projectionBelowSafeFence, queuePageProjection, readProjectionSnapshot, resealSafeChunks,
- sealPageTextProjection, stampEmbeddingInputs, type ProjectionSnapshot } from './page-state/projections.ts';
+import { continueDeferredProjection, DEFERRED_CHUNK_REPLACEMENT, installPageEmbeddings, installPageProjection, preparePageProjection, projectionBelowSafeFence, queuePageProjection,
+ readProjectionSnapshot, resealSafeChunks, sealPageTextProjection, stampEmbeddingInputs, type ProjectionSnapshot } from './page-state/projections.ts';
import { sanitizeText } from './batch-rows.ts';
import { hasProtectedBody, OCR_REQUIRED_ERROR, provenanceDistrusted, safeChunksFilter } from './search/safe-chunks.ts';
import { planEmbeddingReuse } from './embed-reuse.ts';
-import { reuseStoredChunkVectors } from './import-chunk-reuse.ts';
+import { reuseStoredChunkVectors, type KeptChunkRow } from './import-chunk-reuse.ts';
+import { applyMoveWaves, CHUNK_ROW_WRITE_BUDGET, planMoveWaves, type ChunkMove } from './page-state/chunk-moves.ts';
import { extractCodeRefs, imageOfCandidates } from './link-extraction.ts';
import { embedMultimodal, currentEmbeddingSignature } from './embedding.ts';
// #3374 — import-path embeds ride the shared retry loop (429 retry-after +
@@ -254,6 +255,11 @@ export async function importFromContent(
prepare?: (prepared: import('./persistence/prepared-import.ts').PreparedContentImport) => Promise<ImportResult>;
/** #5984, with `prepare`: the coordinator proves the base revision under its page guard, and the caller seals the text projection and checks the read-back (`contentHash`) from its own read after apply; apply skips all three. */
coordinated?: boolean;
+ /**
+ * #7172, with `prepare`: the caller forwards `afterCommit` and seals nothing when apply returns `projectionPending`, so
+ * a chunk replacement over CHUNK_ROW_WRITE_BUDGET row writes commits its page pending and finishes after commit.
+ */
+ boundedChunkWrites?: true;
/** With `coordinated`: the caller's own read of this page (deleted rows included) just before, reused as the import base. */
existingSnapshot?: import('./page-state/types.ts').PageSnapshot | null;
/** Internal canonical metadata, after protected-body overlays and before hashing. */
@@ -724,6 +730,7 @@ export async function importFromContent(
const txOpts = { sourceId: sourceId ?? 'default' };
let persistedProjection: ProjectionSnapshot | null = null;
const [timeZone, mentionPolicy] = await Promise.all([loadBrainTimeZone(engine), readMentionPolicy(engine).catch(() => null)]);
+ let chunkReplacementDeferred = false;
const applyPrepared = async (tx: BrainEngine, preimage?: PageSnapshot | null) => {
if (!opts.coordinated) await assertImportBase(tx, slug, txOpts.sourceId, existing, reused.size > 0);
// #5984: the canonical writes go out in two pipelined waves of mutually independent statements; the
@@ -755,8 +762,22 @@ export async function importFromContent(
// reuse is re-read here, under the page lock, so a kept row is one this
// transaction sees; --no-embed and deferred-embed imports keep vectors too.
const fresh = reusable ? chunks.map(chunk => ({ ...chunk })) : chunks;
- const kept = new Map([...(fresh !== chunks ? await reuseStoredVectors(tx, fresh, true) : [])].filter(([, id]) => id !== null));
- const keptIds = [...kept.values()];
+ const kept = new Map([...(fresh !== chunks ? await reuseStoredVectors(tx, fresh, true) : [])]
+ .filter((entry): entry is [number, KeptChunkRow] => entry[1] !== null));
+ const keptIds = [...kept.values()].map(row => row.id);
+ // #7172: a kept row whose chunk moved (an entry inserted above it) changes index in place. Each move and each
+ // inserted row is a row write (chunk-moves.ts); a managed publication makes at most CHUNK_ROW_WRITE_BUDGET of them
+ // and otherwise deletes the rows it does not keep, commits the page with its projection pending and finishes after
+ // commit (continueDeferredProjection).
+ const moves: ChunkMove[] = [...kept].filter(([i, row]) => row.chunk_index !== fresh[i]!.chunk_index)
+ .map(([i, row]) => ({ id: row.id, from: row.chunk_index, to: fresh[i]!.chunk_index,
+ projected_byte_start: fresh[i]!.projected_byte_start ?? null, projected_byte_end: fresh[i]!.projected_byte_end ?? null }));
+ const inserts = fresh.length - kept.size;
+ const bounded = !segmented && !!opts.prepare && opts.boundedChunkWrites === true;
+ const moveBudget = bounded ? Math.max(0, CHUNK_ROW_WRITE_BUDGET - inserts) : Number.POSITIVE_INFINITY;
+ const movePlan = planMoveWaves(moves, new Map([...kept.values()].map(row => [row.chunk_index, row.id])), moveBudget);
+ const deferChunks = bounded && chunks.length > 0 && (!movePlan.done || inserts > CHUNK_ROW_WRITE_BUDGET);
+ chunkReplacementDeferred = deferChunks;
let written: Page | undefined;
await pipelined(tx, [
() => assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || '', slug),
@@ -818,7 +839,9 @@ export async function importFromContent(
for (const tag of parsed.tags) await tx.addTag(slug, tag, opts.prepare ? txOpts : { ...txOpts, tagSource: 'frontmatter' });
},
async () => {
+ if (deferChunks) return;
if (chunks.length > 0) {
+ if (movePlan.waves.length) await applyMoveWaves(tx, Number(pageId), movePlan.waves);
const embeddingColumn = await stampEmbeddingInputs(tx, fresh, null,
{ title: parsed.title, tier: effectiveCRMode === 'title' ? 'title' : 'none', corpusGeneration });
await tx.upsertChunks(slug, kept.size ? fresh.filter((_, i) => !kept.has(i)) : fresh, { ...txOpts, ...(embeddingColumn ? { embeddingColumn } : {}), sealChunkerVersion: MARKDOWN_CHUNKER_VERSION,
@@ -840,7 +863,7 @@ export async function importFromContent(
}
},
]);
- if (!opts.coordinated && !segmented) await sealPageTextProjection(tx, slug, txOpts.sourceId);
+ if (!opts.coordinated && !segmented && !deferChunks) await sealPageTextProjection(tx, slug, txOpts.sourceId);
if (!opts.coordinated && segmented?.applied?.complete) await sealSegmentedPage(tx, segmented.applied.pageId);
// v0.19.0 E1 — doc↔impl linking: if this markdown page cites code paths
@@ -868,6 +891,11 @@ export async function importFromContent(
persistedProjection = await readProjectionSnapshot(tx, slug, txOpts.sourceId);
}
if (segmented?.applied) return { pageId, sealed: !opts.coordinated && segmented.applied.complete, segmented: { complete: segmented.applied.complete } };
+ if (deferChunks) {
+ // The trigger queued this revision's projection; the reason routes a resident or drain rebuild to the bounded continuation.
+ await queuePageProjection(tx, txOpts.sourceId, slug, DEFERRED_CHUNK_REPLACEMENT);
+ return { pageId, sealed: false, projectionPending: true as const };
+ }
return { pageId, sealed: !opts.coordinated && !opts.beforeCommit, ...(deferSeal ? { chunkerSeal: MARKDOWN_CHUNKER_VERSION } : {}) };
};
if (opts.prepare) return opts.prepare({
@@ -875,7 +903,8 @@ export async function importFromContent(
noop: false, contentHash: hash, result: { slug, status: 'imported', chunks: segmented ? segmented.prepared.rows.chunks : chunks.length, parsedPage,
...(pageQuarantined ? { quarantined: true } : {}), ...(pageFlagged ? { flagged: true, flag_reason: pageFlagReason } : {}), ...(disposition.gate ? { gate: disposition.gate } : {}), ...fences.fields },
validate: tx => assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || '', slug),
- apply: applyPrepared, ...(segmented ? { afterCommit: async (target: BrainEngine) => { await segmented.afterCommit(target); }, segmented } : {}),
+ apply: applyPrepared, ...(segmented ? { afterCommit: async (target: BrainEngine) => { await segmented.afterCommit(target); }, segmented }
+ : opts.boundedChunkWrites ? { afterCommit: async (target: BrainEngine) => { if (chunkReplacementDeferred) await continueDeferredProjection(target, txOpts.sourceId, slug); } } : {}),
});
await withUnmanagedBeliefs(engine, txOpts.sourceId, [slug], 'import', run => maintenanceTransaction(engine, tx => run(tx, () => applyPrepared(tx)), writeTrustOfGate(opts.writeGate)).catch(async (err: unknown) => {
await abortSegmentedStaging(engine, segmented?.prepared);
diff --git a/src/core/page-state/chunk-moves.ts b/src/core/page-state/chunk-moves.ts
new file mode 100644
index 0000000000..fd12ec19ee
--- /dev/null
+++ b/src/core/page-state/chunk-moves.ts
@@ -0,0 +1,57 @@
+import type { BrainEngine } from '../engine.ts';
+
+/**
+ * #7172: the most row writes one page's chunk replacement makes in one transaction.
+ *
+ * A row write here is a new row version of content_chunks: an inserted passage, and an UPDATE of `chunk_index` or of
+ * the vector too, because each changes an indexed column, so the update is not HOT and Postgres adds an entry for the
+ * new version to every index of the table: the GIN index of the passage's search vector (one entry per lexeme), the
+ * HNSW index when the vector is not NULL, and the b-trees (measured on pgvector: renumbering 2,000 rows cost what
+ * inserting 2,000 did). A delete adds no index entry, so it is not counted. On a large table these entries land on
+ * index pages that are not cached; the slowest passage inserts reported on a large production index ran at about
+ * 0.5 s per row, so the bound charges 0.5 s per row write with nothing amortized. A publication's statements each run
+ * under a transaction-local 5 s `statement_timeout` (protocol.ts `declareDurablePersistence`), and half of it is left
+ * for the work every write does besides (lock waits, the page row, a GIN pending-list flush):
+ * floor(2.5 s / 0.5 s) = 5. A replacement that needs more commits its page with the projection pending and finishes
+ * in post-commit transactions of at most this many row writes each (`continueDeferredProjection`).
+ */
+export const CHUNK_ROW_WRITE_BUDGET = 5;
+
+/** A stored chunk row that keeps its id and vector and changes index (`to`), with the span its new chunk records. */
+export interface ChunkMove { id: number; from: number; to: number; projected_byte_start?: number | null; projected_byte_end?: number | null }
+
+/**
+ * The UPDATE statements (waves) that move `moves` without breaking the (page_id, chunk_index) unique index, using at
+ * most `budget` row updates. `occupied` maps each index a remaining row holds to its id. A wave moves rows whose
+ * target is free; when none is (a cycle), one row parks at the negative index `-1 - to` and lands later. `done` says
+ * every move fits.
+ */
+export function planMoveWaves(moves: readonly ChunkMove[], occupied: ReadonlyMap<number, number>, budget: number): { waves: ChunkMove[][]; updates: number; done: boolean } {
+ const at = new Map(occupied);
+ let pending = moves.map(move => ({ ...move }));
+ const waves: ChunkMove[][] = [];
+ let updates = 0;
+ while (pending.length && updates < budget) {
+ const free = pending.filter(move => !at.has(move.to)).slice(0, budget - updates);
+ const wave = free.length ? free : [{ ...pending[0]!, to: -1 - pending[0]!.to }];
+ for (const move of wave) { at.delete(move.from); at.set(move.to, move.id); }
+ waves.push(wave);
+ updates += wave.length;
+ if (free.length) pending = pending.filter(move => !free.includes(move));
+ else pending[0]!.from = wave[0]!.to;
+ }
+ return { waves, updates, done: pending.length === 0 };
+}
+
+/** One UPDATE per wave; a landed row takes its new chunk's span, a parked row keeps its own until it lands. */
+export async function applyMoveWaves(tx: Pick<BrainEngine, 'executeRaw'>, pageId: number, waves: readonly ChunkMove[][]): Promise<void> {
+ for (const wave of waves) {
+ await tx.executeRaw(`UPDATE content_chunks c SET chunk_index = m.target,
+ projected_byte_start = CASE WHEN m.target < 0 THEN c.projected_byte_start ELSE m.byte_start END,
+ projected_byte_end = CASE WHEN m.target < 0 THEN c.projected_byte_end ELSE m.byte_end END
+ FROM unnest($2::int[], $3::int[], $4::bigint[], $5::bigint[]) AS m(id, target, byte_start, byte_end)
+ WHERE c.page_id = $1 AND c.id = m.id`,
+ [pageId, wave.map(move => move.id), wave.map(move => move.to),
+ wave.map(move => move.projected_byte_start ?? null), wave.map(move => move.projected_byte_end ?? null)]);
+ }
+}
diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.ts
index 97aa8c27b1..057c562286 100644
--- a/src/core/page-state/projections.ts
+++ b/src/core/page-state/projections.ts
@@ -16,6 +16,7 @@ import { getEmbeddingModel } from '../ai/gateway.ts';
import { jsonRowBatches } from '../batch-rows.ts';
import { refreshProjectionStatistics } from '../search/projection-statistics.ts';
import { belowSafeChunkFence, chunkGenerationFilter, movableChunkSql } from '../search/safe-chunks.ts';
+import { applyMoveWaves, CHUNK_ROW_WRITE_BUDGET, planMoveWaves, type ChunkMove } from './chunk-moves.ts';
import { buildSegmentedProjection } from '../page-body/projection.ts';
import { isSegmentedPage } from '../page-body/page-shape.ts';
import { pageReadFilter } from '../search/read-policy-sql.ts';
@@ -171,6 +172,112 @@ async function readGuardedProjectionSnapshot(tx: BrainEngine, slug: string, sour
...(fenceOverlay ? { fenceOverlay } : {}) };
}
+/** #7172: the queue reason of a revision whose publication left its chunk replacement to `continueDeferredProjection`. */
+export const DEFERRED_CHUNK_REPLACEMENT = 'chunk_replacement_deferred';
+
+/**
+ * Which stored rows a projection of `chunks` keeps (#5553, A4): each row holding a new chunk at its own index, and
+ * each other row whose chunk the projection holds at another index when its vector is current (`moves`, with the
+ * index and span each lands on). `current` lists the kept rows whose recorded embedding input the page accepts.
+ */
+async function planProjectionKeep(tx: BrainEngine, current: PageSnapshot, context: Awaited<ReturnType<typeof indexingContext>>, stored: Chunk[], chunks: ChunkInput[]) {
+ // #5553: keep a vector only when its recorded embedding input equals the
+ // input the current page would produce. A chunk with no record is kept
+ // only in the pre-contextual NULL mode; explicit none may have inherited
+ // an old title vector, so its missing proof cannot authorize retention.
+ // On a contextual page it is
+ // nulled once and stamped by its re-embed.
+ const mode = current.page.contextual_retrieval_mode;
+ const provenance = embeddingInputContext(context, current.page.title, context.corpusGeneration, chunks);
+ const col = quoteIdentifier(context.column.name);
+ const recorded = new Map((await tx.executeRaw<{ id: number; embedding_input_hash: string | null; movable: boolean }>(
+ `SELECT id,embedding_input_hash,${movableChunkSql(col)} AND model IS NOT DISTINCT FROM $2 AS movable FROM content_chunks WHERE page_id=$1`,
+ [current.page.id, context.provenanceModel])).map(row => [Number(row.id), row]));
+ const currentInput = (chunk: Chunk) => {
+ const hash = recorded.get(Number(chunk.id))?.embedding_input_hash ?? null;
+ return hash === null ? mode == null : acceptedEmbeddingInputHashes(provenance, mode, chunk).includes(hash);
+ };
+ // A4: a chunk unchanged at its index stays; one the new projection holds at
+ // another index stays too when its vector is current, and moves there, so a
+ // top insert re-embeds only the chunks whose text changed.
+ const identity = (chunk: ChunkInput | Chunk) => digest([chunk.chunk_text, chunk.chunk_source,
+ chunk.language ?? null, chunk.symbol_name ?? null, chunk.symbol_type ?? null,
+ chunk.start_line ?? null, chunk.end_line ?? null, chunk.parent_symbol_path ?? null,
+ chunk.doc_comment ?? null, chunk.symbol_name_qualified ?? null, chunk.modality ?? 'text']);
+ const atIndex = new Map(chunks.map(chunk => [chunk.chunk_index, identity(chunk)]));
+ const inPlace = stored.filter(chunk => atIndex.get(chunk.chunk_index) === identity(chunk));
+ const held = new Set(inPlace.map(chunk => chunk.chunk_index));
+ const open = new Map<string, ChunkInput[]>();
+ for (const chunk of chunks) if (!held.has(chunk.chunk_index)) open.set(identity(chunk), [...(open.get(identity(chunk)) ?? []), chunk]);
+ const moves: ChunkMove[] = [];
+ const moved = stored.filter(chunk => {
+ if (held.has(chunk.chunk_index) && atIndex.get(chunk.chunk_index) === identity(chunk)) return false;
+ if (!recorded.get(Number(chunk.id))?.movable || !currentInput(chunk)) return false;
+ const target = open.get(identity(chunk))?.shift();
+ if (!target) return false;
+ moves.push({ id: Number(chunk.id), from: chunk.chunk_index, to: target.chunk_index,
+ projected_byte_start: target.projected_byte_start ?? null, projected_byte_end: target.projected_byte_end ?? null });
+ return true;
+ });
+ const kept = [...inPlace, ...moved];
+ return { kept, moves, current: kept.filter(currentInput).map(chunk => Number(chunk.id)), provenanceModel: context.provenanceModel, column: context.column };
+}
+
+/**
+ * #7172: one bounded step of a chunk replacement a publication deferred (the page committed with its text projection
+ * pending, its search hiding the page's passages until the seal). Under the page guard, at the page's current
+ * revision, a step deletes the rows the projection does not keep (a delete adds no index entry) and then makes at most
+ * `budget` row writes, in this order: kept rows change index (`planMoveWaves`), kept rows whose input is no longer
+ * current lose their vector, and the missing chunks are inserted without vectors. The step that finds nothing left
+ * seals the projection. Idempotent: each step re-reads the page and plans from what is stored, so a crash between
+ * steps resumes where the last committed one left it. 'skipped' when the page is not an unsealed inline Markdown page.
+ */
+export async function continueDeferredProjectionStep(engine: BrainEngine, sourceId: string, slug: string, budget = CHUNK_ROW_WRITE_BUDGET): Promise<'sealed' | 'more' | 'skipped'> {
+ return engine.transaction(async tx => {
+ await tx.lockPageKeys([{ sourceId, slug }]);
+ const prepared = await readGuardedProjectionSnapshot(tx, slug, sourceId, { allowUnsealed: true });
+ if (!prepared || prepared.pageKind !== 'markdown' || prepared.snapshot.page.text_projection_revision === prepared.snapshot.revision) return 'skipped';
+ const current = prepared.snapshot;
+ const pageId = Number(current.page.id);
+ const { chunks } = await preparePageProjection(prepared);
+ const context = await indexingContext(tx, current, prepared.maxChunkTokensOverride);
+ const plan = await planProjectionKeep(tx, current, context, prepared.chunks, chunks);
+ await tx.executeRaw('DELETE FROM content_chunks WHERE page_id=$1 AND NOT(id=ANY($2::int[]))', [pageId, plan.kept.map(chunk => Number(chunk.id))]);
+ const { waves, updates, done } = planMoveWaves(plan.moves, new Map(plan.kept.map(chunk => [chunk.chunk_index, Number(chunk.id)])), budget);
+ await applyMoveWaves(tx, pageId, waves);
+ if (!done) return 'more';
+ let left = budget - updates;
+ const col = quoteIdentifier(plan.column.name);
+ const stale = (await tx.executeRaw<{ id: number }>(`SELECT id FROM content_chunks WHERE page_id=$1 AND ${col} IS NOT NULL
+ AND (model IS DISTINCT FROM $2 OR embedded_text_hash <> md5(chunk_text) OR NOT(id=ANY($3::int[]))) ORDER BY chunk_index`,
+ [pageId, plan.provenanceModel, plan.current])).map(row => Number(row.id));
+ const nulled = stale.slice(0, left);
+ if (nulled.length) {
+ await tx.executeRaw(`UPDATE content_chunks SET ${col}=NULL,embedded_at=NULL,embedded_text_hash=NULL,embedding_input_hash=NULL,
+ embedding_pending_since=COALESCE(embedding_pending_since,now()) WHERE page_id=$1 AND id=ANY($2::int[])`, [pageId, nulled]);
+ }
+ if (stale.length > nulled.length) return 'more';
+ left -= nulled.length;
+ const moved = new Set(plan.moves.map(move => move.id));
+ const occupied = new Set([...plan.kept.filter(row => !moved.has(Number(row.id))).map(row => row.chunk_index), ...plan.moves.map(move => move.to)]);
+ const missing = chunks.filter(chunk => !occupied.has(chunk.chunk_index));
+ const inserts = missing.slice(0, left);
+ if (inserts.length) await tx.upsertChunks(slug, inserts, { sourceId, embeddingColumn: context.column, sealChunkerVersion: MARKDOWN_CHUNKER_VERSION, pageId, deferSeal: true });
+ if (missing.length > inserts.length) return 'more';
+ await sealImportedPage(tx, slug, sourceId, current, MARKDOWN_CHUNKER_VERSION, pageId);
+ await tx.executeRaw('DELETE FROM page_projection_jobs WHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid', [current.sourceIncarnation, slug, current.revision]);
+ return 'sealed';
+ });
+}
+
+/** `continueDeferredProjectionStep` until the page is sealed, skipped, or `until` says stop (a resident's time budget). */
+export async function continueDeferredProjection(engine: BrainEngine, sourceId: string, slug: string, until: () => boolean = () => false): Promise<'sealed' | 'more' | 'skipped'> {
+ for (;;) {
+ const step = await continueDeferredProjectionStep(engine, sourceId, slug);
+ if (step !== 'more' || until()) return step;
+ }
+}
+
/** No provider work under the guard. Delayed derived results lose to newer content. */
export async function installPageProjection(engine: BrainEngine, prepared: ProjectionSnapshot, chunks: ChunkInput[], opts: { seal?: boolean; signature?: string; preserveEmbeddings?: boolean; code?: Awaited<ReturnType<typeof prepareCodeChunks>> } = {}): Promise<void> {
const { snapshot } = prepared;
@@ -197,48 +304,14 @@ export async function installPageProjection(engine: BrainEngine, prepared: Proje
];
if (changed.length) throw new PageProjectionConflictError(snapshot.revision, current!.revision, changed, slug, sourceId);
if (opts.seal && opts.preserveEmbeddings) {
- // #5553: keep a vector only when its recorded embedding input equals the
- // input the current page would produce. A chunk with no record is kept
- // only in the pre-contextual NULL mode; explicit none may have inherited
- // an old title vector, so its missing proof cannot authorize retention.
- // On a contextual page it is
- // nulled once and stamped by its re-embed.
- const mode = current!.page.contextual_retrieval_mode;
- const provenance = embeddingInputContext(context, current!.page.title, context.corpusGeneration, chunks);
- const col = quoteIdentifier(context.column.name);
- const recorded = new Map((await tx.executeRaw<{ id: number; embedding_input_hash: string | null; movable: boolean }>(
- `SELECT id,embedding_input_hash,${movableChunkSql(col)} AND model IS NOT DISTINCT FROM $2 AS movable FROM content_chunks WHERE page_id=$1`,
- [snapshot.page.id, context.provenanceModel])).map(row => [Number(row.id), row]));
- const currentInput = (chunk: Chunk) => {
- const hash = recorded.get(Number(chunk.id))?.embedding_input_hash ?? null;
- return hash === null ? mode == null : acceptedEmbeddingInputHashes(provenance, mode, chunk).includes(hash);
- };
- // A4: a chunk unchanged at its index stays; one the new projection holds at
- // another index stays too when its vector is current, and upsertChunks moves
- // the row there, so a top insert re-embeds only the chunks whose text changed.
- const identity = (chunk: ChunkInput | Chunk) => digest([chunk.chunk_text, chunk.chunk_source,
- chunk.language ?? null, chunk.symbol_name ?? null, chunk.symbol_type ?? null,
- chunk.start_line ?? null, chunk.end_line ?? null, chunk.parent_symbol_path ?? null,
- chunk.doc_comment ?? null, chunk.symbol_name_qualified ?? null, chunk.modality ?? 'text']);
- const atIndex = new Map(chunks.map(chunk => [chunk.chunk_index, identity(chunk)]));
- const elsewhere = new Map<string, number>();
- for (const chunk of chunks) elsewhere.set(identity(chunk), (elsewhere.get(identity(chunk)) ?? 0) + 1);
- const inPlace = stored.filter(chunk => atIndex.get(chunk.chunk_index) === identity(chunk));
- for (const chunk of inPlace) elsewhere.set(identity(chunk), elsewhere.get(identity(chunk))! - 1);
- const moved = stored.filter(chunk => {
- const left = elsewhere.get(identity(chunk)) ?? 0;
- if (atIndex.get(chunk.chunk_index) === identity(chunk) || left <= 0
- || !recorded.get(Number(chunk.id))?.movable || !currentInput(chunk)) return false;
- elsewhere.set(identity(chunk), left - 1);
- return true;
- });
- const kept = [...inPlace, ...moved];
+ const { kept, current: currentIds, provenanceModel, column } = await planProjectionKeep(tx, current!, context, stored, chunks);
+ const col = quoteIdentifier(column.name);
await tx.executeRaw(`DELETE FROM content_chunks WHERE page_id=$1 AND NOT(id=ANY($2::int[]))`, [snapshot.page.id, kept.map(chunk => chunk.id)]);
await tx.executeRaw(`UPDATE content_chunks SET ${col}=NULL,
embedded_at=NULL,embedded_text_hash=NULL,embedding_input_hash=NULL,
embedding_pending_since=COALESCE(embedding_pending_since,now()) WHERE page_id=$1 AND
(model IS DISTINCT FROM $2 OR embedded_text_hash <> md5(chunk_text) OR NOT(id=ANY($3::int[])))`,
- [snapshot.page.id, context.provenanceModel, kept.filter(currentInput).map(chunk => Number(chunk.id))]);
+ [snapshot.page.id, provenanceModel, currentIds]);
} else if (opts.seal) await tx.deleteChunks(slug, { sourceId });
await tx.upsertChunks(slug, chunks, { sourceId, expectedRevision: snapshot.revision, embeddingColumn: context.column });
if (opts.code) await installCodeChunkEdges(tx, slug, sourceId, opts.code);
@@ -680,9 +753,10 @@ export async function rebuildPendingPageProjections(engine: BrainEngine, limit =
try {
const prepared = await engine.transaction(async tx => {
await tx.lockPageKeys([{ sourceId: job.source_id, slug: job.slug }]);
- const pending = await tx.executeRaw(`SELECT 1 FROM page_projection_jobs
+ const pending = await tx.executeRaw<{ reason: string }>(`SELECT reason FROM page_projection_jobs
WHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid`, observed);
if (!pending.length) return null;
+ if (pending[0]!.reason === DEFERRED_CHUNK_REPLACEMENT) return 'deferred';
const read = await readGuardedProjectionSnapshot(tx, job.slug, job.source_id, { allowUnsealed: true });
if (!read) {
const [segmented] = await tx.executeRaw(`SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2 AND body_storage='segmented' AND deleted_at IS NULL`,
@@ -701,6 +775,19 @@ export async function rebuildPendingPageProjections(engine: BrainEngine, limit =
});
if (!prepared) { superseded++; continue; }
if (prepared === 'removed') { superseded++; opts.onHeal?.({ kind: 'removed', source_id: job.source_id, slug: job.slug }); continue; }
+ if (prepared === 'deferred') {
+ // #7172: a publication left this revision's chunk replacement; it finishes in bounded steps, within the deadline.
+ const step = await continueDeferredProjection(engine, job.source_id, job.slug,
+ () => opts.deadlineMs !== undefined && now() - startedAt >= opts.deadlineMs);
+ if (step === 'sealed') rebuilt++;
+ else {
+ superseded++;
+ // A skipped page (sealed meanwhile, or no longer inline Markdown) goes back to the ordinary rebuild.
+ await engine.executeRaw(`UPDATE page_projection_jobs SET updated_at=now()${step === 'skipped' ? ",reason='canonical_change'" : ''}
+ WHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid`, observed);
+ }
+ continue;
+ }
if (prepared === 'segmented') {
const built = await buildSegmentedProjection(engine, { sourceId: job.source_id, slug: job.slug });
await engine.executeRaw(built.sealed
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index 99a9a6ee15..f37ecae828 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -16,7 +16,8 @@ import { serializePageToMarkdown } from '../markdown.ts';
import { isSegmentedPage } from '../page-body/page-shape.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { materializePageSnapshot } from '../page-state/materialize.ts';
-import { installPageEmbeddings, readProjectionSnapshot } from '../page-state/projections.ts';
+import { embeddingInputContext, embeddingWriteTarget, installPageEmbeddings, readProjectionSnapshot } from '../page-state/projections.ts';
+import { acceptedEmbeddingInputHashes } from '../embedding-input-hash.ts';
import { embedSegmentedPage, readSegmentedEmbedPage, type SegmentedEmbedPage } from '../page-body/segmented-embedding.ts';
import { resolveProvenanceStamp, stampIfPageProvenanceComplete } from '../embed-stale.ts';
import { currentEmbeddingSignature, embedBatch } from '../embedding.ts';
@@ -401,14 +402,24 @@ export async function readEmbeddingEffectProjection(engine: BrainEngine, effect:
{ fix: effectStatusFix(effect) });
}
const column = prepared.embeddingColumn;
- const completion = await tx.executeRaw<{ id: number; complete: boolean }>(`SELECT cc.id,
- p.embedding_signature=$2 AND cc.${quoteIdentifier(column.name)} IS NOT NULL AND cc.embedded_at IS NOT NULL
- AND cc.embedded_text_hash=md5(cc.chunk_text) AND cc.model IS NOT DISTINCT FROM $3 AS complete
+ const completion = await tx.executeRaw<{ id: number; chunk_text: string; chunk_source: string | null; embedding_input_hash: string | null; embedded: boolean; stamped: boolean }>(`SELECT cc.id,
+ cc.chunk_text, cc.chunk_source, cc.embedding_input_hash,
+ cc.${quoteIdentifier(column.name)} IS NOT NULL AND cc.embedded_at IS NOT NULL AND cc.embedded_text_hash=md5(cc.chunk_text) AS embedded,
+ p.embedding_signature=$2 AND cc.model IS NOT DISTINCT FROM $3 AS stamped
FROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE p.id=$1 AND ${chunkGenerationFilter('p', 'cc', await chunkManifestReads(engine, tx))}`,
[snapshot.page.id, signature, embeddingCompletionModel(column, signature, model)]);
- const complete = new Set(completion.filter(chunk => chunk.complete === true).map(chunk => chunk.id));
+ // #7172: a vector whose recorded input (#5553: column, model, dimensions, wrapper tier and exact input) is one the
+ // current page accepts is current, whatever the page-level signature says; only the stamp is missing, so it is
+ // restamped (embedPage) rather than paid for again.
+ const target = await embeddingWriteTarget(tx);
+ const accepted = (chunk: { chunk_text: string; chunk_source: string | null; embedding_input_hash: string | null }) => chunk.embedding_input_hash !== null
+ && target.column.name === column.name && model === undefined
+ && acceptedEmbeddingInputHashes(embeddingInputContext(target, prepared.snapshot.page.title, prepared.snapshot.page.corpus_generation ?? null, prepared.chunks),
+ prepared.snapshot.page.contextual_retrieval_mode, chunk).includes(chunk.embedding_input_hash);
+ const complete = new Set(completion.filter(chunk => chunk.embedded === true && (chunk.stamped === true || accepted(chunk))).map(chunk => chunk.id));
const pending = prepared.chunks.filter(chunk => !complete.has(chunk.id));
- return { prepared, pending: pending.length && prepared.snapshot.page.contextual_retrieval_mode === 'per_chunk_synopsis' ? prepared.chunks : pending };
+ return { prepared, pending: pending.length && prepared.snapshot.page.contextual_retrieval_mode === 'per_chunk_synopsis' ? prepared.chunks : pending,
+ restamp: completion.some(chunk => chunk.stamped !== true) };
});
}
@@ -525,6 +536,9 @@ async function embedPage(engine: BrainEngine, config: GBrainConfig, effect: Pers
}
return;
}
+ if (projection.restamp && !(await installPageEmbeddings(engine, prepared, [], signature)).complete) {
+ await completeEffect(engine, effect, { embedding: 'superseded', reason: 'revision_changed' }); return;
+ }
await finishPage(engine, effect, snapshot);
}
diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.ts
index 38c3c6ba1e..239a976be9 100644
--- a/src/core/persistence/import-prepare.ts
+++ b/src/core/persistence/import-prepare.ts
@@ -251,7 +251,7 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wri
? await importImageFile(engine, p.inputPath, p.sourcePath, { ...source, noEmbed: p.noEmbed, bytes: imageBytes, prepare })
: code
? await importCodeFile(engine, p.sourcePath, content, { ...source, noEmbed: true, prepare })
- : await importFromContent(engine, row.slug, content, { ...source, noEmbed: true, remote: false, preserveGateMarkers: true, prepare, fences: 'coordinated', writeGate: await ownerGateInput(engine, row, parseMarkdown(content, row.slug).frontmatter, p.sourcePath),
+ : await importFromContent(engine, row.slug, content, { ...source, noEmbed: true, remote: false, preserveGateMarkers: true, prepare, fences: 'coordinated', boundedChunkWrites: true, writeGate: await ownerGateInput(engine, row, parseMarkdown(content, row.slug).frontmatter, p.sourcePath),
coordinated: true, existingSnapshot: snapshot, activePack: p.activePack, sourcePath: p.sourcePath, filename: basename(p.sourcePath, '.md'), allowEmptyOverwrite: true,
segmentedOwner: { kind: 'import', principalKind: row.principal_kind, principalId: row.principal_id, baseRevision: snapshot?.revision ?? null } });
if (!prepared && result.refusal?.code === 'invalid_fence') throw managedImportRefusal(result.refusal, p.sourcePath);
@@ -288,10 +288,10 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wri
await project(tx, final?.page.id);
if (applied?.segmented) { if (applied.segmented.complete && live) await sealSegmentedPage(tx, Number(live.page.id)); }
else if (applied?.chunkerSeal !== undefined) await sealImportedPage(tx, row.slug, row.source_id, live, applied.chunkerSeal, applied.pageId);
- else if (live) await sealPageTextProjection(tx, row.slug, row.source_id, live);
+ else if (live && !applied?.projectionPending) await sealPageTextProjection(tx, row.slug, row.source_id, live);
}
mutation.postimage = final;
- } else if (!ready.noop && !image) await sealPageTextProjection(tx, row.slug, row.source_id);
+ } else if (!ready.noop && !image && !applied?.projectionPending) await sealPageTextProjection(tx, row.slug, row.source_id);
// #6188: the canonical file is written from the normalized page; the outcome reports what Tier 1 rewrote.
return { ...result, parsedPage: undefined, imported_file: true, source_id: row.source_id, fences_normalized: result.fences_normalized?.length
? pageFencesNormalized({ sourceId: row.source_id, slug: row.slug, fixes: result.fences_normalized, writer: row.principal_kind, path: p.sourcePath, remote: false }) : undefined };
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 2280bf736a..8b5a8fdb27 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -791,7 +791,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
const lean = options.coordinated === true && !targetDeleted && row.operation !== 'restore_page' && !versionTags;
enterClaimStep(clock, 'import_content', undefined, 'db');
const result = await importFromContent(engine, row.slug, content, {
- ...source, noEmbed: true, remote: row.authority.remote, activePack, fences: projected ? 'coordinated' : 'lenient', coordinated: lean,
+ ...source, noEmbed: true, remote: row.authority.remote, activePack, fences: projected ? 'coordinated' : 'lenient', coordinated: lean, boundedChunkWrites: true,
segmentedOwner: { kind: row.operation === 'edit_page' ? 'edit' : 'put', principalKind: row.principal_kind, principalId: row.principal_id, baseRevision: observedRevision },
...(lean ? { existingSnapshot: snapshot } : {}),
// #6259: only owner-tier intents keep gate-owned markers; an ordinary put_page, local or remote, has them stripped.
@@ -895,7 +895,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
const prior = snapshot ? await storedPageTier(tx, row.source_id, row.slug) : null;
// ENG-1: a managed fence edit keeps the page's tier; CEO-12: an agent rewrite that lowers a page files a queue item.
const applied = await (isFenceEditWrite(row) ? withTrustKeep(tx, ['pages'], () => ready.apply(tx, lean ? preimage : undefined)) : ready.apply(tx, lean ? preimage : undefined));
- projectionPending = applied?.segmented?.complete === false;
+ projectionPending = applied?.segmented?.complete === false || applied?.projectionPending === true;
segmentedWrite = applied?.segmented !== undefined;
lowered = prior ? await recordAgentPageLowering(tx, row, { tier: prior, revision: snapshot!.revision }) : null;
// Mandatory metadata shares publication rollback; exact no-ops never heal it. These, and the
@@ -925,7 +925,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
await verifyPageReadable(tx, row.slug, ready.contentHash!, row.source_id, 'importFromContent', live?.page ?? null);
if (applied?.segmented) { if (applied.segmented.complete && live) await sealSegmentedPage(tx, Number(live.page.id)); }
else if (applied?.chunkerSeal !== undefined) await sealImportedPage(tx, row.slug, row.source_id, live, applied.chunkerSeal, applied.pageId);
- else if (live) await sealPageTextProjection(tx, row.slug, row.source_id, live);
+ else if (live && !applied?.projectionPending) await sealPageTextProjection(tx, row.slug, row.source_id, live);
if (core) await core.record(tx, final?.revision ?? null);
publication.postimage = final;
} else {
@@ -933,7 +933,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
// Index installation and terminal receipt share this transaction. The import sealed the projection
// as its last revision-changing step; only a later revision change (restore, tags, links, delete) reseals.
if (applied?.segmented) { if (applied.segmented.complete && applied.pageId !== undefined) await sealSegmentedPage(tx, applied.pageId); }
- else if (!(applied?.sealed && row.operation !== 'restore_page' && !versionTags && !links && !targetDeleted)) await sealPageTextProjection(tx, row.slug, row.source_id);
+ else if (!applied?.projectionPending && !(applied?.sealed && row.operation !== 'restore_page' && !versionTags && !links && !targetDeleted)) await sealPageTextProjection(tx, row.slug, row.source_id);
if (core) await core.record(tx, (await tx.readPageSnapshot(row.slug, source))?.revision ?? null);
}
}
@@ -946,7 +946,8 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
status: noop ? 'skipped' : row.operation === 'restore_page' ? 'restored' : row.operation === 'revert_version' ? 'reverted' : 'created_or_updated',
slug: row.slug, source_id: row.source_id, chunks: ready.result.chunks, noop, ...(projectionPending ? { projection: 'pending' } : {}),
// Wave B: whether search sees a segmented write at commit; a pending one is re-read whenever its receipt is served (searchable.ts).
- ...(segmentedWrite ? { searchable: isQuarantined(ready.parsedPage.frontmatter) ? false : projectionPending ? 'pending' : true } : {}),
+ ...(segmentedWrite ? { searchable: isQuarantined(ready.parsedPage.frontmatter) ? false : projectionPending ? 'pending' : true }
+ : projectionPending ? { searchable: 'pending' } : {}),
...sizeState,
...(ready.result.chunks === 0 && !projectionPending ? {chunk_skip_reason: noop ? 'write_skipped'
: isEmbedSkipped(ready.parsedPage.frontmatter) || isQuarantined(ready.parsedPage.frontmatter) ? 'embed_skip' : 'empty_body'} : {}),
diff --git a/src/core/persistence/prepared-import.ts b/src/core/persistence/prepared-import.ts
index eeb825e1cb..f976558e8d 100644
--- a/src/core/persistence/prepared-import.ts
+++ b/src/core/persistence/prepared-import.ts
@@ -11,6 +11,8 @@ import type { SegmentedImport } from './segmented-apply.ts';
* to the caller, which stamps it with its text seal (`sealImportedPage`).
*/
export interface PreparedImportApplied { pageId?: number; sealed: boolean; chunkerSeal?: number;
+ /** #7172: the apply left the page's chunk rows for its afterCommit (`continueDeferredProjection`); the caller seals nothing. */
+ projectionPending?: true;
/** Wave B: the apply published a segmented body; when `complete` the caller seals it with `sealSegmentedPage`, never the inline seals. */
segmented?: { complete: boolean } }
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index d113ad11c1..44e5ee036d 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -839,7 +839,7 @@ async function prepareSyncMutation(unbounded: BrainEngine, row: WriteRequest, _c
let prepared: PreparedContentImport | undefined;
enterClaimStep(clock, 'import_content', undefined, 'db');
// #6188: the import reuses this screen's fence verdict for the same bytes (one fence scan per file at prepare).
- const importOptions = { ...source, noEmbed: true, remote: row.authority.remote, preserveGateMarkers: true, activePack, coordinated: true, fences: 'coordinated' as const, writeGate: await ownerGateInput(engine, row, parsedInput.frontmatter, p.sourcePath),
+ const importOptions = { ...source, noEmbed: true, remote: row.authority.remote, preserveGateMarkers: true, activePack, coordinated: true, fences: 'coordinated' as const, boundedChunkWrites: true as const, writeGate: await ownerGateInput(engine, row, parsedInput.frontmatter, p.sourcePath),
...(importContent === p.content && screen.status === 'importable' ? { fenceScreen: screen.fences ?? null } : {}),
filename: basename(p.sourcePath).replace(/\.mdx?$/i, ''), sourcePath: p.sourcePath, allowEmptyOverwrite: true,
segmentedOwner: { kind: 'sync' as const, principalKind: row.principal_kind, principalId: row.principal_id, baseRevision: base?.revision ?? null } };
@@ -931,7 +931,7 @@ async function prepareSyncMutation(unbounded: BrainEngine, row: WriteRequest, _c
if (applied.noop) return;
if (installed?.segmented) { if (installed.segmented.complete && live) await sealSegmentedPage(tx, Number(live.page.id)); }
else if (installed?.chunkerSeal !== undefined) await sealImportedPage(tx, row.slug, row.source_id, live, installed.chunkerSeal, installed.pageId);
- else if (live) await sealPageTextProjection(tx, row.slug, row.source_id, live);
+ else if (live && !installed?.projectionPending) await sealPageTextProjection(tx, row.slug, row.source_id, live);
},
() => releaseHold(tx),
async () => { if (final) await recordSyncImportProvenance(tx, { ...importProvenance, page_id: Number(final.page.id), revision: final.revision,
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 15d79af331..94280aa7a2 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -428,6 +428,7 @@ test/sync-waiver-run-imports.test.ts
test/take-resolution-survives-publish.test.ts
test/takes-vector-lifecycle-5885.serial.test.ts
test/terminal-failures-6650.test.ts
+test/timeline-chunk-reuse.test.ts
test/trust-channel-writes.test.ts
test/trust-guarded-supersession.test.ts
test/trust-held-removals.test.ts
diff --git a/test/timeline-chunk-reuse.test.ts b/test/timeline-chunk-reuse.test.ts
new file mode 100644
index 0000000000..b661296932
--- /dev/null
+++ b/test/timeline-chunk-reuse.test.ts
@@ -0,0 +1,235 @@
+/**
+ * #7172: a managed timeline entry keeps the passages it did not change, and its publication stays within a bounded
+ * number of vector-index writes.
+ *
+ * 1. Protects: an entry appended at the end of a page whose stored page signature is stale (NULL, or an older format)
+ * keeps every unchanged passage row and its vector, and the embedding effect embeds only the passages whose text
+ * changed (effects.ts readEmbeddingEffectProjection accepts a vector whose recorded input is current and restamps
+ * the page); an entry at the top of a descending timeline keeps every passage whose text is unchanged under its
+ * old id, renumbered (import-file.ts, page-state/chunk-moves.ts), and the page ends with the passages a fresh
+ * import of the same body gives; a publication whose replacement needs more than CHUNK_ROW_WRITE_BUDGET row
+ * writes commits with its projection pending and finishes in bounded post-commit steps
+ * (page-state/projections.ts continueDeferredProjection), resuming after an interrupted step.
+ * 2. Fails when: a stale page signature re-embeds every passage; a passage whose index moves is deleted and
+ * re-inserted; a top insert publishes every moved passage inside the publication's 5 s statement bound (the
+ * PostgreSQL probe charges each vector-index write 0.6 s and shows the write ending 57014 / write_interrupted).
+ * 3. PGLite always; PostgreSQL when DATABASE_URL is set (test/postgres-unit-arms.txt). Work is counted, never timed,
+ * except the PostgreSQL probe's injected per-row delay.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { openAppendBrain, type AppendBrain } from './helpers/append-brain.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { runEmbedCore } from '../src/commands/embed.ts';
+import { currentEmbeddingSignature } from '../src/core/embedding.ts';
+import { rebuildPendingPageProjections } from '../src/core/page-state/projections.ts';
+import { CHUNK_ROW_WRITE_BUDGET } from '../src/core/page-state/chunk-moves.ts';
+
+const WORDS = 'alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike november oscar papa quebec romeo sierra tango uniform victor whiskey xray yankee zulu'.split(' ');
+function prose(seed: number, words: number): string {
+ const out: string[] = [];
+ for (let i = 0; i < words; i++) out.push(WORDS[(seed * 7 + i * 13 + (i % 5)) % WORDS.length]! + (i % 17 === 16 ? '.' : ''));
+ return out.join(' ');
+}
+/** Compiled truth of `truth` paragraphs and a timeline of `bullets` dated bullets of 15 to 84 words, ascending or descending. */
+function page(truth: number, bullets: number, order: 'ascending' | 'descending'): string {
+ const body = Array.from({ length: truth }, (_, i) => prose(i + 1, 120)).join('\n\n');
+ const lines = Array.from({ length: bullets }, (_, i) => {
+ const day = order === 'ascending' ? i : bullets - 1 - i;
+ return `- **${new Date(Date.UTC(2025, 0, 1 + day)).toISOString().slice(0, 10)}** | manual — Example event ${day} ${prose(day + 100, 15 + (day * 37) % 70)}`;
+ });
+ return `---\ntitle: Example page\ntype: note\n---\n\n${body}\n\n<!-- timeline -->\n\n## Timeline\n\n${lines.join('\n')}\n`;
+}
+
+interface Row { id: number; chunk_index: number; chunk_source: string; chunk_text: string; embedded_at: string | null; vector: boolean }
+
+for (const kind of testBackends()) {
+ describe(`#7172 timeline chunk reuse (${kind})`, () => {
+ let brain: AppendBrain;
+ beforeAll(async () => { brain = await openAppendBrain(kind); }, 600_000);
+ afterAll(() => brain.close(), 120_000);
+
+ const rows = (slug: string) => brain.engine.executeRaw<Row>(`SELECT c.id, c.chunk_index, c.chunk_source, c.chunk_text,
+ c.embedded_at::text AS embedded_at, c.embedding IS NOT NULL AS vector
+ FROM content_chunks c JOIN pages p ON p.id=c.page_id WHERE p.source_id='default' AND p.slug=$1 ORDER BY c.chunk_index`, [slug]);
+ const pageState = async (slug: string) => (await brain.engine.executeRaw<{ sealed: boolean; signature: string | null }>(
+ `SELECT text_projection_revision IS NOT DISTINCT FROM knowledge_revision AS sealed, embedding_signature AS signature
+ FROM pages WHERE source_id='default' AND slug=$1`, [slug]))[0]!;
+ /** Until no persistence effect is queued or running (the background consumer drains them). */
+ const settle = async () => {
+ for (let i = 0; i < 600; i++) {
+ const [row] = await brain.engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_effects WHERE state IN ('queued','running')");
+ if (Number(row!.n) === 0) return;
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+ throw new Error('persistence effects did not drain');
+ };
+ /** A page published through put_page, every passage embedded and the effects drained. */
+ const publish = async (slug: string, content: string) => {
+ const put = await brain.call('put_page', { slug, content, request_id: randomUUID() });
+ expect(put.isError).toBe(false);
+ await settle();
+ await runEmbedCore(brain.engine, { stale: true, quiet: true } as never);
+ await settle();
+ const stored = await rows(slug);
+ expect(stored.every(row => row.vector)).toBe(true);
+ expect((await pageState(slug)).sealed).toBe(true);
+ return stored;
+ };
+ const addEntry = (slug: string, date: string, summary: string) =>
+ brain.call('add_timeline_entry', { slug, date, summary, source: 'manual', request_id: randomUUID() });
+ const bodyOf = async (slug: string) => {
+ const stored = await brain.body(slug);
+ return `---\ntitle: Example page\ntype: note\n---\n\n${stored.truth}\n\n<!-- timeline -->\n\n${stored.timeline}\n`;
+ };
+ /** The passages a fresh import of the page's current body gives, as (index, source, text). */
+ const freshPassages = async (slug: string) => {
+ const twin = `notes/twin-${randomUUID().slice(0, 8)}`;
+ await brain.seed(twin, await bodyOf(slug));
+ return (await rows(twin)).map(row => [row.chunk_index, row.chunk_source, row.chunk_text]);
+ };
+ const passages = (stored: Row[]) => stored.map(row => [row.chunk_index, row.chunk_source, row.chunk_text]);
+ /** A long entry: at the top of these timelines it adds one passage there and shifts every passage below by one. */
+ const LONG = `Example long entry ${prose(7, 450)}`;
+
+ for (const stale of ['null', 'older-format'] as const) {
+ test(`an entry at the end keeps every unchanged passage and its vector when the page signature is ${stale}`, async () => {
+ const slug = `notes/example-stale-${stale}`;
+ const before = await publish(slug, page(24, 60, 'ascending'));
+ await brain.engine.executeRaw('UPDATE pages SET embedding_signature=$2 WHERE source_id=$3 AND slug=$1',
+ [slug, stale === 'null' ? null : 'text-embedding-3-large:1536', 'default']);
+ brain.embedded.length = 0;
+ const added = await addEntry(slug, '2026-10-19', 'Example entry at the end');
+ expect(added.isError).toBe(false);
+ await settle();
+ const after = await rows(slug);
+ const old = new Map(before.map(row => [row.id, row]));
+ const kept = after.filter(row => old.has(row.id));
+ const unchanged = after.filter(row => before.some(prior => prior.chunk_source === row.chunk_source && prior.chunk_text === row.chunk_text));
+ expect(kept.length).toBe(unchanged.length);
+ expect(kept.length).toBeGreaterThanOrEqual(before.length - 1);
+ // A kept passage keeps its vector: never embedded again, so its embedding time is the old one.
+ for (const row of kept) expect(row.embedded_at).toBe(old.get(row.id)!.embedded_at);
+ const oldTexts = new Set(before.map(row => row.chunk_text));
+ expect(brain.embedded.filter(text => oldTexts.has(text))).toEqual([]);
+ expect(brain.embedded.length).toBe(after.length - kept.length);
+ expect(after.every(row => row.vector)).toBe(true);
+ const state = await pageState(slug);
+ expect(state.sealed).toBe(true);
+ expect(state.signature).toBe(currentEmbeddingSignature());
+ }, 600_000);
+ }
+
+ test('an entry at the top of a descending timeline keeps every unchanged passage under its id, renumbered', async () => {
+ const slug = 'notes/example-descending';
+ const before = await publish(slug, page(12, 380, 'descending'));
+ expect(before.filter(row => row.chunk_source === 'timeline').length).toBeGreaterThan(40);
+ brain.embedded.length = 0;
+ const added = await addEntry(slug, '2026-10-19', LONG);
+ expect(added.isError).toBe(false);
+ await settle();
+ const after = await rows(slug);
+ const old = new Map(before.map(row => [row.id, row]));
+ const kept = after.filter(row => old.has(row.id));
+ const key = (row: Row) => `${row.chunk_source}\0${row.chunk_text}`;
+ const beforeKeys = new Set(before.map(key));
+ const unchanged = after.filter(row => beforeKeys.has(key(row)));
+ console.log(`[${kind}] top insert: ${before.length} -> ${after.length} passages, ${unchanged.length} unchanged, ${kept.length} kept, ${brain.embedded.length} embedded`);
+ // Every passage whose text is unchanged keeps its row (id, vector, embedding time); only the others are new.
+ expect(kept.map(key).sort()).toEqual(unchanged.map(key).sort());
+ expect(kept.filter(row => row.chunk_index !== old.get(row.id)!.chunk_index).length).toBeGreaterThan(CHUNK_ROW_WRITE_BUDGET);
+ for (const row of kept) expect(row.embedded_at).toBe(old.get(row.id)!.embedded_at);
+ expect(brain.embedded.length).toBe(after.length - kept.length);
+ expect(after.every(row => row.vector)).toBe(true);
+ expect((await pageState(slug)).sealed).toBe(true);
+ expect(passages(after)).toEqual(await freshPassages(slug));
+ }, 600_000);
+
+ test('an interrupted continuation leaves the entry committed and the drain finishes it', async () => {
+ const slug = 'notes/example-interrupted';
+ await publish(slug, page(12, 380, 'descending'));
+ // Every chunk_index move past the first CHUNK_ROW_WRITE_BUDGET fails, as a crash after the first step would.
+ await brain.engine.executeRaw(`CREATE TABLE IF NOT EXISTS probe_7172_moves (n int)`);
+ await brain.engine.executeRaw(`CREATE OR REPLACE FUNCTION probe_7172_interrupt() RETURNS trigger LANGUAGE plpgsql AS $$
+ BEGIN
+ IF NEW.chunk_index IS DISTINCT FROM OLD.chunk_index THEN
+ INSERT INTO probe_7172_moves VALUES (1);
+ IF (SELECT count(*) FROM probe_7172_moves) > ${CHUNK_ROW_WRITE_BUDGET} THEN RAISE EXCEPTION 'probe_7172 interrupted'; END IF;
+ END IF;
+ RETURN NEW;
+ END $$`);
+ await brain.engine.executeRaw('CREATE TRIGGER probe_7172_interrupt BEFORE UPDATE ON content_chunks FOR EACH ROW EXECUTE FUNCTION probe_7172_interrupt()');
+ let added;
+ try { added = await addEntry(slug, '2026-10-19', LONG); }
+ finally {
+ await brain.engine.executeRaw('DROP TRIGGER IF EXISTS probe_7172_interrupt ON content_chunks');
+ await brain.engine.executeRaw('DROP FUNCTION IF EXISTS probe_7172_interrupt()');
+ await brain.engine.executeRaw('DROP TABLE IF EXISTS probe_7172_moves');
+ }
+ expect(added!.isError).toBe(false);
+ // The entry is committed; the passages are not sealed yet, and the job names the deferred replacement.
+ expect((await brain.body(slug)).timeline).toContain('Example long entry');
+ expect((await pageState(slug)).sealed).toBe(false);
+ const [job] = await brain.engine.executeRaw<{ reason: string }>("SELECT reason FROM page_projection_jobs WHERE slug=$1", [slug]);
+ expect(job?.reason).toBe('chunk_replacement_deferred');
+ const drained = await rebuildPendingPageProjections(brain.engine, 10);
+ expect(drained.rebuilt).toBeGreaterThanOrEqual(1);
+ await settle();
+ await runEmbedCore(brain.engine, { stale: true, quiet: true } as never);
+ const after = await rows(slug);
+ expect((await pageState(slug)).sealed).toBe(true);
+ expect(after.every(row => row.vector)).toBe(true);
+ expect(passages(after)).toEqual(await freshPassages(slug));
+ }, 600_000);
+
+ if (kind === 'postgres') {
+ test('probe: with each indexed row write charged 0.6 s, a top insert commits and no transaction makes more than the budget', async () => {
+ const slug = 'notes/example-slow-index';
+ await publish(slug, page(12, 380, 'descending'));
+ // Each new row version that adds index entries (an insert; an update of chunk_index, the text or the vector, none
+ // of them HOT) costs 0.6 s, as on a large uncached index, and is counted per transaction.
+ await brain.engine.executeRaw('CREATE TABLE probe_7172_writes (tx bigint)');
+ await brain.engine.executeRaw(`CREATE OR REPLACE FUNCTION probe_7172_slow() RETURNS trigger LANGUAGE plpgsql AS $$
+ BEGIN
+ IF TG_OP = 'INSERT' OR NEW.chunk_index IS DISTINCT FROM OLD.chunk_index OR NEW.chunk_text IS DISTINCT FROM OLD.chunk_text
+ OR NEW.embedding IS DISTINCT FROM OLD.embedding THEN
+ INSERT INTO probe_7172_writes VALUES (txid_current());
+ PERFORM pg_sleep(0.6);
+ END IF;
+ RETURN NEW;
+ END $$`);
+ await brain.engine.executeRaw('CREATE TRIGGER probe_7172_slow BEFORE INSERT OR UPDATE ON content_chunks FOR EACH ROW EXECUTE FUNCTION probe_7172_slow()');
+ let receipt: Record<string, any> = {};
+ let interruptions: number | undefined;
+ let writes: Array<{ n: number }> = [];
+ try {
+ const added = await addEntry(slug, '2026-10-19', LONG);
+ const requestId = added.body.write_request?.request_id ?? added.body.request_id;
+ // The reply waits a bounded time; the receipt says how the write ended.
+ receipt = added.body;
+ const state = () => receipt.write_request?.state ?? receipt.state;
+ for (let i = 0; i < 1500 && state() !== 'committed' && state() !== 'failed'; i++) {
+ await new Promise(resolve => setTimeout(resolve, 200));
+ receipt = (await brain.call('get_write_request', { request_id: requestId })).body;
+ }
+ for (let i = 0; i < 1500 && state() === 'committed' && !(await pageState(slug)).sealed; i++) await new Promise(resolve => setTimeout(resolve, 200));
+ [{ transient_interruptions: interruptions }] = await brain.engine.executeRaw<{ transient_interruptions: number }>(
+ 'SELECT transient_interruptions FROM persistence_requests WHERE request_id=$1', [requestId]);
+ writes = await brain.engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM probe_7172_writes GROUP BY tx ORDER BY 1 DESC');
+ } finally {
+ await brain.engine.executeRaw('DROP TRIGGER IF EXISTS probe_7172_slow ON content_chunks');
+ await brain.engine.executeRaw('DROP FUNCTION IF EXISTS probe_7172_slow()');
+ await brain.engine.executeRaw('DROP TABLE IF EXISTS probe_7172_writes');
+ }
+ console.log(`[probe] state ${receipt.write_request?.state ?? receipt.state}, interruptions ${interruptions}, row writes per transaction ${JSON.stringify(writes.map(w => w.n))}`);
+ if ((receipt.write_request?.state ?? receipt.state) !== 'committed') console.log(JSON.stringify(receipt).slice(0, 1200));
+ expect(receipt.write_request?.state ?? receipt.state).toBe('committed');
+ expect(Number(interruptions)).toBe(0);
+ expect(Number(writes[0]?.n ?? 0)).toBeLessThanOrEqual(CHUNK_ROW_WRITE_BUDGET);
+ await settle();
+ expect((await pageState(slug)).sealed).toBe(true);
+ expect(passages(await rows(slug))).toEqual(await freshPassages(slug));
+ }, 900_000);
+ }
+ });
+}