Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip: keep identical unembedded chunk rows on no-embed and deferred imports

time-attack2b83dc85f263
diff --git a/src/core/import-chunk-reuse.ts b/src/core/import-chunk-reuse.ts
index f9ecf5b160..70686ef1ba 100644
--- a/src/core/import-chunk-reuse.ts
+++ b/src/core/import-chunk-reuse.ts
@@ -13,20 +13,24 @@ import type { Chunk, ChunkInput, CRMode } from './types.ts';
* A13 reuse for one page import: copies each stored vector the reuse gate
* admits onto its matching new chunk in `into`, and maps the chunk's index to
* the stored row id when that row already holds exactly what the chunk would
- * insert (so a prepared import can keep it in place), else to null. A
+ * insert (so an import can keep it in place), else to null. With
+ * `keepUnembedded` (the in-transaction pass), an identical stored row with no
+ * vector also maps to its id when the new chunk carries no vector. A
* prepared import reuses nothing from a page stored under per-chunk synopsis.
*/
export async function reuseStoredChunkVectors(
exec: BrainEngine,
into: ChunkInput[],
- { slug, sourceId, title, corpusGeneration, tier, prepared }: { slug: string; sourceId: string; title: string; corpusGeneration: string | null; tier: 'title' | 'none'; prepared: boolean },
+ { slug, sourceId, title, corpusGeneration, tier, prepared, keepUnembedded = false }: { slug: string; sourceId: string; title: string; corpusGeneration: string | null; tier: 'title' | 'none'; prepared: boolean; keepUnembedded?: boolean },
): Promise<Map<number, number | null>> {
const reused = new Map<number, number | null>();
const target = await embeddingWriteTarget(exec);
const provenance = embeddingInputContext(target, title, corpusGeneration, into);
- const rows = await exec.executeRaw<{ chunk_index: number; embedding_input_hash: string | null; contextual_retrieval_mode: string | null; text_only: boolean }>(
+ const rows = await exec.executeRaw<{ chunk_index: number; embedding_input_hash: string | null; contextual_retrieval_mode: string | null; text_only: boolean; unembedded: boolean }>(
`SELECT c.chunk_index, c.embedding_input_hash, p.contextual_retrieval_mode,
- c.embedding_image IS NULL AND c.embedding_multimodal IS NULL AND c.embedded_text_hash = md5(c.chunk_text) AS text_only
+ c.embedding_image IS NULL AND c.embedding_multimodal IS NULL AND c.embedded_text_hash = md5(c.chunk_text) AS text_only,
+ c.embedding IS NULL AND c.embedding_image IS NULL AND c.embedding_multimodal IS NULL
+ AND c.embedding_input_hash IS NULL AND c.embedded_text_hash IS NULL AS unembedded
FROM content_chunks c JOIN pages p ON p.id = c.page_id
WHERE p.source_id = $1 AND p.slug = $2`, [sourceId, slug]);
if (rows.length === 0) return reused;
@@ -37,8 +41,8 @@ export async function reuseStoredChunkVectors(
const textOnly = new Set(rows.filter(row => row.text_only).map(row => Number(row.chunk_index)));
// Reuse is keyed on chunk source + text, so a stored chunk's current-input
// hash is the hash its matching new chunk would record.
- const stored = (await exec.getChunks(slug, { sourceId, includeEmbedding: true, requireSafeChunks: true }))
- .filter(chunk => canReuseMarkdownVector(recorded.get(chunk.chunk_index), rows[0]!.contextual_retrieval_mode, tier, provenance, chunk));
+ const all = await exec.getChunks(slug, { sourceId, includeEmbedding: true, requireSafeChunks: true });
+ const stored = all.filter(chunk => canReuseMarkdownVector(recorded.get(chunk.chunk_index), rows[0]!.contextual_retrieval_mode, tier, provenance, chunk));
const identity = (chunk: ChunkInput | Chunk) => JSON.stringify([chunk.chunk_index, chunk.chunk_text, chunk.chunk_source,
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']);
@@ -52,5 +56,17 @@ export async function reuseStoredChunkVectors(
const row = matched as Chunk;
reused.set(i, recorded.get(row.chunk_index) != null && textOnly.has(row.chunk_index) && identity(row) === identity(into[i]) ? row.id : null);
}
+ // A stored row that never got a vector stays in place under a new chunk that
+ // will not get one either (a --no-embed or deferred write): the same upsert
+ // over it would keep it as it is.
+ if (keepUnembedded) {
+ const unembedded = new Set(rows.filter(row => row.unembedded).map(row => Number(row.chunk_index)));
+ const byIndex = new Map(into.map((chunk, i) => [chunk.chunk_index, i]));
+ for (const row of all) {
+ const i = byIndex.get(row.chunk_index);
+ if (i === undefined || reused.has(i) || into[i]!.embedding || !unembedded.has(row.chunk_index)) continue;
+ if (identity(row) === identity(into[i]!)) reused.set(i, row.id);
+ }
+ }
return reused;
}
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 60e4f1a2f5..6c40c3ed67 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -767,7 +767,7 @@ export async function importFromContent(
const reusable = !!existing && !existing.deleted_at && !opts.forceRechunk && !opts.onPostCommitEmbedding && chunks.length > 0
&& !(opts.prepare && modeRequiresSynopsis(effectiveCRMode)) && !hasProtectedBody(`${existing.compiled_truth}\n${existing.timeline ?? ''}`) && !hasProtectedBody(`${parsed.compiled_truth}\n${parsed.timeline ?? ''}`);
const reuseCtx = { slug, sourceId: sourceId ?? 'default', title: parsed.title, corpusGeneration, tier: effectiveCRMode === 'title' ? 'title' as const : 'none' as const };
- const reuseStoredVectors = (exec: BrainEngine, into: ChunkInput[]) => reuseStoredChunkVectors(exec, into, { ...reuseCtx, prepared: !!opts.prepare });
+ const reuseStoredVectors = (exec: BrainEngine, into: ChunkInput[], keepUnembedded = false) => reuseStoredChunkVectors(exec, into, { ...reuseCtx, prepared: !!opts.prepare, keepUnembedded });
const reused = reusable && !opts.noEmbed && !opts.prepare ? await reuseStoredVectors(engine, chunks) : new Map<number, number | null>();
let embeddingPartial: EmbeddingZeroNormError | undefined;
@@ -847,7 +847,7 @@ export async function importFromContent(
// reuse is re-read here, under the page lock, so a kept row is one this
// transaction sees; --no-embed and deferred-embed imports keep vectors too.
const fresh = reusable ? chunks.map(chunk => ({ ...chunk })) : chunks;
- const kept = new Map([...(fresh !== chunks ? await reuseStoredVectors(tx, fresh) : [])].filter(([, id]) => id !== null));
+ const kept = new Map([...(fresh !== chunks ? await reuseStoredVectors(tx, fresh, true) : [])].filter(([, id]) => id !== null));
const keptIds = [...kept.values()];
let written: Page | undefined;
await pipelined(tx, [
diff --git a/test/import-inline-chunk-keep.test.ts b/test/import-inline-chunk-keep.test.ts
index aa29a3b187..1703e754cc 100644
--- a/test/import-inline-chunk-keep.test.ts
+++ b/test/import-inline-chunk-keep.test.ts
@@ -113,6 +113,29 @@ for (const kind of ['pglite', 'postgres'] as const) {
expect(strip(await rows('notes/no-embed-reference'))).toEqual(strip(after));
}, 120_000);
+ test('a --no-embed edit of a never-embedded page keeps its identical rows; an embedding import embeds them all', async () => {
+ const words = ['quebec', 'romeo', 'sierra', 'tango', 'uniform'];
+ await write('notes/keyless', page('Keyless', words), true);
+ const before = await rows('notes/keyless');
+ expect(before.every(row => row.embedding === null)).toBe(true);
+ words[3] = 'victor';
+ await write('notes/keyless', page('Keyless', words), true);
+ const after = await rows('notes/keyless');
+ const kept = after.filter(row => before.some(old => old.id === row.id));
+ const unchanged = after.filter(row => before.some(old => old.chunk_index === row.chunk_index && old.chunk_text === row.chunk_text));
+ expect(kept.length).toBeGreaterThan(0);
+ expect(kept.map(row => row.id)).toEqual(unchanged.map(row => row.id));
+ for (const row of kept) expect(row).toEqual(before.find(old => old.id === row.id)!);
+ await write('notes/keyless-reference', page('Keyless', words), true);
+ expect(withoutId(await rows('notes/keyless-reference'))).toEqual(withoutId(after));
+ embedded = [];
+ words[0] = 'whiskey';
+ await write('notes/keyless', page('Keyless', words));
+ const embeddedRows = await rows('notes/keyless');
+ expect(embedded.length).toBe(embeddedRows.length);
+ expect(embeddedRows.every(row => row.embedding !== null)).toBe(true);
+ }, 120_000);
+
test('an unchanged re-import with a protected fence keeps nothing', async () => {
const fence = '\n<!--- gbrain:takes:begin -->\nPRIVATE_CANARY\n<!--- gbrain:takes:end -->\n';
await write('notes/protected', page('Protected', ['mike', 'november', 'oscar'], fence));