Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(connectors): resume #6561 alias cursors at run time; drop migration v248 (#6561)
time-attack69bb89b4d385
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex 08fa9c49ca..fdf172970b 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -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 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/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. No upgrade step rewrites alias rows (#6561): `connector-sync.ts` `resumeCheckpoint` resumes from an alias row written after the stable one when the stable key has none or the alias holds the newer completed Gmail backfill, and the run's first save moves that cursor to the stable key; every checkpoint and page write compares against and writes only the stable row. `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 854c0a21b5..649e451c3f 100644--- a/src/core/persistence/connector-checkpoint-migration.ts+++ b/src/core/persistence/connector-checkpoint-migration.ts@@ -174,63 +174,3 @@ 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-sync.ts b/src/core/persistence/connector-sync.tsindex 30aeaaa5c1..0fbd377462 100644--- a/src/core/persistence/connector-sync.ts+++ b/src/core/persistence/connector-sync.ts@@ -68,6 +68,28 @@ const ITEM_WAIT_MS = 5_000;* set recorded. A `write_pending` error, so direct session callers and* `rethrowConnectorWriteError` treat it like any accepted, unfinished write.*/+interface StoredCheckpoint { fingerprint: string; completed_keys: unknown[]; at: number | string }+type GoogleCursorEntry = { generation?: number; state?: { gmail_backfill_done?: boolean; gmail_newest_ms?: number | null } | null };++/**+ * #6561: the cursor a run resumes from. Releases that hashed Google's default `contactsDir` saved it under what+ * is now an alias key; nothing rewrites those rows on upgrade. The stable row is used unless an alias row was+ * written after it and either the stable key has no row, or the alias cursor finished its Gmail backfill and the+ * stable one did not or reached older mail. Once this release saves the stable row it is the newer one, so a+ * reset or a reopened backfill never falls back. A resumed alias cursor takes a generation at or above the+ * stable row's, so the next save still rises.+ */+export function resumeCheckpoint(stable: StoredCheckpoint | null, aliases: StoredCheckpoint[]): unknown[] {+ const entry = (row: StoredCheckpoint) => (row.completed_keys[0] ?? {}) as GoogleCursorEntry;+ const done = (row: StoredCheckpoint) => entry(row).state?.gmail_backfill_done === true;+ const newest = (row: StoredCheckpoint) => Number(entry(row).state?.gmail_newest_ms ?? 0);+ const newer = aliases.filter(alias => !stable || (Number(alias.at) > Number(stable.at) && done(alias) && (!done(stable) || newest(alias) > newest(stable))))+ .sort((a, b) => Number(b.at) - Number(a.at))[0];+ if (!newer) return stable?.completed_keys ?? [];+ const generation = Math.max(Number(entry(newer).generation ?? 0), stable ? Number(entry(stable).generation ?? 0) : 0);+ return [{ ...entry(newer), generation }, ...newer.completed_keys.slice(1)];+}+export class ConnectorWaitBudgetStop extends OperationError {constructor(row?: WriteRequest) {super('write_pending', 'The connector wait budget is spent with accepted writes still pending.',@@ -306,7 +328,10 @@ export function pendingConnectorResult(result: SyncResult | null, session: Manag}export class ManagedConnectorSync {+ /** The cursor this run resumes from and advances (the stable row, or a #6561 alias row the loader chose). */private checkpoint: unknown[] = [];+ /** What the stable key holds: every checkpoint and page write compares against it, and writes go only there. */+ private checkpointRow: unknown[] = [];private receipts: string[] = [];private retryApprovals = new Map<string, string>();/** Failed receipts a previous run ended with: retried automatically, without --retry-failed. */@@ -370,8 +395,11 @@ export class ManagedConnectorSync {this.intentByteCap = Math.max(1024 ** 2, Math.floor(Math.min(limits.principalIntentBytes, PERSISTENCE_IPC_MAX_BYTES) / 2));this.connectorState = await readManagedConnectorState(this.engine, this.sourceId, this.source.incarnation);await this.resolvePendingSet();- 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 rows = await this.engine.executeRaw<StoredCheckpoint>(`SELECT fingerprint,completed_keys,extract(epoch from updated_at)::float8 AS at+ FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=ANY($1::text[])`, [this.checkpointKeys]);+ const stable = rows.find(row => row.fingerprint === this.checkpointKey) ?? null;+ this.checkpointRow = stable?.completed_keys ?? [];+ this.checkpoint = resumeCheckpoint(stable, rows.filter(row => row.fingerprint !== this.checkpointKey));const pointers = await this.engine.executeRaw<{ completed_keys: ConnectorRetry[] }>(`SELECT completed_keys FROM op_checkpointsWHERE op='managed-connector-retry' AND completed_keys->0->>'checkpointKey'=ANY($1::text[])AND completed_keys->0->>'principalId'=$2 AND completed_keys->0->>'principalKind'=$3`,@@ -437,7 +465,7 @@ export class ManagedConnectorSync {// The empty cursor keeps a rising generation, so the next save can never replay an older committed checkpoint receipt.const next = [{ generation: Number((this.checkpoint[0] as { generation?: number }).generation ?? 0) + 1, state: null }];await this.submit('connector_v2_checkpoint', CHECKPOINT_SLUG, null, { checkpointAfter: next, receipts: [], fresh: false });- this.checkpoint = next;+ this.checkpoint = this.checkpointRow = next;this.receipts = [];}this.connectorState = { ...this.connectorState, upgrade_recovery: 'none', resumed_from: null };@@ -574,7 +602,8 @@ export class ManagedConnectorSync {// A targeted refresh must not move the cursor past a carried failure it did not revisit.const blocked = this.targeted && this.unreachedCarried().some(entry => entry.itemRef !== CHECKPOINT_SLUG);if (this.pendingRows.size || this.failedPending.length || blocked) { this.deferred = true; this.lastSaveCommitted = false; return; }- if (this.checkpoint.length && digest((this.checkpoint[0] as { state?: unknown }).state ?? null) === digest(state ?? null)) {+ // A cursor resumed from an alias key is always saved once, so it moves to the stable key.+ if (digest(this.checkpoint) === digest(this.checkpointRow) && this.checkpoint.length && digest((this.checkpoint[0] as { state?: unknown }).state ?? null) === digest(state ?? null)) {if (fresh) await this.stampFreshness(newestContentAt);this.receipts = [];this.lastSaveCommitted = true;@@ -583,7 +612,7 @@ export class ManagedConnectorSync {const next = [{ generation: Number((this.checkpoint[0] as { generation?: number } | undefined)?.generation ?? 0) + 1, state: structuredClone(state) }];await this.submit('connector_v2_checkpoint', CHECKPOINT_SLUG, null,{ checkpointAfter: next, receipts: [...this.receipts], fresh, ...(newestContentAt ? { newestContentAt } : {}) });- this.checkpoint = next;+ this.checkpoint = this.checkpointRow = next;this.receipts = [];this.lastSaveCommitted = true;}@@ -733,7 +762,7 @@ export class ManagedConnectorSync {const next = [{ generation: Number((this.checkpoint[0] as { generation?: number } | undefined)?.generation ?? 0) + 1, state }];try {await this.submit('connector_v2_checkpoint', CHECKPOINT_SLUG, null, { checkpointAfter: next, receipts: [], fresh: false });- this.checkpoint = next;+ this.checkpoint = this.checkpointRow = next;return true;} catch {return false;@@ -800,7 +829,7 @@ export class ManagedConnectorSync {const intent: ConnectorIntent = { kind, connector: this.connector, sourceRoot: this.source.local_path,configHash: this.identity.digest, syncAuthority: this.authority, expected_revision: snapshot?.revision ?? null,sourcePath, noEmbed: this.noEmbed, noSchemaPack: this.noSchemaPack, checkpointKey: this.checkpointKey,- checkpointBefore: kind === 'connector_v2_checkpoint' ? this.checkpoint : cursorOnly(this.checkpoint),+ checkpointBefore: kind === 'connector_v2_checkpoint' ? this.checkpointRow : cursorOnly(this.checkpointRow),ownerEpoch: this.binding ? String(this.binding.owner_epoch) : null, canonicalRoot: this.canonicalRoot,filePath: file?.path ?? null, fileBeforeHash: file?.expectedBeforeHash ?? null, ...extra };const callerIntent = { ...intent, syncAuthority: undefined, newestContentAt: undefined,@@ -861,7 +890,7 @@ export class ManagedConnectorSync {await this.refuseRetryBlocker(tx);const [checkpoint] = await tx.executeRaw<{ completed_keys: unknown[] }>("SELECT completed_keys FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$1 FOR UPDATE", [this.checkpointKey]);- if (digest(checkpoint?.completed_keys ?? []) !== digest(this.checkpoint)) throw opError('revision_conflict', 'The connector cursor changed before retry approval.',+ if (digest(checkpoint?.completed_keys ?? []) !== digest(this.checkpointRow)) throw opError('revision_conflict', 'The connector cursor changed before retry approval.',`Another run moved the connector cursor of ${this.sourceId} while this one re-approved ${slug}; nothing was admitted. Run gbrain sync --source ${this.sourceId} to continue from the new cursor.`,{ fix: connectorSyncFix(this.sourceId, 'A new run reads the current cursor and resolves the recorded pending set first.') });const attempt = (current.retry?.attempt ?? 0) + 1;diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex 284286cf7d..26c3e6c86c 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 = 248;+export const LATEST_SCHEMA_VERSION = 247;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex dc4213ffdc..a4842230dd 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -248,7 +248,6 @@ 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.@@ -495,5 +494,4 @@ 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.tsdeleted file mode 100644index 489fb9811a..0000000000--- a/src/core/schema-migrations/v248-connector-checkpoint-default-leaf-alias.ts+++ /dev/null@@ -1,15 +0,0 @@-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 50513933d6..b2367b2645 100644--- a/test/connector-checkpoint-identity.test.ts+++ b/test/connector-checkpoint-identity.test.ts@@ -10,6 +10,8 @@ import { connectorCheckpointKey, connectorIdentity, connectorIdentityLeaves } frimport { 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 { runMigrations } from '../src/core/migrate.ts';+import { resumeCheckpoint } from '../src/core/persistence/connector-sync.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';@@ -132,8 +134,10 @@ 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.+// a completed pre-field cursor and an interim one. Nothing rewrites those rows on upgrade: the loader picks the+// cursor at run time and every write goes to the stable (pre-field) key. 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);@@ -144,11 +148,11 @@ async function identityKeys(engine: BrainEngine, f: { id: string; dir: string })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); };+const writeRow = (engine: BrainEngine, fingerprint: string, value: Checkpoint, daysAgo: number) => engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at)+ VALUES('managed-connector',$1,$2::text::jsonb,now()-make_interval(days => $3::integer)) ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=EXCLUDED.updated_at`,+[fingerprint, JSON.stringify(value), daysAgo]);+const snapshotRows = (engine: BrainEngine, keys: string[]) => engine.executeRaw<{ fingerprint: string; completed_keys: unknown; at: string }>(+ "SELECT fingerprint,completed_keys,updated_at::text AS at FROM op_checkpoints WHERE fingerprint = ANY($1::text[]) ORDER BY fingerprint", [keys]);/** 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') {@@ -160,71 +164,84 @@ async function upgradedSource(engine: BrainEngine, layout: 'pre-field completedconst 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!);+ if (layout === 'interim only') await writeRow(engine, keys.interim, completed!, 30);else {- await writeRow(engine, keys.preField, completed!);- await writeRow(engine, keys.interim, [{ generation: 1, state: { ...completed![0]!.state, contacts_sync_token: null } }]);+ await writeRow(engine, keys.preField, completed!, 40);+ await writeRow(engine, keys.interim, [{ generation: 1, state: { ...completed![0]!.state, contacts_sync_token: null } }], 30);}return { f, keys, fetcher, calls };}+const quietCapture = async (engine: BrainEngine, f: { id: string; dir: string }, fetcher: (url: string) => Promise<Response>, calls: string[]) => {+ 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');+ await disposePersistenceConsumer(engine);+ return { usedCursor: calls.some(url => url.includes('syncToken=contacts-stable')), admitted: await admissions(engine, f.id, before) };+};++test('#6561: only the interim key holds a cursor: the run resumes from it, its one save lands on the stable key, and the next run admits nothing', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const { f, keys, fetcher, calls } = await upgradedSource(engine, 'interim only');+ const interim = await readRow(engine, keys.interim);+ expect(await quietCapture(engine, f, fetcher, calls)).toEqual({ usedCursor: true, admitted: { pages: 0, checkpoints: 1 } });+ const stable = await readRow(engine, keys.preField);+ expect(stable?.[0]?.state?.contacts_sync_token).toBe('contacts-stable');+ expect(stable?.[0]?.generation).toBe(Number(interim![0]!.generation ?? 0) + 1);+ expect(await readRow(engine, keys.interim)).toEqual(interim);+ expect(await quietCapture(engine, f, fetcher, calls)).toEqual({ usedCursor: true, admitted: { pages: 0, checkpoints: 0 } });+ expect((await orphanConnectorCheckpoints(engine, { minAgeDays: ORPHAN_CHECKPOINT_MIN_AGE_DAYS })).map(row => row.fingerprint)).not.toContain(keys.interim);+ }+}), 180_000);-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 () => {+test('#6561: when the interim cursor is the newer completed backfill, the run resumes from it and saves to the stable key', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const { f, keys, fetcher, calls } = await upgradedSource(engine, 'interim only');+ const interim = (await readRow(engine, keys.interim))!;+ const gmail = (newest: number) => ({ gmail_history_id: `h-${newest}`, gmail_backfill_floor_ms: 1, gmail_backfill_done: true, gmail_newest_ms: newest });+ await writeRow(engine, keys.preField, [{ generation: 5, state: { ...interim[0]!.state, ...gmail(1_000), contacts_sync_token: 'contacts-old' } }], 40);+ await writeRow(engine, keys.interim, [{ generation: 2, state: { ...interim[0]!.state, ...gmail(2_000) } }], 30);+ expect(await quietCapture(engine, f, fetcher, calls)).toEqual({ usedCursor: true, admitted: { pages: 0, checkpoints: 1 } });+ expect(calls.some(url => url.includes('syncToken=contacts-old'))).toBe(false);+ const stable = await readRow(engine, keys.preField);+ expect(stable?.[0]).toMatchObject({ generation: 6, state: { gmail_newest_ms: 2_000, contacts_sync_token: 'contacts-stable' } });+ }+}), 180_000);++test('#6561: a pre-field completed cursor and a newer interim partial one both survive the orphan scan; the run 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();+ expect(await quietCapture(engine, f, fetcher, calls)).toEqual({ usedCursor: true, admitted: { pages: 0, checkpoints: 0 } });}}), 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 () => {+test('#6561: upgrade writes no connector checkpoint row: schema migrations, including the v176 re-key handler, leave both cursors untouched', 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 });+ const { keys } = await upgradedSource(engine, 'pre-field completed + interim partial');+ const before = await snapshotRows(engine, [keys.preField, keys.interim]);+ expect(before).toHaveLength(2);+ await runMigrations(engine);+ for (const migration of MIGRATIONS.filter(m => /connector/.test(m.name) && m.handler)) await migration.handler!(engine);+ expect(await snapshotRows(engine, [keys.preField, keys.interim])).toEqual(before);}}), 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);+test('#6561 loader rule: an alias wins only when written after the stable row and it is the newer completed backfill; a reset or reopened stable row never falls back', () => {+ const row = (fingerprint: string, at: number, generation: number, state: Record<string, unknown> | null) => ({ fingerprint, at, completed_keys: [{ generation, state }] });+ const done = (newest: number) => ({ gmail_backfill_done: true, gmail_newest_ms: newest });+ expect(resumeCheckpoint(null, [])).toEqual([]);+ expect(resumeCheckpoint(null, [row('a', 1, 3, done(5))])).toEqual([{ generation: 3, state: done(5) }]);+ expect(resumeCheckpoint(row('s', 1, 7, done(5)), [row('a', 2, 3, done(9))])).toEqual([{ generation: 7, state: done(9) }]);+ expect(resumeCheckpoint(row('s', 1, 7, done(9)), [row('a', 2, 3, done(5))])).toEqual([{ generation: 7, state: done(9) }]);+ expect(resumeCheckpoint(row('s', 1, 7, done(5)), [row('a', 2, 3, { ...done(9), gmail_backfill_done: false })])).toEqual([{ generation: 7, state: done(5) }]);+ // The stable row this release saved is newer than any alias: a reset (state null) or a reopened backfill stays.+ expect(resumeCheckpoint(row('s', 3, 8, null), [row('a', 2, 3, done(9))])).toEqual([{ generation: 8, state: null }]);+ expect(resumeCheckpoint(row('s', 3, 8, { ...done(1), gmail_backfill_done: false }), [row('a', 2, 3, done(9))]))+ .toEqual([{ generation: 8, state: { ...done(1), gmail_backfill_done: false } }]);+});diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 81af7fa6d1..cd111684ff 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 243,+ "count": 242,"gaps": [17,18,@@ -43,7 +43,6 @@"grantFromRow": "2d0603bb0f964d7e45e04aa76bac54cd4f6f63c91a8d9f028b60b4792bc1695e","hnswMaxDimsForType": "a187cdcc520f813b7c39da97ce53da58509232ed9f851627ef41abfe1b68bd26","migrateAutoThinkToPins": "34267fe3b1cc4ab2850ddcf9ba18ce73d959678233a53de238c85231e6b71470",- "migrateConnectorAliasCheckpoints": "64ed79e69fe2fac760ffdc8a2c072014613649faa88721068182b40af8f1674d","migrateConnectorCheckpoints": "5c13e69a334bfc5275c7d555c4e7b28e034569f086dd4bd70b4b78fa4770dc7a","migrateLegacyTokens": "6e4abe3670127e7a495b56ecbf9f5789edd3a7362d45704656c2210a85b27f4c","migrationNotice": "9a6607b26a9719ef1833571b137bc8ebfcd1e16d545e89ff8728cf3ccbcbb409",@@ -57,7 +56,7 @@"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5","verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"},- "latest": 248,+ "latest": 247,"records": [{"handler": {@@ -3765,25 +3764,6 @@"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": [@@ -4028,8 +4008,7 @@244,245,246,- 247,- 248+ 247]},"normalizer": "migrations-record-v1"