Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(embed): window the stale-signature invalidation and replace the drift pre-counts with one EXISTS (#7148)

garrytan6519f2fc6d86
diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.md
index aec9a3f82e..670c7a89de 100644
--- a/docs/architecture/key-files/providers.md
+++ b/docs/architecture/key-files/providers.md
@@ -40,7 +40,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/embedding-input-limit.ts` — per-model embedding INPUT token caps. Some hosted encoders reject any single input over a hard per-input limit far below their batch budget (a 512-token model would otherwise leave ~35% of a typical vault's chunks permanently unembeddable, re-failing every sweep). `resolveMaxChunkTokens(env?)` resolves the effective chunk-token cap for the ACTIVE embedding model so the chunkers SPLIT (never truncate) at a size the model accepts: `GBRAIN_MAX_CHUNK_TOKENS` env (escape hatch for models not in a recipe; warn-once per distinct invalid value) → recipe per-model `max_input_tokens` × `EMBED_INPUT_SAFETY` (0.6 — covers the cl100k-based `estimateEmbedTokens` overestimate vs BERT-wordpiece tokenizer mismatch) → `DEFAULT_MAX_CHUNK_TOKENS` (2000 for every other provider). `MIN_CHUNK_TOKENS` floor of 64 so a tiny declared limit can't produce confetti chunks; fail-open on any resolver error (a resolver bug must never change chunking for unaffected installs). `maxInputTokensForModel(recipe, modelId)` mirrors `model_dims`' case-fold lookup rule (exact match first, then case-insensitive scan). Consumed at `import-file.ts`'s chunk step. Pinned by `test/embedding-input-limit.test.ts`. Declared limits ([R13] audit, PR #5922): NVIDIA `nvidia/nv-embedqa-e5-v5` 512; DashScope `text-embedding-v1`/`v2` 2048, `v3` 8192; Google `gemini-embedding-001` 2048 (the endpoint truncates silently past it); Zhipu `embedding-2` 512, `embedding-3` 3072; OpenAI `text-embedding-3-*` 8191 and Mistral `mistral-embed` 8192 (above the default, so no chunking change). Pinned by `test/embedding-input-limit-hosted-caps.test.ts`. **Learned caps** (`learnChunkCap` / `learnedChunkCap` / `_resetLearnedChunkCapsForTest`): a process-lifetime per-`provider:model` chunk cap that `src/core/embed-overlength-heal.ts` derives from a provider's single-input over-length rejection when the model declares nothing; `resolveMaxChunkTokens` applies it after the env override and the recipe declaration (both win over it), clamped to the same floor/ceiling.
-- `src/core/embedding-invalidation.ts` — signature-truth guards shared by migration and embed paths, using identical SQL on both engines. `invalidateStaleSignatureEmbeddingsGuarded(engine, {signature, sourceId?, includeNullSignature?})` adds the stale selectors' embed-skip and projection-seal fences to raw engine invalidation. Current model/hash/width chunks survive interrupted batches; fully current active pages can be restamped without another embedding call. Source `FOR SHARE` locks precede mutation in short transactions, serializing both signature writes, raw engine signature/content-drift invalidation, false-stamp clearing and final reconciliation against archive. Archived vectors and page signatures are never mutated. The shared `falseStampPageWhere` and `countFalseStampedChunks` remain archive-visible for retention, plan and completion diagnostics; only the clearing write is fenced. Bare provider-less model aliases retain their existing exemption. Provider dispatch and completion smoke run outside source locks and revalidate live, safe snapshots before sending text. Pinned by `test/embedding-migration.test.ts` and the shared `test/embedding-recovery.serial.test.ts` suite: PGLite runs in the serial lane, while `test/e2e/embedding-recovery-parity.test.ts` selects PostgreSQL.
+- `src/core/embedding-invalidation.ts` — signature-truth guards shared by migration and embed paths, using identical SQL on both engines. `invalidateStaleSignatureEmbeddingsGuarded(engine, {signature, sourceId?, includeNullSignature?})` adds the stale selectors' embed-skip and projection-seal fences to raw engine invalidation. It runs as one statement pair per window of `SIGNATURE_INVALIDATION_PAGE_BATCH` (1000) page ids inside one transaction, so a full-corpus model swap on a large brain stays inside the statement timeout (#7148; Postgres proof in `test/e2e/stale-signature-invalidation-postgres.test.ts`). `hasSignatureDrift` is the embed paths' page-first pre-check: one EXISTS instead of two corpus-wide counts, so a healthy brain never reads `content_chunks` for it and a drifted brain is never counted before the probe. Current model/hash/width chunks survive interrupted batches; fully current active pages can be restamped without another embedding call. Source `FOR SHARE` locks precede mutation in short transactions, serializing both signature writes, raw engine signature/content-drift invalidation, false-stamp clearing and final reconciliation against archive. Archived vectors and page signatures are never mutated. The shared `falseStampPageWhere` and `countFalseStampedChunks` remain archive-visible for retention, plan and completion diagnostics; only the clearing write is fenced. Bare provider-less model aliases retain their existing exemption. Provider dispatch and completion smoke run outside source locks and revalidate live, safe snapshots before sending text. Pinned by `test/embedding-migration.test.ts` and the shared `test/embedding-recovery.serial.test.ts` suite: PGLite runs in the serial lane, while `test/e2e/embedding-recovery-parity.test.ts` selects PostgreSQL.
- `src/core/embedding-pricing.ts` — `EMBEDDING_PRICING` map keyed `provider:model` for the post-upgrade reindex cost estimate. Sibling to `anthropic-pricing.ts`; EMBEDDINGS only — chat/completion pricing lives in `model-pricing.ts` (different unit) and is never mixed in. Every entry carries its official source URL + the date it was last read. Entries: OpenAI text-embedding-3-large ($0.13/1M), 3-small ($0.02/1M), ada-002 ($0.10/1M); Voyage 4-large ($0.12/1M), 4 ($0.06/1M), 4-lite ($0.02/1M), legacy 3-large ($0.18/1M), 3 ($0.06/1M); Mistral mistral-embed ($0.10/1M); Perplexity pplx-embed-v1-4b ($0.03/1M), 0.6b ($0.004/1M). `voyage-4-nano` is deliberately unpriced (open-weight variant, no published hosted rate) so it degrades to "estimate unavailable" rather than a fabricated 0. `lookupEmbeddingPrice(modelString)` returns a tagged union (`known` with price + `unknown` with provider name); `estimateCostFromChars(charCount, pricePerMTok)` uses 3.5 chars/token. Unknown providers degrade to "estimate unavailable" instead of fabricating numbers.
diff --git a/src/commands/embed.ts b/src/commands/embed.ts
index a43225408b..7ce2a5b1d0 100644
--- a/src/commands/embed.ts
+++ b/src/commands/embed.ts
@@ -27,7 +27,7 @@ import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts'
import { StaleChunkProgress } from '../core/embed-stale-progress.ts';
import { assertEmbeddingEnabled } from '../core/embedding-dim-check.ts';
import { writeCliError } from '../cli/cli-error.ts';
-import { countRestampOnlyChunks, invalidateStaleSignatureEmbeddingsGuarded } from '../core/embedding-invalidation.ts';
+import { countRestampOnlyChunks, hasSignatureDrift, invalidateStaleSignatureEmbeddingsGuarded } from '../core/embedding-invalidation.ts';
import { contentDriftSweepLine, runContentDriftSweep, type ContentDriftSweepStatus } from '../core/content-drift-sweep.ts';
import { loadConfig, type GBrainConfig } from '../core/config.ts';
import { slog, serr } from '../core/console-prefix.ts';
@@ -1765,26 +1765,24 @@ async function embedAllStale(
// stale selector excludes them, so NULLing them here (the migrate
// embeddings drain path included) would be permanent loss.
//
- // #4283: NULLing is conditional on a WORKING embedder. The drift pre-count
+ // #4283: NULLing is conditional on a WORKING embedder. The drift pre-check
// keeps the probe's one embed call off the no-drift common path; a failed
// probe (bad key, unreachable provider, wrong-dims model) skips the
// invalidation so a misresolved config can't strip vectors it can never
// replace. validateEmbeddingCreds at runEmbedCore entry is a static env
// check only — the probe is the live proof.
if (!dryRun && signature) {
- let signatureDrift = 0;
+ let drifted = false;
try {
- const sources = await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE NOT archived AND ($1::text IS NULL OR id=$1) ORDER BY id', [sourceId ?? null]);
- for (const source of sources) {
- const wide = await engine.countStaleChunks({ sourceId: source.id, signature, ...(includeNullSig && { includeNullSignature: true }) });
- const nullOnly = await engine.countStaleChunks({ sourceId: source.id });
- signatureDrift += wide - nullOnly;
- }
+ // One page-first EXISTS: a healthy brain answers it without reading content_chunks, and a
+ // drifted one is not counted before the probe, so a count over a large corpus can no longer
+ // time out into a silent "no drift" (#7117 follow-up).
+ drifted = await hasSignatureDrift(engine, { signature, ...(sourceId && { sourceId }), ...(includeNullSig && { includeNullSignature: true }) });
} catch {
- // Pre-count is best-effort; fall through as "no drift" (no NULLing).
+ // Pre-check is best-effort; fall through as "no drift" (no NULLing).
}
let invalidated = 0;
- if (signatureDrift > 0) {
+ if (drifted) {
const probeOk = await probeEmbedder(
(texts, fnOpts) => embedBatchWithBackoff(texts, { abortSignal: fnOpts.abortSignal }),
signature,
@@ -1801,7 +1799,7 @@ async function embedAllStale(
});
} else {
serr(
- ` [embed] WARNING: ${signatureDrift} chunk(s) drifted from signature ${signature} but the ` +
+ ` [embed] WARNING: embedded chunk(s) drifted from signature ${signature} but the ` +
`embedder probe failed — SKIPPING invalidation (existing vectors preserved). ` +
`Check embedding provider config/credentials.`,
);
@@ -1822,20 +1820,23 @@ async function embedAllStale(
// brain, so an unaffected run stays quiet.
if (!includeNullSig) {
try {
- const wide = await engine.countStaleChunks({ ...sourceOpt, signature, includeNullSignature: true });
- const narrow = await engine.countStaleChunks({ ...sourceOpt, signature });
- // #5527: a NULL-signature page whose vectors already match the current
- // model, width and text is only missing its stamp, not in another space.
- const currentSpace = await countRestampOnlyChunks(engine, { signature, sourceId, includeNullSignature: true })
- - await countRestampOnlyChunks(engine, { signature, sourceId });
- const leftBehind = wide - narrow - currentSpace;
- if (leftBehind > 0) {
- serr(
- ` [embed] WARNING: ${leftBehind} embedded chunk(s) sit on pages with no recorded ` +
- `embedding signature and were NOT invalidated — they remain in the previous model's ` +
- `embedding space. Re-run with --include-null-signature (or use ` +
- `\`gbrain migrate embeddings\`) to re-embed them.`,
- );
+ // Only a page with no recorded signature and an embedded chunk can be left behind; without one, skip the counts and the restamp-only md5 scan.
+ if (await hasSignatureDrift(engine, { signature, ...(sourceId && { sourceId }), nullSignatureOnly: true })) {
+ const wide = await engine.countStaleChunks({ ...sourceOpt, signature, includeNullSignature: true });
+ const narrow = await engine.countStaleChunks({ ...sourceOpt, signature });
+ // #5527: a NULL-signature page whose vectors already match the current
+ // model, width and text is only missing its stamp, not in another space.
+ const currentSpace = await countRestampOnlyChunks(engine, { signature, sourceId, includeNullSignature: true })
+ - await countRestampOnlyChunks(engine, { signature, sourceId });
+ const leftBehind = wide - narrow - currentSpace;
+ if (leftBehind > 0) {
+ serr(
+ ` [embed] WARNING: ${leftBehind} embedded chunk(s) sit on pages with no recorded ` +
+ `embedding signature and were NOT invalidated — they remain in the previous model's ` +
+ `embedding space. Re-run with --include-null-signature (or use ` +
+ `\`gbrain migrate embeddings\`) to re-embed them.`,
+ );
+ }
}
} catch {
// The warning probe is best-effort; never break the embed run.
diff --git a/src/core/embed-stale.ts b/src/core/embed-stale.ts
index 57ba9947b3..ba41960d96 100644
--- a/src/core/embed-stale.ts
+++ b/src/core/embed-stale.ts
@@ -26,7 +26,7 @@ import { embedBatchWithBackoff, restampIfDemotedToTitleTier } from './embed-retr
import { wrapChunkTextsForStoredMode } from './embedding-context.ts';
import { healOversizedPageChunks, healedChunksToStaleRows } from './embed-oversize-heal.ts';
import { healAndReportOverLength } from './embed-overlength-heal.ts';
-import { invalidateStaleSignatureEmbeddingsGuarded, splitEmbeddingSignature, currentSpaceChunkPredicate } from './embedding-invalidation.ts';
+import { hasSignatureDrift, invalidateStaleSignatureEmbeddingsGuarded, splitEmbeddingSignature, currentSpaceChunkPredicate } from './embedding-invalidation.ts';
import {
resolveActiveEmbeddingColumnFromEngine,
quoteIdentifier,
@@ -442,16 +442,15 @@ export async function embedStaleForSource(
// the NULL cursor below re-embeds them. GRANDFATHER: NULL signature
// untouched. Best-effort — a failure here must not abort the backfill.
//
- // #4283: NULLing is conditional on a WORKING embedder. The drift pre-count
- // (two cheap COUNTs; probe only fires when drift exists) keeps the probe's
+ // #4283: NULLing is conditional on a WORKING embedder. The drift pre-check
+ // (one page-first EXISTS; probe only fires when drift exists) keeps the probe's
// one embed call off the no-drift common path; a failed probe skips the
// invalidation entirely so a misresolved worker can't strip a corpus it
// can never re-embed.
if (signature) {
try {
- const wide = await engine.countStaleChunks({ sourceId, signature });
- const nullOnly = await engine.countStaleChunks({ sourceId });
- if (wide - nullOnly > 0) {
+ // One page-first EXISTS: no chunk count before the probe, so a large drifted corpus cannot time the pre-check out (#7117 follow-up).
+ if (await hasSignatureDrift(engine, { signature, sourceId })) {
await opts.assertOwned?.();
if (stopped()) return { ...result, aborted: true };
const probeOk = await probeEmbedder(embedFn, signature, signal);
@@ -471,7 +470,7 @@ export async function embedStaleForSource(
} else {
result.invalidationSkipped = 'embedder_probe_failed';
process.stderr.write(
- `\n [embed-stale] ${wide - nullOnly} chunk(s) drifted from signature ${signature} but the embedder probe failed — ` +
+ `\n [embed-stale] embedded chunk(s) drifted from signature ${signature} but the embedder probe failed — ` +
`SKIPPING invalidation (existing vectors preserved). Check embedding provider config/credentials.\n`,
);
}
diff --git a/src/core/embedding-invalidation.ts b/src/core/embedding-invalidation.ts
index 721244289e..c174ef5d38 100644
--- a/src/core/embedding-invalidation.ts
+++ b/src/core/embedding-invalidation.ts
@@ -32,6 +32,7 @@ import {
quoteIdentifier,
} from './search/embedding-column.ts';
import { pageBudgetLimitedFilter } from './page-size-policy.ts';
+import { chunkGenerationFilter } from './search/safe-chunks.ts';
export function splitEmbeddingSignature(signature: string): { model: string; dims: number | null } {
const separator = signature.lastIndexOf(':');
@@ -192,10 +193,24 @@ export async function measureRestampOnlyChunks(
return { chunks: Number(rows[0]?.count ?? 0), chars: Number(rows[0]?.chars ?? 0) };
}
+/** Pages per stale-signature invalidation statement (#7117 follow-up); every statement is bounded by a page-id window. */
+export const SIGNATURE_INVALIDATION_PAGE_BATCH = 1000;
+
+/**
+ * NULL the vectors of chunks outside the target space on pages whose
+ * signature drifted, and restamp pages whose chunks are all current. Runs in
+ * one transaction (the caller's when it passes one, so the migration's census
+ * and lease checks stay in it), as one pair of statements per window of
+ * `pageBatch` page ids: no statement visits more than one window, so a large
+ * brain no longer runs one UPDATE over every chunk into the statement timeout.
+ * A page's chunk invalidation and its restamp run in the same window.
+ */
export async function invalidateStaleSignatureEmbeddingsGuarded(
engine: BrainEngine,
- opts: { signature: string; sourceId?: string; includeNullSignature?: boolean },
+ opts: { signature: string; sourceId?: string; includeNullSignature?: boolean; pageBatch?: number },
): Promise<number> {
+ const pageBatch = Math.trunc(opts.pageBatch ?? SIGNATURE_INVALIDATION_PAGE_BATCH);
+ if (!Number.isFinite(pageBatch) || pageBatch < 1) throw new Error(`invalid signature invalidation page batch: ${opts.pageBatch}`);
return engine.transaction(async tx => {
const sources = await lockEmbeddingSources(tx, opts.sourceId);
const colId = await activeColId(tx);
@@ -209,37 +224,79 @@ export async function invalidateStaleSignatureEmbeddingsGuarded(
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 tx.executeRaw<{ page_id: number }>(
- `UPDATE content_chunks cc
- SET ${colId} = NULL, embedded_at = NULL, embedding_pending_since = now()
- FROM pages p
- WHERE cc.page_id = p.id
- AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived)
- AND cc.${colId} IS NOT NULL
- AND NOT ${currentChunk}
- AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
- AND NOT ${pageBudgetLimitedFilter('p')}
- AND p.deleted_at IS NULL
- AND p.text_projection_revision = p.knowledge_revision
- AND ${sigClause}${srcClause}
- RETURNING cc.page_id`,
- params,
- );
- await tx.executeRaw(
- `UPDATE pages p SET embedding_signature = $1
- WHERE ${sigClause}${srcClause}
- AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived)
+ let after = 0;
+ let invalidated = 0;
+ for (;;) {
+ const [window] = await tx.executeRaw<{ last_id: number | string | null }>(
+ `SELECT max(id) AS last_id FROM (SELECT id FROM pages WHERE id > ${after} ORDER BY id LIMIT ${pageBatch}) b`);
+ if (window?.last_id == null) return invalidated;
+ const last = Number(window.last_id);
+ const pageWindow = ` AND p.id > ${after} AND p.id <= ${last}`;
+ const rows = await tx.executeRaw<{ page_id: number }>(
+ `UPDATE content_chunks cc
+ SET ${colId} = NULL, embedded_at = NULL, embedding_pending_since = now()
+ FROM pages p
+ WHERE cc.page_id = p.id${pageWindow}
+ AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived)
+ AND cc.${colId} IS NOT NULL
+ AND NOT ${currentChunk}
+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
+ AND NOT ${pageBudgetLimitedFilter('p')}
+ AND p.deleted_at IS NULL
+ AND p.text_projection_revision = p.knowledge_revision
+ AND ${sigClause}${srcClause}
+ RETURNING cc.page_id`,
+ params,
+ );
+ await tx.executeRaw(
+ `UPDATE pages p SET embedding_signature = $1
+ WHERE ${sigClause}${srcClause}${pageWindow}
+ AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived)
+ AND p.deleted_at IS NULL
+ AND p.text_projection_revision = p.knowledge_revision
+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
+ AND NOT ${pageBudgetLimitedFilter('p')}
+ AND EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id)
+ AND NOT EXISTS (
+ SELECT 1 FROM content_chunks cc
+ WHERE cc.page_id = p.id AND NOT ${currentChunk}
+ )`,
+ params,
+ );
+ invalidated += (rows as unknown[]).length;
+ after = last;
+ }
+ });
+}
+
+/**
+ * Whether any embedded chunk sits on a page whose signature drifted from
+ * `signature` (NULL-signature pages too with `includeNullSignature`), under
+ * the stale selectors' page rules: the question the embed paths' two-count
+ * pre-check (wide minus NULL-only countStaleChunks) answers, as one EXISTS
+ * that reads pages first and touches chunks only of a drifted page. A healthy
+ * brain answers it without reading content_chunks at all.
+ */
+export async function hasSignatureDrift(
+ engine: Pick<BrainEngine, 'executeRaw'>,
+ opts: { signature: string; sourceId?: string; includeNullSignature?: boolean; nullSignatureOnly?: boolean },
+): Promise<boolean> {
+ const colId = await activeColId(engine);
+ const sigClause = opts.nullSignatureOnly ? 'p.embedding_signature IS NULL'
+ : opts.includeNullSignature ? '(p.embedding_signature IS NULL OR p.embedding_signature <> $2)'
+ : 'p.embedding_signature IS NOT NULL AND p.embedding_signature <> $2';
+ const [row] = await engine.executeRaw<{ drift: boolean }>(
+ `SELECT EXISTS (
+ SELECT 1 FROM pages p
+ WHERE ${sigClause}
AND p.deleted_at IS NULL
- AND p.text_projection_revision = p.knowledge_revision
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
- AND NOT ${pageBudgetLimitedFilter('p')}
- AND EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id)
- AND NOT EXISTS (
- SELECT 1 FROM content_chunks cc
- WHERE cc.page_id = p.id AND NOT ${currentChunk}
- )`,
- params,
- );
- return (rows as unknown[]).length;
- });
+ AND NOT ${pageBudgetLimitedFilter('p')}
+ AND ($1::text IS NULL OR p.source_id = $1)
+ AND EXISTS (SELECT 1 FROM sources s WHERE s.id = p.source_id AND NOT s.archived)
+ AND EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id AND cc.${colId} IS NOT NULL AND ${chunkGenerationFilter('p', 'cc')})
+ ) AS drift`,
+ opts.nullSignatureOnly ? [opts.sourceId ?? null] : [opts.sourceId ?? null, opts.signature],
+ );
+ return row?.drift === true;
}
diff --git a/test/e2e/stale-signature-invalidation-postgres.test.ts b/test/e2e/stale-signature-invalidation-postgres.test.ts
new file mode 100644
index 0000000000..7797c957b3
--- /dev/null
+++ b/test/e2e/stale-signature-invalidation-postgres.test.ts
@@ -0,0 +1,91 @@
+/**
+ * #7148: the stale-signature invalidation under a statement_timeout, on real Postgres.
+ *
+ * Protects: after a model or width swap nearly every chunk is out of the
+ * target space, and the invalidation still finishes on a brain where one
+ * statement over every chunk would outrun statement_timeout: each statement
+ * covers one window of page ids, so its cost is bounded by the window and
+ * not by the corpus. All windows commit together (one transaction), and the
+ * result matches what the one-statement version would have written.
+ * Regression it catches: one UPDATE over all of content_chunks; on a large
+ * brain it was cancelled and rolled back, so nothing was ever invalidated and
+ * every later run repeated the same doomed statement.
+ * Seam: a test-only BEFORE UPDATE trigger costs every chunk row 1 ms, so the
+ * whole 3000-chunk corpus costs one statement 3 s against a 1.5 s
+ * statement_timeout, as row volume does on a large brain, while a window of
+ * five pages costs 0.5 s.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
+import { invalidateStaleSignatureEmbeddingsGuarded, hasSignatureDrift } from '../../src/core/embedding-invalidation.ts';
+
+const d = hasDatabase() ? describe : describe.skip;
+const url = process.env.DATABASE_URL;
+const previousTimeout = process.env.GBRAIN_STATEMENT_TIMEOUT;
+const PAGES = 30;
+const CHUNKS_PER_PAGE = 100;
+
+let engine: PostgresEngine;
+let slow: PostgresEngine;
+
+async function counts(): Promise<{ embedded: number; total: number; restamped: number }> {
+ const [row] = await engine.executeRaw<{ embedded: number; total: number; restamped: number }>(
+ "SELECT count(*) FILTER (WHERE embedding IS NOT NULL)::int AS embedded, count(*)::int AS total, (SELECT count(*)::int FROM pages WHERE embedding_signature = 'target:model:1') AS restamped FROM content_chunks");
+ return row!;
+}
+
+async function seed(): Promise<void> {
+ for (let i = 0; i < PAGES; i++) await engine.putPage('corpus-' + i, { type: 'note', title: 'corpus ' + i, compiled_truth: 'corpus' });
+ 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(
+ "INSERT INTO content_chunks (page_id, chunk_index, chunk_text, token_count, embedding, embedded_at, model, embedded_text_hash) " +
+ "SELECT p.id, g, 'corpus chunk ' || p.slug || ' ' || g, 3, ('[' || array_to_string(array_fill(0.1::real, ARRAY[$1::int]), ',') || ']')::vector, now(), 'old:model', md5('corpus chunk ' || p.slug || ' ' || g) " +
+ "FROM pages p, generate_series(0, $2::int - 1) g WHERE p.slug LIKE 'corpus-%' ORDER BY p.id, g", [dim, CHUNKS_PER_PAGE]);
+ await engine.executeRaw("UPDATE pages SET embedding_signature = 'old:model:" + "' || $1::text, text_projection_revision = knowledge_revision WHERE slug LIKE 'corpus-%'", [String(dim)]);
+}
+
+d('#7148 stale-signature invalidation under statement_timeout (Postgres)', () => {
+ beforeAll(async () => {
+ assertSafeE2eDatabaseUrl(url!);
+ engine = await setupDB();
+ await engine.executeRaw("CREATE OR REPLACE FUNCTION gbrain_test_row_cost() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN PERFORM pg_sleep(0.001); RETURN NEW; END $$");
+ process.env.GBRAIN_STATEMENT_TIMEOUT = '1500ms';
+ slow = new PostgresEngine();
+ await slow.connect({ engine: 'postgres', database_url: url!, poolSize: 2 });
+ }, 60_000);
+
+ afterAll(async () => {
+ if (previousTimeout === undefined) delete process.env.GBRAIN_STATEMENT_TIMEOUT; else process.env.GBRAIN_STATEMENT_TIMEOUT = previousTimeout;
+ await engine?.executeRaw('DROP TRIGGER IF EXISTS gbrain_test_row_cost ON content_chunks');
+ await engine?.executeRaw('DROP FUNCTION IF EXISTS gbrain_test_row_cost()');
+ await slow?.disconnect();
+ await teardownDB();
+ });
+
+ beforeEach(async () => {
+ await engine.executeRaw('DROP TRIGGER IF EXISTS gbrain_test_row_cost ON content_chunks');
+ await engine.executeRaw('TRUNCATE pages CASCADE');
+ });
+
+ test('a full-corpus model swap is invalidated window by window inside the timeout', async () => {
+ await seed();
+ expect(await counts()).toMatchObject({ embedded: PAGES * CHUNKS_PER_PAGE, total: PAGES * CHUNKS_PER_PAGE });
+ expect(await hasSignatureDrift(slow, { signature: 'target:model:1' })).toBe(true);
+ await engine.executeRaw('CREATE TRIGGER gbrain_test_row_cost BEFORE UPDATE ON content_chunks FOR EACH ROW EXECUTE FUNCTION gbrain_test_row_cost()');
+ const invalidated = await invalidateStaleSignatureEmbeddingsGuarded(slow, { signature: 'target:model:1', pageBatch: 5 });
+ expect(invalidated).toBe(PAGES * CHUNKS_PER_PAGE);
+ expect(await counts()).toMatchObject({ embedded: 0, restamped: 0 });
+ expect(await hasSignatureDrift(slow, { signature: 'target:model:1' })).toBe(false);
+ }, 60_000);
+
+ test('a window that still outruns the timeout rolls every window back', async () => {
+ await seed();
+ await engine.executeRaw('CREATE TRIGGER gbrain_test_row_cost BEFORE UPDATE ON content_chunks FOR EACH ROW EXECUTE FUNCTION gbrain_test_row_cost()');
+ const error = await invalidateStaleSignatureEmbeddingsGuarded(slow, { signature: 'target:model:1', pageBatch: PAGES }).then(() => null, (e: unknown) => e);
+ expect(String((error as Error | null)?.message)).toMatch(/statement timeout/);
+ expect(await counts()).toMatchObject({ embedded: PAGES * CHUNKS_PER_PAGE });
+ }, 60_000);
+});
diff --git a/test/embed-stale.test.ts b/test/embed-stale.test.ts
index 905fc49d8f..e53e356b78 100644
--- a/test/embed-stale.test.ts
+++ b/test/embed-stale.test.ts
@@ -453,6 +453,29 @@ describe('signature invalidation is probe-gated (#4283)', () => {
expect(sig[0]!.s).toBe(target);
});
+ test('a drift pre-check that cannot count still invalidates (#7148)', async () => {
+ await seedEmbeddedPage('p1', 3, 'old:model:1536');
+ const target = (await recordedModel('p1')) + ':1536';
+ await engine.executeRaw("UPDATE content_chunks SET model = 'old:model' WHERE page_id = (SELECT id FROM pages WHERE slug = 'p1' AND source_id = 'default')");
+ let timedOut = 0;
+ let armed = true;
+ const timingOut = new Proxy(engine, {
+ get(target, key) {
+ if (key === 'countStaleChunks') return async (...args: Parameters<PGLiteEngine['countStaleChunks']>) => {
+ if (armed) { timedOut++; throw new Error('canceling statement due to statement timeout'); }
+ return target.countStaleChunks(...args);
+ };
+ if (key === 'transaction') armed = false;
+ const value = Reflect.get(target, key, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ const result = await embedStaleForSource(timingOut, 'default', { embeddingSignature: target, embedFn: fakeEmbedFn });
+ expect(result.invalidated).toBe(3);
+ expect(result.embedded).toBe(3);
+ expect(timedOut).toBe(0);
+ });
+
test('no signature drift → no probe call (no embed spend on the common path)', async () => {
const { EMBED_PROBE_TEXT } = await import('../src/core/embed-stale.ts');
await seedPageWithStaleChunks('a', 2); // NULL embeddings only, no drift
diff --git a/test/embedding-recovery.serial.test.ts b/test/embedding-recovery.serial.test.ts
index e5d08330ac..7825728d3f 100644
--- a/test/embedding-recovery.serial.test.ts
+++ b/test/embedding-recovery.serial.test.ts
@@ -1075,7 +1075,7 @@ for (const kind of backends) {
let invalidation = false;
const observe = (tx: BrainEngine): BrainEngine => new Proxy(tx, { get(inner, field) {
if (field === 'executeRaw') return async (sql: string, params?: unknown[]) => {
- if (sql.includes('UPDATE content_chunks cc')) invalidation = true;
+ if (sql.includes('UPDATE content_chunks cc') || sql.includes('AS last_id FROM (SELECT id FROM pages')) invalidation = true;
return inner.executeRaw(sql, params);
};
if (field === 'transaction') return (nested: (tx: BrainEngine) => Promise<unknown>) =>
diff --git a/test/embedding-signature-stale.test.ts b/test/embedding-signature-stale.test.ts
index bdf230b20c..5e3413bb39 100644
--- a/test/embedding-signature-stale.test.ts
+++ b/test/embedding-signature-stale.test.ts
@@ -17,7 +17,7 @@ import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:tes
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import type { ChunkInput } from '../src/core/types.ts';
-import { invalidateStaleSignatureEmbeddingsGuarded } from '../src/core/embedding-invalidation.ts';
+import { hasSignatureDrift, invalidateStaleSignatureEmbeddingsGuarded } from '../src/core/embedding-invalidation.ts';
import { sealPageTextProjection } from '../src/core/page-state/projections.ts';
import { stampIfPageProvenanceComplete } from '../src/core/embed-stale.ts';
import { installFixtureChunks } from './helpers/page-projection.ts';
@@ -193,3 +193,109 @@ describe('embedding_signature stale semantics', () => {
expect(rows[0]?.embedding_signature).toBe('openai:m:1536');
});
});
+
+describe('windowed stale-signature invalidation (#7148)', () => {
+ const model = 'ollama:example-model:latest';
+
+ /** A mixed corpus: drifted, current-under-an-old-stamp, matching, grandfathered, embed_skip, other-source and archived-source pages. */
+ async function seedCorpus(): Promise<string> {
+ const signature = model + ':' + colDim;
+ await engine.executeRaw("INSERT INTO sources (id, name, config) VALUES ('other', 'other', '{}'::jsonb), ('shelf', 'shelf', '{}'::jsonb) ON CONFLICT (id) DO NOTHING");
+ const page = async (slug: string, stamp: string | null, chunkModel: string, sourceId = 'default') => {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: '# ' + slug }, { sourceId });
+ await installFixtureChunks(engine, slug, Array.from({ length: 3 }, (_, i) => ({
+ chunk_index: i, chunk_text: slug + ' chunk ' + i, chunk_source: 'compiled_truth' as const,
+ embedding: new Float32Array(colDim).fill(0.1), model: chunkModel,
+ })), { sourceId });
+ await engine.executeRaw('UPDATE pages SET embedding_signature = $1 WHERE slug = $2 AND source_id = $3', [stamp, slug, sourceId]);
+ };
+ for (let i = 0; i < 7; i++) await page('drift-' + i, 'old:model:1', 'old:model');
+ await page('current-old-stamp', 'old:model:1', model);
+ await page('matching', signature, model);
+ await page('legacy-old', null, 'old:model');
+ await page('legacy-current', null, model);
+ await page('skipped', 'old:model:1', 'old:model');
+ await engine.executeRaw("UPDATE pages SET frontmatter = frontmatter || '{\"embed_skip\": true}'::jsonb WHERE slug = 'skipped'");
+ await page('elsewhere', 'old:model:1', 'old:model', 'other');
+ await page('shelved', 'old:model:1', 'old:model', 'shelf');
+ await engine.executeRaw("UPDATE sources SET archived = true WHERE id = 'shelf'");
+ for (let i = 7; i < 10; i++) await page('drift-' + i, 'old:model:1', 'old:model');
+ return signature;
+ }
+
+ async function snapshot(): Promise<string[]> {
+ const rows = await engine.executeRaw<{ row: string }>(
+ "SELECT p.source_id || '/' || p.slug || ' ' || COALESCE(p.embedding_signature, '-') || ' ' || string_agg(CASE WHEN cc.embedding IS NULL THEN '0' ELSE '1' END, '' ORDER BY cc.chunk_index) AS row FROM pages p JOIN content_chunks cc ON cc.page_id = p.id GROUP BY p.id ORDER BY p.source_id, p.slug");
+ return rows.map(r => r.row);
+ }
+
+ for (const includeNullSignature of [false, true]) {
+ for (const sourceId of [undefined, 'default']) {
+ test('every page window gives the one-statement result (null=' + includeNullSignature + ', source=' + (sourceId ?? 'all') + ')', async () => {
+ const results: Array<{ invalidated: number; rows: string[] }> = [];
+ for (const pageBatch of [undefined, 1, 2, 5]) {
+ await resetPgliteState(engine);
+ const signature = await seedCorpus();
+ const invalidated = await invalidateStaleSignatureEmbeddingsGuarded(engine, { signature, includeNullSignature, ...(sourceId && { sourceId }), ...(pageBatch && { pageBatch }) });
+ results.push({ invalidated, rows: await snapshot() });
+ }
+ const expected = (includeNullSignature ? 33 : 30) + (sourceId ? 0 : 3);
+ expect(results[0]!.invalidated).toBe(expected);
+ for (const r of results.slice(1)) expect(r).toEqual(results[0]!);
+ const rows = results[0]!.rows;
+ expect(rows).toContain('default/current-old-stamp ' + model + ':' + colDim + ' 111');
+ expect(rows).toContain('default/drift-3 old:model:1 000');
+ expect(rows).toContain('default/skipped old:model:1 111');
+ expect(rows).toContain('shelf/shelved old:model:1 111');
+ expect(rows).toContain('default/legacy-current ' + (includeNullSignature ? model + ':' + colDim : '-') + ' 111');
+ expect(rows).toContain('default/legacy-old - ' + (includeNullSignature ? '000' : '111'));
+ expect(rows).toContain('other/elsewhere old:model:1 ' + (sourceId ? '111' : '000'));
+ });
+ }
+ }
+
+ test('rejects a page window below one', async () => {
+ await expect(invalidateStaleSignatureEmbeddingsGuarded(engine, { signature: 'm:1', pageBatch: 0 })).rejects.toThrow(/page batch/);
+ });
+
+ test('hasSignatureDrift answers what the two-count pre-checks answered', async () => {
+ const signature = model + ':' + colDim;
+ const cases: Array<[string, (s: string) => Promise<void>]> = [
+ ['empty', async () => {}],
+ ['drifted', async s => { await seedEmbedded(s, 'x', 'old:model:1'); }],
+ ['matching', async s => { await seedEmbedded(s, 'x', signature); }],
+ ['legacy', async s => { await seedEmbedded(s, 'x', null); }],
+ ['unembedded-drifted', async s => {
+ await seedEmbedded(s, 'x', 'old:model:1');
+ await engine.executeRaw('UPDATE content_chunks SET embedding = NULL');
+ }],
+ ['skipped', async s => {
+ await seedEmbedded(s, 'x', 'old:model:1');
+ await engine.executeRaw("UPDATE pages SET frontmatter = frontmatter || '{\"embed_skip\": true}'::jsonb");
+ }],
+ ['deleted', async s => {
+ await seedEmbedded(s, 'x', 'old:model:1');
+ await engine.softDeletePage(s, { sourceId: 'default' });
+ }],
+ ];
+ const seen: Record<string, boolean[]> = {};
+ for (const [name, seed] of cases) {
+ await resetPgliteState(engine);
+ await seed('case-' + name);
+ const wide = await engine.countStaleChunks({ signature });
+ const wideNull = await engine.countStaleChunks({ signature, includeNullSignature: true });
+ const nullOnly = await engine.countStaleChunks();
+ const answers = [
+ await hasSignatureDrift(engine, { signature }),
+ await hasSignatureDrift(engine, { signature, includeNullSignature: true }),
+ await hasSignatureDrift(engine, { signature, nullSignatureOnly: true }),
+ await hasSignatureDrift(engine, { signature, sourceId: 'default' }),
+ await hasSignatureDrift(engine, { signature, sourceId: 'other' }),
+ ];
+ expect(answers).toEqual([wide - nullOnly > 0, wideNull - nullOnly > 0, wideNull - wide > 0, wide - nullOnly > 0, false]);
+ seen[name] = answers;
+ }
+ expect(seen.drifted).toEqual([true, true, false, true, false]);
+ expect(seen.legacy).toEqual([false, true, true, false, false]);
+ });
+});