Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(embed): batched, resumable content-drift sweep with saved cursor and surfaced status (#7117)
garrytan75a03eff21ad
diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.mdindex 7cca73e141..aec9a3f82e 100644--- a/docs/architecture/key-files/providers.md+++ b/docs/architecture/key-files/providers.md@@ -26,6 +26,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/embedding-state.ts` — #6696 B3 derived embedding state: every chunk, and every live page with no chunk row, in one of `embedded | pending | keyword_only | quarantined | empty | deleted_page_chunks | chunkless_healable` against the ACTIVE embedding column (no stored status). The classifier SQL lives once in `engine-sql/chunks.ts` (`chunkEmbeddingState` reuses `staleChunkWhere`, `chunklessPageState` reuses `chunklessPagesWhere`) behind `BrainEngine.readEmbeddingStateCounts` / `listEmbeddingStateRows`. `readEmbeddingState(engine, { mode, sourceIds })`: `full` is exact; `ops` reads only index-backed counts (the partial index `WHERE <active column> IS NULL`, the frontmatter GIN, the purge index; `embedded` is a planner estimate) and is `status: 'unknown', reason: 'no_covering_index'` without that index, never a scan. `unsearchable` sums pending, quarantined, empty and chunkless_healable (pending drops out on a brain keyless by choice). `embeddingStateFix` builds each state's protocol fix from existing commands. Consumers: doctor `embedding_state`, `gbrain pages unsearchable`, lane B's `get_brain_health`. Tests: `test/embedding-state.test.ts`.- `src/core/embed-stale.ts` — source-wide stale embedding and explicit-page completion keep vector installation, complete-provenance signature checks and title-tier demotion in one page-guarded transaction. The three `src/commands/embed.ts` paths use the same transaction boundary; providers run before it. Standalone/background projection recovery preserves NULL-signature grandfathering and existing stale eligibility; the job's deadline, abort signal and source lease fence recovery, invalidation and publication. Oversized-chunk healing checks ownership and stop conditions before and after its transaction, rolling back prepared changes on loss. The restamp always uses the captured page metadata, so a later same-revision contextual rebuild cannot retain its vectors while an older completion overwrites its mode or corpus generation. `persistence/effects.ts` also retains this atomic completion boundary. `test/embedding-completion-atomic.serial.test.ts` exercises all five completion paths; `test/e2e/migration-wave-healing-fence.test.ts` pins healing rollback on both engines. #5902: without an explicit `concurrency`, `embedStaleForSource` (the unpaced `embed-backfill` job and the remediation embed step) runs `resolveStaleEmbedConcurrency` workers from `src/core/embed-concurrency.ts`: `min(20, max(1, floor(poolMax/2)))` of the engine's real pool (`getPoolDiagnostics().poolMax`, a worker's instance pool included), 20 without a pool; an explicit `GBRAIN_EMBED_CONCURRENCY` keeps the full-pool clamp. Pinned by `test/embed-stale-pool-default.test.ts` + `test/e2e/embed-stale-pool-default-postgres.test.ts`. Wave B: a segmented page is embedded by `page-body/segmented-embedding.ts` (vector-less live rows by chunk_index keyset with the title and plain tier, metered per page, installed by chunk_index and exact text onto rows still in the live generation; never the body or every chunk), from here, `gbrain embed` and the post-commit embedding effect (`data.occurrence_ids` limits an append's effect to the new occurrences).+- `src/core/content-drift-sweep.ts` — the content-drift sweep (#4246) as a resumable pass: `runContentDriftSweep(engine, { sourceId?, signal?, deadline?, stopped?, assertOwned?, timeBudgetMs?, batchRows? })` runs `engine-sql/chunks.ts` `invalidateContentDriftBatch` (5,000 chunk rows past the cursor in id order, bounded before any md5) one transaction per batch, committing the cursor in config row `embed.content_drift_sweep.<column>.<all|source:id>` with the batch under a `FOR UPDATE` lock on that row, so concurrent runs share one pass. A run stops at its 60 s budget, the job deadline or an abort; a completed pass restarts after `embed.content_drift.pass_interval_hours` (default 24) unless it fit in one batch. A failed batch is returned as `state: 'failed'` with the error and recorded as `last_error` (cleared by the next committed batch); a missing v133/v221 column is `unsupported`; an `assertOwned` throw propagates. `embedAllStale` (`EmbedResult.content_drift`), `embedStaleForSource` (`contentDrift`) and the embed, embed-backfill and cycle embed results carry the status; doctor `content_drift_sweep` reads the saved rows.- `src/core/embed-stale-images.ts` — `gbrain embed --stale --images [--source <id>] [--dry-run] [--json]` (requires `GBRAIN_EMBEDDING_MULTIMODAL=true`): selects live image pages whose index `importImageFile`'s hash-skip would call incomplete: an unsealed page only in the `reimport` class (`page-state/projection-class.ts`; `sealable`, `protected` and `archived` are counted, never candidates), a sealed one with no `embedding_image` chunk or no OCR text/`ocr_status: done` while `GBRAIN_EMBEDDING_IMAGE_OCR=true` (`incomplete_sealed`); `ocr_required` counts distrusted reimport pages (the dry run's expectation with OCR off, the importer's refusals after a run), resolves each file from the source's `local_path` (the `default` source falls back to `sync.repo_path`; a subpath-scoped `source_path` resolves against the checkout's git root; a page with no recorded `source_path` is located by its slug, which is the lower-cased repo-relative path, and counted in `missingSourcePath`) and hands it back to the importer, so OCR budget, protected-OCR refusal and the rebuild stay there. #6529: on a managed brain the import goes through `importManagedFile` (the coordinated importer; the legacy writer refuses a managed brain), only for a file inside the source root, and the import records `source_path`. Reports candidates, rebuilt, unchanged, missing source files (`missing_samples`: up to 5 `source:slug: no file at <path tried>` lines, the first printed) and failures; the explicit `--images` CLI (`runEmbedStaleImagesCli`) counts an all-missing, nothing-rebuilt sweep as failures (`sweepFoundNoFiles`), so it never exits 0 as a quiet success. `runStaleImageSweepFirst` is the sweep a plain `gbrain embed --stale` (no `--slugs`) runs before its text drain when multimodal embedding is on, and `foldImageSweep` folds it into the `EmbedResult` as `images`: import failures count toward the run's failures, fileless pages are reported once on stderr (`missingFile`, first sample) and leave the exit code to the text run; a text-only install skips it and keeps the `--images` hint. Pinned by `test/embed-stale-images.test.ts` and `test/embed-stale-images-managed-6529.test.ts` (both engines). Under a cost cap (fix wave 13 P1.18) each import is metered and the sweep stops before the next image once the cap refused; a refused image is not a failure.- `src/core/embed-budget-stop.ts` — the loud time-budget stop for `gbrain embed --stale`. `noteEmbedBudgetStop(engine, result, {sourceId, signature, includeNullSignature, skip})` counts the stale chunks left (same predicate as the catch-up remaining count) and, when any remain, sets `reason: 'time_budget'`, `remaining_stale` and `resume_command` (`gbrain embed --stale --catch-up [--source X] [--include-null-signature]`) on the result; `skip` covers dry runs, `--catch-up` and caller aborts. `embedBudgetStopVerdict(result)` is the stdout verdict `runEmbed` prints; `src/cli/commands/embed.ts` maps the reason to `BUDGET_STOP_EXIT_CODE` (failures still win with 1). Called from every budget exit in `embedAllStale` (readiness-phase deadline returns and the main drain). Pinned by `test/embed.serial.test.ts` ("time-budget stop is loud").diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 6bf83b4e23..4d6486601d 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -685,6 +685,36 @@ the phase, its blocker key and back-off, or the last failed job.3. Confirm with `gbrain doctor --only global_maintenance_stalled`: it is `ok`after a pass completes with the phase passing.+## Content-drift sweep++**Doctor reports `content_drift_sweep` as a warning, or an embed run prints+`content-drift sweep ... FAILED`?** Every `embed --stale` run, embed job and+embed-backfill job runs the content-drift sweep: it re-queues chunks whose text+changed after their vector was computed (`embedded_text_hash` no longer+matches `md5(chunk_text)`). The sweep examines 5,000 chunk rows per statement+in id order and commits its cursor with each batch, in the config row+`embed.content_drift_sweep.<column>.<scope>`, so a pass spans as many runs as+it needs; one run sweeps for at most 60 seconds. After a pass completes, the+next starts once `embed.content_drift.pass_interval_hours` have passed (24 by+default; 0 repeats it every run). A pass that fits in one batch repeats on+every run. The run's result carries `content_drift` (`contentDrift` on+embed-backfill): rows checked and invalidated, the cursor, and `state`+(`complete`, `partial`, `waiting`, `stopped`, `failed`, or `unsupported`+on a schema before migration v133).++A failed batch commits nothing and leaves the cursor before it; the embed run+goes on with the rest of its work and the next run retries the batch. Search+already ignores a vector whose text changed, so a stalled sweep delays+re-embedding, not answers.++1. Read the error: `gbrain doctor --only content_drift_sweep --json` names the+ scope, the chunk id and the message.+2. Fix what it names (a lock held by another session, a statement timeout far+ below one batch, a database error), then run `gbrain embed --stale`. It+ spends embedding tokens, so ask the user first.+3. Confirm with `gbrain doctor --only content_drift_sweep`: it is `ok` once a+ batch commits.+## auto_chronicle has no effect**Say to your agent:** *"Why aren't my meetings showing up as timeline events?"*diff --git a/llms-full.txt b/llms-full.txtindex 8844e977f3..24b24c97ff 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -11059,6 +11059,36 @@ the phase, its blocker key and back-off, or the last failed job.3. Confirm with `gbrain doctor --only global_maintenance_stalled`: it is `ok`after a pass completes with the phase passing.+## Content-drift sweep++**Doctor reports `content_drift_sweep` as a warning, or an embed run prints+`content-drift sweep ... FAILED`?** Every `embed --stale` run, embed job and+embed-backfill job runs the content-drift sweep: it re-queues chunks whose text+changed after their vector was computed (`embedded_text_hash` no longer+matches `md5(chunk_text)`). The sweep examines 5,000 chunk rows per statement+in id order and commits its cursor with each batch, in the config row+`embed.content_drift_sweep.<column>.<scope>`, so a pass spans as many runs as+it needs; one run sweeps for at most 60 seconds. After a pass completes, the+next starts once `embed.content_drift.pass_interval_hours` have passed (24 by+default; 0 repeats it every run). A pass that fits in one batch repeats on+every run. The run's result carries `content_drift` (`contentDrift` on+embed-backfill): rows checked and invalidated, the cursor, and `state`+(`complete`, `partial`, `waiting`, `stopped`, `failed`, or `unsupported`+on a schema before migration v133).++A failed batch commits nothing and leaves the cursor before it; the embed run+goes on with the rest of its work and the next run retries the batch. Search+already ignores a vector whose text changed, so a stalled sweep delays+re-embedding, not answers.++1. Read the error: `gbrain doctor --only content_drift_sweep --json` names the+ scope, the chunk id and the message.+2. Fix what it names (a lock held by another session, a statement timeout far+ below one batch, a database error), then run `gbrain embed --stale`. It+ spends embedding tokens, so ask the user first.+3. Confirm with `gbrain doctor --only content_drift_sweep`: it is `ok` once a+ batch commits.+## auto_chronicle has no effect**Say to your agent:** *"Why aren't my meetings showing up as timeline events?"*diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex 25161b989f..7454770894 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -36,7 +36,6 @@ src/core/cycle/grade-takes.ts GradeTakesPhase.process 402 seed: W5 baseline, refsrc/core/cycle/propose-takes.ts ProposeTakesPhase.process 430 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5958 (issue #5874): call_timeout_ms read and its per-page bound (phaseBoundedCallTimeout); +1 #5425 [UC4]: the one attribution-check call after the extractor returns (logic in propose-takes-attribution.ts)src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 498 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 #5490 review: a narrative a chat_fallback_chain model wrote is hashed under that model so the next cycle re-synthesizes it; +13 fix wave 9 lane P (D-N3): fence-stripped member hash with legacy-hash grandfathering, and the classic write moved to publishClassicConcept (concept-publication.ts); +3 (#5041): opt-in concept write-through hook and the import callback publishClassicConcept runs under the page lock; +6 #4907 (issue #4906): configured budget read, budget-capped counter, summary clause and details.warnings (message text in budgetWarnings); +4 fix wave 11 #6161: concept redirects in grouping and the skipped_deleted pre-check (logic in cycle/concept-redirects.ts); +13 fix wave 12 #6260: a narrative stopped before the end is a counted failure, and the per-member-hash retry bound (state in cycle/concept-retry-bound.ts); +8 #6643 PR B: drifted concepts skipped before spend (state and the live check in persistence/drift-conflicts.ts ConceptDriftSkips), with the warn status, summary clause and skipped_file_drift detailssrc/core/cycle/synthesize.ts runPhaseSynthesizeInner 1048 +1 #5575 I2: output refs take their transcript taint before the provenance stamp (the stamp line stays the signal-guarded literal cycle-abort pins); seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #5854: publish_pending from postprocess, a pending summary publish deferred instead of failing the phase; +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data-src/core/embed-stale.ts embedStaleForSource 303 TODO: large-pages A9/T3: per-page spend cap meters each page in embedOneKey (logic in core/page-embedding-budget.ts meterStaleBatch/spendGrant)src/core/facts/backstop.ts runPipelineBodyInner 358 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/import-file.ts importFromContent 692 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering; lowered to 807 (#5988: screen and sanity config peeled to core/import-screen.ts); +1 #6007: the prepared apply reports its written page and seal (PreparedImportApplied) so put_page skips a re-read and a second seal; +1 #5333: embed-skip transition defeats the unchanged fast paths (the stale-marker clear stays inside the sanity block); +3 #6188: Tier 1 fence step in place before the hidden-row merge (logic in fence-repair/import-step.ts); -146 #5575: content-sanity/write-gate disposition moved to import-screen.ts settleContentDisposition; +4 TODO: large-pages A6/T33: a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors and embeds through the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); +16 Wave B lane 1d (TODO wave-b PR 1): a body above the inline threshold takes the segmented stage and generation flip at the storage step (logic in persistence/segmented-apply.ts); +3 Wave B review: reuseSegments option (a rename re-preparation reuses the staged segmented body) and the remote fence merge over fenceBody; +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting itsrc/core/minions/handlers/subagent-oneshot.ts runSubagentOneshot 378 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 fix wave 9 lane B #4921: the oneshot sub-budget is passed as the call timeoutMs so the 300 s gateway backstop cannot cut itdiff --git a/src/commands/doctor/checks/content-drift-sweep.ts b/src/commands/doctor/checks/content-drift-sweep.tsnew file mode 100644index 0000000000..cc6a700813--- /dev/null+++ b/src/commands/doctor/checks/content-drift-sweep.ts@@ -0,0 +1,54 @@+/**+ * content_drift_sweep doctor check (#7117): the content-drift sweep's saved+ * pass record (core/content-drift-sweep.ts), one config row per embedding+ * column and scope. Warns while the latest batch failed (the row's+ * last_error, cleared by the next batch that commits), naming the error and+ * where the pass stands; otherwise reports each scope's last completed pass+ * and its cursor. Reads config only.+ */+import type { Check } from '../../doctor.ts';+import { agentFix, checkError } from '../check-fix.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { CONTENT_DRIFT_SWEEP_KEY_PREFIX, readContentDriftSweepStates } from '../../../core/content-drift-sweep.ts';++const DOCS = 'docs/guides/troubleshooting.md#content-drift-sweep';++async function runContentDriftSweepCheck(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ try {+ const scopes = (await readContentDriftSweepStates(connectedEngine(ctx))).map(({ key, state }) => ({+ scope: key.slice(CONTENT_DRIFT_SWEEP_KEY_PREFIX.length), cursor: state.cursor, pass_started_at: state.pass_started_at,+ last_completed_at: state.last_completed_at, last_pass_checked: state.last_pass_checked, last_pass_drifted: state.last_pass_drifted,+ last_error: state.last_error,+ }));+ const failing = scopes.filter(s => s.last_error);+ const details = { code: 'content_drift_sweep', scopes, docs: DOCS };+ if (failing.length > 0) {+ checks.push({+ name: 'content_drift_sweep', status: 'warn', details,+ message: `The content-drift sweep's latest batch failed: ${failing.map(s => `${s.scope} at chunk id ${s.cursor} (${s.last_error!.at}): ${s.last_error!.message}`).join('; ')}. `+ + 'Vectors whose chunk text changed stay in place until a pass reaches them; the next embed run retries from the saved cursor. '+ + `Nothing was changed by this check. See ${DOCS}.`,+ fix: agentFix(['gbrain', 'embed', '--stale'], 'Retries the sweep from its saved cursor and re-embeds what it invalidates; embedding spends tokens, so ask the user first.',+ 'content_drift_sweep', { consent: ['paid'], docs: DOCS }),+ });+ return checks;+ }+ checks.push({+ name: 'content_drift_sweep', status: 'ok', details,+ message: scopes.length === 0+ ? 'The content-drift sweep has not run yet; it runs inside embed --stale and the embed jobs.'+ : scopes.map(s => `${s.scope}: ${s.last_completed_at ? `last pass completed ${s.last_completed_at} (${s.last_pass_checked} checked, ${s.last_pass_drifted} invalidated)` : 'no pass completed yet'}`+ + `${s.cursor > 0 ? `, current pass at chunk id ${s.cursor}` : ''}`).join('; '),+ });+ } catch (error) {+ checks.push(checkError('content_drift_sweep', 'read the content-drift sweep state', error, { details: { health: 'unknown' } }));+ }+ return checks;+}++export const contentDriftSweepEntry: DoctorEntry = {+ name: 'content_drift_sweep',+ emits: ['content_drift_sweep'],+ run: runContentDriftSweepCheck,+};diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex cc72c86ea7..f060e60d7f 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -86,6 +86,7 @@ import { imageEmbeddingCoverageEntry } from './checks/image-embedding-coverage.timport { globalMaintenanceTimeoutsEntry } from './checks/global-maintenance-timeouts.ts';import { globalMaintenanceStalledEntry } from './checks/global-maintenance-stalled.ts';import { embedBackfillStalledEntry } from './checks/embed-backfill-stalled.ts';+import { contentDriftSweepEntry } from './checks/content-drift-sweep.ts';import { connectorAccountMismatchEntry } from './checks/connector-account-mismatch.ts';import { legacyJobAuthorityEntry } from './checks/legacy-job-authority.ts';import { legacyTokenGrantsEntry } from './checks/legacy-token-grants.ts';@@ -224,6 +225,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [globalMaintenanceTimeoutsEntry,globalMaintenanceStalledEntry,embedBackfillStalledEntry,+ contentDriftSweepEntry,connectorAccountMismatchEntry,legacyJobAuthorityEntry,legacyTokenGrantsEntry,diff --git a/src/commands/embed.ts b/src/commands/embed.tsindex 7f2f21712c..a43225408b 100644--- a/src/commands/embed.ts+++ b/src/commands/embed.ts@@ -28,6 +28,7 @@ import { StaleChunkProgress } from '../core/embed-stale-progress.ts';import { assertEmbeddingEnabled } from '../core/embedding-dim-check.ts';import { writeCliError } from '../cli/cli-error.ts';import { countRestampOnlyChunks, invalidateStaleSignatureEmbeddingsGuarded } from '../core/embedding-invalidation.ts';+import { contentDriftSweepLine, runContentDriftSweep, type ContentDriftSweepStatus } from '../core/content-drift-sweep.ts';import { loadConfig, type GBrainConfig } from '../core/config.ts';import { slog, serr } from '../core/console-prefix.ts';import { embedBudgetStopVerdict, noteEmbedBudgetStop } from '../core/embed-budget-stop.ts';@@ -376,6 +377,8 @@ export interface EmbedResult {budget_reason?: string;/** #5885: the takes pass of a `stale` drain, when it ran. Its failures are also counted in `failures`. */takes?: EmbedTakesResult;+ /** #7117: the content-drift sweep of a `stale` drain (core/content-drift-sweep.ts): counts, cursor, pass state, error. */+ content_drift?: ContentDriftSweepStatus;}/**@@ -1846,18 +1849,14 @@ async function embedAllStale(// bounded by real content edits (config-independent, unlike signature// drift) and those vectors point at stale text either way. NULL hash// (pre-v133 rows) is grandfathered.+ // #7117: bounded batches, a saved cursor and a per-run time budget (core/content-drift-sweep.ts);+ // a failed batch is reported, never thrown, so the NULL-only loop still runs.if (!dryRun) {- try {- const drifted = staleOpts?.assertOwned ? await engine.transaction(async tx => {- await staleOpts?.assertOwned?.(tx);- return tx.invalidateContentDriftEmbeddings(sourceId ? { sourceId } : undefined);- }) : await engine.invalidateContentDriftEmbeddings(sourceId ? { sourceId } : undefined);- if (drifted > 0 && !staleOpts?.quiet) {- slog(`[embed] invalidated ${drifted} chunk(s) whose text changed after embedding (content drift)`);- }- } catch {- // Best-effort (pre-v133 schema mid-upgrade); the NULL-only loop still runs.- }+ result.content_drift = await runContentDriftSweep(engine, { ...(sourceId && { sourceId }), signal: externalSignal,+ assertOwned: staleOpts?.assertOwned, ...(BUDGET_MS !== null && { deadline: overallStartedAt + BUDGET_MS }) });+ const line = contentDriftSweepLine(result.content_drift, !!staleOpts?.quiet);+ if (line) serr(` [embed] ${line}`);+ if (isAborted(externalSignal)) return;}// Pre-flight: 0 stale chunks → nothing to do, no further DB reads.diff --git a/src/core/config-runtime-keys.ts b/src/core/config-runtime-keys.tsindex f9d7a56971..8d6d5235e4 100644--- a/src/core/config-runtime-keys.ts+++ b/src/core/config-runtime-keys.ts@@ -7,6 +7,7 @@*/export const RUNTIME_READER_CONFIG_KEYS: readonly string[] = ['embed.max_usd_per_page', // page-embedding-budget.ts: large-page embedding cap, default $2 (unlimited under spend.posture tokenmax)+ 'embed.content_drift.pass_interval_hours', // content-drift-sweep.ts: hours between completed content-drift passes, default 24 (0 = every run)'facts.absorb_warn_threshold', // doctor facts_extraction_health absorb-refusal warn threshold, default 10 per 24 h'think.trajectory_enabled', // think/index.ts: trajectory substrate on temporal intents, default on'embedding_image_ocr_max_images', 'embedding_image_ocr_max_usd', // import-file.ts image-OCR per-run caps, default 200 images / $1diff --git a/src/core/content-drift-sweep.ts b/src/core/content-drift-sweep.tsnew file mode 100644index 0000000000..ac0999d2ff--- /dev/null+++ b/src/core/content-drift-sweep.ts@@ -0,0 +1,218 @@+/**+ * #7117: the content-drift sweep (#4246) as a resumable, budgeted pass.+ *+ * A chunk whose stored `embedded_text_hash` no longer matches md5(chunk_text)+ * carries a vector computed from an earlier text. Writers clear the hash and+ * the vector when they change chunk_text, so this sweep is a safety net, not+ * the main path. As one UPDATE it scanned all of content_chunks on every embed+ * job; on a large brain the pool's statement_timeout cancelled it every time,+ * nothing was kept, and the error was swallowed.+ *+ * Each step examines at most `batchRows` chunk rows in id order+ * (`invalidateContentDriftBatch`) and commits its invalidations together with+ * the cursor, in a config row keyed by the active embedding column and the+ * scope (`all` or `source:<id>`). One run stops at its time budget, the job+ * deadline or an abort, so a pass spans as many runs as it needs. Each step+ * locks the cursor row, so concurrent runs share one pass instead of+ * repeating it. A completed pass starts over only after+ * `embed.content_drift.pass_interval_hours` (default 24); a pass that fit in+ * one batch costs one bounded statement and repeats on every run.+ */+import type { BrainEngine } from './engine.ts';+import { CONTENT_DRIFT_BATCH_ROWS, invalidateContentDriftBatch, type ContentDriftBatch } from './engine-sql/chunks.ts';+import { resolveActiveEmbeddingColumnFromEngine } from './search/embedding-column.ts';+import { isMissingSchemaObject } from './utils.ts';++export const CONTENT_DRIFT_SWEEP_KEY_PREFIX = 'embed.content_drift_sweep.';+export const CONTENT_DRIFT_PASS_INTERVAL_KEY = 'embed.content_drift.pass_interval_hours';+export const DEFAULT_CONTENT_DRIFT_PASS_INTERVAL_HOURS = 24;+/** Wall time one run may spend sweeping; one batch is far shorter than any statement_timeout. */+export const DEFAULT_CONTENT_DRIFT_TIME_BUDGET_MS = 60_000;++/** The saved cursor and pass record for one (column, scope). */+export interface ContentDriftSweepState {+ /** Last chunk id the current pass examined; 0 before a pass starts. */+ cursor: number;+ pass_started_at: string | null;+ pass_checked: number;+ pass_drifted: number;+ last_completed_at: string | null;+ last_pass_checked: number | null;+ last_pass_drifted: number | null;+ last_error: { at: string; message: string } | null;+}++export interface ContentDriftSweepStatus {+ scope: string;+ column: string | null;+ /**+ * complete: this run finished a pass. partial: it reached its time budget+ * with the cursor saved. waiting: the last pass completed less than the+ * interval ago, so nothing ran. stopped: an abort or the deadline stopped it.+ * failed: a batch failed (error says why; the cursor stays before it).+ * unsupported: the schema predates the drift columns (v133).+ */+ state: 'complete' | 'partial' | 'waiting' | 'stopped' | 'failed' | 'unsupported';+ checked: number;+ drifted: number;+ batches: number;+ cursor: number;+ last_completed_at: string | null;+ next_pass_at?: string;+ error?: string;+}++export interface ContentDriftSweepOpts {+ sourceId?: string;+ signal?: AbortSignal;+ /** Epoch ms the caller must stop by (a job deadline). */+ deadline?: number;+ /** Extra stop condition checked between batches. */+ stopped?: () => boolean;+ /** Runs inside every batch transaction, before and after its write; a throw ends the sweep and propagates. */+ assertOwned?: (tx: BrainEngine) => Promise<void>;+ timeBudgetMs?: number;+ batchRows?: number;+}++const EMPTY_STATE: ContentDriftSweepState = {+ cursor: 0, pass_started_at: null, pass_checked: 0, pass_drifted: 0,+ last_completed_at: null, last_pass_checked: null, last_pass_drifted: null, last_error: null,+};++export function contentDriftSweepKey(column: string, sourceId?: string): string {+ return `${CONTENT_DRIFT_SWEEP_KEY_PREFIX}${column}.${sourceId === undefined ? 'all' : `source:${sourceId}`}`;+}++export function parseContentDriftSweepState(raw: string | null | undefined): ContentDriftSweepState {+ if (!raw) return { ...EMPTY_STATE };+ try {+ const parsed = JSON.parse(raw) as Partial<ContentDriftSweepState>;+ const cursor = Number(parsed.cursor);+ return { ...EMPTY_STATE, ...parsed, cursor: Number.isSafeInteger(cursor) && cursor > 0 ? cursor : 0 };+ } catch {+ return { ...EMPTY_STATE };+ }+}++async function passIntervalMs(engine: BrainEngine): Promise<number> {+ const raw = await engine.getConfig(CONTENT_DRIFT_PASS_INTERVAL_KEY);+ const hours = raw === null ? NaN : Number(raw);+ return (Number.isFinite(hours) && hours >= 0 ? hours : DEFAULT_CONTENT_DRIFT_PASS_INTERVAL_HOURS) * 3_600_000;+}++/** Lock the cursor row for this step (creating it first), so concurrent runs advance one shared pass. */+async function lockState(tx: BrainEngine, key: string): Promise<ContentDriftSweepState> {+ await tx.executeRaw(`INSERT INTO config (key, value) VALUES ($1, $2) ON CONFLICT (key) DO NOTHING`, [key, JSON.stringify(EMPTY_STATE)]);+ const [row] = await tx.executeRaw<{ value: string }>(`SELECT value FROM config WHERE key = $1 FOR UPDATE`, [key]);+ return parseContentDriftSweepState(row?.value);+}++export async function runContentDriftSweep(engine: BrainEngine, opts: ContentDriftSweepOpts = {}): Promise<ContentDriftSweepStatus> {+ const stopAt = Math.min(Date.now() + (opts.timeBudgetMs ?? DEFAULT_CONTENT_DRIFT_TIME_BUDGET_MS), opts.deadline ?? Infinity);+ const stopped = () => !!opts.signal?.aborted || opts.stopped?.() === true || Date.now() >= (opts.deadline ?? Infinity);+ const batchRows = opts.batchRows ?? CONTENT_DRIFT_BATCH_ROWS;+ const status: ContentDriftSweepStatus = {+ scope: opts.sourceId === undefined ? 'all' : `source:${opts.sourceId}`,+ column: null, state: 'partial', checked: 0, drifted: 0, batches: 0, cursor: 0, last_completed_at: null,+ };+ const ownership: { lost: boolean; error?: unknown } = { lost: false };+ const own = async (tx: BrainEngine) => {+ try {+ await opts.assertOwned?.(tx);+ } catch (error) {+ ownership.lost = true;+ ownership.error = error;+ throw error;+ }+ };+ let key: string | null = null;+ try {+ const column = (await resolveActiveEmbeddingColumnFromEngine(engine)).name;+ status.column = column;+ const stateKey = contentDriftSweepKey(column, opts.sourceId);+ key = stateKey;+ const intervalMs = await passIntervalMs(engine);+ for (;;) {+ if (stopped()) { status.state = 'stopped'; return status; }+ if (Date.now() >= stopAt) { status.state = 'partial'; return status; }+ const step = await engine.transaction(async (tx): Promise<{ state: ContentDriftSweepState; nextAt: number } | { state: ContentDriftSweepState; batch: ContentDriftBatch }> => {+ await own(tx);+ const state = await lockState(tx, stateKey);+ if (state.cursor === 0 && state.last_completed_at && (state.last_pass_checked ?? 0) > batchRows) {+ const nextAt = Date.parse(state.last_completed_at) + intervalMs;+ if (Date.now() < nextAt) return { state, nextAt };+ }+ const batch = await invalidateContentDriftBatch(run => run(tx), column, {+ afterChunkId: state.cursor, limit: batchRows, ...(opts.sourceId !== undefined && { sourceId: opts.sourceId }),+ });+ const now = new Date().toISOString();+ const pass = state.cursor === 0+ ? { pass_started_at: now, pass_checked: batch.checked, pass_drifted: batch.drifted }+ : { pass_started_at: state.pass_started_at, pass_checked: state.pass_checked + batch.checked, pass_drifted: state.pass_drifted + batch.drifted };+ const next: ContentDriftSweepState = batch.lastChunkId === null+ ? { ...EMPTY_STATE, last_completed_at: now, last_pass_checked: pass.pass_checked, last_pass_drifted: pass.pass_drifted }+ : { ...state, ...pass, cursor: batch.lastChunkId, last_error: null };+ await own(tx);+ await tx.setConfig(stateKey, JSON.stringify(next));+ return { state: next, batch };+ });+ status.cursor = step.state.cursor;+ status.last_completed_at = step.state.last_completed_at;+ if ('nextAt' in step) {+ status.state = 'waiting';+ status.next_pass_at = new Date(step.nextAt).toISOString();+ return status;+ }+ status.batches += 1;+ status.checked += step.batch.checked;+ status.drifted += step.batch.drifted;+ if (step.batch.lastChunkId === null) { status.state = 'complete'; return status; }+ }+ } catch (error) {+ if (ownership.lost) throw ownership.error;+ if (stopped()) { status.state = 'stopped'; return status; }+ status.error = error instanceof Error ? error.message : String(error);+ if (isMissingSchemaObject(error, 'column', ['embedded_text_hash', 'embedding_pending_since'])) {+ status.state = 'unsupported';+ return status;+ }+ status.state = 'failed';+ if (key) {+ const failedKey = key;+ const last_error = { at: new Date().toISOString(), message: status.error.slice(0, 500) };+ await engine.transaction(async tx => {+ const state = await lockState(tx, failedKey);+ status.cursor = state.cursor;+ await tx.setConfig(failedKey, JSON.stringify({ ...state, last_error }));+ }).catch(() => {});+ }+ return status;+ }+}++/** One line for stderr, naming what the sweep did and where it stands. */+export function describeContentDriftSweep(s: ContentDriftSweepStatus): string {+ const counts = `${s.checked} chunk(s) checked in ${s.batches} batch(es), ${s.drifted} invalidated`;+ switch (s.state) {+ case 'complete': return `content-drift sweep (${s.scope}) completed a pass: ${counts}`;+ case 'partial': return `content-drift sweep (${s.scope}) reached its time budget at chunk id ${s.cursor}: ${counts}; the next run resumes there`;+ case 'stopped': return `content-drift sweep (${s.scope}) stopped at chunk id ${s.cursor}: ${counts}; the next run resumes there`;+ case 'waiting': return `content-drift sweep (${s.scope}) is idle until ${s.next_pass_at} (last pass completed ${s.last_completed_at})`;+ case 'unsupported': return `content-drift sweep (${s.scope}) skipped: this schema predates embedded_text_hash; run gbrain apply-migrations --yes`;+ case 'failed': return `content-drift sweep (${s.scope}) FAILED at chunk id ${s.cursor} after ${counts}: ${s.error}; the cursor stays before the failed batch`;+ }+}++/** The stderr line for a run: a failure always, otherwise the status unless quiet or idle. */+export function contentDriftSweepLine(s: ContentDriftSweepStatus, quiet: boolean): string | null {+ if (s.state === 'failed') return `WARNING: ${describeContentDriftSweep(s)}`;+ return quiet || s.state === 'waiting' ? null : describeContentDriftSweep(s);+}++/** Every saved sweep state, for doctor. */+export async function readContentDriftSweepStates(engine: BrainEngine): Promise<Array<{ key: string; state: ContentDriftSweepState }>> {+ const config = await engine.getAllConfig();+ return Object.keys(config).filter(key => key.startsWith(CONTENT_DRIFT_SWEEP_KEY_PREFIX)).sort()+ .map(key => ({ key, state: parseContentDriftSweepState(config[key]) }));+}diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex 5b8af25fdf..21021d08c2 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -1678,7 +1678,7 @@ async function runPhaseEmbed(engine: BrainEngine, dryRun: boolean, signal?: Abor// In dry-run, this counts pages with stale chunks that would// have been processed (same semantic as a real run).pages_embedded_count: dryRun ? result.pages_processed : embeddedCount > 0 ? result.pages_processed : 0,- failures: result.failures,+ failures: result.failures, ...(result.content_drift ? { content_drift: result.content_drift } : {}),...(failed ? { failure_samples: result.failure_samples, fix: embedBackfillFix({ backlog: result.failures, verifyCheck: 'embeddings' }) } : {}),},};diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 765cfee9b0..d289c2d37e 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -345,6 +345,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([// GBRA-130 C-6: no completed brain-wide pass while jobs fail or a phase keeps blocking it.'global_maintenance_stalled','embed_backfill_stalled',+ // #7117: the content-drift sweep's latest batch failed.+ 'content_drift_sweep','connector_account_mismatch',// #5157: queued jobs from before the v0.50 authority cutover block every worker.'legacy_job_authority',diff --git a/src/core/embed-stale.ts b/src/core/embed-stale.tsindex 1e4835f1ba..57ba9947b3 100644--- a/src/core/embed-stale.ts+++ b/src/core/embed-stale.ts@@ -34,6 +34,7 @@ import {import { type DbPacer, createNoopPacer, observed } from './db-pacer.ts';import { resolveStaleEmbedConcurrency } from './embed-concurrency.ts';import { AbortError } from './abort-check.ts';+import { contentDriftSweepLine, runContentDriftSweep, type ContentDriftSweepStatus } from './content-drift-sweep.ts';import { meterPageBatch, spendGrant } from './page-embedding-budget.ts';import { chunkGenerationFilter, chunkVisibleFilter } from './search/safe-chunks.ts';import { embedSegmentedPage, embedSegmentedRows, readSegmentedEmbedPage, type SegmentedEmbedOpts } from './page-body/segmented-embedding.ts';@@ -144,6 +145,8 @@ export interface EmbedStaleResult {* NULL-embedding-only staleness instead of destroying working vectors.*/invalidationSkipped?: 'embedder_probe_failed';+ /** #7117: this run's content-drift sweep (core/content-drift-sweep.ts); its invalidations are in `invalidated`. */+ contentDrift?: ContentDriftSweepStatus;/** Last cursor reached. null iff zero stale chunks existed at start. */lastCursor: StaleCursor | null;/** True iff the loop exited because every stale chunk was processed. */@@ -486,21 +489,18 @@ export async function embedStaleForSource(// bounded by real content edits (config-independent, unlike signature// drift) and those vectors point at stale text either way. NULL hash// (pre-v133 rows) is grandfathered.- try {- if (stopped()) return { ...result, aborted: true };- result.invalidated += opts.assertOwned ? await engine.transaction(async tx => {- await opts.assertOwned!(tx);- if (stopped()) throw new AbortError();- const invalidated = await tx.invalidateContentDriftEmbeddings({ sourceId });- await opts.assertOwned!(tx);- if (stopped()) throw new AbortError();- return invalidated;- }) : await engine.invalidateContentDriftEmbeddings({ sourceId });- } catch {- if (stopped()) return { ...result, aborted: true };- await opts.assertOwned?.();- // Non-fatal: fall through to the NULL-only stale loop.- }+ // #7117: bounded batches with a saved cursor (core/content-drift-sweep.ts).+ // A failed batch is reported in the result and on stderr, not thrown, and+ // the NULL-only loop still runs; a lost lease propagates.+ if (stopped()) return { ...result, aborted: true };+ const sweep = await runContentDriftSweep(engine, {+ sourceId, signal, deadline: opts.deadline, stopped,+ assertOwned: opts.assertOwned,+ });+ result.contentDrift = sweep;+ result.invalidated += sweep.drifted;+ if (sweep.state === 'failed') process.stderr.write(`\n [embed-stale] ${contentDriftSweepLine(sweep, true)}\n`);+ if (stopped()) return { ...result, aborted: true };for (;;) {if (stopped()) {diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.tsindex 432eaebbf4..a144a5631d 100644--- a/src/core/engine-sql/chunks.ts+++ b/src/core/engine-sql/chunks.ts@@ -595,28 +595,55 @@ export async function invalidateStaleSignatureEmbeddings(});}-export async function invalidateContentDriftEmbeddings(+/** Chunk rows one content-drift batch examines; each batch is one short statement. */+export const CONTENT_DRIFT_BATCH_ROWS = 5_000;++export interface ContentDriftBatch {+ /** Candidate rows the batch examined (at most `limit`). */+ checked: number;+ /** Rows whose vector it invalidated. */+ drifted: number;+ /** Highest chunk id it examined; null when no row lies past `afterChunkId`. */+ lastChunkId: number | null;+}++/**+ * #4246 / #7117: one bounded step of the content-drift sweep. NULL the+ * embeddings whose stored embed-time hash no longer matches md5(chunk_text)+ * (the vector was computed from a PREVIOUS content revision), among the+ * `limit` chunk rows with the lowest ids above `afterChunkId`. The candidate+ * set is bounded by the primary key before any hash is computed, so a batch+ * costs the same on a healthy corpus as on a drifted one. Feeds the+ * NULL-embedding cursor (mirrors the signature invalidation above).+ * GRANDFATHER: NULL hash (pre-v133 rows) untouched so upgrades don't trigger+ * a corpus-wide re-embed spike. embed_skip pages excluded: the stale+ * selectors can't re-embed them, so NULLing would strand them. S2: keyed on+ * the registry-ACTIVE column (the caller resolves it with the loud resolver).+ * The cursor and limit are inlined, not bound, so a prepared statement never+ * switches to a generic plan that scans the whole table (migration-preludes.ts).+ */+export async function invalidateContentDriftBatch(inTransaction: ChunkTransactionRunner,column: string,- opts?: { sourceId?: string },-): Promise<number> {- // #4246: NULL embeddings whose stored embed-time hash no longer matches- // md5(chunk_text) — the vector was computed from a PREVIOUS content- // revision. Feeds the NULL-embedding cursor (mirrors the signature- // invalidation above). GRANDFATHER: NULL hash (pre-v133 rows) untouched- // so upgrades don't trigger a corpus-wide re-embed spike. embed_skip- // pages excluded — the stale selectors can't re-embed them, so NULLing- // would strand them (same never-NULL-what-nothing-re-embeds rule as- // embedding-invalidation.ts). S2: keyed on the registry-ACTIVE column- // (the engine resolves it with the loud resolver).+ opts: { afterChunkId: number; limit: number; sourceId?: string },+): Promise<ContentDriftBatch> {+ const after = Math.trunc(opts.afterChunkId);+ const limit = Math.trunc(opts.limit);+ if (!Number.isFinite(after) || !Number.isFinite(limit) || after < 0 || limit < 1) {+ throw new Error(`invalid content-drift batch window: after ${opts.afterChunkId}, limit ${opts.limit}`);+ }const colId = trustedSql(quoteIdentifier(column));- const srcClause = opts?.sourceId !== undefined ? sqlFragment` AND p.source_id = ${opts.sourceId}` : sqlFragment``;+ const window = trustedSql(`id > ${after} ORDER BY id LIMIT ${limit}`);+ const srcClause = opts.sourceId !== undefined ? sqlFragment` AND p.source_id = ${opts.sourceId}` : sqlFragment``;return inTransaction(async tx => {- const sources = await lockEmbeddingSources(tx, opts?.sourceId);- const { text, params } = renderFragment(sqlFragment`UPDATE content_chunks cc+ const sources = await lockEmbeddingSources(tx, opts.sourceId);+ // chunk-visibility-ok: the drift sweep visits every chunk row by id; the UPDATE's predicates decide eligibility+ const { text, params } = renderFragment(sqlFragment`WITH b AS (SELECT id FROM content_chunks WHERE ${window}),+ w AS (UPDATE content_chunks ccSET ${colId} = NULL, embedded_at = NULL, embedded_text_hash = NULL, embedding_pending_since = now()- FROM pages p- WHERE cc.page_id = p.id+ FROM b, pages p+ WHERE cc.id = b.id+ AND cc.page_id = p.idAND p.source_id=ANY(${sources}::text[])AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived)AND p.deleted_at IS NULL@@ -624,11 +651,38 @@ export async function invalidateContentDriftEmbeddings(AND cc.embedded_text_hash IS NOT NULLAND cc.embedded_text_hash <> md5(cc.chunk_text)AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT ${budgetLimited}${srcClause}- RETURNING cc.page_id`);- return (await tx.executeRaw(text, params)).length;+ RETURNING 1)+ SELECT (SELECT max(id) FROM b) AS last_id, (SELECT count(*) FROM b)::int AS checked, (SELECT count(*) FROM w)::int AS drifted`);+ const [row] = await tx.executeRaw<{ last_id: number | string | null; checked: number | string; drifted: number | string }>(text, params);+ return {+ checked: Number(row?.checked ?? 0),+ drifted: Number(row?.drifted ?? 0),+ lastChunkId: row?.last_id == null ? null : Number(row.last_id),+ };});}+/**+ * A whole content-drift pass with no saved cursor, as consecutive bounded+ * batches (`invalidateContentDriftBatch`), each in its own transaction from+ * `inTransaction`. Returns the chunk count invalidated. The embed paths run the+ * resumable, budgeted pass in content-drift-sweep.ts instead.+ */+export async function invalidateContentDriftEmbeddings(+ inTransaction: ChunkTransactionRunner,+ column: string,+ opts?: { sourceId?: string },+): Promise<number> {+ let afterChunkId = 0;+ let drifted = 0;+ for (;;) {+ const batch = await invalidateContentDriftBatch(inTransaction, column, { ...opts, afterChunkId, limit: CONTENT_DRIFT_BATCH_ROWS });+ if (batch.lastChunkId === null) return drifted;+ drifted += batch.drifted;+ afterChunkId = batch.lastChunkId;+ }+ }+export async function listStaleChunks(exec: ScopedRead, column: string, opts?: {batchSize?: number;afterPageId?: number;diff --git a/src/core/engine.ts b/src/core/engine.tsindex cf45e69609..154bd6c9c5 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -1290,14 +1290,13 @@ export interface BrainEngine {/*** #4246: NULL out the embeddings (embedding + embedded_at +* embedded_text_hash) of every chunk whose stored `embedded_text_hash` no- * longer matches `md5(chunk_text)` — i.e. the chunk's text was rewritten- * after its vector was computed, so the vector describes a previous- * content revision. Feeds the NULL-embedding cursor exactly like- * invalidateStaleSignatureEmbeddings. GRANDFATHER: NULL hash (rows- * embedded before v133 stamped provenance) is never invalidated — no- * upgrade re-embed spike; the hash lands on each row's next re-embed.- * embed_skip pages are excluded (listStaleChunks can't re-embed them, so- * NULLing would strand them). Returns the chunk count invalidated.+ * longer matches `md5(chunk_text)` (text rewritten after its vector was+ * computed). Feeds the NULL-embedding cursor like+ * invalidateStaleSignatureEmbeddings. GRANDFATHER: NULL hash (pre-v133+ * rows) is never invalidated — no upgrade re-embed spike. embed_skip pages+ * are excluded (listStaleChunks can't re-embed them). #7117: bounded+ * batches in id order, one transaction each, no saved cursor (the embed+ * paths run content-drift-sweep.ts). Returns the chunk count invalidated.*/invalidateContentDriftEmbeddings(opts?: { sourceId?: string }): Promise<number>;/**diff --git a/src/core/minions/handlers/embed-backfill.ts b/src/core/minions/handlers/embed-backfill.tsindex c18e7775a0..0e065a5543 100644--- a/src/core/minions/handlers/embed-backfill.ts+++ b/src/core/minions/handlers/embed-backfill.ts@@ -45,6 +45,7 @@ import {import { pricingSetCommand } from '../../budget/no-pricing.ts';import { getEmbeddingModel, withBudgetTracker } from '../../ai/gateway.ts';import { embedStaleForSource } from '../../embed-stale.ts';+import type { ContentDriftSweepStatus } from '../../content-drift-sweep.ts';import { createEmbedStallWatchdog, resolveEmbedStallAbortSeconds } from '../../embed-stall.ts';import { currentEmbeddingSignature } from '../../embedding.ts';import { readEmbedBackfillBlockers } from '../../embed-backfill-stall.ts';@@ -89,6 +90,8 @@ export interface EmbedBackfillResult {invalidated: number;/** #4283: set when drifted chunks existed but the embedder probe failed. */invalidationSkipped?: 'embedder_probe_failed';+ /** #7117: this run's content-drift sweep: counts, cursor, pass state, error. */+ contentDrift?: ContentDriftSweepStatus;/** $USD spent inside this job (from BudgetTracker.totalSpent). */spentUsd: number;/** Set when status === 'budget_exhausted'. */@@ -356,6 +359,7 @@ export function makeEmbedBackfillHandler(pagesProcessed: result.pagesProcessed,invalidated: result.invalidated,...(result.invalidationSkipped && { invalidationSkipped: result.invalidationSkipped }),+ ...(result.contentDrift && { contentDrift: result.contentDrift }),spentUsd: tracker.totalSpent,};}@@ -404,6 +408,7 @@ export function makeEmbedBackfillHandler(pagesProcessed: result.pagesProcessed,invalidated: result.invalidated,...(result.invalidationSkipped && { invalidationSkipped: result.invalidationSkipped }),+ ...(result.contentDrift && { contentDrift: result.contentDrift }),spentUsd: tracker.totalSpent,...(await budgetLimitedField(engine, sourceId, currentEmbeddingSignature())),};diff --git a/src/core/minions/handlers/embed.ts b/src/core/minions/handlers/embed.tsindex 3592ebce33..6e46986fc8 100644--- a/src/core/minions/handlers/embed.ts+++ b/src/core/minions/handlers/embed.ts@@ -62,6 +62,7 @@ export function makeEmbedHandler(engine: BrainEngine): MinionHandler {dry_run: !!embedResult.dryRun,would_embed: embedResult.would_embed,failures: embedResult.failures,+ ...(embedResult.content_drift && { content_drift: embedResult.content_drift }),};};}diff --git a/test/content-drift-sweep.test.ts b/test/content-drift-sweep.test.tsnew file mode 100644index 0000000000..ff555e8698--- /dev/null+++ b/test/content-drift-sweep.test.ts@@ -0,0 +1,200 @@+/**+ * #7117: the content-drift sweep runs as bounded, resumable batches.+ *+ * Protects: invalidateContentDriftBatch examines at most `limit` chunk rows+ * past its cursor (before any hash is computed) and keeps the #4246 rules+ * (NULL hash grandfathered; embed_skip, archived-source and deleted pages+ * untouched); runContentDriftSweep saves its cursor with each batch, resumes+ * a stopped pass, waits out the pass interval after a completed multi-batch+ * pass, records a failed batch without moving the cursor, and lets a lost+ * lease propagate.+ * Regression it catches: the single unbatched UPDATE that a statement_timeout+ * cancelled on every run with nothing kept and the error swallowed.+ * Seam: none (PGLite; the Postgres timeout path is test/e2e/content-drift-sweep-postgres.test.ts).+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';+import { invalidateContentDriftBatch } from '../src/core/engine-sql/chunks.ts';+import {+ CONTENT_DRIFT_PASS_INTERVAL_KEY,+ contentDriftSweepKey,+ parseContentDriftSweepState,+ readContentDriftSweepStates,+ runContentDriftSweep,+} from '../src/core/content-drift-sweep.ts';+import { embedStaleForSource } from '../src/core/embed-stale.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 30000);++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+});++/** A page with one embedded chunk; `drift` rewrites its text under the kept vector and hash. */+async function seed(slug: string, opts: { drift?: boolean; sourceId?: string } = {}): Promise<void> {+ const sourceId = opts.sourceId ?? 'default';+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: 'seeded' }, { sourceId });+ await installFixtureChunks(engine, slug, [{+ chunk_index: 0, chunk_text: `old text of ${slug}`, chunk_source: 'compiled_truth',+ token_count: 4, embedding: new Float32Array(1536).fill(0.2),+ }], { sourceId });+ if (opts.drift !== false) {+ await engine.executeRaw(+ `UPDATE content_chunks SET chunk_text = 'rewritten ' || chunk_text+ WHERE page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = $2)`, [slug, sourceId]);+ }+}++async function vectorKept(slug: string, sourceId = 'default'): Promise<boolean> {+ const [row] = await engine.executeRaw<{ kept: boolean }>(+ `SELECT cc.embedding IS NOT NULL AS kept FROM content_chunks cc JOIN pages p ON p.id = cc.page_id+ WHERE p.slug = $1 AND p.source_id = $2`, [slug, sourceId]);+ return row!.kept;+}++async function column(): Promise<string> {+ const { resolveActiveEmbeddingColumnFromEngine } = await import('../src/core/search/embedding-column.ts');+ return (await resolveActiveEmbeddingColumnFromEngine(engine)).name;+}++/** The sweep's `stopped` hook, true from its (n+1)th check on: exactly n batches run. */+function afterBatches(n: number): () => boolean {+ let checks = 0;+ return () => checks++ >= n;+}++describe('invalidateContentDriftBatch', () => {+ test('examines at most limit rows past the cursor and keeps the eligibility rules', async () => {+ for (const slug of ['d1', 'd2', 'd3', 'd4']) await seed(slug);+ await seed('current', { drift: false });+ await seed('legacy');+ await engine.executeRaw(`UPDATE content_chunks SET embedded_text_hash = NULL+ WHERE page_id = (SELECT id FROM pages WHERE slug = 'legacy')`);+ await seed('skipped');+ await engine.executeRaw(`UPDATE pages SET frontmatter = frontmatter || '{"embed_skip": true}'::jsonb WHERE slug = 'skipped'`);+ await seed('deleted');+ await engine.softDeletePage('deleted', { sourceId: 'default' });+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ('shelf', 'shelf', '{"federated":true}'::jsonb)`);+ await seed('archived', { sourceId: 'shelf' });+ await engine.executeRaw(`UPDATE sources SET archived = true WHERE id = 'shelf'`);++ const col = await column();+ const run = <T>(fn: (tx: PGLiteEngine) => Promise<T>) => engine.transaction(fn as never) as Promise<T>;+ const batches = [];+ let after = 0;+ for (;;) {+ const batch = await invalidateContentDriftBatch(run, col, { afterChunkId: after, limit: 3 });+ batches.push(batch);+ if (batch.lastChunkId === null) break;+ expect(batch.lastChunkId).toBeGreaterThan(after);+ after = batch.lastChunkId;+ }+ expect(batches.map(b => b.checked)).toEqual([3, 3, 3, 0]);+ expect(batches.reduce((n, b) => n + b.drifted, 0)).toBe(4);+ for (const slug of ['d1', 'd2', 'd3', 'd4']) expect(await vectorKept(slug)).toBe(false);+ for (const slug of ['current', 'legacy', 'skipped', 'deleted']) expect(await vectorKept(slug)).toBe(true);+ expect(await vectorKept('archived', 'shelf')).toBe(true);+ });+});++describe('runContentDriftSweep', () => {+ test('a stopped pass keeps its cursor and the next run finishes it', async () => {+ for (let i = 0; i < 7; i++) await seed(`p${i}`);+ const first = await runContentDriftSweep(engine, { batchRows: 2, stopped: afterBatches(2) });+ expect(first).toMatchObject({ state: 'stopped', batches: 2, checked: 4, drifted: 4 });+ const saved = parseContentDriftSweepState(await engine.getConfig(contentDriftSweepKey(await column())));+ expect(saved.cursor).toBe(first.cursor);+ expect(saved.cursor).toBeGreaterThan(0);+ expect(saved).toMatchObject({ pass_checked: 4, pass_drifted: 4, last_completed_at: null });++ const second = await runContentDriftSweep(engine, { batchRows: 2 });+ expect(second).toMatchObject({ state: 'complete', checked: 3, drifted: 3, cursor: 0 });+ for (let i = 0; i < 7; i++) expect(await vectorKept(`p${i}`)).toBe(false);+ const [{ state }] = await readContentDriftSweepStates(engine);+ expect(state).toMatchObject({ cursor: 0, last_pass_checked: 7, last_pass_drifted: 4 + 3, last_error: null });+ expect(state.last_completed_at).not.toBeNull();+ });++ test('a completed multi-batch pass waits out the interval; 0 hours repeats it', async () => {+ for (let i = 0; i < 3; i++) await seed(`w${i}`);+ expect((await runContentDriftSweep(engine, { batchRows: 2 })).state).toBe('complete');+ await seed('late');+ const idle = await runContentDriftSweep(engine, { batchRows: 2 });+ expect(idle).toMatchObject({ state: 'waiting', batches: 0 });+ expect(Date.parse(idle.next_pass_at!)).toBeGreaterThan(Date.now() + 23 * 3_600_000);+ expect(await vectorKept('late')).toBe(true);++ await engine.setConfig(CONTENT_DRIFT_PASS_INTERVAL_KEY, '0');+ expect(await runContentDriftSweep(engine, { batchRows: 2 })).toMatchObject({ state: 'complete', drifted: 1 });+ expect(await vectorKept('late')).toBe(false);+ });++ test('a pass that fits in one batch runs on every call', async () => {+ await seed('a');+ expect((await runContentDriftSweep(engine)).state).toBe('complete');+ await seed('b');+ expect(await runContentDriftSweep(engine)).toMatchObject({ state: 'complete', drifted: 1 });+ });++ test('source scopes keep separate cursors and touch only their source', async () => {+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ('other', 'other', '{"federated":true}'::jsonb)`);+ await seed('mine');+ await seed('theirs', { sourceId: 'other' });+ expect(await runContentDriftSweep(engine, { sourceId: 'default' })).toMatchObject({ scope: 'source:default', drifted: 1 });+ expect(await vectorKept('theirs', 'other')).toBe(true);+ expect((await readContentDriftSweepStates(engine)).map(s => s.key)).toEqual([contentDriftSweepKey(await column(), 'default')]);+ });++ test('a failed batch is reported and recorded, and the cursor stays before it', async () => {+ for (let i = 0; i < 4; i++) await seed(`f${i}`);+ await runContentDriftSweep(engine, { batchRows: 2, stopped: afterBatches(1) });+ const before = parseContentDriftSweepState(await engine.getConfig(contentDriftSweepKey(await column())));+ await engine.executeRaw(`CREATE FUNCTION refuse_chunk_update() RETURNS trigger LANGUAGE plpgsql AS $$+ BEGIN RAISE EXCEPTION 'chunk writes refused for this test'; END $$`);+ await engine.executeRaw(`CREATE TRIGGER refuse_chunk_update BEFORE UPDATE ON content_chunks FOR EACH ROW EXECUTE FUNCTION refuse_chunk_update()`);+ try {+ const failed = await runContentDriftSweep(engine, { batchRows: 2 });+ expect(failed.state).toBe('failed');+ expect(failed.error).toContain('chunk writes refused for this test');+ expect(failed.cursor).toBe(before.cursor);+ const after = parseContentDriftSweepState(await engine.getConfig(contentDriftSweepKey(await column())));+ expect(after.cursor).toBe(before.cursor);+ expect(after.last_error?.message).toContain('chunk writes refused for this test');+ } finally {+ await engine.executeRaw('DROP TRIGGER refuse_chunk_update ON content_chunks');+ await engine.executeRaw('DROP FUNCTION refuse_chunk_update()');+ }+ const resumed = await runContentDriftSweep(engine, { batchRows: 2 });+ expect(resumed).toMatchObject({ state: 'complete', drifted: 2 });+ expect(parseContentDriftSweepState(await engine.getConfig(contentDriftSweepKey(await column()))).last_error).toBeNull();+ });++ test('a lost lease propagates and leaves the batch uncommitted', async () => {+ await seed('owned');+ const lost = new Error('lease lost');+ await expect(runContentDriftSweep(engine, { assertOwned: async () => { throw lost; } })).rejects.toBe(lost);+ expect(await vectorKept('owned')).toBe(true);+ });++ test('embedStaleForSource reports the sweep and re-embeds what it invalidated', async () => {+ await seed('drifted');+ const result = await embedStaleForSource(engine, 'default', {+ embedFn: async texts => texts.map(() => new Float32Array(1536).fill(0.1)),+ });+ expect(result.contentDrift).toMatchObject({ scope: 'source:default', state: 'complete', drifted: 1 });+ expect(result.invalidated).toBe(1);+ expect(result.embedded).toBe(1);+ });+});diff --git a/test/doctor-content-drift-sweep.test.ts b/test/doctor-content-drift-sweep.test.tsnew file mode 100644index 0000000000..6fdf570400--- /dev/null+++ b/test/doctor-content-drift-sweep.test.ts@@ -0,0 +1,64 @@+/**+ * content_drift_sweep doctor check (#7117): reports the content-drift+ * sweep's latest failure and each scope's last completed pass from the saved+ * sweep state, so a sweep that keeps failing is visible instead of silent.+ *+ * PGLite in-memory ($0).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';+import { runContentDriftSweep } from '../src/core/content-drift-sweep.ts';+import { contentDriftSweepEntry } from '../src/commands/doctor/checks/content-drift-sweep.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import { categorizeCheck } from '../src/core/doctor-categories.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => { if (engine) await engine.disconnect(); }, 60_000);++async function check() {+ const checks = await contentDriftSweepEntry.run({ engine, args: [] } as unknown as DoctorContext);+ if (!Array.isArray(checks)) throw new Error('the entry stopped doctor');+ expect(checks.map(c => c.name)).toEqual(['content_drift_sweep']);+ return checks[0]!;+}++describe('content_drift_sweep doctor check', () => {+ test('ok before any sweep, warn while the latest batch failed, ok after a pass completes', async () => {+ expect(categorizeCheck('content_drift_sweep')).toBe('ops');+ const fresh = await check();+ expect(fresh.status).toBe('ok');+ expect(fresh.message).toContain('has not run yet');++ await engine.putPage('drift', { type: 'note', title: 'drift', compiled_truth: 'seeded' });+ await installFixtureChunks(engine, 'drift', [{ chunk_index: 0, chunk_text: 'old', chunk_source: 'compiled_truth', token_count: 1,+ embedding: new Float32Array(1536).fill(0.2) }]);+ await engine.executeRaw(`UPDATE content_chunks SET chunk_text = 'new' WHERE page_id = (SELECT id FROM pages WHERE slug = 'drift')`);+ await engine.executeRaw(`CREATE FUNCTION refuse_drift_write() RETURNS trigger LANGUAGE plpgsql AS $$+ BEGIN RAISE EXCEPTION 'drift writes refused for this test'; END $$`);+ await engine.executeRaw('CREATE TRIGGER refuse_drift_write BEFORE UPDATE ON content_chunks FOR EACH ROW EXECUTE FUNCTION refuse_drift_write()');+ try {+ expect((await runContentDriftSweep(engine)).state).toBe('failed');+ } finally {+ await engine.executeRaw('DROP TRIGGER refuse_drift_write ON content_chunks');+ await engine.executeRaw('DROP FUNCTION refuse_drift_write()');+ }+ const failing = await check();+ expect(failing.status).toBe('warn');+ expect(failing.message).toContain('drift writes refused for this test');+ expect(failing.fix?.argv).toEqual(['gbrain', 'embed', '--stale']);+ expect(failing.fix?.consent).toEqual(['paid']);++ expect((await runContentDriftSweep(engine)).state).toBe('complete');+ const healthy = await check();+ expect(healthy.status).toBe('ok');+ expect(healthy.message).toMatch(/last pass completed .* \(1 checked, 1 invalidated\)/);+ });+});diff --git a/test/e2e/content-drift-sweep-postgres.test.ts b/test/e2e/content-drift-sweep-postgres.test.tsnew file mode 100644index 0000000000..33038db936--- /dev/null+++ b/test/e2e/content-drift-sweep-postgres.test.ts@@ -0,0 +1,161 @@+/**+ * #7117: the content-drift sweep under a statement_timeout, on real Postgres.+ *+ * Protects: every content-drift statement is bounded to one batch of chunk+ * rows, so a cancel loses at most the batch it hit. Earlier batches stay+ * committed, the sweep's cursor stays before the cancelled batch, the failure+ * is reported (state, error, saved last_error) instead of swallowed, and the+ * next run resumes there and completes the pass. Grandfathered (NULL hash),+ * embed_skip, archived-source and deleted-page rows stay untouched.+ * Regression it catches: one UPDATE over all of content_chunks; any cancel+ * rolled the whole pass back and the next run started from scratch.+ * Seam: a second connection holds a row lock on the last drifted chunk, so the+ * statement that reaches it waits until a 1.5 s statement_timeout cancels it,+ * as the pool's 5 min timeout cancels a whole-table scan on a large brain.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { hasDatabase, setupDB, teardownDB, getConn } from './helpers.ts';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';+import { installFixtureChunks } from '../helpers/page-projection.ts';++const d = hasDatabase() ? describe : describe.skip;+const url = process.env.DATABASE_URL;+const previousTimeout = process.env.GBRAIN_STATEMENT_TIMEOUT;+const FILLER_PAGES = 60;+const CHUNKS_PER_PAGE = 100;+/** Row ranks (0-based, id order) of the drifted filler chunks; the batch size is 5000. */+const EARLY = [10, 2000, 4500];+const LATE = [5200];++let engine: PostgresEngine;+let slow: PostgresEngine;+let lockedId: number;+let release: (() => void) | null = null;++async function vectorKept(id: number): Promise<boolean> {+ const [row] = await engine.executeRaw<{ kept: boolean }>('SELECT embedding IS NOT NULL AS kept FROM content_chunks WHERE id = $1', [id]);+ return row!.kept;+}++async function idAtRank(rank: number): Promise<number> {+ const [row] = await engine.executeRaw<{ id: number }>('SELECT id FROM content_chunks ORDER BY id OFFSET $1 LIMIT 1', [rank]);+ return Number(row!.id);+}++/** Embed chunk rows with a zero vector and a stored hash (`hash` null = grandfathered). */+async function embedRows(ids: number[], hash: string | null): Promise<void> {+ const [{ dim }] = await engine.executeRaw<{ dim: number }>(+ "SELECT atttypmod AS dim FROM pg_attribute WHERE attrelid = 'content_chunks'::regclass AND attname = 'embedding' AND attnum > 0");+ await engine.executeRaw(+ `UPDATE content_chunks SET embedding = ('[' || array_to_string(array_fill(0.1::real, ARRAY[$1::int]), ',') || ']')::vector,+ embedded_at = now(), embedded_text_hash = $2 WHERE id = ANY($3::int[])`, [dim, hash, ids]);+}++async function onlyChunk(slug: string, sourceId = 'default'): Promise<number> {+ const [row] = await engine.executeRaw<{ id: number }>(+ 'SELECT cc.id FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1 AND p.source_id = $2', [slug, sourceId]);+ return Number(row!.id);+}++/** Excluded rows first (low ids, inside the first batch), then the filler corpus with a few drifted rows. */+async function seed(): Promise<{ excluded: number[]; early: number[]; late: number[] }> {+ const single = async (slug: string, sourceId = 'default') => {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: slug }, { sourceId });+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_text: `text of ${slug}`, chunk_source: 'compiled_truth', token_count: 3 }], { sourceId });+ return onlyChunk(slug, sourceId);+ };+ const legacy = await single('legacy');+ const skipped = await single('skipped');+ await engine.executeRaw(`UPDATE pages SET frontmatter = frontmatter || '{"embed_skip": true}'::jsonb WHERE slug = 'skipped'`);+ const deleted = await single('deleted');+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ('shelf', 'shelf', '{"federated":true}'::jsonb)`);+ const archived = await single('archived', 'shelf');+ await embedRows([legacy], null);+ await embedRows([skipped, deleted, archived], 'hash-of-an-earlier-text');+ await engine.softDeletePage('deleted', { sourceId: 'default' });+ await engine.executeRaw(`UPDATE sources SET archived = true WHERE id = 'shelf'`);++ for (let i = 0; i < FILLER_PAGES; i++) await engine.putPage(`filler-${i}`, { type: 'note', title: `filler ${i}`, compiled_truth: 'filler' });+ await engine.executeRaw(+ `INSERT INTO content_chunks (page_id, chunk_index, chunk_text, token_count)+ SELECT p.id, g, 'filler chunk ' || p.slug || ' ' || g, 3 FROM pages p, generate_series(0, $1::int - 1) g+ WHERE p.slug LIKE 'filler-%' ORDER BY p.id, g`, [CHUNKS_PER_PAGE]);+ const total = 4 + FILLER_PAGES * CHUNKS_PER_PAGE;+ const early = await Promise.all(EARLY.map(idAtRank));+ const late = await Promise.all(LATE.map(idAtRank));+ lockedId = await idAtRank(total - 1);+ await embedRows([...early, ...late, lockedId], 'hash-of-an-earlier-text');+ return { excluded: [legacy, skipped, deleted, archived], early, late };+}++/** Hold a row lock on the last drifted chunk from another connection until release(). */+async function lockLastDrifted(): Promise<void> {+ let locked!: () => void;+ const held = new Promise<void>(resolve => { locked = resolve; });+ const done = new Promise<void>(resolve => { release = resolve; });+ void getConn().begin(async sql => {+ await sql`SELECT id FROM content_chunks WHERE id = ${lockedId} FOR UPDATE`;+ locked();+ await done;+ });+ await held;+}++d('#7117 content-drift sweep under statement_timeout (Postgres)', () => {+ beforeAll(async () => {+ assertSafeE2eDatabaseUrl(url!);+ engine = await setupDB();+ process.env.GBRAIN_STATEMENT_TIMEOUT = '1500ms';+ slow = new PostgresEngine();+ await slow.connect({ engine: 'postgres', database_url: url!, poolSize: 3 });+ }, 60_000);++ afterAll(async () => {+ release?.();+ if (previousTimeout === undefined) delete process.env.GBRAIN_STATEMENT_TIMEOUT; else process.env.GBRAIN_STATEMENT_TIMEOUT = previousTimeout;+ await slow?.disconnect();+ await teardownDB();+ });++ beforeEach(async () => {+ release?.();+ release = null;+ await engine.executeRaw('TRUNCATE pages CASCADE');+ await engine.executeRaw("DELETE FROM sources WHERE id = 'shelf'");+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'embed.content_drift_sweep.%'");+ });++ test('a cancelled drift pass keeps the batches before the cancel', async () => {+ const { excluded, early, late } = await seed();+ await lockLastDrifted();+ const error = await slow.invalidateContentDriftEmbeddings().then(() => null, (e: unknown) => e);+ release!();+ expect(String((error as Error | null)?.message)).toMatch(/statement timeout/);+ for (const id of early) expect(await vectorKept(id)).toBe(false);+ for (const id of [...late, lockedId, ...excluded]) expect(await vectorKept(id)).toBe(true);+ }, 60_000);++ test('the sweep reports the cancel, keeps its cursor, and the next run completes the pass', async () => {+ const { runContentDriftSweep, readContentDriftSweepStates } = await import('../../src/core/content-drift-sweep.ts');+ const { excluded, early, late } = await seed();+ await lockLastDrifted();+ const first = await runContentDriftSweep(slow);+ release!();+ expect(first.state).toBe('failed');+ expect(first.error).toMatch(/statement timeout/);+ expect(first).toMatchObject({ batches: 1, checked: 5000, drifted: early.length, cursor: await idAtRank(4999) });+ const [saved] = await readContentDriftSweepStates(engine);+ expect(saved!.state).toMatchObject({ cursor: first.cursor, pass_checked: 5000, pass_drifted: early.length, last_completed_at: null });+ expect(saved!.state.last_error?.message).toMatch(/statement timeout/);+ for (const id of early) expect(await vectorKept(id)).toBe(false);+ for (const id of [...late, lockedId]) expect(await vectorKept(id)).toBe(true);++ const second = await runContentDriftSweep(slow);+ expect(second).toMatchObject({ state: 'complete', batches: 2, checked: 4 + FILLER_PAGES * CHUNKS_PER_PAGE - 5000, drifted: late.length + 1, cursor: 0 });+ for (const id of [...early, ...late, lockedId]) expect(await vectorKept(id)).toBe(false);+ for (const id of excluded) expect(await vectorKept(id)).toBe(true);+ const [after] = await readContentDriftSweepStates(engine);+ expect(after!.state).toMatchObject({ cursor: 0, last_pass_checked: 4 + FILLER_PAGES * CHUNKS_PER_PAGE, last_pass_drifted: early.length + late.length + 1, last_error: null });+ }, 60_000);+});diff --git a/test/embed-stale-signature-pagination.serial.test.ts b/test/embed-stale-signature-pagination.serial.test.tsindex 49755b710c..3a0b92bb0e 100644--- a/test/embed-stale-signature-pagination.serial.test.ts+++ b/test/embed-stale-signature-pagination.serial.test.ts@@ -19,6 +19,8 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import type { ChunkInput } from '../src/core/types.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';import { embedStaleForSource, EMBED_PROBE_TEXT } from '../src/core/embed-stale.ts';+import { contentDriftSweepKey, parseContentDriftSweepState } from '../src/core/content-drift-sweep.ts';+import { resolveActiveEmbeddingColumnFromEngine } from '../src/core/search/embedding-column.ts';const DIMS = 1536;const MODEL = 'openai:text-embedding-3-large';@@ -202,14 +204,15 @@ describe('embed --stale page-level signature reconciliation', () => {WHERE page_id = (SELECT id FROM pages WHERE slug = 'hash-mismatch')AND chunk_index = 0`,);- const originalInvalidate = engine.invalidateContentDriftEmbeddings.bind(engine);- engine.invalidateContentDriftEmbeddings = async () => 0;- try {- await runEmbedCore(engine, { stale: true, catchUp: true, quiet: true });- } finally {- engine.invalidateContentDriftEmbeddings = originalInvalidate;- }+ // The content-drift sweep would repair the mismatch first; a pass that+ // completed just now over a large corpus keeps it idle for this run.+ const column = (await resolveActiveEmbeddingColumnFromEngine(engine)).name;+ await engine.setConfig(contentDriftSweepKey(column), JSON.stringify({+ ...parseContentDriftSweepState(null), last_completed_at: new Date().toISOString(), last_pass_checked: 10_000_000,+ }));+ const result = await runEmbedCore(engine, { stale: true, catchUp: true, quiet: true });+ expect(result.content_drift?.state).toBe('waiting');expect(await pageSignature('hash-mismatch')).toBeNull();});diff --git a/test/embed-stale.test.ts b/test/embed-stale.test.tsindex 488aadac8e..905fc49d8f 100644--- a/test/embed-stale.test.ts+++ b/test/embed-stale.test.ts@@ -84,6 +84,7 @@ describe('embedStaleForSource', () => {chunksProcessed: 0,pagesProcessed: 0,invalidated: 0,+ contentDrift: expect.objectContaining({ scope: 'source:default', state: 'complete', checked: 0, drifted: 0, batches: 1 }),lastCursor: null,done: true,aborted: false,diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 2405d4d5c9..0d0c34fbce 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -1902,6 +1902,18 @@"name": "embed_backfill_stalled","status": "ok"},+ {+ "category": "ops",+ "details": {+ "code": "content_drift_sweep",+ "docs": "docs/guides/troubleshooting.md#content-drift-sweep",+ "scopes": []+ },+ "elapsed_ms": "<volatile>",+ "message": "The content-drift sweep has not run yet; it runs inside embed --stale and the embed jobs.",+ "name": "content_drift_sweep",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 1b2d41942f..985f4efcf7 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -1958,6 +1958,18 @@"name": "embed_backfill_stalled","status": "ok"},+ {+ "category": "ops",+ "details": {+ "code": "content_drift_sweep",+ "docs": "docs/guides/troubleshooting.md#content-drift-sweep",+ "scopes": []+ },+ "elapsed_ms": "<volatile>",+ "message": "The content-drift sweep has not run yet; it runs inside embed --stale and the embed jobs.",+ "name": "content_drift_sweep",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex d8e4e0317f..ecf818f0d0 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -689,6 +689,10 @@"category": "ops","name": "embed_backfill_stalled"},+ {+ "category": "ops",+ "name": "content_drift_sweep"+ },{"category": "ops","name": "connector_account_mismatch"diff --git a/test/fixtures/goldens/sql-text/chunks.json b/test/fixtures/goldens/sql-text/chunks.jsonindex bce01d2a65..b4d3776e13 100644--- a/test/fixtures/goldens/sql-text/chunks.json+++ b/test/fixtures/goldens/sql-text/chunks.json@@ -414,8 +414,8 @@"params": ["array<>"],- "sql": "UPDATE content_chunks cc SET \"embedding\" = NULL, embedded_at = NULL, embedded_text_hash = NULL, embedding_pending_since = now() FROM pages p WHERE cc.page_id = p.id AND p.source_id=ANY($1::text[]) AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived) AND p.deleted_at IS NULL AND cc.\"embedding\" IS NOT NULL AND cc.embedded_text_hash IS NOT NULL AND cc.embedded_text_hash <> md5(cc.chunk_text) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND (CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576) RETURNING cc.page_id",- "textSha256": "0fb0f0109e484923bce97a50af889d1656cea824024ea92f6c40fee587797d11"+ "sql": "WITH b AS (SELECT id FROM content_chunks WHERE id > 0 ORDER BY id LIMIT 5000), w AS (UPDATE content_chunks cc SET \"embedding\" = NULL, embedded_at = NULL, embedded_text_hash = NULL, embedding_pending_since = now() FROM b, pages p WHERE cc.id = b.id AND cc.page_id = p.id AND p.source_id=ANY($1::text[]) AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived) AND p.deleted_at IS NULL AND cc.\"embedding\" IS NOT NULL AND cc.embedded_text_hash IS NOT NULL AND cc.embedded_text_hash <> md5(cc.chunk_text) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND (CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576) RETURNING 1) SELECT (SELECT max(id) FROM b) AS last_id, (SELECT count(*) FROM b)::int AS checked, (SELECT count(*) FROM w)::int AS drifted",+ "textSha256": "e4ab4d9f62a62d4acbe361aee22049a5f8dbe556ce2eb5822c5eba6c8ee4b262"},{"event": "commit",@@ -448,8 +448,8 @@"array<>","string"],- "sql": "UPDATE content_chunks cc SET \"embedding\" = NULL, embedded_at = NULL, embedded_text_hash = NULL, embedding_pending_since = now() FROM pages p WHERE cc.page_id = p.id AND p.source_id=ANY($1::text[]) AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived) AND p.deleted_at IS NULL AND cc.\"embedding\" IS NOT NULL AND cc.embedded_text_hash IS NOT NULL AND cc.embedded_text_hash <> md5(cc.chunk_text) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND (CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576) AND p.source_id = $2 RETURNING cc.page_id",- "textSha256": "69ae8c768a3a7efcd985c7980cb3166fe36b15ecc3da10672b1d0953a11a797f"+ "sql": "WITH b AS (SELECT id FROM content_chunks WHERE id > 0 ORDER BY id LIMIT 5000), w AS (UPDATE content_chunks cc SET \"embedding\" = NULL, embedded_at = NULL, embedded_text_hash = NULL, embedding_pending_since = now() FROM b, pages p WHERE cc.id = b.id AND cc.page_id = p.id AND p.source_id=ANY($1::text[]) AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived) AND p.deleted_at IS NULL AND cc.\"embedding\" IS NOT NULL AND cc.embedded_text_hash IS NOT NULL AND cc.embedded_text_hash <> md5(cc.chunk_text) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND (CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576) AND p.source_id = $2 RETURNING 1) SELECT (SELECT max(id) FROM b) AS last_id, (SELECT count(*) FROM b)::int AS checked, (SELECT count(*) FROM w)::int AS drifted",+ "textSha256": "364dd0839c4cecd030d0a136025343116458e060b6f36c9ba9d099736c249858"},{"event": "commit",