Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(embeddings): exclude soft-deleted pages from raw signature invalidation (#5647)
garrytan3cf08f84dd97
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex 7d376a30e5..5caae7164e 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -306,7 +306,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/core/import-contextual-mode.ts": ["test/e2e/repair-contextual-mode-5621-postgres.test.ts"],"src/core/ai/embedding-guard.ts": ["test/e2e/embedding-zero-norm-4616-postgres.test.ts"],"src/commands/reindex-vectors.ts": ["test/e2e/embedding-zero-norm-4616-postgres.test.ts"],- "src/core/embedding-invalidation.ts": ["test/e2e/embed-stale-dry-run-restamp-5289-postgres.test.ts"],+ "src/core/embedding-invalidation.ts": ["test/e2e/embed-stale-dry-run-restamp-5289-postgres.test.ts", "test/e2e/embedding-tombstones-postgres.test.ts"],"src/core/persistence/effect-git.ts": ["test/e2e/persistence-git-coalescing-5530-postgres.test.ts"],"src/core/persistence/effect-journal.ts": ["test/e2e/persistence-git-coalescing-5530-postgres.test.ts"],"src/core/persistence/grandfather.ts": ["test/e2e/persistence-git-coalescing-5530-postgres.test.ts", "test/e2e/grandfather-projection-postgres.test.ts"],@@ -639,5 +639,5 @@ E2E_TEST_MAP["src/core/engine-sql/executor.ts"] = ENGINE_SQL_EXECUTOR_E2E;E2E_TEST_MAP["src/core/engine-sql/dialect-*.ts"] = ENGINE_SQL_EXECUTOR_E2E;E2E_TEST_MAP["src/core/engine-sql/normalize.ts"] = ["test/e2e/engine-sql-normalize-parity.test.ts"];E2E_TEST_MAP["src/core/engine-sql/brands.ts"] = ["test/e2e/engine-sql-rls-scope.test.ts"];-E2E_TEST_MAP["src/core/engine-sql/chunks.ts"] = ["test/e2e/evidence-delivery-leak.test.ts", "test/e2e/evidence-delivery-parity.test.ts"];+E2E_TEST_MAP["src/core/engine-sql/chunks.ts"] = ["test/e2e/evidence-delivery-leak.test.ts", "test/e2e/evidence-delivery-parity.test.ts", "test/e2e/embedding-tombstones-postgres.test.ts"];E2E_TEST_MAP["src/core/engine-sql/links.ts"] = ["test/e2e/links-read-order.test.ts", "test/e2e/attendance-retrieval-postgres.test.ts", "test/e2e/federated-link-reads-postgres.test.ts"];diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.tsindex 5cdad5f1aa..f33eef5be7 100644--- a/src/core/engine-sql/chunks.ts+++ b/src/core/engine-sql/chunks.ts@@ -414,6 +414,7 @@ export async function invalidateStaleSignatureEmbeddings(SET ${colId} = NULL, embedded_at = NULLFROM pages pWHERE cc.page_id = p.id+ AND p.deleted_at IS NULLAND p.source_id=ANY(${sources}::text[])AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived)AND cc.${colId} IS NOT NULLdiff --git a/test/e2e/embedding-tombstones-postgres.test.ts b/test/e2e/embedding-tombstones-postgres.test.tsnew file mode 100644index 0000000000..b8040a34ce--- /dev/null+++ b/test/e2e/embedding-tombstones-postgres.test.ts@@ -0,0 +1,86 @@+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';+import { installFixtureChunks } from '../helpers/page-projection.ts';+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { invalidateStaleSignatureEmbeddingsGuarded } from '../../src/core/embedding-invalidation.ts';+let engine: PostgresEngine;+const d = hasDatabase() ? describe : describe.skip;+async function seedUnembedded(slug: string, text: string) {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `# ${slug}` });+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_text: text, chunk_source: 'compiled_truth', token_count: 4 }]);+}+d('embedding migration excludes soft-deleted pages', () => {+ beforeAll(async () => { engine = await setupDB(); }, 60000);+ afterAll(async () => { await teardownDB(); });+ beforeEach(async () => { await engine.executeRaw('TRUNCATE pages CASCADE'); });+ test.each(['guarded', 'raw'] as const)('%s signature invalidation preserves tombstone vectors and invalidates live vectors', async (mode) => {+ const deleted = `deleted-drift-${mode}`;+ const live = `live-drift-${mode}`;+ const [{ dim }] = await engine.executeRaw<{ dim: number }>(+ "SELECT atttypmod AS dim FROM pg_attribute WHERE attrelid = 'content_chunks'::regclass AND attname = 'embedding' AND attnum > 0");+ for (const slug of [deleted, live]) {+ await seedUnembedded(slug, 'stale vector');+ await engine.executeRaw(+ `UPDATE content_chunks SET embedding = ('[' || array_to_string(array_fill(0.0::real, ARRAY[$1::int]), ',') || ']')::vector+ WHERE page_id = (SELECT id FROM pages WHERE slug = $2 AND source_id = 'default')`, [dim, slug]);+ await engine.setPageEmbeddingSignature(slug, { signature: 'old:model:1' });+ }+ await engine.softDeletePage(deleted, { sourceId: 'default' });+ const readVector = (slug: string) => engine.executeRaw<{ embedding: string | null }>(+ `SELECT cc.embedding::text AS embedding FROM content_chunks cc JOIN pages p ON p.id = cc.page_id+ WHERE p.slug = $1 AND p.source_id = 'default'`, [slug]);+ const retained = await readVector(deleted);+ expect(retained[0]!.embedding).not.toBeNull();+ const opts = { signature: 'new:model:1' };+ const invalidated = mode === 'guarded'+ ? await invalidateStaleSignatureEmbeddingsGuarded(engine, opts)+ : await engine.invalidateStaleSignatureEmbeddings(opts);+ expect(invalidated).toBe(1);+ expect(await readVector(deleted)).toEqual(retained);+ expect(await readVector(live)).toEqual([{ embedding: null }]);+ });+ test('content drift invalidates only live chunks and preserves deleted chunk metadata', async () => {+ for (const slug of ['deleted-content-drift', 'live-content-drift']) {+ await seedUnembedded(slug, 'current text');+ const [{ dim }] = await engine.executeRaw<{ dim: number }>(+ "SELECT atttypmod AS dim FROM pg_attribute WHERE attrelid='content_chunks'::regclass AND attname='embedding' AND attnum>0");+ await engine.executeRaw(`UPDATE content_chunks SET embedding=('[' || array_to_string(array_fill(0.0::real,ARRAY[$1::int]),',') || ']')::vector,+ embedded_text_hash=md5('old text'),embedded_at='2020-01-01T00:00:00Z'+ WHERE page_id=(SELECT id FROM pages WHERE slug=$2 AND source_id='default')`, [dim, slug]);+ }+ await engine.softDeletePage('deleted-content-drift', { sourceId: 'default' });+ const readDeleted = () => engine.executeRaw(`SELECT embedding::text,embedded_text_hash,embedded_at FROM content_chunks+ WHERE page_id=(SELECT id FROM pages WHERE slug='deleted-content-drift' AND source_id='default')`);+ const before = await readDeleted();+ expect(await engine.invalidateContentDriftEmbeddings()).toBe(1);+ expect(await readDeleted()).toEqual(before);+ expect(await engine.executeRaw(`SELECT embedding FROM content_chunks WHERE page_id=(SELECT id FROM pages+ WHERE slug='live-content-drift' AND source_id='default')`)).toEqual([{ embedding: null }]);+ });++ test('counts and both cursor orders ignore tombstones while preserving their recoverable chunks', async () => {+ await seedUnembedded('tombstone', 'deleted chunk');+ await engine.softDeletePage('tombstone', { sourceId: 'default' });+ await seedUnembedded('live', 'live');+ await seedUnembedded('later-tombstone', 'later deleted');+ await engine.softDeletePage('later-tombstone', { sourceId: 'default' });+ const updatedAt = '2020-01-02T03:04:05.000Z';+ await engine.executeRaw("UPDATE pages SET updated_at = $1::timestamptz WHERE slug = 'live' AND source_id = 'default'", [updatedAt]);+ for (const scope of [{}, { sourceId: 'default' }]) {+ expect(await engine.countStaleChunks(scope)).toBe(1);+ expect(await engine.countStaleChunks({ ...scope, signature: 'new:model:1024', includeNullSignature: true })).toBe(1);+ expect(await engine.sumStaleChunkChars(scope)).toBe(4);+ for (const orderBy of ['page_id', 'updated_desc'] as const) {+ const rows = await engine.listStaleChunks({ ...scope, orderBy, batchSize: 1 });+ expect(rows.map(row => row.slug)).toEqual(['live']);+ const last = rows[0]!;+ const rest = await engine.listStaleChunks({ ...scope, orderBy, batchSize: 1,+ afterPageId: last.page_id, afterChunkIndex: last.chunk_index,+ ...(orderBy === 'updated_desc' ? { afterUpdatedAt: updatedAt } : {}) });+ expect(rest).toHaveLength(0);+ }+ }+ expect((await engine.getPage('tombstone', { sourceId: 'default', includeDeleted: true }))?.deleted_at).not.toBeNull();+ expect(await engine.executeRaw("SELECT count(*)::int AS n FROM content_chunks WHERE page_id=(SELECT id FROM pages WHERE slug='tombstone')")).toEqual([{ n: 1 }]);+ });+});diff --git a/test/embedding-migration.test.ts b/test/embedding-migration.test.tsindex 465aad28a5..dc436aadab 100644--- a/test/embedding-migration.test.ts+++ b/test/embedding-migration.test.ts@@ -103,6 +103,71 @@ async function seedUnembedded(slug: string, text: string): Promise<void> {]);}+describe('embedding migration excludes soft-deleted pages', () => {+ test.each(['guarded', 'raw'] as const)('%s signature invalidation preserves tombstone vectors and invalidates live vectors', async (mode) => {+ await seedEmbedded('deleted-drift', 'retained vector', 'old:model:1');+ await seedEmbedded('live-drift', 'stale vector', 'old:model:1');+ await engine.softDeletePage('deleted-drift', { sourceId: 'default' });+ const readVector = (slug: string) => engine.executeRaw<{ embedding: string | null }>(+ `SELECT cc.embedding::text AS embedding FROM content_chunks cc JOIN pages p ON p.id = cc.page_id+ WHERE p.slug = $1 AND p.source_id = 'default'`, [slug]);+ const retained = await readVector('deleted-drift');+ expect(retained[0]!.embedding).not.toBeNull();+ const opts = { signature: 'new:model:1' };+ const invalidated = mode === 'guarded'+ ? await invalidateStaleSignatureEmbeddingsGuarded(engine, opts)+ : await engine.invalidateStaleSignatureEmbeddings(opts);+ expect(invalidated).toBe(1);+ expect(await readVector('deleted-drift')).toEqual(retained);+ expect(await readVector('live-drift')).toEqual([{ embedding: null }]);+ });++ test('content drift invalidates only live chunks and preserves deleted chunk metadata', async () => {+ for (const slug of ['deleted-content-drift', 'live-content-drift']) {+ await seedUnembedded(slug, 'current text');+ const [{ dim }] = await engine.executeRaw<{ dim: number }>(+ "SELECT atttypmod AS dim FROM pg_attribute WHERE attrelid='content_chunks'::regclass AND attname='embedding' AND attnum>0");+ await engine.executeRaw(`UPDATE content_chunks SET embedding=('[' || array_to_string(array_fill(0.0::real,ARRAY[$1::int]),',') || ']')::vector,+ embedded_text_hash=md5('old text'),embedded_at='2020-01-01T00:00:00Z'+ WHERE page_id=(SELECT id FROM pages WHERE slug=$2 AND source_id='default')`, [dim, slug]);+ }+ await engine.softDeletePage('deleted-content-drift', { sourceId: 'default' });+ const readDeleted = () => engine.executeRaw(`SELECT embedding::text,embedded_text_hash,embedded_at FROM content_chunks+ WHERE page_id=(SELECT id FROM pages WHERE slug='deleted-content-drift' AND source_id='default')`);+ const before = await readDeleted();+ expect(await engine.invalidateContentDriftEmbeddings()).toBe(1);+ expect(await readDeleted()).toEqual(before);+ expect(await engine.executeRaw(`SELECT embedding FROM content_chunks WHERE page_id=(SELECT id FROM pages+ WHERE slug='live-content-drift' AND source_id='default')`)).toEqual([{ embedding: null }]);+ });++ test('counts and both cursor orders ignore tombstones while preserving their recoverable chunks', async () => {+ await seedUnembedded('tombstone', 'deleted chunk');+ await engine.softDeletePage('tombstone', { sourceId: 'default' });+ await seedUnembedded('live', 'live');+ await seedUnembedded('later-tombstone', 'later deleted');+ await engine.softDeletePage('later-tombstone', { sourceId: 'default' });+ const updatedAt = '2020-01-02T03:04:05.000Z';+ await engine.executeRaw("UPDATE pages SET updated_at = $1::timestamptz WHERE slug = 'live' AND source_id = 'default'", [updatedAt]);+ for (const scope of [{}, { sourceId: 'default' }]) {+ expect(await engine.countStaleChunks(scope)).toBe(1);+ expect(await engine.countStaleChunks({ ...scope, signature: 'new:model:1024', includeNullSignature: true })).toBe(1);+ expect(await engine.sumStaleChunkChars(scope)).toBe(4);+ for (const orderBy of ['page_id', 'updated_desc'] as const) {+ const rows = await engine.listStaleChunks({ ...scope, orderBy, batchSize: 1 });+ expect(rows.map(row => row.slug)).toEqual(['live']);+ const last = rows[0]!;+ const rest = await engine.listStaleChunks({ ...scope, orderBy, batchSize: 1,+ afterPageId: last.page_id, afterChunkIndex: last.chunk_index,+ ...(orderBy === 'updated_desc' ? { afterUpdatedAt: updatedAt } : {}) });+ expect(rest).toHaveLength(0);+ }+ }+ expect((await engine.getPage('tombstone', { sourceId: 'default', includeDeleted: true }))?.deleted_at).not.toBeNull();+ expect(await engine.executeRaw("SELECT count(*)::int AS n FROM content_chunks WHERE page_id=(SELECT id FROM pages WHERE slug='tombstone')")).toEqual([{ n: 1 }]);+ });+});+describe('resolveMigrationTarget', () => {test('requires provider:model shape', () => {expect(() => resolveMigrationTarget('text-embedding-3-small')).toThrow(/provider:model/);diff --git a/test/fixtures/goldens/sql-text/chunks.json b/test/fixtures/goldens/sql-text/chunks.jsonindex 145005204a..e9d7ab3337 100644--- a/test/fixtures/goldens/sql-text/chunks.json+++ b/test/fixtures/goldens/sql-text/chunks.json@@ -368,8 +368,8 @@"number","string"],- "sql": "UPDATE content_chunks cc SET \"embedding\" = NULL, embedded_at = NULL FROM pages p WHERE cc.page_id = p.id AND p.source_id=ANY($1::text[]) AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived) AND cc.\"embedding\" IS NOT NULL AND NOT COALESCE(cc.\"embedding\" IS NOT NULL AND cc.model = $2 AND cc.embedded_text_hash = md5(cc.chunk_text) AND vector_dims(cc.\"embedding\") = $3::int, false) AND p.embedding_signature IS NOT NULL AND p.embedding_signature <> $4 RETURNING cc.page_id",- "textSha256": "2bd3f6a068cb4a3c724b5f69f4931157befef13a6be8692441dbdf8c024bab1f"+ "sql": "UPDATE content_chunks cc SET \"embedding\" = NULL, embedded_at = NULL FROM pages p WHERE cc.page_id = p.id AND p.deleted_at IS NULL AND p.source_id=ANY($1::text[]) AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived) AND cc.\"embedding\" IS NOT NULL AND NOT COALESCE(cc.\"embedding\" IS NOT NULL AND cc.model = $2 AND cc.embedded_text_hash = md5(cc.chunk_text) AND vector_dims(cc.\"embedding\") = $3::int, false) AND p.embedding_signature IS NOT NULL AND p.embedding_signature <> $4 RETURNING cc.page_id",+ "textSha256": "21e7a3a312ece95c266d3a91240a030475b0bae3598aa9be1d066d307ace6b8b"},{"event": "commit",@@ -405,8 +405,8 @@"string","string"],- "sql": "UPDATE content_chunks cc SET \"embedding\" = NULL, embedded_at = NULL FROM pages p WHERE cc.page_id = p.id AND p.source_id=ANY($1::text[]) AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived) AND cc.\"embedding\" IS NOT NULL AND NOT COALESCE(cc.\"embedding\" IS NOT NULL AND cc.model = $2 AND cc.embedded_text_hash = md5(cc.chunk_text) AND vector_dims(cc.\"embedding\") = $3::int, false) AND (p.embedding_signature IS NULL OR p.embedding_signature <> $4) AND p.source_id = $5 RETURNING cc.page_id",- "textSha256": "99f8496f2395f592fb2c2526bd01d4cce71296c700a8e4d5a8e40624b886db40"+ "sql": "UPDATE content_chunks cc SET \"embedding\" = NULL, embedded_at = NULL FROM pages p WHERE cc.page_id = p.id AND p.deleted_at IS NULL AND p.source_id=ANY($1::text[]) AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived) AND cc.\"embedding\" IS NOT NULL AND NOT COALESCE(cc.\"embedding\" IS NOT NULL AND cc.model = $2 AND cc.embedded_text_hash = md5(cc.chunk_text) AND vector_dims(cc.\"embedding\") = $3::int, false) AND (p.embedding_signature IS NULL OR p.embedding_signature <> $4) AND p.source_id = $5 RETURNING cc.page_id",+ "textSha256": "6349179f5610dc303ad7be6584575ad4df865ce166939cd9d44e896b68c4b8e2"},{"event": "commit",