Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

embedding paths: image rows are never re-stamped; the image sweep counts classes (#6803)

garrytanacfeeb8f358f
diff --git a/src/commands/migrate-embeddings.ts b/src/commands/migrate-embeddings.ts
index 957f22e824..36e0693266 100644
--- a/src/commands/migrate-embeddings.ts
+++ b/src/commands/migrate-embeddings.ts
@@ -700,7 +700,7 @@ export async function executeMigrationFlow(
await assertOwned();
const readiness = await prepareEmbeddingProjections(engine, { repair: true, assertOwned });
- if (readiness.blocked) return { status: 'apply_failed', reason: `projection_blocked: ${readiness.blocked} page(s) remain; no migration-wide embedding invalidation performed. Canonical projection recovery may have made durable progress. Inspect blockers before retrying: archived sources require deliberate gbrain sources restore <id>; unsupported media requires its source importer. See docs/guides/embedding-migration.md#recovery.` };
+ if (readiness.blocked) return { status: 'apply_failed', reason: `projection_blocked: ${readiness.blocked} page(s) remain; no migration-wide embedding invalidation performed. Canonical projection recovery may have made durable progress. Inspect blockers before retrying: archived sources require deliberate gbrain sources restore <id>; image pages are counted by class in gbrain doctor --only text_projection_readiness --json (gbrain projections drain seals the sealable ones). See docs/guides/embedding-migration.md#recovery.` };
const applied = await applyEmbeddingMigration(engine, plan, {
ignoreEnvOverride: opts.ignoreEnvOverride,
diff --git a/src/core/embed-stale-images.ts b/src/core/embed-stale-images.ts
index 228f9bfad1..42b06c5100 100644
--- a/src/core/embed-stale-images.ts
+++ b/src/core/embed-stale-images.ts
@@ -30,7 +30,8 @@ import { importImageFile } from './import-file.ts';
import { resolveRecordedImageFile, type DirectoryListings, type RecordedImageFile } from './image-asset-resolver.ts';
import { importManagedFile } from './persistence/import-mutations.ts';
import { readManagedMode } from './persistence/managed-mode.ts';
-import { safeChunksFilter } from './search/safe-chunks.ts';
+import { OCR_REQUIRED_ERROR, safeChunksFilter } from './search/safe-chunks.ts';
+import { projectionClassSql } from './page-state/projection-class.ts';
import { serr } from './console-prefix.ts';
import { gitChildEnv } from './git-env.ts';
import { isMultimodalEnabled } from './sync.ts';
@@ -39,8 +40,24 @@ import { embedCostStopVerdict, noteEmbedCostStop, type EmbedCostCap, type EmbedC
export interface StaleImageSweepResult extends EmbedCostStopFields {
candidates: number;
rebuilt: number;
- /** Candidates the importer left unchanged (complete by its own check, or refused). */
+ /** Candidates the importer left unchanged (complete by its own check, or refused for another reason). */
skipped: number;
+ /**
+ * #6803: the classes of the image pages in scope (page-state/projection-class.ts).
+ * `reimport`: unsealed images only the importer can seal (doctor's `reimport`);
+ * `incomplete_sealed`: sealed images missing their visual vector or OCR text;
+ * `ocr_required`: reimport pages of distrusted provenance the importer seals
+ * only after a successful fresh OCR pass (with OCR off, the dry run's
+ * expectation; after a run, the pages it refused); `sealable`, `protected` and
+ * `archived` are never candidates (`gbrain projections drain` seals the first,
+ * the others stay unsealed by design).
+ */
+ reimport: number;
+ incomplete_sealed: number;
+ ocr_required: number;
+ sealable: number;
+ protected: number;
+ archived: number;
missingFile: number;
/** Candidates whose `pages.source_path` was NULL; the sweep located them by slug and the import recorded the path. */
missingSourcePath: number;
@@ -59,21 +76,33 @@ export async function embedStaleImages(
const ocrWanted = process.env.GBRAIN_EMBEDDING_IMAGE_OCR === 'true';
const params: unknown[] = [ocrWanted];
if (opts.sourceId) params.push(opts.sourceId);
- const rows = await engine.executeRaw<{ slug: string; source_id: string; source_path: string | null; local_path: string | null }>(
- `SELECT p.slug, p.source_id, p.source_path, s.local_path FROM pages p JOIN sources s ON s.id = p.source_id
- WHERE p.page_kind = 'image' AND p.deleted_at IS NULL${opts.sourceId ? ' AND p.source_id = $2' : ''}
- AND (NOT (${safeChunksFilter('p')})
- OR p.text_projection_revision IS DISTINCT FROM p.knowledge_revision
+ // #6803: an unsealed image is a candidate only in the reimport class; a sealed one keeps its two incompleteness arms.
+ const scope = `FROM pages p JOIN sources s ON s.id = p.source_id CROSS JOIN LATERAL (SELECT ${projectionClassSql('p', 's')} AS cls) k
+ WHERE p.page_kind = 'image' AND p.deleted_at IS NULL${opts.sourceId ? ' AND p.source_id = $2' : ''}`;
+ const unsealed = 'p.text_projection_revision IS DISTINCT FROM p.knowledge_revision';
+ const incompleteSealed = `(NOT (${safeChunksFilter('p')})
OR NOT EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id = p.id AND c.embedding_image IS NOT NULL)
- OR ($1 AND COALESCE(p.frontmatter->>'ocr_status', '') <> 'done' AND btrim(p.compiled_truth) = ''))
+ OR ($1 AND COALESCE(p.frontmatter->>'ocr_status', '') <> 'done' AND btrim(p.compiled_truth) = ''))`;
+ const rows = await engine.executeRaw<{ slug: string; source_id: string; source_path: string | null; local_path: string | null }>(
+ `SELECT p.slug, p.source_id, p.source_path, s.local_path ${scope}
+ AND CASE WHEN ${unsealed} THEN k.cls = 'reimport' ELSE ${incompleteSealed} END
ORDER BY p.id`, params);
+ const [counts] = await engine.executeRaw<Record<'reimport' | 'incomplete_sealed' | 'ocr_required' | 'sealable' | 'protected' | 'archived', number>>(
+ `SELECT COUNT(*) FILTER (WHERE ${unsealed} AND k.cls = 'reimport')::int AS reimport,
+ COUNT(*) FILTER (WHERE NOT (${unsealed}) AND ${incompleteSealed})::int AS incomplete_sealed,
+ COUNT(*) FILTER (WHERE NOT $1 AND ${unsealed} AND k.cls = 'reimport' AND p.chunker_version < 0)::int AS ocr_required,
+ COUNT(*) FILTER (WHERE ${unsealed} AND k.cls = 'sealable')::int AS sealable,
+ COUNT(*) FILTER (WHERE ${unsealed} AND k.cls = 'protected')::int AS protected,
+ COUNT(*) FILTER (WHERE ${unsealed} AND k.cls = 'archived')::int AS archived ${scope}`, params);
const result: StaleImageSweepResult = { candidates: rows.length, rebuilt: 0, skipped: 0, missingFile: 0, missingSourcePath: rows.filter(row => row.source_path === null).length,
- failures: 0, failure_samples: [], missing_samples: [] };
+ failures: 0, failure_samples: [], missing_samples: [], reimport: Number(counts?.reimport ?? 0), incomplete_sealed: Number(counts?.incomplete_sealed ?? 0),
+ ocr_required: Number(counts?.ocr_required ?? 0), sealable: Number(counts?.sealable ?? 0), protected: Number(counts?.protected ?? 0), archived: Number(counts?.archived ?? 0) };
const fail = (row: { source_id: string; slug: string }, error: string) => {
result.failures++;
if (result.failure_samples.length < SAMPLE_CAP) result.failure_samples.push(`${row.source_id}:${row.slug}: ${error}`);
};
if (opts.dryRun) return result;
+ result.ocr_required = 0;
const repoPath = await engine.getConfig('sync.repo_path').catch(() => null);
const managed = await readManagedMode(engine);
const gitRoots = new Map<string, string | null>();
@@ -103,6 +132,7 @@ export async function embedStaleImages(
if (imported.status === 'imported') result.rebuilt++;
else if (cap?.hit()) break;
else if (imported.status === 'error') fail(row, imported.error ?? 'import failed');
+ else if (imported.error === OCR_REQUIRED_ERROR) result.ocr_required++;
else result.skipped++;
} catch (e) {
if (cap?.hit()) break;
@@ -161,8 +191,12 @@ export async function runEmbedStaleImagesCli(engine: BrainEngine, args: string[]
const capped = costCap?.hit();
if (capped) noteEmbedCostStop(result, capped, args);
if (args.includes('--json')) console.log(JSON.stringify(result));
- else console.log(`[embed] images: ${result.candidates} incomplete${result.missingSourcePath ? ` (${result.missingSourcePath} with no recorded source_path, located by slug)` : ''}, ${dryRun ? '(dry run) nothing rebuilt'
- : `${result.rebuilt} rebuilt, ${result.skipped} unchanged, ${result.missingFile} missing source file, ${result.failures} failed`}`);
+ else {
+ console.log(`[embed] images: ${result.candidates} incomplete (${result.reimport} to reimport, ${result.incomplete_sealed} sealed but incomplete)${result.missingSourcePath ? ` (${result.missingSourcePath} with no recorded source_path, located by slug)` : ''}, ${dryRun ? '(dry run) nothing rebuilt'
+ : `${result.rebuilt} rebuilt, ${result.skipped} unchanged, ${result.ocr_required} need OCR, ${result.missingFile} missing source file, ${result.failures} failed`}`);
+ console.log(`[embed] images: ${result.ocr_required} ${dryRun ? 'would be refused until OCR is enabled' : 'refused for lack of a successful fresh OCR pass'} (ocr_required; GBRAIN_EMBEDDING_IMAGE_OCR=true), `
+ + `${result.sealable} sealable (not candidates: gbrain projections drain seals them keyless), ${result.protected} protected and ${result.archived} archived (not candidates, by design)`);
+ }
if (result.missing_samples.length) serr(`[embed] first missing image file: ${result.missing_samples[0]}`);
if (result.failures > 0) serr(`[embed] first image failure: ${result.failure_samples[0]}`);
if (capped) (args.includes('--json') ? serr : console.log)(embedCostStopVerdict(result, capped));
diff --git a/src/core/embedding-migration.ts b/src/core/embedding-migration.ts
index 3f8d85b4f2..e05ead737b 100644
--- a/src/core/embedding-migration.ts
+++ b/src/core/embedding-migration.ts
@@ -1211,7 +1211,7 @@ export async function applyEmbeddingMigration(
await withMigrationLeaseTransaction(engine, opts.assertOwned,
tx => assertRetainedEmbeddingRebuildability(tx, plan.to_dims, plan.to_model, plan), { deadlockRetries: 3 });
const readiness = await prepareEmbeddingProjections(engine, { repair: true, assertOwned: opts.assertOwned });
- if (readiness.blocked) return { status: 'failed', reason: `projection_blocked: ${readiness.blocked} page(s) remain; no embedding invalidation performed. Canonical projection recovery may have made durable progress. Inspect blockers before retrying: archived sources require deliberate gbrain sources restore <id>; unsupported media requires its source importer. See docs/guides/embedding-migration.md#recovery.` };
+ if (readiness.blocked) return { status: 'failed', reason: `projection_blocked: ${readiness.blocked} page(s) remain; no embedding invalidation performed. Canonical projection recovery may have made durable progress. Inspect blockers before retrying: archived sources require deliberate gbrain sources restore <id>; image pages are counted by class in gbrain doctor --only text_projection_readiness --json (gbrain projections drain seals the sealable ones). See docs/guides/embedding-migration.md#recovery.` };
await opts.assertOwned?.();
// 1. State marker FIRST — a crash after any later step is resumable.
// Same-target re-apply PRESERVES the original started_at (set-if-
diff --git a/src/core/embedding-readiness.ts b/src/core/embedding-readiness.ts
index e3d9d8ba8c..cd218a416e 100644
--- a/src/core/embedding-readiness.ts
+++ b/src/core/embedding-readiness.ts
@@ -74,8 +74,8 @@ export async function reportBlockedProjections(engine: BrainEngine, opts: Projec
samples.push(`${blocked} page(s) still need a text projection, so their chunks were not embedded (${named.map(page => `${page.source_id}:${page.slug}`).join(', ')}${more}); every other stale chunk was embedded. `
+ (pages.some(page => page.page_kind !== 'markdown' && page.page_kind !== 'code')
? isMultimodalEnabled()
- ? `Image and media pages are rebuilt only by their importer; this run's image sweep (images: missing_samples) could not rebuild these: restore their source files, then run gbrain embed --stale${sourceArg} again. `
- : `Image and media pages are rebuilt only by their importer: set GBRAIN_EMBEDDING_MULTIMODAL=true so gbrain embed --stale${sourceArg} sweeps them (or run gbrain embed --stale --images${sourceArg}), or run gbrain sync --full${sourceArg}. ` : '')
+ ? `Image pages are sealed only by gbrain projections drain (importer-attested images, keyless; preview with gbrain projections drain --dry-run) or by their importer; this run's image sweep (images: missing_samples) could not rebuild the rest: restore their source files, then run gbrain embed --stale${sourceArg} again; gbrain doctor --only text_projection_readiness --json counts each class. `
+ : `Image pages are sealed only by gbrain projections drain (importer-attested images, keyless; preview with gbrain projections drain --dry-run) or by their importer: set GBRAIN_EMBEDDING_MULTIMODAL=true so gbrain embed --stale${sourceArg} sweeps the rest (preview with gbrain embed --stale --images --dry-run${sourceArg}); gbrain doctor --only text_projection_readiness --json counts each class. ` : '')
+ 'Rerun gbrain embed --stale to retry bounded projection recovery.');
return new Set(pages.map(page => `${page.source_id}::${page.slug}`));
}
@@ -91,13 +91,15 @@ export async function prepareEmbeddingProjections(engine: BrainEngine, opts: { s
};
let rebuilt = 0;
let blocked = await countBlocked();
- // #6223: a keyset cursor visits each candidate once, so a batch of pages
- // only their importer can rebuild (image/media) never hides repairable pages
- // behind it, and a catch-up run cannot retry the same batch forever.
+ // #6223: a keyset cursor visits each candidate once, so a catch-up run
+ // cannot retry the same batch forever. #6803: it walks only the kinds a
+ // rebuild can build; image pages stay counted as blocked (their seal is the
+ // importer's or `gbrain projections drain`'s), never queued or re-stamped.
let afterPageId = 0;
while (opts.repair && blocked > 0 && !opts.signal?.aborted && Date.now() < (opts.deadline ?? Infinity)) {
const rows = await engine.executeRaw<{ id: number; slug: string; source_id: string }>(`SELECT p.slug,p.source_id,p.id FROM pages p
JOIN sources s ON s.id=p.source_id WHERE ${where} AND NOT s.archived AND p.id>$${params.length + 1}
+ AND (p.page_kind IN ('markdown','code') OR p.body_storage='segmented')
ORDER BY p.id LIMIT $${params.length + 2}`, [...params, afterPageId, limit]);
if (!rows.length) break;
afterPageId = Number(rows[rows.length - 1]!.id);
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 6a8d637fd7..2c0b001636 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -214,9 +214,9 @@ export const CODES = {
effect_not_failed: { class: 'caller', summary: "Only a failed, non-running embedding effect can be explicitly retried." },
embed_backfill_stalled: { class: 'unavailable', actor: 'agent',
summary: "A source's automatic embed-backfill failed the same way several times with nothing embedded, so automatic backfill for it backs off and then stops.",
- why: 'The only remaining work sits on pages whose text projection cannot be rebuilt (a rebuild_failed projection, or an image page only its importer rebuilds). Each identical run spent a worker slot and dead-lettered; after three, automatic submission stops until the blocked pages or the stale chunks change, or a run embeds something (#6803). Explicit gbrain embed --stale and gbrain jobs submit embed-backfill are not gated.',
+ why: 'The only remaining work sits on pages whose text projection cannot be rebuilt (a rebuild_failed projection, or an image page: gbrain projections drain seals the importer-attested ones, the rest need their importer). Each identical run spent a worker slot and dead-lettered; after three, automatic submission stops until the blocked pages or the stale chunks change, or a run embeds something (#6803). Explicit gbrain embed --stale and gbrain jobs submit embed-backfill are not gated.',
docs: 'docs/guides/repair.md#embed-backfill-stalled',
- suggestion: 'Run gbrain doctor --only embed_backfill_stalled to see the blocked pages, preview the repair with gbrain projections drain --dry-run, then run gbrain projections drain; it names each page that still fails and its next step.',
+ suggestion: 'Run gbrain doctor --only embed_backfill_stalled to see the blocked pages, preview the repair with gbrain projections drain --dry-run, then run gbrain projections drain; it names each page that still fails and its next step, and gbrain doctor --only text_projection_readiness --json counts the image pages by class.',
fix: { argv: ['gbrain', 'doctor', '--only', 'embed_backfill_stalled', '--json'], consent: [], actor: 'agent', why: 'Names the blocked pages and the preview-first repair; changes nothing.', requires_exclusive: false } },
embedding_auth_failed: { class: 'unavailable', summary: "The embedding provider rejected the credentials." },
embedding_budget_below_worst_case: { class: 'unavailable', summary: "The embedding migration cap is below its worst-case cost; nothing was changed." },
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index a74b5817b6..ed25c9e527 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -26,7 +26,7 @@ import { sanitizeRemoteBody } from './remote-body.ts';
import { installPageEmbeddings, installPageProjection, preparePageProjection, projectionBelowSafeFence, queuePageProjection, readProjectionSnapshot, resealSafeChunks,
sealPageTextProjection, stampEmbeddingInputs, type ProjectionSnapshot } from './page-state/projections.ts';
import { sanitizeText } from './batch-rows.ts';
-import { hasProtectedBody, provenanceDistrusted, safeChunksFilter } from './search/safe-chunks.ts';
+import { hasProtectedBody, OCR_REQUIRED_ERROR, provenanceDistrusted, safeChunksFilter } from './search/safe-chunks.ts';
import { planEmbeddingReuse } from './embed-reuse.ts';
import { reuseStoredChunkVectors } from './import-chunk-reuse.ts';
import { extractCodeRefs, imageOfCandidates } from './link-extraction.ts';
@@ -1942,7 +1942,7 @@ export async function importImageFile(
: await _ocrLimiter(() => maybeOcr(engine, decoded.buf, decoded.mime));
if ((hadProtectedOcr || (existing?.content_hash === hash && await provenanceDistrusted(engine, existing.id))) && !ocr.successful) {
return { slug: imageSlug, status: 'skipped', chunks: 0,
- error: 'This image had protected OCR, so indexing it requires successful fresh OCR. Enable OCR and reimport the image.' };
+ error: OCR_REQUIRED_ERROR };
}
// Protection checks, chunks and stored OCR must agree on canonical text,
// including markers made recognizable by NUL removal.
diff --git a/src/core/search/safe-chunks.ts b/src/core/search/safe-chunks.ts
index dbc8633cb3..2fd3b4c007 100644
--- a/src/core/search/safe-chunks.ts
+++ b/src/core/search/safe-chunks.ts
@@ -93,6 +93,9 @@ export function belowSafeChunkFence(chunkerVersion: number | null | undefined):
* (bodyWriteChunkVersion): the stored text lost its marker, but the source
* behind it (an image's pixels) did not, so only a fresh attestation counts.
*/
+/** #6803: the importer's refusal of a distrusted image without a successful fresh OCR pass; the sweep counts it as `ocr_required`. */
+export const OCR_REQUIRED_ERROR = 'This image had protected OCR, so indexing it requires successful fresh OCR. Enable OCR and reimport the image.';
+
export async function provenanceDistrusted(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number): Promise<boolean> {
const [row] = await engine.executeRaw<{ chunker_version: number | null }>('SELECT chunker_version FROM pages WHERE id = $1', [pageId]);
return (row?.chunker_version ?? 0) < 0;