Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: invalidate unverified contextual vectors on raw-mode transition

time-attack404801e485e6
diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.md
index 26a8cea76a..1d0f9b02fa 100644
--- a/docs/architecture/RETRIEVAL.md
+++ b/docs/architecture/RETRIEVAL.md
@@ -517,8 +517,12 @@ built from (`content_chunks.embedding_input_hash`: column, model, dimensions,
wrapping tier and wrapped text), and a rebuild keeps it only when the current
page would produce the same input, so an unchanged contextual page keeps its
vectors and a synopsis-mode body edit nulls every synopsis-tier chunk. Vectors
-written before that record existed are kept on non-contextual pages and nulled
-once on contextual ones. Remaining NULL vectors still need an explicitly
+written before that record existed are grandfathered only on pages whose mode
+is still NULL. An explicit `none` page may have inherited a title-wrapped
+vector, so a rebuild clears unstamped vectors there, and switching from title
+or synopsis to `none` clears active text vectors immediately. Genuine old raw
+vectors on explicit `none` pages may need a one-time re-embed; it never starts
+automatically. Remaining NULL vectors still need an explicitly
authorized `gbrain embed --stale` run. A text-ready index is not a promise that
every page has a vector. Diagnostics do not disclose private or foreign-source
pending pages and never start repair themselves.
diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.ts
index 51deedf279..b6306b104a 100644
--- a/src/core/engine-sql/pages.ts
+++ b/src/core/engine-sql/pages.ts
@@ -28,6 +28,7 @@ import type { LegacyUnscopedRead, ScopedRead } from './brands.ts';
import type { ScopedReadRunner } from './cjk-search.ts';
import { compileRowNormalizer } from './normalize.ts';
import { renderFragment, sqlFragment, trustedSql } from './fragment.ts';
+import { quoteIdentifier, resolveWriteColumnFromConfigRows } from '../search/embedding-column.ts';
/**
* PGLite can return zero rows from `INSERT ... ON CONFLICT DO UPDATE ...
@@ -314,6 +315,35 @@ export async function updatePageContextualRetrievalState(
mode: string,
corpusGeneration: string | null,
): Promise<void> {
+ if (mode === 'none') {
+ const { rows: config } = await exec.run<{ key: string; value: string }>(sqlFragment`
+ SELECT key,value FROM config WHERE key IN ('search_embedding_column','embedding_columns')`);
+ const column = resolveWriteColumnFromConfigRows({
+ searchEmbeddingColumn: config.find(row => row.key === 'search_embedding_column')?.value ?? null,
+ embeddingColumnsJson: config.find(row => row.key === 'embedding_columns')?.value ?? null,
+ });
+ const vector = trustedSql(quoteIdentifier(column.name));
+ await exec.run(sqlFragment`
+ WITH previous AS MATERIALIZED (
+ SELECT id, contextual_retrieval_mode AS old_mode,
+ COALESCE(frontmatter, '{}'::jsonb) ? 'embed_skip' AS skipped
+ FROM pages WHERE source_id=${sourceId} AND slug=${slug} AND deleted_at IS NULL
+ FOR UPDATE
+ ), changed AS (
+ UPDATE pages p SET contextual_retrieval_mode=${mode}, corpus_generation=${corpusGeneration},
+ updated_at=now(), embedding_signature=CASE
+ WHEN previous.old_mode IN ('title','per_chunk_synopsis') AND NOT previous.skipped
+ THEN NULL ELSE p.embedding_signature END
+ FROM previous WHERE p.id=previous.id
+ RETURNING p.id, previous.old_mode, previous.skipped
+ )
+ UPDATE content_chunks cc SET ${vector}=NULL, embedded_at=NULL,
+ embedded_text_hash=NULL, embedding_input_hash=NULL
+ FROM changed WHERE cc.page_id=changed.id
+ AND changed.old_mode IN ('title','per_chunk_synopsis') AND NOT changed.skipped
+ AND cc.${vector} IS NOT NULL`);
+ return;
+ }
// Narrow UPDATE — bumps updated_at as a side effect so the autopilot
// sweep doesn't think the page hasn't changed since last touch. Skips
// soft-deleted rows. corpus_generation nullable (caller passes NULL
diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.ts
index 8a9dc9d0db..543c0f5d4f 100644
--- a/src/core/page-state/projections.ts
+++ b/src/core/page-state/projections.ts
@@ -13,7 +13,7 @@ import { getFtsLanguage } from '../fts-language.ts';
import { getEmbeddingModel } from '../ai/gateway.ts';
import { refreshProjectionStatistics } from '../search/projection-statistics.ts';
import { belowSafeChunkFence } from '../search/safe-chunks.ts';
-import { acceptedEmbeddingInputHashes, embeddingInputHash, isContextualMode, plainEmbeddingTier, synopsisBodyHash,
+import { acceptedEmbeddingInputHashes, embeddingInputHash, plainEmbeddingTier, synopsisBodyHash,
type EmbeddingInputContext, type EmbeddingTier } from '../embedding-input-hash.ts';
/**
@@ -158,13 +158,15 @@ export async function installPageProjection(engine: BrainEngine, prepared: Proje
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 where that input is its raw text; on a contextual page it is
+ // only in the pre-contextual NULL mode; explicit none may have inherited
+ // an old title vector, so its missing proof cannot authorize retention.
+ // On a contextual page it is
// nulled once and stamped by its re-embed.
const mode = current!.page.contextual_retrieval_mode;
const provenance = embeddingInputContext(context, current!.page.title, context.corpusGeneration, chunks);
const 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 ? !isContextualMode(mode)
+ 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,
embedded_at=NULL,embedded_text_hash=NULL,embedding_input_hash=NULL WHERE page_id=$1 AND
diff --git a/test/page-projection-vector-preservation.test.ts b/test/page-projection-vector-preservation.test.ts
index 777ca6845a..b7893fec40 100644
--- a/test/page-projection-vector-preservation.test.ts
+++ b/test/page-projection-vector-preservation.test.ts
@@ -137,9 +137,57 @@ for (const kind of backends) {
expect(await canonicalState(neighborId)).toEqual(canonical);
});
+ for (const oldMode of ['title', 'per_chunk_synopsis']) {
+ test(`legacy ${oldMode} vectors are cleared atomically when the stored mode becomes none`, async () => {
+ const page = await seed();
+ await engine.updatePageContextualRetrievalState(slug, sourceId, oldMode, 'legacy-generation');
+ await engine.executeRaw(`UPDATE content_chunks SET embedded_text_hash=md5(chunk_text),
+ embedding_input_hash=NULL WHERE page_id=$1`, [page.page.id]);
+ expect((await storedChunks()).map(c => c.embedding)).toEqual([vectorText, vectorText]);
+ await engine.updatePageContextualRetrievalState(slug, sourceId, 'none', null);
+ expect((await storedChunks()).map(c => [c.embedding, c.embedded_at, c.embedded_text_hash])).toEqual([
+ [null, null, null], [null, null, null],
+ ]);
+ const prepared = (await readProjectionSnapshot(engine, slug, sourceId, { allowUnsealed: true }))!;
+ await installPageProjection(engine, prepared, (await preparePageProjection(prepared)).chunks, preserve);
+ expect((await storedChunks()).map(c => c.embedding)).toEqual([null, null]);
+ });
+ }
+
+ test('an embed_skip page retains its vector when metadata switches to none', async () => {
+ const page = await seed();
+ await engine.updatePageContextualRetrievalState(slug, sourceId, 'title', 'legacy-generation');
+ await engine.executeRaw(`UPDATE pages SET frontmatter='{"embed_skip":true}'::jsonb WHERE id=$1`, [page.page.id]);
+ await engine.updatePageContextualRetrievalState(slug, sourceId, 'none', null);
+ expect((await storedChunks()).map(c => c.embedding)).toEqual([vectorText, vectorText]);
+ });
+
+ test('the mode switch clears only the selected source and active vector column', async () => {
+ const page = await seed();
+ await seed(neighborId);
+ const neighbor = await storedChunks(neighborId);
+ await engine.executeRaw('ALTER TABLE content_chunks ADD COLUMN embedding_projection_test vector(3)');
+ try {
+ await engine.setConfig('embedding_columns', JSON.stringify({
+ embedding_projection_test: { provider: 'openai:fixture', dimensions: 3, type: 'vector' },
+ }));
+ await engine.setConfig('search_embedding_column', 'embedding_projection_test');
+ await engine.executeRaw(`UPDATE content_chunks SET embedding_projection_test='[0.375,-0.25,0]'::vector(3)
+ WHERE page_id=$1`, [page.page.id]);
+ await engine.updatePageContextualRetrievalState(slug, sourceId, 'title', 'legacy-generation');
+ await engine.updatePageContextualRetrievalState(slug, sourceId, 'none', null);
+ expect((await storedChunks()).map(c => c.embedding_projection_test)).toEqual([null, null]);
+ expect((await storedChunks(neighborId)).map(c => c.embedding)).toEqual(neighbor.map(c => c.embedding));
+ } finally {
+ await engine.unsetConfig('search_embedding_column');
+ await engine.unsetConfig('embedding_columns');
+ await engine.executeRaw('ALTER TABLE content_chunks DROP COLUMN embedding_projection_test');
+ }
+ });
+
for (const state of [
{ name: 'NULL hash', hash: null, model: 'current', context: null, keep: true },
- { name: 'current hash', hash: 'current', model: 'current', context: 'none', keep: true },
+ { name: 'current hash', hash: 'current', model: 'current', context: 'none', keep: false },
{ name: 'stale hash', hash: 'stale', model: 'current', context: null, keep: false },
{ name: 'empty hash', hash: '', model: 'current', context: null, keep: false },
{ name: 'malformed hash', hash: "'); DROP TABLE pages; --", model: 'current', context: null, keep: false },