Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(persistence): a prepared page edit keeps unchanged chunk rows and their vectors
time-attack472317c04346
diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex e254d49691..88ca6277f3 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -35,7 +35,7 @@ import { embedMultimodal, currentEmbeddingSignature } from './embedding.ts';import { embedBatchKeepingUsable, embedBatchWithBackoff } from './embed-retry.ts';import { isEmbeddingZeroNormError, type EmbeddingZeroNormError } from './ai/embedding-guard.ts';import { slugifyPath, slugifyCodePath, isCodeFilePath, hasMalformedPathSegment } from './sync.ts';-import type { ChunkInput, Page, PageInput, PageType } from './types.ts';+import type { Chunk, ChunkInput, Page, PageInput, PageType } from './types.ts';import type { PageSnapshot } from './page-state/types.ts';import { pipelined } from './page-state/transactions.ts';import { addPageTags } from './page-state/tags.ts';@@ -759,26 +759,45 @@ export async function importFromContent(// recorded before provenance existed, when the input is the raw chunk text// under the same model. The old index must be sealed and neither body may// hold protected fences, so no reused vector can carry a private sibling.- const reused = new Set<number>();- if (existing && !existing.deleted_at && !opts.noEmbed && !opts.forceRechunk && !opts.prepare && !opts.onPostCommitEmbedding && chunks.length > 0- && !hasProtectedBody(`${existing.compiled_truth}\n${existing.timeline ?? ''}`) && !hasProtectedBody(`${parsed.compiled_truth}\n${parsed.timeline ?? ''}`)) {- const target = await embeddingWriteTarget(engine);- const provenance = embeddingInputContext(target, parsed.title, corpusGeneration, chunks);+ // A prepared (persistence) import defers embedding to its effect worker, so+ // it reuses inside its publication transaction, under the page guard, from+ // the chunks it is about to replace; only the chunks left without a vector+ // reach the provider.+ 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 reuseStoredVectors = async (exec: BrainEngine, into: ChunkInput[]): Promise<Map<number, number | null>> => {+ const reused = new Map<number, number | null>();+ const target = await embeddingWriteTarget(exec);+ const provenance = embeddingInputContext(target, parsed.title, corpusGeneration, into);const tier = effectiveCRMode === 'title' ? 'title' : 'none';- const recorded = new Map((await engine.executeRaw<{ chunk_index: number; embedding_input_hash: string | null }>(- `SELECT c.chunk_index, c.embedding_input_hash FROM content_chunks c JOIN pages p ON p.id = c.page_id- WHERE p.source_id = $1 AND p.slug = $2`, [sourceId ?? 'default', slug])).map(row => [Number(row.chunk_index), row.embedding_input_hash]));+ const rows = await exec.executeRaw<{ chunk_index: number; embedding_input_hash: string | null; contextual_retrieval_mode: string | null; text_only: 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+ FROM content_chunks c JOIN pages p ON p.id = c.page_id+ WHERE p.source_id = $1 AND p.slug = $2`, [sourceId ?? 'default', slug]);+ if (rows.length === 0) return reused;+ const recorded = new Map(rows.map(row => [Number(row.chunk_index), row.embedding_input_hash]));+ 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 engine.getChunks(slug, { sourceId: sourceId ?? 'default', includeEmbedding: true, requireSafeChunks: true }))- .filter(chunk => canReuseMarkdownVector(recorded.get(chunk.chunk_index), existing.contextual_retrieval_mode, tier, provenance, chunk));- for (const [i, matched] of planEmbeddingReuse(stored, chunks, c => `${c.chunk_source}\0${c.chunk_text}`).reuse) {- chunks[i].embedding = matched.embedding as Float32Array;- chunks[i].token_count = matched.token_count ?? undefined;- if (matched.model) chunks[i].model = matched.model;- reused.add(i);+ const stored = (await exec.getChunks(slug, { sourceId: sourceId ?? 'default', includeEmbedding: true, requireSafeChunks: true }))+ .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']);+ for (const [i, matched] of planEmbeddingReuse(stored, into, c => `${c.chunk_source}\0${c.chunk_text}`).reuse) {+ into[i].embedding = matched.embedding as Float32Array;+ into[i].token_count = matched.token_count ?? undefined;+ if (matched.model) into[i].model = matched.model;+ // The stored row already holds exactly what this chunk would insert (same+ // index, identity, vector, recorded input and text hash, no image or+ // multimodal vector the insert would drop), so it can stay in place.+ 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);}- }+ return reused;+ };+ const reused = reusable && !opts.noEmbed && !opts.prepare ? await reuseStoredVectors(engine, chunks) : new Map<number, number | null>();let embeddingPartial: EmbeddingZeroNormError | undefined;const embedChunks = async () => {@@ -852,6 +871,11 @@ export async function importFromContent(});if (existing && !preimage) await tx.createVersion(slug, txOpts); // reads the page itself, so before the page write+ // A prepared import keeps each stored row that is identical to its new chunk+ // and writes only the rest, so an edit rewrites only the chunks it changed.+ const fresh = reusable && opts.prepare ? chunks.map(chunk => ({ ...chunk })) : chunks;+ const kept = new Map([...(fresh !== chunks ? await reuseStoredVectors(tx, fresh) : [])].filter(([, id]) => id !== null));+ const keptIds = [...kept.values()];let written: Page | undefined;await pipelined(tx, [() => assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || '', slug),@@ -888,7 +912,8 @@ export async function importFromContent(},// Replace every derived row atomically. Only vectors the A13 reuse gate above admitted carry over; a new// seal otherwise inherits nothing from an older index, whose contextual vector may have included a private sibling.- () => tx.deleteChunks(slug, txOpts),+ () => keptIds.length ? tx.executeRaw(`DELETE FROM content_chunks WHERE page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = $2)+ AND NOT (id = ANY($3::int[]))`, [slug, txOpts.sourceId, keptIds]) : tx.deleteChunks(slug, txOpts),// Alias projection and readback share the page commit. A later writer can// no longer turn a successful import into a postcommit verification error.() => writePageAliases(tx, slug, sourceId ?? 'default', parsed, opts.activePack, mentionPolicy),@@ -909,9 +934,9 @@ export async function importFromContent(},async () => {if (chunks.length > 0) {- const embeddingColumn = await stampEmbeddingInputs(tx, chunks, null,+ const embeddingColumn = await stampEmbeddingInputs(tx, fresh, null,{ title: parsed.title, tier: effectiveCRMode === 'title' ? 'title' : 'none', corpusGeneration });- await tx.upsertChunks(slug, chunks, { ...txOpts, ...(embeddingColumn ? { embeddingColumn } : {}), sealChunkerVersion: MARKDOWN_CHUNKER_VERSION,+ await tx.upsertChunks(slug, kept.size ? fresh.filter((_, i) => !kept.has(i)) : fresh, { ...txOpts, ...(embeddingColumn ? { embeddingColumn } : {}), sealChunkerVersion: MARKDOWN_CHUNKER_VERSION,...(pageId !== undefined ? { pageId: Number(pageId) } : {}) });// v0.41.31: stamp embedding provenance when this import actually// embedded (not --no-embed), so a later model/dims swap is detectablediff --git a/test/persistence-edit-embedding-reuse.test.ts b/test/persistence-edit-embedding-reuse.test.tsnew file mode 100644index 0000000000..077a48dbe9--- /dev/null+++ b/test/persistence-edit-embedding-reuse.test.ts@@ -0,0 +1,127 @@+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { createHash, randomUUID } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { PostgresEngine } from '../src/core/postgres-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/operations.ts';+import { operationsByName } from '../src/core/operations.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { localHostId } from '../src/core/persistence/identity.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';+import { assertSafeE2eDatabaseUrl } from './helpers/db-guard.ts';++const DIMS = 1536;+const words = 'amber basalt cobalt dune ember fjord granite harbor iris jade kelp lagoon marble nickel onyx pumice quartz reef slate tundra'.split(' ');+function paragraphs(seed: number, count: number): string[] {+ let state = seed;+ const next = () => (state = (state * 1103515245 + 12345) % 2147483648) / 2147483648;+ return Array.from({ length: count }, () => Array.from({ length: 260 }, () => words[Math.floor(next() * words.length)]).join(' ') + '.');+}+const page = (title: string, body: string[], tags: string[] = []) =>+ `---\ntitle: ${title}\ntype: note\n${tags.length ? `tags: [${tags.join(', ')}]\n` : ''}---\n\n${body.join('\n\n')}\n`;+function vector(text: string): Float32Array {+ const digest = createHash('sha256').update(text).digest();+ return Float32Array.from({ length: DIMS }, (_, i) => (digest[i % 32]! - 128) / 128 + Math.sin(i + digest[(i * 7) % 32]!));+}++for (const kind of ['pglite', 'postgres'] as const) {+ const suite = kind === 'postgres' && !process.env.DATABASE_URL ? describe.skip : describe;+ suite(`${kind}: a prepared page edit keeps unchanged chunks`, () => {+ let engine: BrainEngine;+ const sources: string[] = [];+ beforeAll(async () => {+ engine = kind === 'postgres' ? new PostgresEngine() : new PGLiteEngine();+ if (kind === 'postgres') assertSafeE2eDatabaseUrl(process.env.DATABASE_URL!);+ await engine.connect(kind === 'postgres' ? { database_url: process.env.DATABASE_URL! } : {});+ await engine.initSchema();+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'synthetic-edit-reuse-fixture' } });+ __setEmbedTransportForTests(async () => { throw new Error('Provider called outside the effect worker'); });+ }, 120_000);+ afterAll(async () => {+ await disposePersistenceConsumer(engine);+ try {+ await engine.executeRaw('DELETE FROM persistence_effects WHERE source_id=ANY($1::text[])', [sources]);+ await engine.executeRaw('DELETE FROM persistence_requests WHERE source_id=ANY($1::text[])', [sources]);+ await engine.executeRaw('DELETE FROM sources WHERE id=ANY($1::text[])', [sources]);+ } finally {+ await engine.disconnect();+ __setEmbedTransportForTests(null); resetGateway();+ }+ }, 60_000);++ async function fixture() {+ const sourceId = `edit-reuse-${randomUUID().slice(0, 8)}`; sources.push(sourceId);+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);+ const context: OperationContext = { engine, sourceId, config: { engine: kind, embedding_disabled: true }, remote: false, dryRun: false,+ logger: { info() {}, warn() {}, error() {} } };+ const embedded: string[] = [];+ const write = async (slug: string, content: string) => {+ const requestId = randomUUID();+ const revision = (await engine.readPageSnapshot(slug, { sourceId }))?.revision;+ await engine.executeRaw("ALTER TABLE persistence_effects ALTER COLUMN next_attempt_at SET DEFAULT (now()+interval '1 hour')");+ try {+ const receipt = await operationsByName.put_page.handler(context, { slug, request_id: requestId, content, ...(revision ? { expected_revision: revision } : {}) });+ expect(receipt).toMatchObject({ state: 'committed' });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('ALTER TABLE persistence_effects ALTER COLUMN next_attempt_at SET DEFAULT now()');+ }+ const [row] = await engine.executeRaw<{ id: string }>('SELECT id FROM persistence_requests WHERE request_id=$1::uuid AND source_id=$2', [requestId, sourceId]);+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now()+interval '1 hour'");+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now() WHERE request_id=$1::uuid AND kind='embedding'", [row!.id]);+ await runPersistenceEffects(engine, { engine: kind }, { hostId: localHostId(), limit: 1,+ embedding: { signature: `openai:text-embedding-3-large:${DIMS}`, model: 'openai:text-embedding-3-large', embed: async texts => { embedded.push(...texts); return texts.map(vector); } } });+ };+ const rows = (slug: string) => engine.executeRaw<Record<string, unknown>>(`SELECT c.id, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding::text AS embedding,+ c.model, c.token_count, c.embedded_text_hash, c.embedding_input_hash, c.search_vector::text AS search_vector, c.modality+ FROM content_chunks c JOIN pages p ON p.id=c.page_id WHERE p.source_id=$1 AND p.slug=$2 ORDER BY c.chunk_index`, [sourceId, slug]);+ return { write, rows, embedded };+ }+ const withoutId = (rows: Record<string, unknown>[]) => rows.map(({ id: _id, ...rest }) => rest);++ test('a one-paragraph edit embeds only the changed chunks and stores what a fresh write stores', async () => {+ const { write, rows, embedded } = await fixture();+ const body = paragraphs(11, 8);+ await write('notes/edited', page('Reuse Fixture', body));+ const before = await rows("notes/edited");+ expect(before.length).toBeGreaterThan(3);+ expect(before.every(row => row.embedding !== null)).toBe(true);+ embedded.length = 0;+ body[3] = paragraphs(97, 1)[0]!;+ await write('notes/edited', page('Reuse Fixture', body));+ const after = await rows('notes/edited');+ const unchanged = after.filter(row => before.some(old => old.chunk_index === row.chunk_index && old.chunk_text === row.chunk_text));+ expect(unchanged.length).toBeGreaterThan(0);+ expect(embedded.length).toBe(after.length - unchanged.length);+ for (const row of unchanged) expect(row).toEqual(before.find(old => old.chunk_index === row.chunk_index)!);+ // A page written once with the edited content is the reference for every stored column.+ await write('notes/reference', page('Reuse Fixture', body));+ expect(withoutId(after)).toEqual(withoutId(await rows('notes/reference')));+ }, 120_000);++ test('a tag-only edit embeds nothing and keeps every chunk row', async () => {+ const { write, rows, embedded } = await fixture();+ const body = paragraphs(23, 5);+ await write('notes/tagged', page('Tag Fixture', body));+ const before = await rows('notes/tagged');+ embedded.length = 0;+ await write('notes/tagged', page('Tag Fixture', body, ['synthetic-tag']));+ expect(embedded).toEqual([]);+ expect(await rows('notes/tagged')).toEqual(before);+ }, 120_000);++ test('a title change under the title wrapper re-embeds every chunk', async () => {+ const { write, rows, embedded } = await fixture();+ const body = paragraphs(31, 5);+ await write('notes/retitled', page('First Title', body));+ const before = await rows('notes/retitled');+ embedded.length = 0;+ await write('notes/retitled', page('Second Title', body));+ const after = await rows('notes/retitled');+ expect(embedded.length).toBe(after.length);+ expect(embedded.every(text => text.includes('Second Title'))).toBe(true);+ expect(after.every(row => !before.some(old => old.id === row.id))).toBe(true);+ }, 120_000);+ });+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 3a2467de22..abf1620ee3 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -72,6 +72,7 @@ test/page-state-engine.test.tstest/persistence-commit-durability.test.tstest/persistence-deactivate.test.tstest/persistence-diagnostics.test.ts+test/persistence-edit-embedding-reuse.test.tstest/persistence-file-import.test.tstest/persistence-git-subdir-origin.test.tstest/persistence-graph-publication.test.ts