Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(connector): record any run-ending error, clear only on complete runs, retry unpurged items, uncount purged pending items (#6831)

garrytan858a8092e848
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 20f4014628..d1cb27b2c2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -30,9 +30,9 @@ On an older release you can unblock it by hand: `gbrain pages purges list` names
### Itemized changes
-- **Per-item purged skip (#6831).** A managed connector page import whose content matches one of the source's page purge tombstones is skipped before admission (`ManagedConnectorSync.carriesPurgedPage`, same content hash the pages guard compares). If the guard still refuses at publication (`failed` / `purged_content`, for example a purge that landed mid-run), that refusal is skipped the same way, wherever it surfaces: the item's own wait, the pending set at the end of the run, or the pending set a previous run left. A skipped item is not a receipt the checkpoint waits on and never joins the automatic retry set. Every other failed receipt still fails the run, as before. Covers every connector on this path: Google contacts, calendar and Gmail, and GitHub.
-- **Run failures recorded (#6831).** The connector state row records the write refusal or credential error a run ended on (`last_failure`: code, message, item slug and request when the run ended on an item's receipt, time, and the count of runs in a row that ended that way); a run that finishes clears it. It also keeps the 20 most recent purged skips (`purged_items`) and the run's `last_run.purged_skipped` count.
-- **Status surfaces (#6831).** `gbrain sources status` (human and `--json` `connector.last_failure`, `connector.stopped`, `connector.purged_items`); `gbrain sync status --json` gains `connector_last_error` (with `class`, `safe_actions`, `needs_human` and a read-only `fix`), and its `next` names that fix when nothing else applies. `last_error`, the managed-sync cursor and its resume command are unchanged for connector sources. Doctor `sync_freshness` reports a connector source with 3 or more failed runs in a row as STOPPED.
+- **Per-item purged skip (#6831).** A managed connector page import whose content matches one of the source's page purge tombstones is skipped before admission (`ManagedConnectorSync.carriesPurgedPage`, same content hash the pages guard compares). If the guard still refuses at publication (`failed` / `purged_content`, for example a purge that landed mid-run), that refusal is skipped the same way, wherever it surfaces: the item's own wait, the pending set at the end of the run, or the pending set a previous run left. A skipped item is not a receipt the checkpoint waits on and is not counted as imported. A replayed refusal stays skipped, under `--retry-failed` too, while its tombstone stands; once `gbrain pages unpurge` cleared it, the next run retries the item once by itself. Every other failed receipt still fails the run, as before. Covers every connector on this path: Google contacts, calendar and Gmail, and GitHub.
+- **Run failures recorded (#6831).** The connector state row records the error a run ended on (a write refusal, a credential error or any other error, except a lost lease or the caller's own deadline or cancel; `last_failure`: code, message, item slug and request when the run ended on an item's receipt, time, and the count of runs in a row that ended that way); only a complete run clears it. It also keeps the 20 most recent purged skips (`purged_items`) and the run's `last_run.purged_skipped` count.
+- **Status surfaces (#6831).** `gbrain sources status` (human and `--json` `connector.last_failure`, `connector.stopped`, `connector.purged_items`); `gbrain sync status --json` gains `connector_last_error` (with `class`, `safe_actions`, `needs_human` and a read-only `fix`). `last_error`, `state`, `next`, the managed-sync cursor and its resume command are unchanged for connector sources. Doctor `sync_freshness` reports a connector source with 3 or more failed runs in a row as STOPPED. A run counts as failed when it ends on any error other than a lost lease or the caller's deadline or cancel; only a complete run clears the record, so a partial or wait-budget stop leaves it as it was. Recording needs managed persistence (`connector_state` exists only there).
- **`claude-cli` refusals (#6816).** `providerContentBlockReason` recognizes the `claude-cli` adapter's usage-policy refusal: the `claude-cli reported error: API Error:` prefix with no API status, the usage-policy link, and one of the refusal phrases Claude Code has used ("can't help with this", "safeguards flagged this", "violate our Usage Policy"). Any other `claude-cli` error is unchanged. With `chat_fallback_on_refusal: false`, such a refusal is no longer sent on to the next model in `chat_fallback_chain`.
- Tests: `test/connector-purged-item-6831.test.ts` (PGLite) and `test/e2e/connector-purged-item-6831.test.ts` (Postgres) fail on v0.60.260.0 with `purged_content` ending the run and pass here; `test/claude-cli-refusal-6816.test.ts` runs the real adapter and gateway against a stub CLI.
- No schema change.
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.md
index 93ed193f13..68af073fc0 100644
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@ -26,9 +26,9 @@ Managed connector ingestion, connector item holds and the no-op kernel (checkpoi
- `src/core/persistence/purge-deleted.ts` — `purgeDeletedPagesCoordinated` backs the cycle `purge` phase, the purge job, `purge_deleted_pages` and `gbrain pages purge-deleted`. Unmanaged brains keep the engine bulk delete; a managed brain purges each tombstone older than the window (skipping archived sources, which the source lifecycle purges) through `delete_page` with `purge: true` bound to its revision. Revision races are deferred to the next run; any other failure is listed in `blocked` and sets `error`, which fails the purge phase. Tests: `test/managed-writers-w3.test.ts`.
- `src/core/persistence/loop-fact-retirement.ts` — #5869 commitment-fact retirement for closed loops, one coordinator mutation on every brain (operation `loops_close`, intent `retire_loop_fact`, dispatched from `service.ts`): expires the fact and strikes its `## Facts` fence row (context `loop closed: <status>`) through the entity page publication in one transaction; no withdrawal tombstone. The shared rule (also `loopFactDrift`, used by doctor `loop_facts_drift` and `gbrain repair loop-facts`): only a fact in the loop's source that no other open loop references, re-checked under row locks at publication (`shared_with_open_loop`, `source_mismatch` otherwise). `retireLoopFact(ctx, loopId)` submits with the caller's grant and maps a refusal or pending write to `fact_expired: false, retryable: true, reason`. Tests: `test/loops-close-fact.serial.test.ts` (+ Postgres twin).
- `src/core/persistence/connector-authority.ts` -- classifies each Google/GitHub source as `connector_database` (managed, unbound), `bound` or `unmanaged` from `persistence_brain.enabled` and the source binding row. File-lane audits (doctor `undeclared_db_only_pages`, backup coverage) read it so a leftover cache directory at `local_path` is never taken for canonical files. Tests: `test/doctor-silent-death-checks.test.ts`, `test/backup-coverage.serial.test.ts`.
-- `src/core/persistence/connector-sync.ts` — managed Google/GitHub API ingestion through source-scoped journaled `connector_v2_import`/`_delete`/`_checkpoint`/`_google_receipts` intents and `managed-connector` checkpoint CAS, not Git cursors. The checkpoint key, admission `configHash`, mid-sweep change check and publication `source_changed` check all use the parsed-config identity from `connector-identity.ts`, so cycle stamps in `sources.config` never rotate them. Unbound connectors use reviewed `connector_database` SQL-only authority; bound connectors retain canonical file publication with guarded root/hash/revision/epoch. Every managed run checks the credential's resolved account against the pin in the connector state row before reading its checkpoint (`assertAccount`), then applies a requested `--reset-checkpoint` (pending writes resolved first, pin kept). Each import or delete is first screened by running `prepareConnectorMutation` on an unadmitted request through the no-op kernel; unchanged items take no admission. An unchanged checkpoint save is skipped and, when it would have stamped freshness, `last_sync_at` is stamped directly inside a lease-asserted coordinated write. Accepted-pending writes are progress: a 30-second total wait budget (writes committing within one second are free), at most one in-flight write per page, outstanding writes kept under the principal's outstanding and intent-byte limits, and `ConnectorWaitBudgetStop` (a `write_pending` error) when the budget is spent. The checkpoint never advances past a pending page; the run records its pending set in the state row, and the next run resolves it first (committed dropped, failed retried automatically through the retry-pointer path without `--retry-failed`, unreached failures after a complete sweep dropped and counted). Retired `managed_connector_*` intents route to `prepareOutdatedConnectorMutation`, which fails them `connector_intent_outdated` (detail `pre_upgrade` before the v176 cutoff). Standalone entry, page reads and submissions authenticate the current source, local grant and canonical owner and settle retained worktree publications before deriving request identity. Explicit `--retry-failed` atomically admits a linked attempt and stores a per-base-request `managed-connector-retry` pointer. Durable connector cursors, retry pointers and state rows survive generic seven-day checkpoint GC. Tests: `test/persistence-connectors.test.ts`, `test/persistence-connector-retry.test.ts`, `test/connector-checkpoint-identity.test.ts`, `test/connector-wave3.test.ts` and `test/helpers/connector-restart.ts` on PGLite and disposable Postgres. #6831: a page import whose content matches a source page purge tombstone is skipped per item instead of ending the run: screened before admission (`carriesPurgedPage`, the guard's content hash, read only when the source has a tombstone), and a `failed`/`purged_content` receipt the guard still produces (a purge that landed mid-run) is skipped wherever it surfaces (the item's wait, `refreshPending`, `resolvePendingSet`): it is dropped from `receipts`, never joins the automatic retry set, and is counted in `last_run.purged_skipped` and `purged_items`. A run that ends on an `OperationError` or a `CredentialError` records `last_failure` (code, message, the item and request when the run ended on that item's receipt, `consecutive`); `finish()` without an error clears it. Tests: `test/connector-purged-item-6831.test.ts` (+ `test/e2e/` twin).
+- `src/core/persistence/connector-sync.ts` — managed Google/GitHub API ingestion through source-scoped journaled `connector_v2_import`/`_delete`/`_checkpoint`/`_google_receipts` intents and `managed-connector` checkpoint CAS, not Git cursors. The checkpoint key, admission `configHash`, mid-sweep change check and publication `source_changed` check all use the parsed-config identity from `connector-identity.ts`, so cycle stamps in `sources.config` never rotate them. Unbound connectors use reviewed `connector_database` SQL-only authority; bound connectors retain canonical file publication with guarded root/hash/revision/epoch. Every managed run checks the credential's resolved account against the pin in the connector state row before reading its checkpoint (`assertAccount`), then applies a requested `--reset-checkpoint` (pending writes resolved first, pin kept). Each import or delete is first screened by running `prepareConnectorMutation` on an unadmitted request through the no-op kernel; unchanged items take no admission. An unchanged checkpoint save is skipped and, when it would have stamped freshness, `last_sync_at` is stamped directly inside a lease-asserted coordinated write. Accepted-pending writes are progress: a 30-second total wait budget (writes committing within one second are free), at most one in-flight write per page, outstanding writes kept under the principal's outstanding and intent-byte limits, and `ConnectorWaitBudgetStop` (a `write_pending` error) when the budget is spent. The checkpoint never advances past a pending page; the run records its pending set in the state row, and the next run resolves it first (committed dropped, failed retried automatically through the retry-pointer path without `--retry-failed`, unreached failures after a complete sweep dropped and counted). Retired `managed_connector_*` intents route to `prepareOutdatedConnectorMutation`, which fails them `connector_intent_outdated` (detail `pre_upgrade` before the v176 cutoff). Standalone entry, page reads and submissions authenticate the current source, local grant and canonical owner and settle retained worktree publications before deriving request identity. Explicit `--retry-failed` atomically admits a linked attempt and stores a per-base-request `managed-connector-retry` pointer. Durable connector cursors, retry pointers and state rows survive generic seven-day checkpoint GC. Tests: `test/persistence-connectors.test.ts`, `test/persistence-connector-retry.test.ts`, `test/connector-checkpoint-identity.test.ts`, `test/connector-wave3.test.ts` and `test/helpers/connector-restart.ts` on PGLite and disposable Postgres. #6831: a page import whose content matches a source page purge tombstone is skipped per item instead of ending the run: screened before admission (`carriesPurgedPage`, the guard's content hash, read only when the source has a tombstone), and a `failed`/`purged_content` receipt the guard still produces (a purge that landed mid-run) is skipped wherever it surfaces (the item's wait, `refreshPending`, `resolvePendingSet`): it is dropped from `receipts`, never joins the automatic retry set, has its optimistic pending count taken back, and is counted in `last_run.purged_skipped` and `purged_items`. A replayed purged receipt is re-checked against the live tombstones (`purgedNow`) before `mayRetry`: still purged, it is skipped even under `--retry-failed`; cleared, it gets one automatic retry. A run that ends on any error except `LockStolenError` or an aborted caller signal records `last_failure` (code, else `connector_error`; message, the item and request when the run ended on that item's receipt, `consecutive`); only a complete `finish()` (cursor saved, nothing pending or failed) clears it. Tests: `test/connector-purged-item-6831.test.ts` (+ `test/e2e/` twin).
- `src/core/persistence/connector-identity.ts` — `connectorIdentity(kind, rawConfig, localPath)` returns the parsed connector config and a digest over every parsed leaf except credential-delivery fields (Google `access`/`tokenCommand`/`tokenEnv`; GitHub `tokenEnv` and `app` under `scope: repos`, `app.pemPath` always; under `scope: auto` the token env without an App and the App ids are identity). `services`/`repos` are sorted and de-duplicated; a parser leaf missing from `CONNECTOR_LEAF_RULES` joins the identity. #6561: a leaf a parser starts emitting with a behavior-preserving default declares it as `elideWhen` (Google `contactsDir: 'people'`) and is left out of the digest while it holds it, so unchanged sources keep the pre-field key; the non-elided digest is kept as `aliasDigests` (`connectorCheckpointKeys` returns the stable key then its alias keys; `connectorIdentityMatches` accepts an admitted write's frozen `configHash` under either). Also `connectorCheckpointKey` and `isConnectorIntentKind`/`connectorIntentSql`, the one predicate for both intent namespaces. Test: `test/connector-identity.test.ts` enumerates every parser leaf.
-- `src/core/persistence/connector-state.ts` — (fix wave 4: also `first_attempt_at`, the autopilot connector dispatch gate, recorded before the first provider call of a validated, non-preview sync and seeded by migration v181) the per-source-incarnation `op='managed-connector-state'` row (fingerprint `digest({sourceId, incarnation})`, independent of the identity digest): account pin, pending set `{itemRef, requestId, baseRequestId, admittedAt}`, `upgrade_recovery` (`resumed`/`rewalking_once`/`none`) with `resumed_from`, `continuity_unverified` and last-run counts. `writeManagedConnectorState` checks the connector sync lease in the same statement. `connector-status.ts` renders it for `gbrain sources status` without the account. #6831: `purged_items` (newest `CONNECTOR_PURGED_LIMIT` purged skips) and `last_failure` (`ConnectorRunFailure`); `CONNECTOR_STOPPED_RUNS` (3) consecutive failed runs read as stopped in `connector-status.ts` (`sources status` lines, `readConnectorLastError` for `sync status`'s `connector_last_error` and its fallback `next`) and doctor `sync_freshness` (`stoppedConnectorIssues` in `doctor/sync-outcome.ts`).
+- `src/core/persistence/connector-state.ts` — (fix wave 4: also `first_attempt_at`, the autopilot connector dispatch gate, recorded before the first provider call of a validated, non-preview sync and seeded by migration v181) the per-source-incarnation `op='managed-connector-state'` row (fingerprint `digest({sourceId, incarnation})`, independent of the identity digest): account pin, pending set `{itemRef, requestId, baseRequestId, admittedAt}`, `upgrade_recovery` (`resumed`/`rewalking_once`/`none`) with `resumed_from`, `continuity_unverified` and last-run counts. `writeManagedConnectorState` checks the connector sync lease in the same statement. `connector-status.ts` renders it for `gbrain sources status` without the account. #6831: `purged_items` (newest `CONNECTOR_PURGED_LIMIT` purged skips) and `last_failure` (`ConnectorRunFailure`); `CONNECTOR_STOPPED_RUNS` (3) consecutive failed runs read as stopped in `connector-status.ts` (`sources status` lines, `readConnectorLastError` for `sync status`'s additive `connector_last_error`; `last_error`, `state` and `next` are untouched) and doctor `sync_freshness` (`stoppedConnectorIssues` in `doctor/sync-outcome.ts`).
- `src/core/connectors/item-holds.ts` — fix wave 4 connector item holds, shared by Gmail and GitHub on managed and unmanaged brains: `classifyConnectorError` (the one table: source-scoped, rate-limit and item-scoped codes, content vs transient class) and `ItemHoldsRun` (hold after 3 consecutive attempted runs at one upstream version; circuit breaker at 5 attempted items with half transient or 5 and half one code; backoff 1 h/6 h/24 h/daily for 7 days; cap 100, `connector_holds_exhausted`). A run's changes merge only in `finish()`, so mid-run checkpoints carry the holds the run began with and a cursor never passes an item that is not already held. `carryLegacyFailCounts` reads the retired Gmail ledger once.
- `src/core/connectors/item-holds-store.ts` + `connector-hold-session.ts` — reads holds from the cursor state (managed checkpoint row or the unmanaged state file) for `sources status`, doctor `connector_held_items` and `open_loops` completeness; the `connector-hold-retry` request rows and the pending `managed-connector-retry` pointers `sources retry-held` writes; the per-run session that skips held items, publishes holds on a managed abort (`publishHolds`), releases held items' terminal receipts from the automatic retry set and consumes retry-held keys. Git-source holds are not read here: only `sources status` (`persistence/connector-status.ts` `readGitHoldStatuses`, `sources status <id>` filters to one source) and `sources retry-held` (a Git source records a `sync-hold-retry` re-screen request for its held paths; `gbrain sync --retry-held` refuses with that pointer) show them beside connector holds. Writer deactivation and activation never read or block on them.
- `src/core/connectors/connector-text.ts` — #5752 render boundary: prose sanitized with `sanitizeForJsonb` before the no-op screen; identity fields refuse with `invalid_connector_text`.
diff --git a/src/core/persistence/connector-sync.ts b/src/core/persistence/connector-sync.ts
index 60343df06c..11f192de9f 100644
--- a/src/core/persistence/connector-sync.ts
+++ b/src/core/persistence/connector-sync.ts
@@ -47,7 +47,6 @@ import { readConnectorV2Cutoff } from './connector-checkpoint-migration.ts';
import { declarePersistenceProtocol } from './protocol.ts';
import { intentCarriesPurgedContent } from './purged-intent.ts';
import { PERSISTENCE_IPC_MAX_BYTES } from './ipc.ts';
-import { isCredentialError, type CredentialError } from '../creds/errors.ts';
import type { GoogleSourceConfig } from '../google/types.ts';
interface ConnectorLease { handle: DbLockHandle; signal: AbortSignal; }
@@ -314,7 +313,9 @@ export async function withConnectorSync<T>(engine: BrainEngine, sourceId: string
result = await work(session, options);
} catch (error) {
if (!(error instanceof ConnectorWaitBudgetStop)) {
- if (error instanceof OperationError || isCredentialError(error)) await session.finish(error).catch(() => {});
+ // #6831: a run cut short by its caller's deadline or cancel is not a failure of the source.
+ const failure = combined.aborted ? undefined : error;
+ if (error instanceof OperationError || (failure && !(error instanceof LockStolenError))) await session.finish(failure).catch(() => {});
throw error;
}
await session.finish();
@@ -328,7 +329,7 @@ export async function withConnectorSync<T>(engine: BrainEngine, sourceId: string
});
}
-interface PendingWrite { entry: ConnectorPendingEntry; row: WriteRequest; bytes: number }
+interface PendingWrite { entry: ConnectorPendingEntry; row: WriteRequest; bytes: number; counted?: 'created' | 'updated' | 'deleted' }
/** A connector sweep that ended with accepted writes pending, or stopped on its wait budget, reports `partial` / `writer_pending`. */
export function pendingConnectorResult(result: SyncResult | null, session: ManagedConnectorSync): SyncResult {
@@ -688,7 +689,11 @@ export class ManagedConnectorSync {
if (!row || row.state === 'committed') { this.pendingRows.delete(id); continue; }
if (isTerminal(row)) {
this.pendingRows.delete(id);
- if (purgedRefusal(row)) this.skipPurged(pending.entry.itemRef, row); else this.failedPending.push(pending.entry);
+ if (!purgedRefusal(row)) this.failedPending.push(pending.entry);
+ else {
+ if (pending.counted) this.counts[pending.counted]--;
+ this.skipPurged(pending.entry.itemRef, row);
+ }
continue;
}
pending.row = row;
@@ -746,10 +751,10 @@ export class ManagedConnectorSync {
}
/**
* Records the run's pending set, counts and upgrade state; written only while the lease is held. `failure` is the
- * error the run ended on (#6831): it is recorded with a count of runs in a row that ended that way, and a run that
- * ends without one clears it.
+ * error the run ended on (#6831): it is recorded with a count of runs in a row that ended that way. Only a complete
+ * run (its cursor saved, nothing pending or failed) clears it; a partial or wait-budget stop leaves it as it was.
*/
- async finish(failure?: OperationError | CredentialError): Promise<void> {
+ async finish(failure?: unknown): Promise<void> {
await this.refreshPending().catch(() => {});
const now = new Date().toISOString();
const outstanding = [...this.pendingRows.values()].map(pending => pending.entry);
@@ -771,8 +776,10 @@ export class ManagedConnectorSync {
.filter(entry => !listed.has(entry.slug) && !!listed.add(entry.slug)).slice(0, CONNECTOR_PURGED_LIMIT);
const receipt = failure instanceof OperationError ? failure.writeRequest : undefined;
const item = receipt && receipt.request_id === this.lastFailedItem?.requestId ? this.lastFailedItem : null;
- const lastFailure = failure ? { code: (failure instanceof OperationError ? failure.writeError : undefined) ?? failure.code, message: failure.message, slug: item?.slug ?? null, request_id: item?.requestId ?? null,
- at: now, consecutive: (this.connectorState.last_failure?.consecutive ?? 0) + 1 } : null;
+ const named = failure as { code?: unknown; message?: unknown } | undefined;
+ const lastFailure = failure ? { code: (failure instanceof OperationError ? failure.writeError : undefined) ?? (typeof named?.code === 'string' && named.code ? named.code : 'connector_error'),
+ message: typeof named?.message === 'string' ? named.message : String(failure), slug: item?.slug ?? null, request_id: item?.requestId ?? null,
+ at: now, consecutive: (this.connectorState.last_failure?.consecutive ?? 0) + 1 } : complete ? null : this.connectorState.last_failure ?? null;
this.connectorState = { ...this.connectorState, pending, upgrade_recovery: recovery, purged_items: purgedItems, last_failure: lastFailure, last_run: {
page_admissions: this.counts.page_admissions, skipped_unchanged: this.counts.skipped_unchanged, pending: pending.length,
checkpoint_admissions: this.counts.checkpoint_admissions, stopped_on_wait_budget: this.stopped, dropped_upstream: this.counts.dropped_upstream,
@@ -799,7 +806,11 @@ export class ManagedConnectorSync {
* guard's refusal, which `submit` and the pending-set paths skip the same way.
*/
private async carriesPurgedPage(slug: string, content: string | undefined): Promise<boolean> {
- if (!this.hasPagePurges || !content) return false;
+ return this.hasPagePurges && this.purgedNow(slug, content);
+ }
+ /** Whether a page tombstone of the source matches this content now, read without the per-run presence shortcut. */
+ private async purgedNow(slug: string, content: string | undefined): Promise<boolean> {
+ if (!content) return false;
return intentCarriesPurgedContent(this.engine, { source_id: this.sourceId, slug, intent: { content } }, { facts: false, pages: true });
}
/**
@@ -931,11 +942,17 @@ export class ManagedConnectorSync {
{ fix: ownerStatusFix(this.sourceId, 'Shows the source\'s receipts and any retained recovery before a retry is approved again.') });
return { retry, input, row };
};
+ const prior = await selected(this.engine);
+ let row = prior.row;
+ // #6831: a replayed purged refusal stays skipped (even under --retry-failed) while its tombstone stands; once the
+ // owner cleared it, the item gets one automatic retry through the guarded retry path below.
+ if (kind === 'connector_v2_import' && row && purgedRefusal(row) && row.request_id === (this.retryApprovals.get(baseRequestId) ?? baseRequestId)) {
+ if (await this.purgedNow(slug, extra.content)) { this.skipPurged(slug, row); return { row: null, pending: false, created: false }; }
+ this.autoRetry.add(baseRequestId);
+ }
const automatic = this.autoRetry.has(baseRequestId);
const mayRetry = (row: WriteRequest | null) => (this.retryFailed || automatic) && row && ['failed', 'conflict'].includes(row.state) &&
row.request_id === (this.retryApprovals.get(baseRequestId) ?? baseRequestId);
- const prior = await selected(this.engine);
- let row = prior.row;
let admitted = false;
if (mayRetry(row)) {
const failedRow = row!;
@@ -1036,9 +1053,10 @@ export class ManagedConnectorSync {
return { row, pending: false, created: row.outcome?.status === 'created' };
}
this.receipts.push(row.id);
- this.pendingRows.set(row.id, { row, bytes: Buffer.byteLength(JSON.stringify(intent)),
+ const counted = !snapshot ? 'created' : kind === 'connector_v2_delete' ? 'deleted' : 'updated';
+ this.pendingRows.set(row.id, { row, bytes: Buffer.byteLength(JSON.stringify(intent)), counted,
entry: { itemRef: slug, requestId: row.request_id, baseRequestId, admittedAt: new Date(row.created_at).toISOString() } });
- if (!snapshot) this.counts.created++; else if (kind === 'connector_v2_delete') this.counts.deleted++; else this.counts.updated++;
+ this.counts[counted]++;
await this.makeRoom();
return { row, pending: true, created: !snapshot };
}
diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.ts
index 0483f2676a..d1726e994f 100644
--- a/src/core/persistence/sync-status.ts
+++ b/src/core/persistence/sync-status.ts
@@ -245,7 +245,7 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string): Pro
cursor: header ? { index: Number(header.index), total: Number(header.total), pinned_target: header.target ?? null, last_advance_at: p ? new Date(p.lastAt).toISOString() : null, done: !!header.done } : null,
committed_last_10m: Number(committed?.n ?? 0), ...estimate, live_job_id: liveJob, holds, last_error: lastError, needs_human: !!human, ...(human ? { human_reason: human.human_reason } : {}),
resume_argv: resume, ...blockers, cursors: await liveCursors(engine, sourceId, source.incarnation, selected?.key ?? null, failures),
- terminal_failures: terminal, connector_last_error: connectorLastError, next: next ?? recovery_next ?? connectorLastError?.fix ?? null };
+ terminal_failures: terminal, connector_last_error: connectorLastError, next: next ?? recovery_next ?? null };
}
/**
diff --git a/test/connector-purged-item-6831.test.ts b/test/connector-purged-item-6831.test.ts
index 3ccd20eaa0..7fe3eb51a9 100644
--- a/test/connector-purged-item-6831.test.ts
+++ b/test/connector-purged-item-6831.test.ts
@@ -16,17 +16,18 @@ import { calendarRelPath } from '../src/core/google/google-render.ts';
import { slugifyPath } from '../src/core/sync.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
-import { withConnectorSync } from '../src/core/persistence/connector-sync.ts';
+import { unpurgePage } from '../src/core/persistence/page-purge.ts';
+import { CONNECTOR_WAIT_BUDGET_MS, connectorWaitBudget, withConnectorSync } from '../src/core/persistence/connector-sync.ts';
import { CONNECTOR_STOPPED_RUNS, readManagedConnectorState } from '../src/core/persistence/connector-state.ts';
import { connectorStatusLines, readConnectorSourceStatuses } from '../src/core/persistence/connector-status.ts';
import { readSyncStatus } from '../src/core/persistence/sync-status.ts';
import { checkSyncFreshness } from '../src/commands/doctor/checks/extraction-sync.ts';
import { opError } from '../src/core/ops/contract.ts';
import { CredentialError } from '../src/core/creds/errors.ts';
-import { contact, createConnectorFixture, json, options, settleConnectorWrites, withGoogleAccount } from './helpers/connector-fixture.ts';
+import { contact, createConnectorFixture, json, options, settleConnectorWrites, withGoogleAccount, withPausedOwnerBudget } from './helpers/connector-fixture.ts';
import { withEnv } from './helpers/with-env.ts';
-const { engines, env, source, setup, teardown } = createConnectorFixture();
+const { engines, env, source, boundSource, setup, teardown } = createConnectorFixture();
beforeAll(setup, 120_000);
afterAll(teardown);
@@ -150,6 +151,61 @@ test('#6831: a purge that lands after the run started is refused by the pages gu
expect(refused).toEqual({ state: 'failed', error_code: 'purged_content' });
expect(state.pending).toEqual([]);
await disposePersistenceConsumer(engine);
+
+ // The refusing run saved no cursor, so the next runs replay the same refused receipt. While the tombstone stands it
+ // stays skipped, under --retry-failed too, and nothing is admitted again.
+ const admissions = async () => (await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND slug=$2', [f.id, 'notes/item-1']))[0].n;
+ const before = await admissions();
+ const replay = (opts: typeof options & { retryFailed?: boolean }) => withConnectorSync(engine, f.id, 'google', cfg, opts, async managed => managed!.importMarkdown('notes/item-1.md', page(1)));
+ const quiet = spyOn(process.stderr, 'write').mockImplementation(() => true);
+ try {
+ expect((await replay({ ...options, retryFailed: true })).status).toBe('skipped');
+ expect(await admissions()).toBe(before);
+ // Once the owner clears the tombstone, the replayed refusal is retried and the item comes back.
+ await unpurgePage(ctx(engine, f.id), { slug: 'notes/item-1', source_id: f.id });
+ expect((await replay(options)).status).toBe('imported');
+ } finally { quiet.mockRestore(); }
+ await settleConnectorWrites(engine, f.id).catch(() => {});
+ expect(await liveSlugs(engine, f.id)).toEqual(['notes/item-1', 'notes/item-2']);
+ await disposePersistenceConsumer(engine);
+ }
+}), 120_000);
+
+test('#6831: an item that was pending when the run counted it and is then refused as purged content is counted as skipped, not imported', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const f = await boundSource(engine, config);
+ const cfg = parseGoogleSourceConfig(config, f.dir);
+ const page = (body: string) => `---\ntype: note\ntitle: Synthetic pending item\n---\n# Synthetic pending item\n\n${body}\n`;
+ await withConnectorSync(engine, f.id, 'google', cfg, options, async managed => { await managed!.importMarkdown('notes/item-1.md', page('First.')); await managed!.saveState({ first: true }); });
+ await settleConnectorWrites(engine, f.id);
+ await disposePersistenceConsumer(engine);
+ const binding = f.binding;
+ await engine.executeRaw("UPDATE persistence_worktrees SET state='draining' WHERE id=$1::uuid", [binding.worktree_id]);
+ const quiet = spyOn(process.stderr, 'write').mockImplementation(() => true);
+ let counts;
+ try {
+ counts = await withPausedOwnerBudget(() => withConnectorSync(engine, f.id, 'google', cfg, options, async managed => {
+ const imported = await managed!.importMarkdown('notes/item-1.md', page('Second.'));
+ expect(imported.status).toBe('imported');
+ expect(managed!.counts.updated).toBe(1);
+ // The owner refuses the pending update at publication: the page was purged meanwhile.
+ await engine.executeRaw("UPDATE persistence_requests SET state='failed', error_code='purged_content', error_message='this page content was purged from this source and cannot be saved again' WHERE source_id=$1 AND state NOT IN ('committed','failed')", [f.id]);
+ // The owner resumes, so the cursor can commit on the production budget.
+ await engine.executeRaw("UPDATE persistence_worktrees SET state='active' WHERE id=$1::uuid", [binding.worktree_id]);
+ connectorWaitBudget.ms = CONNECTOR_WAIT_BUDGET_MS;
+ await managed!.saveState({ second: true });
+ return { ...managed!.counts };
+ }));
+ } finally {
+ quiet.mockRestore();
+ await engine.executeRaw("UPDATE persistence_worktrees SET state='active' WHERE id=$1::uuid", [binding.worktree_id]);
+ }
+ expect(counts).toMatchObject({ created: 0, updated: 0, purged_skipped: 1 });
+ const state = await connectorState(engine, f.id);
+ expect(state.last_run).toMatchObject({ purged_skipped: 1 });
+ expect(state.purged_items?.map(item => item.slug)).toEqual(['notes/item-1']);
+ expect(state.pending).toEqual([]);
+ await disposePersistenceConsumer(engine);
}
}), 120_000);
@@ -171,7 +227,8 @@ test('#6831: a connector source whose runs keep ending on an error reads as stop
const sync = await readSyncStatus(engine, f.id);
expect(sync.connector_last_error).toMatchObject({ code: 'invalid_fence', consecutive: CONNECTOR_STOPPED_RUNS, stopped: true });
expect(sync.last_error).toBeNull();
- expect(sync.next?.argv).toEqual(['gbrain', 'sources', 'status', f.id, '--json']);
+ expect(sync.connector_last_error?.fix.argv).toEqual(['gbrain', 'sources', 'status', f.id, '--json']);
+ expect(sync.next?.argv).not.toEqual(['gbrain', 'sources', 'status', f.id, '--json']);
// A recent last_sync_at no longer hides the stop.
await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
await engine.executeRaw('UPDATE sources SET last_sync_at=now() WHERE id=$1', [f.id]);
@@ -185,8 +242,20 @@ test('#6831: a connector source whose runs keep ending on an error reads as stop
.rejects.toMatchObject({ code: 'scope_missing' });
expect((await connectorState(engine, f.id)).last_failure).toMatchObject({ code: 'scope_missing', consecutive: CONNECTOR_STOPPED_RUNS + 1 });
- // A run that finishes clears the record.
+ // Any other error that ends the run counts too (a missing token is a plain Error).
+ await expect(withConnectorSync(engine, f.id, 'google', cfg, options, async () => { throw new Error('No token in CONNECTOR_TEST_TOKEN'); }))
+ .rejects.toThrow('No token');
+ expect((await connectorState(engine, f.id)).last_failure).toMatchObject({ code: 'connector_error', message: 'No token in CONNECTOR_TEST_TOKEN', consecutive: CONNECTOR_STOPPED_RUNS + 2 });
+ // A run its caller cancelled is not a failure of the source, and a partial run (no cursor saved) proves no recovery.
+ const cancel = new AbortController();
+ await expect(withConnectorSync(engine, f.id, 'google', cfg, { ...options, signal: cancel.signal }, async () => { cancel.abort(); throw new Error('cancelled by caller'); }))
+ .rejects.toThrow('cancelled by caller');
await withConnectorSync(engine, f.id, 'google', cfg, options, async () => undefined);
+ expect((await connectorState(engine, f.id)).last_failure).toMatchObject({ code: 'connector_error', consecutive: CONNECTOR_STOPPED_RUNS + 2 });
+ expect((await readSyncStatus(engine, f.id)).connector_last_error).toMatchObject({ stopped: true });
+
+ // A run that completes (its cursor saved) clears the record.
+ await withConnectorSync(engine, f.id, 'google', cfg, options, async managed => { await managed!.saveState({ recovered: true }); });
expect((await connectorState(engine, f.id)).last_failure).toBeNull();
expect((await readSyncStatus(engine, f.id)).connector_last_error).toBeNull();
expect((await checkSyncFreshness(engine)).message).not.toContain(`Source '${f.id}' is STOPPED`);