Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

sync: the drain lease, one managed drainer per source (#6712 PR 1)

garrytan9db69d70e42c
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 758b00a4a8..463a7da24a 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -2448,7 +2448,7 @@ async function prepareConnectedDispatch(command: string, args: string[]): Promis
const { syncWatchdogPlan } = await import('../core/sync-reconcile.ts');
const plan = syncWatchdogPlan(args, res);
syncWatchdog = installProcessWatchdog(plan.watchdog);
- (await import('../core/forward-progress.ts')).registerRunDeadline({ atMs: Date.now() + res.deadlineMs, strict: !res.progressWindowMs });
+ (await import('../core/forward-progress.ts')).registerRunDeadline({ atMs: Date.now() + res.deadlineMs, strict: !res.progressWindowMs, ...(res.progressWindowMs ? { progressWindowMs: res.progressWindowMs } : {}) });
process.stderr.write(plan.armedLine);
}
} catch (e) {
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index a33e82590d..d2c96419a2 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -21,6 +21,8 @@ export interface SyncResult {
managedWrite?: import('../core/persistence/sync-run.ts').ManagedSyncWriteDiagnostic;
/** #6643: the request a `--retry-failed` rediscovery waits for (its producer and slug), instead of a silent no-op. */
retryWait?: import('../core/persistence/sync-run.ts').RetryWait;
+ /** #6712 PR 1: another drainer holds (or took) the source's drain lease; `resumable`, nothing admitted by this run. */
+ leaseHeld?: import('../core/persistence/sync-lease.ts').DrainLeaseHeld;
/** #6643: knock-on pages this run re-froze automatically, and the limits that bound it. */
/** #6693: caller remembers refused while their page's file awaited import (or was held), replayed after this sync imported it. */
replayedRemembers?: import('../core/repair/failed-writes.ts').ImportReplayReport;
@@ -93,7 +95,7 @@ export interface SyncResult {
* cron operators can disambiguate timeout vs pull-timeout in monitoring; connector item failures / early stop exit 1 (isFailedPartial).
*/
filesImported?: number;
- reason?: 'timeout' | 'pull_timeout' | 'pull_failed' | 'stall_timeout' | 'checkpoint_unavailable' | 'writer_pending' | 'writer_yield' | 'connector_item_failures' | 'connector_partial';
+ reason?: 'timeout' | 'pull_timeout' | 'pull_failed' | 'stall_timeout' | 'checkpoint_unavailable' | 'writer_pending' | 'writer_yield' | 'connector_item_failures' | 'connector_partial' | 'drain_lease_held';
/**
* v0.42.x (#1794): cumulative file paths durably banked to the checkpoint
* across THIS run + prior resumed runs. Surfaced on every partial/blocked
@@ -352,6 +354,8 @@ export interface SyncOpts {
* (src/core/persistence/sync-drain.ts). Set by the CLI, serve and the `sync` job (#6706); others stay single-pass.
*/
drain?: boolean;
+ /** #6712 PR 1: who takes the source's drain lease (kind and id shown to a follower), and whether a busy lease is followed instead of refused. */
+ drainHolder?: import('../core/persistence/sync-lease.ts').DrainHolderRef; followDrainLease?: boolean;
/** #6706: absolute epoch ms a managed drain stops before (`resumable / deadline`). */ deadlineAtMs?: number;
/** #5984: wall-clock ms the current drain started; managed cursors measure their rate from it. */
drainStartedAt?: number;
diff --git a/src/commands/sync/perform.ts b/src/commands/sync/perform.ts
index 8409ef63e0..26763b958b 100644
--- a/src/commands/sync/perform.ts
+++ b/src/commands/sync/perform.ts
@@ -10,7 +10,7 @@ import {
currentSourceFilesystemSignal,
assertSourceFilesystemActive,
} from '../../core/minions/source-filesystem.ts';
-import { currentJobSignal } from '../../core/minions/submission-authority.ts';
+import { currentJobSignal, currentSubmissionAuthority } from '../../core/minions/submission-authority.ts';
import { currentCompanyBrainSync, getCompanyBrainProfile } from '../../core/company-brain/profile.ts';
import type { BrainEngine } from '../../core/engine.ts';
import type { OperationContext } from '../../core/ops/contract.ts';
@@ -58,35 +58,7 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<
if (connector) return connector;
}
if (opts.signal?.aborted) return finish(await interruptedBeforeWork());
- if (managed) {
- let result = opts.drain
- ? await (await import('../../core/persistence/sync-drain.ts')).drainManagedSync(engine, opts, true)
- : await (await import('../../core/persistence/sync-run.ts')).performManagedSync(engine, opts);
- // #6349: a delta past the cursor bound syncs in stages; a drain takes the next stage from where the last one landed
- // until it reaches HEAD (each stage freezes its own bounded manifest, and a stop resumes at the stored cursor).
- const { deadlinePassed } = await import('../../core/persistence/sync-drain.ts');
- while (opts.drain && result.staged && result.drain?.outcome === 'synced' && !opts.dryRun && !opts.signal?.aborted) {
- // #6706: a caller deadline ends the catch-up between stages; the stage that landed is kept and the next run takes the next one.
- if (deadlinePassed(opts.deadlineAtMs)) { result = { ...result, drain: { ...result.drain, outcome: 'resumable', stop_reason: 'deadline' } }; break; }
- serr(result.staged.slice
- ? `[sync] sliced catch-up: committed the ${result.staged.slice.phase} slice of ${result.staged.target.slice(0, 12)} through ${result.staged.slice.after ?? '(start)'} (the target exceeds the cursor bound); taking the next slice.`
- : `[sync] staged catch-up: synced to ${result.staged.target.slice(0, 12)}, short of HEAD ${result.staged.head.slice(0, 12)} (the delta exceeds the cursor bound); taking the next stage.`);
- const next = await (await import('../../core/persistence/sync-drain.ts')).drainManagedSync(engine, opts, true);
- const stages = (result.staged.stages ?? 1) + 1, d = result.drain, n = next.drain;
- result = { ...next, fromCommit: result.fromCommit, added: result.added + next.added, modified: result.modified + next.modified, deleted: result.deleted + next.deleted,
- renamed: result.renamed + next.renamed, chunksCreated: result.chunksCreated + next.chunksCreated,
- ...(next.staged ? { staged: { ...next.staged, stages } } : {}),
- ...(n ? { drain: { ...n, passes: d.passes + n.passes, processed: d.processed + n.processed, written: d.written + n.written, waived: d.waived + n.waived } } : {}) };
- if (!next.staged) serr(`[sync] staged catch-up reached HEAD after ${stages} stages.`);
- }
- if (!opts.dryRun) await recordUpstreamObservation(engine, opts.sourceId ?? 'default', opts.repoPath);
- if (!opts.dryRun && ['synced', 'first_sync', 'up_to_date'].includes(result.status)) await clearSettledFailures(engine, opts.sourceId ?? 'default');
- if (!opts.dryRun) {
- const replayed = await replayImportedRemembers(engine, opts.sourceId ?? 'default');
- if (replayed) result = { ...result, replayedRemembers: replayed };
- }
- return result;
- }
+ if (managed) return performManagedBranch(engine, opts);
const filesystemRoot = opts.repoPath || await readSyncAnchor(engine, opts.sourceId, 'repo_path');
if (filesystemRoot && !hasSourceFilesystemLock(filesystemRoot)) {
let entered = false;
@@ -129,6 +101,60 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<
}
}
+/**
+ * The managed branch: the drain (or one pass), its staged stages and the post-sync settles, all under the source's drain
+ * lease (#6712 PR 1, persistence/sync-lease.ts). A plain CLI sync follows a live holder within its budget; every other
+ * caller gets `SyncLockBusyError` on a busy lease, as the classic per-source lock does.
+ */
+async function performManagedBranch(engine: BrainEngine, outer: SyncOpts): Promise<SyncResult> {
+ const sourceId = outer.sourceId ?? 'default';
+ const { withDrainLease } = await import('../../core/persistence/sync-lease.ts');
+ const lockKey = syncLockId(sourceId);
+ const work = async (leaseSignal: AbortSignal | undefined): Promise<SyncResult> => {
+ const opts: SyncOpts = leaseSignal ? { ...outer, signal: outer.signal ? AbortSignal.any([outer.signal, leaseSignal]) : leaseSignal } : outer;
+ let result = opts.drain
+ ? await (await import('../../core/persistence/sync-drain.ts')).drainManagedSync(engine, opts, true)
+ : await (await import('../../core/persistence/sync-run.ts')).performManagedSync(engine, opts);
+ // #6349: a delta past the cursor bound syncs in stages; a drain takes the next stage from where the last one landed
+ // until it reaches HEAD (each stage freezes its own bounded manifest, and a stop resumes at the stored cursor).
+ const { deadlinePassed } = await import('../../core/persistence/sync-drain.ts');
+ while (opts.drain && result.staged && result.drain?.outcome === 'synced' && !opts.dryRun && !opts.signal?.aborted) {
+ // #6706: a caller deadline ends the catch-up between stages; the stage that landed is kept and the next run takes the next one.
+ if (deadlinePassed(opts.deadlineAtMs)) { result = { ...result, drain: { ...result.drain, outcome: 'resumable', stop_reason: 'deadline' } }; break; }
+ serr(result.staged.slice
+ ? `[sync] sliced catch-up: committed the ${result.staged.slice.phase} slice of ${result.staged.target.slice(0, 12)} through ${result.staged.slice.after ?? '(start)'} (the target exceeds the cursor bound); taking the next slice.`
+ : `[sync] staged catch-up: synced to ${result.staged.target.slice(0, 12)}, short of HEAD ${result.staged.head.slice(0, 12)} (the delta exceeds the cursor bound); taking the next stage.`);
+ const next = await (await import('../../core/persistence/sync-drain.ts')).drainManagedSync(engine, opts, true);
+ const stages = (result.staged.stages ?? 1) + 1, d = result.drain, n = next.drain;
+ result = { ...next, fromCommit: result.fromCommit, added: result.added + next.added, modified: result.modified + next.modified, deleted: result.deleted + next.deleted,
+ renamed: result.renamed + next.renamed, chunksCreated: result.chunksCreated + next.chunksCreated,
+ ...(next.staged ? { staged: { ...next.staged, stages } } : {}),
+ ...(n ? { drain: { ...n, passes: d.passes + n.passes, processed: d.processed + n.processed, written: d.written + n.written, waived: d.waived + n.waived } } : {}) };
+ if (!next.staged) serr(`[sync] staged catch-up reached HEAD after ${stages} stages.`);
+ }
+ if (!opts.dryRun) await recordUpstreamObservation(engine, opts.sourceId ?? 'default', opts.repoPath);
+ if (!opts.dryRun && ['synced', 'first_sync', 'up_to_date'].includes(result.status)) await clearSettledFailures(engine, opts.sourceId ?? 'default');
+ if (!opts.dryRun) {
+ const replayed = await replayImportedRemembers(engine, opts.sourceId ?? 'default');
+ if (replayed) result = { ...result, replayedRemembers: replayed };
+ }
+ return result;
+ };
+ // A dry run reads and previews only; it never waits for, or keeps out, a drainer.
+ if (outer.dryRun) return work(undefined);
+ try {
+ return await withDrainLease(engine, sourceId, {
+ holder: outer.drainHolder ?? { kind: 'cli', id: null }, remote: currentSubmissionAuthority()?.kind === 'remote_generic',
+ ...(outer.followDrainLease ? { follow: { signal: outer.signal, deadlineAtMs: outer.deadlineAtMs } } : {}),
+ announce: holder => serr(`[sync] source ${sourceId} is being drained by ${holder ? `a ${holder.kind} drainer (pid ${holder.pid ?? '?'} on ${holder.host ?? '?'})` : 'another drainer'}; `
+ + 'following it until it finishes or this run\'s budget ends (one drainer per source; it resumes the same cursor).'),
+ }, work);
+ } catch (err) {
+ if (err instanceof LockUnavailableError && err.lockId === lockKey) throw new SyncLockBusyError(await formatLockBusyMessage(engine, lockKey), lockKey);
+ throw err;
+ }
+}
+
/**
* #6693: after a managed sync (any outcome: a partial run can still import the file), replay the caller remembers refused while
* their page's file awaited import or was held, whose page this run brought back in line with its file. Best effort: a failure
diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.ts
index 20cd95005f..5066405d16 100644
--- a/src/commands/sync/run.ts
+++ b/src/commands/sync/run.ts
@@ -516,7 +516,7 @@ async function runSyncAll(
strategy: cfg.strategy,
concurrency,
signal: composeAbortSignals(allInterrupt.signal, controller?.signal),
- drain: true, noBulk, lanes,
+ drain: true, noBulk, lanes, followDrainLease: true, drainHolder: { kind: 'cli', id: null },
};
// v0.40.6.0 (D6): wrap performSync in withSourcePrefix so every slog /
// serr line emitted from inside the sync code path gets prefixed with
@@ -798,7 +798,7 @@ async function runSingleSourceSync(
exclude: excludePatterns.length > 0 ? excludePatterns : undefined,
includeHidden: includeHiddenPatterns.length > 0 ? includeHiddenPatterns : undefined,
signal: composeAbortSignals(singleSourceInterrupt.signal, singleSourceController?.signal),
- drain: true, noBulk, lanes,
+ drain: true, noBulk, lanes, followDrainLease: true, drainHolder: { kind: 'cli', id: null },
};
// v0.42.42.0 (#2139, Step 4b): single-source `gbrain sync` gets the SAME
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index 2b95ba56f1..dcd8d24f92 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -1286,7 +1286,7 @@ async function runPhaseSync(
noExtract: willRunExtractPhase, // dedupe ONLY when cycle's extract phase will also run.
// If extract isn't scheduled (e.g. `gbrain dream --phase sync`),
// sync's inline extract still runs to preserve prior behavior.
- explicitProcessing: [], // unattended: an unfinished managed cursor keeps its own options (#5632)
+ drainHolder: { kind: 'cycle', id: null }, // #6712 PR 1: a busy drain lease skips like a busy sync lock
});
const syncedCount = result.added + result.modified;
// #3068: a pull_failed partial means the internal git pull failed and the
diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.ts
index 3e6bf51c9a..5dbd3a243f 100644
--- a/src/core/error-catalogue.ts
+++ b/src/core/error-catalogue.ts
@@ -94,6 +94,7 @@ export const ERROR_CATALOGUE = {
sync_drain_connection_lost: { code: 'connection_lost', docs: 'docs/guides/write-refusals.md#drain-connection-lost' },
sync_drain_capacity_paused: { code: 'capacity_paused', docs: 'docs/guides/write-refusals.md#drain-capacity-paused' },
sync_drain_head_blocked: { code: 'drain_stalled', docs: 'docs/guides/write-refusals.md#head-blocked' },
+ sync_drain_lease_held: { code: 'sync_drain_lease_held', docs: 'docs/guides/write-refusals.md#sync_drain_lease_held' },
// D8 `gbrain setup <harness>` (src/commands/setup.ts).
setup_harness_unsupported: { code: 'setup_harness_unsupported', docs: 'docs/guides/repair.md#setup-harness-unsupported' },
setup_owner_conflict: { code: 'setup_owner_conflict', docs: 'docs/guides/repair.md#setup-owner-conflict' },
diff --git a/src/core/forward-progress.ts b/src/core/forward-progress.ts
index 4e42aac7e3..cf71e07573 100644
--- a/src/core/forward-progress.ts
+++ b/src/core/forward-progress.ts
@@ -44,7 +44,8 @@ export function lastForwardProgressAt(): number {
* long-running loop stops itself before a strict deadline so it, not the
* watchdog, writes the final result.
*/
-export interface RunDeadline { atMs: number; strict: boolean }
+/** `progressWindowMs`: a progress-aware deadline stops only once this long passed without progress (#6712 PR 1: a drain-lease follower's budget). */
+export interface RunDeadline { atMs: number; strict: boolean; progressWindowMs?: number }
let runDeadline: RunDeadline | null = null;
export function registerRunDeadline(deadline: RunDeadline | null): void {
runDeadline = deadline;
diff --git a/src/core/minions/handlers/sync.ts b/src/core/minions/handlers/sync.ts
index 9c6e3bf79c..a3727f0e9e 100644
--- a/src/core/minions/handlers/sync.ts
+++ b/src/core/minions/handlers/sync.ts
@@ -8,7 +8,6 @@ import { resolveJobPull } from './job-pull.ts';
export function makeSyncHandler(engine: BrainEngine): MinionHandler {
return async (job) => {
const { performSync } = await import('../../../commands/sync.ts');
- const { explicitSyncProcessing } = await import('../../persistence/sync-authority.ts');
const repoPath = typeof job.data.repoPath === 'string' ? job.data.repoPath : undefined;
const noPull = !resolveJobPull(job.data);
// noEmbed defaults to true (embed is a separate job — submit `embed --stale`
@@ -85,28 +84,14 @@ export function makeSyncHandler(engine: BrainEngine): MinionHandler {
const { planJobDrain, jobDrainProgress, settleJobDrain } = await import('./sync-job-drain.ts');
const plan = await planJobDrain(engine, job);
const progress = jobDrainProgress(job, (await import('../../persistence/sync-drain.ts')).drainEstimate);
- // #6706: one drainer per source. A tick, retry or delayed continuation that starts while another sync job for the same
- // source is live completes as a skip (the dispatcher's maxPending does not see delayed rows), like the lock-busy skip below.
- // A continuation ignores its own parent, which stays active until the worker records the parent's completion.
- // Classic syncs keep master's per-source lock and its skip; only a managed drain takes this guard.
- if (plan.opts.drain && await (await import('../../persistence/managed-mode.ts')).readManagedMode(engine).catch(() => false)) {
- const [live] = await engine.executeRaw<{ id: number | string }>(`SELECT id FROM minion_jobs WHERE name='sync' AND status='active' AND lock_until > now() AND id <> $1 AND id <> $3
- AND (started_at, id) < (SELECT started_at, id FROM minion_jobs WHERE id = $1)
- AND (COALESCE(data->>'sourceId', data->>'source_id')=$2 OR (COALESCE(data->>'sourceId', data->>'source_id') IS NULL AND ($4::text IS NULL AND $2='default' OR data->>'repoPath'=$4))) LIMIT 1`,
- [job.id, sourceId ?? 'default', typeof job.data.continuation_of === 'number' ? job.data.continuation_of : -1, repoPath ?? null]).catch(() => []);
- if (live) {
- console.error(`[sync] skipped: sync job #${live.id} is already draining ${sourceId ?? 'default'}.`);
- return { skipped: true, reason: 'sync_in_progress', source_id: sourceId ?? 'default', running_job_id: Number(live.id),
- next: { command: `gbrain jobs get ${live.id} --json`, safe_to_loop: true, retry_after_ms: 30_000, why: `Sync job #${live.id} is draining source ${sourceId ?? 'default'}; it resumes the cursor, so nothing else needs to run.` } };
- }
- }
let result;
try {
result = await performSync(engine, {
repoPath, sourceId, noPull, noEmbed, noExtract, signal,
...plan.opts,
...(plan.opts.drain ? { onProgress: progress.onProgress } : {}),
- explicitProcessing: explicitSyncProcessing(job.data),
+ // #6712 PR 1: the job drains under the source's drain lease; a busy lease is the skip below.
+ drainHolder: { kind: 'job', id: String(job.id) },
concurrency: concurrencyOverride,
...(githubItem ? { githubItem } : {}),
});
@@ -119,11 +104,14 @@ export function makeSyncHandler(engine: BrainEngine): MinionHandler {
// advanced) anchor.
const { SyncLockBusyError } = await import('../../../commands/sync.ts');
if (err instanceof SyncLockBusyError) {
- console.error(
- `[sync] skipped: sync already in progress for ${sourceId ?? 'default'} ` +
- `(lock ${err.lockKey} held).`,
- );
- return { skipped: true, reason: 'sync_in_progress', source_id: sourceId ?? 'default' };
+ // #6712 PR 1 (folds #6706's live-job guard): one drainer per source is the drain lease; a job that finds it held completes as a skip.
+ const id = sourceId ?? 'default';
+ const holder = await (await import('../../persistence/sync-lease.ts')).readDrainHolder(engine, id).catch(() => null);
+ const runningJob = holder?.kind === 'job' && holder.id && /^\d+$/.test(holder.id) ? Number(holder.id) : null;
+ console.error(`[sync] skipped: sync already in progress for ${id} (lock ${err.lockKey} held${holder ? ` by a ${holder.kind} drainer` : ''}).`);
+ return { skipped: true, reason: 'sync_in_progress', source_id: id, ...(holder ? { holder } : {}),
+ ...(runningJob !== null ? { running_job_id: runningJob, next: { command: `gbrain jobs get ${runningJob} --json`, safe_to_loop: true, retry_after_ms: 30_000,
+ why: `Sync job #${runningJob} is draining source ${id}; it resumes the cursor, so nothing else needs to run.` } } : {}) };
}
// P4.2 (supersedes #6465): a job an older daemon queued for a gbrain-owned content directory completes as a
// skip instead of dying after its attempts; the dispatchers no longer queue one (automaticSyncSkip).
diff --git a/src/core/ops/sync-status.ts b/src/core/ops/sync-status.ts
index 0d452f260f..d48f6e9538 100644
--- a/src/core/ops/sync-status.ts
+++ b/src/core/ops/sync-status.ts
@@ -100,6 +100,7 @@ const sync_brain: Operation = {
noEmbed: (p.no_embed as boolean) || false,
noPull: (p.no_pull as boolean) || false,
full: (p.full as boolean) || false,
+ drainHolder: { kind: 'mcp', id: null },
...sourceOpts,
});
},
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index e2cdf876d2..dca7e94adf 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -18,6 +18,9 @@ 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).
+ | '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'
// #6511: before each keyset chunk of the preparation-time journal sweep (a stalling hook models a slow chunk), and the fact purge's planning read.
diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.ts
index f83cb1a04e..8ca60491ca 100644
--- a/src/core/persistence/sync-drain.ts
+++ b/src/core/persistence/sync-drain.ts
@@ -41,7 +41,9 @@ export type DrainStopReason = 'deadline' | 'drain_stalled' | 'database_contentio
/** #6340: the database connection dropped `CONNECTION_STRIKES` times in a row with no page committed between the drops; the cursor stands, the same command resumes it. */
| 'connection_lost'
/** #6696 (A7): a cumulative write cap (or the background pause line) refused the next admission after the preflight passed; resumable once capacity returns. */
- | 'capacity_paused';
+ | 'capacity_paused'
+ /** #6712 PR 1: another drainer holds the source's drain lease (or took it from this run); resumable, the next run follows it. */
+ | 'drain_lease_held';
/** #6696 (A7): the refusal that paused the drain (`capacity_paused`); `fix` is the host's config raise. */
export interface DrainCapacityPause { code: string; reason: string | null; detail: string | null; message: string; fix?: Action }
/** A capacity refusal raised by an admission after the run's preflight (the preflight's own refusal stops the command up front). */
@@ -576,6 +578,7 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
}
if (!continues(result)) {
if (TERMINAL_STATUSES.has(result.status)) return finish(result, 'synced');
+ if (result.leaseHeld) return finish(result, 'resumable', 'drain_lease_held', { retry_after_ms: result.leaseHeld.retry_after_ms });
// #6278: the breaker's systemic stop is one diagnostic, not a failed page.
if (result.breaker) return finish(result, 'blocked', 'preparation_systemic');
if (result.status === 'blocked_by_failures') return finish(result, 'blocked', 'blocked_by_failures');
@@ -901,7 +904,7 @@ const STOP_DOCS: Record<DrainStopReason, CatalogueName> = {
recovery_required: 'sync_drain_writer_blocked', owner_unavailable: 'sync_drain_writer_blocked', unexpected_file_bytes: 'sync_drain_writer_blocked',
unexpected_staging_bytes: 'sync_drain_writer_blocked', blocked_by_failures: 'sync_drain_blocked_by_failures',
preparation_abandoned: 'sync_drain_preparation_abandoned', preparation_systemic: 'sync_drain_preparation_systemic', write_capacity: 'sync_drain_write_capacity',
- connection_lost: 'sync_drain_connection_lost', capacity_paused: 'sync_drain_capacity_paused',
+ connection_lost: 'sync_drain_connection_lost', capacity_paused: 'sync_drain_capacity_paused', drain_lease_held: 'sync_drain_lease_held',
};
/** What the agent runs next, or null when the sync is done (DX-A2). */
@@ -919,6 +922,12 @@ export function drainNext(result: SyncResult, resumeCommand: string, sourceId: s
+ `${pause?.reason === 'lifetime_ids' ? 'Request ids never free, so ' : ''}${raise ? `the brain host runs ${raise} (reversible)` : 'the brain host raises the cap gbrain doctor --only persistence_capacity --json names'}`
+ `${pause?.reason === 'terminal_bytes' ? ', or receipts compact over time' : ''}; then rerun: ${resumeCommand}`, ...(docs ? { docs } : {}) };
}
+ if (outcome === 'resumable' && (d?.stop_reason === 'drain_lease_held' || result.leaseHeld)) {
+ const held = result.leaseHeld;
+ return { command: resumeCommand, safe_to_loop: true, retry_after_ms: held?.retry_after_ms ?? d?.retry_after_ms ?? 0, ...estimate, code: 'sync_drain_lease_held',
+ why: held?.fix.why ?? 'Another drainer holds this source\'s drain lease and resumes the same cursor; rerun after retry_after_ms.',
+ ...(held ? { fix: renderAction({ ...held.fix, argv: resumeCommand.split(' ') }, cliRenderContext()) } : {}), docs: ERROR_CATALOGUE.sync_drain_lease_held.docs };
+ }
if (outcome === 'resumable') {
const abandoned = d?.stop_reason === 'preparation_abandoned';
return { command: resumeCommand, safe_to_loop: true, retry_after_ms: d?.retry_after_ms ?? 0, ...estimate,
diff --git a/src/core/persistence/sync-group.ts b/src/core/persistence/sync-group.ts
index a4a372f90b..84a5efd23d 100644
--- a/src/core/persistence/sync-group.ts
+++ b/src/core/persistence/sync-group.ts
@@ -21,6 +21,7 @@ import type { WriteRequest } from './model.ts';
import { pipelined } from '../page-state/transactions.ts';
import type { SyncIntent } from './sync-prepare.ts';
import type { SyncAuthority } from './sync-authority.ts';
+import { assertDrainLease } from './sync-lease.ts';
/** What sets a drain's lane ceiling: lanes off, the configured maximum, or the connection pool. */
export type LanesCap = 'disabled' | 'maximum' | 'pool';
@@ -143,6 +144,7 @@ export async function admitGroup(engine: BrainEngine, members: WaiverEntry[], cu
principal: cursor.authority.writer.principal, authority: cursor.authority.writer, callerIntent: member.intent, intent: member.intent }))),
]) as [unknown, WriteRequest[]];
if (!await cursorHolds(tx)) throw new GroupMoved();
+ await assertDrainLease(tx, cursor.sourceId);
return rows;
}), undefined, error => engine.reconnect({ error })).catch(error => { if (error instanceof GroupMoved) return null; throw error; });
}
diff --git a/src/core/persistence/sync-lease.ts b/src/core/persistence/sync-lease.ts
new file mode 100644
index 0000000000..9ab09c7cae
--- /dev/null
+++ b/src/core/persistence/sync-lease.ts
@@ -0,0 +1,179 @@
+/**
+ * #6712 PR 1: the drain lease. One managed drainer per source at a time, whatever started it: the CLI (single
+ * source and `--all`), a serve-delegated run, a sync job, the cycle phase, `sync_brain`, a staged catch-up, an owner
+ * RPC slice or a refresh. The lease is the existing per-source sync lock (`gbrain_cycle_locks` row
+ * `gbrain-sync:<source>`, the row `--break-lock` inspects and breaks), taken by `withRefreshingLock`; its
+ * `acquisition_token` is the fencing token.
+ *
+ * - **Renewal.** TTL `DRAIN_LEASE_TTL_MINUTES`, renewed every `DRAIN_LEASE_REFRESH_MS` by `withRefreshingLock`; a
+ * renewal that matches no row, or the TTL passing unconfirmed (an event loop blocked past it, a machine asleep),
+ * aborts the pass's signal with `LockStolenError`.
+ * - **Takeover.** `tryAcquireDbLock`'s rules, the same as `--break-lock`'s safe path: a TTL that expired with no
+ * heartbeat inside the steal grace, or a same-host holder whose pid is provably dead and whose lease is older than
+ * `HOLDER_TAKEOVER_GRACE_MS`.
+ * - **Fencing.** `assertDrainLease` reads the lock row with this pass's token `FOR SHARE` inside every transaction
+ * that admits sync work or swaps the cursor, so a pass that lost the lease admits nothing and advances no
+ * checkpoint: the row is gone or carries another token, and a takeover waits for the share lock.
+ * - **Cancellation.** The caller's signal aborts the pass; the lease is released in `withRefreshingLock`'s finally.
+ * - **Reentrancy.** A pass inside a lease (the drain's passes, staged stages, a company catch-up) runs under it.
+ *
+ * A caller that may follow (`gbrain sync`, a CLI run delegated to a serve) waits for a live holder within its own
+ * budget, counting the holder's cursor movement as this process's forward progress, and takes the lease when the
+ * holder releases it. Out of budget, or when the lease moved away mid-pass, the run returns `resumable` with
+ * `sync_drain_lease_held`; every other caller gets `SyncLockBusyError` (jobs and the cycle skip on it).
+ */
+import { AsyncLocalStorage } from 'node:async_hooks';
+import type { BrainEngine } from '../engine.ts';
+import type { SyncResult } from '../../commands/sync.ts';
+import type { Action } from '../agent-output.ts';
+import { inspectLock, LockStolenError, LockUnavailableError, syncLockId, withRefreshingLock } from '../db-lock.ts';
+import { currentRunDeadline, lastForwardProgressAt, noteForwardProgress } from '../forward-progress.ts';
+import { faultPoint } from './fault-points.ts';
+
+export const DRAIN_LEASE_TTL_MINUTES = 2;
+export const DRAIN_LEASE_REFRESH_MS = 20_000;
+/** How long a follower waits between looks at the holder, and the retry delay `sync_drain_lease_held` prints. */
+export const FOLLOW_POLL_MS = 2_000;
+export const LEASE_RETRY_AFTER_MS = 60_000;
+/** A follower stops this long before its watchdog would (or half its window, when the window is shorter). */
+const FOLLOW_MARGIN_MS = 30_000;
+const LEASE_OP = 'managed-sync-lease';
+export const SYNC_DRAIN_LEASE_HELD = 'sync_drain_lease_held';
+
+export type DrainHolderKind = 'cli' | 'serve' | 'job' | 'cycle' | 'mcp' | 'owner_slice' | 'refresh';
+export interface DrainHolderRef { kind: DrainHolderKind; id?: string | null }
+export interface DrainHolder { kind: DrainHolderKind | 'unknown'; id: string | null; host: string | null; pid: number | null; started_at: string | null; last_heartbeat_at: string | null }
+export interface DrainLeaseHeld { code: typeof SYNC_DRAIN_LEASE_HELD; holder: DrainHolder | null; retry_after_ms: number; lost?: true; fix: Action }
+interface DrainLease { lockId: string; sourceId: string; token: string }
+
+const leases = new AsyncLocalStorage<ReadonlyMap<string, DrainLease>>();
+
+export function currentDrainLease(sourceId: string): DrainLease | null {
+ return leases.getStore()?.get(syncLockId(sourceId)) ?? null;
+}
+
+/**
+ * The fence: inside a transaction that admits work or swaps the cursor, the lock row must still carry this pass's
+ * token. Throws `LockStolenError` when it does not (the pass ends `resumable` with `sync_drain_lease_held`). A caller
+ * outside any lease (none in production: `performManagedSync` takes one) is not fenced.
+ */
+export async function assertDrainLease(tx: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<void> {
+ const lease = currentDrainLease(sourceId);
+ if (!lease) return;
+ const rows = await tx.executeRaw('SELECT 1 FROM gbrain_cycle_locks WHERE id=$1 AND acquisition_token=$2::uuid FOR SHARE', [lease.lockId, lease.token]);
+ if (!rows.length) throw new LockStolenError(lease.lockId, `the drain lease of source ${sourceId} is no longer held by this pass`);
+}
+
+const iso = (value: Date | null | undefined) => value ? value.toISOString() : null;
+
+/** The live holder of a source's drain lease (kind and id from the row this module writes beside the lock), or null. */
+export async function readDrainHolder(engine: BrainEngine, sourceId: string): Promise<DrainHolder | null> {
+ const snap = await inspectLock(engine, syncLockId(sourceId));
+ if (!snap) return null;
+ const [row] = await engine.executeRaw<{ meta: { token?: string; kind?: DrainHolderKind; id?: string | null } | string | null }>(
+ 'SELECT completed_keys->0 AS meta FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [LEASE_OP, sourceId]).catch(() => []);
+ const raw = typeof row?.meta === 'string' ? JSON.parse(row.meta) : row?.meta;
+ const meta = raw?.token === snap.acquisition_token ? raw : null;
+ return { kind: meta?.kind ?? 'unknown', id: meta?.id ?? null, host: snap.holder_host, pid: snap.holder_pid,
+ started_at: iso(snap.acquired_at), last_heartbeat_at: iso(snap.last_refreshed_at) };
+}
+
+/** What a remote caller may see of a holder: its kind and times, never its host, pid or job id. */
+const redacted = (holder: DrainHolder | null): DrainHolder | null => holder && { ...holder, id: null, host: null, pid: null };
+
+/** The `resumable` result of a run that did not get (or lost) the lease. Nothing was admitted by it; the cursor stands. */
+export function leaseHeldResult(sourceId: string, holder: DrainHolder | null, opts: { lost?: boolean; remote?: boolean; resumeArgv?: string[] } = {}): SyncResult {
+ const shown = opts.remote ? redacted(holder) : holder;
+ const who = shown ? `a ${shown.kind} drainer${shown.pid ? ` (pid ${shown.pid}${shown.host ? ` on ${shown.host}` : ''})` : ''}` : 'another drainer';
+ const argv = opts.resumeArgv ?? ['gbrain', 'sync', '--no-pull', '--source', sourceId];
+ const why = `${opts.lost ? `This run lost the drain lease of source ${sourceId} to ${who}` : `Source ${sourceId} is being drained by ${who}`}${shown?.last_heartbeat_at ? `, last heartbeat ${shown.last_heartbeat_at}` : ''}; `
+ + `one drainer runs per source and it resumes the same cursor, so nothing is lost. Rerun after ${Math.round(LEASE_RETRY_AFTER_MS / 1000)}s: it follows the holder and takes the lease when the holder finishes.`;
+ const fix: Action = { argv, consent: [], actor: 'provider', requires_exclusive: false, why,
+ verify: { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'] } };
+ return { status: 'partial', reason: 'drain_lease_held', fromCommit: null, toCommit: '', added: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [],
+ filesImported: 0, bankedFiles: 0,
+ leaseHeld: { code: SYNC_DRAIN_LEASE_HELD, holder: shown, retry_after_ms: LEASE_RETRY_AFTER_MS, ...(opts.lost ? { lost: true as const } : {}), fix },
+ drain: { outcome: 'resumable', stop_reason: 'drain_lease_held', passes: 0, processed: 0, written: 0, waived: 0, remaining: null, rate_pages_per_min: null, eta_seconds: null,
+ retry_after_ms: LEASE_RETRY_AFTER_MS } };
+}
+
+/**
+ * When a follower stops: the earliest of the caller's own deadline (`deadlineAtMs`, a job's) and the process watchdog
+ * (`--hard-deadline` or the non-TTY window, which extends while progress keeps arriving), less a margin, so the
+ * follower reports before the watchdog fires. `--timeout` arrives as the caller's signal.
+ */
+export function followStopAt(startedAt: number, deadlineAtMs?: number): number {
+ let at = deadlineAtMs ?? Infinity;
+ const run = currentRunDeadline();
+ if (run) at = Math.min(at, run.progressWindowMs ? Math.max(run.atMs, lastForwardProgressAt() + run.progressWindowMs) : run.atMs);
+ if (!Number.isFinite(at)) return at;
+ return at - Math.min(FOLLOW_MARGIN_MS, Math.max(0, (at - startedAt) / 2));
+}
+
+/** A fingerprint of the source's cursor movement: a change between two looks is the holder's progress. */
+async function holderProgress(engine: BrainEngine, sourceId: string): Promise<string | null> {
+ const [row] = await engine.executeRaw<{ at: string | null; n: string | number | null }>(`SELECT max(updated_at)::text AS at, count(*) AS n FROM op_checkpoints
+ WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1`, [sourceId]).catch(() => []);
+ return row ? `${row.at}|${row.n}` : null;
+}
+
+function pause(ms: number, signal?: AbortSignal): Promise<void> {
+ return new Promise(resolve => {
+ if (signal?.aborted) { resolve(); return; }
+ const timer = setTimeout(done, Math.max(0, ms));
+ function done() { clearTimeout(timer); signal?.removeEventListener('abort', done); resolve(); }
+ signal?.addEventListener('abort', done, { once: true });
+ });
+}
+
+export interface DrainLeaseOptions {
+ holder: DrainHolderRef;
+ /** Follow a live holder within this budget; without it a busy lease throws `LockUnavailableError`. */
+ follow?: { signal?: AbortSignal; deadlineAtMs?: number };
+ remote?: boolean;
+ resumeArgv?: string[];
+ /** Called once, when this run starts following a live holder. */
+ announce?: (holder: DrainHolder | null) => void;
+}
+
+/**
+ * Runs `work` under the source's drain lease (`work`'s signal aborts when the lease is lost). Reentrant. A busy
+ * lease throws `LockUnavailableError` unless `follow` is set; a lost lease, and a follow budget that ran out, return
+ * `leaseHeldResult`.
+ */
+export async function withDrainLease(engine: BrainEngine, sourceId: string, opts: DrainLeaseOptions,
+ work: (signal: AbortSignal | undefined) => Promise<SyncResult>): Promise<SyncResult> {
+ const lockId = syncLockId(sourceId);
+ if (leases.getStore()?.has(lockId)) return work(undefined);
+ const startedAt = Date.now();
+ let progress: string | null | undefined;
+ for (;;) {
+ try {
+ return await withRefreshingLock(engine, lockId, async (signal, handle) => {
+ const lease: DrainLease = { lockId, sourceId, token: handle.acquisitionToken };
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)
+ ON CONFLICT (op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`,
+ [LEASE_OP, sourceId, JSON.stringify([{ token: lease.token, kind: opts.holder.kind, id: opts.holder.id ?? null, started_at: new Date().toISOString() }])]);
+ await faultPoint('sync:lease_acquired', { sourceId });
+ const store = new Map(leases.getStore() ?? []);
+ store.set(lockId, lease);
+ return leases.run(store, () => work(signal));
+ }, { ttlMinutes: DRAIN_LEASE_TTL_MINUTES, refreshIntervalMs: DRAIN_LEASE_REFRESH_MS });
+ } catch (error) {
+ if (error instanceof LockStolenError && error.lockId === lockId) {
+ return leaseHeldResult(sourceId, await readDrainHolder(engine, sourceId).catch(() => null), { lost: true, remote: opts.remote, resumeArgv: opts.resumeArgv });
+ }
+ if (!(error instanceof LockUnavailableError) || error.lockId !== lockId || !opts.follow) throw error;
+ }
+ const follow = opts.follow;
+ if (progress === undefined) opts.announce?.(await readDrainHolder(engine, sourceId).catch(() => null));
+ const stopAt = followStopAt(startedAt, follow.deadlineAtMs);
+ if (follow.signal?.aborted || Date.now() >= stopAt) {
+ return leaseHeldResult(sourceId, await readDrainHolder(engine, sourceId).catch(() => null), { remote: opts.remote, resumeArgv: opts.resumeArgv });
+ }
+ const seen = await holderProgress(engine, sourceId);
+ if (progress !== undefined && seen !== progress) noteForwardProgress();
+ progress = seen;
+ await pause(Math.min(FOLLOW_POLL_MS, stopAt - Date.now()), follow.signal);
+ }
+}
diff --git a/src/core/persistence/sync-movement.ts b/src/core/persistence/sync-movement.ts
index de30a68417..fa3f1a9f38 100644
--- a/src/core/persistence/sync-movement.ts
+++ b/src/core/persistence/sync-movement.ts
@@ -96,8 +96,14 @@ interface WatermarkRow { last_commit_at: unknown; admitted: number | string }
interface HeadRow { request_id: string; state: string; claim_phase: unknown; execution_token: string | null; claim_lapsed: boolean | null; publication_started: boolean | null }
interface HoldRow { count: number | string | null; stalled: number | string | null; fences: number | string | null; concurrent: number | string | null; updated_at: unknown }
-/** #6706: the id of the active `sync` Minions job with a live lock that is draining `sourceId`, or null. Never rejects. */
+/**
+ * #6706: the id of the active `sync` Minions job with a live lock that is draining `sourceId`, or null. Never rejects.
+ * #6712 PR 1: a job drains under the source's drain lease, so its holder row names the job first; the job-table read
+ * stays for a job an older gbrain started (it takes no lease).
+ */
export async function liveSyncJob(engine: BrainEngine, sourceId: string): Promise<number | null> {
+ const holder = await (await import('./sync-lease.ts')).readDrainHolder(engine, sourceId).catch(() => null);
+ if (holder?.kind === 'job' && holder.id && /^\d+$/.test(holder.id)) return Number(holder.id);
const [row] = await engine.executeRaw<{ id: number | string }>(`SELECT id FROM minion_jobs WHERE name='sync' AND status='active' AND lock_until > now()
AND (COALESCE(data->>'sourceId', data->>'source_id')=$1 OR (COALESCE(data->>'sourceId', data->>'source_id') IS NULL
AND (data->>'repoPath' IS NULL AND $1='default' OR data->>'repoPath'=(SELECT local_path FROM sources WHERE id=$1)))) ORDER BY started_at LIMIT 1`, [sourceId]).catch(() => []);
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 3e886c07c1..969db5f4a6 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -62,6 +62,9 @@ import { recordSyncRunTrend } from '../fence-repair/census-store.ts';
import { addFencesNormalized, addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, heldGitPaths, fencesNormalizedReport, holdsEscalated, readGitHoldRetryPaths, readGitSourceHolds, readSyncHoldPolicy, recordSyncConversion, recoveredReport, requestGitHoldRetry, writeGitHold, type FencesTally, type SyncHoldPolicy } from './sync-holds.ts';
import { withScreeningPaths } from './screening-paths.ts';
import { withBoundedReadSession } from './bounded-reads.ts';
+import { assertDrainLease, currentDrainLease, leaseHeldResult, readDrainHolder, withDrainLease } from './sync-lease.ts';
+import { LockStolenError, LockUnavailableError, syncLockId } from '../db-lock.ts';
+import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
export interface ManagedSyncWriteDiagnostic {
source_id: string;
@@ -238,6 +241,7 @@ async function saveCursor(engine: BrainEngine, key: string, before: Cursor | nul
}
/** Compare-and-swap inside the caller's transaction; a lost swap returns the cursor that won. */
async function writeCursor(tx: BrainEngine, key: string, before: Cursor | null, next: Cursor, inTx?: (tx: BrainEngine) => Promise<unknown>, synchronous = false): Promise<Cursor> {
+ await assertDrainLease(tx, next.sourceId);
// #6643: a cursor records the indexes it settles without a commit from its first save by this build on; a cursor saved
// before (a run that began on an older build) starts recording at the index it had then.
if (!next.settled) next.settled = before && before.runId === next.runId ? { from: before.settled?.from ?? before.index, ranges: before.settled?.ranges ?? [] } : { from: 0, ranges: [] };
@@ -294,6 +298,7 @@ async function replaceCursor(engine: BrainEngine, key: string, before: CursorHea
await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");
await tx.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid FOR UPDATE', [next.binding.worktree_id]);
// #6643: only the old cursor's own open requests and recovery-bearing ones veto the swap, and the caller is told which.
+ await assertDrainLease(tx, next.sourceId);
const blocker = await oldRunBlocker(tx, next, key);
if (blocker) { assertActive(); return { wait: blocker }; }
await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)`, [`${OP}-manifest`, next.runId, JSON.stringify(next.entries)]);
@@ -1302,6 +1307,7 @@ async function finishCheckpoint(engine: BrainEngine, key: string, cursor: Cursor
async function retireCompletedCursor(engine: BrainEngine, key: string, completed: Cursor, assertActive: () => void): Promise<Cursor | null> {
await engine.transaction(async tx => {
assertActive();
+ await assertDrainLease(tx, completed.sourceId);
await tx.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 AND completed_keys=$3::text::jsonb', [OP, key, JSON.stringify([header(completed)])]);
assertActive();
});
@@ -1372,7 +1378,22 @@ async function oldRunBlocker(engine: Pick<BrainEngine, 'executeRaw'>, cursor: Pi
return row ? { ...row, recovery: row.recovery === true, retry_after_ms: 5000 } : null;
}
+/**
+ * One managed pass under the source's drain lease (#6712 PR 1): reentrant inside a drain, a staged catch-up or a CLI
+ * run that holds it; a direct caller (an owner RPC slice, a refresh) takes it for this pass, and a busy or lost lease
+ * returns `sync_drain_lease_held` (resumable). A dry run takes no lease.
+ */
export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, slice?: { maxPages: number; maxMs: number }): Promise<SyncResult> {
+ if (opts.dryRun || currentDrainLease(opts.sourceId ?? 'default')) return performManagedPass(engine, opts, slice);
+ const sourceId = opts.sourceId ?? 'default';
+ return withDrainLease(engine, sourceId, { holder: opts.drainHolder ?? { kind: slice ? 'owner_slice' : 'cli', id: null } },
+ signal => performManagedPass(engine, signal ? { ...opts, signal: opts.signal ? AbortSignal.any([opts.signal, signal]) : signal } : opts, slice))
+ .catch(async error => {
+ if (!(error instanceof LockUnavailableError) || error.lockId !== syncLockId(sourceId)) throw error;
+ return leaseHeldResult(sourceId, await readDrainHolder(engine, sourceId).catch(() => null), { remote: currentSubmissionAuthority()?.kind === 'remote_generic' });
+ });
+}
+async function performManagedPass(engine: BrainEngine, opts: SyncOpts, slice?: { maxPages: number; maxMs: number }): Promise<SyncResult> {
const state: HoldRunState = {};
const synced = await runManagedSync(engine, opts, slice, state);
if (!state.sourceId || !state.incarnation || synced.status === 'dry_run') return synced;
@@ -1610,6 +1631,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
const [held] = await tx.executeRaw<{ request_id: string | null; same: boolean | null }>(`SELECT completed_keys->0->'pending'->>'requestId' AS request_id,
completed_keys->0->'pending'->'intent' = $3::text::jsonb AS same FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 FOR SHARE`, [OP, key, JSON.stringify(pending.intent)]);
if (held?.request_id !== pending.requestId || held.same !== true) throw new CursorMoved();
+ await assertDrainLease(tx, admitting.sourceId);
assertActive();
return accepted;
}), undefined, error => engine.reconnect({ error })).catch(error => cursorMovedAdmission(engine, key, admitting, pending, error));
@@ -1673,7 +1695,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
// A refresh fence, or an admission refused while other requests hold the writer's outstanding cap (#6278: the drain
// waits for them), is transient admission back-pressure, not a sync failure to record. #6340: neither is a lost
// database connection or a statement timeout: the cursor and its frozen manifest stay, and the next pass resumes them.
- if (!['permission_denied', 'worktree_refreshing', 'refresh_recovery_required'].includes(code) && !isWriteCapacityWait(error)
+ if (!['permission_denied', 'worktree_refreshing', 'refresh_recovery_required'].includes(code) && !isWriteCapacityWait(error) && !(error instanceof LockStolenError)
&& !isRetryableConnError(error) && !isStatementTimeoutError(error) && !(code === 'invalid_params' && phase === 'resume' && (await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1 AND completed_keys->0->>'code' IS DISTINCT FROM 'invalid_params'", [key])).length > 0)) {
const [stored] = cursor ? [] : await engine.executeRaw<{ completed_keys: [CursorHeader] }>('SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [OP, key]);
const failedCursor = cursor ?? stored?.completed_keys?.[0];
diff --git a/src/core/serve-sync-runner.ts b/src/core/serve-sync-runner.ts
index f9db84eb5c..7a63e5468e 100644
--- a/src/core/serve-sync-runner.ts
+++ b/src/core/serve-sync-runner.ts
@@ -353,8 +353,8 @@ async function startVerifiedDelegatedSync(
// flags ride through; the classic path keeps the always-deferred embed rule of the legacy lane.
...(managed
? { drain: true, noBulk: options.noBulk, lanes: options.lanes, noEmbed: options.noEmbed, embedDeferred: options.embedDeferred,
- // #6696: an older CLI omits the list but still sends true for each processing flag its user typed.
- explicitProcessing: options.explicitProcessing ?? typedSyncProcessing(options) }
+ // #6712 PR 1: the CLI's run follows a live drain-lease holder inside the serve, as it would in its own process.
+ followDrainLease: true, drainHolder: { kind: 'serve' as const, id: String(job.id) } }
: { noEmbed: true }),
signal: job.controller.signal,
onProgress: (p) => {