Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

projections: classify the queue; the explicit drain seals importer-attested images (#6803)

garrytand32a37987ec1
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index 94057b0f8f..6375fa408a 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -97,6 +97,7 @@ src/core/output/writer.ts 6 engine_guard Canonical table SQL trigger requires co
src/core/page-state/materialize.ts 1 coordinator Publication is transaction-scoped under admitted authority, source/page guards and revision checks.
src/core/page-state/projection-schema.ts 1 schema Schema installation and forward-reference DDL; coordinated activation quiesces canonical writers.
src/core/page-state/projections.ts 3 projection Derived indexing, retrieval telemetry, or source settings; canonical fields remain guarded by SQL triggers.
+src/core/page-state/image-seal.ts 1 projection The explicit image seal (#6803) sets only text_projection_revision on an importer-attested image page, under its page guard with a revision compare-and-set; no canonical field or body is written.
src/core/page-state/schema.ts 3 schema Schema installation and forward-reference DDL; coordinated activation quiesces canonical writers. The pages DO block constrains an empty pages table only; populated tables are finalized by revision-backfill-schema.ts.
src/core/page-state/revision-backfill-schema.ts 2 schema Migration-pass backfill of pages.knowledge_revision for rows written before the column (#5216): only NULL revisions are assigned, in committed id batches; canonical content is never written, and the revision trigger treats a NULL old revision without reading bodies.
src/core/page-state/tags.ts 5 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication. The frontmatter-claim and explicit-add inserts are two branches of one guarded statement. #5984: addPageTags is the same two-branch statement for many tags of a page the import wrote in its guarded transaction.
diff --git a/scripts/e2e-weights.json b/scripts/e2e-weights.json
index 557e6df7ad..1bb6fce6cf 100644
--- a/scripts/e2e-weights.json
+++ b/scripts/e2e-weights.json
@@ -408,6 +408,7 @@
"test/e2e/preview-approval-postgres.test.ts": 2780,
"test/e2e/private-visibility-plan-postgres.test.ts": 2630,
"test/e2e/projection-drain-postgres.test.ts": 30590,
+ "test/e2e/projection-image-drain-postgres.test.ts": 9000,
"test/e2e/projection-embedding-input-hash.test.ts": 2800,
"test/e2e/projection-readiness-currency.test.ts": 2930,
"test/e2e/projection-recovery-parity.test.ts": 36060,
diff --git a/scripts/ubicloud/weights.json b/scripts/ubicloud/weights.json
index 55d73ee069..f9d7b7b666 100644
--- a/scripts/ubicloud/weights.json
+++ b/scripts/ubicloud/weights.json
@@ -323,6 +323,7 @@
"e2e:test/e2e/postgres-reconnect-singleton.test.ts": 522,
"e2e:test/e2e/preview-approval-postgres.test.ts": 1312,
"e2e:test/e2e/projection-drain-postgres.test.ts": 22004,
+ "e2e:test/e2e/projection-image-drain-postgres.test.ts": 9000,
"e2e:test/e2e/projection-embedding-input-hash.test.ts": 2815,
"e2e:test/e2e/projection-readiness-currency.test.ts": 1577,
"e2e:test/e2e/projection-recovery-parity.test.ts": 30639,
diff --git a/src/cli/commands/projections.ts b/src/cli/commands/projections.ts
index 06f3ebf1f2..d6657721fb 100644
--- a/src/cli/commands/projections.ts
+++ b/src/cli/commands/projections.ts
@@ -46,7 +46,14 @@ export async function run(args: string[], ctx: CliDispatchContext): Promise<void
const config = persistenceConfigForBrain(loadConfig(), brainId, brainId === 'host' ? [] : loadMounts());
if (config?.engine === 'pglite' && config.database_path && !config.database_url) {
const holder = inspectLockHolder(config.database_path);
- if (holder.held) { await refuse(projections.projectionOwnerResidentError(holder, config.database_path, brainId)); return; }
+ if (holder.held) {
+ // #6803: the preview counts come from the resident's own projection_status (null: an older resident, or none listening).
+ const { persistenceSocketPathForConfig, requestPersistenceProjectionStatus } = await import('../../core/persistence/ipc.ts');
+ const socketPath = persistenceSocketPathForConfig(config);
+ const status = socketPath ? await requestPersistenceProjectionStatus(socketPath).catch(() => null) : null;
+ await refuse(projections.projectionOwnerResidentError(holder, config.database_path, brainId, status));
+ return;
+ }
}
const { createProgress } = await import('../../core/progress.ts');
@@ -56,30 +63,21 @@ export async function run(args: string[], ctx: CliDispatchContext): Promise<void
// #6803: the preview reads the queue and rebuilds nothing.
try {
const preview = await projections.previewProjectionDrain(engine, limit ?? 50);
- if (json) { await writeStdoutFinal(JSON.stringify(preview) + '\n'); return; }
- const lines = preview.rows.map(row => ` ${row.reason === 'rebuild_failed' ? 'last failed' : 'queued'}: ${row.source_id}/${row.slug} (${row.reason}, since ${row.updated_at})`);
- await writeStdoutFinal([`projections drain --dry-run: ${preview.pending} queued, ${preview.failed} last failed; nothing was rebuilt.`, ...lines,
- preview.pending ? 'Run `gbrain projections drain` to rebuild them; a page that fails again is printed with its next step.' : 'The projection backlog is empty.'].join('\n') + '\n');
+ await writeStdoutFinal((json ? JSON.stringify(preview) : projections.formatDrainPreview(preview)) + '\n');
} finally {
await finishCliTeardown({ engine });
}
return;
}
try {
- const result = await projections.drainProjections(engine, { limit, progress: createProgress(cliOptsToProgressOptions(getCliOptions())) });
+ const result = await projections.drainProjections(engine, { limit, media: true, progress: createProgress(cliOptsToProgressOptions(getCliOptions())) });
if (json) {
- const { limited: _limited, ...payload } = result;
- await writeStdoutFinal(JSON.stringify(payload) + '\n');
+ await writeStdoutFinal(JSON.stringify(result) + '\n');
} else {
for (const failure of result.failed) {
console.error(`failed: ${failure.source_id}/${failure.slug}: ${failure.reason}\n next: ${projections.projectionFailureNextAction(failure)}`);
}
- const summary = `projections drain: ${result.rebuilt} rebuilt, ${result.superseded} superseded, ${result.failed.length} failed, ${result.remaining} remaining.`;
- const tail = result.remaining === 0 ? ' The projection backlog is empty.'
- : result.limited ? ` Stopped at --limit ${limit}; run \`gbrain projections drain\` again to continue.`
- : result.failed.length ? ' Failed pages stay queued; fix them as shown above, then run `gbrain projections drain` again.'
- : ' Rows queued during this run are left for the next run or the resident owner.';
- await writeStdoutFinal(summary + tail + '\n');
+ await writeStdoutFinal(projections.formatDrainResult(result, limit) + '\n');
}
if (result.failed.length) setCliExitVerdict(1);
} finally {
diff --git a/src/commands/projections.ts b/src/commands/projections.ts
index 5ea3977318..43c0aaa20c 100644
--- a/src/commands/projections.ts
+++ b/src/commands/projections.ts
@@ -1,20 +1,22 @@
/**
* `gbrain projections drain` (#5401): rebuilds queued Markdown and code text
* projections in-process, in batches of up to 100, until every row queued
- * before the run started has been tried once. Trusted local CLI only; it is not
- * an operation, so MCP and remediation cannot run it.
+ * before the run started has been tried once, then (#6803) restores the
+ * importer's own seal on `sealable` image pages (page-state/image-seal.ts),
+ * keyless and without re-embedding. Trusted local CLI only; it is not an
+ * operation, so MCP and remediation cannot run it.
*
- * Postgres: safe beside a resident owner, because each page is rebuilt under
- * its page lock with a revision recheck. PGLite: a resident owner holds the
- * datastore, so the command refuses before opening the engine and the
- * resident drains the backlog itself.
+ * Postgres: safe beside a resident owner, because each page is rebuilt or
+ * sealed under its page lock with a revision recheck. PGLite: a resident owner
+ * holds the datastore and drains text only, so the command does not run and
+ * prints the exclusive stop, drain and start steps instead.
*/
-import type { BrainEngine } from '../core/engine.ts';
+import type { Action } from '../core/agent-output.ts';
import type { OperationError } from '../core/ops/contract.ts';
import { catalogueError } from '../core/error-catalogue.ts';
import type { LockHolderInfo } from '../core/pglite-lock.ts';
-import type { ProgressReporter } from '../core/progress.ts';
-import { type ProjectionRebuildFailure } from '../core/page-state/projections.ts';
+import type { ProjectionBacklog, ProjectionDrainResult, ProjectionRebuildFailure } from '../core/page-state/projections.ts';
+import { IMAGE_SEAL_PAGES_PER_SECOND, TEXT_REBUILD_PAGES_PER_SECOND, projectionDrainLimit } from '../core/page-state/image-seal.ts';
// #6286: the drain lives in core so `migrate` can run it on its target before the config flip.
export { drainProjections, previewProjectionDrain, type ProjectionDrainResult } from '../core/page-state/projections.ts';
import { SERVE_LAUNCHD_LABEL, SERVE_SYSTEMD_UNIT } from '../core/serve-service.ts';
@@ -26,17 +28,25 @@ export const PROJECTION_DRAIN_DOCS = 'docs/guides/repair.md#projection-drain';
export const PROJECTIONS_HELP = `Usage: gbrain projections drain [--dry-run] [--limit <n>] [--json]
Rebuild queued Markdown and code text projections now, in batches of up to 100,
-until every row queued before the run started has been tried once.
+until every row queued before the run started has been tried once, then seal
+the image pages the importer already attested safe (sealable). Keyless: no
+provider call, no file read, no re-embedding. Image pages it cannot seal
+(reimport) need their importer: preview with gbrain embed --stale --images --dry-run.
+Protected-OCR images and archived-source pages stay unsealed by design.
- --dry-run Rebuild nothing: list the queued rows a drain would try, rows
- that last failed (rebuild_failed) first, up to --limit (default 50)
- --limit <n> Try at most n pages in this run (default: no cap)
- --json Print {rebuilt, superseded, failed, remaining} to stdout
- ({pending, failed, rows} with --dry-run)
+ --dry-run Change nothing: print every class count (queued text, sealable,
+ reimport, protected, archived) and the rows a drain would take,
+ oldest first, up to --limit (default 50)
+ --limit <n> Try at most n pages in this run (default: no cap); doctor's fix
+ sizes it to about a minute (${projectionDrainLimit()} images,
+ ${projectionDrainLimit(1)} while text pages wait)
+ --json Print {rebuilt, superseded, failed, remaining, limited, sealed,
+ sealed_with_visual, sealed_text_only, statistics_refreshed,
+ remaining_by_class} to stdout (the class counts and rows with --dry-run)
Exit codes: 0 nothing tried failed; 1 some pages failed; 2 did not run
-(projection_owner_resident: a resident gbrain process holds this PGLite brain
-and drains it itself).
+(projection_owner_resident: a resident gbrain process holds this PGLite brain;
+it drains text only, so stop it, drain and start it again as printed).
On Postgres the drain is safe while \`gbrain serve\` runs. Progress goes to stderr.
Docs: ${PROJECTION_DRAIN_DOCS}
@@ -48,7 +58,7 @@ export function projectionFailureNextAction(failure: ProjectionRebuildFailure):
return `restore frontmatter.file or source_path on ${failure.slug}, then run \`gbrain projections drain\` again`;
}
if (failure.reason.startsWith('This page kind requires its source importer')) {
- return `re-import it from its source: \`gbrain sync --source ${failure.source_id}\``;
+ return `re-import it from its source: preview with \`gbrain embed --stale --images --dry-run --source ${failure.source_id}\` (image pages), or run \`gbrain sync --source ${failure.source_id}\``;
}
if (failure.reason.startsWith('revision_conflict:')) {
return 'the page changed while it was being rebuilt; it stays queued at its new revision and `gbrain projections drain` rebuilds it on its next run';
@@ -56,19 +66,70 @@ export function projectionFailureNextAction(failure: ProjectionRebuildFailure):
return 'run `gbrain doctor`; the page stays queued and `gbrain projections drain` tries it again on its next run';
}
+const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
+
+/** The class counts of a backlog, one phrase. */
+export function projectionClassSummary(backlog: Required<ProjectionBacklog>): string {
+ return `${backlog.pending} queued text, ${backlog.sealable} sealable image(s) (${backlog.sealable_with_visual} with a visual vector), `
+ + `${backlog.reimport} to reimport, ${backlog.protected} protected, ${backlog.archived} archived, ${backlog.failed} last failed`;
+}
+
+/** What remains after a drain or preview, past what the drain itself takes: never "empty" while an image row needs work. */
+function remainderLines(backlog: Required<ProjectionBacklog>): string[] {
+ const lines: string[] = [];
+ if (backlog.reimport) lines.push(`${plural(backlog.reimport, 'image page')} need their importer (fresh OCR and pixels): preview with \`gbrain embed --stale --images --dry-run\`.`);
+ if (backlog.protected || backlog.archived) {
+ lines.push(`${plural(backlog.protected, 'protected-OCR image')} and ${plural(backlog.archived, 'archived-source page')} stay unsealed by design; search leaves them out until the image is reimported clean or the source is restored.`);
+ }
+ return lines;
+}
+
+/** Human output of `--dry-run`. */
+export function formatDrainPreview(preview: Awaited<ReturnType<typeof import('../core/page-state/projections.ts').previewProjectionDrain>>): string {
+ const rows = preview.rows.map(row => ` ${row.reason === 'rebuild_failed' ? 'last failed' : row.page_kind === 'image' ? 'sealable' : 'queued'}: ${row.source_id}/${row.slug} (${row.reason}, since ${row.updated_at})`);
+ const work = preview.pending + preview.sealable;
+ const empty = work + preview.reimport + preview.protected + preview.archived === 0;
+ return [`projections drain --dry-run: ${projectionClassSummary(preview)}; nothing was changed.`, ...rows,
+ ...(work ? [`Run \`gbrain projections drain --limit ${projectionDrainLimit(preview.pending)}\` (repeat until sealable is 0) to rebuild the text rows and seal the sealable images; a page that fails again is printed with its next step.`] : []),
+ ...remainderLines(preview), ...(empty ? ['The projection backlog is empty.'] : [])].join('\n');
+}
+
+/** Human output of a drain; `limit` is the caller's `--limit`, repeated in the continuation. */
+export function formatDrainResult(result: ProjectionDrainResult, limit?: number): string {
+ const after = result.remaining_by_class;
+ const summary = `projections drain: ${result.rebuilt} rebuilt, ${result.superseded} superseded, ${result.failed.length} failed, ${result.remaining} remaining.`;
+ const empty = !after || after.pending + after.sealable + after.reimport + after.protected + after.archived === 0;
+ const tail = result.limited ? ` Stopped at --limit ${limit}; run \`gbrain projections drain --limit ${limit}\` again to continue.`
+ : result.failed.length ? ' Failed pages stay queued; fix them as shown above, then run `gbrain projections drain` again.'
+ : result.remaining === 0 && empty ? ' The projection backlog is empty.'
+ : result.remaining === 0 ? ''
+ : ' Rows queued during this run are left for the next run or the resident owner.';
+ const lines = [summary + tail];
+ if (result.sealed !== undefined) {
+ lines.push(`images: ${result.sealed} sealed (${result.sealed_with_visual} with a visual vector, ${result.sealed_text_only} text-only)`
+ + (result.sealed_text_only ? '; the text-only ones get their visual vector from `gbrain embed --stale --images --dry-run` then the paid run.' : '.')
+ + (result.statistics_refreshed ? ' Projection statistics were refreshed.' : ''));
+ }
+ if (after) {
+ lines.push(`remaining: ${projectionClassSummary(after)}.`);
+ lines.push(...remainderLines(after));
+ }
+ return lines.join('\n');
+}
+
/**
* Stop, drain and restart commands for each way a resident owner can run. The
* restart runs whether or not a page failed, so a drain exit of 1 never leaves
* the owner stopped. `brain` keeps a mounted brain selected in every command.
*/
-export function residentDrainSteps(pid: number | undefined, brain = 'host'): string {
+export function residentDrainSteps(pid: number | undefined, brain = 'host', limit?: number): string {
const uid = '$(id -u)';
// #5195: this brain's own autopilot job, or the shared job an older install still runs it from.
const job = resolveAutopilotJob();
const installed = detectInstalledJob(job).installed;
const launchd = installed?.target === 'macos' ? installed.name : job.launchdLabel;
const systemd = installed?.target === 'linux-systemd' ? installed.name : job.systemdUnit;
- const drain = `gbrain projections drain${brain === 'host' ? '' : ` --brain ${brain}`}`;
+ const drain = `gbrain projections drain${limit === undefined ? '' : ` --limit ${limit}`}${brain === 'host' ? '' : ` --brain ${brain}`}`;
const cycle = (stop: string, start: string) => `${stop} && { ${drain}; ${start}; }`;
return [
`To drain faster, stop the owner, drain, then restart it:`,
@@ -80,13 +141,44 @@ export function residentDrainSteps(pid: number | undefined, brain = 'host'): str
].join('\n');
}
+/**
+ * #6803: the exclusive two-step Action for a PGLite brain a resident holds:
+ * stop the owner (step one, the user's), then the drain (`requires_exclusive`),
+ * then start the owner and verify through the resident-backed doctor read.
+ * `status` is the resident's `projection_status` (null: it gave none).
+ */
+export function residentDrainAction(holder: LockHolderInfo, brain = 'host', status: ProjectionBacklog | null = null): Action {
+ const limit = projectionDrainLimit(status ? status.pending : 1);
+ const brainArgs = brain === 'host' ? [] : ['--brain', brain];
+ const owner = `${holder.subcommand ? `gbrain ${holder.subcommand}` : 'a gbrain process'}${holder.pid ? ` (pid ${holder.pid})` : ''}`;
+ const text = Math.min(status?.pending ?? limit, limit);
+ const seconds = Math.max(1, Math.ceil(text / TEXT_REBUILD_PAGES_PER_SECOND + Math.min(status?.sealable ?? 0, limit - text) / IMAGE_SEAL_PAGES_PER_SECOND));
+ const counts = status ? `${status.sealable ?? 'an unknown number of'} image page(s) the drain can seal and ${status.pending} queued text page(s)`
+ : 'queued pages (the resident did not report its counts)';
+ const argv = ['gbrain', 'projections', 'drain', '--limit', String(limit), ...brainArgs];
+ const drain: Action = {
+ argv, consent: [], actor: 'user', requires_exclusive: true,
+ why: `Seals importer-attested image pages and rebuilds queued text, keyless, at most ${limit} pages per run (repeat until sealable is 0); start the owner again afterwards.`,
+ verify: { argv: ['gbrain', 'doctor', ...brainArgs, '--only', 'text_projection_readiness', '--json'] },
+ };
+ return {
+ ...(holder.pid ? { argv: ['kill', String(holder.pid)] } : {}), consent: [], actor: 'user', requires_exclusive: false,
+ why: `${owner} holds this PGLite brain and drains text only; sealing images needs the database to itself. Stop it, run the next step, then start it again (the commands are in the error hint).`,
+ user_message: `This brain has ${counts}. The running gbrain owner, ${owner}, drains text only, so sealing needs it stopped for about ${seconds} second(s) per drain run; harnesses connected through that serve disconnect until it restarts. Please stop it, run \`${argv.join(' ')}\`, then start it again.`,
+ then: drain,
+ };
+}
+
/** DX-O5 refusal: the drain did not run because a resident process holds this PGLite brain. */
-export function projectionOwnerResidentError(holder: LockHolderInfo, dataDir: string, brain = 'host'): OperationError {
+export function projectionOwnerResidentError(holder: LockHolderInfo, dataDir: string, brain = 'host', status: ProjectionBacklog | null = null): OperationError {
const owner = `${holder.subcommand ? `gbrain ${holder.subcommand}` : 'a gbrain process'}${holder.pid ? ` (pid ${holder.pid})` : ''}`;
- return catalogueError('projection_owner_resident',
+ const error = catalogueError('projection_owner_resident',
`The PGLite brain at ${dataDir} is held by ${owner}, so the drain did not run.`,
[
- `The upgraded resident drains queued projections itself (up to 100 pages per pass, fewer while writes wait); watch the pending count with \`gbrain doctor${brain === 'host' ? '' : ` --brain ${brain}`}\` (text_projection_readiness).`,
+ `The upgraded resident drains queued text projections itself (up to 100 pages per pass, fewer while writes wait); it never seals image pages, so watch the pending count with \`gbrain doctor${brain === 'host' ? '' : ` --brain ${brain}`}\` (text_projection_readiness).`,
residentDrainSteps(holder.pid, brain),
].join('\n'));
+ error.fix = residentDrainAction(holder, brain, status);
+ return error;
}
+
diff --git a/src/core/page-state/image-seal.ts b/src/core/page-state/image-seal.ts
new file mode 100644
index 0000000000..34b7d3af09
--- /dev/null
+++ b/src/core/page-state/image-seal.ts
@@ -0,0 +1,138 @@
+/**
+ * #6803 part 2: `gbrain projections drain` restores the importer's own seal on
+ * `sealable` image pages (page-state/projection-class.ts). Migration v153 only
+ * removed their seal marker: each chunk was written by the importer at or after
+ * the safe-chunk fence with safeChunks true, and the page's revision has not
+ * moved since. Explicit only: the resident never seals images.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { quoteIdentifier } from '../search/embedding-column.ts';
+import { chunkGenerationFilter, chunkGenerationProbe, movableChunkSql } from '../search/safe-chunks.ts';
+import { sealableImageSql } from './projection-class.ts';
+import { jsonRowBatches } from '../batch-rows.ts';
+import { acceptedEmbeddingInputHashes } from '../embedding-input-hash.ts';
+import { embeddingInputContext, embeddingWriteTarget } from './projections.ts';
+import { AGENT_TOOL_LIMIT_MS } from '../agent-output.ts';
+
+/**
+ * Measured `sealImageProjections` throughput, the basis of doctor's drain
+ * `--limit` and the post-upgrade estimate. Measured 2026-10-16 on a 4-vCPU
+ * cloud machine, a full `drainProjections({ media: true })` of 10,000 queued
+ * sealable images (statistics refresh included): 2,047 pages/s on PGLite,
+ * 1,809 pages/s on local Postgres 16; this is the slower, rounded down.
+ */
+export const IMAGE_SEAL_PAGES_PER_SECOND = 1500;
+
+/**
+ * Measured Markdown rebuild throughput of the same drain (no embedding): 2,000
+ * queued notes of about 3 KB, 117 pages/s on PGLite and 87 pages/s on local
+ * Postgres 16, same machine and day; the slower, rounded down.
+ */
+export const TEXT_REBUILD_PAGES_PER_SECOND = 80;
+
+/**
+ * Pages one drain run takes in doctor's fix: half the agent tool limit at the
+ * measured rate, so a run fits the limit with room to spare. The drain takes
+ * queued text first, so while `textPending` rows wait the slower text rate sizes it.
+ */
+export function projectionDrainLimit(textPending = 0): number {
+ const rate = textPending > 0 ? TEXT_REBUILD_PAGES_PER_SECOND : IMAGE_SEAL_PAGES_PER_SECOND;
+ return Math.max(100, Math.floor(rate * AGENT_TOOL_LIMIT_MS / 1000 / 2 / 100) * 100);
+}
+
+/** Whole minutes (at least 1) a drain of `pages` takes at the measured rate. */
+export function projectionDrainMinutes(pages: number): number {
+ return Math.max(1, Math.ceil(pages / IMAGE_SEAL_PAGES_PER_SECOND / 60));
+}
+
+/** Statement group of `sealImageProjections`: pages locked, read and sealed together. */
+export const IMAGE_SEAL_GROUP = 500;
+
+export interface ImageSealResult {
+ sealed: number;
+ /** Sealed pages whose chunk carries a visual vector: image search ranks them again. */
+ sealed_with_visual: number;
+ /** Sealed pages with no visual vector yet (imported with --no-embed): keyword-only until `gbrain embed --stale --images`. */
+ sealed_text_only: number;
+}
+
+type Candidate = { source_id: string; source_incarnation: string; slug: string; revision: string };
+
+/**
+ * Restore the importer's own seal on `sealable` images, set-based: per group
+ * of up to 500 pages, under the page guard, a compare-and-set on the queued
+ * revision with the class re-checked under the guard. No chunk is written and
+ * `embedding_image` and the keyword vector are untouched; a text vector whose recorded embedding input
+ * no longer matches the page (#5553) is nulled for `embed --stale`, as
+ * `installPageProjection` would. The queue trigger deletes the job of every
+ * sealed page. No provider call, no file read. `notAfter` (a database
+ * instant, text) leaves rows queued during the run for the next one.
+ */
+export async function sealImageProjections(engine: BrainEngine, opts: { limit?: number; notAfter?: string } = {}): Promise<ImageSealResult> {
+ const result: ImageSealResult = { sealed: 0, sealed_with_visual: 0, sealed_text_only: 0 };
+ let after: [string, string] = ['00000000-0000-0000-0000-000000000000', ''];
+ let budget = opts.limit ?? Infinity;
+ const target = await embeddingWriteTarget(engine);
+ const col = quoteIdentifier(target.column.name);
+ while (budget > 0) {
+ // A primary-key window of queue rows, each probed by its page's unique key only: without planner statistics
+ // (a fresh PGLite) a deleted_at filter here lets the planner pick pages_dedup_idx and scan the source per row.
+ const params: unknown[] = [after[0], after[1], IMAGE_SEAL_GROUP];
+ const notAfter = opts.notAfter === undefined ? '' : `AND j.updated_at<=$${params.push(opts.notAfter)}::text::timestamptz`;
+ const window = await engine.executeRaw<Candidate & { sealable: boolean }>(`SELECT s.id AS source_id,j.source_incarnation::text AS source_incarnation,
+ j.slug,j.revision::text AS revision,p.sealable IS TRUE AS sealable
+ FROM (SELECT source_incarnation,slug,revision FROM page_projection_jobs j WHERE (j.source_incarnation,j.slug) > ($1::uuid,$2) ${notAfter}
+ ORDER BY j.source_incarnation,j.slug LIMIT $3) j
+ LEFT JOIN LATERAL (SELECT s.id FROM sources s WHERE s.incarnation=j.source_incarnation AND NOT s.archived OFFSET 0) s ON true
+ LEFT JOIN LATERAL (SELECT p.deleted_at IS NULL AND p.knowledge_revision=j.revision AND ${sealableImageSql('p')} AS sealable
+ FROM pages p WHERE p.source_id=s.id AND p.slug=j.slug OFFSET 0) p ON true
+ ORDER BY j.source_incarnation,j.slug`, params);
+ if (!window.length) break;
+ const group = window.filter(row => row.sealable).slice(0, budget);
+ const last = group.length === budget ? group[group.length - 1]! : window[window.length - 1]!;
+ after = [last.source_incarnation, last.slug];
+ if (!group.length) continue;
+ budget -= group.length;
+ const sealed = await engine.transaction(async tx => {
+ await tx.lockPageKeys(group.map(row => ({ sourceId: row.source_id, slug: row.slug })));
+ const pages = await tx.executeRaw<{ id: number; revision: string; title: string; mode: string | null;
+ corpus_generation: string | null }>(`SELECT p.id,p.knowledge_revision::text AS revision,p.title,
+ p.contextual_retrieval_mode AS mode,p.corpus_generation
+ FROM jsonb_to_recordset($1::text::jsonb) AS v(source_id text, slug text, revision uuid)
+ JOIN sources s ON s.id=v.source_id AND NOT s.archived
+ JOIN pages p ON p.source_id=v.source_id AND p.slug=v.slug AND p.deleted_at IS NULL AND p.knowledge_revision=v.revision
+ WHERE ${sealableImageSql('p')}`, [JSON.stringify(group.map(({ source_id, slug, revision }) => ({ source_id, slug, revision })))]);
+ if (!pages.length) return [];
+ const chunks = await tx.executeRaw<{ id: number; page_id: number; chunk_text: string; chunk_source: string;
+ embedding_input_hash: string | null; current: boolean }>(`SELECT id,page_id,chunk_text,chunk_source,embedding_input_hash,
+ ${movableChunkSql(col)} AND model IS NOT DISTINCT FROM $2 AS current
+ FROM content_chunks c WHERE c.page_id=ANY($1::int[]) AND c.${col} IS NOT NULL AND ${chunkGenerationProbe('c')}`, [pages.map(page => Number(page.id)), target.provenanceModel]);
+ const byId = new Map(pages.map(page => [Number(page.id), page]));
+ const stale = chunks.filter(chunk => {
+ const page = byId.get(Number(chunk.page_id))!;
+ if (!chunk.current) return true;
+ if (chunk.embedding_input_hash === null) return page.mode != null;
+ const provenance = embeddingInputContext(target, page.title, page.corpus_generation, [chunk]);
+ return !acceptedEmbeddingInputHashes(provenance, page.mode, chunk).includes(chunk.embedding_input_hash);
+ }).map(chunk => Number(chunk.id));
+ if (stale.length) {
+ await tx.executeRaw(`UPDATE content_chunks SET ${col}=NULL,embedded_at=NULL,embedded_text_hash=NULL,embedding_input_hash=NULL,
+ embedding_pending_since=COALESCE(embedding_pending_since,now()) WHERE id=ANY($1::int[])`, [stale]);
+ }
+ const done: Array<{ has_visual: boolean }> = [];
+ // Only the marker: the importer's keyword vector is still the page's own, since its revision has not moved.
+ for (const batch of jsonRowBatches(pages, page => ({ id: Number(page.id), revision: page.revision }))) {
+ done.push(...await tx.executeRaw<{ has_visual: boolean }>(`UPDATE pages SET text_projection_revision=pages.knowledge_revision
+ FROM jsonb_to_recordset($1::text::jsonb) AS v(id int, revision uuid)
+ WHERE pages.id=v.id AND pages.knowledge_revision=v.revision
+ RETURNING EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=pages.id AND c.embedding_image IS NOT NULL
+ AND ${chunkGenerationFilter('pages', 'c')}) AS has_visual`, [batch]));
+ }
+ return done;
+ });
+ result.sealed += sealed.length;
+ result.sealed_with_visual += sealed.filter(row => row.has_visual).length;
+ }
+ result.sealed_text_only = result.sealed - result.sealed_with_visual;
+ return result;
+}
diff --git a/src/core/page-state/projection-class.ts b/src/core/page-state/projection-class.ts
new file mode 100644
index 0000000000..38114bec39
--- /dev/null
+++ b/src/core/page-state/projection-class.ts
@@ -0,0 +1,51 @@
+/**
+ * #6803 part 2: the classes of the projection queue. One SQL fragment shared
+ * by `projectionBacklog`, `previewProjectionDrain`, the drain, doctor, search's
+ * readiness probe and the `--images` sweep, so the classes partition the queue
+ * by construction:
+ *
+ * - `text`: Markdown, code and segmented pages; the resident drains them.
+ * - `archived`: the source is archived; restoring it makes the row drainable.
+ * - `protected`: an image whose OCR holds a protected marker; never sealed, by design.
+ * - `sealable`: an image the importer attested safe (at or after the safe-chunk
+ * fence, one `image_asset` chunk at index 0 that still holds the page's text)
+ * whose only change since was v153 removing the seal marker
+ * (`gbrain projections drain` restores it: page-state/image-seal.ts).
+ * - `reimport`: every other live image; only the importer (fresh OCR, fresh
+ * pixels) can seal it: `gbrain embed --stale --images`.
+ */
+import { SAFE_FENCE_CHUNKER_VERSION, chunkGenerationFilter, protectedBodyFilter, safeChunksFilter } from '../search/safe-chunks.ts';
+import { boundedBodyPrefixSql } from '../page-window/bounded-lead.ts';
+import { BOUNDED_PREFIX_BYTES } from '../page-window/document.ts';
+
+export type ProjectionClass = 'text' | 'archived' | 'protected' | 'sealable' | 'reimport';
+
+/**
+ * The image chunk the importer writes, unchanged: exactly one row, at index 0,
+ * holding the page's OCR text or filename. The text is compared through the
+ * bounded body prefix; a chunk shorter than the bound that equals it equals
+ * the whole body (a longer OCR text is left to the importer: \`reimport\`).
+ */
+function importerChunkSql(p: string): string {
+ return `(SELECT count(*) = 1 AND bool_and(c.chunk_index = 0 AND c.chunk_source = 'image_asset' AND c.modality = 'image'
+ AND char_length(c.chunk_text) < ${BOUNDED_PREFIX_BYTES} AND c.chunk_text = COALESCE(NULLIF(${boundedBodyPrefixSql(p)}, ''), ${p}.title))
+ FROM content_chunks c WHERE c.page_id = ${p}.id AND ${chunkGenerationFilter(p, 'c')})`;
+}
+
+/** A live, unprotected inline image page the importer sealed at or after the safe-chunk fence. Internal aliases only. */
+export function sealableImageSql(p: string): string {
+ return `(${p}.page_kind = 'image' AND ${p}.body_storage IS DISTINCT FROM 'segmented' AND NOT ${protectedBodyFilter(p)}
+ AND ${safeChunksFilter(p)} AND ${importerChunkSql(p)} IS TRUE)`;
+}
+
+/**
+ * The class of a page's unsealed projection: `p` a live page, `s` its source
+ * (internal aliases with every column).
+ */
+export function projectionClassSql(p: string, s: string): string {
+ return `(CASE WHEN ${s}.archived THEN 'archived'
+ WHEN ${p}.page_kind IS DISTINCT FROM 'image' OR ${p}.body_storage = 'segmented' THEN 'text'
+ WHEN ${protectedBodyFilter(p)} THEN 'protected'
+ WHEN ${p}.chunker_version >= ${SAFE_FENCE_CHUNKER_VERSION} AND ${importerChunkSql(p)} IS TRUE THEN 'sealable'
+ ELSE 'reimport' END)`;
+}
diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.ts
index 91a6d2ad6a..dc70aacf5a 100644
--- a/src/core/page-state/projections.ts
+++ b/src/core/page-state/projections.ts
@@ -15,9 +15,13 @@ import { getFtsLanguage, pageSearchVectorSql } from '../fts-language.ts';
import { getEmbeddingModel } from '../ai/gateway.ts';
import { jsonRowBatches } from '../batch-rows.ts';
import { refreshProjectionStatistics } from '../search/projection-statistics.ts';
-import { belowSafeChunkFence, movableChunkSql } from '../search/safe-chunks.ts';
+import { belowSafeChunkFence, chunkGenerationFilter, movableChunkSql } from '../search/safe-chunks.ts';
import { buildSegmentedProjection } from '../page-body/projection.ts';
import { isSegmentedPage } from '../page-body/page-shape.ts';
+import { pageReadFilter } from '../search/read-policy-sql.ts';
+import type { PageReadScope } from '../types.ts';
+import { projectionClassSql, sealableImageSql } from './projection-class.ts';
+import { advanceProjectionCursor, ineligibleKey, rememberIneligible, residentWindowCtes, type ProjectionScanCursor } from './projection-window.ts';
import { acceptedEmbeddingInputHashes, embeddingInputHash, plainEmbeddingTier, synopsisBodyHash,
type EmbeddingInputContext, type EmbeddingTier } from '../embedding-input-hash.ts';
@@ -393,18 +397,32 @@ export async function preparePageProjection(prepared: ProjectionSnapshot) {
const code = await prepareCodeChunks(page, path);
return { chunks: code.chunks, code };
}
- if (prepared.pageKind !== 'markdown') throw new Error('This page kind requires its source importer.');
+ if (prepared.pageKind !== 'markdown') throw new Error('This page kind requires its source importer (images: see `gbrain doctor --only text_projection_readiness --json`).');
return { chunks: await prepareMarkdownChunks(page, prepared.maxChunkTokens, prepared.fenceOverlay), code: undefined };
}
-// The job queue is usually empty or small while pages grows without bound, so
-// these reads walk jobs and probe sources/pages per job. The OFFSET 0 fences
-// keep the planner from turning the probes back into a scan of pages; PGLite
-// has no autovacuum to give it accurate queue statistics.
-const PROJECTION_JOB_PROBES = `CROSS JOIN LATERAL (SELECT s.id FROM sources s
+// These reads walk jobs and probe sources/pages per job; the OFFSET 0 fences
+// keep the planner from turning the probes back into a scan of pages (PGLite
+// has no autovacuum to give it accurate queue statistics); a probe fetches its
+// page by the unique key alone and filters above that fence, since a
+// `deleted_at` filter beside the key lets a statistics-less planner probe
+// through pages_dedup_idx, a scan of the whole source per job. A queue can hold
+// rows no inline rebuild takes (v153 queued 93K image pages on one brain), so
+// only the explicit drain walks it whole, oldest first; the resident reads a
+// bounded window (page-state/projection-window.ts).
+/**
+ * The page probe of a queue walk. `media` also admits `sealable` image rows
+ * (projection-class.ts), for the explicit drain and its preview only: the
+ * resident, embed paths and `gbrain migrate` never pass it.
+ */
+export function projectionJobProbes(opts: { media?: boolean } = {}): string {
+ const inline = "p.page_kind IN ('markdown','code') AND p.body_storage IS DISTINCT FROM 'segmented'";
+ return `CROSS JOIN LATERAL (SELECT s.id FROM sources s
WHERE s.incarnation=j.source_incarnation AND NOT s.archived OFFSET 0) s
- CROSS JOIN LATERAL (SELECT p.page_kind FROM pages p WHERE p.source_id=s.id AND p.slug=j.slug
- AND p.deleted_at IS NULL AND p.page_kind IN ('markdown','code') AND p.body_storage IS DISTINCT FROM 'segmented' OFFSET 0) p`;
+ CROSS JOIN LATERAL (SELECT p.page_kind FROM (SELECT p.id FROM pages p WHERE p.source_id=s.id AND p.slug=j.slug OFFSET 0) k
+ JOIN pages p ON p.id=k.id WHERE p.deleted_at IS NULL AND ${opts.media ? `((${inline}) OR ${sealableImageSql('p')})` : inline}) p`;
+}
+const PROJECTION_JOB_PROBES = projectionJobProbes();
/**
* Rebuilds between statistics refreshes, per engine. Like autovacuum's analyze
@@ -412,6 +430,29 @@ const PROJECTION_JOB_PROBES = `CROSS JOIN LATERAL (SELECT s.id FROM sources s
* process's first drained rebuild always refreshes.
*/
const statisticsDebt = new WeakMap<BrainEngine, { rebuilt: number; rows: number | null }>();
+const statisticsRefreshes = new WeakMap<BrainEngine, number>();
+
+/** #6803: how many times this process refreshed the projection statistics of `engine` (the drain reports a change). */
+export function projectionStatisticsRefreshes(engine: BrainEngine): number {
+ return statisticsRefreshes.get(engine) ?? 0;
+}
+
+/**
+ * Count `rebuilt` pages (rebuilt or sealed) toward the statistics debt; once
+ * it is due and `drained()` finds no drainable row left, refresh.
+ */
+export async function noteProjectionRebuilds(engine: BrainEngine, rebuilt: number, drained: () => Promise<boolean>): Promise<void> {
+ if (rebuilt <= 0) return;
+ const debt = statisticsDebt.get(engine);
+ const owed = { rebuilt: (debt?.rebuilt ?? 0) + rebuilt, rows: debt?.rows ?? null };
+ statisticsDebt.set(engine, owed);
+ if (owed.rows !== null && owed.rebuilt < 50 + owed.rows * 0.1) return;
+ if (!await drained()) return;
+ await refreshProjectionStatistics(engine);
+ const [pages] = await engine.executeRaw<{ rows: number }>("SELECT GREATEST(reltuples,0)::float8 AS rows FROM pg_class WHERE oid='pages'::regclass");
+ statisticsDebt.set(engine, { rebuilt: 0, rows: Number(pages?.rows ?? 0) });
+ statisticsRefreshes.set(engine, projectionStatisticsRefreshes(engine) + 1);
+}
/**
* #5401: a failed rebuild waits this long before the resident retries it. One
@@ -449,31 +490,122 @@ export interface ProjectionRebuildOptions {
* `superseded` no-op.
*/
onHeal?: (heal: { kind: 'removed' | 'deferred'; source_id: string; slug: string }) => void;
+ /**
+ * #6803: the resident's bounded selection (projection-window.ts) from this
+ * cursor instead of a walk of the whole queue. Only `retryCooldown` applies with it.
+ */
+ window?: ProjectionScanCursor;
+ /** #6803: a media drain seals images next, so the statistics refresh also waits for its `sealable` rows. */
+ media?: boolean;
+}
+
+type QueuedJob = { source_id: string; source_incarnation: string; slug: string; revision: string; page_kind: string };
+type WindowKey = { source_incarnation: string; slug: string };
+
+/**
+ * #6803: the resident's selection: at most RESIDENT_PROBE_BUDGET queue rows
+ * (the recency lane, then the window in key order), each probed by primary
+ * key; rows of a kind the resident never builds go to the negative cache.
+ */
+async function selectWindowJobs(engine: BrainEngine, cursor: ProjectionScanCursor, retryCooldown: boolean):
+ Promise<{ jobs: Array<QueuedJob & { ord: number }>; window: WindowKey[]; highWater: string | null }> {
+ const params: unknown[] = [];
+ const ctes = residentWindowCtes(cursor, params, retryCooldown ? PROJECTION_RETRY_READY_SQL : 'TRUE');
+ const rows = await engine.executeRaw<WindowKey & { lane: string | null; ord: number; revision: string; high_water: string | null }>(`WITH ${ctes}
+ SELECT r.lane,r.ord,r.source_incarnation::text AS source_incarnation,r.slug,r.revision::text AS revision,h.at AS high_water
+ FROM high_water h LEFT JOIN (SELECT source_incarnation,slug,revision,updated_at,lane,ord FROM recent
+ UNION ALL SELECT source_incarnation,slug,revision,updated_at,lane,ord FROM win) r ON true
+ ORDER BY r.lane,r.ord`, params);
+ const window = rows.filter(row => row.lane === 'window').sort((a, b) => Number(a.ord) - Number(b.ord));
+ const seen = new Set<string>();
+ const candidates = [...rows.filter(row => row.lane === 'recent'), ...window].filter(row => {
+ const key = ineligibleKey(row);
+ if (seen.has(key) || cursor.ineligible.has(key)) return false;
+ seen.add(key);
+ return true;
+ });
+ const probed = candidates.length ? await engine.executeRaw<{ i: number; source_id: string | null; archived: boolean | null; page_kind: string | null; body_storage: string | null }>(
+ `SELECT k.i,s.id AS source_id,s.archived,p.page_kind,p.body_storage
+ FROM jsonb_to_recordset($1::text::jsonb) AS k(i int, source_incarnation uuid, slug text)
+ LEFT JOIN LATERAL (SELECT s.id,s.archived FROM sources s WHERE s.incarnation=k.source_incarnation OFFSET 0) s ON true
+ LEFT JOIN LATERAL (SELECT p.page_kind,p.body_storage FROM (SELECT p.id FROM pages p WHERE p.source_id=s.id AND p.slug=k.slug OFFSET 0) q
+ JOIN pages p ON p.id=q.id WHERE p.deleted_at IS NULL) p ON true`,
+ [JSON.stringify(candidates.map((row, i) => ({ i, source_incarnation: row.source_incarnation, slug: row.slug })))]) : [];
+ const jobs: Array<QueuedJob & { ord: number }> = [];
+ for (const probe of probed.sort((a, b) => Number(a.i) - Number(b.i))) {
+ const row = candidates[Number(probe.i)]!;
+ if (probe.page_kind && probe.page_kind !== 'markdown' && probe.page_kind !== 'code') { rememberIneligible(cursor, row); continue; }
+ if (!probe.source_id || probe.archived || !probe.page_kind || probe.body_storage === 'segmented') continue;
+ jobs.push({ source_id: probe.source_id, source_incarnation: row.source_incarnation, slug: row.slug, revision: row.revision,
+ page_kind: probe.page_kind, ord: row.lane === 'window' ? Number(row.ord) : 0 });
+ }
+ return { jobs, window, highWater: rows[0]?.high_water ?? null };
}
-/** Live Markdown and code rows a rebuild can take, and how many of them last failed. */
-export async function projectionBacklog(engine: Pick<BrainEngine, 'executeRaw'>): Promise<{ pending: number; failed: number; oldest_age_seconds: number | null }> {
- const [row] = await engine.executeRaw<{ pending: number; failed: number; oldest: number | null }>(`SELECT COUNT(*)::int AS pending,
- COUNT(*) FILTER (WHERE j.reason='rebuild_failed')::int AS failed,
- EXTRACT(EPOCH FROM now()-MIN(j.updated_at))::float8 AS oldest
- FROM page_projection_jobs j ${PROJECTION_JOB_PROBES}`);
+/**
+ * #6803: the queue by class (projection-class.ts). `pending` keeps its meaning,
+ * the rows the resident drains (Markdown, code, segmented), and `failed` the
+ * ones among them that last failed; the other keys are optional on the wire
+ * (an older resident's `projection_status` omits them). `oldest_age_seconds`
+ * covers every class that needs work (not `protected` or `archived`).
+ */
+export interface ProjectionBacklog {
+ pending: number;
+ failed: number;
+ oldest_age_seconds: number | null;
+ sealable?: number;
+ /** Sealable rows whose chunk carries a visual vector: image search ranks them once sealed. */
+ sealable_with_visual?: number;
+ reimport?: number;
+ /** Reimport rows of distrusted provenance (chunker_version < 0): the importer seals them only after a successful fresh OCR pass. */
+ ocr_required?: number;
+ protected?: number;
+ archived?: number;
+ /** Database time of the count. */
+ as_of?: string;
+}
+
+/** Every class of the queue in one aggregate; `scope` narrows to the pages a caller may read. */
+export async function projectionBacklog(engine: Pick<BrainEngine, 'executeRaw'>, scope: PageReadScope = {}): Promise<Required<ProjectionBacklog>> {
+ const params: unknown[] = [];
+ const read = pageReadFilter('p', scope, params);
+ const [row] = await engine.executeRaw<Record<'pending' | 'failed' | 'sealable' | 'sealable_with_visual' | 'reimport' | 'ocr_required' | 'protected' | 'archived', number>
+ & { oldest: number | null; as_of: string }>(`SELECT COUNT(*) FILTER (WHERE k.cls='text')::int AS pending,
+ COUNT(*) FILTER (WHERE k.cls='text' AND j.reason='rebuild_failed')::int AS failed,
+ COUNT(*) FILTER (WHERE k.cls='sealable')::int AS sealable,
+ COUNT(*) FILTER (WHERE k.cls='sealable' AND EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id AND c.embedding_image IS NOT NULL
+ AND ${chunkGenerationFilter('p', 'c')}))::int AS sealable_with_visual,
+ COUNT(*) FILTER (WHERE k.cls='reimport')::int AS reimport,
+ COUNT(*) FILTER (WHERE k.cls='reimport' AND p.chunker_version < 0)::int AS ocr_required,
+ COUNT(*) FILTER (WHERE k.cls='protected')::int AS protected,
+ COUNT(*) FILTER (WHERE k.cls='archived')::int AS archived,
+ EXTRACT(EPOCH FROM now()-MIN(j.updated_at) FILTER (WHERE k.cls IN ('text','sealable','reimport')))::float8 AS oldest,
+ now()::text AS as_of
+ FROM page_projection_jobs j JOIN sources s ON s.incarnation=j.source_incarnation
+ JOIN pages p ON p.source_id=s.id AND p.slug=j.slug AND p.deleted_at IS NULL
+ CROSS JOIN LATERAL (SELECT ${projectionClassSql('p', 's')} AS cls) k
+ WHERE ${read}`, params);
const oldest = row?.oldest === null || row?.oldest === undefined ? null : Math.max(0, Math.floor(Number(row.oldest)));
- return { pending: Number(row?.pending ?? 0), failed: Number(row?.failed ?? 0), oldest_age_seconds: oldest };
+ const n = (key: 'pending' | 'failed' | 'sealable' | 'sealable_with_visual' | 'reimport' | 'ocr_required' | 'protected' | 'archived') => Number(row?.[key] ?? 0);
+ return { pending: n('pending'), failed: n('failed'), oldest_age_seconds: oldest, sealable: n('sealable'), sealable_with_visual: n('sealable_with_visual'),
+ reimport: n('reimport'), ocr_required: n('ocr_required'), protected: n('protected'), archived: n('archived'), as_of: String(row?.as_of ?? '') };
}
/**
- * #6803: the read-only preview of `gbrain projections drain`: the queued
- * Markdown and code rows a drain would try, in the order it tries them (at most `limit`),
- * with each row's queue reason, so a row that last failed (`rebuild_failed`)
- * is named before anything is rebuilt.
+ * #6803: the read-only preview of `gbrain projections drain`: every class
+ * count (`pending` Markdown/code rows it rebuilds, `sealable` images it seals,
+ * and the `reimport`, `protected` and `archived` rows it leaves), then the rows
+ * it would take, oldest first (at most `limit`), with each row's page kind and
+ * queue reason, so a row that last failed (`rebuild_failed`) is named before
+ * anything is rebuilt.
*/
export async function previewProjectionDrain(engine: Pick<BrainEngine, 'executeRaw'>, limit = 50):
- Promise<{ pending: number; failed: number; rows: Array<{ source_id: string; slug: string; reason: string; updated_at: string }> }> {
+ Promise<Required<ProjectionBacklog> & { rows: Array<{ source_id: string; slug: string; page_kind: string; reason: string; updated_at: string }> }> {
const backlog = await projectionBacklog(engine);
- const rows = await engine.executeRaw<{ source_id: string; slug: string; reason: string; updated_at: string }>(`SELECT s.id AS source_id,j.slug,j.reason,j.updated_at::text AS updated_at
- FROM page_projection_jobs j ${PROJECTION_JOB_PROBES}
+ const rows = await engine.executeRaw<{ source_id: string; slug: string; page_kind: string; reason: string; updated_at: string }>(`SELECT s.id AS source_id,j.slug,p.page_kind,j.reason,j.updated_at::text AS updated_at
+ FROM page_projection_jobs j ${projectionJobProbes({ media: true })}
ORDER BY j.updated_at,j.source_incarnation,j.slug LIMIT $1`, [Math.max(1, limit)]);
- return { pending: backlog.pending, failed: backlog.failed, rows };
+ return { ...backlog, rows };
}
/**
@@ -500,7 +632,8 @@ export async function rebuildPendingPageProjections(engine: BrainEngine, limit =
if (opts.reasons) { params.push(opts.reasons); filters.push(`j.reason=ANY($${params.length}::text[])`); }
if (opts.pages) { params.push(opts.pages.slugs); filters.push(`j.slug=ANY($${params.length}::text[])`); }
const sourceFilter = opts.pages ? `WHERE s.id=$${params.push(opts.pages.sourceId)}` : '';
- const jobs = await engine.executeRaw<{ source_id: string; source_incarnation: string; slug: string; revision: string; page_kind: string }>(`SELECT s.id AS source_id,j.source_incarnation,j.slug,j.revision,p.page_kind
+ const selected = opts.window ? await selectWindowJobs(engine, opts.window, opts.retryCooldown === true) : null;
+ const jobs = selected ? selected.jobs.slice(0, Number(params[0])) : await engine.executeRaw<QueuedJob>(`SELECT s.id AS source_id,j.source_incarnation,j.slug,j.revision,p.page_kind
FROM (SELECT source_incarnation,slug,revision,updated_at FROM page_projection_jobs j
${filters.length ? `WHERE ${filters.join(' AND ')}` : ''}
ORDER BY updated_at,source_incarnation,slug OFFSET 0) j
@@ -508,8 +641,10 @@ export async function rebuildPendingPageProjections(engine: BrainEngine, limit =
ORDER BY j.updated_at,j.source_incarnation,j.slug LIMIT $1`, params);
let rebuilt = 0;
let superseded = 0;
+ let attempted = 0;
for (const [index, job] of jobs.entries()) {
if (opts.deadlineMs !== undefined && index > 0 && now() - startedAt >= opts.deadlineMs) break;
+ attempted = index + 1;
const observed = [job.source_incarnation, job.slug, job.revision];
try {
const prepared = await engine.transaction(async tx => {
@@ -564,20 +699,17 @@ export async function rebuildPendingPageProjections(engine: BrainEngine, limit =
opts.onFailure?.({ source_id: job.source_id, slug: job.slug, reason: `revision_conflict: ${error.message.split('\n')[0].slice(0, 280)}` });
}
}
- if (rebuilt > 0) {
- const debt = statisticsDebt.get(engine);
- const owed = { rebuilt: (debt?.rebuilt ?? 0) + rebuilt, rows: debt?.rows ?? null };
- statisticsDebt.set(engine, owed);
- if (owed.rows !== null && owed.rebuilt < 50 + owed.rows * 0.1) return { rebuilt, superseded };
- const remaining = await engine.executeRaw(`SELECT 1 FROM page_projection_jobs j
- ${PROJECTION_JOB_PROBES}
- WHERE j.reason<>'rebuild_failed' LIMIT 1`);
- if (!remaining.length) {
- await refreshProjectionStatistics(engine);
- const [pages] = await engine.executeRaw<{ rows: number }>("SELECT GREATEST(reltuples,0)::float8 AS rows FROM pg_class WHERE oid='pages'::regclass");
- statisticsDebt.set(engine, { rebuilt: 0, rows: Number(pages?.rows ?? 0) });
- }
+ if (selected && opts.window) {
+ // The window is finished up to its first eligible row this call did not reach.
+ const unreached = selected.jobs.slice(attempted).find(job => job.ord > 0);
+ const last = unreached ? selected.window[unreached.ord - 2] : selected.window.at(-1);
+ advanceProjectionCursor(opts.window, last, selected.highWater);
}
+ // The resident's statistics probe stays inside its window: what it selected and did not rebuild.
+ await noteProjectionRebuilds(engine, rebuilt, async () => selected ? selected.jobs.length <= rebuilt
+ : !(await engine.executeRaw(`SELECT 1 FROM page_projection_jobs j
+ ${projectionJobProbes({ media: opts.media })}
+ WHERE j.reason<>'rebuild_failed' LIMIT 1`)).length);
return { rebuilt, superseded };
}
@@ -588,23 +720,41 @@ export interface ProjectionDrainResult {
rebuilt: number;
superseded: number;
failed: ProjectionRebuildFailure[];
+ /** Markdown/code rows still queued (`pending`). */
remaining: number;
+ /** The run stopped at its `limit` while rows it could take remain. */
limited: boolean;
+ /** #6803, media drains only: `sealable` images sealed. */
+ sealed?: number;
+ sealed_with_visual?: number;
+ sealed_text_only?: number;
+ /** Media drains only: this run refreshed the projection planner statistics (full ANALYZE on PGLite). */
+ statistics_refreshed?: boolean;
+ /** Media drains only: every class of the queue after the run. */
+ remaining_by_class?: Required<ProjectionBacklog>;
}
-export async function drainProjections(engine: BrainEngine, opts: { limit?: number; progress?: ProgressReporter; reasons?: readonly string[] } = {}): Promise<ProjectionDrainResult> {
+/**
+ * `media` (the explicit `gbrain projections drain` only) also seals the
+ * `sealable` images after the Markdown and code rows (image-seal.ts).
+ */
+export async function drainProjections(engine: BrainEngine, opts: { limit?: number; progress?: ProgressReporter; reasons?: readonly string[]; media?: boolean } = {}): Promise<ProjectionDrainResult> {
const [{ runStart }] = await engine.executeRaw<{ runStart: string }>('SELECT now()::text AS "runStart"');
// PGLite's clock can be coarse: wait until it passes the run start, so a page
// that fails in this run is stamped after it and is not tried again.
while (!(await engine.executeRaw<{ passed: boolean }>('SELECT now()>$1::text::timestamptz AS passed', [runStart]))[0]?.passed) {
await new Promise(resolve => setTimeout(resolve, 1));
}
- const total = (await projectionBacklog(engine)).pending;
+ const before = await projectionBacklog(engine);
+ const total = before.pending + (opts.media ? before.sealable : 0);
opts.progress?.start('projections.drain', opts.limit === undefined ? total : Math.min(total, opts.limit));
+ const refreshes = projectionStatisticsRefreshes(engine);
const failed: ProjectionRebuildFailure[] = [];
+ const probes = projectionJobProbes({ media: opts.media });
let rebuilt = 0;
let superseded = 0;
let tried = 0;
+ let seal = { sealed: 0, sealed_with_visual: 0, sealed_text_only: 0 };
try {
// Continue while a batch rebuilt, removed, failed or durably deferred a
// row; stop on a no-op batch. A bare `superseded` row (another worker
@@ -613,7 +763,7 @@ export async function drainProjections(engine: BrainEngine, opts: { limit?: numb
let healed = 0;
let failedNow = 0;
const batch = await rebuildPendingPageProjections(engine, Math.min(DRAIN_BATCH, (opts.limit ?? Infinity) - tried),
- { notAfter: runStart, reasons: opts.reasons, onHeal: () => { healed++; },
+ { notAfter: runStart, reasons: opts.reasons, media: opts.media, onHeal: () => { healed++; },
onFailure: failure => { failed.push(failure); if (!failure.reason.startsWith('revision_conflict:')) failedNow++; } });
rebuilt += batch.rebuilt;
superseded += batch.superseded;
@@ -622,10 +772,21 @@ export async function drainProjections(engine: BrainEngine, opts: { limit?: numb
tried += progressed;
opts.progress?.tick(progressed, `${rebuilt} rebuilt, ${failed.length} failed`);
}
+ if (opts.media && (opts.limit === undefined || tried < opts.limit)) {
+ const { sealImageProjections } = await import('./image-seal.ts');
+ seal = await sealImageProjections(engine, { limit: opts.limit === undefined ? undefined : opts.limit - tried, notAfter: runStart });
+ tried += seal.sealed;
+ opts.progress?.tick(seal.sealed, `${seal.sealed} images sealed`);
+ await noteProjectionRebuilds(engine, seal.sealed, async () => !(await engine.executeRaw(`SELECT 1 FROM page_projection_jobs j ${probes}
+ WHERE j.reason<>'rebuild_failed' LIMIT 1`)).length);
+ }
} finally {
opts.progress?.finish();
}
- const remaining = (await projectionBacklog(engine)).pending;
- return { rebuilt, superseded, failed, remaining, limited: opts.limit !== undefined && tried >= opts.limit && remaining > 0 };
+ const after = await projectionBacklog(engine);
+ const more = opts.limit !== undefined && tried >= opts.limit
+ && (await engine.executeRaw(`SELECT 1 FROM page_projection_jobs j ${probes} LIMIT 1`)).length > 0;
+ const result: ProjectionDrainResult = { rebuilt, superseded, failed, remaining: after.pending, limited: more };
+ return opts.media ? { ...result, ...seal, statistics_refreshed: projectionStatisticsRefreshes(engine) > refreshes, remaining_by_class: after } : result;
}
diff --git a/test/e2e/projection-image-drain-postgres.test.ts b/test/e2e/projection-image-drain-postgres.test.ts
new file mode 100644
index 0000000000..5c3f358359
--- /dev/null
+++ b/test/e2e/projection-image-drain-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../projection-image-drain.test.ts'));
diff --git a/test/projection-image-drain.test.ts b/test/projection-image-drain.test.ts
new file mode 100644
index 0000000000..0f051053f8
--- /dev/null
+++ b/test/projection-image-drain.test.ts
@@ -0,0 +1,294 @@
+/**
+ * #6803 part 2: `gbrain projections drain` makes the projection queue v153 left
+ * drainable and truthful. Every queued row falls in exactly one class
+ * (text, sealable, reimport, protected, archived); the drain rebuilds the text
+ * rows and restores the importer's own seal on `sealable` images in place (no
+ * chunk write, no provider call), so image search ranks them again, while every
+ * other image stays queued and out of search. PGLite here;
+ * test/e2e/projection-image-drain-postgres.test.ts runs the file on Postgres.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importImageFile, _resetOcrRunBudgetForTests } from '../src/core/import-file.ts';
+import { PAGE_PROJECTION_ACTIVATION_SQL } from '../src/core/page-state/projection-schema.ts';
+import { drainProjections, previewProjectionDrain, projectionBacklog } from '../src/core/page-state/projections.ts';
+import { formatDrainResult, residentDrainAction } from '../src/commands/projections.ts';
+import { embedStaleImages } from '../src/core/embed-stale-images.ts';
+import { runEmbed } from '../src/commands/embed.ts';
+import { prepareEmbeddingProjections } from '../src/core/embedding-readiness.ts';
+import { checkProjectionReadiness, residentProjectionReadiness } from '../src/commands/doctor/checks/projection-readiness.ts';
+import { IMAGE_SEAL_PAGES_PER_SECOND, projectionDrainLimit } from '../src/core/page-state/image-seal.ts';
+import { projectionUpgradeNotice } from '../src/core/page-state/projection-upgrade-notice.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { configureGateway, resetGateway, __setGenerateTextTransportForTests } from '../src/core/ai/gateway.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64');
+const PROTECTED_OCR = '<!--- gbrain:takes:begin -->\nSYNTHETIC_PRIVATE_IMAGE_CANARY\n<!--- gbrain:takes:end -->';
+const VISUAL = Array.from({ length: 1024 }, (_, i) => (i === 0 ? 1 : 0));
+const backends = testBackends();
+const origFetch = globalThis.fetch;
+const closers: Array<() => Promise<void>> = [];
+const roots: string[] = [];
+let ocrText = '';
+
+beforeAll(() => {
+ globalThis.fetch = (async () => new Response(
+ JSON.stringify({ data: [{ embedding: VISUAL, index: 0 }], model: 'voyage-multimodal-3', usage: { total_tokens: 10 } }),
+ { status: 200, headers: { 'Content-Type': 'application/json' } })) as unknown as typeof fetch;
+ configureGateway({
+ expansion_model: 'anthropic:claude-sonnet-5-5', embedding_model: 'voyage:voyage-multimodal-3',
+ embedding_multimodal_model: 'voyage:voyage-multimodal-3', embedding_dimensions: 1024,
+ env: { ANTHROPIC_API_KEY: 'synthetic-test-key', VOYAGE_API_KEY: 'synthetic-test-key' },
+ });
+ __setGenerateTextTransportForTests((async () => ({ text: ocrText, usage: { inputTokens: 10, outputTokens: 10 } })) as never);
+});
+
+afterAll(async () => {
+ for (const close of closers) await close();
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
+ globalThis.fetch = origFetch;
+ __setGenerateTextTransportForTests(null);
+ resetGateway();
+ _resetOcrRunBudgetForTests();
+});
+
+async function freshEngine(backend: string): Promise<BrainEngine> {
+ if (backend === 'postgres') {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ closers.push(pg.close);
+ return pg.engine;
+ }
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ closers.push(() => engine.disconnect());
+ return engine;
+}
+
+async function importImage(engine: BrainEngine, root: string, slug: string, opts: { sourceId?: string; noEmbed?: boolean; ocr?: string } = {}) {
+ mkdirSync(join(root, slug, '..'), { recursive: true });
+ writeFileSync(join(root, slug), PNG);
+ ocrText = opts.ocr ?? '';
+ _resetOcrRunBudgetForTests();
+ await withEnv({ GBRAIN_EMBEDDING_MULTIMODAL: 'true', GBRAIN_EMBEDDING_IMAGE_OCR: opts.ocr ? 'true' : 'false' }, async () => {
+ expect((await importImageFile(engine, join(root, slug), slug, { sourceId: opts.sourceId, noEmbed: opts.noEmbed })).status).toBe('imported');
+ });
+}
+
+/**
+ * One image per class plus Markdown, then the v153 activation: sealable with
+ * and without a visual vector, pre-fence, distrusted (protected OCR edited
+ * clean), multi-chunk, protected, an archived-source image and Markdown.
+ */
+async function classFixture(engine: BrainEngine) {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-image-drain-'));
+ roots.push(root);
+ await engine.executeRaw('UPDATE sources SET local_path = $1 WHERE id = $2', [root, 'default']);
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path) VALUES('img-archive','img-archive',$1)", [root]);
+ await importImage(engine, root, 'images/sealable-visual.png');
+ await importImage(engine, root, 'images/sealable-text-only.png', { noEmbed: true });
+ await importImage(engine, root, 'images/pre-fence.png');
+ await engine.executeRaw("UPDATE pages SET chunker_version = 3 WHERE slug = 'images/pre-fence.png'");
+ await importImage(engine, root, 'images/distrusted.png', { ocr: PROTECTED_OCR });
+ const page = (await engine.getPage('images/distrusted.png'))!;
+ await engine.putPage('images/distrusted.png', { ...page, page_kind: 'image', compiled_truth: 'Public caption.' });
+ await importImage(engine, root, 'images/multi-chunk.png');
+ const [multi] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE slug = 'images/multi-chunk.png'");
+ await engine.executeRaw(`INSERT INTO content_chunks(page_id,chunk_index,chunk_text,chunk_source,modality) VALUES($1,1,'second','image_asset','image')`, [multi!.id]);
+ await importImage(engine, root, 'images/protected.png', { ocr: PROTECTED_OCR });
+ await importImage(engine, root, 'images/archived.png', { sourceId: 'img-archive' });
+ await engine.executeRaw("UPDATE sources SET archived = true WHERE id = 'img-archive'");
+ for (const slug of ['notes/alpha', 'notes/beta']) await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `Example note ${slug}.` });
+ await activate(engine);
+}
+
+/** Migration v153's activation, one statement at a time. */
+async function activate(engine: BrainEngine) {
+ for (const statement of PAGE_PROJECTION_ACTIVATION_SQL.split(';').map(part => part.trim()).filter(Boolean)) await engine.executeRaw(statement);
+}
+
+async function remoteImageHits(engine: BrainEngine): Promise<string[]> {
+ await engine.setConfig('search.image_query.daily_budget_usd_per_client', '5');
+ const results = await operationsByName.search_by_image.handler(
+ { engine, remote: true, auth: { token: 't', clientId: 'remote-client', scopes: ['read'] } } as never,
+ { image_data: PNG.toString('base64') },
+ ) as Array<{ slug: string }>;
+ return results.map(r => r.slug);
+}
+
+const visual = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ v: string | null }>(
+ 'SELECT c.embedding_image::text AS v FROM content_chunks c JOIN pages p ON p.id = c.page_id WHERE p.slug = $1', [slug]))[0]?.v ?? null;
+const queued = async (engine: BrainEngine) => (await engine.executeRaw<{ slug: string }>('SELECT slug FROM page_projection_jobs ORDER BY slug')).map(r => r.slug);
+
+for (const backend of backends) {
+ describe(`projection image drain (${backend})`, () => {
+ test('classes partition the queue; the drain seals only importer-attested images and image search ranks them again', async () => {
+ const engine = await freshEngine(backend);
+ await classFixture(engine);
+ const total = (await queued(engine)).length;
+ const backlog = await projectionBacklog(engine);
+ expect(backlog).toMatchObject({ pending: 2, sealable: 2, sealable_with_visual: 1, reimport: 3, ocr_required: 1, protected: 1, archived: 1 });
+ expect(backlog.pending + backlog.sealable! + backlog.reimport! + backlog.protected! + backlog.archived!).toBe(total);
+ const before = await visual(engine, 'images/sealable-visual.png');
+ expect(before).not.toBeNull();
+ expect(await remoteImageHits(engine)).not.toContain('images/sealable-visual.png');
+
+ const preview = await previewProjectionDrain(engine);
+ expect(preview.rows.filter(row => row.page_kind === 'image').map(row => row.slug).sort()).toEqual(['images/sealable-text-only.png', 'images/sealable-visual.png']);
+ const drained = await drainProjections(engine, { media: true });
+ expect(drained).toMatchObject({ rebuilt: preview.pending, sealed: preview.sealable, sealed_with_visual: preview.sealable_with_visual, sealed_text_only: 1, failed: [] });
+ expect(drained.remaining_by_class).toMatchObject({ pending: 0, sealable: 0, reimport: 3, protected: 1, archived: 1 });
+
+ expect(await visual(engine, 'images/sealable-visual.png')).toBe(before);
+ const hits = await remoteImageHits(engine);
+ expect(hits).toContain('images/sealable-visual.png');
+ for (const slug of ['images/pre-fence.png', 'images/distrusted.png', 'images/multi-chunk.png', 'images/protected.png']) expect(hits).not.toContain(slug);
+ expect(await queued(engine)).toEqual(['images/archived.png', 'images/distrusted.png', 'images/multi-chunk.png', 'images/pre-fence.png', 'images/protected.png']);
+ const human = formatDrainResult(drained);
+ expect(human).not.toContain('backlog is empty');
+ expect(human).toContain('3 image pages need their importer');
+ }, 180_000);
+
+ test('101 unsealable rows ahead of a sealable one do not stop the drain; a limited batch says so', async () => {
+ const engine = await freshEngine(backend);
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-image-drain-'));
+ roots.push(root);
+ await engine.executeRaw('UPDATE sources SET local_path = $1 WHERE id = $2', [root, 'default']);
+ await engine.executeRaw(`INSERT INTO pages(source_id,slug,type,page_kind,title,compiled_truth,timeline,chunker_version)
+ SELECT 'default','images/a-legacy-'||lpad(i::text,3,'0')||'.png','image','image','legacy','','',0 FROM generate_series(1,101) i`);
+ await importImage(engine, root, 'images/z-attested-1.png');
+ await importImage(engine, root, 'images/z-attested-2.png');
+ await activate(engine);
+ await engine.executeRaw(`UPDATE page_projection_jobs SET updated_at = now() - interval '1 hour' WHERE slug LIKE 'images/a-legacy-%'`);
+ expect(await projectionBacklog(engine)).toMatchObject({ reimport: 101, sealable: 2 });
+ const limited = await drainProjections(engine, { media: true, limit: 1 });
+ expect(limited).toMatchObject({ sealed: 1, limited: true, remaining_by_class: expect.objectContaining({ sealable: 1, reimport: 101 }) });
+ expect(formatDrainResult(limited, 1)).toContain('run `gbrain projections drain --limit 1` again to continue');
+ expect(await drainProjections(engine, { media: true })).toMatchObject({ sealed: 1, limited: false });
+ }, 180_000);
+
+ test('doctor counts each class, asks before sealing, routes reimport to the paid sweep and leaves by-design rows to judgement', async () => {
+ const engine = await freshEngine(backend);
+ await classFixture(engine);
+ const queuedCheck = await checkProjectionReadiness(engine);
+ expect(queuedCheck).toMatchObject({ status: 'warn', details: { pending: 2, sealable: 2, sealable_with_visual: 1, reimport: 3, ocr_required: 1, protected: 1, archived: 1 } });
+ expect(queuedCheck.fix).toMatchObject({ argv: ['gbrain', 'projections', 'drain', '--limit', String(projectionDrainLimit(2))],
+ preview_argv: ['gbrain', 'projections', 'drain', '--dry-run', '--json'], actor: 'agent', ask_user: true, consent: [] });
+ expect(queuedCheck.fix!.user_message).toContain('2 image page(s) are out of search');
+ expect((await checkProjectionReadiness(engine, {}, { remote: true })).fix).toMatchObject({ actor: 'host_admin' });
+ // The drain takes text first, so queued text sizes the run at the slower text rate; images alone get the seal rate.
+ expect(projectionDrainLimit(2)).toBeLessThan(projectionDrainLimit());
+
+ await drainProjections(engine, { media: true });
+ const reimport = await withEnv({ GBRAIN_EMBEDDING_MULTIMODAL: 'true' }, () => checkProjectionReadiness(engine));
+ expect(reimport.status).toBe('warn');
+ expect(reimport.fix).toMatchObject({ argv: ['gbrain', 'embed', '--stale', '--images', '--max-usd', '<USD>'], consent: ['paid', 'egress'], ask_user: true,
+ preview_argv: ['gbrain', 'embed', '--stale', '--images', '--dry-run', '--json'] });
+ expect(reimport.message).toContain('GBRAIN_EMBEDDING_IMAGE_OCR=true');
+ const blocked = await withEnv({ GBRAIN_EMBEDDING_MULTIMODAL: 'false' }, () => checkProjectionReadiness(engine));
+ expect(blocked.fix).toBeUndefined();
+ expect(blocked).toMatchObject({ fix_unavailable_reason: 'operator_judgement', details: { reimport_blocked_by: 'GBRAIN_EMBEDDING_MULTIMODAL' } });
+
+ await engine.executeRaw("UPDATE pages SET deleted_at = now() WHERE slug IN ('images/pre-fence.png','images/distrusted.png','images/multi-chunk.png')");
+ const byDesign = await checkProjectionReadiness(engine);
+ expect(byDesign).toMatchObject({ status: 'ok', severity: 'info', fix_unavailable_reason: 'operator_judgement', details: { protected: 1, archived: 1 } });
+ expect(byDesign.message).toContain('stay unsealed by design');
+ }, 180_000);
+
+ test('post-upgrade names the drain preview with a measured estimate while image pages wait, and writes nothing', async () => {
+ const engine = await freshEngine(backend);
+ expect(await projectionUpgradeNotice(engine)).toBeNull();
+ await classFixture(engine);
+ const jobs = await queued(engine);
+ const notice = (await projectionUpgradeNotice(engine))!.join('\n');
+ expect(notice).toContain('[AGENT]');
+ expect(notice).toContain(`2 image page(s) the importer already attested can be sealed keyless by gbrain projections drain (about 1 minute(s) at ${IMAGE_SEAL_PAGES_PER_SECOND} pages/s, the rate measured`);
+ expect(notice).toContain('3 image page(s) need their importer');
+ expect(notice).toContain('next: run: gbrain projections drain --dry-run');
+ expect(await queued(engine)).toEqual(jobs);
+ await engine.executeRaw("UPDATE pages SET deleted_at = now() WHERE slug IN ('images/pre-fence.png','images/distrusted.png','images/multi-chunk.png')");
+ await drainProjections(engine, { media: true });
+ expect(await projectionUpgradeNotice(engine)).toBeNull();
+ }, 180_000);
+
+ test('embedding recovery never queues or re-stamps image rows, and a rebuild_failed image keeps its reason', async () => {
+ const engine = await freshEngine(backend);
+ await classFixture(engine);
+ await engine.executeRaw("UPDATE page_projection_jobs SET reason = 'rebuild_failed' WHERE slug = 'images/pre-fence.png'");
+ const images = async () => engine.executeRaw<{ slug: string; reason: string; revision: string; updated_at: string }>(`SELECT slug,reason,revision::text AS revision,
+ updated_at::text AS updated_at FROM page_projection_jobs WHERE slug LIKE 'images/%' ORDER BY slug`);
+ const before = await images();
+ expect(before.find(row => row.slug === 'images/pre-fence.png')?.reason).toBe('rebuild_failed');
+ const recovered = await prepareEmbeddingProjections(engine, { repair: true });
+ expect(recovered.rebuilt).toBe(2);
+ expect(await images()).toEqual(before);
+ expect(await projectionBacklog(engine)).toMatchObject({ pending: 0, sealable: 2, reimport: 3 });
+ }, 180_000);
+
+ test('embed --stale --images counts every class: sealable is never a candidate and an ocr_required refusal is its own count', async () => {
+ const engine = await freshEngine(backend);
+ await classFixture(engine);
+ const lines: string[] = [];
+ const origLog = console.log;
+ console.log = (...args: unknown[]) => { lines.push(args.map(String).join(' ')); };
+ try {
+ await withEnv({ GBRAIN_EMBEDDING_MULTIMODAL: 'true', GBRAIN_EMBEDDING_IMAGE_OCR: 'false' }, async () => {
+ await runEmbed(engine, ['--stale', '--images', '--dry-run']);
+ await runEmbed(engine, ['--stale', '--images', '--dry-run', '--json']);
+ });
+ } finally { console.log = origLog; }
+ expect(JSON.parse(lines.at(-1)!)).toMatchObject({ candidates: 3, reimport: 3, incomplete_sealed: 0, ocr_required: 1, sealable: 2, protected: 1, archived: 1 });
+ expect(lines[0]).toContain('3 incomplete (3 to reimport, 0 sealed but incomplete)');
+ expect(lines[1]).toContain('1 would be refused until OCR is enabled (ocr_required; GBRAIN_EMBEDDING_IMAGE_OCR=true), 2 sealable (not candidates');
+ expect(lines[1]).toContain('1 protected and 1 archived (not candidates, by design)');
+
+ ocrText = '';
+ _resetOcrRunBudgetForTests();
+ const swept = await withEnv({ GBRAIN_EMBEDDING_MULTIMODAL: 'true', GBRAIN_EMBEDDING_IMAGE_OCR: 'false' },
+ async () => embedStaleImages(engine, { dryRun: false }));
+ expect(swept).toMatchObject({ candidates: 3, rebuilt: 2, ocr_required: 1, skipped: 0, failures: 0 });
+ expect(await projectionBacklog(engine)).toMatchObject({ sealable: 2, reimport: 1, ocr_required: 1 });
+ }, 180_000);
+
+ if (backend === 'pglite') {
+ test('a resident that predates the class counts is named, with the restart step', () => {
+ const old = residentProjectionReadiness(4242, { pending: 2, failed: 0, oldest_age_seconds: 5 }, 'STOP-DRAIN-RESTART');
+ expect(old).toMatchObject({ status: 'warn', fix_unavailable_reason: 'operator_judgement', details: { readiness: 'unknown', owner_pid: 4242 } });
+ expect(old.message).toContain('predates this upgrade');
+ expect(old.message).toContain('STOP-DRAIN-RESTART');
+ });
+
+ test('a resident holding sealable images gets the exclusive two-step action: stop, drain, restart, verify through doctor', () => {
+ const status = { pending: 4, failed: 0, oldest_age_seconds: 5, sealable: 3000, sealable_with_visual: 2000, reimport: 7, ocr_required: 1, protected: 1, archived: 0, as_of: 'now' };
+ const holder = { held: true, pid: 4242, subcommand: 'serve' } as Parameters<typeof residentDrainAction>[0];
+ const check = residentProjectionReadiness(4242, status, 'STOP-DRAIN-RESTART', residentDrainAction(holder, 'host', status));
+ expect(check.status).toBe('warn');
+ expect(check.fix).toMatchObject({ argv: ['kill', '4242'], actor: 'user', requires_exclusive: false,
+ then: { argv: ['gbrain', 'projections', 'drain', '--limit', String(projectionDrainLimit(4))], actor: 'user', requires_exclusive: true,
+ verify: { argv: ['gbrain', 'doctor', '--only', 'text_projection_readiness', '--json'] } } });
+ expect(check.fix!.user_message).toContain('3000 image page(s) the drain can seal and 4 queued text page(s)');
+ expect(check.fix!.user_message).toContain('stopped for about 3 second(s) per drain run; harnesses connected through that serve disconnect');
+ });
+
+ test('projection statistics reflect the sealed share after the drain', async () => {
+ const engine = await freshEngine(backend);
+ await classFixture(engine);
+ const drained = await drainProjections(engine, { media: true });
+ expect(drained.statistics_refreshed).toBe(true);
+ const [stats] = await engine.executeRaw<{ vals: string | null; freqs: number[] | null }>(`SELECT most_common_vals::text AS vals, most_common_freqs AS freqs
+ FROM pg_stats_ext_exprs WHERE statistics_name = 'pages_text_projection_current_stats'`);
+ const [share] = await engine.executeRaw<{ sealed: number }>(`SELECT avg(CASE WHEN text_projection_revision = knowledge_revision THEN 1.0 ELSE 0 END)::float8 AS sealed FROM pages`);
+ const vals = String(stats?.vals ?? '').replace(/[{}]/g, '').split(',');
+ const sealedFreq = Number(stats?.freqs?.[vals.indexOf('t')] ?? 0);
+ expect(sealedFreq).toBeCloseTo(Number(share!.sealed), 2);
+ }, 180_000);
+ }
+ });
+}
diff --git a/test/projections-drain-cli.serial.test.ts b/test/projections-drain-cli.serial.test.ts
index 1b2763a201..12e176b1ff 100644
--- a/test/projections-drain-cli.serial.test.ts
+++ b/test/projections-drain-cli.serial.test.ts
@@ -70,7 +70,10 @@ describe('gbrain projections drain', () => {
expect(human.stdout).toContain('projections drain: 2 rebuilt, 0 superseded, 0 failed, 0 remaining. The projection backlog is empty.');
const again = await runCli(['projections', 'drain', '--json'], { home: healthyHome });
expect(again.exitCode).toBe(0);
- expect(JSON.parse(again.stdout)).toEqual({ rebuilt: 0, superseded: 0, failed: [], remaining: 0 });
+ // #6803: the JSON now also carries limited, the image seal counts and every class left.
+ expect(JSON.parse(again.stdout)).toEqual({ rebuilt: 0, superseded: 0, failed: [], remaining: 0, limited: false, sealed: 0, sealed_with_visual: 0,
+ sealed_text_only: 0, statistics_refreshed: false, remaining_by_class: { pending: 0, failed: 0, oldest_age_seconds: null, sealable: 0,
+ sealable_with_visual: 0, reimport: 0, ocr_required: 0, protected: 0, archived: 0, as_of: expect.any(String) } });
}, 120_000);
test('exit 1 reports each failed page with its source, slug, reason and next action', async () => {