Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(embed): pages waiting for a projection no longer starve every other stale chunk (#6223)

time-attack94e1d5229879
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.md
index ced1e3e3e6..e9e3ac5c9c 100644
--- a/docs/architecture/key-files/commands-2-continued.md
+++ b/docs/architecture/key-files/commands-2-continued.md
@@ -11,4 +11,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/dream.ts` — `gbrain dream` CLI; thin alias over `runCycle`. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`, `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range), `--unsafe-bypass-dream-guard` (plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` / `readSingleTranscript({bypassGuard})`; loud stderr warning at synthesize-phase entry; never auto-applied for `--input`). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs the scored triage pass but skips synthesis (NOT zero LLM calls). Exit 1 on status=failed; a `cycle_already_running` skip names the lock holder (pid, host, age) from `report.lock_holder`. Source scope enters the shared 6-tier resolver whenever `--source <id>` is given OR `GBRAIN_SOURCE` is set (a null explicit falls through to tier 2: validated + `assertSourceExists`, so an invalid/unknown env value is a clean exit 1; the `__all__` sentinel is excluded and falls through to the unscoped routing, which already spans every source); an env scope naming the brain's default-like source keeps the full implicit cycle (#4700 semantics), any other keeps the `--source` freshness boundary. `resolveBrainDir` returns `string | null` (order: `--dir` → resolved source's `local_path` → global `sync.repo_path` → null); a checkout-less postgres/Supabase brain runs DB-only phases (incl. `resolve_symbol_edges`) and skips the 6 filesystem phases with `details.reason: 'no_brain_dir'`; `runDream` owns the only hard error (no checkout AND no engine). When `--source` resolves but has no on-disk checkout, returns null (DB-only) rather than borrowing another source's global `sync.repo_path` (would mix scopes). Pinned by `test/dream-postgres.serial.test.ts`. `--drain [--window <seconds>]` for `--phase extract_atoms`: `runDrain()` bypasses the pack-gate and runs the single-hold bounded drain from `src/core/cycle/extract-atoms-drain.ts` under the same `cycleLockIdFor(sourceId)` the routine cycle uses (concurrent autopilot tick defers with `cycle_already_running`), reporting `{extracted, skipped, remaining, stopped}`. `--window` is a hard deadline for starting work (the item in flight finishes). Exits `EXIT_DRAIN_INCOMPLETE` (= `BUDGET_STOP_EXIT_CODE` 11; was 3, which A3 reserves for confirmation_required) unless `stopped: drained` with `remaining: 0` (a null count is exit 11, never a drained success; `--json` adds `resume_command`), printing the rerun command (`gbrain dream --drain --window <s> [--source <id>]`) on stderr; `LockUnavailableError` → `cycle_already_running` skip (also exit 11). Under `--json` (D2) every path is one document: usage errors are `invalid_params` envelopes (exit 2, unknown `--phase` included), a failed or contained cycle under the guard is a `cycle_failed` envelope leading with the CycleReport keys, and `retriage` / `reset-key` refusals are envelopes. The `extract_atoms_backlog` doctor check (`computeExtractAtomsBacklogCheck`) surfaces the silent pack-gated backlog with the exact `--drain` command; pack-gated cycle skips carry a greppable `pack_gated:true` marker. `dream retriage` dispatches on `args[0] === 'retriage'` BEFORE `parseArgs` (its flag set never collides with cycle flags; `dream retriage --help` prints subcommand help engine-free per the same IRON RULE). `--eval-run` opts the process in to `GBRAIN_DECIDE_SLOTS` (`enableDecideEvalOverride`) for eval harnesses; consent, egress and the daily cap still apply.
-- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. Explicit slug/slugs and non-stale all routes require live-source projection snapshots before healing or provider work; unavailable preparation and refused installation are recorded through existing failure results and the CLI nonzero exit verdict. Archived rows are preserved and never knowingly dispatched, while active pages in a mixed run can progress. Dry runs retain their read-only counts, and the global page selectors are unchanged. These routes keep provider calls outside the existing source-before-page guards. Pinned by the explicit archived-admission and actual CLI cases in `test/embedding-recovery.serial.test.ts` (PGLite) and its PostgreSQL wrapper, `test/e2e/embedding-recovery-parity.test.ts`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it reads the live canonical snapshot and re-checks `getChunks`. `installPageProjection` then locks the page, verifies the originating revision and source incarnation, and installs/seals chunks in one transaction. A newer canonical edit prevents installation; the single-page chunkless path uses the same guarded installer. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; a budget stop that leaves stale chunks is never silent: `src/core/embed-budget-stop.ts` records `reason: 'time_budget'`, `remaining_stale` and `resume_command`, `runEmbed` prints the verdict on stdout and the CLI exits 11 (`BUDGET_STOP_EXIT_CODE`); an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, captures a guarded projection snapshot, embeds outside the transaction, and installs through `installPageEmbeddings`. The installer checks revision, source incarnation, chunk identities/text and indexing context, then updates vectors and provenance without replacing chunk text or membership. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). Keep this shared field list for prepared chunk metadata rather than copying a per-path list. The final guarded embedding installer updates vectors and provenance only, preserving the installed modality, code metadata, text and chunk membership. Pinned by `test/embed-modality-preserved.test.ts`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Successful complete page embeddings stamp `pages.embedding_signature` inside the guarded installation transaction so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page through `stampIfPageProvenanceComplete` in `src/core/embed-stale.ts` (shared with the minion `embed-backfill` drain, `embedStaleForSource`): the stamp is judged from DB state — every chunk carries an active-column vector whose `model` and vector width match the signature and whose `embedded_text_hash` matches `md5(chunk_text)` — never from the batch subset, because `listStaleChunks` pages by row with no page alignment, so a page straddling a batch boundary is stamped by whichever batch lands its last chunk (a partially-stale page keeping preserved chunks of another model, or a NULL model/hash, stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent: all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). In `--stale`, a page whose guarded projection snapshot is unavailable when its turn comes (edited, tagged or unsealed after the readiness gate) counts its chunks as failures and is named in one end-of-run batch-summary sample (the first five slugs plus a count of the rest); a page whose source was archived mid-run is left to the archived-work report so it is counted once. Pinned by `test/embed-stale-unavailable-snapshot.serial.test.ts`. Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the single implementation — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-default-concurrency.test.ts` (20 page workers on both paths when the env var is unset) and `test/embed-pool-abort.test.ts` (an abort stops both page pools from claiming further pages). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.test.ts`. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (two `countStaleChunks` calls) followed by one live `probeEmbedder` embed call (from `src/core/embed-stale.ts`; validates a real vector whose dims match the signature's trailing `:<dims>`) must succeed before anything is NULLed, so a misresolved config (temp `GBRAIN_HOME` → default model, no key) can never strip vectors it cannot replace; a failed probe warns loudly on stderr and degrades to NULL-only staleness. Every live stale run also calls `engine.invalidateContentDriftEmbeddings` (not probe-gated — blast radius is bounded by real content edits) so chunks whose `embedded_text_hash` no longer matches `md5(chunk_text)` re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned by `test/embed-stale.test.ts` (probe-gate + content-drift blocks). The `--stale` single-flight lock HEARTBEAT (interval `GBRAIN_EMBED_LOCK_HEARTBEAT_MS`, default 5 min — test seam) is refresh-bounded per tick: each `refresh()` races a per-tick timeout (`GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`, default 30s via `DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`) with its own AbortController, so ONE never-settling refresh call can't silence the heartbeat forever; a slow tick never stacks on the next (`beating` guard), a refresh returning false (stolen/released lock) aborts the drain immediately as `lock_lost`, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort as `lock_lost` rather than running without mutual exclusion. The interval is deliberately NOT unref'd (a lost drain promise stays a LOUD hang instead of a silent exit-0 that leaks the locks) while the per-tick timeout timer IS unref'd. `runEmbedCore --stale` also arms the progress-keyed stall watchdog from `src/core/embed-stall.ts` (`GBRAIN_EMBED_STALL_ABORT_SECONDS`, default 900 — see that entry): on stall it aborts the drain, releases the run's self-acquired locks, flushes the summary, and returns `reason: 'stall_timeout'`. Pinned by `test/embed.serial.test.ts` (heartbeat + stall blocks) + `test/jobs-embed-stall-wiring.serial.test.ts`. Explicit `--stale --facts --source ID` is a read-only NULL-fact preview; `--yes --max-cost-usd N` consents to bounded execution, not automatic/full-brain repair. The selected-brain configuration is forwarded out of band to the resident owner, never reloaded from the host or supplied over the wire; selected and DB off-switches fail closed. #5183: the page-embedding worker count comes from `resolveEmbedConcurrency` in `src/core/embed-concurrency.ts` (GBRAIN_EMBED_CONCURRENCY, a paced cap, and on Postgres never above the client pool; one warning when an explicit setting is lowered). A chunkless page whose projection install loses to another installer (the resident rebuild) re-reads through `retryProjectionConflict` and embeds the sealed chunks it finds; a conflict that outlasts the retries is recorded as a `[page_projection_conflict]` failure sample with the envelope's next step (`test/embedding-recovery.serial.test.ts`). `--all` passes the sliding pool an `onError` handler: an error that escapes `embedOnePage` (its snapshot read runs before the page's own try) counts that page once on `result.failures` with an `Error embedding <slug>` stderr line, unless the run is already aborting when the error arrives (shutdown, not a failure); `test/embed-partial-failure-3037.serial.test.ts`.
+- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. Explicit slug/slugs and non-stale all routes require live-source projection snapshots before healing or provider work; unavailable preparation and refused installation are recorded through existing failure results and the CLI nonzero exit verdict. Archived rows are preserved and never knowingly dispatched, while active pages in a mixed run can progress. Dry runs retain their read-only counts, and the global page selectors are unchanged. These routes keep provider calls outside the existing source-before-page guards. Pinned by the explicit archived-admission and actual CLI cases in `test/embedding-recovery.serial.test.ts` (PGLite) and its PostgreSQL wrapper, `test/e2e/embedding-recovery-parity.test.ts`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it reads the live canonical snapshot and re-checks `getChunks`. `installPageProjection` then locks the page, verifies the originating revision and source incarnation, and installs/seals chunks in one transaction. A newer canonical edit prevents installation; the single-page chunkless path uses the same guarded installer. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; a budget stop that leaves stale chunks is never silent: `src/core/embed-budget-stop.ts` records `reason: 'time_budget'`, `remaining_stale` and `resume_command`, `runEmbed` prints the verdict on stdout and the CLI exits 11 (`BUDGET_STOP_EXIT_CODE`); an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, captures a guarded projection snapshot, embeds outside the transaction, and installs through `installPageEmbeddings`. The installer checks revision, source incarnation, chunk identities/text and indexing context, then updates vectors and provenance without replacing chunk text or membership. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). Keep this shared field list for prepared chunk metadata rather than copying a per-path list. The final guarded embedding installer updates vectors and provenance only, preserving the installed modality, code metadata, text and chunk membership. Pinned by `test/embed-modality-preserved.test.ts`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Successful complete page embeddings stamp `pages.embedding_signature` inside the guarded installation transaction so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page through `stampIfPageProvenanceComplete` in `src/core/embed-stale.ts` (shared with the minion `embed-backfill` drain, `embedStaleForSource`): the stamp is judged from DB state — every chunk carries an active-column vector whose `model` and vector width match the signature and whose `embedded_text_hash` matches `md5(chunk_text)` — never from the batch subset, because `listStaleChunks` pages by row with no page alignment, so a page straddling a batch boundary is stamped by whichever batch lands its last chunk (a partially-stale page keeping preserved chunks of another model, or a NULL model/hash, stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent: all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). In `--stale`, a page whose guarded projection snapshot is unavailable when its turn comes (edited, tagged or unsealed after the readiness gate) counts its chunks as failures and is named in one end-of-run batch-summary sample (the first five slugs plus a count of the rest); a page whose source was archived mid-run is left to the archived-work report so it is counted once. Pinned by `test/embed-stale-unavailable-snapshot.serial.test.ts`. Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the single implementation — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-default-concurrency.test.ts` (20 page workers on both paths when the env var is unset) and `test/embed-pool-abort.test.ts` (an abort stops both page pools from claiming further pages). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.test.ts`. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (two `countStaleChunks` calls) followed by one live `probeEmbedder` embed call (from `src/core/embed-stale.ts`; validates a real vector whose dims match the signature's trailing `:<dims>`) must succeed before anything is NULLed, so a misresolved config (temp `GBRAIN_HOME` → default model, no key) can never strip vectors it cannot replace; a failed probe warns loudly on stderr and degrades to NULL-only staleness. Every live stale run also calls `engine.invalidateContentDriftEmbeddings` (not probe-gated — blast radius is bounded by real content edits) so chunks whose `embedded_text_hash` no longer matches `md5(chunk_text)` re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned by `test/embed-stale.test.ts` (probe-gate + content-drift blocks). The `--stale` single-flight lock HEARTBEAT (interval `GBRAIN_EMBED_LOCK_HEARTBEAT_MS`, default 5 min — test seam) is refresh-bounded per tick: each `refresh()` races a per-tick timeout (`GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`, default 30s via `DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`) with its own AbortController, so ONE never-settling refresh call can't silence the heartbeat forever; a slow tick never stacks on the next (`beating` guard), a refresh returning false (stolen/released lock) aborts the drain immediately as `lock_lost`, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort as `lock_lost` rather than running without mutual exclusion. The interval is deliberately NOT unref'd (a lost drain promise stays a LOUD hang instead of a silent exit-0 that leaks the locks) while the per-tick timeout timer IS unref'd. `runEmbedCore --stale` also arms the progress-keyed stall watchdog from `src/core/embed-stall.ts` (`GBRAIN_EMBED_STALL_ABORT_SECONDS`, default 900 — see that entry): on stall it aborts the drain, releases the run's self-acquired locks, flushes the summary, and returns `reason: 'stall_timeout'`. Pinned by `test/embed.serial.test.ts` (heartbeat + stall blocks) + `test/jobs-embed-stall-wiring.serial.test.ts`. Explicit `--stale --facts --source ID` is a read-only NULL-fact preview; `--yes --max-cost-usd N` consents to bounded execution, not automatic/full-brain repair. The selected-brain configuration is forwarded out of band to the resident owner, never reloaded from the host or supplied over the wire; selected and DB off-switches fail closed. #5183: the page-embedding worker count comes from `resolveEmbedConcurrency` in `src/core/embed-concurrency.ts` (GBRAIN_EMBED_CONCURRENCY, a paced cap, and on Postgres never above the client pool; one warning when an explicit setting is lowered). A chunkless page whose projection install loses to another installer (the resident rebuild) re-reads through `retryProjectionConflict` and embeds the sealed chunks it finds; a conflict that outlasts the retries is recorded as a `[page_projection_conflict]` failure sample with the envelope's next step (`test/embedding-recovery.serial.test.ts`). `--all` passes the sliding pool an `onError` handler: an error that escapes `embedOnePage` (its snapshot read runs before the page's own try) counts that page once on `result.failures` with an `Error embedding <slug>` stderr line, unless the run is already aborting when the error arrives (shutdown, not a failure); `test/embed-partial-failure-3037.serial.test.ts`. #6223: pages still blocked after bounded projection recovery no longer end `--stale` early; healthy chunks embed, the blocked pages' chunks count as failures, and one sample names them (not the mid-run "changed" summary) with `gbrain embed --stale --images` / `gbrain sync --full` for image and media pages.
diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.md
index c96c44c965..589058ce57 100644
--- a/docs/architecture/key-files/providers.md
+++ b/docs/architecture/key-files/providers.md
@@ -3,7 +3,7 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/core/embedding-readiness.ts` — bounded source-aware recovery through canonical projection snapshots, queued intent, preparation and guarded installation. Global readiness remains archive-visible. Plain stale repair selects active sources for recovery and separately reports archived stranded work, so live pages can progress without pretending the whole brain completed. `countArchivedEmbeddingWork` classifies archived NULL vectors, non-NULL hash drift, signature work, contentful chunkless pages and, for migration, pending projections before authorization. Repair queues and snapshots require a live source under the existing source-before-page guard; unsupported pages remain blocked, never revision-stamped. The invalidation SQL additionally excludes unsealed projections.
+- `src/core/embedding-readiness.ts` — bounded source-aware recovery through canonical projection snapshots, queued intent, preparation and guarded installation. Global readiness remains archive-visible. Plain stale repair selects active sources for recovery and separately reports archived stranded work, so live pages can progress without pretending the whole brain completed. `countArchivedEmbeddingWork` classifies archived NULL vectors, non-NULL hash drift, signature work, contentful chunkless pages and, for migration, pending projections before authorization. Repair queues and snapshots require a live source under the existing source-before-page guard; unsupported pages remain blocked, never revision-stamped. The invalidation SQL additionally excludes unsealed projections. #6223: repair walks a keyset cursor (each candidate once per call, ending on a short batch), so a batch of image/media pages only their importer can rebuild never hides repairable pages behind it; `listPendingProjectionPages` lists the first blocked pages for the caller's report. `embed --stale` and `embedStaleForSource` no longer stop when pages stay blocked: the guarded drain skips their unsealed snapshots (the CLI counts their chunks as failures and names them with `gbrain embed --stale --images`; the source drain adds them to `blocked` and stays incomplete).
- `src/core/embedding-migration-retention.ts` — fail-closed retained-vector rebuildability check shared by migration preflight, direct apply, schema transition, pinned-column repair and invalidation/config transactions. Transaction-local SHARE locks freeze source/page/vector/withdrawal/config eligibility during the census and mutation. Sealed importer text chunks can be embedded and oversized chunks healed without regenerating their source projection; unsealed unsupported media still refuses. Width changes protect archived, skipped, deleted and unrebuildable retained page vectors; same-width checks match the shared false-stamp predicate, signature gate and current-space test. Archived pending work, including same-target content drift, metadata-only restamping, NULL vectors and chunkless pages, refuses before authorization or provider work; correct target-stamped archived vectors, including grandfathered NULL hashes, are retained controls. Companion retention checks follow actual schema/pinned-width changes and the same-target persisted migration marker; the guard returns the locked companion-clear decision consumed by the writer, ignoring a different target's completed-clear flag. Schema-only work leaves takes untouched. Existing fact eligibility and deliberate expiry/supersession/audit/withdrawal policy remain unchanged. Unknown registry, width or census fails closed. The source census includes archive state, but embed leases are not archive coordination. Synthetic two-engine regressions cover preservation refusals, real imported-image migration, same-target companion preservation, retarget/first-clear refusal and fail-closed metadata. Completion counts remain archive-visible; refusal never restores a source automatically.
- `src/core/embedding-migration-budget.ts` — finite authorization in the existing migration marker. Each provider attempt reserves its maximum input price under the acquired leases and a `FOR UPDATE` on the marker row, and records a pending entry keyed by attempt id; `settle(usage)` takes the same lock and replaces the reservation with the reported usage (refund or overshoot). Idempotent per (`authorization_generation`, attempt id): a repeated or stale-generation settle is a no-op, so a crash before settlement keeps the maximum. Missing usage keeps the maximum. Usage above the reservation debits actual, adds `overshoot_usd` and sets `halted`, which refuses further dispatch until an explicit `--max-cost-usd` renewal. `authorizeMigrationBudget(..., worstCase)` throws `MigrationBudgetRefusal` (`embedding_budget_below_worst_case`, with cap, worst case, retained debits, the filled `--max-cost-usd` command and the `write-refusals.md` anchor) before writing any state when the cap is below debits + worst case. Refusal copy prints the operator's cap, never a remainder. Resume preserves every debit; unknown prices or missing input bounds refuse. Marker corruption cannot erase a versioned authorization. Only an explicitly reauthorized legacy marker without authorization fields can be replaced.
- `src/core/embedding-migration-worst-case.ts` — `planMigrationWorstCase(engine, plan, { rerankerModel })`: Σ per-request maximum input from `embed-batch-plan.ts` over what the run sends (target probe, the drain's two probes, stale chunks per page (including content drift: a stored text hash that no longer matches) split by `healOversizedChunks` at the target chunk size over the complete page (a split re-indexes siblings, so every healed chunk of that page counts) and wrapped with `wrapChunkTextsForStoredMode`, the chunks projection recovery and the chunkless heal will create — replayed through `readProjectionSnapshot` + `preparePageProjection` at the current chunk size then the target-size heal, and directly at the target size, keeping the larger ceiling, replacing those pages' existing chunks — stale facts in 100-row per-source batches, three smoke-check queries, the reranker probe when switching), priced with operator overrides. `usd` is null only when the embedding model is unpriced; an unpriced reranker lands in `unpriced_models` and the embedding bound is still enforced. Owns the migration and reranker probe texts. Computed at plan time for the printed estimate and again under the migration locks for the refusal.
diff --git a/src/commands/embed.ts b/src/commands/embed.ts
index e59739da32..9fd6458f34 100644
--- a/src/commands/embed.ts
+++ b/src/commands/embed.ts
@@ -1,5 +1,5 @@
import { sanitizeRemoteBody } from '../core/remote-body.ts';
-import { prepareEmbeddingProjections, countArchivedEmbeddingWork } from '../core/embedding-readiness.ts';
+import { prepareEmbeddingProjections, countArchivedEmbeddingWork, listPendingProjectionPages } from '../core/embedding-readiness.ts';
import { embedStaleFacts, type EmbedFactsResult } from '../core/embed-facts.ts';
import { embedTakesForStaleDrain, type EmbedTakesResult } from '../core/embed-takes.ts';
import { parseFactEmbedArgs } from './embed-facts-delegate.ts';
@@ -1646,10 +1646,20 @@ async function embedAllStale(
readiness = await prepareEmbeddingProjections(engine, { ...readinessOptions, repair: true, assertOwned: staleOpts?.assertOwned });
if (isAborted(externalSignal) || Date.now() >= (readinessOptions.deadline ?? Infinity)) return await noteBudgetStop();
}
+ // #6223: pages still waiting for a projection after bounded recovery never
+ // block the rest of the source. The guarded drain below refuses their
+ // unsealed snapshots, counts their stale chunks as failures and installs no
+ // vector for them; everything else embeds in this run.
+ const blockedPages = readiness.blocked && !dryRun ? await listPendingProjectionPages(engine, readinessOptions) : [];
+ const blockedProjections = new Set(blockedPages.map(page => `${page.source_id}::${page.slug}`));
if (readiness.blocked && !dryRun) {
- result.failures += readiness.blocked;
- result.failure_samples.push('Projection recovery remains blocked; rerun embed --stale for bounded recovery or restore unsupported media with its source importer.');
- return;
+ const media = blockedPages.some(page => page.page_kind !== 'markdown' && page.page_kind !== 'code');
+ const named = blockedPages.slice(0, 5);
+ const more = readiness.blocked > named.length ? ` and ${readiness.blocked - named.length} more` : '';
+ const sourceArg = sourceId ? ` --source ${sourceId}` : '';
+ result.failure_samples.push(`${readiness.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. `
+ + (media ? `Image and media pages are rebuilt only by their importer: run gbrain embed --stale --images${sourceArg} (needs GBRAIN_EMBEDDING_MULTIMODAL=true) or gbrain sync --full${sourceArg}. ` : '')
+ + 'Rerun gbrain embed --stale to retry bounded projection recovery.');
}
// Chunkless-page safety net: pre-flight count mirrors the countStaleChunks
@@ -2025,8 +2035,9 @@ async function embedAllStale(
if (!prepared) {
// #5804: a page edited, deleted or unsealed mid-run is a counted failure, not a silent
// skip. An archived source is left to reportArchived, which already counts its pages.
+ // #6223: a page already reported as waiting for its projection is counted, not renamed.
const [source] = await observed(pacer, () => engine.executeRaw<{ archived: boolean }>('SELECT archived FROM sources WHERE id = $1', [keySourceId]));
- if (!source?.archived) { result.failures += stale.length; unavailablePages.set(key, slug); }
+ if (!source?.archived) { result.failures += stale.length; if (!blockedProjections.has(key)) unavailablePages.set(key, slug); }
return;
}
const selected = new Map(stale.map(c => [c.chunk_index, c]));
diff --git a/src/core/embed-stale.ts b/src/core/embed-stale.ts
index 02b2b1ee87..5eb806901a 100644
--- a/src/core/embed-stale.ts
+++ b/src/core/embed-stale.ts
@@ -394,8 +394,10 @@ export async function embedStaleForSource(
readiness = await prepareEmbeddingProjections(engine, { ...readinessOptions, repair: true });
if (stopped()) return { ...result, aborted: true };
}
- if (readiness.blocked) return { ...result, blocked: readiness.blocked, complete: false, done: true,
- remaining: await engine.countStaleChunks({ sourceId, ...(signature && { signature }) }) };
+ // #6223: pages still waiting for a projection never block the rest of the
+ // source; the drain skips their unsealed snapshots and the result stays
+ // incomplete with them counted in `blocked`.
+ const projectionBlocked = readiness.blocked;
const stamp = await resolveProvenanceStamp(engine, signature); // column resolved once per drain, not per page
if (stopped()) return { ...result, aborted: true };
await opts.assertOwned?.();
@@ -484,6 +486,7 @@ export async function embedStaleForSource(
if (batch.length === 0) {
const blocked = await countArchivedEmbeddingWork(engine, { sourceId, signature });
if (blocked) { result.blocked = blocked; result.failures = (result.failures ?? 0) + blocked; }
+ if (projectionBlocked) result.blocked = (result.blocked ?? 0) + projectionBlocked;
const remaining = await engine.countStaleChunks({ sourceId, ...(signature && { signature }) });
if (remaining || result.chunksProcessed || result.blocked) {
result.remaining = remaining;
@@ -631,6 +634,7 @@ export async function embedStaleForSource(
if (batch.length < batchSize) {
const blocked = await countArchivedEmbeddingWork(engine, { sourceId, signature });
if (blocked) { result.blocked = blocked; result.failures = (result.failures ?? 0) + blocked; }
+ if (projectionBlocked) result.blocked = (result.blocked ?? 0) + projectionBlocked;
result.remaining = await engine.countStaleChunks({ sourceId, ...(signature && { signature }) });
result.complete = result.remaining === 0 && !result.blocked;
result.done = true;
diff --git a/src/core/embedding-readiness.ts b/src/core/embedding-readiness.ts
index 9be54c522e..334142fabf 100644
--- a/src/core/embedding-readiness.ts
+++ b/src/core/embedding-readiness.ts
@@ -21,8 +21,10 @@ export async function countArchivedEmbeddingWork(engine: BrainEngine, opts: { so
return row.n;
}
-export async function prepareEmbeddingProjections(engine: BrainEngine, opts: { sourceId?: string; limit?: number; repair?: boolean; existingChunksOnly?: boolean; activeSourcesOnly?: boolean; stale?: { signature?: string; includeNullSignature?: boolean }; signal?: AbortSignal; deadline?: number; assertOwned?: (tx?: BrainEngine) => Promise<void> } = {}) {
- const limit = Math.max(1, Math.min(opts.limit ?? 100, 100));
+type ProjectionScope = { sourceId?: string; existingChunksOnly?: boolean; activeSourcesOnly?: boolean; stale?: { signature?: string; includeNullSignature?: boolean } };
+
+/** The pages still waiting for a text projection under `opts`, as one WHERE clause over `pages p JOIN sources s`. */
+async function pendingProjectionWhere(engine: BrainEngine, opts: ProjectionScope): Promise<{ where: string; params: unknown[] }> {
const params: unknown[] = [opts.sourceId ?? null, opts.existingChunksOnly ?? false];
let eligible = '';
if (opts.stale) {
@@ -38,6 +40,23 @@ export async function prepareEmbeddingProjections(engine: BrainEngine, opts: { s
AND ($1::text IS NULL OR p.source_id=$1)
${opts.activeSourcesOnly ? 'AND NOT s.archived' : ''}
AND (NOT $2::boolean OR EXISTS(SELECT 1 FROM content_chunks c WHERE c.page_id=p.id)) ${eligible}`;
+ return { where, params };
+}
+
+/**
+ * #6223: the first pages (at most `limit`, 1000 by default) of active sources
+ * still waiting for a projection, for the report a caller makes after bounded
+ * recovery left some blocked (image/media pages only their importer rebuilds).
+ */
+export async function listPendingProjectionPages(engine: BrainEngine, opts: ProjectionScope, limit = 1000) {
+ const { where, params } = await pendingProjectionWhere(engine, opts);
+ return engine.executeRaw<{ source_id: string; slug: string; page_kind: string }>(`SELECT p.source_id,p.slug,p.page_kind FROM pages p
+ JOIN sources s ON s.id=p.source_id WHERE ${where} AND NOT s.archived ORDER BY p.id LIMIT $${params.length + 1}`, [...params, limit]);
+}
+
+export async function prepareEmbeddingProjections(engine: BrainEngine, opts: { sourceId?: string; limit?: number; repair?: boolean; existingChunksOnly?: boolean; activeSourcesOnly?: boolean; stale?: { signature?: string; includeNullSignature?: boolean }; signal?: AbortSignal; deadline?: number; assertOwned?: (tx?: BrainEngine) => Promise<void> } = {}) {
+ const limit = Math.max(1, Math.min(opts.limit ?? 100, 100));
+ const { where, params } = await pendingProjectionWhere(engine, opts);
const countBlocked = async () => {
const [remaining] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pages p
JOIN sources s ON s.id=p.source_id WHERE ${where}`, params);
@@ -46,10 +65,16 @@ 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.
+ let afterPageId = 0;
while (opts.repair && blocked > 0 && !opts.signal?.aborted && Date.now() < (opts.deadline ?? Infinity)) {
- const previousBlocked = blocked;
- const rows = await engine.executeRaw<{ slug: string; source_id: string }>(`SELECT p.slug,p.source_id FROM pages p
- JOIN sources s ON s.id=p.source_id WHERE ${where} AND NOT s.archived ORDER BY p.id LIMIT $${params.length + 1}`, [...params, limit]);
+ 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}
+ ORDER BY p.id LIMIT $${params.length + 2}`, [...params, afterPageId, limit]);
+ if (!rows.length) break;
+ afterPageId = Number(rows[rows.length - 1]!.id);
for (const row of rows) {
if (opts.signal?.aborted || Date.now() >= (opts.deadline ?? Infinity)) break;
await opts.assertOwned?.();
@@ -86,7 +111,7 @@ export async function prepareEmbeddingProjections(engine: BrainEngine, opts: { s
}
await opts.assertOwned?.();
blocked = await countBlocked();
- if (blocked >= previousBlocked) break;
+ if (rows.length < limit) break;
}
return { rebuilt, blocked };
}
diff --git a/test/embed-stale-unavailable-snapshot.serial.test.ts b/test/embed-stale-unavailable-snapshot.serial.test.ts
index c507339fa1..09265472fd 100644
--- a/test/embed-stale-unavailable-snapshot.serial.test.ts
+++ b/test/embed-stale-unavailable-snapshot.serial.test.ts
@@ -24,6 +24,8 @@ import { installFixtureChunks } from './helpers/page-projection.ts';
import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
import { runEmbedCore } from '../src/commands/embed.ts';
import type { BrainEngine } from '../src/core/engine.ts';
+import { listPendingProjectionPages, prepareEmbeddingProjections } from '../src/core/embedding-readiness.ts';
+import { embedStaleForSource } from '../src/core/embed-stale.ts';
const DIMS = 1536;
let engine: PGLiteEngine;
@@ -76,6 +78,57 @@ async function nullVectors(slug: string): Promise<number> {
return row.n;
}
+// #6223 (fix wave 12, W1.5): a page only its importer can rebuild (an image
+// page whose projection was unsealed) must not starve every other stale chunk.
+async function blockedImagePage(slug: string) {
+ await stalePage(slug);
+ await engine.executeRaw("UPDATE pages SET page_kind='image', text_projection_revision=NULL WHERE slug=$1", [slug]);
+}
+const chunkRows = (slug: string) => engine.executeRaw(
+ 'SELECT c.chunk_index,c.chunk_text,c.embedding IS NULL AS unembedded FROM content_chunks c JOIN pages p ON p.id=c.page_id WHERE p.slug=$1 ORDER BY c.chunk_index', [slug]);
+
+describe('embed --stale past pages still waiting for a projection (#6223)', () => {
+ test.each([[false], [true]])('a blocked image page does not starve healthy stale chunks (catchUp=%s)', async catchUp => {
+ await blockedImagePage('images/scan-0001');
+ await stalePage('notes/healthy');
+ const before = await chunkRows('images/scan-0001');
+ const result = await runEmbedCore(engine, { stale: true, quiet: true, catchUp, batchSize: 1 });
+ expect(result.embedded).toBe(1);
+ expect(await nullVectors('notes/healthy')).toBe(0);
+ expect(result.failures).toBe(1);
+ const samples = result.failure_samples.join(' ');
+ expect(samples).toContain('default:images/scan-0001');
+ expect(samples).toContain('gbrain embed --stale --images');
+ expect(samples).not.toContain('changed, was deleted or lost its projection during this run');
+ expect(await chunkRows('images/scan-0001')).toEqual(before);
+ });
+
+ test('bounded recovery reaches a repairable page behind a full batch of blocked image pages', async () => {
+ for (const slug of ['images/a', 'images/b']) await blockedImagePage(slug);
+ await stalePage('notes/repairable');
+ await engine.executeRaw("UPDATE pages SET text_projection_revision=NULL WHERE slug='notes/repairable'");
+ const result = await prepareEmbeddingProjections(engine, { repair: true, limit: 2, activeSourcesOnly: true });
+ expect(result).toEqual({ rebuilt: 1, blocked: 2 });
+ expect((await listPendingProjectionPages(engine, { activeSourcesOnly: true })).map(page => [page.slug, page.page_kind]))
+ .toEqual([['images/a', 'image'], ['images/b', 'image']]);
+ const repaired = await engine.readPageSnapshot('notes/repairable');
+ expect(repaired?.page.text_projection_revision).toBe(repaired?.revision);
+ });
+
+ test('the source drain (embed-backfill, remediation) embeds healthy pages and stays incomplete', async () => {
+ await blockedImagePage('images/scan-0002');
+ await stalePage('notes/healthy-source');
+ const texts: string[] = [];
+ const result = await embedStaleForSource(engine, 'default', {
+ embedFn: async values => { texts.push(...values); return values.map(() => new Float32Array(DIMS).fill(0.001)); } });
+ expect(result.embedded).toBe(1);
+ expect(texts.join(' ')).not.toContain('images/scan-0002');
+ expect(result.blocked).toBe(1);
+ expect(result.complete).toBe(false);
+ expect(await nullVectors('notes/healthy-source')).toBe(0);
+ });
+});
+
describe('embed --stale with a projection snapshot that becomes unavailable mid-run (#5804)', () => {
test('edited pages are counted failures with one batch summary; untouched pages still embed', async () => {
await stalePage('notes/tagged-mid-run');
diff --git a/test/embedding-readiness.test.ts b/test/embedding-readiness.test.ts
index 176e479fc6..c3d5c4b6ca 100644
--- a/test/embedding-readiness.test.ts
+++ b/test/embedding-readiness.test.ts
@@ -44,3 +44,23 @@ test('projection recovery stops after a batch makes no progress', async () => {
expect(await prepareEmbeddingProjections(engine, { repair: true })).toEqual({ rebuilt: 0, blocked: 1 });
expect(batches).toBe(1);
});
+
+// #6223 (fix wave 12): recovery walks a keyset cursor, so several full batches
+// of pages no projection can be built for are each visited once and it stops.
+test('projection recovery advances past full unavailable batches and terminates', async () => {
+ const cursors: unknown[] = [];
+ const engine = mockEmbedProjectionEngine({
+ readPageSnapshot: async () => null,
+ executeRaw: async (sql: string, params?: unknown[]) => {
+ if (sql.startsWith('SELECT count(')) return [{ n: 5 }];
+ if (sql.startsWith('SELECT p.slug,p.source_id')) {
+ const after = Number(params![params!.length - 2]);
+ cursors.push(after);
+ return [1, 2, 3, 4, 5].filter(id => id > after).slice(0, 2).map(id => ({ id, slug: `synthetic-unavailable-${id}`, source_id: 'default' }));
+ }
+ return [];
+ },
+ });
+ expect(await prepareEmbeddingProjections(engine, { repair: true, limit: 2 })).toEqual({ rebuilt: 0, blocked: 5 });
+ expect(cursors).toEqual([0, 2, 4]);
+});