Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(large-pages): vector validity keyed by chunk content and embedding input (A4/T32)

garrytanee92fec4ba21
diff --git a/src/commands/embed.ts b/src/commands/embed.ts
index 5f6a3314c3..c5d5d19da1 100644
--- a/src/commands/embed.ts
+++ b/src/commands/embed.ts
@@ -1188,16 +1188,17 @@ async function embedPage(
const fullyEmbedded = failed === 0 && toEmbed.length === chunks.length;
// Vectors and their completion stamps share the page guard. A later
// contextual rebuild must not be relabeled by this attempt's restamp.
- if (!await engine.transaction(async tx => {
- if (!await installPageEmbeddings(tx, prepared, updated,
- fullyEmbedded ? currentEmbeddingSignature() ?? undefined : undefined)) return false;
- if (fullyEmbedded) await restampIfDemotedToTitleTier(tx, prepared.snapshot.page, slug, page.source_id);
- return true;
- })) {
+ const install = await engine.transaction(async tx => {
+ const installed = await installPageEmbeddings(tx, prepared, updated,
+ fullyEmbedded ? currentEmbeddingSignature() ?? undefined : undefined);
+ if (fullyEmbedded && installed.complete) await restampIfDemotedToTitleTier(tx, prepared.snapshot.page, slug, page.source_id);
+ return installed;
+ });
+ if (!install.complete && install.installed === 0) {
recordFailure(result, toEmbed.length, slug, EMBED_UNAVAILABLE_MESSAGE);
return;
}
- result.embedded += toEmbed.length - failed;
+ result.embedded += install.installed;
if (failed > 0) {
recordFailure(result, failed, slug, firstError);
serr(` ${slug}: ${failed} chunk(s) failed to embed; embedded the other ${toEmbed.length - failed}`);
@@ -1372,15 +1373,16 @@ async function embedAll(
}));
// Partial failures retain their old context; a full completion stamps
// its vectors and title-tier convention in the same guarded transaction.
- if (!await observed(pacer, () => engine.transaction(async tx => {
- if (!await installPageEmbeddings(tx, prepared, updated, failed === 0 ? signature : undefined)) return false;
- if (failed === 0) await restampIfDemotedToTitleTier(tx, prepared.snapshot.page, page.slug, pageSourceId);
- return true;
- }))) {
+ const install = await observed(pacer, () => engine.transaction(async tx => {
+ const installed = await installPageEmbeddings(tx, prepared, updated, failed === 0 ? signature : undefined);
+ if (failed === 0 && installed.complete) await restampIfDemotedToTitleTier(tx, prepared.snapshot.page, page.slug, pageSourceId);
+ return installed;
+ }));
+ if (!install.complete && install.installed === 0) {
recordFailure(result, toEmbed.length, page.slug, EMBED_UNAVAILABLE_MESSAGE);
return;
}
- result.embedded += toEmbed.length - failed;
+ result.embedded += install.installed;
if (failed > 0) {
recordFailure(result, failed, page.slug, firstError);
serr(`\n ${page.slug}: ${failed} chunk(s) failed to embed; embedded the other ${toEmbed.length - failed}`);
@@ -2074,16 +2076,15 @@ async function embedAllStale(
// The last batch stamps from complete DB provenance (#4825).
// Keep both stamps with vector installation so later contextual
// work cannot commit between installation and title-tier demotion.
- if (!await observed(pacer, () => engine.transaction(async tx => {
+ const install = await observed(pacer, () => engine.transaction(async tx => {
await staleOpts?.assertOwned?.(tx);
- if (!await installPageEmbeddings(tx, prepared, merged)) return false;
+ const installed = await installPageEmbeddings(tx, prepared, merged);
if (stamp && failed === 0) await stampIfPageProvenanceComplete(tx, slug, keySourceId, stamp);
- if (failed === 0 && stale.length === existing.length) {
- await restampIfDemotedToTitleTier(tx, prepared.snapshot.page, slug, keySourceId);
- }
- return true;
- }))) return;
- result.embedded += stale.length - failed;
+ if (failed === 0 && stale.length === existing.length && installed.complete) await restampIfDemotedToTitleTier(tx, prepared.snapshot.page, slug, keySourceId);
+ return installed;
+ }));
+ if (!install.complete && install.installed === 0) return;
+ result.embedded += install.installed;
if (failed > 0) {
recordFailure(result, failed, slug, firstError);
serr(`\n ${slug}: ${failed} chunk(s) failed to embed; embedded the other ${stale.length - failed}`);
diff --git a/src/core/contextual-retrieval-service.ts b/src/core/contextual-retrieval-service.ts
index 523bc13599..37067f6109 100644
--- a/src/core/contextual-retrieval-service.ts
+++ b/src/core/contextual-retrieval-service.ts
@@ -324,8 +324,8 @@ export async function reembedPageWithContextualRetrieval(
await tx.lockPageKeys([{ sourceId: page.source_id, slug: page.slug }]);
if (digest(sourcePolicy(await loadSourceRow(tx, page.source_id))) !== digest(sourcePolicy(source))) return false;
if (embedded) {
- if (!await installPageEmbeddings(tx, prepared, embedded.map(chunk => ({ ...chunk, model: prepared.embeddingModel ?? undefined })),
- undefined, { tier: mode, corpusGeneration: generation })) return false;
+ if (!(await installPageEmbeddings(tx, prepared, embedded.map(chunk => ({ ...chunk, model: prepared.embeddingModel ?? undefined })),
+ undefined, { tier: mode, corpusGeneration: generation })).complete) return false;
} else {
const current = await readProjectionSnapshot(tx, page.slug, page.source_id, { allowUnsealed: true });
if (!sameProjection(prepared, current)) return false;
diff --git a/src/core/embed-stale.ts b/src/core/embed-stale.ts
index ee819e3305..f72e0aef52 100644
--- a/src/core/embed-stale.ts
+++ b/src/core/embed-stale.ts
@@ -325,13 +325,14 @@ export async function embedStalePages(
embedding: staleIdxToEmbedding.get(c.chunk_index) ?? undefined,
token_count: c.token_count || Math.ceil(c.chunk_text.length / 4),
}));
- if (!await engine.transaction(async tx => {
- if (!await installPageEmbeddings(tx, prepared, merged,
- opts.embeddingSignature && stale.length === existing.length ? opts.embeddingSignature : undefined)) return false;
- if (stale.length === existing.length) await restampIfDemotedToTitleTier(tx, prepared.snapshot.page, slug, sourceId);
- return true;
- })) continue;
- result.embedded += stale.length;
+ const install = await engine.transaction(async tx => {
+ const installed = await installPageEmbeddings(tx, prepared, merged,
+ opts.embeddingSignature && stale.length === existing.length ? opts.embeddingSignature : undefined);
+ if (stale.length === existing.length && installed.complete) await restampIfDemotedToTitleTier(tx, prepared.snapshot.page, slug, sourceId);
+ return installed;
+ });
+ if (!install.complete && install.installed === 0) continue;
+ result.embedded += install.installed;
result.pagesProcessed += 1;
} catch (e) {
if (opts.signal?.aborted) {
@@ -577,18 +578,18 @@ export async function embedStaleForSource(
}));
// The keyset's last batch stamps complete DB provenance (#4825),
// with context demotion in the same transaction as its vector writes.
- if (!await observed(pacer, () => engine.transaction(async tx => {
+ const install = await observed(pacer, () => engine.transaction(async tx => {
await opts.assertOwned?.(tx);
if (stopped()) throw new AbortError();
- if (!await installPageEmbeddings(tx, prepared, merged)) return false;
+ const installed = await installPageEmbeddings(tx, prepared, merged);
if (stamp) await stampIfPageProvenanceComplete(tx, slug, keySourceId, stamp);
- if (stale.length === existing.length) await restampIfDemotedToTitleTier(tx, prepared.snapshot.page, slug, keySourceId);
+ if (stale.length === existing.length && installed.complete) await restampIfDemotedToTitleTier(tx, prepared.snapshot.page, slug, keySourceId);
await opts.assertOwned?.(tx);
if (stopped()) throw new AbortError();
- return true;
- }))) return;
- result.embedded += stale.length;
- result.pagesProcessed += 1;
+ return installed;
+ }));
+ result.embedded += install.installed;
+ if (install.complete || install.installed > 0) result.pagesProcessed += 1;
} catch (e: unknown) {
result.failures = (result.failures ?? 0) + stale.length;
// Aborted mid-fetch is expected; treat as graceful exit.
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 0915a8057b..2738838322 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -876,7 +876,7 @@ export async function importFromContent(
const signature = currentEmbeddingSignature();
await embedChunks();
const installed = await installPageEmbeddings(engine, persistedProjection, chunks, embeddingPartial ? undefined : signature ?? undefined);
- return { status: installed ? 'embedded' : 'superseded' };
+ return { status: installed.complete ? 'embedded' : 'superseded' };
} catch {
return { status: 'failed', error: 'Page content was saved, but embedding failed. Check the embedding provider and database on the brain host, then run gbrain embed --stale --source <source-id>.' };
}
diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.ts
index b63e3ddf59..c7b82d6508 100644
--- a/src/core/page-state/projections.ts
+++ b/src/core/page-state/projections.ts
@@ -13,8 +13,9 @@ import { digest } from '../persistence/digest.ts';
import { quoteIdentifier, resolveWriteColumnFromConfigRows, vectorCastSuffix } from '../search/embedding-column.ts';
import { getFtsLanguage, pageSearchVectorSql } from '../fts-language.ts';
import { getEmbeddingModel } from '../ai/gateway.ts';
+import { jsonRowBatches } from '../batch-rows.ts';
import { refreshProjectionStatistics } from '../search/projection-statistics.ts';
-import { belowSafeChunkFence } from '../search/safe-chunks.ts';
+import { belowSafeChunkFence, movableChunkSql } from '../search/safe-chunks.ts';
import { acceptedEmbeddingInputHashes, embeddingInputHash, plainEmbeddingTier, synopsisBodyHash,
type EmbeddingInputContext, type EmbeddingTier } from '../embedding-input-hash.ts';
@@ -186,16 +187,6 @@ 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) {
- const byIndex = new Map(chunks.map(chunk => [chunk.chunk_index, chunk]));
- const identity = (chunk: ChunkInput | Chunk) => [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 matching = stored.filter(chunk => {
- const next = byIndex.get(chunk.chunk_index);
- return next && digest(identity(chunk)) === digest(identity(next));
- }).map(chunk => chunk.id);
- await tx.executeRaw(`DELETE FROM content_chunks WHERE page_id=$1 AND NOT(id=ANY($2::int[]))`, [snapshot.page.id, matching]);
// #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
@@ -204,15 +195,40 @@ export async function installPageProjection(engine: BrainEngine, prepared: Proje
// 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 recorded = await tx.executeRaw<{ id: number; chunk_index: number; embedding_input_hash: string | null }>(
- 'SELECT id,chunk_index,embedding_input_hash FROM content_chunks WHERE page_id=$1', [snapshot.page.id]);
- const currentInput = recorded.filter(row => row.embedding_input_hash === null ? mode == null
- : acceptedEmbeddingInputHashes(provenance, mode, byIndex.get(Number(row.chunk_index))!).includes(row.embedding_input_hash)).map(row => Number(row.id));
- await tx.executeRaw(`UPDATE content_chunks SET ${quoteIdentifier(context.column.name)}=NULL,
+ 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];
+ 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, currentInput]);
+ [snapshot.page.id, context.provenanceModel, kept.filter(currentInput).map(chunk => Number(chunk.id))]);
} 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);
@@ -226,59 +242,104 @@ export async function installPageProjection(engine: BrainEngine, prepared: Proje
});
}
+/** What `installPageEmbeddings` committed. */
+export interface PageEmbeddingInstall {
+ /** Offered vectors committed (each onto every current row holding its chunk text and source). */
+ installed: number;
+ /**
+ * The page still holds the chunk set the vectors were prepared from (same
+ * indices, text and sources) and every offered vector committed, so completion stamps (the embedding
+ * signature, a title-tier restamp, an effect's completion) describe it.
+ */
+ complete: boolean;
+}
+
/**
- * Embedding-only updates require the same chunk identities and text, too.
- * `built` names the wrapping the vectors were built under when it is not the
- * page's plain re-embed convention (the contextual service's synopsis tier and
- * its corpus generation); it is recorded with each vector.
+ * A4: a late vector commits by chunk content, not by page revision. Each
+ * offered vector lands on the current rows holding its exact chunk text and
+ * source (any id or index) when the embedding input it was built for (the
+ * captured title, tier, corpus generation and, for synopsis vectors, the
+ * captured body hash) is still the input the current page accepts
+ * (`acceptedEmbeddingInputHashes`, #5553); a vector whose chunk left the page or
+ * whose context moved (title edit, synopsis body change) is dropped. So an
+ * embed of a live, growing page converges instead of being discarded on every
+ * append. A deleted page, an archived or recreated source, another page id, an
+ * unsealed projection or a changed indexing context (model, column, mode,
+ * corpus generation) refuses everything. `built` names the wrapping the vectors
+ * were built under when it is not the page's plain re-embed convention (the
+ * contextual service's synopsis tier and the corpus generation it stamps next);
+ * that publication describes the whole page, so it installs only when complete.
+ * UPDATE-only, in bounded batches: a late embed never replaces text, chunk
+ * identity, metadata or membership.
*/
export async function installPageEmbeddings(engine: BrainEngine, prepared: ProjectionSnapshot, chunks: ChunkInput[], signature?: string,
- built?: { tier: EmbeddingTier; corpusGeneration?: string | null }): Promise<boolean> {
+ built?: { tier: EmbeddingTier; corpusGeneration?: string | null }): Promise<PageEmbeddingInstall> {
const { snapshot } = prepared;
const sourceId = snapshot.page.source_id;
const slug = snapshot.page.slug;
+ const refused: PageEmbeddingInstall = { installed: 0, complete: false };
return engine.transaction(async tx => {
await tx.lockPageKeys([{ sourceId, slug }]);
const current = await tx.readPageSnapshot(slug, { sourceId });
- if (!current || current.page.deleted_at || current.revision !== snapshot.revision || current.sourceIncarnation !== snapshot.sourceIncarnation || current.page.id !== snapshot.page.id
- || current.page.text_projection_revision !== current.revision) return false;
+ if (!current || current.page.deleted_at || current.sourceIncarnation !== snapshot.sourceIncarnation || current.page.id !== snapshot.page.id
+ || current.page.text_projection_revision !== current.revision) return refused;
const [source] = await tx.executeRaw<{ archived: boolean }>('SELECT archived FROM sources WHERE id=$1', [sourceId]);
- if (!source || source.archived) return false;
+ if (!source || source.archived) return refused;
const context = await indexingContext(tx, current, prepared.maxChunkTokensOverride);
- if (context.key !== prepared.indexingContext) return false;
+ if (context.key !== prepared.indexingContext) return refused;
const stored = await tx.getChunks(slug, { sourceId, includeUnsealed: true });
- if (stored.length !== prepared.chunks.length || stored.some((c, i) => c.id !== prepared.chunks[i].id
- || c.chunk_index !== prepared.chunks[i].chunk_index || c.chunk_text !== prepared.chunks[i].chunk_text)) return false;
- const byIndex = new Map(stored.map(chunk => [chunk.chunk_index, chunk]));
- if (chunks.some(chunk => !byIndex.has(chunk.chunk_index) || byIndex.get(chunk.chunk_index)!.chunk_text !== chunk.chunk_text
- || byIndex.get(chunk.chunk_index)!.chunk_source !== chunk.chunk_source)) return false;
+ const key = (chunk: { chunk_text: string; chunk_source?: string | null }) => `${chunk.chunk_source}\0${chunk.chunk_text}`;
+ const rows = new Map<string, number[]>();
+ for (const chunk of stored) {
+ const ids = rows.get(key(chunk));
+ if (ids) ids.push(chunk.id);
+ else rows.set(key(chunk), [chunk.id]);
+ }
// Use the checked descriptor: config writes do not take the page guard,
// so resolving again could send these vectors to a different model's column.
const column = context.column;
- const tier = built?.tier ?? plainEmbeddingTier(current.page.contextual_retrieval_mode);
- const provenance = embeddingInputContext(context, current.page.title,
- built?.corpusGeneration !== undefined ? built.corpusGeneration : context.corpusGeneration, stored);
- // This is deliberately UPDATE-only: a late embed can never replace text,
- // chunk identity, metadata, or membership in the installed projection.
+ const mode = current.page.contextual_retrieval_mode;
+ const tier = built?.tier ?? plainEmbeddingTier(mode);
+ const generation = built?.corpusGeneration !== undefined ? built.corpusGeneration : context.corpusGeneration;
+ const capturedInput = embeddingInputContext(context, snapshot.page.title, generation, prepared.chunks);
+ const currentInput = embeddingInputContext(context, current.page.title, generation, stored);
+ const accepted = new Map<string, { ids: number[]; hash: string; chunk: ChunkInput }>();
+ let installed = 0;
+ let dropped = 0;
for (const chunk of chunks) {
if (!chunk.embedding && !chunk.embedding_image) continue;
- const original = byIndex.get(chunk.chunk_index)!;
- const vector = chunk.embedding ? `[${Array.from(chunk.embedding).join(',')}]` : null;
- const image = chunk.embedding_image ? `[${Array.from(chunk.embedding_image).join(',')}]` : null;
- await tx.executeRaw(`UPDATE content_chunks SET
- ${quoteIdentifier(column.name)}=CASE WHEN $2::text IS NULL THEN ${quoteIdentifier(column.name)} ELSE $2${vectorCastSuffix(column)} END,
- embedding_image=CASE WHEN $3::text IS NULL THEN embedding_image ELSE $3::vector END,
- embedding_input_hash=CASE WHEN $2::text IS NULL THEN embedding_input_hash ELSE $7 END,
- embedded_at=now(),embedded_text_hash=md5(chunk_text),model=COALESCE($4,model),
- embedding_pending_since=CASE WHEN $2::text IS NULL THEN embedding_pending_since ELSE NULL END
- WHERE id=$1 AND page_id=$5 AND chunk_text=$6`,
+ const ids = rows.get(key(chunk));
+ const hash = embeddingInputHash(capturedInput, tier, chunk);
+ const currentHashes = built ? [embeddingInputHash(currentInput, built.tier, chunk)] : acceptedEmbeddingInputHashes(currentInput, mode, chunk);
+ if (!ids || (chunk.embedding && !currentHashes.includes(hash))) { dropped++; continue; }
+ installed++;
+ if (!accepted.has(key(chunk))) accepted.set(key(chunk), { ids, hash, chunk });
+ }
+ const complete = dropped === 0 && stored.length === prepared.chunks.length && stored.every((c, i) => c.chunk_index === prepared.chunks[i].chunk_index && c.chunk_text === prepared.chunks[i].chunk_text && c.chunk_source === prepared.chunks[i].chunk_source);
+ if (built && !complete) return refused;
+ const updates = [...accepted.values()].flatMap(({ ids, hash, chunk }) => ids.map(id => ({ id, hash, chunk })));
+ const col = quoteIdentifier(column.name);
+ for (const batch of jsonRowBatches(updates, ({ id, hash, chunk }) => ({
+ id,
+ chunk_text: chunk.chunk_text,
+ embedding: chunk.embedding ? `[${Array.from(chunk.embedding).join(',')}]` : null,
+ image: chunk.embedding_image ? `[${Array.from(chunk.embedding_image).join(',')}]` : null,
// Bind the full provider:model captured before the provider call. Keeping
// an old label on a new vector prevents provenance-complete migration.
- [original.id, vector, image, chunk.model ?? (vector ? prepared.embeddingModel : null), snapshot.page.id, original.chunk_text,
- embeddingInputHash(provenance, tier, original)]);
+ model: chunk.model ?? (chunk.embedding ? prepared.embeddingModel : null),
+ input_hash: hash,
+ }))) {
+ await tx.executeRaw(`UPDATE content_chunks SET
+ ${col}=CASE WHEN v.embedding IS NULL THEN content_chunks.${col} ELSE v.embedding${vectorCastSuffix(column)} END,
+ embedding_image=CASE WHEN v.image IS NULL THEN content_chunks.embedding_image ELSE v.image::vector END,
+ embedding_input_hash=CASE WHEN v.embedding IS NULL THEN content_chunks.embedding_input_hash ELSE v.input_hash END,
+ embedded_at=now(),embedded_text_hash=md5(content_chunks.chunk_text),model=COALESCE(v.model,content_chunks.model),
+ embedding_pending_since=CASE WHEN v.embedding IS NULL THEN content_chunks.embedding_pending_since ELSE NULL END
+ FROM jsonb_to_recordset($2::text::jsonb) AS v(id int, chunk_text text, embedding text, image text, model text, input_hash text)
+ WHERE content_chunks.id=v.id AND content_chunks.page_id=$1 AND content_chunks.chunk_text=v.chunk_text`, [snapshot.page.id, batch]);
}
- if (signature) await tx.setPageEmbeddingSignature(slug, { sourceId, signature });
- return true;
+ if (signature && complete) await tx.setPageEmbeddingSignature(slug, { sourceId, signature });
+ return { installed, complete };
});
}
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index f5bc0c6dc9..b352d97ca1 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -362,9 +362,11 @@ async function embedPage(engine: BrainEngine, config: GBrainConfig, effect: Pers
await assertEmbeddingEffectEnabled(tx, config);
signal.throwIfAborted();
// A partially refused page keeps its signature unstamped so `gbrain embed --stale` finds the refused chunks.
- const installed = await installPageEmbeddings(tx, prepared, pending.map((chunk, i) => ({ chunk_index: chunk.chunk_index,
+ // A partial install (the page changed under the provider call) keeps the vectors whose chunk and input
+ // still match and settles like a superseded one: the newer revision's own effect embeds the rest.
+ const installed = (await installPageEmbeddings(tx, prepared, pending.map((chunk, i) => ({ chunk_index: chunk.chunk_index,
chunk_text: chunk.chunk_text, chunk_source: chunk.chunk_source, embedding: vectors[i] ?? undefined, model: opts.embedding?.model })),
- refused ? undefined : signature);
+ refused ? undefined : signature)).complete;
if (installed && refused) {
// A refused chunk keeps no vector from an earlier convention, and the page reads as not fully embedded.
const ids = refused.failures.map(f => pending[f.index]?.id).filter((id): id is number => id !== undefined);
diff --git a/src/core/persistence/projection-reindex.ts b/src/core/persistence/projection-reindex.ts
index ae2ca9e8a8..37b5481cb4 100644
--- a/src/core/persistence/projection-reindex.ts
+++ b/src/core/persistence/projection-reindex.ts
@@ -93,8 +93,8 @@ export async function reindexCodeProjection(engine: BrainEngine, slug: string, s
const installed = await installPageEmbeddings(engine, prepared, chunks.map((c, i) => ({
chunk_index: c.chunk_index, chunk_text: c.chunk_text, chunk_source: c.chunk_source,
model: prepared.embeddingModel ?? undefined, embedding: vectors[i] })));
- if (!installed) throw opError('revision_conflict', 'Code changed while embedding; text remains queued or searchable without new vectors.',
- `Code page ${slug} in source ${sourceId} changed while its vectors were computed, so they were discarded. Run gbrain reindex-code --source ${sourceId} again to embed the current revision.`,
+ if (!installed.complete) throw opError('revision_conflict', 'Code changed while embedding; text remains queued or searchable without new vectors.',
+ `Code page ${slug} in source ${sourceId} changed while its vectors were computed, so only the ${installed.installed} of ${chunks.length} vectors whose chunks are unchanged were installed. Run gbrain reindex-code --source ${sourceId} again to embed the current revision.`,
{ fix: previewFix(sourceId) });
}
}
diff --git a/test/contextual-retrieval-service-pure.test.ts b/test/contextual-retrieval-service-pure.test.ts
index fec390eb85..6fb9ff9c4c 100644
--- a/test/contextual-retrieval-service-pure.test.ts
+++ b/test/contextual-retrieval-service-pure.test.ts
@@ -534,14 +534,16 @@ function makeServiceEngine(chunks: ChunkInput[]) {
return [{ chunker_version: MARKDOWN_CHUNKER_VERSION, corpus_generation: null }];
}
if (sql.startsWith('UPDATE content_chunks SET')) {
- const original = storedChunks.find(chunk => chunk.id === params[0]);
- if (!original || params[4] !== original.page_id || params[5] !== original.chunk_text) {
- throw new Error('Embedding update must address the existing chunk row and text');
+ for (const row of JSON.parse(String(params[1])) as Array<{ id: number; chunk_text: string; embedding: string | null; model: string | null }>) {
+ const original = storedChunks.find(chunk => chunk.id === row.id);
+ if (!original || params[0] !== original.page_id || row.chunk_text !== original.chunk_text) {
+ throw new Error('Embedding update must address the existing chunk row and text');
+ }
+ embeddedChunks.push({ ...original,
+ embedding: row.embedding == null ? undefined : new Float32Array(JSON.parse(row.embedding)),
+ model: typeof row.model === 'string' ? row.model : undefined,
+ });
}
- embeddedChunks.push({ ...original,
- embedding: params[1] == null ? undefined : new Float32Array(JSON.parse(String(params[1]))),
- model: typeof params[3] === 'string' ? params[3] : undefined,
- });
return [];
}
if (!sql.includes('FROM sources')) throw new Error(`Unexpected fixture SQL: ${sql}`);
diff --git a/test/e2e/migration-wave-prepared-withdrawal.test.ts b/test/e2e/migration-wave-prepared-withdrawal.test.ts
index cf0446afcf..6e3f16429c 100644
--- a/test/e2e/migration-wave-prepared-withdrawal.test.ts
+++ b/test/e2e/migration-wave-prepared-withdrawal.test.ts
@@ -37,16 +37,16 @@ for (const kind of ['pglite', 'postgres'] as const) {
const prepared = (await readProjectionSnapshot(engine, slug, sourceId))!;
const install = () => installPageEmbeddings(engine, prepared, prepared.chunks.map(chunk => ({ chunk_index: chunk.chunk_index, chunk_source: chunk.chunk_source, chunk_text: chunk.chunk_text, embedding: vector })), `${model}:8`);
if (order === 'install-first') {
- expect(await install()).toBe(true);
+ expect((await install()).complete).toBe(true);
expect(await engine.searchVector(vector, { sourceId })).toHaveLength(1);
}
expect((await recordFactWithdrawal(engine, fact.id, sourceId, true)).withdrawn).toBe(true);
- expect(await install()).toBe(false);
+ expect(await install()).toEqual({ installed: 0, complete: false });
expect(await engine.searchVector(vector, { sourceId })).toEqual([]);
expect(await engine.searchKeyword('withdrawalsentinel', { sourceId })).toEqual([]);
expect((await rebuildPendingPageProjections(engine, 100)).rebuilt).toBeGreaterThan(0);
expect((await engine.getChunks(slug, { sourceId })).map(c => c.chunk_text).join('\n')).not.toContain(claim);
- expect(await install()).toBe(false);
+ expect(await install()).toEqual({ installed: 0, complete: false });
expect(await engine.searchKeyword('withdrawalsentinel', { sourceId })).toEqual([]);
});
}
@@ -62,7 +62,7 @@ for (const kind of ['pglite', 'postgres'] as const) {
else if (change === 'model') await engine.setConfig('embedding_model', 'openai:text-embedding-3-large');
else expect(await engine.softDeletePage(slug, { sourceId })).not.toBeNull();
const before = await engine.executeRaw('SELECT to_jsonb(c) AS chunk FROM content_chunks c WHERE page_id=$1 ORDER BY id', [prepared.snapshot.page.id]);
- expect(await installPageEmbeddings(engine, prepared, prepared.chunks.map(chunk => ({ chunk_index: chunk.chunk_index, chunk_source: chunk.chunk_source, chunk_text: chunk.chunk_text, embedding: vector })))).toBe(false);
+ expect(await installPageEmbeddings(engine, prepared, prepared.chunks.map(chunk => ({ chunk_index: chunk.chunk_index, chunk_source: chunk.chunk_source, chunk_text: chunk.chunk_text, embedding: vector })))).toEqual({ installed: 0, complete: false });
expect(await engine.executeRaw('SELECT to_jsonb(c) AS chunk FROM content_chunks c WHERE page_id=$1 ORDER BY id', [prepared.snapshot.page.id])).toEqual(before);
await engine.setConfig('embedding_model', model);
});
diff --git a/test/embed-stale-chunkless-pages.serial.test.ts b/test/embed-stale-chunkless-pages.serial.test.ts
index c93e6a7e3f..67dfa4f709 100644
--- a/test/embed-stale-chunkless-pages.serial.test.ts
+++ b/test/embed-stale-chunkless-pages.serial.test.ts
@@ -323,9 +323,9 @@ describe('embed --stale chunkless-page safety net (end-to-end)', () => {
})));
const newer = (await readProjectionSnapshot(engine, slug, 'default'))!;
const vector = new Float32Array(DIMS); vector[0] = 0.75;
- expect(await installPageEmbeddings(engine, newer, newer.chunks.map(c => ({
+ expect((await installPageEmbeddings(engine, newer, newer.chunks.map(c => ({
chunk_index: c.chunk_index, chunk_source: c.chunk_source, chunk_text: c.chunk_text, embedding: vector,
- })))).toBe(true);
+ })))).complete).toBe(true);
current = await engine.getChunks(slug, { includeEmbedding: true });
}
return result;
diff --git a/test/helpers/embed-projection-mock.ts b/test/helpers/embed-projection-mock.ts
index 684557641f..03d834b130 100644
--- a/test/helpers/embed-projection-mock.ts
+++ b/test/helpers/embed-projection-mock.ts
@@ -47,7 +47,15 @@ export function mockEmbedProjectionEngine(overrides: Partial<Record<string, any>
return engine;
}
+/**
+ * Vector writes installPageEmbeddings issued, one entry per updated row. Its
+ * batched statement binds `[page_id, rows]`; each row is expanded to the
+ * positional layout `[id, vector, image, model, page_id, chunk_text, input_hash]`.
+ */
export function embeddingUpdates(engine: BrainEngine) {
return (engine as any)._calls.filter((call: any) => call.method === 'executeRaw'
- && /^UPDATE content_chunks SET/.test(call.args[0]));
+ && /^UPDATE content_chunks SET/.test(call.args[0]))
+ .flatMap((call: any) => !call.args[0].includes('jsonb_to_recordset') ? [call]
+ : (JSON.parse(call.args[1][1]) as any[]).map(row => ({ ...call,
+ args: [call.args[0], [row.id, row.embedding, row.image, row.model, call.args[1][0], row.chunk_text, row.input_hash]] })));
}
diff --git a/test/import-publication-guards.test.ts b/test/import-publication-guards.test.ts
index 49ebba9242..9aad9e09a5 100644
--- a/test/import-publication-guards.test.ts
+++ b/test/import-publication-guards.test.ts
@@ -166,7 +166,11 @@ for (const intervening of ['none', 'page', 'chunks', 'indexing-context'] as cons
expect(after.snapshot!.page.compiled_truth).toBe(expected.snapshot!.page.compiled_truth);
expect(after.chunks.map(chunk => [chunk.id, chunk.chunk_index, chunk.chunk_text])).toEqual(
expected.chunks.map(chunk => [chunk.id, chunk.chunk_index, chunk.chunk_text]));
- expect(after.chunks.every(chunk => chunk.embedding_is_null)).toBe(intervening !== 'none');
+ // A4: a chunk the page still holds with the same text and embedding input keeps the
+ // vector built for it; the late fragment, a changed body or a changed context gets none.
+ const kept = intervening === 'none' ? after.chunks : intervening === 'chunks' ? before.chunks : [];
+ expect(after.chunks.filter(chunk => !chunk.embedding_is_null).map(chunk => chunk.chunk_text))
+ .toEqual(kept.map(chunk => chunk.chunk_text));
} finally {
if (previousMode === null) await engine.executeRaw("DELETE FROM config WHERE key='contextual_retrieval.mode'");
else await engine.setConfig('contextual_retrieval.mode', previousMode);
diff --git a/test/page-embedding-content-validity.test.ts b/test/page-embedding-content-validity.test.ts
new file mode 100644
index 0000000000..2efa56f7f8
--- /dev/null
+++ b/test/page-embedding-content-validity.test.ts
@@ -0,0 +1,135 @@
+/**
+ * A4 / T32: vector validity follows chunk content and full embedding-input
+ * provenance, not the page revision; rebuilds keep shifted chunks' vectors.
+ *
+ * Authoring gate. (1) Contract: a late embed of a live page commits the vectors
+ * of chunks the page still holds unchanged (an append during a long embed
+ * converges) and drops vectors whose chunk left or whose captured input (title,
+ * synopsis body hash) no longer matches; completion stamps follow only a
+ * complete install; a projection rebuild after a top insert keeps the vector
+ * of every chunk it only shifted. (2) Regressions: revision-bound discard of a
+ * whole run, committing a title- or synopsis-stale vector, stamping a signature
+ * over unembedded new chunks, index-keyed vector loss. (3) Existing tests pin
+ * refusal on model/source/deletion changes and same-index preservation, not
+ * these. (4) No production seam.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { ChunkInput } from '../src/core/types.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { installPageEmbeddings, installPageProjection, preparePageProjection, queuePageProjection, readProjectionSnapshot,
+ rebuildPendingPageProjections } from '../src/core/page-state/projections.ts';
+import { installFixtureChunks } from './helpers/page-projection.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const sourceId = 'content-validity-test';
+const slug = 'notes/live-thread-alice-example';
+
+for (const kind of testBackends()) {
+ describe(`A4 content-keyed vector validity (${kind})`, () => {
+ let engine: BrainEngine;
+ let closePostgres: (() => Promise<void>) | undefined;
+ let dims = 0;
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close: closePostgres } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
+ const [row] = await engine.executeRaw<{ dim: number }>(
+ `SELECT atttypmod AS dim FROM pg_attribute WHERE attrelid = 'content_chunks'::regclass AND attname = 'embedding' AND attnum > 0`);
+ dims = Number(row!.dim);
+ }, 120_000);
+ beforeEach(async () => { await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1)', [sourceId]); });
+ afterEach(async () => { await engine.executeRaw('DELETE FROM sources WHERE id=$1', [sourceId]); });
+ afterAll(async () => { if (kind === 'pglite') await engine.disconnect(); await closePostgres?.(); });
+
+ const vec = (seed: number) => { const v = new Float32Array(dims); v[seed % dims] = 0.5; v[(seed + 1) % dims] = -0.25; return v; };
+ const vecText = (seed: number) => `[${Array.from(vec(seed)).join(',')}]`;
+ const fixture = (texts: string[]): ChunkInput[] => texts.map((chunk_text, chunk_index) => ({ chunk_index, chunk_text, chunk_source: 'compiled_truth' }));
+ const A = 'Message from alice-example at 9:00 about the launch.';
+ const B = 'Reply from charlie-example at 9:05 with the agenda.';
+ const C = 'Appended message from alice-example at 9:30.';
+
+ async function write(texts: string[], opts: { title?: string; mode?: string | null; generation?: string | null } = {}) {
+ await engine.putPage(slug, { type: 'note', title: opts.title ?? 'Live thread', compiled_truth: texts.join('\n\n'), frontmatter: {} }, { sourceId });
+ await installFixtureChunks(engine, slug, fixture(texts), { sourceId });
+ if (opts.mode !== undefined) await engine.updatePageContextualRetrievalState(slug, sourceId, opts.mode as never, opts.generation ?? null);
+ }
+ async function vectors() {
+ return engine.executeRaw<{ chunk_text: string; embedding: string | null; embedding_input_hash: string | null; embedded_text_hash: string | null; text_md5: string }>(
+ `SELECT cc.chunk_text, cc.embedding::text AS embedding, cc.embedding_input_hash, cc.embedded_text_hash, md5(cc.chunk_text) AS text_md5
+ FROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE p.source_id=$1 AND p.slug=$2 ORDER BY cc.chunk_index`, [sourceId, slug]);
+ }
+ const signatureOf = async () => (await engine.executeRaw<{ s: string | null }>(
+ 'SELECT embedding_signature AS s FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]))[0]?.s ?? null;
+ const offer = (prepared: NonNullable<Awaited<ReturnType<typeof readProjectionSnapshot>>>) =>
+ prepared.chunks.map((c, i) => ({ chunk_index: c.chunk_index, chunk_text: c.chunk_text, chunk_source: c.chunk_source, embedding: vec(i) }));
+
+ test('an append during the embed commits the vectors of the unchanged chunks; the new chunk waits and no signature lands', async () => {
+ await write([A, B]);
+ const prepared = (await readProjectionSnapshot(engine, slug, sourceId))!;
+ await write([A, B, C]);
+ expect(await installPageEmbeddings(engine, prepared, offer(prepared), 'test:model:8')).toEqual({ installed: 2, complete: false });
+ const rows = await vectors();
+ expect(rows.map(r => [r.chunk_text, r.embedding])).toEqual([[A, vecText(0)], [B, vecText(1)], [C, null]]);
+ for (const row of rows.slice(0, 2)) {
+ expect(row.embedded_text_hash).toBe(row.text_md5);
+ expect(row.embedding_input_hash).not.toBeNull();
+ }
+ expect(await signatureOf()).toBeNull();
+ });
+
+ test('a chunk that moved to another index still receives its vector', async () => {
+ await write([A, B]);
+ const prepared = (await readProjectionSnapshot(engine, slug, sourceId))!;
+ await write([C, A, B]);
+ expect(await installPageEmbeddings(engine, prepared, offer(prepared))).toEqual({ installed: 2, complete: false });
+ expect((await vectors()).map(r => r.embedding)).toEqual([null, vecText(0), vecText(1)]);
+ });
+
+ test('a title edit on a title-tier page drops every vector built under the old title', async () => {
+ await write([A, B], { mode: 'title' });
+ const prepared = (await readProjectionSnapshot(engine, slug, sourceId))!;
+ await write([A, B], { title: 'Renamed thread', mode: 'title' });
+ expect(await installPageEmbeddings(engine, prepared, offer(prepared))).toEqual({ installed: 0, complete: false });
+ expect((await vectors()).map(r => r.embedding)).toEqual([null, null]);
+ });
+
+ test('a synopsis vector built over the old body is dropped after an append; with the body unchanged it publishes', async () => {
+ await write([A, B], { mode: 'per_chunk_synopsis', generation: 'gen-1' });
+ const stale = (await readProjectionSnapshot(engine, slug, sourceId))!;
+ await write([A, B, C], { mode: 'per_chunk_synopsis', generation: 'gen-1' });
+ const built = { tier: 'per_chunk_synopsis' as const, corpusGeneration: 'gen-2' };
+ expect(await installPageEmbeddings(engine, stale, offer(stale), undefined, built)).toEqual({ installed: 0, complete: false });
+ expect((await vectors()).map(r => r.embedding)).toEqual([null, null, null]);
+ const fresh = (await readProjectionSnapshot(engine, slug, sourceId))!;
+ // Same chunks, same title: a frontmatter-only edit moves the revision, not the input.
+ await engine.putPage(slug, { type: 'note', title: 'Live thread', compiled_truth: [A, B, C].join('\n\n'), frontmatter: { touched: true } }, { sourceId });
+ await installFixtureChunks(engine, slug, fixture([A, B, C]), { sourceId });
+ await engine.updatePageContextualRetrievalState(slug, sourceId, 'per_chunk_synopsis', 'gen-1');
+ expect(await installPageEmbeddings(engine, fresh, offer(fresh), undefined, built)).toEqual({ installed: 3, complete: true });
+ expect((await vectors()).map(r => r.embedding)).toEqual([vecText(0), vecText(1), vecText(2)]);
+ });
+
+ test('a projection rebuild after a top insert keeps the vector of every chunk it only shifted', async () => {
+ const paragraph = (i: number) => `## 2024-03-${String(1 + (i % 28)).padStart(2, '0')}\n\n` + Array.from({ length: 16 },
+ (_, line) => `**alice-example** (2024-03-15 1:0${line % 10} PM): message ${i}.${line} about acme-example plans and next steps for the launch review.`).join('\n');
+ const body = Array.from({ length: 40 }, (_, i) => paragraph(i)).join('\n\n');
+ await engine.putPage(slug, { type: 'note', title: 'Live thread', compiled_truth: body, frontmatter: {} }, { sourceId });
+ const unsealed = (await readProjectionSnapshot(engine, slug, sourceId, { allowUnsealed: true }))!;
+ await installPageProjection(engine, unsealed, (await preparePageProjection(unsealed)).chunks, { seal: true });
+ const prepared = (await readProjectionSnapshot(engine, slug, sourceId))!;
+ expect(prepared.chunks.length).toBeGreaterThan(10);
+ expect((await installPageEmbeddings(engine, prepared, offer(prepared))).complete).toBe(true);
+ const before = new Map((await vectors()).map(r => [r.chunk_text, r.embedding]));
+
+ await engine.putPage(slug, { type: 'note', title: 'Live thread', compiled_truth: `${paragraph(99)}\n\n${body}`, frontmatter: {} }, { sourceId });
+ await queuePageProjection(engine, sourceId, slug, 'test_top_insert');
+ expect(await rebuildPendingPageProjections(engine, 10)).toEqual({ rebuilt: 1, superseded: 0 });
+ const after = await vectors();
+ const shifted = after.filter(r => before.has(r.chunk_text));
+ expect(shifted.length).toBeGreaterThanOrEqual(prepared.chunks.length - 2);
+ for (const row of shifted) expect(row.embedding).toBe(before.get(row.chunk_text)!);
+ expect(after.filter(r => r.embedding === null).length).toBe(after.length - shifted.length);
+ }, 60_000);
+ });
+}
diff --git a/test/page-embedding-install-batch.test.ts b/test/page-embedding-install-batch.test.ts
index c70b48358f..52c8bda368 100644
--- a/test/page-embedding-install-batch.test.ts
+++ b/test/page-embedding-install-batch.test.ts
@@ -53,7 +53,7 @@ for (const kind of testBackends()) {
const { prepared, chunks } = await capture();
expect(chunks.length).toBeGreaterThanOrEqual(2);
const before = await rows();
- expect(await installPageEmbeddings(engine, prepared, chunks.map((c, i) => i === 0 ? { ...c, embedding: vector(0.25) } : c))).toBe(true);
+ expect((await installPageEmbeddings(engine, prepared, chunks.map((c, i) => i === 0 ? { ...c, embedding: vector(0.25) } : c))).complete).toBe(true);
const after = await rows();
expect(after[0]!.embedding).toBe(text(vector(0.25)));
expect(after[0]!.embedded_text_hash).toBe(after[0]!.text_md5);
@@ -65,10 +65,10 @@ for (const kind of testBackends()) {
test('an image-only chunk keeps its text vector, input hash and model and gains the image and stamps', async () => {
const { prepared, chunks } = await capture();
- expect(await installPageEmbeddings(engine, prepared, chunks.map(c => ({ ...c, embedding: vector(0.5), model: 'test:text-model' })))).toBe(true);
+ expect((await installPageEmbeddings(engine, prepared, chunks.map(c => ({ ...c, embedding: vector(0.5), model: 'test:text-model' })))).complete).toBe(true);
const withText = await rows();
const again = await capture();
- expect(await installPageEmbeddings(engine, again.prepared, again.chunks.map((c, i) => i === 1 ? { ...c, embedding_image: image } : c))).toBe(true);
+ expect((await installPageEmbeddings(engine, again.prepared, again.chunks.map((c, i) => i === 1 ? { ...c, embedding_image: image } : c))).complete).toBe(true);
const after = await rows();
expect(after[0]).toEqual(withText[0]!);
expect(after[1]!.embedding).toBe(withText[1]!.embedding);
@@ -80,7 +80,7 @@ for (const kind of testBackends()) {
test('every chunk in one call gets its own vector, model and input hash', async () => {
const { prepared, chunks } = await capture();
- expect(await installPageEmbeddings(engine, prepared, chunks.map((c, i) => ({ ...c, embedding: vector(0.125 * (i + 1)), model: `test:model-${i}` })))).toBe(true);
+ expect((await installPageEmbeddings(engine, prepared, chunks.map((c, i) => ({ ...c, embedding: vector(0.125 * (i + 1)), model: `test:model-${i}` })))).complete).toBe(true);
const after = await rows();
expect(after.map(r => r.embedding)).toEqual(chunks.map((_, i) => text(vector(0.125 * (i + 1)))));
expect(after.map(r => r.model)).toEqual(chunks.map((_, i) => `test:model-${i}`));
@@ -88,14 +88,25 @@ for (const kind of testBackends()) {
for (const row of after) expect(row.embedded_text_hash).toBe(row.text_md5);
});
- test('a delayed install against a changed page writes nothing', async () => {
+ test('a delayed install against a changed page writes only the chunks the page still holds unchanged (A4)', async () => {
const { prepared, chunks } = await capture();
await engine.putPage(slug, { type: 'note', title: 'Batch fixture', compiled_truth: 'A newer body replaced the captured one.',
timeline: '2026-01-02: Synthetic event.', frontmatter: {} }, { sourceId });
await seal();
const before = await rows();
- expect(await installPageEmbeddings(engine, prepared, chunks.map(c => ({ ...c, embedding: vector(0.9) })))).toBe(false);
- expect(await rows()).toEqual(before);
+ const captured = new Set(chunks.map(c => c.chunk_text));
+ const unchanged = before.filter(r => captured.has(r.chunk_text));
+ expect(unchanged.length).toBeGreaterThan(0);
+ expect(unchanged.length).toBeLessThan(before.length);
+ expect(await installPageEmbeddings(engine, prepared, chunks.map(c => ({ ...c, embedding: vector(0.75) }))))
+ .toEqual({ installed: chunks.filter(c => before.some(r => r.chunk_text === c.chunk_text)).length, complete: false });
+ const after = await rows();
+ after.forEach((row, i) => {
+ if (!captured.has(row.chunk_text)) return expect(row).toEqual(before[i]!);
+ expect(row.embedding).toBe(text(vector(0.75)));
+ expect(row.embedded_text_hash).toBe(row.text_md5);
+ expect(row.embedding_input_hash).not.toBeNull();
+ });
});
});
}
diff --git a/test/page-projection-concurrency.test.ts b/test/page-projection-concurrency.test.ts
index b8915237c9..6abeb5ef94 100644
--- a/test/page-projection-concurrency.test.ts
+++ b/test/page-projection-concurrency.test.ts
@@ -96,12 +96,12 @@ test('delayed embeddings cannot replace new chunks at the same indices', async (
await engine.putPage('embedding-race', page('After embedding'), { sourceId });
const current = (await readProjectionSnapshot(engine, 'embedding-race', sourceId, { allowUnsealed: true }))!;
await installPageProjection(engine, current, chunk('After embedding'), { seal: true });
- expect(await installPageEmbeddings(engine, prepared, chunk('Before embedding'))).toBe(false);
+ expect(await installPageEmbeddings(engine, prepared, chunk('Before embedding'))).toEqual({ installed: 0, complete: false });
expect((await engine.getChunks('embedding-race', { sourceId }))[0].chunk_text).toBe('After embedding');
// Even an unchanged logical revision cannot accept a stale chunk layout.
const sameRevision = (await readProjectionSnapshot(engine, 'embedding-race', sourceId))!;
await installPageProjection(engine, sameRevision, chunk('A re-chunked snapshot'), { seal: true });
- expect(await installPageEmbeddings(engine, sameRevision, chunk('After embedding'))).toBe(false);
+ expect(await installPageEmbeddings(engine, sameRevision, chunk('After embedding'))).toEqual({ installed: 0, complete: false });
}
});
@@ -112,7 +112,7 @@ test('embedding completion updates only vectors and rejects an indexing-context
await installPageProjection(engine, (await readProjectionSnapshot(engine, 'embedding-completion', sourceId, { allowUnsealed: true }))!, chunk('Stable text'), { seal: true });
const prepared = (await readProjectionSnapshot(engine, 'embedding-completion', sourceId))!;
const vector = new Float32Array(1536); vector[0] = 1;
- expect(await installPageEmbeddings(engine, prepared, [{ ...chunk('Stable text')[0], embedding: vector }])).toBe(true);
+ expect((await installPageEmbeddings(engine, prepared, [{ ...chunk('Stable text')[0], embedding: vector }])).complete).toBe(true);
const current = (await readProjectionSnapshot(engine, 'embedding-completion', sourceId))!;
expect(current.chunks.map(c => [c.id,c.chunk_text,c.chunk_index])).toEqual(prepared.chunks.map(c => [c.id,c.chunk_text,c.chunk_index]));
const [stored] = await engine.executeRaw<{ hash: string; matches: boolean }>('SELECT embedded_text_hash AS hash,embedded_text_hash=md5(chunk_text) AS matches FROM content_chunks WHERE id=$1', [current.chunks[0].id]);
@@ -120,7 +120,7 @@ test('embedding completion updates only vectors and rejects an indexing-context
const old = await engine.getConfig('contextual_retrieval.mode');
try {
await engine.setConfig('contextual_retrieval.mode', 'projection-test-changed');
- expect(await installPageEmbeddings(engine, prepared, [{ ...chunk('Stable text')[0], embedding: vector }])).toBe(false);
+ expect(await installPageEmbeddings(engine, prepared, [{ ...chunk('Stable text')[0], embedding: vector }])).toEqual({ installed: 0, complete: false });
} finally {
if (old !== null) await engine.setConfig('contextual_retrieval.mode', old);
else await engine.executeRaw("DELETE FROM config WHERE key='contextual_retrieval.mode'");
@@ -136,14 +136,14 @@ test('embedding completion stamps the captured full model and rejects a runtime
await installPageProjection(engine, (await readProjectionSnapshot(engine, 'embedding-model', sourceId, { allowUnsealed: true }))!, chunk('Model provenance'), { seal: true });
const prepared = (await readProjectionSnapshot(engine, 'embedding-model', sourceId))!;
const vector = new Float32Array(1536); vector[0] = 1;
- expect(await installPageEmbeddings(engine, prepared, [{ ...chunk('Model provenance')[0], embedding: vector }])).toBe(true);
+ expect((await installPageEmbeddings(engine, prepared, [{ ...chunk('Model provenance')[0], embedding: vector }])).complete).toBe(true);
const [stored] = await engine.executeRaw<{ model: string }>('SELECT model FROM content_chunks WHERE id=$1', [prepared.chunks[0].id]);
expect(stored.model).toBe('openai:text-embedding-3-small');
configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
- expect(await installPageEmbeddings(engine, prepared, [{ ...chunk('Model provenance')[0], embedding: vector }])).toBe(false);
+ expect(await installPageEmbeddings(engine, prepared, [{ ...chunk('Model provenance')[0], embedding: vector }])).toEqual({ installed: 0, complete: false });
expect((await engine.executeRaw<{ model: string }>('SELECT model FROM content_chunks WHERE id=$1', [prepared.chunks[0].id]))[0].model).toBe(stored.model);
const current = (await readProjectionSnapshot(engine, 'embedding-model', sourceId))!;
- expect(await installPageEmbeddings(engine, current, [{ ...chunk('Model provenance')[0], embedding: vector, model: 'fixture:explicit-model' }])).toBe(true);
+ expect((await installPageEmbeddings(engine, current, [{ ...chunk('Model provenance')[0], embedding: vector, model: 'fixture:explicit-model' }])).complete).toBe(true);
expect((await engine.executeRaw<{ model: string }>('SELECT model FROM content_chunks WHERE id=$1', [prepared.chunks[0].id]))[0].model).toBe('fixture:explicit-model');
}
} finally { resetGateway(); }
diff --git a/test/page-projection-origin.test.ts b/test/page-projection-origin.test.ts
index 0611ef3140..9bd147a9d3 100644
--- a/test/page-projection-origin.test.ts
+++ b/test/page-projection-origin.test.ts
@@ -52,9 +52,9 @@ async function seed(engine: BrainEngine, slug: string, seal = true) {
async function embedCurrent(engine: BrainEngine, slug: string) {
const prepared = (await readProjectionSnapshot(engine, slug, sourceId))!;
const vector = new Float32Array(1536); vector[0] = 0.75;
- expect(await installPageEmbeddings(engine, prepared, prepared.chunks.map(c => ({
+ expect((await installPageEmbeddings(engine, prepared, prepared.chunks.map(c => ({
chunk_index: c.chunk_index, chunk_source: c.chunk_source, chunk_text: c.chunk_text, embedding: vector,
- })))).toBe(true);
+ })))).complete).toBe(true);
return engine.getChunks(slug, { sourceId, includeEmbedding: true });
}
@@ -209,7 +209,7 @@ test('a column switch after context validation cannot redirect vectors into the
});
const vector = new Float32Array(1536); vector[0] = 0.75;
if (installation === 'embeddings') {
- expect(await installPageEmbeddings(raced, origin, [{ ...chunk(body), embedding: vector }])).toBe(true);
+ expect((await installPageEmbeddings(raced, origin, [{ ...chunk(body), embedding: vector }])).complete).toBe(true);
} else {
await installPageProjection(raced, origin, [{ ...chunk(body), embedding: vector }], { seal: true });
}
diff --git a/test/page-projection-vector-preservation.test.ts b/test/page-projection-vector-preservation.test.ts
index 768f64d7fa..05c7a9ba6a 100644
--- a/test/page-projection-vector-preservation.test.ts
+++ b/test/page-projection-vector-preservation.test.ts
@@ -169,9 +169,9 @@ for (const kind of backends) {
const pending = (await readProjectionSnapshot(engine, slug, sourceId, { allowUnsealed: true }))!;
await installPageProjection(engine, pending, (await preparePageProjection(pending)).chunks, preserve);
const prepared = (await readProjectionSnapshot(engine, slug, sourceId))!;
- expect(await installPageEmbeddings(engine, prepared, prepared.chunks.map(c => ({
+ expect((await installPageEmbeddings(engine, prepared, prepared.chunks.map(c => ({
chunk_index: c.chunk_index, chunk_text: c.chunk_text, chunk_source: c.chunk_source, embedding: vector,
- })))).toBe(true);
+ })))).complete).toBe(true);
const before = await storedChunks();
expect(before.map(c => c.embedding_input_hash).every(Boolean)).toBe(true);
const rebuild = await capture();
@@ -292,7 +292,7 @@ for (const kind of backends) {
await seed();
const { prepared, chunks } = await capture();
const newer = new Float32Array(1536); newer[0] = 0.875;
- expect(await installPageEmbeddings(engine, prepared, chunks.map(c => ({ ...c, embedding: newer })))).toBe(true);
+ expect((await installPageEmbeddings(engine, prepared, chunks.map(c => ({ ...c, embedding: newer })))).complete).toBe(true);
const before = await storedChunks();
expect(before.map(c => c.embedding)).toEqual([`[${Array.from(newer).join(',')}]`, `[${Array.from(newer).join(',')}]`]);
await expect(installPageProjection(engine, prepared, chunks, preserve)).rejects.toBeInstanceOf(PageProjectionConflictError);
@@ -329,7 +329,7 @@ for (const kind of backends) {
const ready = new Promise<void>(resolve => { entered = resolve; });
const newer = new Float32Array(1536); newer[0] = 0.9375;
const writer = engine.transaction(async tx => {
- expect(await installPageEmbeddings(tx, prepared, chunks.map(c => ({ ...c, embedding: newer })))).toBe(true);
+ expect((await installPageEmbeddings(tx, prepared, chunks.map(c => ({ ...c, embedding: newer })))).complete).toBe(true);
entered();
await held;
});
diff --git a/test/persistence-drain-latency.serial.test.ts b/test/persistence-drain-latency.serial.test.ts
index feb5d93c44..0e9d3487c7 100644
--- a/test/persistence-drain-latency.serial.test.ts
+++ b/test/persistence-drain-latency.serial.test.ts
@@ -65,8 +65,8 @@ describe('effects drain latency (PGLite)', () => {
const prepared = (await readProjectionSnapshot(engine, slug, sourceId, { allowUnsealed: true }))!;
await installPageProjection(engine, prepared, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Widget Co renewal notes.' }], { seal: true });
const sealed = (await readProjectionSnapshot(engine, slug, sourceId))!;
- expect(await installPageEmbeddings(engine, sealed, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Widget Co renewal notes.',
- embedding: new Float32Array(1536).fill(0.1), model: MODEL }], `${MODEL}:1536`)).toBe(true);
+ expect((await installPageEmbeddings(engine, sealed, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Widget Co renewal notes.',
+ embedding: new Float32Array(1536).fill(0.1), model: MODEL }], `${MODEL}:1536`)).complete).toBe(true);
await engine.executeRaw("UPDATE persistence_effects SET state='committed', outcome='{}'::jsonb WHERE kind<>'embedding'");
// Clone the committed request and its queued no-op effect: every clone is its own request, as an import leaves them.
const columns = async (table: string, skip: string[]) => (await engine.executeRaw<{ c: string }>(
diff --git a/test/persistence-embedding-effects.test.ts b/test/persistence-embedding-effects.test.ts
index 21b2c2d905..c209fb6652 100644
--- a/test/persistence-embedding-effects.test.ts
+++ b/test/persistence-embedding-effects.test.ts
@@ -103,7 +103,7 @@ for (const kind of testBackends()) {
check('already-complete projection uses provenance without reading vectors or calling the provider', async () => {
const f = await fixture();
const prepared = (await readProjectionSnapshot(engine, 'page', f.sourceId))!;
- expect(await installPageEmbeddings(engine, prepared, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Current', embedding: vectors()[0], model }], signature)).toBe(true);
+ expect((await installPageEmbeddings(engine, prepared, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Current', embedding: vectors()[0], model }], signature)).complete).toBe(true);
expect((await readProjectionSnapshot(engine, 'page', f.sourceId))!.chunks[0].embedding).toBeNull();
let calls = 0;
await run(async () => { calls++; return vectors(); });
diff --git a/test/persistence-embedding-noop-settle.test.ts b/test/persistence-embedding-noop-settle.test.ts
index 9b9065b5be..a3e81ea86f 100644
--- a/test/persistence-embedding-noop-settle.test.ts
+++ b/test/persistence-embedding-noop-settle.test.ts
@@ -72,7 +72,7 @@ for (const kind of testBackends()) {
await installPageProjection(engine, prepared, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: `Body of ${slug}` }], { seal: true });
if (embedded) {
const sealed = (await readProjectionSnapshot(engine, slug, sourceId))!;
- expect(await installPageEmbeddings(engine, sealed, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: `Body of ${slug}`, embedding: vector(), model }], signature)).toBe(true);
+ expect((await installPageEmbeddings(engine, sealed, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: `Body of ${slug}`, embedding: vector(), model }], signature)).complete).toBe(true);
}
// Only embedding effects are due; Git and other effects of these writes wait.
await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now()+interval '1 hour' WHERE kind<>'embedding'");
@@ -195,7 +195,7 @@ for (const kind of testBackends()) {
expect(opened).toBe(0);
// A stale effect that becomes a no-op behind the cursor is the runner's; a new no-op past it settles here.
const sealed = (await readProjectionSnapshot(engine, stale[0]!.slug, stale[0]!.sourceId))!;
- expect(await installPageEmbeddings(engine, sealed, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: `Body of ${stale[0]!.slug}`, embedding: vector(), model }], signature)).toBe(true);
+ expect((await installPageEmbeddings(engine, sealed, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: `Body of ${stale[0]!.slug}`, embedding: vector(), model }], signature)).complete).toBe(true);
const fresh = await page('cursor/fresh', true);
await engine.executeRaw('UPDATE persistence_effects SET next_attempt_at=now() WHERE id=ANY($1::text[]::bigint[])', [[stale[0]!.effectId, fresh.effectId]]);
expect(await settleNoopEmbeddingEffects(engine, localHostId(), signature, second.cursor)).toMatchObject({ settled: 1, done: true });
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 4833f6c750..b46fedc3ee 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -90,6 +90,7 @@ test/managed-sync-stale-group-head.test.ts
test/migration-persistence-request-slug-index.test.ts
test/owner-refusal.test.ts
test/pack-relation-direction-engine.test.ts
+test/page-embedding-content-validity.test.ts
test/page-embedding-install-batch.test.ts
test/page-prepare-shared-origin-6517.test.ts
test/page-purge-journal-timeout-6511.test.ts
diff --git a/test/projection-embedding-input-hash.test.ts b/test/projection-embedding-input-hash.test.ts
index 170af41d61..aa4823a431 100644
--- a/test/projection-embedding-input-hash.test.ts
+++ b/test/projection-embedding-input-hash.test.ts
@@ -77,7 +77,7 @@ for (const kind of backends) {
const prepared = (await readProjectionSnapshot(engine, slug, sourceId))!;
const chunks = prepared.chunks.filter(c => !only || only.includes(c.chunk_index))
.map(c => ({ chunk_index: c.chunk_index, chunk_text: c.chunk_text, chunk_source: c.chunk_source, embedding: vec(c.chunk_index + 1) }));
- expect(await (installPageEmbeddings as (...a: unknown[]) => Promise<boolean>)(engine, prepared, chunks, undefined, override)).toBe(true);
+ expect((await (installPageEmbeddings as (...a: unknown[]) => Promise<{ complete: boolean }>)(engine, prepared, chunks, undefined, override)).complete).toBe(true);
}
async function rebuild() {
await queuePageProjection(engine, sourceId, slug, 'test_rebuild');
diff --git a/test/put-page-persistence.test.ts b/test/put-page-persistence.test.ts
index 0e8a183c36..ed77ab51d5 100644
--- a/test/put-page-persistence.test.ts
+++ b/test/put-page-persistence.test.ts
@@ -410,14 +410,21 @@ describe('put_page persistence boundary', () => {
const body = content('Content with a replaced chunk generation.');
await engine.setConfig('sync.repo_path', '');
configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-test' } });
+ let rechunked: Array<[number, number, string]> = [];
__setEmbedTransportForTests(async ({ values }) => {
await importFromContent(engine, slug, body, { noEmbed: true, sourceId: 'default', forceRechunk: true });
+ rechunked = (await engine.getChunks(slug, { sourceId: 'default' })).map(chunk => [chunk.id, chunk.chunk_index, chunk.chunk_text]);
return { values, warnings: [], embeddings: values.map(() => new Array(1536).fill(0.1)), usage: { tokens: 1 } };
});
const result = await put(slug, body);
expect(result.response.isError).not.toBe(true);
- expect(await embedding(result)).toMatchObject({ state: 'committed', reason: 'revision_changed' });
- expect((await engine.getChunks(slug, { sourceId: 'default' })).every(chunk => chunk.embedding_is_null)).toBe(true);
+ // A4: the vectors describe the same chunk text and embedding input, so they land on the
+ // rechunked rows; the newer chunk generation itself stays (same ids, indices and text).
+ expect(await embedding(result)).toMatchObject({ state: 'committed' });
+ const after = await engine.getChunks(slug, { sourceId: 'default' });
+ expect(rechunked.length).toBeGreaterThan(0);
+ expect(after.map(chunk => [chunk.id, chunk.chunk_index, chunk.chunk_text])).toEqual(rechunked);
+ expect(after.every(chunk => !chunk.embedding_is_null)).toBe(true);
});
for (const action of ['soft-delete', 'hard-delete', 'recreate'] as const) {