Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(embed): skip and report facts over the embedding input limit instead of failing the batch (#7211)
garrytan9fbaed34d82b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c5cef35680..c384e4c78d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,9 +10,9 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).-## [0.60.332.0] - 2026-10-20+## [0.60.333.0] - 2026-10-21-**A model or dimension swap now finishes re-embedding on a large brain.** After a swap, `gbrain embed --stale`, the background backfill and `gbrain migrate embeddings` mark every chunk from the old model for re-embedding. That marking was one statement over the whole brain, so on a large brain the statement timeout cancelled it, nothing was marked, and the next run hit the same timeout. Separately, before probing the embedder, every embed run counted drifted chunks with two full joins over every chunk. On a large drifted brain those counts timed out too, and the timeout was read as "no drift", so the swap was silently skipped.+**A model or dimension swap now finishes re-embedding on a large brain, and one overlong fact no longer stops the fact backfill.** After a swap, `gbrain embed --stale`, the background backfill and `gbrain migrate embeddings` mark every chunk from the old model for re-embedding. That marking was one statement over the whole brain, so on a large brain the statement timeout cancelled it, nothing was marked, and the next run hit the same timeout. Separately, before probing the embedder, every embed run counted drifted chunks with two full joins over every chunk. On a large drifted brain those counts timed out too, and the timeout was read as "no drift", so the swap was silently skipped.### What changed@@ -21,17 +21,21 @@ identifiers and attribution are available in the pre-removal Git revision| Marking old-model chunks after a model or width swap | one statement over every chunk; cancelled by the statement timeout on a large brain | one pair of statements per 1,000 pages, all committed together || The drift check before the embedder probe | two `count(*)` joins over every chunk on every run; a timeout read as "no drift" | one page-first `EXISTS`; a healthy brain answers it without reading chunks || The "probe failed, skipping invalidation" warning | named a chunk count | no count, since nothing is counted before the probe |+| A fact longer than the embedding input limit during `gbrain embed --facts` | the whole batch failed with "A fact exceeds the embedding input limit; no batch was sent", and every later run stopped at the same fact | that fact is skipped, never truncated, and reported (`refused_oversized` with its id, doctor `fact_take_vectors`, `gbrain embed --held`); every other fact embeds |### What to watch for after you upgrade- Nothing runs on upgrade. The next `gbrain embed --stale` or `gbrain migrate embeddings` after a swap marks the old vectors and re-embeds them as before.+- A skipped fact stays stale with its text unchanged. Shorten or split it in its page's `## Facts` fence, or withdraw it with `gbrain forget <fact-id>`; the next `gbrain embed --facts` embeds it once it fits. Until then `gbrain migrate embeddings` counts it as remaining.### Itemized changes- `invalidateStaleSignatureEmbeddingsGuarded` runs in page-id windows (`SIGNATURE_INVALIDATION_PAGE_BATCH`, 1000) inside one transaction.- New `hasSignatureDrift` replaces the drift pre-counts in `gbrain embed` and the embed backfill, and gates the NULL-signature (left-behind) warning's counts.-Follow-up to #7117 (#7148).+- `gbrain embed --facts` skips facts over the input limit (`readOversizedStaleFacts`) and reports `refused_oversized`, `refused_samples` and `refused_fix`; doctor `fact_take_vectors` adds `facts.oversized`, and `gbrain embed --held` lists them with `oversized_facts`.++Follow-up to #7117 (#7148). Oversized facts reported by @dyana1lyons-ai (#7211).## [0.60.330.0] - 2026-10-20diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.mdindex 670c7a89de..2658e3c68d 100644--- a/docs/architecture/key-files/providers.md+++ b/docs/architecture/key-files/providers.md@@ -15,7 +15,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/embed-backfill-submit.ts` — Automatic per-source embed-backfill submitter with a true discriminated result union: `submitted` requires `jobId` plus an explicit spend-bypass payload, `cooldown` requires a reason plus a numeric remaining duration or explicit `null` for active work, `spend_capped` requires cap/spend payloads, and `no_worker_surface` requires the refused engine kind. It queries cooldown/spend state only after the shared admission classification accepts a worker-backed engine, preserving Postgres behavior while guaranteeing PGLite/unknown refusal before config, schema, or SQL access; callers handle every status exhaustively.-- `src/core/embed-facts.ts` — explicit source-scoped NULL-fact vector repair with read-only default preview, finite nonnegative spend cap plus optional count/time bounds, row-version/incarnation/withdrawal CAS and per-attempt cost accounting. Selected-brain policy is a trusted out-of-band argument; engine DB off-switch and policy are rechecked on every provider attempt. Managed mode updates physical projection only and live PGLite delegates through private `writer_embed_facts`, not a canonical fact rewrite. Tests: `test/e2e/fact-embedding-backfill-parity.test.ts`, `test/fact-backfill-resident.test.ts`.+- `src/core/embed-facts.ts` — explicit source-scoped NULL-fact vector repair with read-only default preview, finite nonnegative spend cap plus optional count/time bounds, row-version/incarnation/withdrawal CAS and per-attempt cost accounting. Selected-brain policy is a trusted out-of-band argument; engine DB off-switch and policy are rechecked on every provider attempt. Managed mode updates physical projection only and live PGLite delegates through private `writer_embed_facts`, not a canonical fact rewrite. A fact over the embedding input limit is skipped, never sent or truncated, and does not use up `--max-facts`; the result reports it (`refused_oversized`, `refused_samples`, `refused_fix`) and leaves it out of `remaining`. `readOversizedStaleFacts` (`src/core/facts/embedding-identity.ts`) feeds that, doctor `fact_take_vectors` and `gbrain embed --held` (#7211). Tests: `test/e2e/fact-embedding-backfill-parity.test.ts`, `test/fact-backfill-resident.test.ts`, `test/fact-embedding-oversized-7211.test.ts`.- `src/core/embedding-input-hash.ts` — per-chunk embedding-input provenance (#5553). `embeddingInputHash` digests the vector column, model, dimensions, wrapping tier and the exact input (chunk text; title prefix + text; or, for the unrecomputable synopsis tier, the page's corpus generation, title, `synopsisBodyHash` of the chunk set and the text). `acceptedEmbeddingInputHashes` also accepts title-tier vectors on synopsis pages; `plainEmbeddingTier` mirrors `wrapChunkTextsForStoredMode`. A body change therefore nulls every synopsis-tier chunk and nothing else unchanged. Pinned by `test/projection-embedding-input-hash.test.ts` (PGLite and Postgres).- `src/core/embed-oversize-heal.ts` — heals ALREADY-STORED chunks that exceed the active embedding model's per-input token cap (new imports respect `resolveMaxChunkTokens()`, but `--stale` re-embeds existing `chunk_text` rows chunked under looser caps, which fail every sweep forever). `healOversizedChunks` splits oversized rows in place (never truncates; char-based hard split as the pathological fallback), re-indexes contiguously, carries each piece's modality/code-symbol metadata, and leaves embeddings unset so `upsertChunks` preserves vectors for unchanged `(chunk_index, chunk_text)` pairs and NULLs the split/shifted ones; `healOversizedPageChunks` is the load-split-upsert-reload wrapper. `healedChunksToStaleRows(chunks, slug, sourceId)` remaps a post-heal chunk list back into the stale-row shape — the shared seam between `src/commands/embed.ts:embedAllStale` and `src/core/embed-stale.ts:embedStaleForSource` so the two drains cannot drift; `chunk_source` passes through UNCHANGED (coercing `fenced_code` to `compiled_truth` would make `wrapChunkTextsForStoredMode` prefix code chunks, violating the D20-T4 never-wrap convention). Pinned by `test/embed-oversize-heal.test.ts`.diff --git a/src/commands/doctor/checks/vector-coverage.ts b/src/commands/doctor/checks/vector-coverage.tsindex 7f5eebfd47..a05c1a6a13 100644--- a/src/commands/doctor/checks/vector-coverage.ts+++ b/src/commands/doctor/checks/vector-coverage.ts@@ -10,7 +10,8 @@*/import { loadConfig } from '../../../core/config.ts';import { AUDIT_ROW_SOURCES } from '../../../core/facts/audit-sources.ts';-import { eligibleFactEmbedding, partiallyEmbeddedFact, staleFactEmbedding } from '../../../core/facts/embedding-identity.ts';+import { eligibleFactEmbedding, partiallyEmbeddedFact, staleFactEmbedding, readOversizedStaleFacts, oversizedFactLine, OVERSIZED_FACT_FIX } from '../../../core/facts/embedding-identity.ts';+import { resolveMaxChunkTokens } from '../../../core/embedding-input-limit.ts';import { EMBED_MAX_CHARS } from '../../../core/ai/embed-batch-plan.ts';import { takesAutoEmbedEnabled } from '../../../core/embed-takes.ts';import type { Check } from '../../doctor.ts';@@ -59,8 +60,13 @@ async function runFactTakeVectors(ctx: DoctorContext): Promise<Check[]> {}const sum = (key: keyof Omit<SourceVectors, 'source_id'>) => bySource.reduce((n, r) => n + r[key], 0);const partiallyEmbedded = factRows.filter(r => sources.some(s => s.id === r.source_id)).reduce((n, r) => n + Number(r.partial), 0);+ const maxTokens = resolveMaxChunkTokens();+ const oversized = sum('facts_stale') ? await readOversizedStaleFacts(engine, { sourceId: ctx.orphanRatioSourceId ?? undefined, model, dims, maxTokens }) : [];const facts = { missing: sum('facts_missing'), other_model: sum('facts_stale') - sum('facts_missing'), stale: sum('facts_stale'),- partially_embedded: partiallyEmbedded };+ partially_embedded: partiallyEmbedded, oversized: oversized.length };+ const oversizedNote = oversized.length+ ? ` ${oversized.length} of the stale fact(s) are longer than the embedding input limit (${maxTokens} tokens), so gbrain embed --facts skips them instead of truncating (first: ${oversizedFactLine(oversized[0]!, maxTokens)}). ${OVERSIZED_FACT_FIX} gbrain embed --held --dry-run lists them.`+ : '';const partialNote = partiallyEmbedded? ` ${partiallyEmbedded} fact(s) are partially embedded: longer than ${EMBED_MAX_CHARS} characters, so their vector covers only the start of the fact. They stay current and are never re-embedded or charged again.`: '';@@ -81,7 +87,7 @@ async function runFactTakeVectors(ctx: DoctorContext): Promise<Check[]> {status: 'warn',message: `${facts.stale} active fact(s) and ${takes.stale} active take(s) have no ${model} (${dims}d) vector for their current text ` +`(facts: ${facts.missing} missing, ${facts.other_model} from another model or text; takes: ${takes.missing_or_changed} missing or claim changed, ${takes.other_model} from another model). ` +- `Vector dedup, consolidation and semantic take search skip them. Fix: ${fix.join('; ')}${partialNote && `.${partialNote}`}`,+ `Vector dedup, consolidation and semantic take search skip them. Fix: ${fix.join('; ')}${partialNote && `.${partialNote}`}${oversizedNote}`,details: { code: 'stale_vectors', applicable: true, model, dims, facts, takes, by_source: bySource,cause: 'facts and takes without a current-model vector', fix, docs: VECTOR_COVERAGE_DOCS },fix: factSources.lengthdiff --git a/src/commands/embed-facts-delegate.ts b/src/commands/embed-facts-delegate.tsindex d3dcbb7b07..a1868d53f7 100644--- a/src/commands/embed-facts-delegate.ts+++ b/src/commands/embed-facts-delegate.ts@@ -6,7 +6,7 @@ import { inspectLockHolder } from '../core/pglite-lock.ts';import { maybeDelegateLocalAdministration, persistenceConfigForBrain } from '../core/persistence/local-client.ts';import { PersistenceIpcTransportError } from '../core/persistence/ipc.ts';import { validateEmbedFactsOptions, type EmbedFactsOptions } from '../core/embed-facts-options.ts';-import type { EmbedFactsResult } from '../core/embed-facts.ts';+import { refusedFactsLine, type EmbedFactsResult } from '../core/embed-facts.ts';import { OperationError, opError } from '../core/ops/contract.ts';import { readFix } from '../core/ops/op-fix.ts';import { setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';@@ -56,6 +56,8 @@ export async function maybeDelegateFactEmbed(hostConfig: GBrainConfig | null, arwhy: 'The owner stopped before admission, so the same request has not run yet.' } });}const result = delegated.result as EmbedFactsResult;+ const refused = refusedFactsLine(result);+ if (refused) process.stderr.write(refused + '\n');await writeStdoutFinal(JSON.stringify(result, null, 2) + '\n');if (result.failures) setCliExitVerdict(1);return true;diff --git a/src/commands/embed.ts b/src/commands/embed.tsindex 7ce2a5b1d0..29b372b7b2 100644--- a/src/commands/embed.ts+++ b/src/commands/embed.ts@@ -2,7 +2,7 @@ import { jsonRequested } from '../core/cli-force-exit.ts';import { prepareProseChunks } from '../core/markdown-chunks.ts';import type { FenceChunkOverlay } from '../core/eligibility/fence-overlay.ts';import { prepareEmbeddingProjections, countArchivedEmbeddingWork, reportBlockedProjections } from '../core/embedding-readiness.ts';-import { embedStaleFacts, type EmbedFactsResult } from '../core/embed-facts.ts';+import { embedStaleFacts, refusedFactsLine, type EmbedFactsResult } from '../core/embed-facts.ts';import { embedTakesForStaleDrain, type EmbedTakesResult } from '../core/embed-takes.ts';import { parseFactEmbedArgs } from './embed-facts-delegate.ts';import { readProjectionSnapshot, installPageProjection, installPageEmbeddings, PageProjectionConflictError, retryProjectionConflict } from '../core/page-state/projections.ts';@@ -896,6 +896,7 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConfif (args.includes('--facts')) {const result = await embedStaleFacts(engine, parseFactEmbedArgs(args), selectedConfig);if (!jsonRequested(args)) console.log(JSON.stringify(result, null, 2));+ if (result.refused_oversized) serr(refusedFactsLine(result)!);return result;}// Keyless clean refusal — see isKeylessStaleRefusal. Checked BEFORE the@@ -1774,9 +1775,7 @@ async function embedAllStale(if (!dryRun && signature) {let drifted = false;try {- // 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).+ // #7148: one page-first EXISTS, never a count over every chunk, so a timeout can no longer read as "no drift".drifted = await hasSignatureDrift(engine, { signature, ...(sourceId && { sourceId }), ...(includeNullSig && { includeNullSignature: true }) });} catch {// Pre-check is best-effort; fall through as "no drift" (no NULLing).diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 5890cdd7bd..16ebbadb1a 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1031,6 +1031,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.330.0', text: 'New doctor check `uncommitted_sync_deletions` and explicit-only repair kind `gbrain repair uncommitted-deletions --source <id>` (#7130): on each managed source\'s owner host, doctor warns about soft-deleted pages a sync removed although Git never held their recorded file (`.gitignore` excludes it, or no commit holds it and it is not on the disk), bounded to 20,000 tombstones per source and 2,000 Git evidence reads per run. The repair previews each page (slug, recorded path, deletion time, evidence, whether a sync deleted it) with a hash; `--apply --expect <hash> --yes` restores exactly that set, each page live and database-only (detached: it forgets its recorded file and no file is written), so the next sync keeps it. Pages another writer deleted join only with `--include-ambiguous`; a sync deletion is recognized by its record or receipt for the page\'s current tombstone. A preview reads one bounded window, newest page id first, and `--after <page-id>` (named in the preview\'s `next_after` and in the doctor message) continues past it. It refuses off the owner host (`not_owner_host`) and a changed plan (`preview_changed`); without `--yes` a non-interactive run exits 3 and changes nothing. Pages already purged cannot be restored by this command; only a backup (pg_dump, or `gbrain backup create`) can bring them back. It never runs on upgrade or automatically.' },// #7148 (GBRA-145, #7117 follow-up). `since` is restamped at the merge slot.{ since: 'TBD', text: 'After a model or dimension swap, `gbrain embed --stale`, the embed backfill and `gbrain migrate embeddings` now mark old-model chunks for re-embedding in windows of 1,000 pages (all committed together) instead of one statement over the whole brain, which a large brain cancelled at the statement timeout on every run. The drift check before the embedder probe is one page-first lookup instead of two counts over every chunk, so a count that timed out can no longer skip the swap silently; the "embedder probe failed" warning no longer names a chunk count.' },+ // #7211 (GBRA-145). `since` is restamped at the merge slot.+ { since: 'TBD', text: '`gbrain embed --facts` no longer fails a whole batch, and every later run, on one fact longer than the embedding input limit: that fact is skipped (never truncated), keeps its text and stays stale, and the result reports it (`refused_oversized`, `refused_samples` with fact ids, `refused_fix`) without counting it in `remaining` or against `--max-facts`. Doctor `fact_take_vectors` adds `facts.oversized`, and `gbrain embed --held` lists them. Shorten or split the fact, or withdraw it with `gbrain forget <fact-id>`, and the next run embeds it once it fits.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/embed-facts.ts b/src/core/embed-facts.tsindex fa6c799220..930db19319 100644--- a/src/core/embed-facts.ts+++ b/src/core/embed-facts.ts@@ -16,7 +16,7 @@ import { validateEmbedFactsOptions, type EmbedFactsOptions } from './embed-factsimport { AUDIT_ROW_SOURCES } from './facts/audit-sources.ts';import { resolveMaxChunkTokens } from './embedding-input-limit.ts';import { estimateTokens } from './chunkers/token-estimate.ts';-import { eligibleFactEmbedding, staleFactEmbedding } from './facts/embedding-identity.ts';+import { eligibleFactEmbedding, staleFactEmbedding, readOversizedStaleFacts, oversizedFactLine, OVERSIZED_FACT_FIX } from './facts/embedding-identity.ts';export interface EmbedFactsOpts extends EmbedFactsOptions {signal?: AbortSignal;@@ -38,6 +38,10 @@ export interface EmbedFactsResult {cost_usd: number;cost_estimated: boolean;stopped: 'preview' | 'complete' | 'limit' | 'time_budget' | 'aborted' | 'failed';+ /** #7211: stale facts over the embedding input limit; skipped, never sent or truncated, and not counted in `remaining`. */+ refused_oversized: number;+ refused_samples: string[];+ refused_fix?: string;}interface PendingFact {@@ -48,6 +52,12 @@ interface PendingFact {const eligible = `f.source_id = $1 AND ${eligibleFactEmbedding} AND ${staleFactEmbedding}`;+/** #7211: the stderr line a fact run prints when it skipped facts over the embedding input limit. */+export function refusedFactsLine(result: Pick<EmbedFactsResult, 'refused_oversized' | 'refused_samples' | 'refused_fix'>): string | null {+ if (!result.refused_oversized) return null;+ return `[embed] ${result.refused_oversized} fact(s) are longer than the embedding input limit and were skipped, not truncated (first: ${result.refused_samples[0]}). ${result.refused_fix}`;+}+export async function embedStaleFacts(engine: BrainEngine, opts: EmbedFactsOpts, selectedConfig: GBrainConfig | null = null): Promise<EmbedFactsResult> {const { signal: externalSignal, assertOwned, migrationDrain, ...wireOptions } = opts;opts = { ...validateEmbedFactsOptions(wireOptions), signal: migrationDrain?.signal ?? externalSignal,@@ -88,13 +98,26 @@ export async function embedStaleFacts(engine: BrainEngine, opts: EmbedFactsOpts,};const initial = await census();const maxFacts = migrationDrain ? initial.count : opts.maxFacts ?? 100;+ const maxTokens = resolveMaxChunkTokens();+ const refused = async () => {+ const rows = await readOversizedStaleFacts(engine, { sourceId: opts.sourceId, model, dims, maxTokens });+ result.refused_oversized = rows.length;+ result.refused_samples = rows.slice(0, 5).map(row => oversizedFactLine(row, maxTokens));+ if (rows.length) result.refused_fix = OVERSIZED_FACT_FIX;+ else delete result.refused_fix;+ return rows.length;+ };const result: EmbedFactsResult = {- source_id: opts.sourceId, dryRun, total_stale: initial.count,- would_embed: dryRun ? Math.min(initial.count, maxFacts) : 0,+ source_id: opts.sourceId, dryRun, total_stale: initial.count, would_embed: 0,attempted: 0, embedded: 0, remaining: initial.count, failures: 0,failure_samples: [], cost_usd: 0, cost_estimated: false, stopped: dryRun ? 'preview' : 'complete',+ refused_oversized: 0, refused_samples: [],};- if (dryRun) return result;+ if (dryRun) {+ result.remaining = initial.count - await refused();+ result.would_embed = Math.min(result.remaining, maxFacts);+ return result;+ }const assertEnabled = async (target: BrainEngine) => {assertEmbeddingEnabled(selectedConfig);const disabled = await target.getConfig('embedding_disabled');@@ -123,7 +146,6 @@ export async function embedStaleFacts(engine: BrainEngine, opts: EmbedFactsOpts,const signal = AbortSignal.any([...(budgetTimer ? [budgetTimer] : []), ...(opts.signal ? [opts.signal] : [])]);const budgetStop = (error?: unknown) => opts.signal?.aborted !== true&& (budgetTimer?.aborted === true || error instanceof BudgetExhausted && error.reason === 'runtime');- const maxTokens = resolveMaxChunkTokens();let afterId = '0';while (result.attempted < maxFacts) {if (budgetStop()) { result.stopped = 'time_budget'; break; }@@ -133,13 +155,13 @@ export async function embedStaleFacts(engine: BrainEngine, opts: EmbedFactsOpts,WHERE ${eligible} AND f.id > $5::bigint AND f.id <= $6::bigintORDER BY f.id LIMIT $7`, [...params, afterId, initial.lastId, Math.min(batchSize, maxFacts - result.attempted)]);if (!batch.length) break;- result.attempted += batch.length;+ const lastId = batch[batch.length - 1].id;+ const fitting = batch.filter(row => estimateTokens(row.fact) <= maxTokens);+ if (!fitting.length) { afterId = lastId; continue; }+ result.attempted += fitting.length;try {- if (batch.some(row => estimateTokens(row.fact) > maxTokens)) {- throw new Error('A fact exceeds the embedding input limit; no batch was sent');- }signal.throwIfAborted();- const inputCeiling = batch.reduce((sum, row) => sum + Math.max(1, Buffer.byteLength(row.fact, 'utf8')), 0);+ const inputCeiling = fitting.reduce((sum, row) => sum + Math.max(1, Buffer.byteLength(row.fact, 'utf8')), 0);const vectors = await withAIInvocationGuard(async call => {signal.throwIfAborted();if (call.kind !== 'embedding') throw new Error('Fact backfill permits embedding calls only');@@ -156,11 +178,11 @@ export async function embedStaleFacts(engine: BrainEngine, opts: EmbedFactsOpts,if (!usage) result.cost_estimated = true;tracker.record({ modelId: call.model, reservation, kind: 'embed', inputTokens: usage?.inputTokens ?? inputCeiling, outputTokens: 0 });} };- }, () => embed(batch.map(row => row.fact), {+ }, () => embed(fitting.map(row => row.fact), {abortSignal: signal, embeddingModel: model, dimensions: dims, inputType: 'document',}), { inherit: true });signal.throwIfAborted();- if (vectors.length !== batch.length || vectors.some(vector =>+ if (vectors.length !== fitting.length || vectors.some(vector =>vector.length !== dims || !vector.every(Number.isFinite))) {throw new Error('Embedding provider returned an incomplete or invalid fact batch');}@@ -176,29 +198,29 @@ export async function embedStaleFacts(engine: BrainEngine, opts: EmbedFactsOpts,throw new Error('Embedding model changed during fact backfill; rerun the scoped preview');}let count = 0;- for (let i = 0; i < batch.length; i++) {+ for (let i = 0; i < fitting.length; i++) {signal.throwIfAborted();const rows = await tx.executeRaw(`UPDATE facts f SET embedding=$7::${shape.columnType}, embedded_at=now(),embedding_model=$3,embedded_text_hash=md5(f.fact)WHERE ${eligible} AND f.id=$5::bigint AND f.xmin::text=$6 RETURNING f.id::text`,- [...params, batch[i].id, batch[i].version, `[${Array.from(vectors[i]).join(',')}]`]);+ [...params, fitting[i].id, fitting[i].version, `[${Array.from(vectors[i]).join(',')}]`]);count += rows.length;}signal.throwIfAborted();return count;});result.embedded += installed;- if (installed !== batch.length) {- result.failures += batch.length - installed;+ if (installed !== fitting.length) {+ result.failures += fitting.length - installed;result.failure_samples.push('Fact state changed during embedding; changed rows were not overwritten. Rerun the scoped preview.');result.stopped = 'failed';break;}- afterId = batch[batch.length - 1].id;+ afterId = lastId;} catch (error) {if (budgetStop(error)) { result.stopped = 'time_budget'; break; }- result.failures += batch.length;+ result.failures += fitting.length;result.failure_samples.push(redactUrlsInText(redactConnectionInfo(redactFindings(error instanceof Error ? error.message : String(error), { highEntropy: true }).text,)).replace(/\s+/g, ' ').slice(0, 500));@@ -207,7 +229,7 @@ export async function embedStaleFacts(engine: BrainEngine, opts: EmbedFactsOpts,}}result.cost_usd = tracker.totalSpent;- result.remaining = (await census()).count;+ result.remaining = (await census()).count - await refused();if (result.stopped === 'complete' && result.remaining > 0) result.stopped = 'limit';return result;}diff --git a/src/core/facts/embedding-identity.ts b/src/core/facts/embedding-identity.tsindex 1c02b4c7f5..65c72b2aed 100644--- a/src/core/facts/embedding-identity.ts+++ b/src/core/facts/embedding-identity.ts@@ -1,6 +1,7 @@import type { BrainEngine } from '../engine.ts';import { AUDIT_ROW_SOURCES } from './audit-sources.ts';import { EMBED_MAX_CHARS } from '../ai/embed-batch-plan.ts';+import { estimateTokens } from '../chunkers/token-estimate.ts';// #6960: one anti-join per fingerprint, each an equality on fact_hash, so the// planner hashes or index-probes the fingerprint once per fact. A single@@ -40,3 +41,30 @@ export async function countStaleFactEmbeddings(engine: Pick<BrainEngine, 'execut[sourceId ?? null, [...AUDIT_ROW_SOURCES], model, dimensions]);return { count: Number(row.count), chars: Number(row.chars) };}++export interface OversizedFact { id: string; source_id: string; slug: string | null; tokens: number }++const OVERSIZED_SCAN_CAP = 10_000;+export const OVERSIZED_FACT_FIX = 'A skipped fact stays stale, with its text unchanged, until it fits: shorten or split it (edit its row in the page\'s ## Facts fence, then sync), or withdraw it with gbrain forget <fact-id>.';++/**+ * #7211: stale, embeddable facts whose text is over the embedding input limit,+ * which the backfill skips instead of sending or truncating. Bytes bound+ * tokens from above (a cl100k token, and the len/4 fallback, is at least one+ * byte), so only facts longer than `maxTokens` bytes are read and measured,+ * at most OVERSIZED_SCAN_CAP of them.+ */+export async function readOversizedStaleFacts(engine: Pick<BrainEngine, 'executeRaw'>,+ opts: { sourceId?: string; model: string; dims: number; maxTokens: number }): Promise<OversizedFact[]> {+ const rows = await engine.executeRaw<{ id: string; source_id: string; slug: string | null; fact: string }>(+ `SELECT f.id::text, f.source_id, f.source_markdown_slug AS slug, f.fact FROM facts f+ WHERE ($1::text IS NULL OR f.source_id = $1) AND ${eligibleFactEmbedding} AND ${staleFactEmbedding}+ AND octet_length(f.fact) > $5::int ORDER BY f.id LIMIT ${OVERSIZED_SCAN_CAP}`,+ [opts.sourceId ?? null, [...AUDIT_ROW_SOURCES], opts.model, opts.dims, opts.maxTokens]);+ return rows.map(row => ({ id: row.id, source_id: row.source_id, slug: row.slug, tokens: estimateTokens(row.fact) }))+ .filter(row => row.tokens > opts.maxTokens);+}++export function oversizedFactLine(row: OversizedFact, maxTokens: number): string {+ return `fact ${row.id} (${row.slug ? `page ${row.slug}` : 'database-only'}, source ${row.source_id}): about ${row.tokens} tokens, limit ${maxTokens}`;+}diff --git a/src/core/held-embedding.ts b/src/core/held-embedding.tsindex e6f4198fa3..b9a9b3e1b4 100644--- a/src/core/held-embedding.ts+++ b/src/core/held-embedding.ts@@ -34,6 +34,8 @@ import { chunkGenerationFilter } from './search/safe-chunks.ts';import { quoteIdentifier } from './search/embedding-column.ts';import { embeddingWriteTarget } from './page-state/projections.ts';import { budgetRowAppliesFilter } from './page-size-policy.ts';+import { readOversizedStaleFacts, oversizedFactLine, OVERSIZED_FACT_FIX, type OversizedFact } from './facts/embedding-identity.ts';+import { resolveMaxChunkTokens } from './embedding-input-limit.ts';import { reservationCostUsd } from './budget/reservation-cost.ts';import { loadPricingOverrides } from './budget/budget-tracker.ts';import { estimatePageEmbedUsd, listBudgetLimitedPages } from './page-embedding-budget.ts';@@ -147,10 +149,29 @@ type HeldListing = {embedded: 0; skipped: 0; would_embed: number; total_chunks: number; pages_processed: 0; failures: 0; failure_samples: []; dryRun: boolean; chunkless_pages_healed: 0;held?: number; capped?: number; pages?: Array<{ slug: string; source_id: string; state: string; reason: string | null; pending_chunks: number; spent_usd: number; est_usd: number }>;sources?: BudgetLimitedReportSource[];+ oversized_facts?: OversizedFact[];};const emptyListing = (dryRun: boolean): HeldListing => ({ embedded: 0, skipped: 0, would_embed: 0, total_chunks: 0, pages_processed: 0, failures: 0, failure_samples: [], dryRun, chunkless_pages_healed: 0,...(dryRun ? { held: 0, capped: 0, pages: [], sources: [] } : {}) });+/**+ * #7211: stale facts over the embedding input limit, which `gbrain embed --facts` skips. No+ * approval releases them (only an edit that makes the text fit does), so --held lists them and moves on.+ */+async function oversizedFacts(engine: BrainEngine, sourceId: string | undefined, say: (line: string) => void): Promise<OversizedFact[]> {+ const { getEmbeddingModel, getEmbeddingDimensions } = await import('./ai/gateway.ts');+ let model: string, dims: number;+ try { model = getEmbeddingModel(); dims = getEmbeddingDimensions(); } catch { return []; }+ const maxTokens = resolveMaxChunkTokens();+ const rows = await readOversizedStaleFacts(engine, { ...(sourceId ? { sourceId } : {}), model, dims, maxTokens });+ if (!rows.length) return rows;+ say(`[embed] ${rows.length} fact(s) are longer than the embedding input limit and are skipped by gbrain embed --facts:`);+ for (const row of rows.slice(0, 20)) say(`[embed] ${oversizedFactLine(row, maxTokens)}`);+ if (rows.length > 20) say(`[embed] … and ${rows.length - 20} more (gbrain embed --held --dry-run --json lists every one)`);+ say(`[embed] ${OVERSIZED_FACT_FIX}`);+ return rows;+}+/*** `gbrain embed --held`: list the held and capped large pages with what each* would cost to finish. A dry run returns the listing (every source unless@@ -164,10 +185,12 @@ export async function heldEmbedArgv(engine: BrainEngine, args: readonly string[]const at = args.indexOf('--source');const sourceId = at >= 0 ? args[at + 1] : undefined;const dryRun = args.includes('--dry-run');+ const oversized = await oversizedFacts(engine, sourceId, say);+ const withFacts = (listing: HeldListing): HeldListing => oversized.length ? { ...listing, oversized_facts: oversized } : listing;const limited = await listBudgetLimitedPages(engine, { ...(sourceId ? { sourceId } : {}), limit: null });if (limited.length === 0) {say('[embed] No large pages are held or capped by embed.max_usd_per_page.');- return emptyListing(dryRun);+ return withFacts(emptyListing(dryRun));}const pages = limited.map(row => ({ slug: row.slug, source_id: row.source_id, state: row.state, reason: row.reason, pending_chunks: row.pending_chunks,spent_usd: row.spent_usd, est_usd: estimatePageEmbedUsd(row.pending_chars, signature) }));@@ -179,8 +202,8 @@ export async function heldEmbedArgv(engine: BrainEngine, args: readonly string[]if (dryRun) {const found = await budgetLimitedReport(engine, { ...(sourceId ? { sourceId } : {}), signature });if (found) say(`[embed] ${found.line}`);- return { ...emptyListing(true), would_embed: found?.report.pending_chunks ?? 0, total_chunks: found?.report.pending_chunks ?? 0,- held: found?.report.held ?? 0, capped: found?.report.capped ?? 0, pages, sources: found?.report.by_source ?? [] };+ return withFacts({ ...emptyListing(true), would_embed: found?.report.pending_chunks ?? 0, total_chunks: found?.report.pending_chunks ?? 0,+ held: found?.report.held ?? 0, capped: found?.report.capped ?? 0, pages, sources: found?.report.by_source ?? [] });}if (sources.length > 1) {const found = await budgetLimitedReport(engine, { signature });diff --git a/test/fact-embedding-oversized-7211.test.ts b/test/fact-embedding-oversized-7211.test.tsnew file mode 100644index 0000000000..ef88b60c7e--- /dev/null+++ b/test/fact-embedding-oversized-7211.test.ts@@ -0,0 +1,145 @@+/**+ * #7211: one fact longer than the embedding input limit must not wedge the+ * stale-fact backfill. Before, the loop threw "A fact exceeds the embedding+ * input limit; no batch was sent" for the whole batch, so every later run hit+ * the same row first and the facts behind it never embedded.+ *+ * Policy: no silent truncation. An oversized fact is skipped with a reported+ * refusal (run summary, doctor fact_take_vectors, embed --held), stays stale+ * with its text unchanged, and embeds once an edit makes it fit. Every other+ * fact progresses, and skipped facts do not use up --max-facts.+ * The cap is pinned low (GBRAIN_MAX_CHUNK_TOKENS=64) so short synthetic facts+ * cross it; the astral fact is under 64 characters but over 64 tokens.+ * Reported by @dyana1lyons-ai.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { __setEmbedTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { embedStaleFacts } from '../src/core/embed-facts.ts';+import { estimateTokens } from '../src/core/chunkers/token-estimate.ts';+import { factTakeVectorsEntry } from '../src/commands/doctor/checks/vector-coverage.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import type { Check } from '../src/commands/doctor.ts';+import { readFactsEmbeddingDim } from '../src/core/embedding-dim-check.ts';+import { heldEmbedArgv } from '../src/core/held-embedding.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const SOURCE = 'oversized-fact-7211';+const MODEL = 'openai:text-embedding-3-small';+const CAP = 64;+const LONG = Array.from({ length: 60 }, (_, i) => 'clause' + i).join(' ');+const ASTRAL = '\u{1F9EA}\u{1F52C}\u{1F9EC}'.repeat(15);+let calls: string[][] = [];+let DIMS = 0;++const doctor = async (engine: BrainEngine) =>+ (await factTakeVectorsEntry.run({ engine, orphanRatioSourceId: SOURCE, progress: { heartbeat() {} } } as unknown as DoctorContext) as Check[])[0];+const approved = { sourceId: SOURCE, yes: true, maxCostUsd: 1 };+const capped = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_MAX_CHUNK_TOKENS: String(CAP) }, fn);++for (const backend of testBackends()) describe('oversized facts never wedge the fact backfill (' + backend + ')', () => {+ let engine: BrainEngine;+ beforeAll(async () => {+ if (backend === 'postgres') {+ const { setupDB, getEngine } = await import('./e2e/helpers.ts');+ await setupDB();+ engine = getEngine();+ } else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ }+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SOURCE]);+ DIMS = (await readFactsEmbeddingDim(engine)).dims!;+ await engine.setConfig('embedding_model', MODEL);+ await engine.setConfig('embedding_dimensions', String(DIMS));+ });+ afterAll(async () => {+ __setEmbedTransportForTests(null);+ resetGateway();+ await engine.executeRaw('DELETE FROM facts WHERE source_id = $1', [SOURCE]);+ await engine.executeRaw('DELETE FROM sources WHERE id = $1', [SOURCE]);+ if (backend === 'pglite') await engine.disconnect();+ });+ beforeEach(async () => {+ calls = [];+ configureGateway({ embedding_model: MODEL, embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'test-key' } });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => {+ calls.push([...values]);+ return { values, usage: { tokens: values.length }, warnings: [], embeddings: values.map(() => Array(DIMS).fill(0.25)) };+ }) as never);+ await engine.executeRaw('DELETE FROM facts WHERE source_id = $1', [SOURCE]);+ });++ async function seed(...facts: string[]): Promise<string[]> {+ const ids: string[] = [];+ for (const fact of facts) {+ const row = await engine.insertFact({ fact, kind: 'fact', confidence: 1, source: 'notes', visibility: 'world', notability: 'medium' }, { source_id: SOURCE });+ ids.push(String(row.id));+ }+ return ids;+ }+ const texts = async () => (await engine.executeRaw<{ fact: string; embedded: boolean }>(+ 'SELECT fact, embedding IS NOT NULL AS embedded FROM facts WHERE source_id = $1 ORDER BY id', [SOURCE])).map(r => [r.fact, r.embedded]);++ test('the fixtures cross the cap by tokens, not only by characters', () => {+ expect(estimateTokens(LONG)).toBeGreaterThan(CAP);+ expect([...ASTRAL].length).toBeLessThan(CAP);+ expect(estimateTokens(ASTRAL)).toBeGreaterThan(CAP);+ });++ test('normal facts embed, oversized facts are refused with their ids, and a second run does not wedge', async () => {+ const [, longId, , astralId] = await seed('Alice example joined Acme example.', LONG, 'Bob example leads Fund A.', ASTRAL, 'Carol example moved to Oslo.');+ const first = await capped(() => embedStaleFacts(engine, approved));+ expect(first).toMatchObject({ embedded: 3, attempted: 3, failures: 0, failure_samples: [], refused_oversized: 2, remaining: 0, stopped: 'complete' });+ expect(first.refused_samples.join('\n')).toContain('fact ' + longId);+ expect(first.refused_samples.join('\n')).toContain('fact ' + astralId);+ expect(first.refused_fix).toContain('gbrain forget');+ expect(calls.flat()).not.toContain(LONG);+ expect(calls.flat()).not.toContain(ASTRAL);+ expect(await texts()).toEqual([['Alice example joined Acme example.', true], [LONG, false], ['Bob example leads Fund A.', true], [ASTRAL, false], ['Carol example moved to Oslo.', true]]);++ calls = [];+ const second = await capped(() => embedStaleFacts(engine, approved));+ expect(second).toMatchObject({ total_stale: 2, embedded: 0, failures: 0, refused_oversized: 2, remaining: 0, stopped: 'complete' });+ expect(calls).toEqual([]);+ });++ test('refused facts do not use up --max-facts', async () => {+ await seed(LONG, ASTRAL, 'Alice example joined Acme example.');+ const run = await capped(() => embedStaleFacts(engine, { ...approved, maxFacts: 1 }));+ expect(run).toMatchObject({ embedded: 1, attempted: 1, refused_oversized: 2, remaining: 0 });+ });++ test('an edit that makes the fact fit embeds it; an edit to an embedded fact makes it stale again', async () => {+ const [shortId, longId] = await seed('Alice example joined Acme example.', LONG);+ await capped(() => embedStaleFacts(engine, approved));+ await engine.executeRaw("UPDATE facts SET fact = 'Dave example founded Acme example.' WHERE id = $1::bigint", [longId]);+ await engine.executeRaw("UPDATE facts SET fact = 'Alice example left Acme example.' WHERE id = $1::bigint", [shortId]);+ calls = [];+ const run = await capped(() => embedStaleFacts(engine, approved));+ expect(run).toMatchObject({ total_stale: 2, embedded: 2, refused_oversized: 0, remaining: 0, stopped: 'complete' });+ expect(calls.flat().sort()).toEqual(['Alice example left Acme example.', 'Dave example founded Acme example.']);+ });++ test('the preview counts refused facts apart from the work it would do', async () => {+ await seed(LONG, 'Alice example joined Acme example.');+ const preview = await capped(() => embedStaleFacts(engine, { sourceId: SOURCE }));+ expect(preview).toMatchObject({ dryRun: true, total_stale: 2, would_embed: 1, refused_oversized: 1, stopped: 'preview' });+ expect(calls).toEqual([]);+ });++ test('doctor and embed --held name the refused facts and the fix', async () => {+ const [longId] = await seed(LONG);+ const check = await capped(() => doctor(engine));+ expect(check).toMatchObject({ status: 'warn', details: { facts: { stale: 1, oversized: 1 } } });+ expect(check.message).toContain('longer than the embedding input limit');+ expect(check.message).toContain('gbrain forget');+ const said: string[] = [];+ const held = await capped(() => heldEmbedArgv(engine, ['--held', '--dry-run'], null, line => said.push(line)));+ expect(held).toMatchObject({ dryRun: true, oversized_facts: [{ id: longId, source_id: SOURCE }] });+ expect(said.join('\n')).toContain('fact ' + longId);+ });+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 1745fd8d1d..37e2e0c918 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -62,6 +62,7 @@ test/extract-endpoint-revision.serial.test.tstest/extract-entities-managed.test.tstest/extract-timeline-from-meetings-managed.test.tstest/extraction-watermark-atoms.test.ts+test/fact-embedding-oversized-7211.test.tstest/fact-fence-adoption-exits.test.tstest/fact-purge-lookup-timeout-6511.test.tstest/facts-publication-large-fence-6898.test.ts