Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: stop autopilot re-running stalled embed-backfills, mis-pinned connectors and brain-wide connector cycles (#6803 parts 1 and 4)

garrytaned3c6b6a08bc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9554c2767a..9e5bd29143 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,52 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.60.258.0] - 2026-10-16
+
+**Autopilot stops re-running the same failing jobs forever: a background embedding catch-up that can't make progress backs off and stops, a connector whose login changed is skipped instead of retried every few minutes, and a connector's cycle no longer walks the whole brain.** On a large brain three loops were burning the queue around the clock. A background embedding catch-up that was blocked by pages it could not rebuild failed the same way every 10 minutes, about 96 times a day, with nothing embedded. A Google or GitHub source whose credential now belongs to a different account was refused (correctly) and then tried again at every autopilot interval. And every connector's maintenance cycle re-read every page in the brain, not just its own, so on a brain with hundreds of thousands of pages it ran past its 30-minute deadline, never recorded that it finished, and started the same full walk again.
+
+### What you'd see
+
+| Situation | Before | Now |
+|---|---|---|
+| A background embed-backfill ends with nothing embedded and the same blocked pages | resubmitted every 10 minutes, dead-letters every time | waits 20, then 40 minutes; after 3 identical failures automatic submission stops (`stalled`) |
+| A retry inside one embed-backfill job finds the same blockers | runs again | dead-letters at once with `embed_backfill_stalled` |
+| Finding what blocks it | not reported | doctor `embed_backfill_stalled` names up to 10 blocked pages, their kind and queue reason |
+| Previewing the repair | none | `gbrain projections drain --dry-run` lists the queued pages without rebuilding |
+| A Google or GitHub source whose credential is now another account | synced and refused every autopilot interval | refused once, then skipped (`unavailable-path`, code `connector_account_changed`); doctor `connector_account_mismatch` lists it |
+| A connector source's autopilot cycle on a large brain | extract_facts and emotional weight walk every page in the brain; times out at 30 minutes and repeats | only that source's pages changed since its last cycle |
+
+### If you're stuck in the loop now
+
+Before upgrading, on the brain host:
+
+```bash
+gbrain doctor --json # embed_backfill / text_projection_readiness / sync_freshness
+gbrain projections drain --limit 500 # retries the queued Markdown and code pages; each failure prints why and a next step
+gbrain sources list # find the connector source whose sync is refused with connector_account_changed
+gbrain sources archive <source> # if the old account is retired; or restore its credential, then gbrain sync --source <source>
+```
+
+After upgrading the loops stop by themselves. To clear what remains:
+
+```bash
+gbrain doctor --only embed_backfill_stalled # names the blocked pages
+gbrain projections drain --dry-run # preview, rebuilds nothing
+gbrain projections drain # the repair
+gbrain doctor --only connector_account_mismatch # names the skipped connector sources
+gbrain sync --source <source> # after restoring the pinned account's credential
+```
+
+Nothing runs on upgrade: the drain and the re-sync are explicit steps. Automatic embed-backfill re-arms by itself once the blocked pages or the stale chunks change, or a run embeds anything. A source skip clears when a sync passes the account check, or when the source's connector config changes. `gbrain embed --stale` and `gbrain jobs submit embed-backfill` are never held back.
+
+### Itemized changes
+
+- **Embed-backfill stall cap** (`src/core/embed-backfill-stall.ts`, `src/core/embed-backfill-submit.ts`, `src/core/minions/handlers/embed-backfill.ts`). A run that embeds nothing records a blocker fingerprint (stale chunk count, archived embedding work, pages still waiting for a projection) in its job progress. `submitEmbedBackfill` backs off by the cooldown times 2 per identical failure and returns the new `stalled` status at 3 (`EMBED_BACKFILL_STALL_LIMIT`). A `delayed` job (between retries) now counts as in flight. The handler throws an unrecoverable error when a retry finds the fingerprint it recorded, so the job dead-letters instead of using its remaining attempts. The sync, connector, GitHub and federation submitters report `stalled` as a skip.
+- **Mis-pinned connector skip** (`src/core/persistence/connector-account-mismatch.ts`, `connector-state.ts`, `connector-sync.ts`, `src/commands/autopilot-fanout.ts`, `src/commands/autopilot-dispatch.ts`). An `account_changed` or `account_unresolved` refusal records `account_mismatch` with a digest of the source's connector config in the connector state; a passing account check clears it. The fan-out puts such a source in the `unavailable-path` bucket and the freshness loop skips it with `freshness_source_path_skipped` (`code: connector_account_changed`), while the recorded config digest matches the current one. Both fail open when the state cannot be read.
+- **Connector cycle scope** (`src/core/cycle.ts`, `src/core/cycle/extract-facts.ts`, `src/core/minions/handlers/autopilot-cycle.ts`). A connector source's cycle passes `sourceChangedSince` (its last completed cycle): `extract_facts` drains its watermark for that source instead of a full walk, and `recompute_emotional_weight` recomputes only the source's changed pages. A full `extract_facts` walk under a source now lists only that source's slugs.
+- **Doctor**: new `embed_backfill_stalled` (fix `gbrain projections drain`, preview `gbrain projections drain --dry-run --json`) and `connector_account_mismatch` (fix `gbrain sync --source <source>` after restoring the credential) checks. New error code `embed_backfill_stalled`; `gbrain errors connector_account_changed` describes the skip.
+- **`gbrain projections drain --dry-run`** lists the queued rows (rows that last failed first, with their reason) up to `--limit` (default 50) and rebuilds nothing; `--json` gives `{pending, failed, rows}`.
+
## [0.60.257.0] - 2026-10-16
**Doctor stops reading real errors as "not migrated yet", recall and think use your query prefix everywhere, `gbrain waiting` stops listing bank alerts as people, and a surviving `gbrain serve` takes back hook IPC.** This is fix wave 18b: the older backlog nobody else had picked up, plus what wave 17 deferred. Doctor checks and four write paths used to swallow any missing column as a pre-migration brain; they now tolerate only the exact object they need and fail with the real error otherwise. `think`, `synthesize` and six more query paths embedded questions without the brain's `embedding_query_prefix`, so their retrieval drifted from hybrid search. Gmail bulk and no-reply mail opened reply-owed loops, and muting a sender left its old loops open. On Postgres, an aborted transaction left its statement running on the server.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 090a003bde..e57679c135 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -640,7 +640,9 @@ More: [docs/guides/write-refusals.md#drain-connection-lost](../../docs/guides/wr
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| The connector credential resolves to a different account than the source is pinned to. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+| The connector credential resolves to a different account than the source is pinned to. | A connector source is pinned to the account it first synced, so a swapped credential can never import another account's mail, calendar or repositories into it. The refused run records the mismatch, and autopilot skips the source (unavailable-path) instead of retrying it every interval (#6803). | Restore the credential for the pinned account and run gbrain sync --source <id> (it clears the skip once the account check passes), or add a new source for the new account and archive this one with gbrain sources archive <id>. gbrain doctor --only connector_account_mismatch lists every affected source. Run: gbrain doctor --only connector_account_mismatch --json | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/write-refusals.md#connector-account-changed](../../docs/guides/write-refusals.md#connector-account-changed)
### connector_fence_below_timeline
@@ -946,6 +948,16 @@ More: [docs/operations/spend-controls.md#dream-paid-loop-breaker-dreambreakermax
|---|---|---|---|---|---|---|
| Only a failed, non-running embedding effect can be explicitly retried. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### embed_backfill_stalled
+
+<a id="embed_backfill_stalled"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A source's automatic embed-backfill failed the same way several times with nothing embedded, so automatic backfill for it backs off and then stops. | The only remaining work sits on pages whose text projection cannot be rebuilt (a rebuild_failed projection, or an image page only its importer rebuilds). Each identical run spent a worker slot and dead-lettered; after three, automatic submission stops until the blocked pages or the stale chunks change, or a run embeds something (#6803). Explicit gbrain embed --stale and gbrain jobs submit embed-backfill are not gated. | Run gbrain doctor --only embed_backfill_stalled to see the blocked pages, preview the repair with gbrain projections drain --dry-run, then run gbrain projections drain; it names each page that still fails and its next step. Run: gbrain doctor --only embed_backfill_stalled --json | agent | `gbrain doctor --json` | 1 | no |
+
+More: [docs/guides/repair.md#embed-backfill-stalled](../../docs/guides/repair.md#embed-backfill-stalled)
+
### embedding_auth_failed
<a id="embedding_auth_failed"></a>
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 30a5e9f887..0fb9d6def5 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -298,8 +298,32 @@ To drain now:
gbrain projections drain # until every page queued at the start was tried once
gbrain projections drain --limit 5000
gbrain projections drain --json # {rebuilt, superseded, failed: [{source_id, slug, reason}], remaining}
+gbrain projections drain --dry-run # rebuild nothing: list the queued rows, rows that last failed first
```
+`--dry-run` is the preview: it reads the queue only and prints each row it
+would try with its queue reason (`rebuild_failed` rows first), up to `--limit`
+(default 50); `--json` gives `{pending, failed, rows}`.
+
+<a id="embed-backfill-stalled"></a>
+**An automatic embed-backfill that keeps failing the same way.** A page whose
+projection cannot be rebuilt (`rebuild_failed`) leaves its chunks
+unembeddable, so every automatic `embed-backfill` for that source ends
+`incomplete; N chunks remain and M projections are blocked` with nothing
+embedded. After the first such failure the next automatic submission waits
+twice the cooldown (20, then 40 minutes); after three identical failures
+automatic submission stops for that source, and a retry inside one job that
+finds the same blockers dead-letters instead of running again. Doctor
+`embed_backfill_stalled` names the blocked pages, their page kind and queue
+reason. Preview with `gbrain projections drain --dry-run`, then run
+`gbrain projections drain`: it retries each queued Markdown or code page in the
+foreground and prints why a page still fails and its next step. Image and media
+pages are rebuilt only by their importer (`gbrain sync --full --source <id>` or
+`gbrain embed --stale --images --source <id>`). Automatic backfill resumes by
+itself once the blocked pages or the stale chunks change, or a run embeds
+anything; `gbrain embed --stale --source <id>` and
+`gbrain jobs submit embed-backfill` are never held back.
+
| Exit | Meaning |
| --- | --- |
| 0 | Nothing tried failed. "The projection backlog is empty." appears only when `remaining` is 0. |
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 34924c5f34..9620aa4296 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -69,7 +69,7 @@ of making a duplicate.
| `invalid_source_uri` | `invalid_source_uri` | The brain has shared skillpacks, and the page's stored `source_uri` is a `file:` URI that cannot be turned into a local path, so gbrain cannot prove the write stays outside a skillpack. Shared-skill protection stays on. | The source owner inspects the page's stored `source_uri` on the brain host and replaces it with an absolute file URI or clears it; there is no dedicated command yet. Retry with a **new** request ID. |
| `queue_capacity` | `queue_capacity` | Admission would exceed a write-journal limit. Existing requests keep their place; nothing is evicted. For the cumulative limits (lifetime request IDs and receipt bytes), `detail` names the limit, for example `principal_lifetime_ids`; for the outstanding-request caps, `detail` carries the counts (`outstanding=<used> limit=<limit>`), and a managed `gbrain sync` drain waits them out ([`write_capacity`](#drain-write-capacity)). | For a cumulative limit, run the printed `gbrain config set persistence.limits.<limit> <value>` (sized for about one more year at the current rate), then retry with the **same** request ID. For outstanding-request, queued-byte or recovery-byte limits, let outstanding requests finish and check `gbrain sources writer status`. See [bounded admission and retention](concurrent-writes.md#bounded-admission-and-retention). |
| <a id="checkpoint-validation-timeout"></a>`index_building`, `index_missing` or `indexes_valid` | `checkpoint_validation_timeout` | A managed sync's checkpoint validation (the check that every page receipt of the run committed) hit the coordinator's 5-second statement timeout on a large `persistence_requests` table. The checkpoint request failed terminally instead of being retried ahead of every other write to the source, so other writes proceed; `last_commit` is unchanged and every page the run already committed stays committed. `detail` says which of three states the request indexes were in when the hint was built. | `index_building`: migration 179 is still building the indexes; wait (doctor `persistence_request_indexes` shows progress), then run the printed retry. `index_missing`: run `gbrain repair request-indexes --apply` (it drops an INVALID index and rebuilds it concurrently on Postgres), then the printed retry. `indexes_valid`: run the printed retry once; if it times out again, report the request id with the `persistence_request_indexes` and `persistence_request_growth` entries of `gbrain doctor --json`. The retry is `gbrain sync --source <source> --no-pull --retry-failed` plus the run's `--repo` base and cursor options (`--full`, `--working-tree`, `--src-subpath`, `--exclude`, `--include-hidden`, `--strategy`) and saved processing flags, so it resumes the same cursor. Do not cancel the request: a cancelled checkpoint still blocks the next one. |
-| <a id="connector-account-changed"></a>`account_changed`, `account_unresolved` | `connector_account_changed` | A managed Google or GitHub connector's credential resolves to a different account than the one pinned for the source (Google email, GitHub App installation or login), or to no account at all. Google checks every enabled service before any service runs. Nothing was imported. No reset flag authorizes an account change. | The suggestion gives two branches with real values. (A) Restore the credential for the pinned account (the configured `g_token_env`, `g_token_command`, vault credential, `gh_token_env` or GitHub App key), then `gbrain sync --source <source>`. (B) For a deliberate change, add a new source for the new account (`gbrain google setup --account <email>`, or `gbrain sources add <new-id> --kind github … --app-install <id>`), then `gbrain sources archive <source>`; existing pages stay under the old source. |
+| <a id="connector-account-changed"></a>`account_changed`, `account_unresolved` | `connector_account_changed` | A managed Google or GitHub connector's credential resolves to a different account than the one pinned for the source (Google email, GitHub App installation or login), or to no account at all. Google checks every enabled service before any service runs. Nothing was imported. No reset flag authorizes an account change. | The suggestion gives two branches with real values. (A) Restore the credential for the pinned account (the configured `g_token_env`, `g_token_command`, vault credential, `gh_token_env` or GitHub App key), then `gbrain sync --source <source>`. (B) For a deliberate change, add a new source for the new account (`gbrain google setup --account <email>`, or `gbrain sources add <new-id> --kind github … --app-install <id>`), then `gbrain sources archive <source>`; existing pages stay under the old source. The refused run is recorded, and autopilot then skips the source (an `unavailable-path` skip in the fan-out, `freshness_source_path_skipped` with `code: connector_account_changed` in the freshness loop) instead of retrying it every interval; doctor `connector_account_mismatch` lists such sources. A `gbrain sync --source <source>` that passes the account check clears the skip, and so does a change to the source's connector config (one more automatic try). |
| <a id="connector-intent-outdated"></a>`pre_upgrade` | `connector_intent_outdated` | A connector write was admitted in the intent format retired in v0.60.11.0. With detail `pre_upgrade` it was admitted before this brain's upgrade; otherwise a connector host older than v0.60.11.0 admitted it. The consumer recovers any file publication in progress first, then fails the request. | `pre_upgrade`: nothing to do; the item is fetched again on the next `gbrain sync --source <source>` under a new request ID. Otherwise: `gbrain upgrade` on the host that runs connector jobs, then `gbrain sync --source <source>`. |
| <a id="invalid-connector-text"></a>`invalid_connector_text` | `invalid_connector_text` | A Google or GitHub item's identity field (a path, item id or account) contains a NUL or an unpaired UTF-16 surrogate, which cannot be stored. Prose (bodies, subjects, titles) is cleaned at render time and never refused. The item is counted toward a hold; the rest of the sync continues. | Nothing to run for one refusal. Once the item is held, `gbrain sources status <source>` names it; after the provider data is fixed, `gbrain sources retry-held <source>`, then `gbrain sync --source <source>`. |
| <a id="connector-holds-exhausted"></a>`connector_holds_exhausted` | `connector_holds_exhausted` | A Google or GitHub source already holds 100 items and this sync would hold another. The sync stopped without advancing its cursor. So many held items usually means a source-wide problem (a broken renderer, a revoked scope), not bad items. | `gbrain sources status <source>` to see the held items and their error codes, fix the cause, then `gbrain sources retry-held <source>` and `gbrain sync --source <source>`. `gbrain sync --source <source> --full` also clears every hold. |
diff --git a/src/cli/commands/projections.ts b/src/cli/commands/projections.ts
index 18fba7f75a..06f3ebf1f2 100644
--- a/src/cli/commands/projections.ts
+++ b/src/cli/commands/projections.ts
@@ -13,6 +13,7 @@ export async function run(args: string[], ctx: CliDispatchContext): Promise<void
return;
}
const json = args.includes('--json');
+ const dryRun = args.includes('--dry-run');
const { OperationError } = await import('../../core/ops/contract.ts');
const { reportPersistenceCliError } = await import('../../commands/persistence-delegate.ts');
const refuse = async (error: InstanceType<typeof OperationError>) => {
@@ -21,7 +22,7 @@ export async function run(args: string[], ctx: CliDispatchContext): Promise<void
};
const limitAt = args.indexOf('--limit');
const limitValue = limitAt === -1 ? undefined : args[limitAt + 1];
- const known = new Set(['drain', '--json', '--limit', ...(limitValue === undefined ? [] : [limitValue])]);
+ const known = new Set(['drain', '--json', '--dry-run', '--limit', ...(limitValue === undefined ? [] : [limitValue])]);
const unknown = args.find(arg => !known.has(arg));
if (args[0] !== 'drain' || unknown !== undefined) {
await refuse(new OperationError('invalid_params', `Unknown projections argument '${unknown ?? args[0]}'.`,
@@ -51,6 +52,19 @@ export async function run(args: string[], ctx: CliDispatchContext): Promise<void
const { createProgress } = await import('../../core/progress.ts');
const { cliOptsToProgressOptions } = await import('../../core/cli-options.ts');
const engine = await ctx.connectEngine();
+ if (dryRun) {
+ // #6803: the preview reads the queue and rebuilds nothing.
+ try {
+ const preview = await projections.previewProjectionDrain(engine, limit ?? 50);
+ if (json) { await writeStdoutFinal(JSON.stringify(preview) + '\n'); return; }
+ const lines = preview.rows.map(row => ` ${row.reason === 'rebuild_failed' ? 'last failed' : 'queued'}: ${row.source_id}/${row.slug} (${row.reason}, since ${row.updated_at})`);
+ await writeStdoutFinal([`projections drain --dry-run: ${preview.pending} queued, ${preview.failed} last failed; nothing was rebuilt.`, ...lines,
+ preview.pending ? 'Run `gbrain projections drain` to rebuild them; a page that fails again is printed with its next step.' : 'The projection backlog is empty.'].join('\n') + '\n');
+ } finally {
+ await finishCliTeardown({ engine });
+ }
+ return;
+ }
try {
const result = await projections.drainProjections(engine, { limit, progress: createProgress(cliOptsToProgressOptions(getCliOptions())) });
if (json) {
diff --git a/src/commands/autopilot-dispatch.ts b/src/commands/autopilot-dispatch.ts
index bc66f86c60..662162cabe 100644
--- a/src/commands/autopilot-dispatch.ts
+++ b/src/commands/autopilot-dispatch.ts
@@ -8,7 +8,8 @@ import type { BrainEngine } from '../core/engine.ts';
import type { MinionQueue } from '../core/minions/queue.ts';
import { loadAllSources, parseSourceConfig, sourceConfigHasRemoteUrl, sourceLocalPathSkipWarning, type SourceRow } from '../core/sources-load.ts';
import { isConnectorSourceKind } from '../core/persistence/connector-identity.ts';
-import { attemptedConnectorSourceIds } from '../core/persistence/connector-state.ts';
+import { attemptedConnectorSourceIds, type ConnectorAccountMismatch } from '../core/persistence/connector-state.ts';
+import { connectorAccountMismatches, connectorAccountMismatchSkipWarning } from '../core/persistence/connector-account-mismatch.ts';
import { AUTOPILOT_GIT_PULL_KEY, automaticGitPullDisabled, automaticSyncPull } from '../core/persistence/automatic-sync-policy.ts';
import { isSyncDisabledConfig } from '../core/sync-policy.ts';
import { automaticSyncSkip, loadActivationPendingSourceIds, reportAutomaticSyncSkip, skipActivationPendingSync } from '../core/sync-policy.ts';
@@ -261,6 +262,8 @@ export async function dispatchFreshnessSyncs(
const { isFederatedV2Enabled } = await import('../core/feature-flags.ts');
if (await isFederatedV2Enabled(engine)) {
const attempted = await attemptedConnectorSourceIds(engine).catch(() => null);
+ // #6803: unreadable mismatch records fail open; the connector sync refuses again on its own.
+ const mismatched = await connectorAccountMismatches(engine).catch(() => new Map<string, ConnectorAccountMismatch>());
const sources = await loadAllSources(engine);
// #6451: one status line per tick when the operator turned automatic pulls off.
if (await automaticGitPullDisabled(engine)) {
@@ -273,7 +276,7 @@ export async function dispatchFreshnessSyncs(
const now = Date.now();
for (const src of sources) {
if (isConnectorSourceKind(parseSourceConfig(src.config).kind)) {
- await dispatchConnectorFreshnessSync(queue, src, attempted, activationPending, { intervalMs, now, slot, timeoutMs, jsonMode });
+ await dispatchConnectorFreshnessSync(queue, src, attempted, activationPending, mismatched, { intervalMs, now, slot, timeoutMs, jsonMode });
continue;
}
if (!src.local_path) continue;
@@ -350,11 +353,18 @@ async function dispatchConnectorFreshnessSync(
src: SourceRow,
attempted: Set<string> | null,
activationPending: Awaited<ReturnType<typeof loadActivationPendingSourceIds>>,
+ mismatched: ReadonlyMap<string, ConnectorAccountMismatch>,
{ intervalMs, now, slot, timeoutMs, jsonMode }: { intervalMs: number; now: number; slot: string; timeoutMs: number; jsonMode: boolean },
): Promise<void> {
if (isSyncDisabledConfig(src.config)) return;
if (skipActivationPendingSync(activationPending, src.id, 'freshness_sync_skipped', jsonMode, (l) => process.stderr.write(l + '\n'))) return;
if (connectorAwaitingFirstSync(src, attempted, jsonMode)) return;
+ const mismatch = mismatched.get(src.id);
+ if (mismatch) {
+ const reason = connectorAccountMismatchSkipWarning(src.id, mismatch);
+ process.stderr.write((jsonMode ? JSON.stringify({ event: 'freshness_source_path_skipped', source_id: src.id, code: 'connector_account_changed', reason }) : reason) + '\n');
+ return;
+ }
const ageMs = now - (src.last_sync_at ? new Date(src.last_sync_at).getTime() : 0);
if (ageMs < intervalMs) return;
try {
diff --git a/src/commands/autopilot-fanout.ts b/src/commands/autopilot-fanout.ts
index 1347da3b3d..e24f7c3838 100644
--- a/src/commands/autopilot-fanout.ts
+++ b/src/commands/autopilot-fanout.ts
@@ -41,7 +41,8 @@ import type { MinionQueue } from '../core/minions/queue.ts';
import { SOURCE_FRESHNESS_PHASES, MAINTENANCE_PHASES, LAST_GLOBAL_AT_KEY } from '../core/cycle.ts';
import { CONNECTOR_SOURCE_PHASES } from '../core/cycle/phase-scope.ts';
import { isConnectorSourceKind } from '../core/persistence/connector-identity.ts';
-import { attemptedConnectorSourceIds } from '../core/persistence/connector-state.ts';
+import { attemptedConnectorSourceIds, type ConnectorAccountMismatch } from '../core/persistence/connector-state.ts';
+import { connectorAccountMismatches, connectorAccountMismatchSkipWarning } from '../core/persistence/connector-account-mismatch.ts';
import { parseSourceConfig, sourceLocalPathSkipWarning } from '../core/sources-load.ts';
import { automaticSyncPull } from '../core/persistence/automatic-sync-policy.ts';
import { automaticSyncSkip, loadActivationPendingSourceIds, reportAutomaticSyncSkip } from '../core/sync-policy.ts';
@@ -368,6 +369,7 @@ export function selectSourcesForDispatch(
cooldownOpts: CooldownOpts = { baseMin: FAILURE_COOLDOWN_BASE_MIN, capMin: FAILURE_COOLDOWN_CAP_MIN },
pathExists: (path: string) => boolean = () => true,
connectorIds: ReadonlySet<string> = new Set(),
+ accountMismatches: ReadonlyMap<string, ConnectorAccountMismatch> = new Map(),
): {
dispatch: SourceRow[];
skippedFresh: SourceRow[];
@@ -382,7 +384,9 @@ export function selectSourcesForDispatch(
const cooldown: SourceRow[] = [];
const unavailablePath: Array<SourceRow & { skip_warning: string }> = [];
for (const s of sources) {
- const skipWarning = s.local_path && !connectorIds.has(s.id) ? sourceLocalPathSkipWarning(s.id, s.local_path, pathExists, s.config) : null;
+ const mismatch = connectorIds.has(s.id) ? accountMismatches.get(s.id) : undefined;
+ const skipWarning = mismatch ? connectorAccountMismatchSkipWarning(s.id, mismatch)
+ : s.local_path && !connectorIds.has(s.id) ? sourceLocalPathSkipWarning(s.id, s.local_path, pathExists, s.config) : null;
if (skipWarning) {
unavailablePath.push({ ...s, skip_warning: skipWarning });
continue;
@@ -542,6 +546,8 @@ export async function dispatchPerSource(
}
const pathExists = opts.pathExists ?? existsSync;
+ // #6803: a connector whose credential resolves to another account is unavailable until the operator repins it.
+ const accountMismatches = connectorIds.size ? await connectorAccountMismatches(engine).catch(() => new Map<string, ConnectorAccountMismatch>()) : new Map<string, ConnectorAccountMismatch>();
const { dispatch, skippedFresh, skippedCap, skippedCooldown, skippedUnavailablePath } =
selectSourcesForDispatch(
sources,
@@ -552,6 +558,7 @@ export async function dispatchPerSource(
cooldownOpts,
pathExists,
connectorIds,
+ accountMismatches,
);
for (const src of skippedUnavailablePath) {
diff --git a/src/commands/doctor/checks/connector-account-mismatch.ts b/src/commands/doctor/checks/connector-account-mismatch.ts
new file mode 100644
index 0000000000..0117e85347
--- /dev/null
+++ b/src/commands/doctor/checks/connector-account-mismatch.ts
@@ -0,0 +1,62 @@
+/**
+ * connector_account_mismatch doctor check (#6803): connector sources whose
+ * last sync refused with `connector_account_changed` because the credential
+ * resolves to a different account than the source is pinned to. Autopilot
+ * skips them (unavailable-path) instead of retrying every interval, so this
+ * check is where the operator learns a source has stopped importing. The fix
+ * is the operator's: restore the credential for the pinned account and sync
+ * by hand, or archive the source after adding one for the new account.
+ * Account identities stay out of the message; the sync refusal names them locally.
+ */
+import type { BrainEngine } from '../../../core/engine.ts';
+import type { Check } from '../../doctor.ts';
+import { doctorVerify } from '../check-fix.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+import { connectorAccountMismatches } from '../../../core/persistence/connector-account-mismatch.ts';
+
+const DOCS = 'docs/guides/write-refusals.md#connector-account-changed';
+
+export async function connectorAccountMismatchCheck(engine: BrainEngine): Promise<Check> {
+ try {
+ const found = [...(await connectorAccountMismatches(engine))].sort(([a], [b]) => a.localeCompare(b));
+ if (found.length === 0) return { name: 'connector_account_mismatch', status: 'ok', message: 'No connector source is waiting for its account to be repinned.' };
+ const [first] = found[0]!;
+ const listed = found.map(([id, m]) => `${id} (${m.detail === 'account_unresolved' ? 'credential resolves to no account' : 'credential resolves to a different account'} since ${m.at})`).join(', ');
+ return {
+ name: 'connector_account_mismatch',
+ status: 'warn',
+ message: `${found.length} connector source(s) stopped importing because their credential no longer resolves to the pinned account: ${listed}. `
+ + 'Autopilot skips them until they are repinned, so nothing is retried in the background. '
+ + `Restore the credential for the pinned account, then run gbrain sync --source <id> (the sync prints the pinned and resolved accounts). `
+ + 'For a deliberate account change, add a new source for the new account and archive this one with gbrain sources archive <id>; its pages stay. '
+ + `Changing the source's connector config also lets autopilot try it once more. See ${DOCS}.`,
+ details: { code: 'connector_account_changed', sources: found.map(([id, m]) => ({ source_id: id, detail: m.detail, since: m.at })), docs: DOCS },
+ fix: {
+ argv: ['gbrain', 'sync', '--source', first],
+ consent: ['credentials'],
+ actor: 'user',
+ why: `The credential for ${first} must first be restored to the account the source is pinned to; this sync then checks the account and clears the skip, or refuses again naming both accounts.`,
+ user_message: `Your connector source ${first} stopped importing: its credential now belongs to a different account than the one it was set up with. `
+ + `Restore that account's credential and run the sync, or tell me to set up a new source for the new account and archive this one.`,
+ verify: doctorVerify('connector_account_mismatch'),
+ docs: DOCS,
+ requires_exclusive: false,
+ },
+ };
+ } catch (error) {
+ return { name: 'connector_account_mismatch', status: 'warn', message: `Connector account state could not be read: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,
+ details: { health: 'unknown' }, fix_unavailable_reason: 'check_errored' };
+ }
+}
+
+async function runConnectorAccountMismatch(ctx: DoctorContext): Promise<Check[]> {
+ const checks: Check[] = [];
+ checks.push({ ...(await connectorAccountMismatchCheck(connectedEngine(ctx))), name: 'connector_account_mismatch' });
+ return checks;
+}
+
+export const connectorAccountMismatchEntry: DoctorEntry = {
+ name: 'connector_account_mismatch',
+ emits: ['connector_account_mismatch'],
+ run: runConnectorAccountMismatch,
+};
diff --git a/src/commands/doctor/checks/embed-backfill-stalled.ts b/src/commands/doctor/checks/embed-backfill-stalled.ts
new file mode 100644
index 0000000000..b8f8f51ac1
--- /dev/null
+++ b/src/commands/doctor/checks/embed-backfill-stalled.ts
@@ -0,0 +1,82 @@
+/**
+ * embed_backfill_stalled doctor check (#6803): sources whose automatic
+ * embed-backfill keeps failing the same way with nothing embedded. The
+ * submit gate (embed-backfill-stall.ts) backs these off and then stops
+ * queueing them; this check names the pages blocking them and the repair.
+ *
+ * The usual blocker is a page whose text projection cannot be rebuilt
+ * (`page_projection_jobs.reason = 'rebuild_failed'`), which the backfill's
+ * bounded recovery retries silently. `gbrain projections drain` retries it
+ * in the foreground and prints why it fails and what to do; its `--dry-run`
+ * is the preview. Image and media pages are rebuilt only by their importer.
+ * Nothing here runs a repair.
+ */
+import type { BrainEngine } from '../../../core/engine.ts';
+import type { Check } from '../../doctor.ts';
+import { doctorVerify } from '../check-fix.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+import { EMBED_BACKFILL_STALL_LIMIT, readEmbedBackfillBlockers, readEmbedBackfillStall } from '../../../core/embed-backfill-stall.ts';
+
+const DOCS = 'docs/guides/repair.md#embed-backfill-stalled';
+const LISTED = 10;
+
+export async function embedBackfillStalledCheck(engine: BrainEngine): Promise<Check> {
+ try {
+ const sources = await engine.executeRaw<{ source_id: string }>(
+ `SELECT DISTINCT data->>'sourceId' AS source_id FROM minion_jobs
+ WHERE name = 'embed-backfill' AND status IN ('failed', 'dead') AND progress ? 'stall'
+ AND finished_at > now() - interval '7 days'`);
+ const stalled = [];
+ for (const { source_id } of sources) {
+ const stall = source_id ? await readEmbedBackfillStall(engine, source_id) : null;
+ if (!stall) continue;
+ const current = await readEmbedBackfillBlockers(engine, source_id, stall.signature);
+ if (current.fingerprint !== stall.fingerprint) continue;
+ const reasons = new Map((await engine.executeRaw<{ slug: string; reason: string }>(
+ `SELECT j.slug, j.reason FROM page_projection_jobs j JOIN sources s ON s.incarnation = j.source_incarnation
+ WHERE s.id = $1 AND j.slug = ANY($2::text[])`, [source_id, current.pages.slice(0, LISTED).map(p => p.slug)])).map(r => [r.slug, r.reason]));
+ stalled.push({ source_id, failures: stall.failures, stopped: stall.failures >= EMBED_BACKFILL_STALL_LIMIT,
+ last_failed_at: stall.last_finished_at.toISOString(), remaining_chunks: current.remaining, blocked: current.blocked,
+ pages: current.pages.slice(0, LISTED).map(p => ({ slug: p.slug, page_kind: p.page_kind, queue_reason: reasons.get(p.slug) ?? null })) });
+ }
+ if (stalled.length === 0) return { name: 'embed_backfill_stalled', status: 'ok', message: 'No automatic embed-backfill is repeating the same failure.' };
+ const media = stalled.some(s => s.pages.some(p => p.page_kind !== 'markdown' && p.page_kind !== 'code'));
+ const lines = stalled.map(s => `${s.source_id}: ${s.failures} identical failed run(s) with nothing embedded, last ${s.last_failed_at}`
+ + `${s.stopped ? '; automatic backfill is stopped' : '; retries are backing off'}; ${s.remaining_chunks} stale chunk(s), ${s.blocked} blocked page(s)`
+ + (s.pages.length ? `: ${s.pages.map(p => `${p.slug} (${p.page_kind}${p.queue_reason ? `, ${p.queue_reason}` : ''})`).join(', ')}${s.blocked > s.pages.length ? `, +${s.blocked - s.pages.length} more` : ''}` : ''));
+ return {
+ name: 'embed_backfill_stalled',
+ status: 'warn',
+ message: `Automatic embed-backfill is stuck on pages it cannot project. ${lines.join('. ')}. `
+ + 'Preview with gbrain projections drain --dry-run, then run gbrain projections drain: it retries each queued Markdown or code page in the foreground and prints why one fails and the next step. '
+ + (media ? 'Image and media pages are rebuilt only by their importer: restore their source files and run gbrain sync --full --source <id>, or gbrain embed --stale --images --source <id>. ' : '')
+ + `Once the blocked pages change, the next automatic backfill runs by itself. Nothing was changed by this check. See ${DOCS}.`,
+ details: { code: 'embed_backfill_stalled', sources: stalled, stall_limit: EMBED_BACKFILL_STALL_LIMIT, docs: DOCS },
+ fix: {
+ argv: ['gbrain', 'projections', 'drain'],
+ preview_argv: ['gbrain', 'projections', 'drain', '--dry-run', '--json'],
+ consent: [],
+ actor: 'agent',
+ why: 'Retries the queued projection rebuilds in the foreground and names each page that still fails with its next step; the preview lists them and changes nothing.',
+ verify: doctorVerify('embed_backfill_stalled'),
+ docs: DOCS,
+ requires_exclusive: false,
+ },
+ };
+ } catch (error) {
+ return { name: 'embed_backfill_stalled', status: 'warn', message: `Embed-backfill history could not be read: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,
+ details: { health: 'unknown' }, fix_unavailable_reason: 'check_errored' };
+ }
+}
+
+async function runEmbedBackfillStalled(ctx: DoctorContext): Promise<Check[]> {
+ const checks: Check[] = [];
+ checks.push({ ...(await embedBackfillStalledCheck(connectedEngine(ctx))), name: 'embed_backfill_stalled' });
+ return checks;
+}
+
+export const embedBackfillStalledEntry: DoctorEntry = {
+ name: 'embed_backfill_stalled',
+ emits: ['embed_backfill_stalled'],
+ run: runEmbedBackfillStalled,
+};
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index 6ac413c3ba..4fbcec5c3a 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -84,6 +84,8 @@ import {
import { queueHealthEntry, indexAuditEntry, imageAssetsEntry } from './checks/queue-assets.ts';
import { imageEmbeddingCoverageEntry } from './checks/image-embedding-coverage.ts';
import { globalMaintenanceTimeoutsEntry } from './checks/global-maintenance-timeouts.ts';
+import { embedBackfillStalledEntry } from './checks/embed-backfill-stalled.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';
import { grantNewOpsEntry } from './checks/grant-new-ops.ts';
@@ -199,6 +201,8 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
salienceEntry,
queueHealthEntry,
globalMaintenanceTimeoutsEntry,
+ embedBackfillStalledEntry,
+ connectorAccountMismatchEntry,
legacyJobAuthorityEntry,
legacyTokenGrantsEntry,
grantNewOpsEntry,
diff --git a/src/commands/projections.ts b/src/commands/projections.ts
index cb6a523800..5ea3977318 100644
--- a/src/commands/projections.ts
+++ b/src/commands/projections.ts
@@ -16,20 +16,23 @@ import type { LockHolderInfo } from '../core/pglite-lock.ts';
import type { ProgressReporter } from '../core/progress.ts';
import { type ProjectionRebuildFailure } from '../core/page-state/projections.ts';
// #6286: the drain lives in core so `migrate` can run it on its target before the config flip.
-export { drainProjections, type ProjectionDrainResult } from '../core/page-state/projections.ts';
+export { drainProjections, previewProjectionDrain, type ProjectionDrainResult } from '../core/page-state/projections.ts';
import { SERVE_LAUNCHD_LABEL, SERVE_SYSTEMD_UNIT } from '../core/serve-service.ts';
import { resolveAutopilotJob } from '../core/autopilot-paths.ts';
import { detectInstalledJob } from './autopilot/jobs.ts';
export const PROJECTION_DRAIN_DOCS = 'docs/guides/repair.md#projection-drain';
-export const PROJECTIONS_HELP = `Usage: gbrain projections drain [--limit <n>] [--json]
+export const PROJECTIONS_HELP = `Usage: gbrain projections drain [--dry-run] [--limit <n>] [--json]
Rebuild queued Markdown and code text projections now, in batches of up to 100,
until every row queued before the run started has been tried once.
+ --dry-run Rebuild nothing: list the queued rows a drain would try, rows
+ that last failed (rebuild_failed) first, up to --limit (default 50)
--limit <n> Try at most n pages in this run (default: no cap)
--json Print {rebuilt, superseded, failed, remaining} to stdout
+ ({pending, failed, rows} with --dry-run)
Exit codes: 0 nothing tried failed; 1 some pages failed; 2 did not run
(projection_owner_resident: a resident gbrain process holds this PGLite brain
diff --git a/src/commands/sources.ts b/src/commands/sources.ts
index f3dde2601b..14031dbdfe 100644
--- a/src/commands/sources.ts
+++ b/src/commands/sources.ts
@@ -1190,6 +1190,8 @@ async function runFederate(engine: BrainEngine, args: string[], value: boolean):
console.log(` → embed-backfill skipped (24h spend cap $${sub.spendCapUsd} reached for this source).`);
} else if (sub.status === 'no_worker_surface') {
console.log(` → embed-backfill not queued (${sub.engineKind} has no recognized persistent worker); run: gbrain embed --stale --source ${id}`);
+ } else if (sub.status === 'stalled') {
+ console.log(` → embed-backfill not queued: the last ${sub.failures} runs failed on the same blocked pages with nothing embedded. See: gbrain doctor --only embed_backfill_stalled`);
} else { sub satisfies never; }
} catch (err) {
// Federation flip already succeeded; embed-backfill is a follow-up nicety.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index d2d26a4344..e238239491 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -686,6 +686,10 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.257.0', text: 'On Windows, a PGLite brain whose data directory makes the IPC socket path longer than 107 bytes now places its sockets at `%USERPROFILE%\\.gbrain\\run\\<kind>-<hash>.sock` (the Postgres scheme, same `.gbrain-ipc-secret` guard) instead of failing to bind them, so hooks and local commands reach `gbrain serve` again. A path still too long is logged as `ipc_path_too_long` and reported by the new doctor check `ipc_socket_path`.' },
{ since: '0.60.257.0', text: '`gbrain backup create` on PGLite now refuses before it takes the lock or writes anything when the brain is outside what its archive holds: a data directory that is not `<root>/.gbrain/brain.pglite` or is reached through a symlink is `unmanaged_database_path` (a `.gbrain` alias used to get `symlink_path`), and an estimated archive over 8 GiB is `backup_too_large` (it used to run the dump and fail late). Under `--json` both are their own envelope with an ask-the-user physical-copy fix instead of `storage_error`; the legacy `reason` is unchanged. Doctor `pglite_data_dir` now warns on a healthy PGLite brain whose estimated archive passes 6 GiB.' },
{ since: '0.60.257.0', text: '`gbrain bootstrap harness --token` on a PGLite brain now wires the harness when no serve answers at the serve URL and none holds the brain, and exits 13 with JSON `status: "pending_verify"` instead of exit 1 before writing anything. Re-run the same command with the same `--token` once `gbrain serve --http` runs to verify it; `gbrain bootstrap harness --status` reports `status: "partial"` and exits 1 until that run passes. A serve holding the brain at another URL, any HTTP answer, no `--token` and Postgres brains still fail as before. The harness `--json` result gains `status` (`ok`, `failed` or `pending_verify`).' },
+ // #6803 parts 1 and 4 hotfix. `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
+ { since: '0.60.257.0', text: 'An automatic embed-backfill that ends with nothing embedded and the same blocked pages (a projection that keeps failing to rebuild) is no longer resubmitted every 10 minutes: the next automatic submission waits twice the cooldown per identical failure, and after 3 identical failures sync, connector and federation submitters stop (`stalled`) until the blocked pages or the stale chunks change or a run embeds something. A retry inside one job that finds the same blockers dead-letters at once with `embed_backfill_stalled`. Doctor `embed_backfill_stalled` names the blocked pages and `gbrain projections drain --dry-run` previews the repair. `gbrain embed --stale` and `gbrain jobs submit embed-backfill` are not held back.' },
+ { since: '0.60.257.0', text: 'A managed Google or GitHub source whose credential no longer matches its pinned account is now skipped by autopilot after the first refusal (fan-out `unavailable-path`, freshness `freshness_source_path_skipped` with `code: connector_account_changed`) instead of being synced and refused every interval. Doctor `connector_account_mismatch` lists such sources. A `gbrain sync --source <id>` that passes the account check, or a change to the source\'s connector config, clears the skip.' },
+ { since: '0.60.257.0', text: 'A connector source\'s autopilot cycle now extracts facts and recomputes emotional weight only for that source\'s pages changed since its last completed cycle. Before, both phases walked every page in the brain on every connector cycle, which on a large brain ran past the 30-minute job deadline, so the cycle never finished and repeated the full walk.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index f2b5612fe4..292fa12d7d 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -93,7 +93,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--path', '--probe', '--source', '--vectors', '--yes'],
'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--resume', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],
- 'projections': ['--brain', '--enable-dcr', '--help', '--http', '--install', '--json', '--limit', '--now', '--port', '--public-url', '--remove', '--source', '--status', '--surface', '--user'],
+ 'projections': ['--brain', '--dry-run', '--enable-dcr', '--help', '--http', '--install', '--json', '--limit', '--now', '--port', '--public-url', '--remove', '--source', '--status', '--surface', '--user'],
'protocol': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],
'providers': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--model', '--source', '--status', '--touchpoint'],
'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],
diff --git a/src/core/connectors/sync.ts b/src/core/connectors/sync.ts
index 07b678d73c..44ad639d3b 100644
--- a/src/core/connectors/sync.ts
+++ b/src/core/connectors/sync.ts
@@ -69,6 +69,7 @@ export type EmbedKickoffOutcome =
| 'pglite_inline'
| 'cooldown'
| 'spend_capped'
+ | 'stalled'
| 'no_worker_surface'
| 'below_threshold'
| 'none';
@@ -494,6 +495,7 @@ export async function maybeKickoffEmbed(
if (status === 'submitted') return 'postgres_submitted';
if (status === 'cooldown') return 'cooldown';
if (status === 'spend_capped') return 'spend_capped';
+ if (status === 'stalled') return 'stalled';
if (status === 'no_worker_surface') return 'no_worker_surface';
return 'none';
} catch (e) {
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index aef629b4ce..c152c0f264 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -580,6 +580,15 @@ export interface CycleOpts {
* Validated via `assertValidSourceId` in `cycleLockIdFor` (defense-in-depth).
*/
sourceId?: string;
+ /**
+ * #6803: set by the autopilot-cycle handler for a connector source, whose
+ * cycle has no sync phase. The source's pages changed after this instant
+ * (null: never cycled, so every page of the source) are the cycle's
+ * incremental set; extract_facts reconciles through its bounded watermark
+ * drain. Without it a checkout-less source cycle took the full-walk mode and
+ * walked every page of the brain on every cycle.
+ */
+ sourceChangedSince?: string | null;
/**
* #4700 — bare `gbrain dream` may opt the brain's default-like source
* (sources.default / sole-non-default routing) into the full implicit
@@ -2250,6 +2259,11 @@ async function runCycleUnscoped(
// legitimate full reconcile — only a sync that ran and failed suppresses it.
let syncAttempted = false;
let synthesizeWrittenSlugs: string[] | undefined;
+ const sourceChangedSlugs = engine && cycleSourceId && opts.sourceChangedSince !== undefined
+ ? (await engine.executeRaw<{ slug: string }>(
+ 'SELECT slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND ($2::timestamptz IS NULL OR updated_at>$2::timestamptz) ORDER BY slug',
+ [cycleSourceId, opts.sourceChangedSince])).map(row => row.slug)
+ : undefined;
if (phases.includes('sync')) {
checkAborted(cycleSignal);
if (!engine) {
@@ -2406,7 +2420,7 @@ async function runCycleUnscoped(
// (#1928, codex: keying off phases.includes('sync') wrongly suppressed
// the skipped-sync full reconcile).
const syncRanButFailed = syncAttempted && syncPagesAffected === undefined;
- const xfSlugs = syncRanButFailed ? [] : syncPagesAffected;
+ const xfSlugs = syncRanButFailed || sourceChangedSlugs ? [] : syncPagesAffected;
const { result, duration_ms } = await timePhase(() =>
runPhaseExtractFacts(engine, brainDir, xfSourceId, dryRun, xfSlugs, cycleSignal), 'extract_facts');
result.duration_ms = duration_ms;
@@ -2624,10 +2638,11 @@ async function runCycleUnscoped(
// cycle, do incremental over their union. If neither phase ran (e.g.,
// user passed `--phase recompute_emotional_weight`), do full walk.
const incremental: string[] | undefined =
- (syncPagesAffected || synthesizeWrittenSlugs)
+ (syncPagesAffected || synthesizeWrittenSlugs || sourceChangedSlugs)
? Array.from(new Set([
...(syncPagesAffected ?? []),
...(synthesizeWrittenSlugs ?? []),
+ ...(sourceChangedSlugs ?? []),
]))
: undefined;
// #4797: raced + signal + lock-refresh + progress, like consolidate —
diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.ts
index 78bb483106..ce02902e32 100644
--- a/src/core/cycle/extract-facts.ts
+++ b/src/core/cycle/extract-facts.ts
@@ -972,9 +972,10 @@ export async function runExtractFacts(
// real incremental no-op; don't escalate to full-brain walk.
slugs = opts.slugs;
} else {
- // Full walk: every page in the brain. Bounded by engine.getAllSlugs
- // which is already the precedent for full-extract paths.
- const allSlugs = await engine.getAllSlugs();
+ // Full walk: every page of this source. Each page reconciles under
+ // `sourceId`, so another source's slugs are never this run's work (#6803:
+ // the unscoped walk visited the whole brain on every connector cycle).
+ const allSlugs = await engine.getAllSlugs({ sourceId });
slugs = Array.from(allSlugs);
}
// v0.35.5: union the canonicals touched by the phantom-redirect pass
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 33aa956a67..f517f1c2fb 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -314,6 +314,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([
'queue_health',
// #4578: brain-wide maintenance jobs dying at their deadline.
'global_maintenance_timeouts',
+ 'embed_backfill_stalled',
+ 'connector_account_mismatch',
// #5157: queued jobs from before the v0.50 authority cutover block every worker.
'legacy_job_authority',
// F3: legacy tokens on the JSONB-only grant shape (info) and grant drift (warn).
diff --git a/src/core/embed-backfill-stall.ts b/src/core/embed-backfill-stall.ts
new file mode 100644
index 0000000000..f1e2b6e17e
--- /dev/null
+++ b/src/core/embed-backfill-stall.ts
@@ -0,0 +1,85 @@
+/**
+ * #6803 (1): bounded retry for an embed-backfill that keeps failing the same
+ * way without progress.
+ *
+ * A backfill whose only remaining work sits on pages it cannot project (a
+ * `rebuild_failed` projection, an image page only its importer rebuilds) ends
+ * `incomplete` and dead-letters, and every automatic submitter (a sync that
+ * imported content, a connector's large-sync defer, a federation flip) queued
+ * the next one as soon as the 10-minute cooldown passed: the same failure 96
+ * times a day with nothing embedded. Each such run now records its blocker
+ * fingerprint in the job's progress (`stall`). `submitEmbedBackfill` reads
+ * the streak of identical no-progress failures for the source, backs off
+ * (cooldown x2 per failure) and, at `EMBED_BACKFILL_STALL_LIMIT`, stops
+ * submitting. Any change re-arms it: a run that embedded something or
+ * completed ends the streak, and a different fingerprint (new stale chunks, a
+ * blocker repaired or added) lets the next submission through. Explicit runs
+ * (`gbrain embed --stale`, `gbrain jobs submit embed-backfill`) never pass
+ * through this gate. doctor `embed_backfill_stalled` names the blocking pages.
+ */
+import type { BrainEngine } from './engine.ts';
+import { digest } from './persistence/digest.ts';
+import { countArchivedEmbeddingWork, listPendingProjectionPages } from './embedding-readiness.ts';
+
+/** Identical no-progress failed jobs after which automatic submission stops for the source. */
+export const EMBED_BACKFILL_STALL_LIMIT = 3;
+
+/** What a no-progress run recorded, and what a submitter recomputes to compare. */
+export interface EmbedBackfillBlockers {
+ fingerprint: string;
+ /** Stale chunks left in the source. */
+ remaining: number;
+ /** Pages still waiting for a text projection, plus archived pages with embedding work. */
+ blocked: number;
+ /** The embedding signature the run drained under; a submitter recomputes with the same one. */
+ signature: string | null;
+}
+
+export interface EmbedBackfillBlockerPage { source_id: string; slug: string; page_kind: string }
+
+/**
+ * The source's current blockers: the stale-chunk count, the pages still
+ * waiting for a projection (as the backfill's own readiness pass selects
+ * them) and archived embedding work. Pages are listed for the fingerprint and
+ * for doctor; at most 1000 are read.
+ */
+export async function readEmbedBackfillBlockers(engine: BrainEngine, sourceId: string, signature: string | null):
+ Promise<EmbedBackfillBlockers & { pages: EmbedBackfillBlockerPage[] }> {
+ const sig = signature ?? undefined;
+ const remaining = await engine.countStaleChunks({ sourceId, ...(sig && { signature: sig }) });
+ const archived = await countArchivedEmbeddingWork(engine, { sourceId, signature: sig });
+ const pages = await listPendingProjectionPages(engine, { sourceId, existingChunksOnly: true, activeSourcesOnly: true, stale: { signature: sig } });
+ return {
+ fingerprint: digest({ remaining, archived, pages: pages.map(p => `${p.source_id}::${p.slug}`) }),
+ remaining,
+ blocked: pages.length + archived,
+ signature,
+ pages,
+ };
+}
+
+export interface EmbedBackfillStall extends EmbedBackfillBlockers {
+ /** Consecutive most recent finished jobs that failed with this fingerprint and embedded nothing. */
+ failures: number;
+ /** When the most recent of them finished. */
+ last_finished_at: Date;
+}
+
+/** The source's current streak of identical no-progress failures, or null when its latest finished backfill is not one. */
+export async function readEmbedBackfillStall(engine: BrainEngine, sourceId: string): Promise<EmbedBackfillStall | null> {
+ const rows = await engine.executeRaw<{ status: string; finished_at: Date | string | null; stall: EmbedBackfillBlockers | null }>(
+ `SELECT status, finished_at, progress->'stall' AS stall
+ FROM minion_jobs
+ WHERE name = 'embed-backfill' AND data->>'sourceId' = $1 AND status IN ('completed', 'failed', 'dead', 'cancelled')
+ ORDER BY id DESC LIMIT $2`,
+ [sourceId, EMBED_BACKFILL_STALL_LIMIT],
+ );
+ const first = rows[0];
+ if (!first?.stall?.fingerprint || !first.finished_at || (first.status !== 'dead' && first.status !== 'failed')) return null;
+ let failures = 0;
+ for (const row of rows) {
+ if ((row.status !== 'dead' && row.status !== 'failed') || row.stall?.fingerprint !== first.stall.fingerprint) break;
+ failures++;
+ }
+ return { ...first.stall, signature: first.stall.signature ?? null, failures, last_finished_at: new Date(first.finished_at) };
+}
diff --git a/src/core/embed-backfill-submit.ts b/src/core/embed-backfill-submit.ts
index 668b02ef8b..63b6a78f5e 100644
--- a/src/core/embed-backfill-submit.ts
+++ b/src/core/embed-backfill-submit.ts
@@ -30,6 +30,10 @@
* embed-backfill-tagged rows in the budget audit JSONL. Refuses
* submission when spend has hit the cap.
*
+ * 4. Stall cap (#6803). Backs off, then refuses, while the source's last
+ * backfills failed identically with nothing embedded and its blockers
+ * have not changed since (embed-backfill-stall.ts).
+ *
* Both bounds are config-overridable:
* - `embed.backfill_cooldown_min` (default 10)
* - `embed.backfill_max_usd_per_source_24h` (default 25)
@@ -43,6 +47,7 @@ import { opError } from './ops/contract.ts';
import { readFix } from './ops/op-fix.ts';
import { embedBackfillWorkerSurface } from './minions/embed-backfill-admission.ts';
import { MinionQueue } from './minions/queue.ts';
+import { EMBED_BACKFILL_STALL_LIMIT, readEmbedBackfillBlockers, readEmbedBackfillStall } from './embed-backfill-stall.ts';
import { parseUsdLimit, resolveSpendPosture, type SpendPosture } from './spend-posture.ts';
export const COOLDOWN_CONFIG_KEY = 'embed.backfill_cooldown_min';
@@ -57,6 +62,8 @@ export type SubmitEmbedBackfillResult =
| { status: 'cooldown'; reason: 'active_or_waiting'; cooldownRemainingSeconds: null }
| { status: 'cooldown'; reason: 'recently_finished'; cooldownRemainingSeconds: number }
| { status: 'spend_capped'; spend24hUsd: number; spendCapUsd: number }
+ /** #6803: the last EMBED_BACKFILL_STALL_LIMIT backfills failed identically with nothing embedded, and nothing has changed since. */
+ | { status: 'stalled'; failures: number; remaining: number; blocked: number; lastFailedAt: string }
| { status: 'no_worker_surface'; engineKind: 'pglite' | 'unknown' };
export type SubmitEmbedBackfillStatus = SubmitEmbedBackfillResult['status'];
@@ -171,7 +178,7 @@ export async function submitEmbedBackfill(
);
if (lastJob[0]) {
- if (lastJob[0].status === 'active' || lastJob[0].status === 'waiting') {
+ if (lastJob[0].status === 'active' || lastJob[0].status === 'waiting' || lastJob[0].status === 'delayed') {
// Active or waiting has no truthful retry countdown; keep the payload
// required and explicit instead of omitting a branch-dependent field.
return { status: 'cooldown', reason: 'active_or_waiting', cooldownRemainingSeconds: null };
@@ -190,6 +197,24 @@ export async function submitEmbedBackfill(
}
}
+ // ── #6803: identical no-progress failures ───────────────────
+ // Back off (cooldown x2 per identical failure) and stop at the stall limit
+ // while the source's blockers are exactly what the failed runs recorded.
+ // A different fingerprint (new stale chunks, a blocker repaired or added)
+ // re-arms the next submission; a run that embedded something or completed
+ // already ended the streak.
+ const stall = await readEmbedBackfillStall(engine, sourceId);
+ if (stall && (await readEmbedBackfillBlockers(engine, sourceId, stall.signature)).fingerprint === stall.fingerprint) {
+ if (stall.failures >= EMBED_BACKFILL_STALL_LIMIT) {
+ return { status: 'stalled', failures: stall.failures, remaining: stall.remaining, blocked: stall.blocked, lastFailedAt: stall.last_finished_at.toISOString() };
+ }
+ const backoffMs = cooldownMin * 60_000 * 2 ** stall.failures;
+ const ageMs = now - stall.last_finished_at.getTime();
+ if (ageMs < backoffMs) {
+ return { status: 'cooldown', reason: 'recently_finished', cooldownRemainingSeconds: Math.ceil((backoffMs - ageMs) / 1000) };
+ }
+ }
+
// ── 24h rolling spend cap ─────────────────────────────────────
// v0.42.42.0 (#2139): `spend.posture=tokenmax` waves past the cap (the
// operator declared cost isn't the constraint). The per-job BudgetTracker
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 9fc93395dd..e4f41f188f 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -127,7 +127,11 @@ export const CODES = {
why: "A pooler drop (ECONNABORTED, ECONNRESET, ETIMEDOUT, EPIPE) is a transport fault, not a page fault: the drain reconnects and retries at 5, 15 and 45 seconds, and the frozen manifest and cursor stay as they are. Three consecutive drops with no progress mean the database is unreachable from here for now.",
docs: 'docs/guides/write-refusals.md#drain-connection-lost',
suggestion: 'Check the database URL and pooler (gbrain doctor --json), then rerun the same gbrain sync; it resumes at the stored cursor without re-freezing the manifest.' },
- connector_account_changed: { class: 'caller', summary: "The connector credential resolves to a different account than the source is pinned to." },
+ connector_account_changed: { class: 'caller', summary: "The connector credential resolves to a different account than the source is pinned to.",
+ why: 'A connector source is pinned to the account it first synced, so a swapped credential can never import another account\'s mail, calendar or repositories into it. The refused run records the mismatch, and autopilot skips the source (unavailable-path) instead of retrying it every interval (#6803).',
+ docs: 'docs/guides/write-refusals.md#connector-account-changed',
+ suggestion: 'Restore the credential for the pinned account and run gbrain sync --source <id> (it clears the skip once the account check passes), or add a new source for the new account and archive this one with gbrain sources archive <id>. gbrain doctor --only connector_account_mismatch lists every affected source.',
+ fix: { argv: ['gbrain', 'doctor', '--only', 'connector_account_mismatch', '--json'], consent: [], actor: 'agent', why: 'Lists the connector sources autopilot skips for an account mismatch; changes nothing.', requires_exclusive: false } },
connector_fence_below_timeline: { class: 'caller', summary: "A stored page carries a fence the connector render cannot preserve." },
connector_holds_exhausted: { class: 'caller', summary: "The source holds the maximum number of failed items; its cursor did not advance." },
connector_intent_outdated: { class: 'caller', summary: "The connector request no longer matches the stored connector intent." },
@@ -195,6 +199,12 @@ export const CODES = {
dirty_tree: { class: 'caller', summary: "Commit or stash canonical skill edits before optimization." },
doctor_tier_unavailable: { class: 'host_only', actor: 'host_admin', summary: "The remote serve cannot answer this doctor tier or check for this client, so the thin client ran nothing.", why: "A serve older than the doctor ops tier does not advertise run_doctor's tier and only parameters or get_brain_health, and a token without admin scope cannot call run_doctor; the thin client never falls back to the full report.", docs: 'docs/guides/troubleshooting.md#doctor-ops-tier', fix: { argv: ['gbrain', 'doctor', '--tier', 'ops', '--json'], consent: [], actor: 'host_admin', why: 'The ops report, run on the brain host (or after upgrading and restarting its serve).', requires_exclusive: false } },
effect_not_failed: { class: 'caller', summary: "Only a failed, non-running embedding effect can be explicitly retried." },
+ embed_backfill_stalled: { class: 'unavailable', actor: 'agent',
+ summary: "A source's automatic embed-backfill failed the same way several times with nothing embedded, so automatic backfill for it backs off and then stops.",
+ why: 'The only remaining work sits on pages whose text projection cannot be rebuilt (a rebuild_failed projection, or an image page only its importer rebuilds). Each identical run spent a worker slot and dead-lettered; after three, automatic submission stops until the blocked pages or the stale chunks change, or a run embeds something (#6803). Explicit gbrain embed --stale and gbrain jobs submit embed-backfill are not gated.',
+ docs: 'docs/guides/repair.md#embed-backfill-stalled',
+ suggestion: 'Run gbrain doctor --only embed_backfill_stalled to see the blocked pages, preview the repair with gbrain projections drain --dry-run, then run gbrain projections drain; it names each page that still fails and its next step.',
+ fix: { argv: ['gbrain', 'doctor', '--only', 'embed_backfill_stalled', '--json'], consent: [], actor: 'agent', why: 'Names the blocked pages and the preview-first repair; changes nothing.', requires_exclusive: false } },
embedding_auth_failed: { class: 'unavailable', summary: "The embedding provider rejected the credentials." },
embedding_budget_below_worst_case: { class: 'unavailable', summary: "The embedding migration cap is below its worst-case cost; nothing was changed." },
embedding_configuration: { class: 'host_only', summary: "The brain's embedding configuration is invalid." },
diff --git a/src/core/github-source.ts b/src/core/github-source.ts
index 78d5fcfac9..b34b094875 100644
--- a/src/core/github-source.ts
+++ b/src/core/github-source.ts
@@ -1447,7 +1447,7 @@ async function runExtractAndEmbed(
const sub = await submitEmbedBackfill(deps.engine, deps.sourceId, { reason: 'github_sync_defer' });
if (sub.status === 'submitted') {
process.stderr.write(`[github] large sync (${totalChanges} pages); embeds deferred to embed-backfill job ${sub.jobId} — or ${drainHint}\n`);
- } else if (sub.status === 'cooldown' || sub.status === 'spend_capped' || sub.status === 'no_worker_surface') {
+ } else if (sub.status === 'cooldown' || sub.status === 'spend_capped' || sub.status === 'no_worker_surface' || sub.status === 'stalled') {
process.stderr.write(`[github] large sync (${totalChanges} pages); embed-backfill not queued (${sub.status}) — ${drainHint}\n`);
} else { sub satisfies never; }
} catch (err) {
diff --git a/src/core/minions/handlers/autopilot-cycle.ts b/src/core/minions/handlers/autopilot-cycle.ts
index 6edcedaff7..7d5d8ce715 100644
--- a/src/core/minions/handlers/autopilot-cycle.ts
+++ b/src/core/minions/handlers/autopilot-cycle.ts
@@ -50,6 +50,7 @@ export function makeAutopilotCycleHandler(engine: BrainEngine): MinionHandler {
// source's `local_path` here and use it as the cycle's brainDir below.
let sourceLocalPath: string | null = null;
let connectorSource = false;
+ let lastSourceCycleAt: string | null = null;
if (rawSourceId !== undefined && rawSourceId !== null) {
if (typeof rawSourceId !== 'string') {
throw new Error(`autopilot-cycle: invalid source_id (not a string): ${JSON.stringify(rawSourceId)}`);
@@ -65,8 +66,9 @@ export function makeAutopilotCycleHandler(engine: BrainEngine): MinionHandler {
// immediately if source is gone or archived; runCycle never even
// acquires a lock. Also fetches local_path so FS phases bind to the
// source's own checkout (the #2227/#2194 mixed-scope fix).
- const rows = await engine.executeRaw<{ archived: boolean | null; local_path: string | null; kind: string | null }>(
- `SELECT archived, local_path, config->>'kind' AS kind FROM sources WHERE id = $1`,
+ const rows = await engine.executeRaw<{ archived: boolean | null; local_path: string | null; kind: string | null; last_cycle: string | null }>(
+ `SELECT archived, local_path, config->>'kind' AS kind,
+ COALESCE(config->>'last_source_cycle_at', config->>'last_full_cycle_at') AS last_cycle FROM sources WHERE id = $1`,
[rawSourceId],
);
if (rows.length === 0) {
@@ -86,6 +88,7 @@ export function makeAutopilotCycleHandler(engine: BrainEngine): MinionHandler {
sourceId = rawSourceId;
// #5673: a connector source's local_path is never a brain directory.
connectorSource = isConnectorSourceKind(rows[0].kind);
+ lastSourceCycleAt = rows[0].last_cycle && Number.isFinite(Date.parse(rows[0].last_cycle)) ? rows[0].last_cycle : null;
sourceLocalPath = !connectorSource && typeof rows[0].local_path === 'string' && rows[0].local_path.length > 0
? rows[0].local_path
: null;
@@ -153,6 +156,8 @@ export function makeAutopilotCycleHandler(engine: BrainEngine): MinionHandler {
deadlineAtMs: job.deadlineAtMs, // #2781: phases budget sub-work from remaining time
privateQueueOwnerJobId: job.id,
...(sourceId ? { sourceId } : {}),
+ // #6803: a connector cycle has no sync phase; its incremental set is the source's pages changed since its last cycle.
+ ...(connectorSource ? { sourceChangedSince: lastSourceCycleAt } : {}),
...(effectivePhases !== undefined ? { phases: effectivePhases as any } : {}),
yieldBetweenPhases: async () => {
// Yield to the event loop so worker lock-renewal can fire.
diff --git a/src/core/minions/handlers/embed-backfill.ts b/src/core/minions/handlers/embed-backfill.ts
index 432ae8f04c..5933f3f677 100644
--- a/src/core/minions/handlers/embed-backfill.ts
+++ b/src/core/minions/handlers/embed-backfill.ts
@@ -47,6 +47,8 @@ import { getEmbeddingModel, withBudgetTracker } from '../../ai/gateway.ts';
import { embedStaleForSource } from '../../embed-stale.ts';
import { createEmbedStallWatchdog, resolveEmbedStallAbortSeconds } from '../../embed-stall.ts';
import { currentEmbeddingSignature } from '../../embedding.ts';
+import { readEmbedBackfillBlockers } from '../../embed-backfill-stall.ts';
+import { UnrecoverableError } from '../errors.ts';
import { type DbPacer, createDbPacer, createNoopPacer } from '../../db-pacer.ts';
import { resolvePaceMode, loadPaceModeConfig, readPaceEnv } from '../../pace-mode.ts';
import type { BrainEngine } from '../../engine.ts';
@@ -345,7 +347,27 @@ export function makeEmbedBackfillHandler(
// in a row while an entire corpus sat stripped. NULLed chunks stay NULL
// for the next (fixed-config) run to pick up.
if ((result.remaining ?? 0) > 0 || (result.blocked ?? 0) > 0) {
- throw new Error(`embed-backfill: incomplete; ${result.remaining ?? 0} chunks remain and ${result.blocked ?? 0} projections are blocked. Durable progress is retained; inspect provider and projection readiness before retrying.`);
+ const message = `embed-backfill: incomplete; ${result.remaining ?? 0} chunks remain and ${result.blocked ?? 0} projections are blocked. Durable progress is retained; inspect provider and projection readiness before retrying.`;
+ // #6803: a run that embedded nothing records its blocker fingerprint, so
+ // automatic submission backs off and stops after identical failures
+ // (embed-backfill-stall.ts); a retry of this job that finds the same
+ // blockers dead-letters instead of failing the same way again.
+ let repeated = false;
+ if (result.embedded === 0) {
+ try {
+ const { fingerprint, remaining, blocked, signature } = await readEmbedBackfillBlockers(engine, sourceId, currentEmbeddingSignature());
+ const [prior] = job.attempts_made > 0
+ ? await engine.executeRaw<{ fingerprint: string | null }>("SELECT progress->'stall'->>'fingerprint' AS fingerprint FROM minion_jobs WHERE id=$1", [job.id])
+ : [];
+ await job.updateProgress({ embedded: 0, chunksProcessed: result.chunksProcessed, cursor: result.lastCursor, spentUsd: tracker.totalSpent,
+ stall: { fingerprint, remaining, blocked, signature } });
+ repeated = prior?.fingerprint === fingerprint;
+ } catch { /* the stall record is bookkeeping; the incomplete failure below stands either way */ }
+ }
+ if (repeated) {
+ throw new UnrecoverableError(`${message} No progress since the previous attempt and the same blockers remain; see gbrain doctor --only embed_backfill_stalled.`);
+ }
+ throw new Error(message);
}
if (result.embedded === 0 && (result.invalidated > 0 || result.chunksProcessed > 0)) {
throw new Error(
diff --git a/src/core/minions/handlers/sync.ts b/src/core/minions/handlers/sync.ts
index ec54d698aa..07a93dfcdd 100644
--- a/src/core/minions/handlers/sync.ts
+++ b/src/core/minions/handlers/sync.ts
@@ -165,7 +165,7 @@ export function makeSyncHandler(engine: BrainEngine): MinionHandler {
});
if (submission.status === 'submitted') {
embedJobId = submission.jobId;
- } else if (submission.status === 'cooldown' || submission.status === 'spend_capped' || submission.status === 'no_worker_surface') {
+ } else if (submission.status === 'cooldown' || submission.status === 'spend_capped' || submission.status === 'no_worker_surface' || submission.status === 'stalled') {
embedSkipReason = submission.status;
} else {
submission satisfies never;
diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.ts
index 776096c329..54b9c22c3b 100644
--- a/src/core/page-state/projections.ts
+++ b/src/core/page-state/projections.ts
@@ -461,6 +461,21 @@ export async function projectionBacklog(engine: Pick<BrainEngine, 'executeRaw'>)
return { pending: Number(row?.pending ?? 0), failed: Number(row?.failed ?? 0), oldest_age_seconds: oldest };
}
+/**
+ * #6803: the read-only preview of `gbrain projections drain`: the queued
+ * Markdown and code rows a drain would try, rows that last failed first, then oldest (at most `limit`),
+ * with each row's queue reason, so a row that last failed (`rebuild_failed`)
+ * is named before anything is rebuilt.
+ */
+export async function previewProjectionDrain(engine: Pick<BrainEngine, 'executeRaw'>, limit = 50):
+ Promise<{ pending: number; failed: number; rows: Array<{ source_id: string; slug: string; reason: string; updated_at: string }> }> {
+ const backlog = await projectionBacklog(engine);
+ const rows = await engine.executeRaw<{ source_id: string; slug: string; reason: string; updated_at: string }>(`SELECT s.id AS source_id,j.slug,j.reason,j.updated_at::text AS updated_at
+ FROM page_projection_jobs j ${PROJECTION_JOB_PROBES}
+ ORDER BY (j.reason='rebuild_failed') DESC,j.updated_at,j.slug LIMIT $1`, [Math.max(1, limit)]);
+ return { pending: backlog.pending, failed: backlog.failed, rows };
+}
+
/**
* Bounded and keyless. Unsupported media remains queued for its source importer.
*
diff --git a/src/core/persistence/connector-account-mismatch.ts b/src/core/persistence/connector-account-mismatch.ts
new file mode 100644
index 0000000000..9cef2a7771
--- /dev/null
+++ b/src/core/persistence/connector-account-mismatch.ts
@@ -0,0 +1,58 @@
+/**
+ * #6803: a connector source whose credential resolves to a different account
+ * than its pin (`connector_account_changed`) cannot import anything until the
+ * operator repins it. The refused run records the mismatch in the source's
+ * connector state (`account_mismatch`); autopilot reads it here and classifies
+ * the source unavailable-path instead of dispatching a sync and a cycle for it
+ * every interval. A sync that passes the account check clears the record, and
+ * a changed connector config re-arms the source for one more automatic try.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { digest } from './digest.ts';
+import { parseSourceConfig } from '../sources-load.ts';
+import { connectorIdentity, isConnectorSourceKind, type ConnectorKind } from './connector-identity.ts';
+import { CONNECTOR_STATE_OP, connectorStateKey, type ConnectorAccountMismatch } from './connector-state.ts';
+
+/**
+ * #6803: the whole parsed connector config, credential settings included
+ * (`g_token_command`, `gh_token_env`, ...), unlike the identity digest. A
+ * change to it is an operator repin attempt, so autopilot tries the source once more.
+ */
+export function connectorConfigDigest(config: object): string {
+ return digest(config);
+}
+
+/**
+ * #6803: active connector sources whose last sync refused with
+ * `connector_account_changed` and whose connector config has not changed
+ * since. Autopilot classifies them unavailable-path until the operator repins
+ * (`gbrain sync --source <id>` passes the account check), changes the config,
+ * or archives the source.
+ */
+export async function connectorAccountMismatches(engine: Pick<BrainEngine, 'executeRaw'>): Promise<Map<string, ConnectorAccountMismatch>> {
+ const sources = await engine.executeRaw<{ id: string; incarnation: string; local_path: string | null; config: unknown }>(
+ 'SELECT id,incarnation::text AS incarnation,local_path,config FROM sources WHERE archived IS NOT TRUE');
+ const keyed = new Map(sources.filter(s => isConnectorSourceKind(parseSourceConfig(s.config).kind))
+ .map(s => [connectorStateKey(s.id, s.incarnation), s]));
+ const found = new Map<string, ConnectorAccountMismatch>();
+ if (keyed.size === 0) return found;
+ const rows = await engine.executeRaw<{ fingerprint: string; mismatch: ConnectorAccountMismatch }>(`SELECT fingerprint, completed_keys->0->'account_mismatch' AS mismatch
+ FROM op_checkpoints WHERE op=$1 AND fingerprint=ANY($2::text[]) AND jsonb_typeof(completed_keys->0->'account_mismatch')='object'`,
+ [CONNECTOR_STATE_OP, [...keyed.keys()]]);
+ for (const row of rows) {
+ const source = keyed.get(row.fingerprint)!;
+ const raw = parseSourceConfig(source.config);
+ let current: string;
+ try { current = connectorConfigDigest(connectorIdentity(raw.kind as ConnectorKind, raw, source.local_path).config); } catch { continue; }
+ if (row.mismatch.config_digest === current) found.set(source.id, row.mismatch);
+ }
+ return found;
+}
+
+/** #6803: the dispatch line for a source skipped while its credential resolves to another account. */
+export function connectorAccountMismatchSkipWarning(sourceId: string, mismatch: Pick<ConnectorAccountMismatch, 'at' | 'detail'>): string {
+ const what = mismatch.detail === 'account_unresolved' ? 'its credential resolves to no account' : 'its credential resolves to a different account than the source is pinned to';
+ return `[dispatch] ${sourceId}: connector source skipped (unavailable): ${what} (connector_account_changed since ${mismatch.at}). `
+ + `Restore the credential for the pinned account, then run: gbrain sync --source ${sourceId}. For a deliberate account change, add a new source and archive this one: gbrain sources archive ${sourceId}. `
+ + `Autopilot retries it by itself only after its connector config changes.`;
+}
diff --git a/src/core/persistence/connector-state.ts b/src/core/persistence/connector-state.ts
index b2331d5cb3..b6f0a469c6 100644
--- a/src/core/persistence/connector-state.ts
+++ b/src/core/persistence/connector-state.ts
@@ -61,10 +61,23 @@ export interface ConnectorState {
* connector sources that have one; checkpoint-row existence never counts.
*/
first_attempt_at?: string | null;
+ /**
+ * #6803: the last account check refused with `connector_account_changed`.
+ * Autopilot skips the source (unavailable-path) while the connector config
+ * still digests to `config_digest`; a sync that passes the check clears it.
+ */
+ account_mismatch?: ConnectorAccountMismatch | null;
+}
+
+export interface ConnectorAccountMismatch {
+ at: string;
+ detail: 'account_changed' | 'account_unresolved';
+ /** `connectorConfigDigest` of the config the refused run read (credential settings included). */
+ config_digest: string;
}
export const emptyConnectorState = (): ConnectorState => ({ version: 1, account: null, pinned_at: null, continuity_unverified: false,
- pending: [], upgrade_recovery: 'none', resumed_from: null, last_run: null, first_attempt_at: null });
+ pending: [], upgrade_recovery: 'none', resumed_from: null, last_run: null, first_attempt_at: null, account_mismatch: null });
export function connectorStateKey(sourceId: string, incarnation: string): string {
return digest({ sourceId, incarnation });
@@ -156,3 +169,4 @@ export function describeConnectorAccount(account: ConnectorAccount): string {
return [account.installationId !== null ? `installation ${account.installationId}` : null, account.login ? `login ${account.login}` : null]
.filter(Boolean).join(', ') || 'no installation or login';
}
+
diff --git a/src/core/persistence/connector-sync.ts b/src/core/persistence/connector-sync.ts
index 0fbd377462..0a901cca62 100644
--- a/src/core/persistence/connector-sync.ts
+++ b/src/core/persistence/connector-sync.ts
@@ -34,6 +34,7 @@ import { LockStolenError, syncLockId, withRefreshingLock, type DbLockHandle } fr
import { ownedGoogleReceipts, prepareGoogleReceiptPatch, type GoogleReceipts } from './connector-google-receipts.ts';
import { connectorCheckpointKeys, connectorIdentity, connectorIdentityMatches, type ConnectorIdentity, type ConnectorKind } from './connector-identity.ts';
import { readManagedConnectorState, recordConnectorSyncAttempt, sameConnectorAccount, writeManagedConnectorState, type ConnectorAccount, type ConnectorPendingEntry, type ConnectorRunCounts, type ConnectorState } from './connector-state.ts';
+import { connectorConfigDigest } from './connector-account-mismatch.ts';
import { connectorAccountChanged, connectorFenceHint, docsAnchor, receiptDeliveredHint, CONNECTOR_INTENT_OUTDATED_OLD_HOST, CONNECTOR_INTENT_OUTDATED_PRE_UPGRADE } from './connector-errors.ts';
import { inspectUnchanged, screeningRequest } from './noop-kernel.ts';
import { conceptPreservationHold, preserveCanonicalFences } from '../cycle/concept-publication.ts';
@@ -435,12 +436,16 @@ export class ManagedConnectorSync {
async assertAccount(resolved: ConnectorAccount | null): Promise<void> {
if (this.blockedByCheckpoint) { this.stopped = true; throw new ConnectorWaitBudgetStop(); }
const configured = this.identity.kind === 'google' ? (this.identity.config as GoogleSourceConfig).account : null;
- if (resolved === null) throw connectorAccountChanged(this.sourceId, this.identity.kind, this.identity.config, this.connectorState.account ?? configured ?? 'the pinned account', null);
+ if (resolved === null) throw await this.accountRefused(connectorAccountChanged(this.sourceId, this.identity.kind, this.identity.config, this.connectorState.account ?? configured ?? 'the pinned account', null));
if (configured !== null && resolved.kind === 'google' && resolved.email !== configured) {
- throw connectorAccountChanged(this.sourceId, this.identity.kind, this.identity.config, this.connectorState.account ?? configured, resolved);
+ throw await this.accountRefused(connectorAccountChanged(this.sourceId, this.identity.kind, this.identity.config, this.connectorState.account ?? configured, resolved));
}
const pinned = this.connectorState.account;
- if (pinned && !sameConnectorAccount(pinned, resolved)) throw connectorAccountChanged(this.sourceId, this.identity.kind, this.identity.config, pinned, resolved);
+ if (pinned && !sameConnectorAccount(pinned, resolved)) throw await this.accountRefused(connectorAccountChanged(this.sourceId, this.identity.kind, this.identity.config, pinned, resolved));
+ if (this.connectorState.account_mismatch) {
+ this.connectorState = { ...this.connectorState, account_mismatch: null };
+ if (pinned) await this.writeState();
+ }
if (!pinned) {
const migrated = this.connectorState.upgrade_recovery === 'resumed';
this.connectorState = { ...this.connectorState, account: resolved, pinned_at: new Date().toISOString(), continuity_unverified: migrated };
@@ -452,6 +457,17 @@ export class ManagedConnectorSync {
}
if (this.resetRequested) await this.resetCheckpoint();
}
+ /**
+ * #6803: records the refusal in the connector state so autopilot stops
+ * dispatching this source until the operator repins it or changes its
+ * connector config. Best-effort: the refusal itself is what the caller sees.
+ */
+ private async accountRefused(error: OperationError): Promise<OperationError> {
+ this.connectorState = { ...this.connectorState, account_mismatch: { at: new Date().toISOString(),
+ detail: error.detail === 'account_unresolved' ? 'account_unresolved' : 'account_changed', config_digest: connectorConfigDigest(this.identity.config) } };
+ await this.writeState().catch(() => undefined);
+ return error;
+ }
/** `--reset-checkpoint`: resolve pending writes, then start from an empty cursor. Existing pages stay; the pin is kept. */
private async resetCheckpoint(): Promise<void> {
this.resetRequested = false;
diff --git a/src/core/sync-embed-backfill.ts b/src/core/sync-embed-backfill.ts
index a091c04392..c8a606721a 100644
--- a/src/core/sync-embed-backfill.ts
+++ b/src/core/sync-embed-backfill.ts
@@ -135,7 +135,8 @@ export type SyncEmbedBackfillOutcome =
reason: 'no_worker_surface' | 'auto_submit_disabled';
}
| { status: 'skipped'; reason: 'cooldown'; command: string }
- | { status: 'skipped'; reason: 'spend_capped'; command: string; spend_cap_usd: number };
+ | { status: 'skipped'; reason: 'spend_capped'; command: string; spend_cap_usd: number }
+ | { status: 'skipped'; reason: 'stalled'; command: string; failures: number };
export async function resolveSyncEmbedBackfill(
engine: BrainEngine,
@@ -168,6 +169,8 @@ export async function resolveSyncEmbedBackfill(
};
case 'no_worker_surface':
return { status: 'manual_drain_required', command, reason: 'no_worker_surface' };
+ case 'stalled':
+ return { status: 'skipped', reason: 'stalled', command, failures: submitted.failures };
default:
submitted satisfies never;
throw new Error('unreachable embed-backfill submission result');
@@ -185,6 +188,10 @@ export function formatSyncEmbedBackfillOutcome(
case 'manual_drain_required':
return `embed-backfill not queued; manual drain required: \`${outcome.command}\`${source}`;
case 'skipped': {
+ if (outcome.reason === 'stalled') {
+ return `embed-backfill skipped${source}: the last ${outcome.failures} runs failed on the same blocked pages with nothing embedded; `
+ + `see \`gbrain doctor --only embed_backfill_stalled\` (manual drain: \`${outcome.command}\`)`;
+ }
const detail = outcome.reason === 'cooldown'
? 'cooldown'
: `24h spend cap $${outcome.spend_cap_usd}`;
diff --git a/test/connector-account-mismatch-dispatch.serial.test.ts b/test/connector-account-mismatch-dispatch.serial.test.ts
new file mode 100644
index 0000000000..2c5c15c456
--- /dev/null
+++ b/test/connector-account-mismatch-dispatch.serial.test.ts
@@ -0,0 +1,120 @@
+/**
+ * #6803 (4): a connector source whose credential resolves to a different
+ * account than its pin refuses every sync with `connector_account_changed`.
+ * Autopilot used to dispatch a `sync` and an `autopilot-cycle` for it every
+ * interval forever (44 dead syncs a day on a production brain). The refused
+ * run now records the mismatch in the source's connector state, and both
+ * autopilot loops classify the source unavailable-path until the operator
+ * repins it (a sync that passes the account check) or changes its connector config.
+ *
+ * Real connector sync refusal, then the real freshness loop and per-source
+ * fan-out, on every configured engine. Serial: the fixture toggles the
+ * brain-wide persistence switch and process env.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { dispatchFreshnessSyncs } from '../src/commands/autopilot-dispatch.ts';
+import { dispatchPerSource } from '../src/commands/autopilot-fanout.ts';
+import { parseGoogleSourceConfig, runGoogleSync } from '../src/core/google/google-source.ts';
+import { recordConnectorSyncAttempt } from '../src/core/persistence/connector-state.ts';
+import { connectorAccountMismatches } from '../src/core/persistence/connector-account-mismatch.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { contact, createConnectorFixture, googleConfig, json, options, withGoogleAccount } from './helpers/connector-fixture.ts';
+
+const fixture = createConnectorFixture();
+const { engines, env, source } = fixture;
+beforeAll(fixture.setup, 120_000);
+afterAll(fixture.teardown);
+
+const contacts = async (url: string) => url.includes('/settings/sendAs') ? json({ sendAs: [] })
+ : json({ connections: [contact('first', 'First Example')], nextSyncToken: 'contacts-1' });
+const sync = (engine: BrainEngine, f: { id: string; dir: string }, account: string, config: Record<string, unknown> = googleConfig) =>
+ runGoogleSync(engine, f.id, parseGoogleSourceConfig(config, f.dir), options, withGoogleAccount(contacts, account));
+
+async function queued(engine: BrainEngine, sourceId: string): Promise<string[]> {
+ const rows = await engine.executeRaw<{ name: string }>(
+ "SELECT name FROM minion_jobs WHERE COALESCE(data->>'sourceId', data->>'source_id')=$1 ORDER BY id", [sourceId]);
+ return rows.map(r => r.name);
+}
+
+async function tick(engine: BrainEngine, lines: string[]) {
+ const write = process.stderr.write.bind(process.stderr);
+ const log = console.log;
+ (process.stderr as { write: unknown }).write = (chunk: string) => { lines.push(String(chunk)); return true; };
+ console.log = (...args: unknown[]) => { lines.push(args.map(String).join(' ')); };
+ try {
+ const queue = new MinionQueue(engine);
+ const slot = `slot-${Math.random()}`;
+ await dispatchFreshnessSyncs(engine, queue, { baseInterval: 60, slot, timeoutMs: 60_000, jsonMode: true });
+ return await dispatchPerSource(engine, queue, { repoPath: '/nonexistent', slot, timeoutMs: 60_000, fanoutMax: 10, jsonMode: true,
+ emit: line => { lines.push(line); }, log: line => { lines.push(line); } });
+ } finally {
+ (process.stderr as { write: unknown }).write = write;
+ console.log = log;
+ }
+}
+
+async function makeStale(engine: BrainEngine, sourceId: string) {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw(`UPDATE sources SET last_sync_at=NULL,
+ config=config - 'last_full_cycle_at' - 'last_source_cycle_at' WHERE id=$1`, [sourceId]);
+ await engine.executeRaw("DELETE FROM minion_jobs WHERE COALESCE(data->>'sourceId', data->>'source_id')=$1", [sourceId]);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+}
+
+describe('#6803 mis-pinned connector source in autopilot dispatch', () => {
+ test('a refused account check makes the source unavailable-path until it is repinned', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const f = await source(engine, googleConfig);
+ await recordConnectorSyncAttempt(engine, f.id);
+ expect((await sync(engine, f, googleConfig.g_account)).added).toBe(1);
+ await disposePersistenceConsumer(engine);
+
+ // A healthy, attempted connector is dispatched by both loops.
+ await makeStale(engine, f.id);
+ const healthy = await tick(engine, []);
+ expect(healthy.skipped_unavailable_path).not.toContain(f.id);
+ expect(await queued(engine, f.id)).toEqual(['sync', 'autopilot-cycle']);
+
+ // The credential now resolves to another account: the sync refuses and records it.
+ await expect(sync(engine, f, '[email protected]')).rejects.toMatchObject({ code: 'connector_account_changed' });
+ await disposePersistenceConsumer(engine);
+ expect([...(await connectorAccountMismatches(engine)).keys()]).toContain(f.id);
+
+ await makeStale(engine, f.id);
+ const lines: string[] = [];
+ const skipped = await tick(engine, lines);
+ expect(skipped.skipped_unavailable_path).toContain(f.id);
+ expect(await queued(engine, f.id)).toEqual([]);
+ const events = lines.flatMap(l => l.split('\n')).filter(l => l.startsWith('{')).map(l => JSON.parse(l) as Record<string, unknown>);
+ expect(events.some(e => e.event === 'freshness_source_path_skipped' && e.source_id === f.id && e.code === 'connector_account_changed')).toBe(true);
+ expect(events.some(e => e.event === 'fanout_source_path_skipped' && e.source_id === f.id && String(e.reason).includes(`gbrain sync --source ${f.id}`))).toBe(true);
+
+ // The operator restores the credential and syncs by hand: the account check passes and clears the record.
+ await sync(engine, f, googleConfig.g_account);
+ await disposePersistenceConsumer(engine);
+ expect([...(await connectorAccountMismatches(engine)).keys()]).not.toContain(f.id);
+ await makeStale(engine, f.id);
+ const repinned = await tick(engine, []);
+ expect(repinned.skipped_unavailable_path).not.toContain(f.id);
+ expect(await queued(engine, f.id)).toEqual(['sync', 'autopilot-cycle']);
+ }
+ }), 180_000);
+
+ test('a changed connector config re-arms the source for one more automatic try', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const f = await source(engine, googleConfig);
+ await recordConnectorSyncAttempt(engine, f.id);
+ expect((await sync(engine, f, googleConfig.g_account)).added).toBe(1);
+ await expect(sync(engine, f, '[email protected]')).rejects.toMatchObject({ code: 'connector_account_changed' });
+ await disposePersistenceConsumer(engine);
+ expect([...(await connectorAccountMismatches(engine)).keys()]).toContain(f.id);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw(`UPDATE sources SET config=jsonb_set(config, '{g_token_env}', '"CONNECTOR_TEST_TOKEN_NEW"') WHERE id=$1`, [f.id]);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ expect([...(await connectorAccountMismatches(engine)).keys()]).not.toContain(f.id);
+ }
+ }), 180_000);
+});
diff --git a/test/connector-cycle-extract-facts-scope.serial.test.ts b/test/connector-cycle-extract-facts-scope.serial.test.ts
new file mode 100644
index 0000000000..0e1f0eb7ab
--- /dev/null
+++ b/test/connector-cycle-extract-facts-scope.serial.test.ts
@@ -0,0 +1,69 @@
+/**
+ * #6803 (4): a checkout-less per-source cycle (a connector source: phases
+ * extract, extract_facts, recompute_emotional_weight, no sync) reconciled
+ * facts for EVERY slug in the brain on every cycle. With no sync phase the
+ * phase got `slugs: undefined`, the full-walk mode, and the full walk read
+ * `engine.getAllSlugs()` unscoped, so a connector source on a 290K-page brain
+ * walked every other source's pages until the autopilot-cycle job died with
+ * `aborted: timeout`. A connector cycle now reconciles only its own source,
+ * through the bounded reconcile watermark drain.
+ *
+ * Real handler and cycle on every configured engine. Serial: the fixture
+ * toggles the brain-wide persistence switch and process env.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { makeAutopilotCycleHandler } from '../src/core/minions/handlers/autopilot-cycle.ts';
+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { createConnectorFixture, googleConfig } from './helpers/connector-fixture.ts';
+
+const fixture = createConnectorFixture();
+const { engines, env, source } = fixture;
+beforeAll(fixture.setup, 120_000);
+afterAll(fixture.teardown);
+
+const OTHER_PAGES = 40;
+
+async function seed(engine: BrainEngine): Promise<{ connector: string; other: string }> {
+ const connector = (await source(engine, googleConfig)).id;
+ const other = (await source(engine, {})).id;
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.putPage('emails/example', { title: 'Synthetic exchange', type: 'email', compiled_truth: 'A synthetic note.' }, { sourceId: connector });
+ for (let i = 0; i < OTHER_PAGES; i++) {
+ await engine.putPage(`notes/n-${i}`, { title: `Note ${i}`, type: 'note', compiled_truth: `Body ${i}.` }, { sourceId: other });
+ }
+ return { connector, other };
+}
+
+describe('#6803 connector cycle extract_facts scope', () => {
+ test('a connector cycle reconciles only its own source, through the bounded drain', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const { connector } = await seed(engine);
+ const out = await makeAutopilotCycleHandler(engine)({ id: 1, data: { source_id: connector } } as never) as {
+ report: { brain_dir: string | null; phases: Array<{ phase: string; status: string; details: Record<string, unknown> }> };
+ };
+ expect(out.report.brain_dir).toBeNull();
+ const facts = out.report.phases.find(p => p.phase === 'extract_facts');
+ expect(facts).toBeDefined();
+ expect(Number(facts!.details.pagesScanned)).toBeLessThanOrEqual(1);
+ const weight = out.report.phases.find(p => p.phase === 'recompute_emotional_weight');
+ expect(weight?.details).toMatchObject({ mode: 'incremental', pages_recomputed: 1 });
+ // The next cycle starts from this cycle's stamp: nothing in the source changed since.
+ const again = await makeAutopilotCycleHandler(engine)({ id: 2, data: { source_id: connector } } as never) as typeof out;
+ expect(again.report.phases.find(p => p.phase === 'recompute_emotional_weight')?.details).toMatchObject({ mode: 'incremental', pages_recomputed: 0 });
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ }
+ }), 180_000);
+
+ test('a full walk for one source never visits another source\'s slugs', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const { connector } = await seed(engine);
+ const result = await runExtractFacts(engine, { sourceId: connector, drain: {} });
+ expect(result.pagesScanned).toBe(1);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ }
+ }), 180_000);
+});
diff --git a/test/e2e/embed-backfill-stall-postgres.test.ts b/test/e2e/embed-backfill-stall-postgres.test.ts
new file mode 100644
index 0000000000..afe9812046
--- /dev/null
+++ b/test/e2e/embed-backfill-stall-postgres.test.ts
@@ -0,0 +1,124 @@
+/**
+ * #6803 (1): an embed-backfill whose only remaining work sits on pages it
+ * cannot project dead-lettered every ~15 minutes forever (23 dead jobs a day
+ * on a production brain, nothing embedded), because every automatic submitter
+ * queued the next run as soon as the 10-minute cooldown passed.
+ *
+ * Real Postgres job queue and worker: each submitted job runs the real
+ * handler (only the stale drain is stubbed to report the blocked shape) and
+ * fails through the worker's retry/dead-letter path; the submit gate reads
+ * the resulting rows. Identical no-progress failures back off, stop at the
+ * limit, and a changed blocker or real progress re-arms the backfill.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { getEngine, hasDatabase, setupDB, teardownDB } from './helpers.ts';
+import { MinionQueue } from '../../src/core/minions/queue.ts';
+import { MinionWorker } from '../../src/core/minions/worker.ts';
+import { makeEmbedBackfillHandler } from '../../src/core/minions/handlers/embed-backfill.ts';
+import { submitEmbedBackfill, type SubmitEmbedBackfillResult } from '../../src/core/embed-backfill-submit.ts';
+import { EMBED_BACKFILL_STALL_LIMIT } from '../../src/core/embed-backfill-stall.ts';
+import { embedBackfillStalledCheck } from '../../src/commands/doctor/checks/embed-backfill-stalled.ts';
+import type { EmbedStaleResult } from '../../src/core/embed-stale.ts';
+
+const describeE2E = hasDatabase() ? describe : describe.skip;
+const SOURCE = 'stall-example';
+const MIN = 60_000;
+
+let embedded = 0;
+const runStale = async (): Promise<EmbedStaleResult> => ({ embedded, chunksProcessed: embedded, pagesProcessed: embedded ? 1 : 0, invalidated: 0,
+ lastCursor: null, done: true, aborted: false, remaining: 2, blocked: 1, complete: false });
+
+/** A page with an unembedded chunk whose text projection is behind its revision: what the backfill's readiness pass reports blocked. */
+async function blockPage(slug: string) {
+ const engine = getEngine();
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `Body of ${slug}.` }, { sourceId: SOURCE });
+ const [page] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [SOURCE, slug]);
+ const [chunks] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM content_chunks WHERE page_id=$1', [page.id]);
+ if (chunks.n === 0) {
+ await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source) VALUES ($1, 0, $2, 'compiled_truth')`, [page.id, `Body of ${slug}.`]);
+ }
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE id=$1', [page.id]);
+}
+
+/** Submit through the gate, then run the job to its terminal state on a real worker. */
+async function submitAndRun(nowMs: number): Promise<SubmitEmbedBackfillResult> {
+ const engine = getEngine();
+ const result = await submitEmbedBackfill(engine, SOURCE, { reason: 'test', cooldownMinOverride: 10, spendCapUsdOverride: 1_000_000, nowMs });
+ if (result.status !== 'submitted') return result;
+ await engine.executeRaw('UPDATE minion_jobs SET backoff_delay=10 WHERE id=$1', [result.jobId]);
+ const queue = new MinionQueue(engine);
+ const worker = new MinionWorker(engine, { pollInterval: 25 });
+ worker.register('embed-backfill', makeEmbedBackfillHandler(engine, { runStale }));
+ const running = worker.start();
+ try {
+ for (let i = 0; i < 600; i++) {
+ const status = (await queue.getJob(result.jobId))?.status;
+ if (status === 'dead' || status === 'failed' || status === 'completed') break;
+ await new Promise(r => setTimeout(r, 25));
+ }
+ } finally {
+ worker.stop();
+ await running;
+ }
+ return result;
+}
+
+async function lastJob() {
+ const [row] = await getEngine().executeRaw<{ status: string; attempts_made: number; error_text: string | null; finished_at: Date }>(
+ "SELECT status, attempts_made, error_text, finished_at FROM minion_jobs WHERE name='embed-backfill' ORDER BY id DESC LIMIT 1");
+ return row;
+}
+
+describeE2E('E2E: embed-backfill stall cap (#6803)', () => {
+ beforeAll(async () => {
+ await setupDB();
+ await getEngine().executeRaw("INSERT INTO sources (id, name, config) VALUES ($1, $1, '{}'::jsonb) ON CONFLICT (id) DO NOTHING", [SOURCE]);
+ await blockPage('notes/blocked-a');
+ });
+ afterAll(async () => { await teardownDB(); });
+
+ test('identical no-progress failures back off, stop at the limit, and re-arm when the blocker changes', async () => {
+ embedded = 0;
+ // Run 1: the job fails, its retry sees the same blockers and dead-letters instead of failing a third time.
+ expect((await submitAndRun(Date.now())).status).toBe('submitted');
+ const first = await lastJob();
+ expect(first.status).toBe('dead');
+ expect(first.attempts_made).toBe(2);
+ expect(first.error_text).toStartWith('embed-backfill: incomplete; 2 chunks remain and 1 projections are blocked.');
+ expect(first.error_text).toContain('No progress since the previous attempt');
+
+ // The plain 10-minute cooldown would admit a run at +11 min; one identical failure doubles it.
+ let finished = new Date(first.finished_at).getTime();
+ const held = await submitAndRun(finished + 11 * MIN);
+ expect(held).toMatchObject({ status: 'cooldown', reason: 'recently_finished' });
+ expect((await submitAndRun(finished + 21 * MIN)).status).toBe('submitted');
+ finished = new Date((await lastJob()).finished_at).getTime();
+ // Two identical failures: 40 minutes.
+ expect((await submitAndRun(finished + 39 * MIN)).status).toBe('cooldown');
+ expect((await submitAndRun(finished + 41 * MIN)).status).toBe('submitted');
+ finished = new Date((await lastJob()).finished_at).getTime();
+
+ // At the limit, automatic submission stops however long it waits.
+ const stalled = await submitAndRun(finished + 7 * 24 * 60 * MIN);
+ expect(stalled).toMatchObject({ status: 'stalled', failures: EMBED_BACKFILL_STALL_LIMIT, remaining: 1, blocked: 1 });
+ const jobs = await getEngine().executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM minion_jobs WHERE name='embed-backfill'");
+ expect(jobs[0].n).toBe(EMBED_BACKFILL_STALL_LIMIT);
+
+ // doctor names the blocked page and the preview-first repair.
+ const check = await embedBackfillStalledCheck(getEngine());
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('notes/blocked-a');
+ expect(check.fix).toMatchObject({ argv: ['gbrain', 'projections', 'drain'], preview_argv: ['gbrain', 'projections', 'drain', '--dry-run', '--json'] });
+
+ // A changed blocker re-arms the backfill.
+ await blockPage('notes/blocked-b');
+ expect((await submitAndRun(finished + 7 * 24 * 60 * MIN)).status).toBe('submitted');
+
+ // Real progress ends the streak: the next identical failure starts over at the plain backoff.
+ embedded = 1;
+ expect((await submitAndRun(Date.now() + 7 * 24 * 60 * MIN)).status).toBe('submitted');
+ embedded = 0;
+ finished = new Date((await lastJob()).finished_at).getTime();
+ expect((await submitAndRun(finished + 11 * MIN)).status).toBe('submitted');
+ }, 120_000);
+});
diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.json
index 3fb3dd7df5..26758a43f3 100644
--- a/test/fixtures/goldens/doctor/content-pglite-human.json
+++ b/test/fixtures/goldens/doctor/content-pglite-human.json
@@ -153,6 +153,8 @@
" [OK] subagent_capability: Subagent tier resolves to default (claude-sonnet-4-6) — full tool-loop capability",
" [OK] facts_health: facts_health(default): 0 active, 0 today, 0 this week, 0 consolidated, top entities —",
" [OK] global_maintenance_timeouts: Brain-wide maintenance jobs are finishing within their deadline.",
+ " [OK] embed_backfill_stalled: No automatic embed-backfill is repeating the same failure.",
+ " [OK] connector_account_mismatch: No connector source is waiting for its account to be repinned.",
" [OK] legacy_job_authority: No queued job predates submission authority.",
" [OK] legacy_token_grant_shape: Every active legacy token uses the unified grant columns. The permissions mirror for older gbrain binaries is kept until 2026-11-04.",
" [OK] legacy_token_grant_drift: No legacy token grant has drifted from its permissions mirror.",
diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.json
index f63d0528d2..18b5f74d63 100644
--- a/test/fixtures/goldens/doctor/content-pglite-json.json
+++ b/test/fixtures/goldens/doctor/content-pglite-json.json
@@ -1933,6 +1933,20 @@
"name": "global_maintenance_timeouts",
"status": "ok"
},
+ {
+ "category": "ops",
+ "elapsed_ms": "<volatile>",
+ "message": "No automatic embed-backfill is repeating the same failure.",
+ "name": "embed_backfill_stalled",
+ "status": "ok"
+ },
+ {
+ "category": "ops",
+ "elapsed_ms": "<volatile>",
+ "message": "No connector source is waiting for its account to be repinned.",
+ "name": "connector_account_mismatch",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
index 8b2364223a..d3f01814d6 100644
--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
@@ -2051,6 +2051,20 @@
"name": "global_maintenance_timeouts",
"status": "ok"
},
+ {
+ "category": "ops",
+ "elapsed_ms": "<volatile>",
+ "message": "No automatic embed-backfill is repeating the same failure.",
+ "name": "embed_backfill_stalled",
+ "status": "ok"
+ },
+ {
+ "category": "ops",
+ "elapsed_ms": "<volatile>",
+ "message": "No connector source is waiting for its account to be repinned.",
+ "name": "connector_account_mismatch",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
@@ -5869,6 +5883,20 @@
"name": "global_maintenance_timeouts",
"status": "ok"
},
+ {
+ "category": "ops",
+ "elapsed_ms": "<volatile>",
+ "message": "No automatic embed-backfill is repeating the same failure.",
+ "name": "embed_backfill_stalled",
+ "status": "ok"
+ },
+ {
+ "category": "ops",
+ "elapsed_ms": "<volatile>",
+ "message": "No connector source is waiting for its account to be repinned.",
+ "name": "connector_account_mismatch",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
index e8f127bef4..8b539566a8 100644
--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
@@ -2055,6 +2055,20 @@
"name": "global_maintenance_timeouts",
"status": "ok"
},
+ {
+ "category": "ops",
+ "elapsed_ms": "<volatile>",
+ "message": "No automatic embed-backfill is repeating the same failure.",
+ "name": "embed_backfill_stalled",
+ "status": "ok"
+ },
+ {
+ "category": "ops",
+ "elapsed_ms": "<volatile>",
+ "message": "No connector source is waiting for its account to be repinned.",
+ "name": "connector_account_mismatch",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
@@ -5874,6 +5888,20 @@
"name": "global_maintenance_timeouts",
"status": "ok"
},
+ {
+ "category": "ops",
+ "elapsed_ms": "<volatile>",
+ "message": "No automatic embed-backfill is repeating the same failure.",
+ "name": "embed_backfill_stalled",
+ "status": "ok"
+ },
+ {
+ "category": "ops",
+ "elapsed_ms": "<volatile>",
+ "message": "No connector source is waiting for its account to be repinned.",
+ "name": "connector_account_mismatch",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 3f484f6fd5..5fc1bc425d 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -1748,6 +1748,20 @@
"name": "global_maintenance_timeouts",
"status": "ok"
},
+ {
+ "category": "ops",
+ "elapsed_ms": "<volatile>",
+ "message": "No automatic embed-backfill is repeating the same failure.",
+ "name": "embed_backfill_stalled",
+ "status": "ok"
+ },
+ {
+ "category": "ops",
+ "elapsed_ms": "<volatile>",
+ "message": "No connector source is waiting for its account to be repinned.",
+ "name": "connector_account_mismatch",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 080a98183a..36a7c8a08f 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -1804,6 +1804,20 @@
"name": "global_maintenance_timeouts",
"status": "ok"
},
+ {
+ "category": "ops",
+ "elapsed_ms": "<volatile>",
+ "message": "No automatic embed-backfill is repeating the same failure.",
+ "name": "embed_backfill_stalled",
+ "status": "ok"
+ },
+ {
+ "category": "ops",
+ "elapsed_ms": "<volatile>",
+ "message": "No connector source is waiting for its account to be repinned.",
+ "name": "connector_account_mismatch",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 91b38c3056..b2d8606b5a 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -1808,6 +1808,20 @@
"name": "global_maintenance_timeouts",
"status": "ok"
},
+ {
+ "category": "ops",
+ "elapsed_ms": "<volatile>",
+ "message": "No automatic embed-backfill is repeating the same failure.",
+ "name": "embed_backfill_stalled",
+ "status": "ok"
+ },
+ {
+ "category": "ops",
+ "elapsed_ms": "<volatile>",
+ "message": "No connector source is waiting for its account to be repinned.",
+ "name": "connector_account_mismatch",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index 9bb5e17af3..a13b94576a 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -649,6 +649,14 @@
"category": "ops",
"name": "global_maintenance_timeouts"
},
+ {
+ "category": "ops",
+ "name": "embed_backfill_stalled"
+ },
+ {
+ "category": "ops",
+ "name": "connector_account_mismatch"
+ },
{
"category": "ops",
"name": "legacy_job_authority"
diff --git a/test/projection-drain.test.ts b/test/projection-drain.test.ts
index d8f8bfa4a7..b89f29e78e 100644
--- a/test/projection-drain.test.ts
+++ b/test/projection-drain.test.ts
@@ -7,7 +7,7 @@
import { afterAll, beforeAll, expect, test } from 'bun:test';
import type { BrainEngine } from '../src/core/engine.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { rebuildPendingPageProjections, projectionBacklog } from '../src/core/page-state/projections.ts';
+import { rebuildPendingPageProjections, projectionBacklog, previewProjectionDrain } from '../src/core/page-state/projections.ts';
import { runResidentProjectionInvocation } from '../src/core/persistence/consumer.ts';
import { claimNextWrite, hasClaimableWrite } from '../src/core/persistence/journal.ts';
import { localHostId } from '../src/core/persistence/identity.ts';
@@ -128,6 +128,21 @@ test('a drain run tries a failing page once, keeps rebuilding the rest, and repo
}
}, 120_000);
+test('#6803: the drain preview lists a failed page first and rebuilds nothing', async () => {
+ for (const engine of engines) {
+ const sourceId = await backlog(engine, 3);
+ await engine.putPage('broken-code', { type: 'code', page_kind: 'code', title: 'Missing origin', compiled_truth: 'export const example = 1;' }, { sourceId });
+ await drainProjections(engine);
+ await engine.executeRaw(`INSERT INTO page_projection_jobs(source_incarnation,slug,revision,reason)
+ SELECT s.incarnation,p.slug,p.knowledge_revision,'test_backlog' FROM pages p JOIN sources s ON s.id=p.source_id WHERE p.source_id=$1 AND p.slug LIKE 'notes/%'`, [sourceId]);
+ const before = await engine.executeRaw<{ slug: string; reason: string; revision: string }>('SELECT slug,reason,revision::text AS revision FROM page_projection_jobs ORDER BY slug');
+ const preview = await previewProjectionDrain(engine, 2);
+ expect(preview).toMatchObject({ pending: 4, failed: 1 });
+ expect(preview.rows.map(r => [r.source_id, r.slug, r.reason])).toEqual([[sourceId, 'broken-code', 'rebuild_failed'], [sourceId, 'notes/n-0000', 'test_backlog']]);
+ expect(await engine.executeRaw('SELECT slug,reason,revision::text AS revision FROM page_projection_jobs ORDER BY slug')).toEqual(before);
+ }
+}, 120_000);
+
test('the resident selector waits 30 seconds before retrying a failed page; the drain command does not', async () => {
for (const engine of engines) {
const sourceId = await backlog(engine, 0);