Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(#6712 PR 4b lane C): replace the non-company cursor adoption, fan-in and overtaken-cursor tests with pass-level tests; strategy-6696 asserts the one pass row (red: an explicit configured strategy never checkpoints)

garrytan1ab9c6977a60
diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.md
index 9de742d346..2ee4a93cf9 100644
--- a/docs/architecture/key-files/managed-sync-bookkeeping.md
+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md
@@ -13,7 +13,7 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The
- `src/core/persistence/managed-sync-orphans.ts` + `src/core/repair/managed-sync-orphans.ts` — `gbrain repair managed-sync-orphans --source <id>` (#5459), explicit-only and preview-bound (approved set, `preview_changed` on drift). `classifyManagedSyncOrphans` (read-only; doctor `sync_failures` names the repair when it finds any) takes the source's managed-sync bookkeeping and classes each row `no_cursor` (a failure row with no cursor to resume), `principal_unadoptable` (an unfinished cursor recorded by a principal that is no longer an active local writer, by join on the recorded principal), `superseded` (a pre-options cursor a later run replaced), `incarnation_retired` (#6518: an unfinished cursor or a failure row recorded under a source incarnation the source no longer has, joined on the source id alone, archived sources excluded, a live pending request still retaining it) or `mirror_only` (#6518: a local ledger row with a `managed_cursor_key` and no durable failure row under that key; `mirrorOnlyManagedFailures`, which throws on a failed durable read rather than naming every mirror), and keeps `pending_request_live` and `resumable` rows untouched. `retireManagedSyncOrphan` retires one row atomically: an `incarnation_retired` cursor needs the source still active under another incarnation at apply time and skips the live-writer veto (no retired key is resumable); a `mirror_row` deletes nothing durable and prunes the ledger row only when the durable read, repeated at apply, still finds none. `pruneMirrorOnlyManagedFailures` is the successful-sync path (`clearSettledManagedSyncFailures`). Doctor `sync_failures` classifies whenever the brain is reachable, so the diagnostic is reachable with no current-incarnation failure visible, and reports a failed classification as unknown. `sources set-strategy` points at it when an unfinished run blocks a strategy change. Pinned by `test/repair-managed-sync-orphans.test.ts` and `test/managed-sync-orphans-incarnation-6518.test.ts` (both engines); `test/repair-explicit-only.test.ts` pins its place last in `REPAIR_KINDS`. #6712 PR 3 (L7): `slug_mode_refused` is an unfinished cursor whose every page committed and whose checkpoint was refused `slug_root_mode_mismatch` while the source still pins the other mode (`slugModeRefusedSql`, bound to the run and request at apply); no sync rediscovers it, so retiring it is how a person keeps the pin, and its slice record is cleared like `checkpoint_moved`'s.
-- `src/core/persistence/sync-cursor-key.ts` — #6712 PR 1: one managed cursor per source. `managedCursorKey` is a digest of the source incarnation and, for a company approval only, the company; writer principal, authority and options no longer select a cursor. `legacyManagedCursorKey` reproduces the pre-0.60.255.0 key (read-only). `resolveManagedCursor` is the one boundary that picks a run's key and folds older keys in crash-safely under the drain lease: the canonical unfinished cursor wins, else the newest older-key unfinished cursor is adopted and finished in place under its own key; every other older cursor has its queued requests cancelled and is retired through `retireManagedSyncOrphan` (reason `superseded_by_adoption`, fenced by `assertDrainLease`). A cursor with a running, recovering or publishing request or a recovery row is retained and the pass waits for that request (`writer_pending`) before it drains anything. A company brain's finished old-key cursors are kept. Pinned by `test/persistence-sync-cursor-adoption.test.ts` and `test/persistence-sync-cursor-strategy-6696.test.ts`.
+- `src/core/persistence/sync-cursor-key.ts` — #6712 PR 1: one managed cursor per source. `managedCursorKey` is a digest of the source incarnation and, for a company approval only, the company; writer principal, authority and options no longer select a cursor. `legacyManagedCursorKey` reproduces the pre-0.60.255.0 key (read-only). `resolveManagedCursor` is the one boundary that picks a run's key and folds older keys in crash-safely under the drain lease: the canonical unfinished cursor wins, else the newest older-key unfinished cursor is adopted and finished in place under its own key; every other older cursor has its queued requests cancelled and is retired through `retireManagedSyncOrphan` (reason `superseded_by_adoption`, fenced by `assertDrainLease`). A cursor with a running, recovering or publishing request or a recovery row is retained and the pass waits for that request (`writer_pending`) before it drains anything. A company brain's finished old-key cursors are kept. Pinned by `test/sync-pass-handover-6712.test.ts` (the live pass's handover of an older binary's cursors) and `test/persistence-sync-cursor-strategy-6696.test.ts`.
- `src/core/persistence/sync-lease.ts` — #6712 PR 1: the drain lease, one managed drainer per source. `withDrainLease` takes the source's sync lock (`syncLockId`) with a 2-minute TTL renewed every 20 s, so a dead holder's lease lapses inside one cron tick; it is reentrant for the holder (nested passes and the in-process lanes reuse it). The holder record (`managed-sync-lease` checkpoint: kind, id, version, start) plus the lock row give `readDrainHolder` (host, pid, heartbeat, `progress`: commits, last commit, last cursor save). A non-job holder also writes a beacon row in the `gbrain-drain-lease` minion queue (application authority, `max_stalled` 0, renewed with the lease, deleted on release) so an older binary's `liveSyncJob` backs off; downgrades are quiescent (stop serve and crons first). `assertDrainLease` is the fence inside every transaction that admits work, settles or holds an entry, folds a cursor in or swaps the cursor. Following callers (the CLI, a CLI run delegated to a serve) wait for a live holder within their budget (`followStopAt`) and take over when it releases; out of budget, or after losing the lease, they return `leaseHeldResult` (`resumable`, `sync_drain_lease_held`, `next.retry_after_ms` 60 s, `safe_to_loop`); a holder with no progress for `HOLDER_STALL_MS` (5 min) returns `leaseStalledResult` (`blocked`, `drain_stalled`, cause `no_progress`, `stall.lease_holder`). Jobs and the cycle get `SyncLockBusyError` and skip. Pinned by `test/persistence-sync-lease.test.ts`.
- `src/core/wire-skew.ts` — #6712 PR 1: the one record of wire-skew windows, each a version floor plus a calendar date (`WIRE_SKEW_WINDOWS.explicitProcessing`: floor 0.60.255.0, accepted and ignored until 2026-11-14). The delegation and admin wires read the field name from here, so removing the window is one edit. #6712 PR 2: each window names the hand-offs that accept it (`wires`) and its shape (`accepts`); `retiredWireFields` / `retiredWireNotice` serve both validators. `CONFIG_ROLLBACK_WINDOWS` records the rollback config keys' windows (honored until a date, from a version floor, with the notice that named them).
- `src/core/sync-flags.ts` — #6712 PR 2: `SYNC_FLAGS`, every `gbrain sync` flag once, with its route (`forward` / `client` / `refuse`) on the serve and PGLite owner hand-offs; `syncFlagsRouted` and `syncWireFields` derive the ladder's, the IPC validator's and the owner lane's allowlists. A flag the argv parsers read must be listed (`test/sync-flag-table-6712.test.ts`). #6712 PR 3 (L7): `managed: true` marks the ten flags `gbrain sync --help` lists under "Managed brains" (`MANAGED_HELP_FLAGS`, table order; `test/sync-managed-help-l7-6712.test.ts` pins the section and runs doctor's cron recipe through the managed flag validator).
diff --git a/scripts/postgres-arm-weights.json b/scripts/postgres-arm-weights.json
index a255f219c4..13133316d1 100644
--- a/scripts/postgres-arm-weights.json
+++ b/scripts/postgres-arm-weights.json
@@ -141,7 +141,6 @@
"test/persistence-skill-bundles.serial.test.ts": 8866,
"test/persistence-skill-crash.slow.test.ts": 43178,
"test/persistence-skip-cost.test.ts": 7714,
- "test/persistence-sync-cursor-adoption.test.ts": 60388,
"test/persistence-sync-cursor-options.test.ts": 11035,
"test/persistence-sync-cursor-strategy-6696.test.ts": 11399,
"test/persistence-sync-fence-holds.test.ts": 32583,
diff --git a/scripts/test-weights.json b/scripts/test-weights.json
index d721cbebf2..7445e1d7f1 100644
--- a/scripts/test-weights.json
+++ b/scripts/test-weights.json
@@ -2207,7 +2207,6 @@
"test/persistence-source-lifecycle.test.ts": 5709,
"test/persistence-staging.test.ts": 1403,
"test/persistence-sync-checkpoint-validation.test.ts": 9759,
- "test/persistence-sync-cursor-adoption.test.ts": 29387,
"test/persistence-sync-cursor-options.test.ts": 2366,
"test/persistence-sync-cursor-strategy-6696.test.ts": 2703,
"test/persistence-sync-fence-holds.test.ts": 6860,
@@ -2215,7 +2214,6 @@
"test/persistence-sync-lease.test.ts": 11776,
"test/persistence-sync-legacy-files-5751.test.ts": 1362,
"test/persistence-sync-origin-native.test.ts": 2689,
- "test/persistence-sync-overtaken-cursor-5522.test.ts": 3440,
"test/persistence-sync-receipt-diagnostics.test.ts": 6,
"test/persistence-sync-stdio-owner.test.ts": 22557,
"test/persistence-take-receipt-authority.test.ts": 1362,
diff --git a/scripts/ubicloud/weights.json b/scripts/ubicloud/weights.json
index 1489ad692c..88220440cc 100644
--- a/scripts/ubicloud/weights.json
+++ b/scripts/ubicloud/weights.json
@@ -2620,7 +2620,6 @@
"unit:test/persistence-sync-holds.test.ts": 11450,
"unit:test/persistence-sync-legacy-files-5751.test.ts": 4571,
"unit:test/persistence-sync-origin-native.test.ts": 6447,
- "unit:test/persistence-sync-overtaken-cursor-5522.test.ts": 5081,
"unit:test/persistence-sync-receipt-diagnostics.test.ts": 289,
"unit:test/persistence-sync-stdio-owner.test.ts": 46891,
"unit:test/persistence-take-receipt-authority.test.ts": 2387,
diff --git a/test/e2e/fix-wave-4-lane-a.test.ts b/test/e2e/fix-wave-4-lane-a.test.ts
index 9175576945..0ac9483d55 100644
--- a/test/e2e/fix-wave-4-lane-a.test.ts
+++ b/test/e2e/fix-wave-4-lane-a.test.ts
@@ -1,8 +1,7 @@
import { registerPostgresTests } from '../helpers/test-backends.ts';
-// Fix wave 4 lane A (#5762, #5751, #5522): the PostgreSQL arm of the checkpoint validation, legacy working-tree file and overtaken cursor suites.
+// Fix wave 4 lane A (#5762, #5751): the PostgreSQL arm of the checkpoint validation and legacy working-tree file suites.
await registerPostgresTests(
() => import('../persistence-sync-checkpoint-validation.test.ts'),
() => import('../persistence-sync-legacy-files-5751.test.ts'),
- () => import('../persistence-sync-overtaken-cursor-5522.test.ts'),
);
diff --git a/test/persistence-sync-cursor-adoption.test.ts b/test/persistence-sync-cursor-adoption.test.ts
deleted file mode 100644
index fa07003707..0000000000
--- a/test/persistence-sync-cursor-adoption.test.ts
+++ /dev/null
@@ -1,315 +0,0 @@
-import { afterAll, afterEach, beforeAll, expect, test } from 'bun:test';
-import { randomUUID } from 'node:crypto';
-import { execFileSync } from 'node:child_process';
-import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import type { BrainEngine } from '../src/core/engine.ts';
-import type { SyncOpts } from '../src/commands/sync.ts';
-import { claimWorktree } from '../src/core/persistence/ownership.ts';
-import { performManagedSync } from '../src/core/persistence/sync-run.ts';
-import { __setManagedCursorKeyForTests, managedCursorKey, SUPERSEDED_BY_ADOPTION_MESSAGE } from '../src/core/persistence/sync-cursor-key.ts';
-import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
-import { installFaultHook } from '../src/core/persistence/fault-points.ts';
-import { prepareRemoteJob, withSubmissionAuthority } from '../src/core/minions/submission-authority.ts';
-import type { OperationContext } from '../src/core/ops/contract.ts';
-import { withEnv } from './helpers/with-env.ts';
-import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
-
-// #6712 PR 1: one cursor per source incarnation, adopted by whoever resumes it. What these tests protect:
-// - admitted requests keep their identity: they are read under the principal frozen in their own intent and publish
-// under it, while the resumer's authority is validated and stamped on the cursor in the adoption CAS and everything
-// frozen afterwards is admitted under the resumer (cross-principal, remote→local);
-// - a remote caller never adopts a local cursor (local→remote) and a revoked writer resumes nothing;
-// - the fan-in finishes an older key's newest unfinished cursor in place and supersedes the rest (their queued requests
-// cancelled), never retiring one whose request is still running, and never touching a company approval's cursor.
-// The eng-review probe (adoption vs admitted-request identity) is the first test: a cross-principal adoption of a run
-// whose admitted request is still running, new admissions after it, and a run stopped during checkpoint completion that
-// a third writer finishes. On the base the resumer reads the admitted request under its own principal, misses it and
-// admits it again under the same request_id.
-
-const home = mkdtempSync(join(tmpdir(), 'gbrain-cursor-adoption-'));
-const homes = { a: join(home, 'writer-a'), b: join(home, 'writer-b'), c: join(home, 'writer-c') };
-const engines: BrainEngine[] = [];
-let closePostgres: (() => Promise<void>) | undefined;
-const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
-beforeAll(async () => {
- for (const dir of Object.values(homes)) mkdirSync(dir, { recursive: true });
- const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
- if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }
-}, 120_000);
-afterEach(() => installFaultHook(undefined));
-afterAll(async () => {
- await withEnv({ GBRAIN_HOME: homes.a }, async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } });
- await closePostgres?.(); rmSync(home, { recursive: true, force: true });
-});
-async function fixture(engine: BrainEngine, names = ['a', 'b', 'c']) {
- const id = `adopt-${randomUUID().slice(0, 12)}`, root = join(home, id);
- mkdirSync(root); git(root, 'init', '-q');
- for (const name of names) writeFileSync(join(root, `${name}.md`), `---\ntitle: ${name}\n---\nA durable observation named ${name} at acme-example.\n`);
- git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'seed');
- await disposePersistenceConsumer(engine);
- await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
- await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);
- await claimWorktree(engine, id, root);
- await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
- return id;
-}
-const env = { OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
-/** Each writer is its own local CLI registration on the same host: the host identity is shared, the registration is not. */
-function shareHost(writer: keyof typeof homes): void {
- const from = join(homes.a, '.gbrain', 'persistence', 'host.json'), dir = join(homes[writer], '.gbrain', 'persistence');
- if (writer === 'a' || !existsSync(from)) return;
- mkdirSync(dir, { recursive: true, mode: 0o700 });
- if (!existsSync(join(dir, 'host.json'))) { copyFileSync(from, join(dir, 'host.json')); chmodSync(join(dir, 'host.json'), 0o600); }
-}
-const as = <T>(writer: keyof typeof homes, fn: () => Promise<T>) => { shareHost(writer); return withEnv({ GBRAIN_HOME: homes[writer], ...env }, fn); };
-const each = (fn: (engine: BrainEngine) => Promise<void>) => as('a', async () => { for (const engine of engines) await fn(engine); });
-const opts = (sourceId: string): SyncOpts => ({ sourceId, noPull: true, noEmbed: true, noExtract: true });
-const requests = async (engine: BrainEngine, id: string) => engine.executeRaw<{ request_id: string; principal_id: string; kind: string; state: string; writer: string }>(
- `SELECT request_id::text AS request_id, principal_id, intent->>'kind' AS kind, state, intent->'syncAuthority'->'writer'->'principal'->>'id' AS writer
- FROM persistence_requests WHERE source_id=$1 ORDER BY sequence`, [id]);
-const cursorWriter = async (engine: BrainEngine, id: string) => (await engine.executeRaw<{ id: string }>(
- "SELECT completed_keys->0->'authority'->'writer'->'principal'->>'id' AS id FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [id]))[0]?.id;
-/** Stalls the consumer's preparation of the matching request until released, so the run's wait ends with it admitted and running. */
-function stallPreparation(match: (requestId: string) => Promise<boolean>) {
- let release!: () => void;
- const gate = new Promise<void>(resolve => { release = resolve; });
- installFaultHook(async (point, detail) => { if (point === 'consumer:preparing' && detail.requestId && await match(detail.requestId)) await gate; });
- return release;
-}
-
-test('cross-principal adoption keeps every admitted request under its own principal: running members, new admissions, a stop during checkpoint completion', async () => each(async engine => {
- const id = await fixture(engine);
- const kindOf = async (requestId: string) => (await engine.executeRaw<{ kind: string }>("SELECT intent->>'kind' AS kind FROM persistence_requests WHERE request_id=$1::uuid", [requestId]))[0]?.kind;
- // Writer A commits one page.
- expect(await as('a', () => performManagedSync(engine, opts(id), { maxPages: 1, maxMs: 1000 }))).toMatchObject({ status: 'partial' });
- // Writer B admits the next page, whose preparation stalls: B's wait ends with it running.
- let release = stallPreparation(async rid => await kindOf(rid) === 'managed_sync_import');
- expect(await as('b', () => performManagedSync(engine, opts(id)))).toMatchObject({ status: 'partial', reason: 'writer_pending' });
- const [first, running] = await requests(engine, id);
- expect(running).toMatchObject({ state: 'running', kind: 'managed_sync_import' });
- expect(running!.principal_id).not.toBe(first!.principal_id);
- // Writer C adopts while B's request is still running, then admits the rest; its checkpoint's preparation stalls.
- const releaseB = release;
- release = stallPreparation(async rid => await kindOf(rid) === 'managed_sync_checkpoint');
- setTimeout(releaseB, 500);
- const byC = await as('c', () => performManagedSync(engine, opts(id)));
- expect(byC).toMatchObject({ status: 'partial', reason: 'writer_pending', cursorAdopted: { writer_changed: true } });
- // A (again) finishes the checkpoint C admitted, reading it under C's principal.
- setTimeout(release, 500);
- const byA = await as('a', () => performManagedSync(engine, opts(id)));
- expect(byA.status).toBe('first_sync');
- const rows = await requests(engine, id);
- expect(new Set(rows.map(row => row.request_id)).size).toBe(rows.length);
- expect(rows.map(row => [row.kind, row.state])).toEqual([['managed_sync_import', 'committed'], ['managed_sync_import', 'committed'],
- ['managed_sync_import', 'committed'], ['managed_sync_checkpoint', 'committed']]);
- // Every request was admitted by the writer whose authority it carries: A, B, C, C.
- for (const row of rows) expect(row.principal_id).toBe(row.writer);
- expect(rows[1]!.principal_id).toBe(running!.principal_id);
- expect(rows[2]!.principal_id).toBe(rows[3]!.principal_id);
- expect(new Set(rows.map(row => row.principal_id)).size).toBe(3);
- expect(await engine.getPage('c', { sourceId: id })).not.toBeNull();
-}), 180_000);
-
-test('remote→local: the host CLI adopts a remote job\'s unfinished cursor and admits the rest under its own grant', async () => each(async engine => {
- const id = await fixture(engine);
- const clientId = `adopt-client-${randomUUID()}`;
- await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_name,client_secret_hash,scope,source_id,allowed_operations)
- VALUES($1,'example-client','test-only','admin',$2,ARRAY['submit_job'])`, [clientId, id]);
- try {
- const ctx = { engine, remote: true, sourceId: id, auth: { clientId, principal: { kind: 'oauth_client', id: clientId }, scopes: ['admin'], sourceId: id,
- allowedOperations: ['submit_job'] } } as unknown as OperationContext;
- const accepted = await prepareRemoteJob(ctx, 'sync', { noPull: true });
- expect(await withSubmissionAuthority(accepted.authority, () => performManagedSync(engine, { ...accepted.data } as SyncOpts, { maxPages: 1, maxMs: 1000 })))
- .toMatchObject({ status: 'partial' });
- expect(await cursorWriter(engine, id)).toBe(clientId);
- const local = await performManagedSync(engine, opts(id));
- expect(local).toMatchObject({ status: 'first_sync', cursorAdopted: { writer_changed: true } });
- const rows = await requests(engine, id);
- expect(rows[0]!.principal_id).toBe(clientId);
- expect(rows.slice(1).every(row => row.principal_id !== clientId && row.principal_id === row.writer)).toBe(true);
- } finally { await engine.executeRaw('DELETE FROM oauth_clients WHERE client_id=$1', [clientId]); }
-}), 180_000);
-
-test('local→remote: a remote job never adopts a local cursor; it is told the host CLI resumes it', async () => each(async engine => {
- const id = await fixture(engine);
- expect(await performManagedSync(engine, opts(id), { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });
- const writer = await cursorWriter(engine, id);
- const clientId = `adopt-client-${randomUUID()}`;
- await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_name,client_secret_hash,scope,source_id,allowed_operations)
- VALUES($1,'example-client','test-only','admin',$2,ARRAY['submit_job'])`, [clientId, id]);
- try {
- const ctx = { engine, remote: true, sourceId: id, auth: { clientId, principal: { kind: 'oauth_client', id: clientId }, scopes: ['admin'], sourceId: id,
- allowedOperations: ['submit_job'] } } as unknown as OperationContext;
- const accepted = await prepareRemoteJob(ctx, 'sync', { noPull: true });
- const refused = await withSubmissionAuthority(accepted.authority, () => performManagedSync(engine, { ...accepted.data } as SyncOpts)).then(() => null, (error: unknown) => error);
- expect(refused).toMatchObject({ code: 'sync_in_progress', reason: 'local_resume_required', fix: { actor: 'user', argv: ['gbrain', 'sync', '--no-pull', '--source', id] } });
- expect(await cursorWriter(engine, id)).toBe(writer!);
- expect((await requests(engine, id)).every(row => row.principal_id !== clientId)).toBe(true);
- } finally { await engine.executeRaw('DELETE FROM oauth_clients WHERE client_id=$1', [clientId]); }
- expect((await performManagedSync(engine, opts(id))).status).toBe('first_sync');
-}), 180_000);
-
-test('a revoked writer resumes nothing; another writer adopts its cursor and nothing more is admitted on the revoked grant', async () => each(async engine => {
- const id = await fixture(engine);
- expect(await as('b', () => performManagedSync(engine, opts(id), { maxPages: 1, maxMs: 1000 }))).toMatchObject({ status: 'partial' });
- const revoked = (await cursorWriter(engine, id))!;
- await engine.executeRaw('UPDATE persistence_local_writers SET revoked_at=now() WHERE id=$1::uuid', [revoked]);
- const refused = await as('b', () => performManagedSync(engine, opts(id))).then(() => null, (error: unknown) => error);
- expect(refused).toMatchObject({ code: 'permission_denied' });
- expect((await requests(engine, id)).filter(row => row.principal_id === revoked)).toHaveLength(1);
- expect((await as('c', () => performManagedSync(engine, opts(id)))).status).toBe('first_sync');
- expect((await requests(engine, id)).filter(row => row.principal_id === revoked)).toHaveLength(1);
- expect(await cursorWriter(engine, id)).not.toBe(revoked);
-}), 180_000);
-
-test('fan-in: the newest older-key cursor finishes in place; an older one is kept while its request runs, then superseded', async () => each(async engine => {
- const id = await fixture(engine, ['a', 'b', 'c', 'd']);
- const keys = async () => (await engine.executeRaw<{ key: string; done: string | null }>(
- "SELECT fingerprint AS key, completed_keys->0->>'done' AS done FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1 ORDER BY fingerprint", [id]));
- const park = (key: string, op: string) => engine.executeRaw('UPDATE op_checkpoints SET op=$2 WHERE fingerprint=$1 AND op IN (\'managed-sync\',\'managed-sync-parked\')', [key, op]);
- let release = () => {};
- try {
- // An older binary's cursor (`legacy-newest`) that committed one page and has nothing open...
- __setManagedCursorKeyForTests(() => 'legacy-newest');
- expect(await performManagedSync(engine, opts(id), { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });
- await park('legacy-newest', 'managed-sync-parked');
- // ...and another (`legacy-running`) whose admitted request is still running.
- __setManagedCursorKeyForTests(() => 'legacy-running');
- release = stallPreparation(async () => true);
- expect(await performManagedSync(engine, opts(id))).toMatchObject({ status: 'partial', reason: 'writer_pending' });
- await park('legacy-newest', 'managed-sync');
- await engine.executeRaw("UPDATE op_checkpoints SET updated_at=now()-interval '1 hour' WHERE op='managed-sync' AND fingerprint='legacy-running'");
- } finally { __setManagedCursorKeyForTests(null); }
- // The current key runs: the newest is adopted and finished in place; the running one is retained, never retired under its request.
- expect(await engine.executeRaw("SELECT 1 FROM persistence_requests WHERE source_id=$1 AND intent->>'cursorKey'='legacy-running' AND state='running'", [id])).toHaveLength(1);
- // The pass waits for that request (writer_pending, naming it) instead of publishing beside it.
- const waited = await performManagedSync(engine, opts(id));
- expect(waited).toMatchObject({ status: 'partial', reason: 'writer_pending', retryWait: { state: 'running' }, cursorFanIn: { adopted: true, superseded: 0, retained: 1 } });
- release();
- installFaultHook(undefined);
- for (let i = 0; i < 100 && (await engine.executeRaw("SELECT 1 FROM persistence_requests WHERE source_id=$1 AND state IN ('queued','running')", [id])).length; i++) await new Promise(resolve => setTimeout(resolve, 100));
- const folded = await performManagedSync(engine, opts(id));
- expect({ status: folded.status, write: folded.managedWrite?.reason ?? null }).toEqual({ status: 'first_sync', write: null });
- expect(folded.cursorFanIn).toEqual({ adopted: true, superseded: 1, retained: 0 });
- expect((await keys()).map(row => row.key)).toEqual(['legacy-newest']);
- // The next run supersedes what is left of the older keys and finishes under the current key.
- writeFileSync(join(home, id, 'e.md'), '---\ntitle: e\n---\nA durable observation named e at acme-example.\n');
- git(join(home, id), 'add', '.'); git(join(home, id), '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'e');
- expect((await performManagedSync(engine, opts(id))).status).toBe('synced');
- const inc = (await engine.executeRaw<{ i: string }>('SELECT incarnation::text AS i FROM sources WHERE id=$1', [id]))[0]!.i;
- expect(await keys()).toEqual([{ key: managedCursorKey(inc, undefined), done: 'true' }]);
- expect(await engine.executeRaw("SELECT 1 FROM persistence_requests WHERE source_id=$1 AND state NOT IN ('committed','cancelled')", [id])).toHaveLength(0);
- const cancelled = await engine.executeRaw<{ message: string }>("SELECT error_message AS message FROM persistence_requests WHERE source_id=$1 AND state='cancelled'", [id]);
- for (const row of cancelled) expect(row.message).toBe(SUPERSEDED_BY_ADOPTION_MESSAGE);
- expect(await engine.getPage('e', { sourceId: id })).not.toBeNull();
-}), 180_000);
-
-test('fan-in is crash-safe: a run killed right after it supersedes an older-key cursor leaves it retired, and the next run finishes', async () => each(async engine => {
- const id = await fixture(engine, ['a', 'b', 'c', 'd']);
- const park = (key: string, op: string) => engine.executeRaw('UPDATE op_checkpoints SET op=$2 WHERE fingerprint=$1 AND op IN (\'managed-sync\',\'managed-sync-parked\')', [key, op]);
- const older = `${id}-older`, newest = `${id}-newest`;
- try {
- __setManagedCursorKeyForTests(() => older);
- expect(await performManagedSync(engine, opts(id), { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });
- await park(older, 'managed-sync-parked');
- __setManagedCursorKeyForTests(() => newest);
- expect(await performManagedSync(engine, opts(id), { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });
- await park(older, 'managed-sync');
- await engine.executeRaw("UPDATE op_checkpoints SET updated_at=now()-interval '1 hour' WHERE op='managed-sync' AND fingerprint=$1", [older]);
- } finally { __setManagedCursorKeyForTests(null); }
- for (let i = 0; i < 100 && (await engine.executeRaw("SELECT 1 FROM persistence_requests WHERE source_id=$1 AND state IN ('queued','running')", [id])).length; i++) await new Promise(resolve => setTimeout(resolve, 100));
- installFaultHook(async (point, detail) => { if (point === 'sync:cursor_adopted' && detail.sourceId === id) throw new Error('killed after the supersede'); });
- await expect(performManagedSync(engine, opts(id))).rejects.toThrow('killed after the supersede');
- installFaultHook(undefined);
- const cursors = async () => (await engine.executeRaw<{ key: string }>(
- "SELECT fingerprint AS key FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1 ORDER BY fingerprint", [id])).map(row => row.key);
- expect(await cursors()).toEqual([newest]);
- const resumed = await performManagedSync(engine, opts(id));
- expect(resumed.status).toBe('first_sync');
- expect(resumed.cursorFanIn).toEqual({ adopted: true, superseded: 0, retained: 0 });
- for (const name of ['a', 'b', 'c', 'd']) expect(await engine.getPage(name, { sourceId: id })).not.toBeNull();
- expect(await engine.executeRaw("SELECT 1 FROM persistence_requests WHERE source_id=$1 AND state NOT IN ('committed','cancelled')", [id])).toHaveLength(0);
- for (const row of await engine.executeRaw<{ message: string }>("SELECT error_message AS message FROM persistence_requests WHERE source_id=$1 AND state='cancelled'", [id])) {
- expect(row.message).toBe(SUPERSEDED_BY_ADOPTION_MESSAGE);
- }
-}), 180_000);
-
-// Outside-voice review: a request claimed between the fan-in's read and its retirement must still hold the pass back.
-test('fan-in: a request claimed between the read and the retirement keeps the pass waiting (writer_pending), not draining beside it', async () => each(async engine => {
- const id = await fixture(engine, ['a', 'b', 'c', 'd']);
- const park = (key: string, op: string) => engine.executeRaw('UPDATE op_checkpoints SET op=$2 WHERE fingerprint=$1 AND op IN (\'managed-sync\',\'managed-sync-parked\')', [key, op]);
- const newest = `${id}-newest`, raced = `${id}-raced`;
- let release = () => {};
- try {
- __setManagedCursorKeyForTests(() => newest);
- expect(await performManagedSync(engine, opts(id), { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });
- await park(newest, 'managed-sync-parked');
- __setManagedCursorKeyForTests(() => raced);
- release = stallPreparation(async () => true);
- expect(await performManagedSync(engine, opts(id))).toMatchObject({ status: 'partial', reason: 'writer_pending' });
- await park(newest, 'managed-sync');
- await engine.executeRaw("UPDATE op_checkpoints SET updated_at=now()-interval '1 hour' WHERE op='managed-sync' AND fingerprint=$1", [raced]);
- } finally { __setManagedCursorKeyForTests(null); }
- // The fan-in's first read of the raced cursor's requests sees nothing open (the claim lands right after it).
- const execute = engine.executeRaw;
- let hidden = false;
- engine.executeRaw = async function (this: BrainEngine, sql: string, params?: unknown[]) {
- if (!hidden && sql.includes("intent->>'cursorKey'=$2") && sql.startsWith('SELECT * FROM persistence_requests') && params?.[1] === raced) { hidden = true; return []; }
- return execute.call(this, sql, params);
- } as BrainEngine['executeRaw'];
- let waited;
- try { waited = await performManagedSync(engine, opts(id)); } finally { engine.executeRaw = execute; }
- expect(hidden).toBe(true);
- expect(waited).toMatchObject({ status: 'partial', reason: 'writer_pending', retryWait: { state: 'running' }, cursorFanIn: { adopted: true, superseded: 0, retained: 1 } });
- release();
- installFaultHook(undefined);
- for (let i = 0; i < 100 && (await engine.executeRaw("SELECT 1 FROM persistence_requests WHERE source_id=$1 AND state IN ('queued','running')", [id])).length; i++) await new Promise(resolve => setTimeout(resolve, 100));
- expect((await performManagedSync(engine, opts(id))).status).toBe('first_sync');
-}), 180_000);
-
-// Outside-voice review: a remote caller refused adoption must not have cancelled or retired the local runs it passed over.
-test('a remote job refused the local winner folds nothing in: every older-key cursor and its requests stay as they were', async () => each(async engine => {
- const id = await fixture(engine, ['a', 'b', 'c', 'd']);
- const park = (key: string, op: string) => engine.executeRaw('UPDATE op_checkpoints SET op=$2 WHERE fingerprint=$1 AND op IN (\'managed-sync\',\'managed-sync-parked\')', [key, op]);
- const newest = `${id}-newest`, older = `${id}-older`;
- const keys = async () => (await engine.executeRaw<{ key: string }>("SELECT fingerprint AS key FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1 ORDER BY fingerprint", [id])).map(row => row.key);
- try {
- __setManagedCursorKeyForTests(() => older);
- expect(await performManagedSync(engine, opts(id), { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });
- await park(older, 'managed-sync-parked');
- __setManagedCursorKeyForTests(() => newest);
- expect(await performManagedSync(engine, opts(id), { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });
- await park(older, 'managed-sync');
- await engine.executeRaw("UPDATE op_checkpoints SET updated_at=now()-interval '1 hour' WHERE op='managed-sync' AND fingerprint=$1", [older]);
- } finally { __setManagedCursorKeyForTests(null); }
- const before = { keys: await keys(), requests: await requests(engine, id) };
- expect(before.keys).toEqual([newest, older].sort());
- const clientId = `adopt-client-${randomUUID()}`;
- await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_name,client_secret_hash,scope,source_id,allowed_operations)
- VALUES($1,'example-client','test-only','admin',$2,ARRAY['submit_job'])`, [clientId, id]);
- try {
- const ctx = { engine, remote: true, sourceId: id, auth: { clientId, principal: { kind: 'oauth_client', id: clientId }, scopes: ['admin'], sourceId: id,
- allowedOperations: ['submit_job'] } } as unknown as OperationContext;
- const accepted = await prepareRemoteJob(ctx, 'sync', { noPull: true });
- const refused = await withSubmissionAuthority(accepted.authority, () => performManagedSync(engine, { ...accepted.data } as SyncOpts)).then(() => null, (error: unknown) => error);
- expect(refused).toMatchObject({ code: 'sync_in_progress', reason: 'local_resume_required' });
- } finally { await engine.executeRaw('DELETE FROM oauth_clients WHERE client_id=$1', [clientId]); }
- expect({ keys: await keys(), requests: await requests(engine, id) }).toEqual(before);
- // The host CLI then folds them in.
- expect((await performManagedSync(engine, opts(id))).status).toBe('first_sync');
-}), 180_000);
-
-test('a company approval\'s cursor is never adopted or superseded by an ordinary run of the source', async () => each(async engine => {
- const id = await fixture(engine);
- const inc = (await engine.executeRaw<{ i: string }>('SELECT incarnation::text AS i FROM sources WHERE id=$1', [id]))[0]!.i;
- const header = { sourceId: id, incarnation: inc, runId: randomUUID(), index: 0, total: 0, companyReceiptId: 'receipt-example', counts: {} };
- await engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync','company-example',$1::text::jsonb)", [JSON.stringify([header])]);
- const result = await performManagedSync(engine, opts(id));
- expect(result.status).toBe('first_sync');
- expect(result.cursorFanIn).toBeUndefined();
- expect(await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync' AND fingerprint='company-example'")).toHaveLength(1);
- await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-sync' AND fingerprint='company-example'");
-}), 180_000);
diff --git a/test/persistence-sync-cursor-strategy-6696.test.ts b/test/persistence-sync-cursor-strategy-6696.test.ts
index 26a04dc418..df3f2204a4 100644
--- a/test/persistence-sync-cursor-strategy-6696.test.ts
+++ b/test/persistence-sync-cursor-strategy-6696.test.ts
@@ -9,20 +9,19 @@ import type { BrainEngine } from '../src/core/engine.ts';
import type { SyncOpts } from '../src/commands/sync.ts';
import { claimWorktree } from '../src/core/persistence/ownership.ts';
import { performManagedSync } from '../src/core/persistence/sync-run.ts';
-import { managedCursorKey } from '../src/core/persistence/sync-cursor-key.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { withEnv } from './helpers/with-env.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
// #6696 C1: `sync --all` passes the source's configured strategy while a single-source CLI run, autopilot's cycle and a
// serve-delegated run pass none, so the same source got two cursor keys (two unfinished cursors that could not resume each
-// other). #6712 PR 1 rewrote these tests: the key no longer digests any option (`managedCursorKey(incarnation, company)`),
-// so the strategy normalization (`selectManagedCursor`) is deleted. Every run of the source selects the same cursor, a run
-// with other options finishes the unfinished one under its frozen options, and a cursor written under an older key is
-// finished in place under that key (the requests it admitted name it), after which the next run takes the current key.
+// other). #6712 PR 1 took every option out of the cursor key; #6712 PR 4b replaced a non-company source's cursor with one
+// live pass row per source incarnation (`managed-sync-pass`, `<source>:<incarnation>`). Every caller's pass of the source,
+// whatever strategy it passes, reads and writes that one row and leaves no cursor row behind. The legacy-key handover
+// (an older binary's cursor) is covered by sync-pass-handover-6712.test.ts and sync-pass-cursor-retirement-6712.test.ts.
//
-// Regression guarded: an option creeping back into the key (the keys diverge again), or an older key's live cursor moved
-// to the current key (its queued requests are fenced out by the cursor they no longer match).
+// Regression guarded: an option creeping back into the pass row's key (two rows for one source), or a pass of one caller
+// unable to finish another's.
const home = mkdtempSync(join(tmpdir(), 'gbrain-cursor-strategy-'));
const engines: BrainEngine[] = [];
@@ -48,12 +47,13 @@ async function fixture(engine: BrainEngine, config: Record<string, unknown>) {
await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
return id;
}
+const lastCommit = async (engine: BrainEngine, id: string) => (await engine.executeRaw<{ c: string | null }>('SELECT last_commit AS c FROM sources WHERE id=$1', [id]))[0]!.c;
const rootOf = async (engine: BrainEngine, id: string) => (await engine.executeRaw<{ p: string }>('SELECT local_path AS p FROM sources WHERE id=$1', [id]))[0]!.p;
const isolated = (fn: (engine: BrainEngine) => Promise<void>) => withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {
for (const engine of engines) await fn(engine);
});
-const cursors = async (engine: BrainEngine, id: string) => engine.executeRaw<{ key: string; done: string | null; strategy: string | null }>(
- "SELECT fingerprint AS key,completed_keys->0->>'done' AS done,completed_keys->0->'syncOptions'->>'strategy' AS strategy FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [id]);
+const stateRows = async (engine: BrainEngine, id: string) => engine.executeRaw<{ op: string; key: string }>(
+ "SELECT op, fingerprint AS key FROM op_checkpoints WHERE op IN ('managed-sync','managed-sync-pass') AND (completed_keys->0->>'sourceId'=$1 OR completed_keys->0->>'source_id'=$1) ORDER BY op, fingerprint", [id]);
const refused = async (engine: BrainEngine, id: string) => (await engine.executeRaw<{ n: number }>(
"SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND state IN ('failed','conflict','cancelled')", [id]))[0]!.n;
const incarnation = async (engine: BrainEngine, id: string) => (await engine.executeRaw<{ i: string }>('SELECT incarnation::text AS i FROM sources WHERE id=$1', [id]))[0]!.i;
@@ -61,42 +61,25 @@ const incarnation = async (engine: BrainEngine, id: string) => (await engine.exe
const single = (sourceId: string): SyncOpts => ({ sourceId, noPull: true, noEmbed: true });
const all = (sourceId: string): SyncOpts => ({ ...single(sourceId), strategy: 'markdown' });
-test('a single-source run and a `sync --all` run of a source configured with a strategy select one cursor key', async () => isolated(async engine => {
+test('a single-source run and a `sync --all` run of a source configured with a strategy share one pass row', async () => isolated(async engine => {
const id = await fixture(engine, { strategy: 'markdown' });
expect(await performManagedSync(engine, single(id), { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });
- const key = managedCursorKey(await incarnation(engine, id), undefined);
- expect(await cursors(engine, id)).toEqual([{ key, done: null, strategy: null }]);
- // `sync --all`'s strategy differs from the cursor's frozen (absent) one: it finishes that run and says so.
+ const pass = [{ op: 'managed-sync-pass', key: `${id}:${await incarnation(engine, id)}` }];
+ expect(await stateRows(engine, id)).toEqual(pass);
const finished = await performManagedSync(engine, all(id));
expect(finished.status).toBe('first_sync');
- expect(finished.cursorAdopted).toMatchObject({ writer_changed: false, legacy_key: false, sync_options: expect.objectContaining({ strategy: null }) });
- expect(await cursors(engine, id)).toEqual([{ key, done: 'true', strategy: null }]);
+ expect(await stateRows(engine, id)).toEqual(pass);
expect(await refused(engine, id)).toBe(0);
+ for (const name of ['a', 'b', 'c', 'd']) expect(await engine.getPage(name, { sourceId: id })).not.toBeNull();
+ expect(await lastCommit(engine, id)).toBe(git(await rootOf(engine, id), 'rev-parse', 'HEAD'));
}), 120_000);
-test('an unfinished cursor under an older key finishes under that key; the next fresh run takes the current key', async () => isolated(async engine => {
- const id = await fixture(engine, {});
- expect(await performManagedSync(engine, single(id), { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });
- // The same cursor as an older binary keyed it (the key digested principal, authority and options).
- const legacy = `legacy-${randomUUID()}`;
- await engine.executeRaw("UPDATE op_checkpoints SET fingerprint=$2 WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [id, legacy]);
- await engine.executeRaw(`UPDATE sources SET config='{"strategy":"markdown"}'::jsonb WHERE id=$1`, [id]);
- const resumed = await performManagedSync(engine, single(id));
- expect(resumed.status).toBe('first_sync');
- expect(resumed.cursorFanIn).toEqual({ adopted: true, superseded: 0, retained: 0 });
- expect(await cursors(engine, id)).toEqual([{ key: legacy, done: 'true', strategy: null }]);
- expect(await refused(engine, id)).toBe(0);
- // Finished: the next run retires it and takes the current key, whichever caller it is.
- writeFileSync(join(await rootOf(engine, id), 'e.md'), '---\ntitle: e\n---\nA durable observation named e at fund-a.\n');
- git(await rootOf(engine, id), 'add', '.'); git(await rootOf(engine, id), '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'e');
- expect((await performManagedSync(engine, all(id))).status).toBe('synced');
- expect(await cursors(engine, id)).toEqual([{ key: managedCursorKey(await incarnation(engine, id), undefined), done: 'true', strategy: 'markdown' }]);
-}), 120_000);
-
-test('an explicit --strategy that differs from the configured one resumes the same cursor', async () => isolated(async engine => {
+test('an explicit --strategy that differs from the configured one runs on the same pass row, and the next plain pass checkpoints HEAD', async () => isolated(async engine => {
const id = await fixture(engine, { strategy: 'markdown' });
expect(await performManagedSync(engine, single(id), { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });
- const finished = await performManagedSync(engine, { ...single(id), strategy: 'auto' });
- expect(finished.status).toBe('first_sync');
- expect(await cursors(engine, id)).toHaveLength(1);
+ expect((await performManagedSync(engine, { ...single(id), strategy: 'auto' })).status).not.toBe('blocked_by_failures');
+ expect(await stateRows(engine, id)).toEqual([{ op: 'managed-sync-pass', key: `${id}:${await incarnation(engine, id)}` }]);
+ expect((await performManagedSync(engine, single(id))).status).not.toBe('blocked_by_failures');
+ for (const name of ['a', 'b', 'c', 'd']) expect(await engine.getPage(name, { sourceId: id })).not.toBeNull();
+ expect(await lastCommit(engine, id)).toBe(git(await rootOf(engine, id), 'rev-parse', 'HEAD'));
}), 120_000);
diff --git a/test/persistence-sync-overtaken-cursor-5522.test.ts b/test/persistence-sync-overtaken-cursor-5522.test.ts
deleted file mode 100644
index fe52b7d4cc..0000000000
--- a/test/persistence-sync-overtaken-cursor-5522.test.ts
+++ /dev/null
@@ -1,149 +0,0 @@
-import { afterAll, beforeAll, expect, test } from 'bun:test';
-import { randomUUID } from 'node:crypto';
-import { execFileSync } from 'node:child_process';
-import { join } from 'node:path';
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import type { BrainEngine } from '../src/core/engine.ts';
-import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { claimWorktree } from '../src/core/persistence/ownership.ts';
-import { performManagedSync } from '../src/core/persistence/sync-run.ts';
-import { __setManagedCursorKeyForTests } from '../src/core/persistence/sync-cursor-key.ts';
-import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
-import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
-import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
-import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
-import { withEnv } from './helpers/with-env.ts';
-import { SYNC_IMPORT_PROVENANCE_OP } from '../src/core/persistence/sync-holds.ts';
-
-// #5522: a commit-driven cursor and a --working-tree cursor of one source used
-// different cursor keys. When the working-tree run imports a file the sliced
-// commit-driven run froze as new (pageId null), resuming the commit-driven run
-// used to refuse with page_identity_changed on every run.
-//
-// #6712 PR 1: a source has one cursor key, so a working-tree run resumes the commit
-// cursor instead of overtaking it. Two such cursors now exist only when an older
-// gbrain left them; these tests create them under older keys (`legacy`) and resume
-// with the current key, which adopts the commit cursor (made the newest) in place
-// and supersedes the finished or idle working-tree one. The #5522 invariants hold
-// for the adopted cursor.
-
-const home = mkdtempSync(join(tmpdir(), 'gbrain-5522-'));
-const engines: BrainEngine[] = [];
-let closePostgres: (() => Promise<void>) | undefined;
-const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SOURCE: undefined, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
-const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
-const commit = (root: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'content'); };
-beforeAll(async () => {
- const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
- if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }
-}, 120_000);
-afterAll(async () => {
- await withEnv(env, async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } });
- await closePostgres?.(); rmSync(home, { recursive: true, force: true });
-});
-const park = (engine: BrainEngine, key: string, op: string) =>
- engine.executeRaw("UPDATE op_checkpoints SET op=$2 WHERE fingerprint=$1 AND op IN ('managed-sync','managed-sync-parked')", [key, op]);
-/**
- * Runs `fn` as an older gbrain whose cursor key for this source is `key`. An older gbrain never saw the other old-key
- * cursor (`hide`), so it is parked meanwhile: the current resolver would adopt it.
- */
-async function legacy<T>(engine: BrainEngine, key: string, fn: () => Promise<T>, hide?: string): Promise<T> {
- __setManagedCursorKeyForTests(() => key);
- if (hide) await park(engine, hide, 'managed-sync-parked');
- try { return await fn(); } finally {
- __setManagedCursorKeyForTests(null);
- if (hide) await park(engine, hide, 'managed-sync');
- }
-}
-/** Makes the commit-driven cursor the newest unfinished one, so the current key adopts it. */
-const ageWorking = (engine: BrainEngine, id: string) =>
- engine.executeRaw("UPDATE op_checkpoints SET updated_at=now()-interval '1 hour' WHERE op='managed-sync' AND fingerprint=$1", [`${id}-working`]);
-const each = (fn: (engine: BrainEngine) => Promise<void>) => withEnv(env, async () => { for (const engine of engines) await fn(engine); });
-
-async function fixture(engine: BrainEngine, names: string[]) {
- const id = `s-${randomUUID().slice(0, 12)}`, root = join(home, id);
- mkdirSync(root); git(root, 'init', '-q');
- for (const name of names) writeFileSync(join(root, `${name}.md`), `---\ntitle: ${name}\n---\nObservation ${name} for the sliced run.\n`);
- commit(root);
- await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
- await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);
- await claimWorktree(engine, id, root);
- await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
- const base = { sourceId: id, noPull: true, noEmbed: true, noExtract: true };
- return { id, root, base, working: { ...base, workingTree: true } };
-}
-const imports = async (engine: BrainEngine, id: string) =>
- (await engine.executeRaw<{ slug: string }>("SELECT slug FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import' ORDER BY sequence", [id])).map(r => r.slug);
-const lastCommit = async (engine: BrainEngine, id: string) =>
- (await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [id]))[0].last_commit;
-
-test('#5522 a commit-driven resume overtaken by a working-tree import of the same files completes without admitting them again', async () => each(async engine => {
- const f = await fixture(engine, ['a', 'b', 'c']);
- expect(await legacy(engine, `${f.id}-commit`, () => performManagedSync(engine, f.base, { maxPages: 1, maxMs: 60_000 }))).toMatchObject({ status: 'partial', reason: 'writer_yield', filesImported: 1 });
- expect((await legacy(engine, `${f.id}-working`, () => performManagedSync(engine, f.working), `${f.id}-commit`)).status).toBe('first_sync');
- expect(await imports(engine, f.id)).toEqual(['a', 'b', 'c']);
- expect(await performManagedSync(engine, f.base)).toMatchObject({ status: 'first_sync', filesImported: 3, cursorFanIn: { adopted: true } });
- expect(await imports(engine, f.id)).toEqual(['a', 'b', 'c']);
- expect(await lastCommit(engine, f.id)).toBe(git(f.root, 'rev-parse', 'HEAD'));
- expect((await performManagedSync(engine, f.base)).status).toBe('up_to_date');
-}), 180_000);
-
-test('#5522 a resume mixing files another cursor imported and files it did not commits its checkpoint', async () => each(async engine => {
- const f = await fixture(engine, ['a', 'b', 'c']);
- await legacy(engine, `${f.id}-commit`, () => performManagedSync(engine, f.base, { maxPages: 1, maxMs: 60_000 }));
- // The working-tree run imports b and yields before c, so it never checkpoints.
- expect(await legacy(engine, `${f.id}-working`, () => performManagedSync(engine, f.working, { maxPages: 2, maxMs: 60_000 }), `${f.id}-commit`)).toMatchObject({ status: 'partial', reason: 'writer_yield' });
- expect(await imports(engine, f.id)).toEqual(['a', 'b']);
- await ageWorking(engine, f.id);
- expect(await performManagedSync(engine, f.base)).toMatchObject({ status: 'first_sync', added: 2, cursorFanIn: { adopted: true, superseded: 1 } });
- expect(await imports(engine, f.id)).toEqual(['a', 'b', 'c']);
- expect(await lastCommit(engine, f.id)).toBe(git(f.root, 'rev-parse', 'HEAD'));
-}), 180_000);
-
-// #6340: the refusals below are holds now (`concurrent_write`); the invariant they protect, that the foreign write is never overwritten, is unchanged.
-test('#5522 a foreign write to the page at that origin holds the entry on resume and is never overwritten', async () => each(async engine => {
- const f = await fixture(engine, ['a', 'b', 'c']);
- await legacy(engine, `${f.id}-commit`, () => performManagedSync(engine, f.base, { maxPages: 1, maxMs: 60_000 }));
- await legacy(engine, `${f.id}-working`, () => performManagedSync(engine, f.working), `${f.id}-commit`);
- await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.executeRaw(
- "UPDATE pages SET compiled_truth='A foreign edit after the working-tree import.',content_hash='foreign' WHERE source_id=$1 AND slug='b'", [f.id]), TEST_WRITE_ATTRIBUTION));
- const resumed = await performManagedSync(engine, f.base);
- expect(resumed.status).not.toBe('blocked_by_failures');
- expect(resumed.held?.map(hold => [hold.path, hold.code])).toEqual([['b.md', 'concurrent_write']]);
- expect(await imports(engine, f.id)).toEqual(['a', 'b', 'c']);
- expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toBe('A foreign edit after the working-tree import.');
-}), 180_000);
-
-test('#5522 a page soft-deleted at that origin, or a pinned page deleted and recreated with the same text, is held', async () => each(async engine => {
- const deleted = await fixture(engine, ['a', 'b']);
- await legacy(engine, `${deleted.id}-commit`, () => performManagedSync(engine, deleted.base, { maxPages: 1, maxMs: 60_000 }));
- await legacy(engine, `${deleted.id}-working`, () => performManagedSync(engine, deleted.working), `${deleted.id}-commit`);
- await engine.transaction(tx => withCoordinatedWrite(tx, [deleted.id], () => tx.softDeletePage('b', { sourceId: deleted.id }), TEST_WRITE_ATTRIBUTION));
- const held = await performManagedSync(engine, deleted.base);
- expect(held.status).not.toBe('blocked_by_failures');
- expect(held.held?.map(hold => [hold.path, hold.code])).toEqual([['b.md', 'concurrent_write']]);
- expect(await engine.getPage('b', { sourceId: deleted.id })).toBeNull();
-
- // An entry enumerated against an existing page keeps its pinned identity.
- const pinned = await fixture(engine, ['a', 'b']);
- await performManagedSync(engine, pinned.base);
- for (const name of ['a', 'b']) writeFileSync(join(pinned.root, `${name}.md`), `---\ntitle: ${name}\n---\nRevised observation ${name}.\n`);
- commit(pinned.root);
- await legacy(engine, `${pinned.id}-commit`, () => performManagedSync(engine, pinned.base, { maxPages: 1, maxMs: 60_000 }));
- const before = await engine.getPage('b', { sourceId: pinned.id });
- await engine.transaction(tx => withCoordinatedWrite(tx, [pinned.id], () => tx.softDeletePage('b', { sourceId: pinned.id }), TEST_WRITE_ATTRIBUTION));
- // The older gbrain recorded no import provenance, so its working-tree run recreates the page (#6712 holds it when a record
- // shows the database side moved).
- await engine.executeRaw("DELETE FROM op_checkpoints WHERE op=$1 AND completed_keys->0->>'page_id'=$2", [SYNC_IMPORT_PROVENANCE_OP, String(before!.id)]);
- await legacy(engine, `${pinned.id}-working`, () => performManagedSync(engine, pinned.working), `${pinned.id}-commit`);
- const after = await engine.getPage('b', { sourceId: pinned.id });
- expect(after?.compiled_truth).toContain('Revised observation b');
- expect(after?.id !== before?.id || after?.updated_at !== before?.updated_at).toBe(true);
- // The recreated page holds exactly what the pinned entry would import: it is re-bound and passed, nothing is rewritten,
- // and the checkpoint accepts the target the working-tree run already reached.
- const resumed = await performManagedSync(engine, pinned.base);
- expect(resumed).toMatchObject({ status: 'synced', waived: { imports: 1, deletes: 0 } });
- expect(resumed.held ?? []).toEqual([]);
- expect((await engine.getPage('b', { sourceId: pinned.id }))?.updated_at).toEqual(after?.updated_at);
-}), 180_000);
diff --git a/test/sync-pass-handover-6712.test.ts b/test/sync-pass-handover-6712.test.ts
new file mode 100644
index 0000000000..03799c4d73
--- /dev/null
+++ b/test/sync-pass-handover-6712.test.ts
@@ -0,0 +1,182 @@
+/**
+ * #6712 PR 4b lane C: what the cursor adoption tests protected, on the live pass (design v3.2 §3.5, §3.6).
+ *
+ * A non-company source no longer keeps a cursor to adopt, so these replace persistence-sync-cursor-adoption.test.ts and
+ * the fan-in half of persistence-sync-cursor-strategy-6696.test.ts. Protects:
+ * - every request a pass admits carries the authority of the writer that admitted it, when several local writers run
+ * the passes of one source in turn;
+ * - a revoked writer's pass is refused and admits nothing; another writer's pass converges;
+ * - the legacy handover (`retireLegacyCursors`): a pass waits (`writer_pending`, naming the request) while a request under
+ * an older binary's unfinished cursor is running, then retires it and converges; a remote job retires nothing and
+ * names the brain host (`reconcile_host_required`), leaving every cursor row and request as it was; a pass killed
+ * right after it superseded an older cursor leaves that cursor retired, and the next pass converges.
+ * Synthetic content only.
+ */
+import { afterAll, afterEach, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { SyncOpts } from '../src/commands/sync.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { resolveManagedSyncContext } from '../src/core/persistence/sync-discovery.ts';
+import { managedSyncAuthority } from '../src/core/persistence/sync-authority.ts';
+import { syncCursorOptions } from '../src/core/persistence/sync-slices.ts';
+import { prepareRemoteJob, withSubmissionAuthority } from '../src/core/minions/submission-authority.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-pass-handover-'));
+const homes = { a: join(home, 'writer-a'), b: join(home, 'writer-b'), c: join(home, 'writer-c') };
+let engine: PGLiteEngine;
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+beforeAll(async () => {
+ for (const dir of Object.values(homes)) mkdirSync(dir, { recursive: true });
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+}, 120_000);
+afterEach(() => installFaultHook(undefined));
+afterAll(async () => {
+ await withEnv({ GBRAIN_HOME: homes.a }, async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });
+ rmSync(home, { recursive: true, force: true });
+});
+const NAMES = ['a', 'b', 'c', 'd'];
+async function fixture() {
+ const id = `handover-${randomUUID().slice(0, 12)}`, root = join(home, id);
+ mkdirSync(root); git(root, 'init', '-q');
+ for (const name of NAMES) writeFileSync(join(root, `${name}.md`), `---\ntitle: ${name}\n---\nA durable observation named ${name} at acme-example.\n`);
+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'seed');
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return { id, root };
+}
+const env = { OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+/** Each writer is its own local CLI registration on the same host: the host identity is shared, the registration is not. */
+function shareHost(writer: keyof typeof homes): void {
+ const from = join(homes.a, '.gbrain', 'persistence', 'host.json'), dir = join(homes[writer], '.gbrain', 'persistence');
+ if (writer === 'a' || !existsSync(from)) return;
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
+ if (!existsSync(join(dir, 'host.json'))) { copyFileSync(from, join(dir, 'host.json')); chmodSync(join(dir, 'host.json'), 0o600); }
+}
+const as = <T>(writer: keyof typeof homes, fn: () => Promise<T>) => { shareHost(writer); return withEnv({ GBRAIN_HOME: homes[writer], ...env }, fn); };
+const opts = (sourceId: string): SyncOpts => ({ sourceId, noPull: true, noEmbed: true, noExtract: true });
+const requests = async (id: string) => engine.executeRaw<{ request_id: string; principal_id: string; kind: string; state: string; writer: string | null }>(
+ `SELECT request_id::text AS request_id, principal_id, intent->>'kind' AS kind, state, intent->'syncAuthority'->'writer'->'principal'->>'id' AS writer
+ FROM persistence_requests WHERE source_id=$1 ORDER BY sequence`, [id]);
+const cursorRows = async (id: string) => (await engine.executeRaw<{ key: string }>(
+ "SELECT fingerprint AS key FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1 ORDER BY fingerprint", [id])).map(row => row.key);
+const livePages = async (id: string) => (await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL ORDER BY slug', [id])).map(row => row.slug);
+const minutesAgo = (n: number) => new Date(Date.now() - n * 60_000).toISOString();
+
+/** An unfinished cursor (and its manifest) an older binary left under `key` for the source, admitting nothing yet. */
+async function legacyCursor(id: string, root: string, key: string, ageMinutes: number) {
+ const incarnation = (await engine.executeRaw<{ i: string }>('SELECT incarnation::text AS i FROM sources WHERE id=$1', [id]))[0]!.i;
+ const context = await resolveManagedSyncContext(engine, opts(id) as never);
+ const authority = await managedSyncAuthority(engine, id, incarnation, root);
+ const entries = NAMES.map(name => ({ path: `${name}.md`, sourcePath: `${name}.md`, action: 'import', working: false, slug: name, pageId: null, revision: null }));
+ const binding = { ...context.binding, owner_epoch: String((context.binding as { owner_epoch?: unknown }).owner_epoch), topology_generation: String(context.binding.topology_generation) };
+ const runId = `run-${key}`;
+ const cursor = { binding, root: context.root, gitRoot: context.gitRoot, sourceId: id, incarnation, from: null, target: git(root, 'rev-parse', 'HEAD'), slugMode: 'git-root',
+ discoveredAt: minutesAgo(ageMinutes), runId, index: 0, total: entries.length, authority, processingOptions: { noEmbed: true, noExtract: true, noSchemaPack: false },
+ syncOptions: syncCursorOptions(opts(id)), counts: { added: 0, modified: 0, deleted: 0, chunks: 0 } };
+ await engine.executeRaw('INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,$3::text::jsonb,$4::timestamptz)',
+ ['managed-sync', key, JSON.stringify([cursor]), minutesAgo(ageMinutes)]);
+ await engine.executeRaw('INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,$3::text::jsonb,$4::timestamptz)',
+ ['managed-sync-manifest', runId, JSON.stringify(entries), minutesAgo(ageMinutes)]);
+ return { incarnation, runId };
+}
+
+test('every request a pass admits carries the authority of the writer that admitted it, across writers taking turns', async () => as('a', async () => {
+ const { id } = await fixture();
+ expect(await as('a', () => performManagedSync(engine, opts(id), { maxPages: 1, maxMs: 1000 }))).toMatchObject({ status: 'partial' });
+ expect((await as('b', () => performManagedSync(engine, opts(id), { maxPages: 1, maxMs: 1000 }))).status).toBe('partial');
+ expect((await as('c', () => performManagedSync(engine, opts(id)))).status).toBe('first_sync');
+ const rows = await requests(id);
+ expect(new Set(rows.map(row => row.request_id)).size).toBe(rows.length);
+ expect(rows.filter(row => row.kind === 'managed_sync_import').every(row => row.state === 'committed')).toBe(true);
+ for (const row of rows.filter(row => row.writer !== null)) expect(row.principal_id).toBe(row.writer!);
+ expect(new Set(rows.filter(row => row.kind === 'managed_sync_import').map(row => row.principal_id)).size).toBe(3);
+ expect(await livePages(id)).toEqual(NAMES);
+}), 180_000);
+
+test('a revoked writer\'s pass is refused and admits nothing; another writer\'s pass converges', async () => as('a', async () => {
+ const { id } = await fixture();
+ expect(await as('b', () => performManagedSync(engine, opts(id), { maxPages: 1, maxMs: 1000 }))).toMatchObject({ status: 'partial' });
+ const revoked = (await requests(id))[0]!.principal_id;
+ await engine.executeRaw('UPDATE persistence_local_writers SET revoked_at=now() WHERE id=$1::uuid', [revoked]);
+ const before = (await requests(id)).filter(row => row.principal_id === revoked);
+ expect(before.length).toBeGreaterThan(0);
+ const refused = await as('b', () => performManagedSync(engine, opts(id))).then(() => null, (error: unknown) => error);
+ expect(refused).toMatchObject({ code: 'permission_denied' });
+ expect((await requests(id)).filter(row => row.principal_id === revoked)).toEqual(before);
+ expect((await as('c', () => performManagedSync(engine, opts(id)))).status).toBe('first_sync');
+ expect((await requests(id)).filter(row => row.principal_id === revoked)).toEqual(before);
+ expect(await livePages(id)).toEqual(NAMES);
+}), 180_000);
+
+test('a request still running under an older binary\'s unfinished cursor keeps the pass waiting; once it settles the pass retires the cursor and converges', async () => as('a', async () => {
+ const { id, root } = await fixture();
+ const key = `legacy-running-${id}`;
+ const { incarnation, runId } = await legacyCursor(id, root, key, 60);
+ const requestId = randomUUID();
+ await engine.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,authority,intent_bytes,terminal_reservation,
+ state,intent,updated_at,admitter_version)
+ VALUES('local_cli','fixture',$1::uuid,'submit_job',$2,$3::uuid,'a',$4,'{}'::jsonb,0,0,'running',$5::text::jsonb,now(),'0.60.262.0')`,
+ [requestId, id, incarnation, randomUUID(), JSON.stringify({ kind: 'managed_sync_import', cursorKey: key, runId, index: 0 })]);
+ const waited = await performManagedSync(engine, opts(id));
+ expect(waited).toMatchObject({ status: 'partial', reason: 'writer_pending', retryWait: { request_id: requestId, state: 'running' } });
+ expect(await cursorRows(id)).toEqual([key]);
+ expect(await livePages(id)).toEqual([]);
+ await engine.executeRaw("UPDATE persistence_requests SET state='committed', completed_at=now() WHERE request_id=$1::uuid", [requestId]);
+ const converged = await performManagedSync(engine, opts(id));
+ expect(converged.status).toBe('first_sync');
+ expect(await cursorRows(id)).toEqual([]);
+ expect(await livePages(id)).toEqual(NAMES);
+}), 180_000);
+
+test('a remote job retires no unfinished local cursor: it names the brain host, every cursor row and request stays, and the host CLI then converges', async () => as('a', async () => {
+ const { id, root } = await fixture();
+ const newest = `legacy-newest-${id}`, older = `legacy-older-${id}`;
+ await legacyCursor(id, root, older, 60);
+ await legacyCursor(id, root, newest, 10);
+ const before = { cursors: await cursorRows(id), requests: await requests(id) };
+ expect(before.cursors).toEqual([newest, older].sort());
+ const clientId = `handover-client-${randomUUID()}`;
+ await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_name,client_secret_hash,scope,source_id,allowed_operations)
+ VALUES($1,'example-client','test-only','admin',$2,ARRAY['submit_job'])`, [clientId, id]);
+ try {
+ const ctx = { engine, remote: true, sourceId: id, auth: { clientId, principal: { kind: 'oauth_client', id: clientId }, scopes: ['admin'], sourceId: id,
+ allowedOperations: ['submit_job'] } } as unknown as OperationContext;
+ const accepted = await prepareRemoteJob(ctx, 'sync', { noPull: true });
+ const remote = await withSubmissionAuthority(accepted.authority, () => performManagedSync(engine, { ...accepted.data } as SyncOpts));
+ expect({ status: remote.status, reason: remote.reason ?? null }).toEqual({ status: 'blocked_by_failures', reason: 'reconcile_host_required' });
+ } finally { await engine.executeRaw('DELETE FROM oauth_clients WHERE client_id=$1', [clientId]); }
+ expect({ cursors: await cursorRows(id), requests: await requests(id) }).toEqual(before);
+ expect(await livePages(id)).toEqual([]);
+ expect((await performManagedSync(engine, opts(id))).status).toBe('first_sync');
+ expect(await cursorRows(id)).toEqual([]);
+ expect(await livePages(id)).toEqual(NAMES);
+}), 180_000);
+
+test('a pass killed right after it superseded an older cursor leaves that cursor retired, and the next pass converges', async () => as('a', async () => {
+ const { id, root } = await fixture();
+ const newest = `legacy-newest-${id}`, older = `legacy-older-${id}`;
+ await legacyCursor(id, root, older, 60);
+ await legacyCursor(id, root, newest, 10);
+ installFaultHook(async (point, detail) => { if (point === 'sync:cursor_adopted' && detail.sourceId === id) throw new Error('killed after the supersede'); });
+ await expect(performManagedSync(engine, opts(id))).rejects.toThrow('killed after the supersede');
+ installFaultHook(undefined);
+ expect(await cursorRows(id)).toEqual([newest]);
+ expect(await livePages(id)).toEqual([]);
+ expect((await performManagedSync(engine, opts(id))).status).toBe('first_sync');
+ expect(await cursorRows(id)).toEqual([]);
+ expect(await livePages(id)).toEqual(NAMES);
+}), 180_000);