Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(embedding): leave restamp-only vectors out of paid migration estimates (PR #6959)

time-attack2b1ac8f4bb06
diff --git a/src/core/embedding-invalidation.ts b/src/core/embedding-invalidation.ts
index 0fd1978e71..721244289e 100644
--- a/src/core/embedding-invalidation.ts
+++ b/src/core/embedding-invalidation.ts
@@ -43,11 +43,11 @@ export function splitEmbeddingSignature(signature: string): { model: string; dim
return { model: signature.slice(0, separator), dims };
}
-export function currentSpaceChunkPredicate(colId: string, modelParam: number, dimsParam: number): string {
- return `COALESCE(cc.${colId} IS NOT NULL
- AND cc.model = $${modelParam}
- AND cc.embedded_text_hash = md5(cc.chunk_text)
- AND vector_dims(cc.${colId}) = $${dimsParam}::int, false)`;
+export function currentSpaceChunkPredicate(colId: string, modelParam: number, dimsParam: number, alias = 'cc'): string {
+ return `COALESCE(${alias}.${colId} IS NOT NULL
+ AND ${alias}.model = $${modelParam}
+ AND ${alias}.embedded_text_hash = md5(${alias}.chunk_text)
+ AND vector_dims(${alias}.${colId}) = $${dimsParam}::int, false)`;
}
export async function lockEmbeddingSources(tx: Pick<BrainEngine, 'executeRaw'>, sourceId?: string): Promise<string[]> {
@@ -166,13 +166,22 @@ export async function countRestampOnlyChunks(
engine: Pick<BrainEngine, 'executeRaw'>,
opts: { signature: string; sourceId?: string; includeNullSignature?: boolean },
): Promise<number> {
+ return (await measureRestampOnlyChunks(engine, opts)).chunks;
+}
+
+/** countRestampOnlyChunks plus their text size, so a paid estimate can leave them out. */
+export async function measureRestampOnlyChunks(
+ engine: Pick<BrainEngine, 'executeRaw'>,
+ opts: { signature: string; sourceId?: string; includeNullSignature?: boolean },
+): Promise<{ chunks: number; chars: number }> {
const colId = quoteIdentifier((await resolveActiveEmbeddingColumnFromEngine(engine, { fallbackToLegacy: true })).name);
const { model, dims } = splitEmbeddingSignature(opts.signature);
const sigClause = opts.includeNullSignature
? '(p.embedding_signature IS NULL OR p.embedding_signature <> $1)'
: 'p.embedding_signature IS NOT NULL AND p.embedding_signature <> $1';
- const rows = await engine.executeRaw<{ count: number | string }>(
- `SELECT count(*)::int AS count FROM content_chunks cc JOIN pages p ON p.id = cc.page_id
+ const rows = await engine.executeRaw<{ count: number | string; chars: number | string }>(
+ `SELECT count(*)::int AS count, COALESCE(sum(length(cc.chunk_text)), 0)::bigint AS chars
+ FROM content_chunks cc JOIN pages p ON p.id = cc.page_id
WHERE p.deleted_at IS NULL AND ${sigClause}
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
AND NOT ${pageBudgetLimitedFilter('p')}
@@ -180,7 +189,7 @@ export async function countRestampOnlyChunks(
AND ${currentSpaceChunkPredicate(colId, 2, 3)}`,
[opts.signature, model, dims, opts.sourceId ?? null],
);
- return Number(rows[0]?.count ?? 0);
+ return { chunks: Number(rows[0]?.count ?? 0), chars: Number(rows[0]?.chars ?? 0) };
}
export async function invalidateStaleSignatureEmbeddingsGuarded(
diff --git a/src/core/embedding-migration-worst-case.ts b/src/core/embedding-migration-worst-case.ts
index cdcbf6cf8c..f22d2433ae 100644
--- a/src/core/embedding-migration-worst-case.ts
+++ b/src/core/embedding-migration-worst-case.ts
@@ -24,7 +24,7 @@ import { embedRequestCeilings, rerankRequestMaxInputTokens } from './ai/embed-ba
import { wrapChunkTextsForStoredMode } from './embedding-context.ts';
import type { ChunkInput, CRMode } from './types.ts';
import { readContentChunksEmbeddingDim } from './embedding-dim-check.ts';
-import { falseStampPageWhere } from './embedding-invalidation.ts';
+import { currentSpaceChunkPredicate, falseStampPageWhere } from './embedding-invalidation.ts';
import { resolveActiveEmbeddingColumnFromEngine, quoteIdentifier } from './search/embedding-column.ts';
import { eligibleFactEmbedding, staleFactEmbedding } from './facts/embedding-identity.ts';
import { AUDIT_ROW_SOURCES } from './facts/audit-sources.ts';
@@ -94,9 +94,11 @@ async function eachStalePage(engine: BrainEngine, plan: EmbeddingMigrationPlan,
const column = (await readContentChunksEmbeddingDim(engine)).exists
? quoteIdentifier((await resolveActiveEmbeddingColumnFromEngine(engine, { fallbackToLegacy: true })).name)
: null;
- const staleChunk = (c: string) => column === null ? 'true' : `(${c}.${column} IS NULL OR p.embedding_signature IS NULL OR p.embedding_signature <> $1
+ // #5289: without a column rebuild, invalidation keeps a vector already in the target space and the drain never sends it.
+ const kept = (c: string) => plan.dim_change ? 'false' : currentSpaceChunkPredicate(column!, 2, 5, c);
+ const staleChunk = (c: string) => column === null ? 'true' : `((${c}.${column} IS NULL OR p.embedding_signature IS NULL OR p.embedding_signature <> $1
OR (${c}.embedded_text_hash IS NOT NULL AND ${c}.embedded_text_hash <> md5(${c}.chunk_text))
- OR (${c}.${column} IS NOT NULL AND ${falseStampPageWhere(column, 1, 2)}))`;
+ OR (${c}.${column} IS NOT NULL AND ${falseStampPageWhere(column, 1, 2)})) AND NOT ${kept(c)})`;
const livePage = column === null ? 'true' : `p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter,'{}'::jsonb) ? 'embed_skip')`;
let page: ChunkRow[] = [];
const flush = () => {
@@ -114,7 +116,7 @@ async function eachStalePage(engine: BrainEngine, plan: EmbeddingMigrationPlan,
AND EXISTS (SELECT 1 FROM content_chunks cs WHERE cs.page_id=p.id AND ${staleChunk('cs')})
AND (cc.page_id > $3 OR (cc.page_id = $3 AND cc.chunk_index > $4))
ORDER BY cc.page_id, cc.chunk_index LIMIT ${SCAN_PAGE}`,
- [`${plan.to_model}:${plan.to_dims}`, plan.to_model, after.page, after.chunk]);
+ [`${plan.to_model}:${plan.to_dims}`, plan.to_model, after.page, after.chunk, ...(column === null || plan.dim_change ? [] : [plan.to_dims])]);
for (const row of rows) {
if (page.length && page[0].page_id !== row.page_id) flush();
page.push(row);
diff --git a/src/core/embedding-migration.ts b/src/core/embedding-migration.ts
index e05ead737b..0d164c37c8 100644
--- a/src/core/embedding-migration.ts
+++ b/src/core/embedding-migration.ts
@@ -11,7 +11,7 @@ import {
lockEmbeddingSources,
splitEmbeddingSignature,
currentSpaceChunkPredicate,
- countRestampOnlyChunks,
+ measureRestampOnlyChunks,
} from './embedding-invalidation.ts';
import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';
import { readPrimaryEmbeddingStores, readStoredEmbeddingIdentity } from './stored-embedding-identity.ts';
@@ -631,7 +631,9 @@ export async function planEmbeddingMigration(
// counts what the stamp hides. No overlap — the stale predicates skip
// exactly the target-stamped pages' EMBEDDED chunks counted here.
falseStamped = await countFalseStampedChunks(engine, toModel, toDims);
- if (!schemaRebuildNeeded(col.dims, toDims)) restamp = await countRestampOnlyChunks(engine, { signature: sig, includeNullSignature: true });
+ const kept = schemaRebuildNeeded(col.dims, toDims) ? { chunks: 0, chars: 0 } : await measureRestampOnlyChunks(engine, { signature: sig, includeNullSignature: true });
+ restamp = kept.chunks;
+ totalChars = Math.max(0, totalChars - kept.chars);
} else {
// Column ABSENT: the stale predicates reference cc.embedding and would
// throw. Every chunk needs embedding once the column is (re)built.
diff --git a/test/e2e/migration-restamp-estimate-postgres.test.ts b/test/e2e/migration-restamp-estimate-postgres.test.ts
new file mode 100644
index 0000000000..012c69e894
--- /dev/null
+++ b/test/e2e/migration-restamp-estimate-postgres.test.ts
@@ -0,0 +1,59 @@
+/**
+ * PR #6959 on real Postgres + pgvector: a migration's paid estimate and its
+ * worst-case authorization leave out chunks whose vectors are already in the
+ * target space (same model, text hash and width), because invalidation keeps
+ * those vectors and the drain only restamps their page. The PGLite arm is
+ * test/migrate-embeddings-dry-run-split-5226.serial.test.ts.
+ *
+ * Run: DATABASE_URL=postgres://...gbrain_test bun test test/e2e/migration-restamp-estimate-postgres.test.ts
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { installFixtureChunks } from '../helpers/page-projection.ts';
+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';
+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';
+import { planEmbeddingMigration } from '../../src/core/embedding-migration.ts';
+import { planMigrationWorstCase } from '../../src/core/embedding-migration-worst-case.ts';
+import { readContentChunksEmbeddingDim } from '../../src/core/embedding-dim-check.ts';
+
+const RUN = hasDatabase();
+const d = RUN ? describe : describe.skip;
+const MODEL = 'openai:text-embedding-3-large';
+let engine: PostgresEngine;
+let dims: number;
+
+async function seed(slug: string, chunks: number, vectors: boolean): Promise<void> {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `# ${slug}` });
+ await installFixtureChunks(engine, slug, Array.from({ length: chunks }, (_, i) => ({
+ chunk_index: i, chunk_text: `${slug} body ${i}`, chunk_source: 'compiled_truth' as const, token_count: 4,
+ ...(vectors ? { embedding: new Float32Array(dims).fill(0.002), model: MODEL } : {}),
+ })));
+}
+
+d('migration estimate excludes restamp-only chunks (Postgres)', () => {
+ beforeAll(async () => {
+ engine = await setupDB();
+ dims = (await readContentChunksEmbeddingDim(engine)).dims!;
+ configureGateway({ embedding_model: MODEL, embedding_dimensions: dims, env: { OPENAI_API_KEY: 'sk-test-fake' } });
+ }, 60_000);
+
+ afterAll(async () => {
+ resetGateway();
+ await teardownDB();
+ });
+
+ test('plan chars, cost and worst case match the paid-only brain', async () => {
+ const target = { to: MODEL, dim: dims, fromModel: 'legacy:model', fromDims: dims };
+ await seed('no-vectors', 1, false);
+ const paidOnly = await planEmbeddingMigration(engine, target);
+ const paidWorst = await planMigrationWorstCase(engine, paidOnly);
+ await seed('current-vectors', 2, true);
+ const mixed = await planEmbeddingMigration(engine, target);
+ expect(mixed.dim_change).toBe(false);
+ expect(mixed.chunks_to_restamp).toBe(2);
+ expect(paidOnly.total_chars).toBe('no-vectors body 0'.length);
+ expect(mixed.total_chars).toBe(paidOnly.total_chars);
+ expect(mixed.est_cost_usd).toBe(paidOnly.est_cost_usd);
+ expect(await planMigrationWorstCase(engine, mixed)).toEqual(paidWorst);
+ });
+});
diff --git a/test/migrate-embeddings-dry-run-split-5226.serial.test.ts b/test/migrate-embeddings-dry-run-split-5226.serial.test.ts
index ae05c111ed..53c5e5875b 100644
--- a/test/migrate-embeddings-dry-run-split-5226.serial.test.ts
+++ b/test/migrate-embeddings-dry-run-split-5226.serial.test.ts
@@ -18,6 +18,7 @@ import { join } from 'node:path';
import { runEmbedCore } from '../src/commands/embed.ts';
import { runMigrateEmbeddings } from '../src/commands/migrate-embeddings.ts';
import { planEmbeddingMigration } from '../src/core/embedding-migration.ts';
+import { planMigrationWorstCase } from '../src/core/embedding-migration-worst-case.ts';
import { __setEmbedTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
import { EMBED_PROBE_TEXT } from '../src/core/embed-stale.ts';
import type { BrainEngine } from '../src/core/engine.ts';
@@ -87,6 +88,31 @@ describe('#5226 migrate embeddings dry run', () => {
expect(plan.chunks_to_embed).toBe(3);
});
+ test('PR #6959: restamp-only chunks are left out of the paid estimate and the worst-case authorization', async () => {
+ await seed(engine, 'no-vectors', 1, null);
+ const paidOnly = await planEmbeddingMigration(engine, { to: MODEL, dim: DIMS, fromModel: 'legacy:model', fromDims: DIMS });
+ const paidWorst = await planMigrationWorstCase(engine, paidOnly);
+ await seed(engine, 'current-vectors', 2, { model: MODEL });
+ const mixed = await planEmbeddingMigration(engine, { to: MODEL, dim: DIMS, fromModel: 'legacy:model', fromDims: DIMS });
+ expect(mixed.chunks_to_restamp).toBe(2);
+ expect(mixed.chunks_to_embed).toBe(1);
+ expect(paidOnly.total_chars).toBe('no-vectors body 0'.length);
+ expect(mixed.total_chars).toBe(paidOnly.total_chars);
+ expect(mixed.est_cost_usd).toBe(paidOnly.est_cost_usd);
+ const mixedWorst = await planMigrationWorstCase(engine, mixed);
+ expect(mixedWorst).toEqual(paidWorst);
+ });
+
+ test('PR #6959: a width change still prices current vectors (the column is rebuilt)', async () => {
+ await seed(engine, 'no-vectors', 1, null);
+ const target = { to: 'openai:text-embedding-3-small', dim: 1024, fromModel: MODEL, fromDims: DIMS };
+ const before = await planMigrationWorstCase(engine, await planEmbeddingMigration(engine, target));
+ await seed(engine, 'current-vectors', 2, { model: MODEL });
+ const plan = await planEmbeddingMigration(engine, target);
+ expect(plan.total_chars).toBe(['no-vectors body 0', 'current-vectors body 0', 'current-vectors body 1'].join('').length);
+ expect((await planMigrationWorstCase(engine, plan)).input_tokens).toBeGreaterThan(before.input_tokens);
+ });
+
test('the printed plan names both figures', async () => {
await seed(engine, 'current-vectors', 2, { model: MODEL });
await seed(engine, 'no-vectors', 1, null);