Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
sync: one cursor key per source with crash-safe fan-in (#6712 PR 1)
garrytan6af9de3d8255
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.tsindex dca7e94adf..7d5a4870b2 100644--- a/src/core/persistence/fault-points.ts+++ b/src/core/persistence/fault-points.ts@@ -18,8 +18,8 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect| 'consumer:preparing' | 'lane:applied'// #6712 PR 0: after `freezeEntry` froze an import entry (its bytes are read) and before the request is admitted or published.| 'sync:after_freeze'- // #6712 PR 1: after a pass took the source's drain lease (before it reads the cursor), and after the cursor fan-in adopted- // an old-key cursor under the source's one key (before the old rows are retired).+ // #6712 PR 1: after a pass took the source's drain lease (before it reads the cursor); after each cursor the fan-in+ // superseded is retired (before the next one), and after a pass stamped its authority on a cursor another writer started.| 'sync:lease_acquired' | 'sync:cursor_adopted'// #6511: the page purge's in-transaction journal lookups (page-purge.ts `journalLookup`); a hook that throws a 57014 models a statement timeout there.| 'purge:slug_lookup' | 'purge:tail_recheck' | 'purge:pending_recheck' | 'purge:redaction_read'diff --git a/src/core/persistence/managed-sync-orphans.ts b/src/core/persistence/managed-sync-orphans.tsindex 1ddf8ef790..1d1d2a3d73 100644--- a/src/core/persistence/managed-sync-orphans.ts+++ b/src/core/persistence/managed-sync-orphans.ts@@ -38,7 +38,8 @@ import type { BrainEngine } from '../engine.ts';import type { SqlEngine } from './model.ts';import { clearManagedSyncFailure, loadSyncFailures } from '../sync-failure-ledger.ts';-export type ManagedSyncOrphanReason = 'no_cursor' | 'principal_unadoptable' | 'superseded' | 'incarnation_retired' | 'mirror_only';+/** `superseded_by_adoption` (#6712 PR 1): an unfinished cursor of the incarnation that the drain's fan-in did not adopt (sync-cursor-key.ts). */+export type ManagedSyncOrphanReason = 'no_cursor' | 'principal_unadoptable' | 'superseded' | 'incarnation_retired' | 'mirror_only' | 'superseded_by_adoption';export type ManagedSyncOrphanRetained = 'pending_request_live' | 'resumable';export interface ManagedSyncOrphan {@@ -201,9 +202,15 @@ export async function pruneMirrorOnlyManagedFailures(engine: SqlEngine, sourceId* still active under a different incarnation at apply time; the live-writer* veto below is for a cursor the live writer could still resume, which no* retired key can be, so it does not apply. The live pending-request guard does.+ *+ * #6712 PR 1: a `superseded_by_adoption` cursor is one the drain's fan-in passed over for the incarnation's adopted+ * cursor; it is deleted only while no request admitted under its key is still open or carries recovery, and `inTx`+ * (the drain lease's fence) runs first in the same transaction.*/-export async function retireManagedSyncOrphan(engine: BrainEngine, orphan: Pick<ManagedSyncOrphan, 'kind' | 'cursor_key' | 'run_id' | 'source_id' | 'source_incarnation' | 'reason'>): Promise<{ cursor: boolean; failure: boolean; manifest: boolean; mirror: boolean }> {+export async function retireManagedSyncOrphan(engine: BrainEngine, orphan: Pick<ManagedSyncOrphan, 'kind' | 'cursor_key' | 'run_id' | 'source_id' | 'source_incarnation' | 'reason'>,+ inTx?: (tx: BrainEngine) => Promise<void>): Promise<{ cursor: boolean; failure: boolean; manifest: boolean; mirror: boolean }> {const retired = orphan.reason === 'incarnation_retired';+ const mode = retired ? 'retired' : orphan.reason === 'superseded_by_adoption' ? 'adoption' : 'orphan';if (orphan.kind === 'mirror_row') {const durable = await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1", [orphan.cursor_key]);if (durable.length) return { cursor: false, failure: false, manifest: false, mirror: false };@@ -211,6 +218,7 @@ export async function retireManagedSyncOrphan(engine: BrainEngine, orphan: Pick<}const removed = await engine.transaction(async tx => {await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','2000ms',true)");+ await inTx?.(tx);let cursor = false;if (orphan.kind === 'unfinished_cursor') {const rows = await tx.executeRaw(`@@ -219,12 +227,14 @@ export async function retireManagedSyncOrphan(engine: BrainEngine, orphan: Pick<AND c.completed_keys->0->>'sourceId'=$2 AND c.completed_keys->0->>'incarnation'=$3AND NOT EXISTS(SELECT 1 FROM persistence_requests r WHERE r.request_id=(c.completed_keys->0->'pending'->>'requestId')::uuidAND r.source_id=$2 AND r.state NOT IN ('committed','failed','conflict','cancelled'))- AND ($4::boolean AND EXISTS(SELECT 1 FROM sources s WHERE s.id=$2 AND NOT COALESCE(s.archived,false) AND s.incarnation::text<>$3)- OR NOT $4::boolean AND NOT EXISTS(SELECT 1 FROM persistence_local_writers w WHERE w.revoked_at IS NULL+ AND ($4::text='retired' AND EXISTS(SELECT 1 FROM sources s WHERE s.id=$2 AND NOT COALESCE(s.archived,false) AND s.incarnation::text<>$3)+ OR $4::text='adoption' AND NOT EXISTS(SELECT 1 FROM persistence_requests r WHERE r.source_id=$2 AND r.intent->>'cursorKey'=$1+ AND (r.state IN ('queued','running','recovering') OR r.recovery IS NOT NULL))+ OR $4::text='orphan' AND NOT EXISTS(SELECT 1 FROM persistence_local_writers w WHERE w.revoked_at IS NULLAND w.id::text=c.completed_keys->0->'authority'->'writer'->'principal'->>'id'AND c.completed_keys->0->'authority'->'writer'->'principal'->>'kind' IN ('local_cli','local_stdio')AND (c.completed_keys->0 ? 'syncOptions')))- RETURNING fingerprint`, [orphan.cursor_key, orphan.source_id, orphan.source_incarnation, retired]);+ RETURNING fingerprint`, [orphan.cursor_key, orphan.source_id, orphan.source_incarnation, mode]);cursor = rows.length > 0;if (!cursor) return { cursor: false, failure: false, manifest: false, mirror: false };}diff --git a/src/core/persistence/sync-cursor-key.ts b/src/core/persistence/sync-cursor-key.tsindex be51d59f5a..f4561a0f9b 100644--- a/src/core/persistence/sync-cursor-key.ts+++ b/src/core/persistence/sync-cursor-key.ts@@ -1,42 +1,134 @@/**- * The durable cursor key of a managed sync run, and the one boundary that picks it (#6696 C1).+ * #6712 PR 1: one managed cursor per source incarnation (and company approval), whoever runs the sync.*- * The key digests the source incarnation, the writer principal and authority, a company approval and the run's- * cursor-selecting options (`syncCursorOptions`). `sync --all` passes a source's configured strategy while a- * single-source CLI run, the cycle, a serve-delegated run and a sync job pass none, so one source used to get two keys:- * two unfinished cursors that could not resume each other. `selectManagedCursor` runs inside `runManagedSync` (every- * managed caller crosses it) and `managedSyncCursorKey`: a run without `--strategy` selects its cursor with the- * configured strategy, for fresh cursors only. When an unfinished cursor is held under the key the run's raw options- * select (written before this rule, or before the strategy was configured), the run resumes it under that key, so the- * requests it already admitted (their `intent.cursorKey`) keep matching their cursor.+ * The key used to digest the writer principal, its authority and the run's cursor-selecting options, so a CLI run, a+ * sync job, `sync --all` and a serve-delegated run of one source each held their own unfinished cursor and none could+ * resume another's (#5632, #6696). It is now `managedCursorKey(incarnation, company)`.+ *+ * `resolveManagedCursor` folds in the cursors written under an older key (`legacyManagedCursorKey`). It runs under the+ * drain lease, before the pass reads its cursor, and every write it makes checks the lease's fence:+ * - The incarnation's unfinished cursor under the current key wins; otherwise the newest unfinished one under an older+ * key is adopted and finished in place, under its own key and frozen manifest. The requests it admitted name that+ * key (`intent.cursorKey`) and the publication fence reads the row by it, so the row never moves and no admitted+ * payload is rewritten. The next run after it finishes discovers under the current key.+ * - Every other unfinished cursor is superseded: its still-queued requests are cancelled (never one that started+ * publishing or carries recovery), then it is retired through the orphan repair path (`retireManagedSyncOrphan`,+ * reason `superseded_by_adoption`) with its failure row, and its manifest when no cursor shares it. A cursor with a+ * running or recovering request, or a recovery row, under its key is left in place and the pass waits for it+ * (`writer_pending`, `waitFor`) before it drains anything: recovery is never suppressed, and the adopted run never+ * publishes a page beside a superseded run's in-flight write.+ * - A finished cursor under an older key is retired (a company brain keeps its finished cursors: each records the+ * approval it synced).+ * Each step commits on its own and repeats safely. Only the lease holder writes cursors, so the newest unfinished cursor+ * stays the newest and a crash anywhere in the fan-in leaves a state the next pass folds the same way.*/-import type { SyncOpts } from '../../commands/sync.ts';import type { BrainEngine } from '../engine.ts';import type { currentCompanyBrainSync } from '../company-brain/profile.ts';import { digest } from './digest.ts';+import { completeWrite, lockCounters } from './journal.ts';+import { retireManagedSyncOrphan } from './managed-sync-orphans.ts';+import { isTerminal, principalKey, requestPrincipal, type WriteRequest } from './model.ts';import type { SyncAuthority } from './sync-authority.ts';-import type { ManagedSyncContext } from './sync-discovery.ts';+import { clearManagedSyncFailureAfterSuccess } from './sync-failures.ts';+import { assertDrainLease } from './sync-lease.ts';+import { faultPoint } from './fault-points.ts';import type { SyncCursorOptions } from './sync-prepare.ts';-import { syncCursorOptions } from './sync-slices.ts';type CompanySync = ReturnType<typeof currentCompanyBrainSync>;-export function managedCursorKey(incarnation: string, authority: SyncAuthority, company: CompanySync, syncOptions: SyncCursorOptions): string {- return digest({ source: incarnation, principal: authority.writer.principal, authority, ...(company ? { company: { receiptId: company.receiptId, planDigest: company.plan.plan_digest } } : {}),- options: syncOptions });+const companyPart = (company: CompanySync) => company ? { company: { receiptId: company.receiptId, planDigest: company.plan.plan_digest } } : {};++let keyForTests: ((incarnation: string) => string) | null = null;+/** Tests only: the key fresh cursors are written under, to build a cursor an older binary keyed differently. */+export function __setManagedCursorKeyForTests(key: ((incarnation: string) => string) | null): void { keyForTests = key; }++/** The key of the source incarnation's managed cursor (and of its company approval, on a company brain). */+export function managedCursorKey(incarnation: string, company: CompanySync): string {+ return keyForTests?.(incarnation) ?? digest({ source: incarnation, ...companyPart(company) });}-/** The options, cursor-selecting options and key a managed run uses; `opts.strategy` is the configured one when the key was normalized. */-export async function selectManagedCursor(engine: Pick<BrainEngine, 'executeRaw'>, input: { opts: SyncOpts; context: Pick<ManagedSyncContext, 'incarnation' | 'source'>;- authority: SyncAuthority; company: CompanySync }): Promise<{ opts: SyncOpts; syncOptions: SyncCursorOptions; key: string }> {- const { opts, context, authority, company } = input;- const raw = syncCursorOptions(opts);- const rawKey = managedCursorKey(context.incarnation, authority, company, raw);- const configured = context.source.config?.strategy;- if (company || opts.strategy || typeof configured !== 'string' || !configured) return { opts, syncOptions: raw, key: rawKey };- const live = await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 AND COALESCE(completed_keys->0->>'done','false')<>'true'", [rawKey]);- if (live.length) return { opts, syncOptions: raw, key: rawKey };- const normalized = { ...opts, strategy: configured as SyncOpts['strategy'] };- const syncOptions = syncCursorOptions(normalized);- return { opts: normalized, syncOptions, key: managedCursorKey(context.incarnation, authority, company, syncOptions) };+/** The key a cursor was written under before #6712 PR 1. Read-only: it names the options of an older failure row. */+export function legacyManagedCursorKey(incarnation: string, authority: SyncAuthority, company: CompanySync, syncOptions: SyncCursorOptions): string {+ return digest({ source: incarnation, principal: authority.writer.principal, authority, ...companyPart(company), options: syncOptions });+}++export const SUPERSEDED_BY_ADOPTION_MESSAGE = 'Another unfinished sync run of this source was adopted; this queued page of a superseded run was not published, and the adopted run (or the next sync) imports it.';++export interface CursorResolution {+ /** The key of the cursor this pass reads, resumes or creates. */+ key: string;+ /** Set when the pass finishes a cursor written under an older key, in place. */+ adoptedLegacyKey?: string;+ /** Older-key cursors retired by this pass, and those left for later because a request under them is still open. */+ superseded: string[];+ retained: string[];+ /** The first open request under a retained cursor: the pass waits for it to settle. */+ waitFor?: { request_id: string; kind: string | null; slug: string; state: string; recovery: boolean };+}++interface CursorRow { key: string; done: boolean; company_receipt_id: string | null; run_id: string | null }++/** Picks the cursor a pass uses and folds in the others (module header); `readOnly` (a dry run) only picks. */+export async function resolveManagedCursor(engine: BrainEngine, input: { sourceId: string; incarnation: string; company: CompanySync; assertActive: () => void;+ readOnly?: boolean }): Promise<CursorResolution> {+ const { sourceId, incarnation, company, assertActive } = input;+ const canonical = managedCursorKey(incarnation, company);+ const rows = (await engine.executeRaw<CursorRow>(`SELECT fingerprint AS key, COALESCE(completed_keys->0->>'done','false')='true' AS done,+ completed_keys->0->>'companyReceiptId' AS company_receipt_id, completed_keys->0->>'runId' AS run_id+ FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1 AND completed_keys->0->>'incarnation'=$2+ ORDER BY updated_at DESC, fingerprint COLLATE "C"`, [sourceId, incarnation])).filter(row => (row.company_receipt_id ?? null) === (company?.receiptId ?? null));+ assertActive();+ const unfinished = rows.filter(row => !row.done);+ const winner = unfinished.find(row => row.key === canonical) ?? unfinished[0] ?? (company ? rows.find(row => row.key === canonical) ?? rows[0] : undefined);+ const key = winner?.key ?? canonical;+ const resolution: CursorResolution = { key, ...(key !== canonical ? { adoptedLegacyKey: key } : {}), superseded: [], retained: [] };+ const fence = (tx: BrainEngine) => assertDrainLease(tx, sourceId);+ for (const row of input.readOnly ? [] : rows) {+ if (row.key === key || row.key === canonical && row.done) continue;+ if (row.done) {+ if (company) continue;+ await engine.transaction(async tx => {+ await fence(tx);+ await tx.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 AND COALESCE(completed_keys->0->>'done','false')='true'", [row.key]);+ });+ await clearManagedSyncFailureAfterSuccess(engine, row.key);+ } else {+ const open = await supersede(engine, row, { sourceId, incarnation, fence });+ if (open === null) {+ resolution.superseded.push(row.key);+ await faultPoint('sync:cursor_adopted', { sourceId });+ } else {+ resolution.retained.push(row.key);+ if (open !== 'kept') resolution.waitFor ??= { request_id: open.request_id, kind: (open.intent as { kind?: string } | null)?.kind ?? null, slug: open.slug,+ state: open.state, recovery: !!open.recovery };+ }+ }+ assertActive();+ }+ return resolution;+}++/**+ * Cancels the queued requests of a passed-over cursor, then retires it (null). While a request under it is running,+ * recovering or publishing, nothing is touched and that request is returned; `kept` when the retirement found it no+ * longer qualifies.+ */+async function supersede(engine: BrainEngine, row: CursorRow, input: { sourceId: string; incarnation: string; fence: (tx: BrainEngine) => Promise<void> }): Promise<WriteRequest | 'kept' | null> {+ const open = await engine.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'cursorKey'=$2+ AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) ORDER BY sequence`, [input.sourceId, row.key]);+ const busy = open.find(request => request.state !== 'queued' || request.recovery || request.publication_started);+ if (busy) return busy;+ // One row per transaction, as `cancelRows` does: holding several request rows at once deadlocks against claim renewals.+ for (const request of open) {+ await engine.transaction(async tx => {+ await lockCounters(tx, ['brain', principalKey(requestPrincipal(request)), ...(request.worktree_id ? [`worktree:${request.worktree_id}`] : [])]);+ await input.fence(tx);+ const [current] = await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid FOR UPDATE', [request.id]);+ if (!current || isTerminal(current) || current.execution_token !== request.execution_token || current.publication_started || current.recovery) return;+ await completeWrite(tx, current, 'cancelled', {}, { code: 'cancelled', message: SUPERSEDED_BY_ADOPTION_MESSAGE, detail: { superseded_cursor: row.key } });+ });+ }+ const retired = await retireManagedSyncOrphan(engine, { kind: 'unfinished_cursor', cursor_key: row.key, run_id: row.run_id, source_id: input.sourceId,+ source_incarnation: input.incarnation, reason: 'superseded_by_adoption' }, input.fence);+ return retired.cursor ? null : 'kept';}diff --git a/test/persistence-sync-cursor-adoption.test.ts b/test/persistence-sync-cursor-adoption.test.tsnew file mode 100644index 0000000000..2ccf0111d3--- /dev/null+++ b/test/persistence-sync-cursor-adoption.test.ts@@ -0,0 +1,220 @@+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('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.tsindex 446307d9af..26a04dc418 100644--- a/test/persistence-sync-cursor-strategy-6696.test.ts+++ b/test/persistence-sync-cursor-strategy-6696.test.ts@@ -8,19 +8,21 @@ 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 { managedSyncCursorKey, performManagedSync } from '../src/core/persistence/sync-run.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). Strategy normalization picks the configured strategy for a run without --strategy, for fresh cursors only: an-// unfinished cursor written under the old (un-normalized) key keeps resuming under that key, so the requests it already-// admitted (their intent.cursorKey) still match their cursor.+// 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.//-// Regression guarded: the normalization done in one caller only (the keys keep diverging), or applied to a live cursor-// (its queued requests are fenced out by the cursor they no longer match).+// 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).const home = mkdtempSync(join(tmpdir(), 'gbrain-cursor-strategy-'));const engines: BrainEngine[] = [];@@ -46,6 +48,7 @@ async function fixture(engine: BrainEngine, config: Record<string, unknown>) {await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');return id;}+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);});@@ -53,36 +56,47 @@ const cursors = async (engine: BrainEngine, id: string) => engine.executeRaw<{ k"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 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;// What each caller passes: the single-source CLI, the cycle and a delegated run pass no strategy; `sync --all` passes the configured one.-const single = (sourceId: string): SyncOpts => ({ sourceId, noPull: true, noEmbed: true, explicitProcessing: [] } as SyncOpts);+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 => {const id = await fixture(engine, { strategy: 'markdown' });- expect(await managedSyncCursorKey(engine, single(id))).toBe(await managedSyncCursorKey(engine, all(id)));expect(await performManagedSync(engine, single(id), { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });- expect((await performManagedSync(engine, all(id))).status).toBe('first_sync');- expect(await cursors(engine, id)).toEqual([expect.objectContaining({ strategy: 'markdown' })]);+ 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 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 refused(engine, id)).toBe(0);}), 120_000);-test('an unfinished cursor under the old key (no strategy) finishes under that key; the next fresh run is normalized', async () => isolated(async engine => {+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, {});- // A cursor written while the source had no strategy configured (the key an older binary computed for this source).expect(await performManagedSync(engine, single(id), { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });- const [legacy] = await cursors(engine, id);- expect(legacy).toMatchObject({ strategy: null });+ // 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]);- expect(await managedSyncCursorKey(engine, single(id))).toBe(legacy!.key);- expect((await performManagedSync(engine, single(id))).status).toBe('first_sync');- expect(await cursors(engine, id)).toEqual([{ key: legacy!.key, done: 'true', strategy: null }]);+ 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: a fresh run takes the normalized key, and `sync --all` agrees with it.- expect(await managedSyncCursorKey(engine, single(id))).not.toBe(legacy!.key);- expect(await managedSyncCursorKey(engine, single(id))).toBe(await managedSyncCursorKey(engine, all(id)));+ // 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 keeps its own key', async () => isolated(async engine => {+test('an explicit --strategy that differs from the configured one resumes the same cursor', async () => isolated(async engine => {const id = await fixture(engine, { strategy: 'markdown' });- expect(await managedSyncCursorKey(engine, { ...single(id), strategy: 'auto' })).not.toBe(await managedSyncCursorKey(engine, single(id)));+ 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);}), 120_000);diff --git a/test/persistence-sync-overtaken-cursor-5522.test.ts b/test/persistence-sync-overtaken-cursor-5522.test.tsindex 539d1d3dd4..02a3d3408c 100644--- a/test/persistence-sync-overtaken-cursor-5522.test.ts+++ b/test/persistence-sync-overtaken-cursor-5522.test.ts@@ -8,16 +8,24 @@ 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';-// #5522: a commit-driven cursor and a --working-tree cursor of one source use+// #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[] = [];@@ -33,6 +41,23 @@ 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[]) {@@ -44,7 +69,7 @@ async function fixture(engine: BrainEngine, names: string[]) {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, explicitProcessing: [] };+ 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) =>@@ -54,10 +79,10 @@ const lastCommit = async (engine: BrainEngine, id: string) =>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 performManagedSync(engine, f.base, { maxPages: 1, maxMs: 60_000 })).toMatchObject({ status: 'partial', reason: 'writer_yield', filesImported: 1 });- expect((await performManagedSync(engine, f.working)).status).toBe('first_sync');+ 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 });+ 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');@@ -65,11 +90,12 @@ test('#5522 a commit-driven resume overtaken by a working-tree import of the samtest('#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 performManagedSync(engine, f.base, { maxPages: 1, maxMs: 60_000 });+ 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 performManagedSync(engine, f.working, { maxPages: 2, maxMs: 60_000 })).toMatchObject({ status: 'partial', reason: 'writer_yield' });+ 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']);- expect(await performManagedSync(engine, f.base)).toMatchObject({ status: 'first_sync', added: 2 });+ 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);@@ -77,8 +103,8 @@ test('#5522 a resume mixing files another cursor imported and files it did not c// #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 performManagedSync(engine, f.base, { maxPages: 1, maxMs: 60_000 });- await performManagedSync(engine, f.working);+ 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);@@ -90,8 +116,8 @@ test('#5522 a foreign write to the page at that origin holds the entry on resumetest('#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 performManagedSync(engine, deleted.base, { maxPages: 1, maxMs: 60_000 });- await performManagedSync(engine, deleted.working);+ 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');@@ -103,10 +129,10 @@ test('#5522 a page soft-deleted at that origin, or a pinned page deleted and recawait 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 performManagedSync(engine, pinned.base, { maxPages: 1, maxMs: 60_000 });+ 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));- await performManagedSync(engine, pinned.working);+ 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);diff --git a/test/sync-knock-on-recovery-6643.test.ts b/test/sync-knock-on-recovery-6643.test.tsindex 869733a7ec..075241beb0 100644--- a/test/sync-knock-on-recovery-6643.test.ts+++ b/test/sync-knock-on-recovery-6643.test.ts@@ -17,6 +17,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { __setManagedCursorKeyForTests } from '../src/core/persistence/sync-cursor-key.ts';import { readSyncStatus } from '../src/core/persistence/sync-status.ts';import { classifySyncFault } from '../src/core/persistence/sync-fault-class.ts';import { readManagedSyncFailures } from '../src/core/persistence/sync-failures.ts';@@ -265,8 +266,17 @@ test('with two cursors, sync status shows the one its recorded failure belongs tconst f = await stoppedRun();const blockedRun = (await readSyncStatus(engine, f.id)).run_id!;await clearConfig();- // A newer cursor of the same source, selected by different options, runs to the end.- const other = await performManagedSync(engine, { ...f.opts, exclude: ['nothing-matches/**'] });+ // A newer cursor of the same source, selected by different options, runs to the end. #6712 PR 1: one key per source,+ // so a second cursor is one an older gbrain left under its own key; it ran while the blocked cursor did not exist for it.+ const blockedKey = (await engine.executeRaw<{ fingerprint: string }>("SELECT fingerprint FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.id]))[0]!.fingerprint;+ await engine.executeRaw("UPDATE op_checkpoints SET op='managed-sync-parked' WHERE op='managed-sync' AND fingerprint=$1", [blockedKey]);+ __setManagedCursorKeyForTests(() => `${f.id}-older-key`);+ let other: Awaited<ReturnType<typeof performManagedSync>>;+ try { other = await performManagedSync(engine, { ...f.opts, exclude: ['nothing-matches/**'] }); }+ finally {+ __setManagedCursorKeyForTests(null);+ await engine.executeRaw("UPDATE op_checkpoints SET op='managed-sync' WHERE op='managed-sync-parked' AND fingerprint=$1", [blockedKey]);+ }expect(other.status).not.toBe('blocked_by_failures');const status = await readSyncStatus(engine, f.id);expect(status.run_id).toBe(blockedRun);