Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: preserve legacy raw vectors across contextual reindex and reject import races

time-attackb0b84c7c2182
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2f70f46720..ef20524769 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -36,7 +36,7 @@ cost to replace any cleared vectors.
- The shared page-state writer clears active vectors and their completion stamps atomically on a contextual-to-`none` transition, in both PGLite and PostgreSQL.
- Projection rebuilds no longer accept an unstamped vector on an explicit `none` page as proof that it came from raw text; they still preserve verified current inputs and grandfather pre-contextual NULL-mode pages.
-- Markdown re-import cannot reinstate an unstamped title vector after the mode switch and label it as raw. Repairing a pre-contextual NULL-mode page into `none` records raw provenance for retained vectors so a later rebuild does not discard them.
+- Markdown re-import cannot reinstate an unstamped title vector after the mode switch or race a concurrent contextual update. Repair and contextual reindex record raw provenance when they move a pre-contextual NULL-mode page to `none`, so a later rebuild does not discard retained raw vectors.
## [0.60.69.0] - 2026-10-05
diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.md
index 1d0f9b02fa..13dbb7aaf1 100644
--- a/docs/architecture/RETRIEVAL.md
+++ b/docs/architecture/RETRIEVAL.md
@@ -517,15 +517,17 @@ 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 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.
+written before that record existed are grandfathered on pages whose mode
+is still NULL; contextual-mode repair and reindex stamp compatible raw inputs
+when moving those pages to explicit `none`. 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.
Markdown chunk creation applies the strict protected-body sanitizer before
splitting text. For remote reads, all existing chunks of every page kind are
diff --git a/src/core/contextual-retrieval-service.ts b/src/core/contextual-retrieval-service.ts
index 0162bc6fe3..e3f39102a6 100644
--- a/src/core/contextual-retrieval-service.ts
+++ b/src/core/contextual-retrieval-service.ts
@@ -62,6 +62,7 @@ import type { BrainEngine } from './engine.ts';
import type { ChunkInput, CRMode, Page } from './types.ts';
import type { SourceRow } from './sources-ops.ts';
import { installPageEmbeddings, readProjectionSnapshot, type ProjectionSnapshot } from './page-state/projections.ts';
+import { reconcileContextualEmbeddingInputs } from './page-state/contextual-proof.ts';
import { digest } from './persistence/digest.ts';
/**
@@ -328,6 +329,10 @@ export async function reembedPageWithContextualRetrieval(
if (!sameProjection(prepared, current)) return false;
}
await tx.updatePageContextualRetrievalState(page.slug, page.source_id, mode, generation);
+ if (!embedded && mode === 'none' && page.contextual_retrieval_mode == null
+ && !Object.hasOwn(page.frontmatter ?? {}, 'embed_skip')) {
+ await reconcileContextualEmbeddingInputs(tx, prepared.snapshot, mode, generation);
+ }
return true;
});
return installed ? null : superseded;
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 7861968c89..a56473a683 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -823,7 +823,7 @@ export async function importFromContent(
let persistedProjection: ProjectionSnapshot | null = null;
const [timeZone, mentionPolicy] = await Promise.all([loadBrainTimeZone(engine), readMentionPolicy(engine).catch(() => null)]);
const applyPrepared = async (tx: BrainEngine, preimage?: PageSnapshot | null) => {
- if (!opts.coordinated) await assertImportBase(tx, slug, txOpts.sourceId, existing);
+ if (!opts.coordinated) await assertImportBase(tx, slug, txOpts.sourceId, existing, reused.size > 0);
await assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || '', slug);
if (existing) await tx.createVersion(slug, preimage ? { ...txOpts, preimage } : txOpts);
diff --git a/src/core/page-state/contextual-proof.ts b/src/core/page-state/contextual-proof.ts
new file mode 100644
index 0000000000..285f2f1a3f
--- /dev/null
+++ b/src/core/page-state/contextual-proof.ts
@@ -0,0 +1,28 @@
+import type { BrainEngine } from '../engine.ts';
+import type { PageSnapshot } from './types.ts';
+import { quoteIdentifier } from '../search/embedding-column.ts';
+import { acceptedEmbeddingInputHashes, embeddingInputHash, isContextualMode } from '../embedding-input-hash.ts';
+import { embeddingInputContext, embeddingWriteTarget } from './projections.ts';
+
+export async function reconcileContextualEmbeddingInputs(tx: BrainEngine, snapshot: PageSnapshot,
+ mode: string, corpusGeneration: string | null): Promise<number> {
+ const target = await embeddingWriteTarget(tx);
+ const chunks = await tx.getChunks(snapshot.page.slug, { sourceId: snapshot.page.source_id, includeUnsealed: true });
+ const provenance = embeddingInputContext(target, snapshot.page.title, corpusGeneration, chunks);
+ const recorded = new Map((await tx.executeRaw<{ id: number; embedding_input_hash: string | null }>(
+ 'SELECT id,embedding_input_hash FROM content_chunks WHERE page_id=$1', [snapshot.page.id])).map(r => [Number(r.id), r.embedding_input_hash]));
+ const stale = chunks.filter(chunk => !chunk.embedding_is_null).filter(chunk => {
+ const hash = recorded.get(Number(chunk.id)) ?? null;
+ return hash === null ? isContextualMode(mode) || chunk.model !== target.provenanceModel
+ : !acceptedEmbeddingInputHashes(provenance, mode, chunk).includes(hash);
+ }).map(chunk => Number(chunk.id));
+ if (stale.length) await tx.executeRaw(`UPDATE content_chunks SET ${quoteIdentifier(target.column.name)}=NULL,
+ embedded_at=NULL,embedded_text_hash=NULL,embedding_input_hash=NULL WHERE page_id=$1 AND id=ANY($2::int[])`, [snapshot.page.id, stale]);
+ const staleIds = new Set(stale);
+ const raw = chunks.filter(chunk => !chunk.embedding_is_null && !staleIds.has(Number(chunk.id))
+ && recorded.get(Number(chunk.id)) == null);
+ if (raw.length) await tx.executeRaw(`UPDATE content_chunks c SET embedding_input_hash=proof.hash
+ FROM unnest($2::int[],$3::text[]) AS proof(id,hash) WHERE c.page_id=$1 AND c.id=proof.id`,
+ [snapshot.page.id, raw.map(chunk => Number(chunk.id)), raw.map(chunk => embeddingInputHash(provenance, 'none', chunk))]);
+ return stale.length;
+}
diff --git a/src/core/page-state/import-guard.ts b/src/core/page-state/import-guard.ts
index fb3acc3c3e..586f77e242 100644
--- a/src/core/page-state/import-guard.ts
+++ b/src/core/page-state/import-guard.ts
@@ -7,7 +7,7 @@ import { stableJson } from '../persistence/digest.ts';
import { assertPageRevision, type PageSnapshot } from './types.ts';
/** Imported bytes are prepared outside transactions; publication still needs CAS. */
-export async function assertImportBase(tx: BrainEngine, slug: string, sourceId: string, existing: Page | null): Promise<void> {
+export async function assertImportBase(tx: BrainEngine, slug: string, sourceId: string, existing: Page | null, reusedEmbeddings = false): Promise<void> {
await tx.lockPageKeys([{ sourceId, slug }]);
const current = await tx.getPage(slug, { sourceId, includeDeleted: true });
if ((current?.id ?? null) !== (existing?.id ?? null)) {
@@ -16,6 +16,11 @@ export async function assertImportBase(tx: BrainEngine, slug: string, sourceId:
{ fix: readFix(`Shows which page holds ${slug} now and its revision.`, { argv: ['gbrain', 'get', '--source', sourceId, '--', slug], mcp: { tool: 'get_page', arguments: { slug, source_id: sourceId } } }) });
}
assertPageRevision(current ? { revision: current.knowledge_revision! } : null, existing ? { expectedRevision: existing.knowledge_revision } : {});
+ if (reusedEmbeddings && (current?.contextual_retrieval_mode ?? null) !== (existing?.contextual_retrieval_mode ?? null)) {
+ throw opError('revision_conflict', 'The contextual retrieval mode changed while this import prepared reusable embeddings; nothing was written.',
+ `Page ${slug} in source ${sourceId} changed embedding mode without changing its canonical revision. Read the current page, then retry the import so it builds vectors for that mode.`,
+ { fix: readFix('Reads the current page before retrying the import.', { argv: ['gbrain', 'get', '--source', sourceId, '--', slug], mcp: { tool: 'get_page', arguments: { slug, source_id: sourceId } } }) });
+ }
}
const canonicalFields = (p: Page | ParsedPage) => ({ type: p.type, title: p.title, compiled_truth: p.compiled_truth,
timeline: p.timeline ?? '', frontmatter: p.frontmatter });
diff --git a/src/core/repair/contextual-mode.ts b/src/core/repair/contextual-mode.ts
index 4cb9d9df52..5ff7adef31 100644
--- a/src/core/repair/contextual-mode.ts
+++ b/src/core/repair/contextual-mode.ts
@@ -15,9 +15,7 @@
* pages are left alone and counted.
*/
import type { BrainEngine } from '../engine.ts';
-import { quoteIdentifier } from '../search/embedding-column.ts';
-import { acceptedEmbeddingInputHashes, embeddingInputHash, isContextualMode } from '../embedding-input-hash.ts';
-import { embeddingInputContext, embeddingWriteTarget } from '../page-state/projections.ts';
+import { reconcileContextualEmbeddingInputs } from '../page-state/contextual-proof.ts';
import { resolveImportContextualMode } from '../import-contextual-mode.ts';
import { embedStalePages } from '../embed-stale.ts';
import { afterCursor, type RepairCursor, type RepairHandler, type RepairItem, type RepairScope } from './core.ts';
@@ -46,25 +44,7 @@ export const contextualModeRepair: RepairHandler = {
|| Object.hasOwn(snapshot.page.frontmatter ?? {}, 'embed_skip')) return null;
const { mode, corpusGeneration } = await resolveImportContextualMode(tx, item.source_id, snapshot.page.frontmatter, true);
await tx.updatePageContextualRetrievalState(item.slug, item.source_id, mode, corpusGeneration);
- const target = await embeddingWriteTarget(tx);
- const chunks = await tx.getChunks(item.slug, { sourceId: item.source_id, includeUnsealed: true });
- const provenance = embeddingInputContext(target, snapshot.page.title, corpusGeneration, chunks);
- const recorded = new Map((await tx.executeRaw<{ id: number; embedding_input_hash: string | null }>(
- 'SELECT id,embedding_input_hash FROM content_chunks WHERE page_id=$1', [snapshot.page.id])).map(r => [Number(r.id), r.embedding_input_hash]));
- const stale = chunks.filter(chunk => !chunk.embedding_is_null).filter(chunk => {
- const hash = recorded.get(Number(chunk.id)) ?? null;
- return hash === null ? isContextualMode(mode) || chunk.model !== target.provenanceModel
- : !acceptedEmbeddingInputHashes(provenance, mode, chunk).includes(hash);
- }).map(chunk => Number(chunk.id));
- if (stale.length) await tx.executeRaw(`UPDATE content_chunks SET ${quoteIdentifier(target.column.name)}=NULL,
- embedded_at=NULL,embedded_text_hash=NULL,embedding_input_hash=NULL WHERE page_id=$1 AND id=ANY($2::int[])`, [snapshot.page.id, stale]);
- const staleIds = new Set(stale);
- const raw = chunks.filter(chunk => !chunk.embedding_is_null && !staleIds.has(Number(chunk.id))
- && recorded.get(Number(chunk.id)) == null);
- if (raw.length) await tx.executeRaw(`UPDATE content_chunks c SET embedding_input_hash=proof.hash
- FROM unnest($2::int[],$3::text[]) AS proof(id,hash) WHERE c.page_id=$1 AND c.id=proof.id`,
- [snapshot.page.id, raw.map(chunk => Number(chunk.id)), raw.map(chunk => embeddingInputHash(provenance, 'none', chunk))]);
- return stale.length;
+ return reconcileContextualEmbeddingInputs(tx, snapshot, mode, corpusGeneration);
});
if (cleared === null) return false;
if (cleared > 0 && opts?.embed) {
diff --git a/test/import-revision-concurrency.test.ts b/test/import-revision-concurrency.test.ts
index 3a43dacd42..28aac2a3f7 100644
--- a/test/import-revision-concurrency.test.ts
+++ b/test/import-revision-concurrency.test.ts
@@ -77,3 +77,18 @@ test('absence guards reject create races and physical recreation of the same slu
expect((await engine.getPage(slug, { sourceId }))!.frontmatter.captured_at).toBe('recreated');
}
});
+
+test('embedding reuse refuses a concurrent contextual-mode change without a canonical revision change', async () => {
+ for (const engine of engines) {
+ const slug = 'notes/contextual-race';
+ await importFromContent(engine, slug, content('initial'), { sourceId, noEmbed: true });
+ const original = (await engine.getPage(slug, { sourceId }))!;
+ await engine.updatePageContextualRetrievalState(slug, sourceId, 'none', null);
+ const updated = (await engine.getPage(slug, { sourceId }))!;
+ expect(updated.knowledge_revision).toBe(original.knowledge_revision);
+ await expect(engine.transaction(tx => assertImportBase(tx, slug, sourceId, original, true)))
+ .rejects.toMatchObject({ code: 'revision_conflict',
+ fix: { argv: ['gbrain', 'get', '--source', sourceId, '--', slug] } });
+ expect((await engine.getPage(slug, { sourceId }))!.contextual_retrieval_mode).toBe('none');
+ }
+});
diff --git a/test/repair-contextual-mode-5621.serial.test.ts b/test/repair-contextual-mode-5621.serial.test.ts
index 3a79bb6186..fac685d0e6 100644
--- a/test/repair-contextual-mode-5621.serial.test.ts
+++ b/test/repair-contextual-mode-5621.serial.test.ts
@@ -23,6 +23,7 @@ import { runRepair, resolveRepairScope } from '../src/core/repair/core.ts';
import { contextualModeRepair } from '../src/core/repair/contextual-mode.ts';
import { checkContextualRetrievalCoverage } from '../src/commands/doctor/checks/calibration.ts';
import { titleTierCorpusGeneration } from '../src/core/contextual-retrieval-service.ts';
+import { reembedPageWithContextualRetrieval } from '../src/core/contextual-retrieval-service.ts';
import { __setEmbedTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { testBackends } from './helpers/test-backends.ts';
@@ -117,6 +118,24 @@ for (const kind of testBackends()) describe(`#5621 gbrain repair contextual-mode
expect(await vectors('off', slug)).toEqual(stamped);
});
+ test('contextual reindex stamps grandfathered raw vectors when resolving a NULL mode to none', async () => {
+ const slug = 'notes/legacy-raw-reindex';
+ await legacyPage('off', slug, 'Legacy Reindex Example');
+ await engine.executeRaw(`UPDATE content_chunks SET embedding_input_hash=NULL WHERE page_id=(SELECT id FROM pages WHERE source_id='off' AND slug=$1)`, [slug]);
+ const before = await vectors('off', slug);
+ inputs = [];
+ expect(await reembedPageWithContextualRetrieval({ engine, pageSlug: slug, sourceId: 'off', globalMode: 'none' }))
+ .toMatchObject({ kind: 'skipped', reason: 'mode_none' });
+ const stamped = await vectors('off', slug);
+ expect((await page('off', slug)).mode).toBe('none');
+ expect(stamped.map(row => row.v)).toEqual(before.map(row => row.v));
+ expect(stamped.every(row => row.h !== null)).toBe(true);
+ expect(inputs).toHaveLength(0);
+ await queuePageProjection(engine, 'off', slug, 'regression');
+ await rebuildPendingPageProjections(engine, 10);
+ expect(await vectors('off', slug)).toEqual(stamped);
+ });
+
test('stamps like a fresh import; unchanged inputs queue no re-embed, changed inputs re-embed once; a second run changes nothing', async () => {
await legacyPage('plain', 'notes/raw-embedded', 'Raw Embedded Example');
await legacyPage('off', 'notes/source-off', 'Source Off Example');