Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(#7172): bound vector-index writes, not every chunk row write

garrytan99518743176e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0c6dbafabe..1f3d5d03db 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,11 +19,11 @@ identifiers and attribution are available in the pre-removal Git revision
| 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 managed put_page, edit_page, add_timeline_entry, tag write, import or sync 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 |
+| A managed put_page, edit_page, add_timeline_entry, tag write, import or sync whose passages need more than 5 vector-index writes (a passage that carries a vector, inserted or renumbered) | 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 vector-index writes each, then the projection is sealed. Passages without a vector (new text, a new page) are still written in the publication, as before |
| 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.
+The bound of 5 is derived in `src/core/page-state/chunk-moves.ts` (`CHUNK_VECTOR_WRITE_BUDGET`): a row version that carries a vector adds an HNSW entry, a graph search over the whole index that nothing amortizes across rows, while one without a vector adds no HNSW entry and only cheap b-tree and GIN pending-list entries (measured on pgvector: 300 passages inserted in 2.2 s with vectors and 0.06 s without; 300 renumbered in about 1 s with vectors and 0.002 s without). The slowest reported rate on a large index is about 0.5 s per vector-carrying 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
@@ -34,7 +34,7 @@ The 5-row bound is derived in `src/core/page-state/chunk-moves.ts` (`CHUNK_ROW_W
### 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).
+- New `src/core/page-state/chunk-moves.ts`: the vector-index 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, holding the page's queue row under a claim it renews each step (the lease a segmented projection claim uses); the projection drain resumes a page whose steps stopped (queue reason `chunk_replacement_deferred`). A group publication now runs its members' post-commit work, as a single publication does.
- Writes that wrap a page publication in their own (takes, the facts fence, maintenance pages) still replace passages in one transaction.
- `readEmbeddingEffectProjection` accepts a vector whose recorded input hash is one the current page accepts, whatever the page-level signature says, and restamps the page.
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index 808840fe3d..bb0cb60426 100644
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@ -7,7 +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/chunk-moves.ts` — #7172: `CHUNK_VECTOR_WRITE_BUDGET` (5), the most new `content_chunks` row versions carrying a vector (inserts, and non-HOT updates of `chunk_index`, text or vector; each adds an HNSW entry) one transaction of a managed chunk replacement makes, with its derivation from the publication's 5 s statement bound (a version without a vector is not counted); `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 431afcdf23..09c34b89b8 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1024,7 +1024,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ 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 put_page, edit_page, add_timeline_entry, add_tag or remove_tag, 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: 'A managed put_page, edit_page, add_timeline_entry, add_tag or remove_tag, managed import or sync whose passages need more than 5 vector-index writes (a passage carrying a vector, inserted or renumbered) commits the page first and finishes its passages in post-commit transactions of at most 5 vector-index 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.' },
];
diff --git a/src/core/import-chunk-reuse.ts b/src/core/import-chunk-reuse.ts
index f576cff754..7910269be1 100644
--- a/src/core/import-chunk-reuse.ts
+++ b/src/core/import-chunk-reuse.ts
@@ -13,8 +13,11 @@ 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 }
+/**
+ * A stored row an import keeps: its id and the index it holds now (a kept row whose new chunk sits elsewhere moves
+ * there). `vector`: the row holds one, so moving it is a vector-index write (page-state/chunk-moves.ts).
+ */
+export interface KeptChunkRow { id: number; chunk_index: number; vector: boolean }
/**
* A13 reuse for one page import: copies each stored vector the reuse gate
@@ -70,7 +73,7 @@ export async function reuseStoredChunkVectors(
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);
+ 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, vector: true } : 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
@@ -81,7 +84,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, { id: row.id, chunk_index: row.chunk_index });
+ if (identity(row) === identity(into[i]!)) reused.set(i, { id: row.id, chunk_index: row.chunk_index, vector: false });
}
}
return reused;
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 1fb0895e53..0ced88b7c5 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -762,8 +762,8 @@ export async function importFromContent(
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 changes index in place; a managed publication over CHUNK_ROW_WRITE_BUDGET row
- // writes deletes the rows it does not keep, commits the page pending and finishes after commit (chunk-moves.ts).
+ // #7172: a kept row whose chunk moved changes index in place; a managed publication over CHUNK_VECTOR_WRITE_BUDGET
+ // vector-index writes deletes the rows it does not keep, commits the page pending and finishes after commit (chunk-moves.ts).
const chunkWrites = planImportChunkWrites(fresh, kept, !segmented && !!opts.prepare && opts.boundedChunkWrites === true);
const deferChunks = chunkReplacementDeferred = chunkWrites.defer;
let written: Page | undefined;
diff --git a/src/core/page-state/chunk-moves.ts b/src/core/page-state/chunk-moves.ts
index 571be6c387..d4ae5a348d 100644
--- a/src/core/page-state/chunk-moves.ts
+++ b/src/core/page-state/chunk-moves.ts
@@ -2,30 +2,40 @@ import type { BrainEngine } from '../engine.ts';
import type { ChunkInput } from '../types.ts';
/**
- * #7172: the most row writes one page's chunk replacement makes in one transaction.
+ * #7172: the most vector-index writes one transaction of a page's chunk replacement makes.
*
- * 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`).
+ * A vector-index write is a new content_chunks row version that carries a vector: an inserted passage with one, or an
+ * UPDATE of a passage with one (moving it to another `chunk_index` changes an indexed column, so the update is not HOT
+ * and the new version gets an entry in every index, the HNSW index included). Each such entry is an HNSW insert: a
+ * graph search over the whole index whose pages have no locality with the page being written, so nothing amortizes
+ * across rows and on a large uncached index each costs disk reads. A version with a NULL vector gets no HNSW entry
+ * (pgvector skips NULL), and its other entries are cheap: the b-tree entries of one page land on the same leaves and
+ * the search-vector GIN entries go to its pending list. Measured on pgvector with a 20,000-row 1,536-dimension HNSW
+ * index, warm: 300 passages inserted with vectors took 2.2 s and without 0.06 s; 300 passages renumbered took 0.7 to
+ * 1.3 s with vectors and 0.002 s without. So only vector-carrying versions are counted, and inserting passages
+ * without vectors, deleting rows and clearing a vector are not. The slowest vector-carrying passage writes reported on
+ * a large production index ran at about 0.5 s per row, so the bound charges 0.5 s per vector-index 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, the passages without vectors, 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
+ * vector-index writes each (`continueDeferredProjection`).
*/
-export const CHUNK_ROW_WRITE_BUDGET = 5;
+export const CHUNK_VECTOR_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 }
+/**
+ * A stored chunk row that keeps its id and vector and changes index (`to`), with the span its new chunk records.
+ * `vectorless`: the row has no vector, so moving it makes no vector-index write.
+ */
+export interface ChunkMove { id: number; from: number; to: number; projected_byte_start?: number | null; projected_byte_end?: number | null; vectorless?: boolean }
/**
* 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; `pending` and `at` are the moves left and the occupied indexes once the waves ran.
+ * most `budget` vector-index writes (a move of a row with a vector; a vectorless move is free). `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, a vectorless one when the cycle has one. `done` says every move
+ * fits; `updates` counts the vector-index writes; `pending` and `at` are the moves left and the occupied indexes once
+ * the waves ran.
*/
export function planMoveWaves(moves: readonly ChunkMove[], occupied: ReadonlyMap<number, number>, budget: number):
{ waves: ChunkMove[][]; updates: number; done: boolean; pending: ChunkMove[]; at: Map<number, number> } {
@@ -33,31 +43,38 @@ export function planMoveWaves(moves: readonly ChunkMove[], occupied: ReadonlyMap
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 }];
+ const cost = (move: ChunkMove) => move.vectorless ? 0 : 1;
+ while (pending.length) {
+ const open = pending.filter(move => !at.has(move.to));
+ const free: ChunkMove[] = [];
+ for (const move of open) if (updates + cost(move) <= budget) { free.push(move); updates += cost(move); }
+ const parked = open.length ? undefined : pending.find(move => move.vectorless) ?? (updates < budget ? pending[0] : undefined);
+ if (!free.length && !parked) break;
+ const wave = parked ? [{ ...parked, to: -1 - parked.to }] : free;
+ if (parked) updates += cost(parked);
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;
+ if (parked) parked.from = wave[0]!.to;
+ else pending = pending.filter(move => !free.includes(move));
}
return { waves, updates, done: pending.length === 0, pending, at };
}
/**
- * #7172: an import's chunk row writes. `kept` maps a new chunk's position in `fresh` to the stored row it keeps; a kept
- * row whose chunk sits at another index moves there (`waves`). With `bounded` (a managed publication), `defer` says the
- * moves and inserts pass CHUNK_ROW_WRITE_BUDGET, so the publication leaves them to `continueDeferredProjection`.
+ * #7172: an import's chunk row writes. `kept` maps a new chunk's position in `fresh` to the stored row it keeps (`vector`:
+ * the row has one); a kept row whose chunk sits at another index moves there (`waves`). With `bounded` (a managed
+ * publication), `defer` says the vector-index writes (moves of rows with a vector, inserts of chunks carrying one) pass
+ * CHUNK_VECTOR_WRITE_BUDGET, so the publication leaves the replacement to `continueDeferredProjection`.
*/
-export function planImportChunkWrites(fresh: readonly ChunkInput[], kept: ReadonlyMap<number, { id: number; chunk_index: number }>, bounded: boolean):
+export function planImportChunkWrites(fresh: readonly ChunkInput[], kept: ReadonlyMap<number, { id: number; chunk_index: number; vector: boolean }>, bounded: boolean):
{ waves: ChunkMove[][]; defer: boolean } {
const moves = [...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;
+ to: fresh[i]!.chunk_index, projected_byte_start: fresh[i]!.projected_byte_start ?? null, projected_byte_end: fresh[i]!.projected_byte_end ?? null,
+ ...(row.vector ? {} : { vectorless: true }) }));
+ const vectorInserts = fresh.filter((chunk, i) => !kept.has(i) && (chunk.embedding || chunk.embedding_image)).length;
const plan = planMoveWaves(moves, new Map([...kept.values()].map(row => [row.chunk_index, row.id])),
- bounded ? Math.max(0, CHUNK_ROW_WRITE_BUDGET - inserts) : Number.POSITIVE_INFINITY);
- return { waves: plan.waves, defer: bounded && fresh.length > 0 && (!plan.done || inserts > CHUNK_ROW_WRITE_BUDGET) };
+ bounded ? Math.max(0, CHUNK_VECTOR_WRITE_BUDGET - vectorInserts) : Number.POSITIVE_INFINITY);
+ return { waves: plan.waves, defer: bounded && fresh.length > 0 && (!plan.done || vectorInserts > CHUNK_VECTOR_WRITE_BUDGET) };
}
/** One UPDATE per wave; a landed row takes its new chunk's span, a parked row keeps its own until it lands. */
diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.ts
index 5f1b1ef04f..fe84665774 100644
--- a/src/core/page-state/projections.ts
+++ b/src/core/page-state/projections.ts
@@ -17,7 +17,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 { applyMoveWaves, CHUNK_VECTOR_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';
@@ -226,7 +226,7 @@ async function planProjectionKeep(tx: BrainEngine, current: PageSnapshot, contex
return { kept, moves, current: kept.filter(currentInput).map(chunk => Number(chunk.id)), provenanceModel: context.provenanceModel, column: context.column };
}
-/** #7172: a deferred chunk replacement's remaining row writes, planned once from what is stored and spent in steps. */
+/** #7172: a deferred chunk replacement's remaining writes, planned once from what is stored and spent in steps. */
interface DeferredReplacement {
current: PageSnapshot; pageId: number; column: ResolvedColumn; moves: ChunkMove[]; at: Map<number, number>; stale: number[]; inserts: ChunkInput[];
/** `chunkRowsFingerprint` after the plan's last committed step: a step that finds another one plans again. */
@@ -264,16 +264,16 @@ async function planDeferredReplacement(tx: BrainEngine, sourceId: string, slug:
/**
* #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 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. The plan (`state`) is made once from what is stored and carried
- * between steps only after a step commits; a step whose page revision or chunk rows differ from what the plan's last
- * step left plans again, so a crash, a concurrent step or a newer write resumes from the stored rows. Each step renews
- * the job's `updated_at`, the lease that keeps the resident's drain off a replacement being continued. 'skipped' when
- * the page is not an unsealed inline Markdown page.
+ * revision, a step moves kept rows (each holds a vector) to their new indexes with at most `budget` vector-index
+ * writes (`planMoveWaves`); the step that finishes the moves clears the vectors whose input is no longer current,
+ * inserts the missing chunks without vectors (neither adds a vector-index entry) and seals the projection. The plan
+ * (`state`) is made once from what is stored and carried between steps only after a step commits; a step whose page
+ * revision or chunk rows differ from what the plan's last step left plans again, so a crash, a concurrent step or a
+ * newer write resumes from the stored rows. Each step renews the job's `updated_at`, the lease that keeps the
+ * resident's drain off a replacement being continued. 'skipped' when the page is not an unsealed inline Markdown page.
*/
export async function continueDeferredProjectionStep(engine: BrainEngine, sourceId: string, slug: string,
- state: { plan?: DeferredReplacement; token?: string } = {}, budget = CHUNK_ROW_WRITE_BUDGET): Promise<'sealed' | 'more' | 'skipped' | 'held'> {
+ state: { plan?: DeferredReplacement; token?: string } = {}, budget = CHUNK_VECTOR_WRITE_BUDGET): Promise<'sealed' | 'more' | 'skipped' | 'held'> {
const claim = `${DEFERRED_CHUNK_CLAIM}:${state.token ??= randomUUID()}`;
const [step, next] = await engine.transaction(async (tx): Promise<['sealed' | 'more' | 'skipped' | 'held', DeferredReplacement?]> => {
await tx.lockPageKeys([{ sourceId, slug }]);
@@ -291,21 +291,16 @@ export async function continueDeferredProjectionStep(engine: BrainEngine, source
const { current, pageId } = base;
const waves = planMoveWaves(base.moves, base.at, budget);
await applyMoveWaves(tx, pageId, waves.waves);
- let left = budget - waves.updates;
- const nulled = waves.done ? base.stale.slice(0, left) : [];
- if (nulled.length) {
- await tx.executeRaw(`UPDATE content_chunks SET ${quoteIdentifier(base.column.name)}=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]);
- }
- left -= nulled.length;
- const stale = base.stale.slice(nulled.length);
- const inserts = waves.done && !stale.length ? base.inserts.slice(0, left) : [];
- if (inserts.length) await tx.upsertChunks(slug, inserts, { sourceId, embeddingColumn: base.column, sealChunkerVersion: MARKDOWN_CHUNKER_VERSION, pageId, deferSeal: true });
const job = [current.sourceIncarnation, slug, current.revision];
- if (!waves.done || stale.length || inserts.length < base.inserts.length) {
+ if (!waves.done) {
await tx.executeRaw('UPDATE page_projection_jobs SET reason=$4,updated_at=now() WHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid', [...job, claim]);
- return ['more', { ...base, moves: waves.pending, at: waves.at, stale, inserts: base.inserts.slice(inserts.length), fingerprint: await chunkRowsFingerprint(tx, pageId) }];
+ return ['more', { ...base, moves: waves.pending, at: waves.at, fingerprint: await chunkRowsFingerprint(tx, pageId) }];
+ }
+ if (base.stale.length) {
+ await tx.executeRaw(`UPDATE content_chunks SET ${quoteIdentifier(base.column.name)}=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, base.stale]);
}
+ if (base.inserts.length) await tx.upsertChunks(slug, base.inserts, { sourceId, embeddingColumn: base.column, sealChunkerVersion: MARKDOWN_CHUNKER_VERSION, pageId, deferSeal: true });
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', job);
return ['sealed'];
diff --git a/test/chunk-moves.test.ts b/test/chunk-moves.test.ts
index eb63e46e91..fcdb557ddc 100644
--- a/test/chunk-moves.test.ts
+++ b/test/chunk-moves.test.ts
@@ -1,12 +1,13 @@
/**
* #7172: planMoveWaves renumbers kept chunk rows without breaking the (page_id, chunk_index) unique index, within a
- * row-write budget.
+ * budget of vector-index writes.
*
* 1. Protects: every planned wave moves rows only onto free indexes (or parks one row of a cycle at a negative index),
- * applying the waves in order reaches every target, the number of row updates never passes the budget, and a plan
- * cut by the budget says so (`done: false`).
- * 2. Fails when: a wave lands a row on an index another row still holds, a cycle never resolves, or a plan spends more
- * updates than its budget.
+ * applying the waves in order reaches every target, the number of updates of rows with a vector never passes the
+ * budget, a move of a row without one is free (it adds no HNSW entry), and a plan cut by the budget says so
+ * (`done: false`).
+ * 2. Fails when: a wave lands a row on an index another row still holds, a cycle never resolves, a plan spends more
+ * vector-row updates than its budget, or a vectorless move is charged or held back.
* 3. Pure; no engine.
*/
import { describe, expect, test } from 'bun:test';
@@ -57,4 +58,22 @@ describe('planMoveWaves', () => {
}
expect(planMoveWaves(moves, at, 20).done).toBe(true);
});
+
+ test('a row without a vector moves free of the budget, and a cycle parks it rather than a row with one', () => {
+ const at = new Map(Array.from({ length: 20 }, (_, i) => [i, 100 + i] as [number, number]));
+ const shift = Array.from({ length: 20 }, (_, i) => ({ ...move(100 + i, i, i + 1), vectorless: true }));
+ const free = planMoveWaves(shift, at, 0);
+ expect(free).toMatchObject({ done: true, updates: 0 });
+ expect([...replay(at, free.waves)].sort((a, b) => a[0] - b[0])).toEqual(Array.from({ length: 20 }, (_, i) => [i + 1, 100 + i]));
+ const mixed = Array.from({ length: 20 }, (_, i) => ({ ...move(100 + i, i, i + 1), ...(i % 2 ? {} : { vectorless: true }) }));
+ const cut = planMoveWaves(mixed, at, 3);
+ expect(cut.updates).toBe(3);
+ expect(cut.done).toBe(false);
+ replay(at, cut.waves);
+ const swap = new Map([[0, 10], [1, 11]]);
+ const parked = planMoveWaves([move(10, 0, 1), { ...move(11, 1, 0), vectorless: true }], swap, 1);
+ expect(parked.waves[0]).toEqual([{ id: 11, from: 1, to: -1, vectorless: true }]);
+ expect(parked).toMatchObject({ done: true, updates: 1 });
+ expect([...replay(swap, parked.waves)].sort((a, b) => a[0] - b[0])).toEqual([[0, 11], [1, 10]]);
+ });
});
diff --git a/test/timeline-chunk-reuse.test.ts b/test/timeline-chunk-reuse.test.ts
index 1f0b7c2c15..cf43a58a98 100644
--- a/test/timeline-chunk-reuse.test.ts
+++ b/test/timeline-chunk-reuse.test.ts
@@ -7,8 +7,8 @@
* 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
+ * import of the same body gives; a publication whose replacement needs more than CHUNK_VECTOR_WRITE_BUDGET
+ * vector-index 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
@@ -23,7 +23,7 @@ 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';
+import { CHUNK_VECTOR_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 {
@@ -137,7 +137,7 @@ for (const kind of testBackends()) {
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);
+ expect(kept.filter(row => row.chunk_index !== old.get(row.id)!.chunk_index).length).toBeGreaterThan(CHUNK_VECTOR_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);
@@ -148,13 +148,13 @@ for (const kind of testBackends()) {
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.
+ // Every chunk_index move past the first CHUNK_VECTOR_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;
+ IF (SELECT count(*) FROM probe_7172_moves) > ${CHUNK_VECTOR_WRITE_BUDGET} THEN RAISE EXCEPTION 'probe_7172 interrupted'; END IF;
END IF;
RETURN NEW;
END $$`);
@@ -184,16 +184,17 @@ for (const kind of testBackends()) {
}, 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 () => {
+ test('probe: with each vector-index 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.
+ // Each new row version that adds an HNSW entry (one carrying a vector: an insert, or 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.
+ // A version with a NULL vector adds no HNSW entry and is not charged (chunk-moves.ts measures both).
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
+ IF NEW.embedding IS NOT NULL AND (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;
@@ -222,11 +223,11 @@ for (const kind of testBackends()) {
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))}`);
+ console.log(`[probe] state ${receipt.write_request?.state ?? receipt.state}, interruptions ${interruptions}, vector-index 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);
+ expect(Number(writes[0]?.n ?? 0)).toBeLessThanOrEqual(CHUNK_VECTOR_WRITE_BUDGET);
await settle();
expect((await pageState(slug)).sealed).toBe(true);
expect(passages(await rows(slug))).toEqual(await freshPassages(slug));