Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(connectors): Google default contactsDir keeps the pre-field checkpoint key (#6561)
time-attacka34e0e556573
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex 9f8c577a1b..08fa9c49ca 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -27,7 +27,7 @@ Managed connector ingestion, connector item holds and the no-op kernel (checkpoi- `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.-- `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. 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-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.- `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.@@ -39,7 +39,7 @@ Managed connector ingestion, connector item holds and the no-op kernel (checkpoi- `src/core/persistence/screening-paths.ts` — GBRA-75 wave 7: `withScreeningPaths(run)` opens one screening batch's memo of root-level filesystem facts and `screeningPath(key, compute)` resolves each once inside it: other sources' root realpaths (`assertImportPaths`), shared skillpack root canonical paths and the source root's Git scope (`knowledge-guard.ts`). Per-file paths are never memoized; a nested batch joins the open one; the memo closes with `run`, so work that outlives it computes fresh; a throwing compute is never memoized. Opened by the managed import plan and screen loops (`import-mutations.ts`), each sync waiver screen (`screenWaiver`) and `sync-run.ts` `waiveRun`'s screens. Tests: `test/persistence-skip-cost.test.ts`.- `src/core/persistence/sync-waivers.ts` — managed-sync no-op waivers (#5470, #5984). `waiveNoopEntry` screens a frozen, unadmitted entry: an unchanged import (`unchangedSyncImport`, moved here from `sync-run.ts`, with the #5751 working-tree kernel waivers) or a delete whose page is already soft-deleted at the entry's frozen `expected_revision` with its file absent (never an unowned deletion or a rename). A candidate runs `validateSyncAuthority` first (a revoked grant throws before any waiver), then commits in one transaction with a fixed lock order: page guard (`lockPageKeys`), then the managed-sync cursor row `FOR UPDATE`; it re-reads the snapshot (and, for deletes, the origin and file absence) and refuses while `UNFINISHED_PAGE_REQUEST_SQL` finds an unfinished request for the page by slug, page id or a `renameFrom` naming it. That lookup is three `LIMIT 1` branches served by `persistence_requests_pending`, `persistence_requests_recovery` and the database-only pending index (EXPLAIN pinned in `test/persistence-managed-sync.test.ts`). A cursor that moved meanwhile is adopted instead of waived again, so `waived` counts only increment in the winning transaction. `GBRAIN_SYNC_WAIVE_NOOP=0` admits every entry. #6278: the lookup also matches the entry's file path, origin and a rename from that origin (`unfinishedPageRequestParams`), so the hold gate in `sync-run.ts` shares it. `unchangedSyncImport` (and so `sameContentAtOrigin`'s preparation) runs the sync preparer under `raceSyncBudget` against `persistence.sync_preparation_ms` (`syncPreparationBudgetMs`, read at most every 5 s, default 120 s) and the run's signal: past the budget nothing is waived and the origin refusal stands (fail open, nothing counted or held, `SyncPreparationBudgetExceeded`); a cancelled run propagates. GBRA-75 wave 8: `unchangedSyncImport` prepares with `{ unsaved: true }`, so its validation also accepts this run's cursor with nothing pending; before that every import waiver-run screen failed the cursor check and each unchanged file took a pending save, a second screen and its own waiver transaction. `waiveNoopRun` (up to 64 entries, one cursor write) re-reads the owner epoch under its lock (a change passes nothing; the per-entry path then refuses it) and each import's file bytes (an edit ends the prefix). Tests: `test/sync-waiver-budget.test.ts`, `test/sync-waiver-run-imports.test.ts`, `test/persistence-managed-sync.test.ts` (#5984 waiver cases), `test/persistence-sync-legacy-files-5751.test.ts`.- `src/core/persistence/accepted-pending.ts` — `acceptedPendingReceipt(error)`: the shared test for an accepted, not yet committed write, used by managed atom publication, extract_atoms, managed import and the connector budget. `publicationHold(error)` returns `pending` for such a receipt or `contention` for an OperationError `storage_error` with detail `database_contention` and no receipt (admission rolled back, nothing recorded), else null — never from a message, a terminal receipt, a contention error carrying a receipt or a permission refusal; `publishOrHold(fn)` runs one publication and returns null on commit, the hold when there is one, and rethrows anything else. Used by the patterns, drift and synthesize dream phases.-- `src/core/persistence/connector-checkpoint-migration.ts` — migration 176 and orphan cleanup. The newest committed checkpoint receipt per source incarnation (found by slug, so a compacted one is still seen and re-walks) is copied to the stable key with `INSERT … ON CONFLICT DO NOTHING`; state rows are seeded; the cutoff is stored in `op_checkpoints` (`op=managed-connector-migration`, fingerprint `v2-cutoff`, excluded from the checkpoint purge). `orphanConnectorCheckpoints` keeps rows touched after the start, rows any registered source (archived included) can load, and rows referenced by a non-terminal request or a pending set; timestamps bind as text. `gbrain repair connector-checkpoints` (`src/core/repair/connector-checkpoints.ts`) and the `connector_checkpoints` doctor check reuse it with a 7-day floor. `connector-reset.ts` guards `gbrain sync --reset-checkpoint` to connector sources.+- `src/core/persistence/connector-checkpoint-migration.ts` — migration 176 and orphan cleanup. The newest committed checkpoint receipt per source incarnation (found by slug, so a compacted one is still seen and re-walks) is copied to the stable key with `INSERT … ON CONFLICT DO NOTHING`; state rows are seeded; the cutoff is stored in `op_checkpoints` (`op=managed-connector-migration`, fingerprint `v2-cutoff`, excluded from the checkpoint purge). `orphanConnectorCheckpoints` keeps rows touched after the start, rows any registered source (archived included) can load under its stable or alias key (`loadableConnectorKeys`, #6561), and rows referenced by a non-terminal request or a pending set; timestamps bind as text. `gbrain repair connector-checkpoints` (`src/core/repair/connector-checkpoints.ts`, whose preview counts alias-kept rows as `alias_protected`) and the `connector_checkpoints` doctor check reuse it with a 7-day floor. Migration 248 (`migrateConnectorAliasCheckpoints`, #6561; placeholder number) copies an interim-key cursor to the stable key when that has none, and swaps the two rows (one transaction, compare-and-set, generation above both) when only the interim cursor finished its Gmail backfill or both finished and it reached newer mail. `connector-reset.ts` guards `gbrain sync --reset-checkpoint` to connector sources.- `src/core/persistence/graduation-target.ts` — engine graduation target side. `resolveTargetRoutes` reads the URL from `--url` or the `--url-env` variable and resolves the DDL route once (explicit `GBRAIN_DIRECT_DATABASE_URL`, else the Supabase direct derivation, else the main URL); `connectTargetEngines` hands that route to the connection manager as an explicit override, so no session-pooler fallback is chosen for the run. `targetIdentity` hashes host, port, database and user, never the password; `redactTargetUrl` is the only display form. `probeTarget` runs read-only probes in `BEGIN READ ONLY` sessions on both routes (server version, `vector` with halfvec, CREATE privilege, `session_replication_role` permission inside a savepoint, table ownership, seed-only emptiness, existing embedding columns, the role's superuser and BYPASSRLS standing and the auto-RLS event trigger and its function owner); `targetProbeBlockers` (non-superuser targets get the exact SQL a DBA runs for `vector`, BYPASSRLS and the event trigger) and `assertTargetReachable` turn a probe into plan blockers and typed refusals. `crossCheckRoutes` proves both routes reach one database with a transaction-scoped advisory lock keyed by a fresh nonce, read back from `pg_locks` through the other route. Tests: `test/graduation-target.test.ts`.- `src/core/persistence/graduation-drain.ts` — engine graduation drain. `graduationBlockers` lists what keeps a brain from copying, each with its structured action: requests this host owns (drained), requests and host bindings owned by another host, recovering topology changes and effects, the writer admin lock, and OAuth clients bound to a missing source (an FK only Postgres enforces; never cleared silently, since unbinding widens access). `drainForGraduation` refuses up front on anything the drain cannot clear, then publishes this host's queued, running and recovering requests with a `requestsOnly` `PersistenceConsumer` bounded by the timeout and always runs its stop barrier before returning; the `graduation_drain_timeout` refusal is built by `graduation-errors.ts`. `freezeSource` stops the resident consumer and sets the PGLite connection to read-only transactions; `withSourceWritable` runs one read-write transaction for custody writes. Tests: `test/graduation-drain.test.ts`.- `src/core/persistence/graduation-copy.ts` — engine graduation copier (in process). `copyTable` reads source rows through the digest's own plan (`digestPlan` with inventory transforms, `rowFilter`, `::text` values, COLLATE "C" keyset batches) and writes them in one target transaction per table that sets `gbrain.graduation_run`, bypasses user triggers (`session_replication_role = replica`, or DISABLE/ENABLE TRIGGER by name in the same transaction, never the `gbrain_graduation_fence` triggers), deletes the target's rows (seed rows included) and inserts byte-sized batches as one `$1::text::jsonb` array cast back per column type. The per-column contract (`columnContract`) refuses missing, retyped, target-only or differently generated columns outside the entry's `columnAllowlist`; generated columns are never inserted. Self-FKs take a second update pass under DISABLE TRIGGER. `copySequences` applies each source sequence's exact position, raised to the target column maximum. `deferIndexes`/`buildDeferredIndexes` drop and rebuild HNSW (through `buildDeferredAnnIndexes`) and GIN indexes, keeping the pending list in the target-owned `graduation.deferred_indexes` config row. Tests: `test/graduation-copy.test.ts`, `test/e2e/graduation-copy.test.ts`.diff --git a/src/core/persistence/connector-checkpoint-migration.ts b/src/core/persistence/connector-checkpoint-migration.tsindex d5e53eda08..854c0a21b5 100644--- a/src/core/persistence/connector-checkpoint-migration.ts+++ b/src/core/persistence/connector-checkpoint-migration.ts@@ -20,7 +20,7 @@* older binary may still be using an old key during a mixed-version window.*/import type { BrainEngine } from '../engine.ts';-import { connectorCheckpointKey, connectorIdentity, type ConnectorKind } from './connector-identity.ts';+import { connectorCheckpointKeys, connectorIdentity, type ConnectorKind } from './connector-identity.ts';import { CONNECTOR_STATE_OP, connectorStateKey, emptyConnectorState, type ConnectorState } from './connector-state.ts';type Sql = Pick<BrainEngine, 'executeRaw' | 'transaction' | 'kind'>;@@ -33,14 +33,22 @@ export async function readConnectorV2Cutoff(engine: Pick<BrainEngine, 'executeRainterface SourceRow { id: string; incarnation: string; local_path: string | null; config: Record<string, unknown> | string | null; archived: boolean }-/** Stable checkpoint keys of every registered connector source (archived ones included: a restore must still find its cursor). */-export async function loadableConnectorKeys(engine: Pick<BrainEngine, 'executeRaw'>): Promise<Map<string, { id: string; incarnation: string; archived: boolean }>> {+export interface LoadableConnectorKey { id: string; incarnation: string; archived: boolean; alias: boolean }++/**+ * Checkpoint keys of every registered connector source (archived ones included: a restore must still find its+ * cursor): each source's stable key, plus its alias keys (`alias: true`, #6561) so rows an earlier release wrote+ * under them are never orphans while the source exists.+ */+export async function loadableConnectorKeys(engine: Pick<BrainEngine, 'executeRaw'>): Promise<Map<string, LoadableConnectorKey>> {const rows = await engine.executeRaw<SourceRow>("SELECT id,incarnation::text,local_path,config,archived FROM sources WHERE config->>'kind' IN ('google','github')");- const keys = new Map<string, { id: string; incarnation: string; archived: boolean }>();+ const keys = new Map<string, LoadableConnectorKey>();for (const row of rows) {const config = typeof row.config === 'string' ? JSON.parse(row.config) as Record<string, unknown> : row.config ?? {};- keys.set(connectorCheckpointKey(row.id, row.incarnation, connectorIdentity(config.kind as ConnectorKind, config, row.local_path)),- { id: row.id, incarnation: row.incarnation, archived: row.archived === true });+ const [stable, ...aliases] = connectorCheckpointKeys(row.id, row.incarnation, connectorIdentity(config.kind as ConnectorKind, config, row.local_path));+ const source = { id: row.id, incarnation: row.incarnation, archived: row.archived === true };+ keys.set(stable!, { ...source, alias: false });+ for (const alias of aliases) keys.set(alias, { ...source, alias: true });}return keys;}@@ -78,6 +86,16 @@ export async function orphanConnectorCheckpoints(engine: Pick<BrainEngine, 'execORDER BY c.op, c.fingerprint LIMIT $1`, [opts.limit ?? 100_000, loadable, opts.before ?? null, opts.minAgeDays ?? null, CONNECTOR_STATE_OP]);}+/** Checkpoint and retry rows kept only because their key is a source's #6561 alias key (the repair preview lists them). */+export async function aliasProtectedConnectorCheckpoints(engine: Pick<BrainEngine, 'executeRaw'>): Promise<number> {+ const aliases = [...(await loadableConnectorKeys(engine))].filter(([, source]) => source.alias).map(([key]) => key);+ if (!aliases.length) return 0;+ const [row] = await engine.executeRaw<{ n: number | string }>(`SELECT count(*)::int AS n FROM op_checkpoints c+ WHERE (c.op='managed-connector' AND c.fingerprint = ANY($1::text[]))+ OR (c.op='managed-connector-retry' AND c.completed_keys->0->>'checkpointKey' = ANY($1::text[]))`, [aliases]);+ return Number(row?.n ?? 0);+}+/*** Deletes the given orphans. Each DELETE re-applies the whole orphan predicate* in the same statement, so a row loaded, touched or newly referenced since@@ -126,6 +144,7 @@ export async function migrateConnectorCheckpoints(engine: Sql, log: (line: strinconst report: ConnectorMigrationReport = { rekeyed: [], rewalking: [], removed: { checkpoints: 0, retries: 0 } };// Archived sources are migrated too: archive and restore keep the incarnation, so a restore resumes its cursor.for (const [key, source] of await loadableConnectorKeys(engine)) {+ if (source.alias) continue;const receipt = newest.get(`${source.id}\u0000${source.incarnation}`);// No managed checkpoint yet, or already saved by this release under its stable key.if (!receipt || receipt.kind === 'connector_v2_checkpoint') continue;@@ -155,3 +174,63 @@ export async function migrateConnectorCheckpoints(engine: Sql, log: (line: strin}return report;}++interface CheckpointRow { completed_keys: Array<{ generation?: number; state?: { gmail_backfill_done?: boolean; gmail_newest_ms?: number | null } | null }> }++export interface ConnectorAliasMigrationReport { copied: string[]; swapped: string[] }++/**+ * #6561 upgrade: releases that hashed Google's default `contactsDir` saved checkpoints under what is now an+ * alias key. Per source: when the stable key has no row, the alias row is copied to it; when both exist and+ * only the alias cursor finished its backfill, or both finished and the alias reached newer mail+ * (`gmail_newest_ms`), the two rows swap in one transaction, so the newer cursor is loaded and the older one+ * stays under the alias key (an alias key is never an orphan while its source exists). A cursor that moved+ * meanwhile (an older binary still running) rolls the swap back and leaves both rows. The swapped-in cursor+ * takes a generation above both, so no older committed checkpoint receipt can replay over it. Otherwise the+ * stable row stands. Each step is compare-and-set; a rerun changes nothing.+ */+export async function migrateConnectorAliasCheckpoints(engine: Pick<BrainEngine, 'executeRaw' | 'transaction'>,+ log: (line: string) => void = line => process.stderr.write(`${line}\n`)): Promise<ConnectorAliasMigrationReport> {+ const report: ConnectorAliasMigrationReport = { copied: [], swapped: [] };+ const keys = [...(await loadableConnectorKeys(engine))];+ const read = async (fingerprint: string) => (await engine.executeRaw<CheckpointRow>(+ "SELECT completed_keys FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$1", [fingerprint]))[0];+ const done = (row: CheckpointRow) => row.completed_keys[0]?.state?.gmail_backfill_done === true;+ const newest = (row: CheckpointRow) => Number(row.completed_keys[0]?.state?.gmail_newest_ms ?? 0);+ const generation = (row: CheckpointRow) => Number(row.completed_keys[0]?.generation ?? 0);+ for (const [stableKey, source] of keys) {+ if (source.alias) continue;+ for (const [aliasKey] of keys.filter(([, other]) => other.alias && other.id === source.id && other.incarnation === source.incarnation)) {+ const alias = await read(aliasKey);+ if (!alias) continue;+ const stable = await read(stableKey);+ if (!stable) {+ const copied = await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys)+ SELECT 'managed-connector',$1,completed_keys FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$2+ ON CONFLICT (op,fingerprint) DO NOTHING RETURNING op`, [stableKey, aliasKey]);+ if (copied.length) report.copied.push(source.id);+ continue;+ }+ if (!done(alias) || (done(stable) && newest(alias) <= newest(stable))) continue;+ const promoted = [{ ...alias.completed_keys[0], generation: Math.max(generation(stable), generation(alias)) + 1 }, ...alias.completed_keys.slice(1)];+ const raced = new Error('alias checkpoint moved');+ const swapped = await engine.transaction(async tx => {+ const moved = await tx.executeRaw(`UPDATE op_checkpoints SET completed_keys=$2::text::jsonb, updated_at=now()+ WHERE op='managed-connector' AND fingerprint=$1 AND completed_keys=$3::text::jsonb RETURNING op`,+ [stableKey, JSON.stringify(promoted), JSON.stringify(stable.completed_keys)]);+ if (!moved.length) return false;+ const kept = await tx.executeRaw(`UPDATE op_checkpoints SET completed_keys=$2::text::jsonb, updated_at=now()+ WHERE op='managed-connector' AND fingerprint=$1 AND completed_keys=$3::text::jsonb RETURNING op`,+ [aliasKey, JSON.stringify(stable.completed_keys), JSON.stringify(alias.completed_keys)]);+ if (!kept.length) throw raced;+ return true;+ }).catch(error => { if (error === raced) return false; throw error; });+ if (swapped) report.swapped.push(source.id);+ }+ }+ if (report.copied.length || report.swapped.length) {+ log(` connector checkpoints (#6561): ${report.copied.length} source(s) carried their cursor over from the interim key, `+ + `${report.swapped.length} switched to the newer interim cursor (the older one is kept under the interim key).`);+ }+ return report;+}diff --git a/src/core/persistence/connector-identity.ts b/src/core/persistence/connector-identity.tsindex f4bc01e15c..27b70b7e4d 100644--- a/src/core/persistence/connector-identity.ts+++ b/src/core/persistence/connector-identity.ts@@ -11,12 +11,20 @@* credential belongs to is checked separately against the connector state* pin (`connector-state.ts`), because excluded credential fields can change* which account a sweep reads.+ *+ * #6561: a leaf a parser starts emitting with a default that preserves the+ * earlier behavior (Google `contactsDir: 'people'`) declares that default as+ * `elideWhen`, and is left out of the digest while it holds it, so unchanged+ * sources keep the pre-field checkpoint key. Releases that hashed the default+ * wrote checkpoints under the non-elided digest; it stays addressable as an+ * alias (`aliasDigests`, `connectorCheckpointKeys`) so those rows are loaded+ * by the upgrade migration and never orphaned.*/import { digest } from './digest.ts';import { parseGoogleSourceConfig } from '../google/source-config.ts';import { parseGitHubSourceConfig } from '../github-source-config.ts';import type { GitHubSourceConfig } from '../github-source.ts';-import type { GoogleSourceConfig } from '../google/types.ts';+import { DEFAULT_CONTACTS_DIR, type GoogleSourceConfig } from '../google/types.ts';export type ConnectorKind = 'google' | 'github';@@ -25,7 +33,9 @@ export const CONNECTOR_SOURCE_KINDS: readonly ConnectorKind[] = ['google', 'githexport function isConnectorSourceKind(kind: unknown): kind is ConnectorKind { return CONNECTOR_SOURCE_KINDS.includes(kind as ConnectorKind); }export type ConnectorConfig = GoogleSourceConfig | GitHubSourceConfig;type LeafClass = 'identity' | 'excluded';-type Rule = LeafClass | ((config: GitHubSourceConfig) => LeafClass);+/** An identity leaf left out of the digest while it holds the default it was introduced with (#6561). */+interface ElidedLeaf { elideWhen: unknown }+type Rule = LeafClass | ElidedLeaf | ((config: GitHubSourceConfig) => LeafClass);const underAuto = (config: GitHubSourceConfig): LeafClass => config.scope === 'auto' ? 'identity' : 'excluded';@@ -34,9 +44,10 @@ const underAuto = (config: GitHubSourceConfig): LeafClass => config.scope === 'a* output and fails on a leaf missing here; an unlisted leaf still joins the* identity at runtime, never the exclusion list.*/-export const CONNECTOR_LEAF_RULES: { google: Record<string, LeafClass>; github: Record<string, Rule> } = {+export const CONNECTOR_LEAF_RULES: { google: Record<string, LeafClass | ElidedLeaf>; github: Record<string, Rule> } = {google: {- account: 'identity', services: 'identity', historyDays: 'identity', futureDays: 'identity', calendarId: 'identity', contactsDir: 'identity', dir: 'identity',+ account: 'identity', services: 'identity', historyDays: 'identity', futureDays: 'identity', calendarId: 'identity', dir: 'identity',+ contactsDir: { elideWhen: DEFAULT_CONTACTS_DIR },access: 'excluded', tokenCommand: 'excluded', tokenEnv: 'excluded', loopsExcludeLabels: 'excluded',},github: {@@ -62,22 +73,31 @@ export function connectorConfigLeaves(config: object): Record<string, unknown> {return leaves;}+const leafRule = (kind: ConnectorKind, path: string): Rule | undefined => (CONNECTOR_LEAF_RULES[kind] as Record<string, Rule>)[path];+export function classifyConnectorLeaf(kind: ConnectorKind, config: ConnectorConfig, path: string): LeafClass | undefined {- const rule = (CONNECTOR_LEAF_RULES[kind] as Record<string, Rule>)[path];- return typeof rule === 'function' ? rule(config as GitHubSourceConfig) : rule;+ const rule = leafRule(kind, path);+ if (typeof rule === 'function') return rule(config as GitHubSourceConfig);+ return typeof rule === 'object' ? 'identity' : rule;}-/** The identity-bearing leaves, canonicalized: set-valued lists sorted and de-duplicated. */-export function connectorIdentityLeaves(kind: ConnectorKind, config: ConnectorConfig): Record<string, unknown> {+/**+ * The identity-bearing leaves, canonicalized: set-valued lists sorted and de-duplicated. An elided leaf holding+ * its default is left out unless `elide` is false (the digest releases before #6561 computed).+ */+export function connectorIdentityLeaves(kind: ConnectorKind, config: ConnectorConfig, elide = true): Record<string, unknown> {const identity: Record<string, unknown> = {};for (const [path, value] of Object.entries(connectorConfigLeaves(config))) {if (classifyConnectorLeaf(kind, config, path) === 'excluded') continue;+ const rule = leafRule(kind, path);+ if (elide && typeof rule === 'object' && value === rule.elideWhen) continue;identity[path] = (path === 'services' || path === 'repos') && Array.isArray(value) ? [...new Set(value.map(String))].sort() : value;}return identity;}-export interface ConnectorIdentity { kind: ConnectorKind; config: ConnectorConfig; digest: string }+/** `digest` addresses the checkpoint; `aliasDigests` are earlier releases' digests of the same config (#6561). */+export interface ConnectorIdentity { kind: ConnectorKind; config: ConnectorConfig; digest: string; aliasDigests: string[] }export function parseConnectorConfig(kind: ConnectorKind, raw: Record<string, unknown>, localPath: string | null): ConnectorConfig {return kind === 'google' ? parseGoogleSourceConfig(raw, localPath ?? '') : parseGitHubSourceConfig(raw, localPath ?? '');@@ -86,13 +106,25 @@ export function parseConnectorConfig(kind: ConnectorKind, raw: Record<string, un/** The parsed connector config plus its identity digest. The raw config is never an identity. */export function connectorIdentity(kind: ConnectorKind, raw: Record<string, unknown>, localPath: string | null): ConnectorIdentity {const config = parseConnectorConfig(kind, raw, localPath);- return { kind, config, digest: digest({ kind, identity: connectorIdentityLeaves(kind, config) }) };+ const canonical = digest({ kind, identity: connectorIdentityLeaves(kind, config) });+ const interim = digest({ kind, identity: connectorIdentityLeaves(kind, config, false) });+ return { kind, config, digest: canonical, aliasDigests: interim === canonical ? [] : [interim] };+}++/** True when `configHash` (frozen on an admitted write) names this identity under its canonical or an alias digest. */+export function connectorIdentityMatches(identity: Pick<ConnectorIdentity, 'digest' | 'aliasDigests'>, configHash: string): boolean {+ return configHash === identity.digest || identity.aliasDigests.includes(configHash);}export function connectorCheckpointKey(sourceId: string, incarnation: string, identity: Pick<ConnectorIdentity, 'kind' | 'digest'>): string {return digest({ sourceId, incarnation, connector: identity.kind, identity: identity.digest });}+/** Every key a source's checkpoint may live under: the canonical key first, then its alias keys. */+export function connectorCheckpointKeys(sourceId: string, incarnation: string, identity: Pick<ConnectorIdentity, 'kind' | 'digest' | 'aliasDigests'>): string[] {+ return [identity.digest, ...identity.aliasDigests].map(d => connectorCheckpointKey(sourceId, incarnation, { kind: identity.kind, digest: d }));+}+/** Legacy and current connector intent namespaces; every filter on connector kinds uses these. */export const CONNECTOR_INTENT_PREFIXES = ['connector_v2_', 'managed_connector_'] as const;export function isConnectorIntentKind(kind: unknown): boolean {diff --git a/src/core/persistence/connector-sync.ts b/src/core/persistence/connector-sync.tsindex b2040a84b8..30aeaaa5c1 100644--- a/src/core/persistence/connector-sync.ts+++ b/src/core/persistence/connector-sync.ts@@ -32,7 +32,7 @@ import { assertPhysicalRoot } from './physical-root.ts';import type { PageSnapshot } from '../page-state/types.ts';import { LockStolenError, syncLockId, withRefreshingLock, type DbLockHandle } from '../db-lock.ts';import { ownedGoogleReceipts, prepareGoogleReceiptPatch, type GoogleReceipts } from './connector-google-receipts.ts';-import { connectorCheckpointKey, connectorIdentity, type ConnectorIdentity, type ConnectorKind } from './connector-identity.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 { 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';@@ -331,13 +331,16 @@ export class ManagedConnectorSync {readonly counts: Omit<ConnectorRunCounts, 'finished_at' | 'pending' | 'stopped_on_wait_budget'> & { created: number; updated: number; deleted: number } = {page_admissions: 0, skipped_unchanged: 0, checkpoint_admissions: 0, dropped_upstream: 0, created: 0, updated: 0, deleted: 0 };readonly checkpointKey: string;+ /** The stable key plus its #6561 alias keys: retry approvals recorded under an alias still apply. */+ private readonly checkpointKeys: string[];private readonly connector: ConnectorKind;constructor(private engine: BrainEngine, readonly sourceId: string, private identity: ConnectorIdentity,private source: ConnectorSource, private authority: SyncAuthority, private binding: WorktreeBinding | null,private canonicalRoot: string | null, private noEmbed: boolean, private noSchemaPack: boolean, private retryFailed = false,private lease?: ConnectorLease, private resetRequested = false, private targeted = false, private fullSweep = false) {this.connector = identity.kind;- this.checkpointKey = connectorCheckpointKey(sourceId, source.incarnation, identity);+ this.checkpointKeys = connectorCheckpointKeys(sourceId, source.incarnation, identity);+ this.checkpointKey = this.checkpointKeys[0]!;}async assertLease(engine: BrainEngine): Promise<void> {if (!this.lease) return;@@ -370,9 +373,9 @@ export class ManagedConnectorSync {const [row] = await this.engine.executeRaw<{ completed_keys: unknown[] }>("SELECT completed_keys FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$1", [this.checkpointKey]);this.checkpoint = row?.completed_keys ?? [];const pointers = await this.engine.executeRaw<{ completed_keys: ConnectorRetry[] }>(`SELECT completed_keys FROM op_checkpoints- WHERE op='managed-connector-retry' AND completed_keys->0->>'checkpointKey'=$1+ WHERE op='managed-connector-retry' AND completed_keys->0->>'checkpointKey'=ANY($1::text[])AND completed_keys->0->>'principalId'=$2 AND completed_keys->0->>'principalKind'=$3`,- [this.checkpointKey, this.authority.writer.principal.id, this.authority.writer.principal.kind]);+ [this.checkpointKeys, this.authority.writer.principal.id, this.authority.writer.principal.kind]);this.retryApprovals = new Map(pointers.map(row => [row.completed_keys[0].baseRequestId, row.completed_keys[0].requestId]));}/**@@ -948,7 +951,7 @@ export async function prepareConnectorMutation(engine: BrainEngine, row: WriteReawait validateSyncAuthority(tx, p.syncAuthority, row.slug);const [source] = await tx.executeRaw<ConnectorSource>('SELECT incarnation,archived,local_path,config FROM sources WHERE id=$1', [row.source_id]);if (!source || source.archived || source.incarnation !== row.source_incarnation || source.config.kind !== p.connector ||- connectorIdentity(p.connector, source.config, source.local_path).digest !== p.configHash || source.local_path !== p.sourceRoot) {+ !connectorIdentityMatches(connectorIdentity(p.connector, source.config, source.local_path), p.configHash) || source.local_path !== p.sourceRoot) {throw connectorPublicationRefusal('source_changed', 'The connector configuration changed after admission.', row,`The connector configuration, path or incarnation of ${row.source_id} changed after this write was admitted.`);}diff --git a/src/core/repair/connector-checkpoints.ts b/src/core/repair/connector-checkpoints.tsindex 763b34026f..cb8c866657 100644--- a/src/core/repair/connector-checkpoints.ts+++ b/src/core/repair/connector-checkpoints.ts@@ -3,10 +3,11 @@* rows and retry pointers that no registered connector source can load and* that are older than 7 days. Cleanup only; the upgrade migration's re-key* copy never runs here. Rows referenced by a non-terminal request or a- * recorded pending set are kept. No journal admission: these rows are- * connector bookkeeping, not canonical pages.+ * recorded pending set are kept, and so are rows under a source's #6561+ * alias key (the interim Google key), counted as `alias_protected`. No journal+ * admission: these rows are connector bookkeeping, not canonical pages.*/-import { deleteOrphanConnectorCheckpoints, orphanConnectorCheckpoints, type OrphanCheckpointRow } from '../persistence/connector-checkpoint-migration.ts';+import { aliasProtectedConnectorCheckpoints, deleteOrphanConnectorCheckpoints, orphanConnectorCheckpoints, type OrphanCheckpointRow } from '../persistence/connector-checkpoint-migration.ts';import type { RepairHandler, RepairItem } from './core.ts';export const ORPHAN_CHECKPOINT_MIN_AGE_DAYS = 7;@@ -21,7 +22,7 @@ export const connectorCheckpointsRepair: RepairHandler = {const items: RepairItem[] = rows.map((row, index) => ({ cursor: { phase: row.op === 'managed-connector' ? 0 : 1, id: index + 1 },source_id: '(brain)', slug: `${row.op}:${row.fingerprint.slice(0, 12)}`, chars: 0, action: 'delete_orphan',change: { from: JSON.stringify(row), to: 'deleted' } }));- return { items, residuals: {} };+ return { items, residuals: { alias_protected: await aliasProtectedConnectorCheckpoints(engine) } };},async apply(ctx, item) {const row = JSON.parse(item.change!.from!) as OrphanCheckpointRow;diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex 26c3e6c86c..284286cf7d 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 247;+export const LATEST_SCHEMA_VERSION = 248;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex a4842230dd..dc4213ffdc 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -248,6 +248,7 @@ import { v244 } from './v244-chunk-projected-spans.ts';import { v245 } from './v245-page-search-vector-bounded-timeline.ts';import { v246 } from './v246-page-embedding-budget.ts';import { v247 } from './v247-page-extraction-state.ts';+import { v248 } from './v248-connector-checkpoint-default-leaf-alias.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -494,4 +495,5 @@ export const MIGRATIONS: Migration[] = [v245,v246,v247,+ v248,];diff --git a/src/core/schema-migrations/v248-connector-checkpoint-default-leaf-alias.ts b/src/core/schema-migrations/v248-connector-checkpoint-default-leaf-alias.tsnew file mode 100644index 0000000000..489fb9811a--- /dev/null+++ b/src/core/schema-migrations/v248-connector-checkpoint-default-leaf-alias.ts@@ -0,0 +1,15 @@+import type { Migration } from './types.ts';+import { migrateConnectorAliasCheckpoints } from '../persistence/connector-checkpoint-migration.ts';++export const v248: Migration = {+ // #6561: v0.60.176.0 hashed Google's new default `contactsDir` into the+ // connector identity, re-keying every Google checkpoint. The identity now+ // elides the default (the pre-field key again) and keeps the interim key as+ // an alias. Carry each source's interim cursor to the stable key when the+ // stable key has none, or when the interim cursor is the newer completed+ // one (the older is kept under the alias). Handler-only, statement-at-a-time+ // (one two-statement transaction per swap), rerun-safe. Placeholder number:+ // the integrator renumbers at merge.+ version: 248, name: 'connector_checkpoint_default_leaf_alias', idempotent: true, sql: '',+ handler: async engine => { await migrateConnectorAliasCheckpoints(engine); },+};diff --git a/test/connector-checkpoint-identity.test.ts b/test/connector-checkpoint-identity.test.tsindex b021333b09..50513933d6 100644--- a/test/connector-checkpoint-identity.test.ts+++ b/test/connector-checkpoint-identity.test.ts@@ -5,6 +5,13 @@ import type { BrainEngine } from '../src/core/engine.ts';import { parseGoogleSourceConfig, runGoogleSync } from '../src/core/google/google-source.ts';import { disposePersistenceConsumer, startPersistenceConsumer, waitForWrite } from '../src/core/persistence/service.ts';import type { WriteRequest } from '../src/core/persistence/model.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { connectorCheckpointKey, connectorIdentity, connectorIdentityLeaves } from '../src/core/persistence/connector-identity.ts';+import { orphanConnectorCheckpoints } from '../src/core/persistence/connector-checkpoint-migration.ts';+import { digest } from '../src/core/persistence/digest.ts';+import { MIGRATIONS } from '../src/core/schema-migrations/registry.generated.ts';+import { connectorCheckpointsRepair, ORPHAN_CHECKPOINT_MIN_AGE_DAYS } from '../src/core/repair/connector-checkpoints.ts';+import { resolveRepairScope, runRepair } from '../src/core/repair/core.ts';import { withEnv } from './helpers/with-env.ts';import { createConnectorFixture, options, json, googleConfig, contact, withPausedOwnerBudget } from './helpers/connector-fixture.ts';@@ -123,3 +130,101 @@ test('#5470: a rotating provider cursor costs exactly one checkpoint admission a}}}), 180_000);++// #6561: v0.60.176.0 hashed the new default `contactsDir` into the identity, so a source upgraded across it had+// a completed pre-field cursor and an interim one. Keys are derived here from the leaves themselves (not from the+// fixed identity function), so the same test runs against a build that still hashes the default.+async function identityKeys(engine: BrainEngine, f: { id: string; dir: string }) {+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text FROM sources WHERE id=$1', [f.id]);+ const interimLeaves = connectorIdentityLeaves('google', connectorIdentity('google', googleConfig, f.dir).config, false);+ const { contactsDir: _default, ...preFieldLeaves } = interimLeaves;+ const key = (identity: Record<string, unknown>) => connectorCheckpointKey(f.id, incarnation, { kind: 'google', digest: digest({ kind: 'google', identity }) });+ return { preField: key(preFieldLeaves), interim: key(interimLeaves) };+}+type Checkpoint = Array<{ generation?: number; state?: Record<string, unknown> | null }>;+const readRow = async (engine: BrainEngine, fingerprint: string) => (await engine.executeRaw<{ completed_keys: Checkpoint }>(+ "SELECT completed_keys FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$1", [fingerprint]))[0]?.completed_keys ?? null;+const writeRow = (engine: BrainEngine, fingerprint: string, value: Checkpoint) => engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at)+ VALUES('managed-connector',$1,$2::text::jsonb,now()-interval '30 days') ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=EXCLUDED.updated_at`,+[fingerprint, JSON.stringify(value)]);+/** The schema migration that carries interim cursors over, run the way runMigrations runs it (absent on a build without the fix). */+const runAliasMigration = async (engine: BrainEngine) => { await MIGRATIONS.find(m => m.name === 'connector_checkpoint_default_leaf_alias')?.handler?.(engine); };++/** One completed sweep, then its cursor laid out the way an upgrade across the interim releases leaves it. */+async function upgradedSource(engine: BrainEngine, layout: 'pre-field completed + interim partial' | 'interim only') {+ const f = await source(engine, googleConfig);+ const { fetcher, calls } = peopleFetcher();+ expect((await runGoogleSync(engine, f.id, parseGoogleSourceConfig(googleConfig, f.dir), options, fetcher)).added).toBe(2);+ await disposePersistenceConsumer(engine);+ const keys = await identityKeys(engine, f);+ const completed = (await readRow(engine, keys.preField)) ?? (await readRow(engine, keys.interim));+ expect(completed?.[0]?.state?.contacts_sync_token).toBe('contacts-stable');+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-connector' AND fingerprint = ANY($1::text[])", [[keys.preField, keys.interim]]);+ if (layout === 'interim only') await writeRow(engine, keys.interim, completed!);+ else {+ await writeRow(engine, keys.preField, completed!);+ await writeRow(engine, keys.interim, [{ generation: 1, state: { ...completed![0]!.state, contacts_sync_token: null } }]);+ }+ return { f, keys, fetcher, calls };+}++test('#6561: a pre-field completed cursor and an interim partial one both survive the orphan scan; the quiet capture resumes the completed cursor and admits nothing', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const { f, keys, fetcher, calls } = await upgradedSource(engine, 'pre-field completed + interim partial');+ const retryKey = `retry-${f.id}`;+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at)+ VALUES('managed-connector-retry',$1,$2::text::jsonb,now()-interval '30 days')`, [retryKey, JSON.stringify([{ checkpointKey: keys.interim, baseRequestId: retryKey }])]);+ await runAliasMigration(engine);+ const orphans = (await orphanConnectorCheckpoints(engine, { minAgeDays: ORPHAN_CHECKPOINT_MIN_AGE_DAYS })).map(row => row.fingerprint);+ for (const kept of [keys.preField, keys.interim, retryKey]) expect(orphans).not.toContain(kept);+ const ctx = { engine, config: { engine: engine.kind }, remote: false, logger: console } as unknown as OperationContext;+ expect((await runRepair(ctx, connectorCheckpointsRepair, await resolveRepairScope(engine), { apply: false })).residuals?.alias_protected).toBeGreaterThanOrEqual(2);+ const before = await mark(engine, f.id);+ calls.length = 0;+ expect((await runGoogleSync(engine, f.id, parseGoogleSourceConfig(googleConfig, f.dir), options, fetcher)).status).toBe('up_to_date');+ expect(calls.some(url => url.includes('syncToken=contacts-stable'))).toBe(true);+ expect(await admissions(engine, f.id, before)).toEqual({ pages: 0, checkpoints: 0 });+ expect(await readRow(engine, keys.interim)).not.toBeNull();+ }+}), 180_000);++test('#6561: a source created on an interim release carries its cursor to the stable key; the quiet capture admits nothing and a rerun changes nothing', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const { f, keys, fetcher, calls } = await upgradedSource(engine, 'interim only');+ await runAliasMigration(engine);+ const carried = await readRow(engine, keys.preField);+ expect(carried).toEqual(await readRow(engine, keys.interim));+ await runAliasMigration(engine);+ expect(await readRow(engine, keys.preField)).toEqual(carried);+ expect((await orphanConnectorCheckpoints(engine, { minAgeDays: ORPHAN_CHECKPOINT_MIN_AGE_DAYS })).map(row => row.fingerprint)).not.toContain(keys.interim);+ const before = await mark(engine, f.id);+ calls.length = 0;+ expect((await runGoogleSync(engine, f.id, parseGoogleSourceConfig(googleConfig, f.dir), options, fetcher)).status).toBe('up_to_date');+ expect(calls.some(url => url.includes('syncToken=contacts-stable'))).toBe(true);+ expect(await admissions(engine, f.id, before)).toEqual({ pages: 0, checkpoints: 0 });+ }+}), 180_000);++test('#6561: when both cursors finished their Gmail backfill, the newer one is loaded and the older one is kept under the interim key', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await source(engine, googleConfig);+ const keys = await identityKeys(engine, f);+ const gmail = (newest: number, done = true) => ({ gmail_history_id: `h-${newest}`, gmail_backfill_floor_ms: 1, gmail_backfill_done: done, gmail_newest_ms: newest });+ const preField: Checkpoint = [{ generation: 5, state: gmail(1_000) }];+ const interim: Checkpoint = [{ generation: 2, state: gmail(2_000) }];+ await writeRow(engine, keys.preField, preField);+ await writeRow(engine, keys.interim, interim);+ await runAliasMigration(engine);+ expect(await readRow(engine, keys.preField)).toEqual([{ generation: 6, state: gmail(2_000) }]);+ expect(await readRow(engine, keys.interim)).toEqual(preField);+ await runAliasMigration(engine);+ expect(await readRow(engine, keys.preField)).toEqual([{ generation: 6, state: gmail(2_000) }]);+ // A newer interim cursor that never finished its backfill does not replace a completed one.+ const g = await source(engine, googleConfig);+ const other = await identityKeys(engine, g);+ await writeRow(engine, other.preField, preField);+ await writeRow(engine, other.interim, [{ generation: 2, state: gmail(9_000, false) }]);+ await runAliasMigration(engine);+ expect(await readRow(engine, other.preField)).toEqual(preField);+ }+}), 120_000);diff --git a/test/connector-identity.test.ts b/test/connector-identity.test.tsindex d3b18c1f89..f413fd0199 100644--- a/test/connector-identity.test.ts+++ b/test/connector-identity.test.ts@@ -1,5 +1,5 @@import { describe, expect, test } from 'bun:test';-import { classifyConnectorLeaf, connectorConfigLeaves, connectorIdentity, CONNECTOR_LEAF_RULES, isConnectorIntentKind } from '../src/core/persistence/connector-identity.ts';+import { classifyConnectorLeaf, connectorCheckpointKey, connectorCheckpointKeys, connectorConfigLeaves, connectorIdentity, connectorIdentityMatches, CONNECTOR_LEAF_RULES, isConnectorIntentKind } from '../src/core/persistence/connector-identity.ts';import { parseGoogleSourceConfig } from '../src/core/google/google-source.ts';import { parseGitHubSourceConfig } from '../src/core/github-source.ts';@@ -65,3 +65,50 @@ describe('connector identity stability', () => {expect(isConnectorIntentKind('managed_sync_import')).toBe(false);});});++// #6561: v0.60.176.0 added an always-emitted `contactsDir: 'people'` leaf, which re-keyed every Google checkpoint+// (the pre-field cursor was lost and exposed to orphan cleanup). Both digests below come from the issue's real runs:+// the v0.60.126.0 implementation, and the interim releases that hashed the default leaf.+describe('#6561: a parser default that preserves behavior keeps the pre-field identity', () => {+ const raw = { kind: 'google', g_account: '[email protected]', g_services: 'gmail,contacts', g_dir: '/fixture' };+ const PRE_FIELD = '81b1c0b0c86d07b67f11eb6dd6e8ebdc5839f74db8c2f033eb48c19cfae7b6e8';+ const INTERIM = '52a7990a8ff21b7fe252a86ac5cea35141f6952aeb35da37c445476e184126ee';+ const fixture = (extra: Record<string, unknown> = {}) => connectorIdentity('google', { ...raw, ...extra }, '/fixture');++ test('an unchanged default-contacts config hashes to the pre-field digest; the interim digest is its alias', () => {+ expect(fixture().digest).toBe(PRE_FIELD);+ expect(fixture().aliasDigests).toEqual([INTERIM]);+ });+ test('absent, explicit default and a spelled-out default contacts dir are one identity', () => {+ expect(fixture({ g_contacts_dir: 'people' }).digest).toBe(PRE_FIELD);+ expect(fixture({ g_contacts_dir: '/people/' }).digest).toBe(PRE_FIELD);+ });+ test('a non-default contacts dir and every other content change still isolate, with no alias', () => {+ const changed = [fixture({ g_contacts_dir: 'contacts' }), fixture({ g_account: '[email protected]' }), fixture({ g_services: 'gmail' }),+ fixture({ g_dir: '/elsewhere' }), fixture({ g_history_days: 30 })];+ for (const identity of changed) expect(identity.digest).not.toBe(PRE_FIELD);+ expect(new Set(changed.map(identity => identity.digest)).size).toBe(changed.length);+ expect(fixture({ g_contacts_dir: 'contacts' }).aliasDigests).toEqual([]);+ });+ test('the checkpoint keys of a source: the canonical key first, then the interim alias; incarnation still isolates', () => {+ const keys = connectorCheckpointKeys('fixture-google', '11111111-1111-4111-8111-111111111111', fixture());+ expect(keys).toEqual([+ connectorCheckpointKey('fixture-google', '11111111-1111-4111-8111-111111111111', { kind: 'google', digest: PRE_FIELD }),+ connectorCheckpointKey('fixture-google', '11111111-1111-4111-8111-111111111111', { kind: 'google', digest: INTERIM }),+ ]);+ expect(connectorCheckpointKeys('fixture-google', '22222222-2222-4222-8222-222222222222', fixture())).not.toContain(keys[0]);+ });+ test('a write admitted under the interim digest (its frozen configHash) still matches the unchanged source; a real change does not', () => {+ expect(connectorIdentityMatches(fixture(), INTERIM)).toBe(true);+ expect(connectorIdentityMatches(fixture(), PRE_FIELD)).toBe(true);+ expect(connectorIdentityMatches(fixture({ g_services: 'gmail' }), INTERIM)).toBe(false);+ expect(connectorIdentityMatches(fixture({ g_contacts_dir: 'contacts' }), INTERIM)).toBe(false);+ });+ test('every parser leaf with an always-present default declares the value that elides it', () => {+ const bare = parseGoogleSourceConfig({ kind: 'google' }, '/brain');+ const leaves = connectorConfigLeaves(bare);+ const defaulted = Object.keys(leaves).filter(leaf => !['account', 'services', 'historyDays', 'calendarId', 'dir', 'access'].includes(leaf));+ expect(defaulted).toEqual(['contactsDir']);+ for (const leaf of defaulted) expect((CONNECTOR_LEAF_RULES.google[leaf] as { elideWhen?: unknown }).elideWhen, `google:${leaf}`).toBe(leaves[leaf]);+ });+});diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex abdfc2d495..81af7fa6d1 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 242,+ "count": 243,"gaps": [17,18,@@ -43,7 +43,8 @@"grantFromRow": "2d0603bb0f964d7e45e04aa76bac54cd4f6f63c91a8d9f028b60b4792bc1695e","hnswMaxDimsForType": "a187cdcc520f813b7c39da97ce53da58509232ed9f851627ef41abfe1b68bd26","migrateAutoThinkToPins": "34267fe3b1cc4ab2850ddcf9ba18ce73d959678233a53de238c85231e6b71470",- "migrateConnectorCheckpoints": "e0403022a56559556c82a9fa1e90d928f36e1d09c7db570e1d788a87d2dc9521",+ "migrateConnectorAliasCheckpoints": "64ed79e69fe2fac760ffdc8a2c072014613649faa88721068182b40af8f1674d",+ "migrateConnectorCheckpoints": "5c13e69a334bfc5275c7d555c4e7b28e034569f086dd4bd70b4b78fa4770dc7a","migrateLegacyTokens": "6e4abe3670127e7a495b56ecbf9f5789edd3a7362d45704656c2210a85b27f4c","migrationNotice": "9a6607b26a9719ef1833571b137bc8ebfcd1e16d545e89ff8728cf3ccbcbb409","pageSearchVectorTriggerFnSql": "f9f083978d2a5cd756a889781ee07a921132c4db9d3cfa1b041da2af95a4a4b5",@@ -56,7 +57,7 @@"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5","verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"},- "latest": 247,+ "latest": 248,"records": [{"handler": {@@ -3764,6 +3765,25 @@"transaction": "absent","verify": "absent","version": 247+ },+ {+ "handler": {+ "form": "arrow",+ "helpers": [+ "migrateConnectorAliasCheckpoints"+ ],+ "sha256": "7462886db701b0d573d42e2bdd475fa8aa7c74328dc60753cf0664943c567c1d"+ },+ "idempotent": true,+ "name": "connector_checkpoint_default_leaf_alias",+ "sql": {+ "length": 0,+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 248}],"versions": [@@ -4008,7 +4028,8 @@244,245,246,- 247+ 247,+ 248]},"normalizer": "migrations-record-v1"