Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
sync: lease follower, stalled-holder stop and holder records (#6712 PR 1)
garrytan101cac479446
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex d200900d9e..71581d0695 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -3134,6 +3134,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c|---|---|---|---|---|---|---|| Another sync run of the source replaced the managed-sync cursor before this checkpoint published, so the checkpoint had nothing left to publish. | The replacing run (a --retry-failed rediscovery or a newer sync of the source) covers the source from its own discovery; the superseded checkpoint's receipt is a conflict, no managed-sync failure is recorded for it, and the run that awaited it goes on with the winning cursor. A same-run index lag still reports revision_conflict. | Nothing to repair: let the current sync finish. gbrain sync status --source <id> --json shows the cursor that now covers the source. | agent | `repeat the read that failed` | 1 | no |+### sync_drain_lease_held++<a id="sync_drain_lease_held"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| Another process holds the source's drain lease and is still committing pages; this run followed it until its own budget ended, or lost the lease mid-pass, and stopped `resumable`. | One managed drainer per source: two drainers on one cursor raced each other's checkpoints. A follower counts the holder's commits as its own progress, takes the lease when the holder releases it, and stops `drain_stalled` (cause `no_progress`) instead when the holder commits nothing for 5 minutes, so a wedged holder never reads as a clean exit. | Rerun next.command after next.retry_after_ms (safe_to_loop), or let the holder finish; Ctrl-C while following leaves the holder running. | provider | `repeat the read that failed` | 1 | yes |++More: [docs/guides/write-refusals.md#sync_drain_lease_held](../../docs/guides/write-refusals.md#sync_drain_lease_held)+### sync_in_progress<a id="sync_in_progress"></a>diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.mdindex c25fab1957..104ebaddf0 100644--- a/docs/guides/sync-unblock-runbook.md+++ b/docs/guides/sync-unblock-runbook.md@@ -113,6 +113,7 @@ Every hold and error has three fields, from one table| `write_capacity` | connection | retry | no | writer status shows the cap held by requests that never settle || `write_capacity_backpressure` | connection | retry | no | reason lifetime_ids (request ids never free, so only the host raise lifts it), or the pause outlasts a day || `capacity_paused` | connection | retry | no | reason lifetime_ids (only the host raise resumes it), or the same pause after the raise |+| `sync_drain_lease_held` | connection | retry | no | never: a holder that stops committing ends the run drain_stalled instead || `storage_error` | connection | retry | no | the same error after a rerun (then it is not a dropped connection) || `graduation_in_progress` | connection | retry | no | gbrain migrate --status --json reports no running move and the fence still refuses || `preparation_systemic` | systemic | upgrade, retry | yes | always |diff --git a/src/commands/sync/args.ts b/src/commands/sync/args.tsindex 5623496743..7d7613021e 100644--- a/src/commands/sync/args.ts+++ b/src/commands/sync/args.ts@@ -128,7 +128,14 @@ Options:the host keeps one write consumer. This flag (orGBRAIN_SYNC_NO_DELEGATE=1) opts out: on Postgres thesync runs here beside the serve; on PGLite it fails- fast if a live serve holds the brain.+ fast if a live serve holds the brain. It never skips+ the drain lease: one drainer per managed source.+ --break-lock Release the source's sync lock (the managed drain+ lease) left by a holder that is gone: a dead pid on+ this host, or a heartbeat past its TTL. A live holder+ is never broken; --max-age <s> narrows it.+ --force-break-lock Release it without the liveness check (destructive:+ only when you have stopped the holder yourself).--no-schema-pack Skip loading the active schema pack (no per-file packregex runs; pages use legacy prefix typing). Escapehatch if a suspect pack regex is wedging sync.@@ -168,6 +175,15 @@ Options:until it is done, blocked, or this budget ends;progress never extends it. A stopped managed drainis 'resumable' (exit 0): rerun the same command.+ When another process is draining the source (a+ serve, a sync job, another terminal), the run follows+ it within this budget and its own deadline, printing+ the holder and the pages it commits; it takes over+ when the holder finishes. Out of budget it is+ 'resumable' with code sync_drain_lease_held; a holder+ that commits nothing for 5 minutes stops it blocked+ (drain_stalled). Ctrl-C stops following and leaves+ the holder alone.See docs/guides/live-sync.md (catching up a largebacklog on managed Postgres).--yes Accept any interactive prompts (CI / non-TTY).@@ -238,8 +254,6 @@ export function parseSyncFlags(args: string[]) {const skipFailed = args.includes('--skip-failed');const retryFailed = args.includes('--retry-failed'), resetCheckpoint = args.includes('--reset-checkpoint');const noSchemaPack = args.includes('--no-schema-pack'); // v0.41.37.0 #1569- const explicitProcessing = ([['--no-embed', 'noEmbed'], ['--no-extract', 'noExtract'], ['--no-schema-pack', 'noSchemaPack']] as const)- .filter(([flag]) => args.includes(flag)).map(([, key]) => key);const includeGitignored = args.includes('--include-gitignored');// Untracked-gap fix: --working-tree imports uncommitted working-tree state.// The config fallback (sync.include_working_tree) resolves inside@@ -291,7 +305,7 @@ export function parseSyncFlags(args: string[]) {console.error(`--max-age cannot be combined with --force-break-lock (force skips all guards).`);process.exit(1);}- return { repoPath, watch, interval, dryRun, full, noPull, noBulk, lanes, noEmbed, noExtract, skipFailed, retryFailed, resetCheckpoint, noSchemaPack, explicitProcessing, includeGitignored, workingTree, syncAll, missingPathMode, jsonOut, yesFlag, breakLock, forceBreakLock, maxAgeSeconds };+ return { repoPath, watch, interval, dryRun, full, noPull, noBulk, lanes, noEmbed, noExtract, skipFailed, retryFailed, resetCheckpoint, noSchemaPack, includeGitignored, workingTree, syncAll, missingPathMode, jsonOut, yesFlag, breakLock, forceBreakLock, maxAgeSeconds };}export type SyncFlags = ReturnType<typeof parseSyncFlags>;diff --git a/src/commands/sync/perform.ts b/src/commands/sync/perform.tsindex 26763b958b..5aeca59acf 100644--- a/src/commands/sync/perform.ts+++ b/src/commands/sync/perform.ts@@ -132,6 +132,7 @@ async function performManagedBranch(engine: BrainEngine, outer: SyncOpts): Promi...(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.`);}+ await printCursorAdoption(result, sourceId);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) {@@ -146,8 +147,14 @@ async function performManagedBranch(engine: BrainEngine, outer: SyncOpts): Promireturn 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).'),+ tty: process.stderr.isTTY === true,+ announce: (holder, phase) => {+ const who = holder ? `a ${holder.kind} drainer (pid ${holder.pid ?? '?'} on ${holder.host ?? '?'}${holder.version ? `, gbrain ${holder.version}` : ''})` : 'another drainer';+ const done = holder?.progress ? `${holder.progress.committed} page(s) committed since it started${holder.progress.last_committed_at ? `, last at ${holder.progress.last_committed_at}` : ''}` : 'progress unknown';+ serr(phase === 'start'+ ? `[sync] source ${sourceId} is being drained by ${who}; following it until it finishes or this run's budget ends (one drainer per source; it resumes the same cursor). Ctrl-C stops following and leaves it running.`+ : `[sync] following ${who}: ${done}.`);+ },}, work);} catch (err) {if (err instanceof LockUnavailableError && err.lockId === lockKey) throw new SyncLockBusyError(await formatLockBusyMessage(engine, lockKey), lockKey);@@ -155,6 +162,24 @@ async function performManagedBranch(engine: BrainEngine, outer: SyncOpts): Promi}}+/**+ * #6712 PR 1: the one-line notices of a resumed cursor. A run that finished another writer's (or another option set's)+ * unfinished run names that run's own options, and a kept opt-out names the command that settles what it skipped.+ */+async function printCursorAdoption(result: SyncResult, sourceId: string): Promise<void> {+ const adopted = result.cursorAdopted;+ if (adopted?.sync_options !== undefined) {+ const { managedSyncResumeArgs } = await import('../../core/sync-reconcile.ts');+ serr(`[sync] resumed the unfinished sync run of source ${sourceId}${adopted.writer_changed ? ' that another writer started' : ''}; it finishes under its own frozen options `+ + `(gbrain sync ${managedSyncResumeArgs({ sourceId, processingOptions: adopted.processing_options, syncOptions: adopted.sync_options }).join(' ')}), and the next run uses this run's.`);+ }+ const kept = result.inherited_options ?? [];+ if (!kept.length) return;+ const flags = { noEmbed: '--no-embed', noExtract: '--no-extract', noSchemaPack: '--no-schema-pack' } as const;+ const settle = [...(kept.includes('noEmbed') ? ['gbrain embed --stale'] : []), ...(kept.includes('noExtract') ? ['gbrain extract --stale'] : [])];+ serr(`[sync] kept the unfinished run's ${kept.map(key => flags[key]).join(' ')} for the pages it imports${settle.length ? `; ${settle.join(' and ')} settle${settle.length === 1 ? 's' : ''} them afterwards` : ''}.`);+}+/*** #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 failurediff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex cf04bfd125..4006786ada 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -484,6 +484,12 @@ export const CODES = {why: "Usually a dropped connection or a failed statement; the same error after a rerun is not transient. `detail: persistence_mode_unknown` (#6482): the persistence_brain singleton is missing, duplicated or carries a non-boolean `enabled`, so gbrain cannot tell whether the brain is managed and refuses every write, sync, connector run and activation step that depends on it rather than route a managed brain through the unmanaged writer; only a well-formed `enabled: false` row selects the unmanaged path.",suggestion: 'For persistence_mode_unknown: run gbrain sources writer status --probe --json on the brain host (it reports the malformed state instead of refusing), fix the persistence_brain row it names, then gbrain doctor --json.' },sync_not_applicable: { class: 'caller', summary: "Sync does not apply to this source: its directory is not a Git checkout.", why: "Sync imports changes between Git commits. A gbrain-owned content directory (created by init) holds files gbrain manages itself and is not a Git repository, so there is nothing to sync; gbrain never initializes Git on its own.", reasons: ['content_directory'] },+ // #6712 PR 1: the drain lease (src/core/persistence/sync-lease.ts).+ sync_drain_lease_held: { class: 'retryable', actor: 'provider',+ summary: "Another process holds the source's drain lease and is still committing pages; this run followed it until its own budget ended, or lost the lease mid-pass, and stopped `resumable`.",+ why: "One managed drainer per source: two drainers on one cursor raced each other's checkpoints. A follower counts the holder's commits as its own progress, takes the lease when the holder releases it, and stops `drain_stalled` (cause `no_progress`) instead when the holder commits nothing for 5 minutes, so a wedged holder never reads as a clean exit.",+ docs: 'docs/guides/write-refusals.md#sync_drain_lease_held',+ suggestion: 'Rerun next.command after next.retry_after_ms (safe_to_loop), or let the holder finish; Ctrl-C while following leaves the holder running.' },sync_in_progress: { class: 'retryable', summary: "A sync is running on this source, or a write in flight or the sync's frozen manifest still names the file a repair would write.",why: "A repair that changed a file the running sync admits later would make that entry refuse on its raw hash, and a file a write in flight names would be written twice; so the one candidate waits while the rest of the source is repaired. `candidate_in_flight`: the file is named; `busy_set_unreadable`: the busy set could not be read, so every candidate waited.",reasons: ['candidate_in_flight', 'busy_set_unreadable'],diff --git a/src/core/minions/handlers/sync.ts b/src/core/minions/handlers/sync.tsindex a3727f0e9e..fe28a1964c 100644--- a/src/core/minions/handlers/sync.ts+++ b/src/core/minions/handlers/sync.ts@@ -84,6 +84,22 @@ 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.+ // #6712 PR 1: the drain lease is the guard between processes of this build; this one still catches a job an older+ // worker runs during a rolling upgrade (it holds no lease). The lease's holder records are not jobs.+ 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 queue <> 'gbrain-drain-lease' 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, {@@ -106,7 +122,8 @@ export function makeSyncHandler(engine: BrainEngine): MinionHandler {if (err instanceof SyncLockBusyError) {// #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 read = await (await import('../../persistence/sync-lease.ts')).readDrainHolder(engine, id).catch(() => null);+ const holder = read && read.kind !== 'unknown' ? read : 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 } : {}),diff --git a/src/core/persistence/managed-retry-actions.ts b/src/core/persistence/managed-retry-actions.tsdeleted file mode 100644index 42bf39ee84..0000000000--- a/src/core/persistence/managed-retry-actions.ts+++ /dev/null@@ -1,82 +0,0 @@-/**- * The next action for each managed failure a `--retry-failed` run does not retry because another cursor key holds it- * (#6696 C3). A failure recorded before runs kept their options cannot name them, so "rerun with the same options"- * was a command nobody could run. Each row is classified instead:- *- * - `resumable`: the row recorded its options, or an option set reproduces its cursor key exactly (this run's options- * with and without the source's configured strategy and `--full`, or the options another cursor of the source- * recorded; the key is a digest, so a match is those options). The command is a `replay` when an unfinished run- * holds the key and a `fresh_discovery` (a new run from HEAD under those options, which clears the key's failures- * when it completes) when none does.- * - `orphaned`: the existing orphan repair names it (`classifyManagedSyncOrphans`): preview, then apply.- * - `unresolved`: nothing selects it now. A run whose request is still in flight is shown by `sync status`; otherwise a- * current run of the source completing supersedes the option-less cursor, and the orphan repair then retires it.- *- * Read-only.- */-import type { SyncOpts } from '../../commands/sync.ts';-import type { BrainEngine } from '../engine.ts';-import { currentCompanyBrainSync } from '../company-brain/profile.ts';-import { checkpointRetryCommand } from './checkpoint-validation.ts';-import { digest } from './digest.ts';-import { classifyManagedSyncOrphans } from './managed-sync-orphans.ts';-import { managedSyncAuthority } from './sync-authority.ts';-import { managedCursorKey } from './sync-cursor-key.ts';-import { resolveManagedSyncContext } from './sync-discovery.ts';-import type { ManagedSyncFailure } from './sync-failures.ts';-import type { SyncCursorOptions } from './sync-prepare.ts';-import { syncCursorOptions } from './sync-slices.ts';--export type ManagedRetryClass = 'resumable' | 'orphaned' | 'unresolved';-export type ManagedRetryLabel = 'replay' | 'fresh_discovery' | 'orphan_repair' | 'pending_request' | 'after_current_run';-export interface ManagedRetryAction { class: ManagedRetryClass; label: ManagedRetryLabel; command: string; failures: ManagedSyncFailure[] }--/** One action per distinct command, in the order the rows first need it. */-export async function managedRetryActions(engine: BrainEngine, opts: SyncOpts, failures: ManagedSyncFailure[]): Promise<ManagedRetryAction[]> {- if (!failures.length) return [];- const context = await resolveManagedSyncContext(engine, opts);- const { sourceId, incarnation } = context;- const authority = await managedSyncAuthority(engine, sourceId, incarnation, opts.repoPath ?? context.root);- const company = currentCompanyBrainSync(sourceId);- const unfinished = new Set((await engine.executeRaw<{ key: string }>(`SELECT fingerprint AS key FROM op_checkpoints WHERE op='managed-sync'- AND fingerprint=ANY($1::text[]) AND COALESCE(completed_keys->0->>'done','false')<>'true'`, [[...new Set(failures.map(f => f.cursor_key))]])).map(row => row.key));- const recorded = await engine.executeRaw<{ options: SyncCursorOptions }>(`SELECT DISTINCT completed_keys->0->'syncOptions' AS options FROM op_checkpoints- WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1 AND completed_keys->0->>'incarnation'=$2 AND completed_keys->0->'syncOptions' IS NOT NULL`, [sourceId, incarnation]);- const base = syncCursorOptions(opts);- const configured = typeof context.source.config?.strategy === 'string' ? context.source.config.strategy : null;- const candidates = company ? [] : [...[...new Set([base.strategy, configured, null])].flatMap(strategy => [false, true].map(full => ({ ...base, strategy, full }))),- ...recorded.map(row => row.options)];- const byKey = new Map(candidates.map(options => [managedCursorKey(incarnation, authority, company, options), options]));- const { orphans, retained } = await classifyManagedSyncOrphans(engine, [sourceId]);- const orphanKind = new Map(orphans.map(orphan => [orphan.cursor_key, orphan.kind]));- const pending = new Set(retained.filter(row => row.why === 'pending_request_live').map(row => row.cursor_key));- const actions = new Map<string, ManagedRetryAction>();- for (const failure of failures) {- const key = failure.cursor_key;- const options = failure.syncOptions ?? byKey.get(key);- const [cls, label, command]: [ManagedRetryClass, ManagedRetryLabel, string] = orphanKind.get(key) === 'unfinished_cursor' || (!options && orphanKind.has(key))- ? ['orphaned', 'orphan_repair', `gbrain repair managed-sync-orphans --source ${sourceId}`]- : options ? ['resumable', unfinished.has(key) ? 'replay' : 'fresh_discovery',- checkpointRetryCommand({ sourceId, processingOptions: failure.processingOptions, syncOptions: options, repoPath: opts.repoPath })]- : pending.has(key) ? ['unresolved', 'pending_request', `gbrain sync status --source ${sourceId} --json`]- : ['unresolved', 'after_current_run', `gbrain sync --source ${sourceId} --no-pull`];- const id = digest({ label, command });- const action = actions.get(id) ?? { class: cls, label, command, failures: [] };- action.failures.push(failure);- actions.set(id, action);- }- return [...actions.values()];-}--/** The human line for one action: count, class, what the command does, then the command last. */-export function formatManagedRetryAction(action: ManagedRetryAction): string {- const sourceId = action.failures[0]!.source_id;- const what: Record<ManagedRetryLabel, string> = {- replay: 'resumable (replay of the unfinished run under its recorded options)',- fresh_discovery: 'resumable (fresh discovery, not a replay: no unfinished run holds them; a new run from HEAD under the failed run\'s options clears them when it completes)',- orphan_repair: 'safely orphaned (nothing current can resume them; preview the repair, then apply it with the hash it prints)',- pending_request: 'unresolved (their run predates recorded options and its request is still in flight; this shows it)',- after_current_run: `unresolved (their run predates recorded options and no current option set selects it; once a current run of this source completes, gbrain repair managed-sync-orphans --source ${sourceId} retires them)`,- };- return `${action.failures.length} ${what[action.label]}: ${action.command}`;-}diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.tsindex 8ca60491ca..e56049390e 100644--- a/src/core/persistence/sync-drain.ts+++ b/src/core/persistence/sync-drain.ts@@ -116,6 +116,8 @@ export interface DrainStall {owner_kind?: string | null;owner_nonce?: string | null;last_sql?: ClaimLastSql | null;+ /** #6712 PR 1: the drain-lease holder a following run waited on (`no_progress`: it heartbeats but commits nothing). */+ lease_holder?: import('./sync-lease.ts').DrainHolder;/** #6317: the owner's heartbeat row, when the stop read one (`owner_wedged_here`). */owner_row?: DrainOwnerRow | null;/** #6317: whether the stop came at the ceiling (true) or on the owner's own wedged verdict before it (false), and the ceiling judged against. */@@ -578,7 +580,8 @@ 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 });+ if (result.leaseHeld) return result.drain?.stop_reason === 'drain_stalled' ? finish(result, 'blocked', 'drain_stalled', { stall: result.drain.stall })+ : 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');@@ -928,6 +931,20 @@ export function drainNext(result: SyncResult, resumeCommand: string, sourceId: swhy: 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 };}+ // #6712 PR 1: the drain-lease holder this run followed heartbeats but has committed nothing (and saved no cursor) for the+ // stall window. Waiting again would read as a clean exit on every tick, so this stops blocked with the holder named.+ if (d?.stop_reason === 'drain_stalled' && d.stall?.lease_holder) {+ const holder = d.stall.lease_holder, who = `the ${holder.kind} drainer${holder.pid ? ` (pid ${holder.pid}${holder.host ? ` on ${holder.host}` : ''})` : ''}`;+ const breakLock = `gbrain sync --source ${sourceId} --no-pull --break-lock`;+ return { command: `gbrain sources writer status --source ${sourceId} --json`, safe_to_loop: false, retry_after_ms: 0, ...estimate, code: 'drain_stalled', cause: 'no_progress',+ why: `Source ${sourceId}'s drain lease is held by ${who}${holder.version ? `, gbrain ${holder.version}` : ''}, which still heartbeats but has committed no page and saved no cursor for ${d.stall.stalled_seconds}s, `+ + `so this run stopped following it. Inspect the writer (read-only), then stop that process (or wait for it if it is a long discovery) and rerun: ${resumeCommand}. `+ + `Once it has exited, ${breakLock} releases a lease it left behind; it never breaks a live holder.`,+ fix: renderAction({ argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'], consent: [], actor: 'host_admin', requires_exclusive: false,+ why: 'Status names the source\'s writer, its step and the requests it holds, read-only.',+ user_message: `Source ${sourceId} is held by ${who}, which has made no progress for ${d.stall.stalled_seconds}s. Stop that process, then run: ${breakLock} and ${resumeCommand}`,+ verify: { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'] } }, cliRenderContext()), docs: ERROR_CATALOGUE.sync_drain_stalled.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-fault-class.ts b/src/core/persistence/sync-fault-class.tsindex 43611cb3d2..fcf8701ece 100644--- a/src/core/persistence/sync-fault-class.ts+++ b/src/core/persistence/sync-fault-class.ts@@ -82,6 +82,9 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [escalate: 'reason lifetime_ids (request ids never free, so only the host raise lifts it), or the pause outlasts a day' },{ code: 'capacity_paused', class: 'connection', safe_actions: ['retry'], needs_human: false,escalate: 'reason lifetime_ids (only the host raise resumes it), or the same pause after the raise' },+ // #6712 PR 1: another process holds the source's drain lease and is committing; a stalled holder ends drain_stalled instead.+ { code: 'sync_drain_lease_held', class: 'connection', safe_actions: ['retry'], needs_human: false,+ escalate: 'never: a holder that stops committing ends the run drain_stalled instead' },{ code: 'storage_error', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'the same error after a rerun (then it is not a dropped connection)' },// #6513: the engine-graduation fence (SQLSTATE 55000) refuses every write until the move finishes; the cursor and manifest stand.{ code: 'graduation_in_progress', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'gbrain migrate --status --json reports no running move and the fence still refuses' },diff --git a/src/core/persistence/sync-lease.ts b/src/core/persistence/sync-lease.tsindex 9ab09c7cae..0202eb24a1 100644--- a/src/core/persistence/sync-lease.ts+++ b/src/core/persistence/sync-lease.ts@@ -15,12 +15,21 @@* 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.+ * - **Reentrancy.** A pass inside a lease (the drain's passes, staged stages, a company catch-up) runs under it. A CLI+ * run hands itself to a serve before it takes the lease (`maybeDelegateManagedSyncToServe` runs first), so the serve's+ * run never follows the process that is waiting for it.+ * - **Older binaries.** A drainer older than this lease takes no lock, but its autopilot and its sync jobs back off from+ * a live `sync` job row (#6713's `liveSyncJob`). Every holder keeps its holder record as such a row+ * (`LEASE_BEACON_QUEUE`, no worker claims it) renewed with the lease and deleted on release, so nothing of the lease+ * is left in sync state once it is released; downgrade stays quiescent (stop serve, cron and jobs first), since an+ * older CLI run by hand ignores both.** 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).+ * budget, counting the holder's commits and cursor saves 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`; a holder that has made no progress for `HOLDER_STALL_MS` stops it `blocked` with+ * `drain_stalled` (cause `no_progress`) instead, so a wedged holder never reads as a clean exit on every cron tick.+ * Every other caller gets `SyncLockBusyError` (jobs and the cycle skip on it).*/import { AsyncLocalStorage } from 'node:async_hooks';import type { BrainEngine } from '../engine.ts';@@ -29,6 +38,7 @@ 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';+import { VERSION } from '../../version.ts';export const DRAIN_LEASE_TTL_MINUTES = 2;export const DRAIN_LEASE_REFRESH_MS = 20_000;@@ -37,13 +47,23 @@ 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';+/** The minion queue of the holder records (also the beacon older binaries' `liveSyncJob` sees); no worker serves it. */+export const LEASE_BEACON_QUEUE = 'gbrain-drain-lease';+/** A holder with no commit and no cursor save for this long is wedged (the in-pass governor's no-progress window). */+export const HOLDER_STALL_MS = 5 * 60_000;+/** How often a following run prints the holder's progress: on a terminal, and otherwise. */+const FOLLOW_REPORT_TTY_MS = 10_000, FOLLOW_REPORT_MS = 60_000;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 }+/** The holder's commits since it took the lease, and its last commit or cursor save. */+export interface DrainHolderProgress { committed: number; last_committed_at: string | null; last_progress_at: 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;+ /** The holder's gbrain version (null for a holder that predates it). */+ version: string | null; progress: DrainHolderProgress | null }+/** `safe_to_loop` and `retry_after_ms` are the `next` fields of the drain's other owner stops (`owner_wedged_here`). */+export interface DrainLeaseHeld { code: typeof SYNC_DRAIN_LEASE_HELD; holder: DrainHolder | null; retry_after_ms: number; safe_to_loop: true; lost?: true; fix: Action }interface DrainLease { lockId: string; sourceId: string; token: string }const leases = new AsyncLocalStorage<ReadonlyMap<string, DrainLease>>();@@ -70,12 +90,34 @@ const iso = (value: Date | null | undefined) => value ? value.toISOString() : nuexport 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;+ const [row] = await engine.executeRaw<{ meta: { kind?: DrainHolderKind; id?: string | null; version?: string } | string | null }>(+ "SELECT data->'drain_lease_beacon' AS meta FROM minion_jobs WHERE queue=$1 AND lock_token=$2", [LEASE_BEACON_QUEUE, snap.acquisition_token]).catch(() => []);+ const meta = typeof row?.meta === 'string' ? JSON.parse(row.meta) : row?.meta ?? 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) };+ started_at: iso(snap.acquired_at), last_heartbeat_at: iso(snap.last_refreshed_at), version: meta?.version ?? null,+ progress: await holderProgress(engine, sourceId, snap.acquired_at).catch(() => null) };+}++/** The source's managed-sync commits since `since`, and its last commit or cursor save at all. */+async function holderProgress(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, since: Date | null): Promise<DrainHolderProgress> {+ const [row] = await engine.executeRaw<{ committed: number | string; last_committed_at: Date | string | null; last_saved_at: Date | string | null }>(`+ SELECT (SELECT count(*) FROM persistence_requests r WHERE r.worktree_id=b.worktree_id AND r.state='committed'+ AND COALESCE(r.intent->>'kind','') LIKE 'managed_sync_%' AND r.completed_at >= $2::timestamptz) AS committed,+ (SELECT max(r.completed_at) FROM persistence_requests r WHERE r.worktree_id=b.worktree_id AND r.source_incarnation=b.source_incarnation+ AND r.state='committed' AND COALESCE(r.intent->>'kind','') LIKE 'managed_sync_%') AS last_committed_at,+ (SELECT max(c.updated_at) FROM op_checkpoints c WHERE c.op='managed-sync' AND c.completed_keys->0->>'sourceId'=$1) AS last_saved_at+ FROM persistence_source_bindings b WHERE b.source_id=$1`, [sourceId, (since ?? new Date(0)).toISOString()]);+ const at = (value: Date | string | null | undefined) => value == null ? null : new Date(value).toISOString();+ const committedAt = at(row?.last_committed_at), savedAt = at(row?.last_saved_at);+ return { committed: Number(row?.committed ?? 0), last_committed_at: committedAt,+ last_progress_at: [committedAt, savedAt].filter((value): value is string => !!value).sort().pop() ?? null };+}++/** A holder that has held the lease, and made no commit or cursor save, for `HOLDER_STALL_MS`. */+export function holderStalled(holder: DrainHolder | null, now = Date.now()): boolean {+ if (!holder?.started_at || !holder.progress) return false;+ const since = Math.max(Date.parse(holder.started_at), holder.progress.last_progress_at ? Date.parse(holder.progress.last_progress_at) : 0);+ return now - since >= HOLDER_STALL_MS;}/** What a remote caller may see of a holder: its kind and times, never its host, pid or job id. */@@ -86,17 +128,32 @@ export function leaseHeldResult(sourceId: string, holder: DrainHolder | null, opconst 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 progress = shown?.progress ? `, ${shown.progress.committed} page(s) committed since it took the lease${shown.progress.last_committed_at ? ` (last at ${shown.progress.last_committed_at})` : ''}` : '';+ 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}` : ''}${progress}; `+ + `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. `+ + `If the holder is gone, gbrain sync --source ${sourceId} --break-lock releases its lease (never a live holder's); gbrain sources writer status --source ${sourceId} --json shows the writer, read-only.`;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 },+ leaseHeld: { code: SYNC_DRAIN_LEASE_HELD, holder: shown, retry_after_ms: LEASE_RETRY_AFTER_MS, safe_to_loop: true, ...(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 } };}+/**+ * The `blocked` result of a follower whose holder heartbeats but has made no progress for `HOLDER_STALL_MS`: the drain's+ * own stall (`drain_stalled`, cause `no_progress`), naming the holder, so `drainNext` renders its escape steps.+ */+export function leaseStalledResult(sourceId: string, holder: DrainHolder, opts: { remote?: boolean } = {}): SyncResult {+ const shown = opts.remote ? redacted(holder)! : holder;+ const since = Math.max(Date.parse(holder.started_at ?? ''), holder.progress?.last_progress_at ? Date.parse(holder.progress.last_progress_at) : 0) || Date.now();+ const held = leaseHeldResult(sourceId, holder, opts);+ return { ...held, drain: { ...held.drain!, outcome: 'blocked', stop_reason: 'drain_stalled', retry_after_ms: 0,+ stall: { request_id: '', state: 'lease_held', blocked_reason: null, head_request_id: null, head_state: null, claimable_here: null, owner_is_this_host: null,+ stalled_seconds: Math.round((Date.now() - since) / 1000), cause: 'no_progress', owner_pid: shown.pid, owner_kind: shown.kind, owner_nonce: null, lease_holder: shown } } };+}+/*** 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@@ -110,13 +167,6 @@ export function followStopAt(startedAt: number, deadlineAtMs?: number): number {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; }@@ -132,32 +182,54 @@ export interface DrainLeaseOptions {follow?: { signal?: AbortSignal; deadlineAtMs?: number };remote?: boolean;resumeArgv?: string[];- /** Called once, when this run starts following a live holder. */- announce?: (holder: DrainHolder | null) => void;+ /** Called when this run starts following a live holder, then every 10 s on a terminal (60 s otherwise) while it follows. */+ announce?: (holder: DrainHolder | null, phase: 'start' | 'progress') => void;+ tty?: boolean;+}++/**+ * The holder record: one `gbrain-drain-lease` minion row per lease, keyed by the lease token, carrying the holder's+ * kind, id and version. It doubles as the beacon an older binary's `liveSyncJob` sees, so an older autopilot backs off+ * while any holder drains. Application authority keeps it out of the unreviewed-job gate; `max_stalled` 0 and+ * `remove_on_fail` drop a dead holder's row instead of queueing it. It is renewed with the lease and deleted on release.+ */+async function writeHolderRecord(engine: BrainEngine, sourceId: string, lease: DrainLease, holder: DrainHolderRef): Promise<void> {+ await engine.executeRaw(`DELETE FROM minion_jobs WHERE queue=$1 AND name='sync' AND data->>'sourceId'=$2`, [LEASE_BEACON_QUEUE, sourceId]);+ await engine.executeRaw(`INSERT INTO minion_jobs(name,queue,status,submission_authority,data,max_attempts,max_stalled,lock_token,lock_until,started_at,remove_on_complete,remove_on_fail)+ VALUES('sync',$1,'active','{"version":1,"kind":"application"}'::jsonb,$2::text::jsonb,1,0,$3,now()+make_interval(mins => $4),now(),true,true)`,+ [LEASE_BEACON_QUEUE, JSON.stringify({ sourceId, drain_lease_beacon: { kind: holder.kind, id: holder.id ?? null, version: VERSION } }), lease.token, DRAIN_LEASE_TTL_MINUTES]);}/*** 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`.+ * `leaseHeldResult`, and a holder stalled for `HOLDER_STALL_MS` returns `leaseStalledResult`.*/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;+ let seen: string | undefined, reportedAt = 0;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));+ await writeHolderRecord(engine, sourceId, lease, opts.holder);+ const beacon = setInterval(() => {+ void engine.executeRaw(`UPDATE minion_jobs SET lock_until=now()+make_interval(mins => $3),updated_at=now() WHERE queue=$1 AND lock_token=$2`,+ [LEASE_BEACON_QUEUE, lease.token, DRAIN_LEASE_TTL_MINUTES]).catch(() => undefined);+ }, DRAIN_LEASE_REFRESH_MS);+ beacon.unref?.();+ try {+ await faultPoint('sync:lease_acquired', { sourceId });+ const store = new Map(leases.getStore() ?? []);+ store.set(lockId, lease);+ return await leases.run(store, () => work(signal));+ } finally {+ clearInterval(beacon);+ await engine.executeRaw('DELETE FROM minion_jobs WHERE queue=$1 AND lock_token=$2', [LEASE_BEACON_QUEUE, lease.token]).catch(() => undefined);+ }}, { ttlMinutes: DRAIN_LEASE_TTL_MINUTES, refreshIntervalMs: DRAIN_LEASE_REFRESH_MS });} catch (error) {if (error instanceof LockStolenError && error.lockId === lockId) {@@ -166,14 +238,16 @@ export async function withDrainLease(engine: BrainEngine, sourceId: string, optsif (!(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 holder = await readDrainHolder(engine, sourceId).catch(() => null);+ if (seen === undefined) { opts.announce?.(holder, 'start'); reportedAt = Date.now(); }+ else if (Date.now() - reportedAt >= (opts.tty ? FOLLOW_REPORT_TTY_MS : FOLLOW_REPORT_MS)) { opts.announce?.(holder, 'progress'); reportedAt = Date.now(); }+ // The holder's commits and cursor saves are this run's forward progress: the progress-aware watchdog window extends with them.+ const now = `${holder?.started_at ?? ''}|${holder?.progress?.committed ?? ''}|${holder?.progress?.last_progress_at ?? ''}`;+ if (seen !== undefined && now !== seen) noteForwardProgress();+ seen = now;+ if (holder && holderStalled(holder)) return leaseStalledResult(sourceId, holder, { remote: opts.remote });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;+ if (follow.signal?.aborted || Date.now() >= stopAt) return leaseHeldResult(sourceId, holder, { remote: opts.remote, resumeArgv: opts.resumeArgv });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.tsindex fa3f1a9f38..ece292da02 100644--- a/src/core/persistence/sync-movement.ts+++ b/src/core/persistence/sync-movement.ts@@ -104,7 +104,8 @@ interface HoldRow { count: number | string | null; stalled: number | string | nuexport 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()+ // The lease's beacon row (sync-lease.ts) is for older binaries; this build reads the lease holder above.+ const [row] = await engine.executeRaw<{ id: number | string }>(`SELECT id FROM minion_jobs WHERE name='sync' AND status='active' AND lock_until > now() AND queue <> 'gbrain-drain-lease'AND (COALESCE(data->>'sourceId', data->>'source_id')=$1 OR (COALESCE(data->>'sourceId', data->>'source_id') IS NULLAND (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(() => []);return row ? Number(row.id) : null;diff --git a/test/persistence-sync-lease.test.ts b/test/persistence-sync-lease.test.tsnew file mode 100644index 0000000000..2fce7d4ea3--- /dev/null+++ b/test/persistence-sync-lease.test.ts@@ -0,0 +1,237 @@+import { afterAll, afterEach, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { 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, SyncResult } from '../src/commands/sync.ts';+import { performSync } from '../src/commands/sync/perform.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { DRAIN_LEASE_TTL_MINUTES, HOLDER_STALL_MS, LEASE_BEACON_QUEUE, followStopAt, readDrainHolder, withDrainLease } from '../src/core/persistence/sync-lease.ts';+import { drainNext } from '../src/core/persistence/sync-drain.ts';+import { liveSyncJob } from '../src/core/persistence/sync-movement.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { syncLockId, tryAcquireDbLock } from '../src/core/db-lock.ts';+import { SyncLockBusyError } from '../src/core/sync-lock.ts';+import { noteForwardProgress, registerRunDeadline } from '../src/core/forward-progress.ts';+import { withEnv } from './helpers/with-env.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++// #6712 PR 1: the drain lease. One managed drainer per source, whoever started it, fenced on the lock's acquisition+// token; a plain CLI sync follows a live holder within its budget instead of draining beside it. Each test here fails on+// the base (no lease: both drainers run, nothing is fenced, nothing is followed).++const home = mkdtempSync(join(tmpdir(), 'gbrain-sync-lease-'));+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 () => {+ 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); registerRunDeadline(null); });+afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, 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) {+ const id = `lease-${randomUUID().slice(0, 12)}`, root = join(home, id);+ mkdirSync(root); git(root, 'init', '-q');+ for (const name of ['a', 'b', 'c']) 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 isolated = (fn: (engine: BrainEngine) => Promise<void>) => withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {+ for (const engine of engines) await fn(engine);+});+const plain = (sourceId: string, extra: Partial<SyncOpts> = {}): SyncOpts => ({ sourceId, noPull: true, noEmbed: true, noExtract: true, ...extra });+const done = (): SyncResult => ({ status: 'up_to_date', fromCommit: null, toCommit: '', added: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [] });+/** A holder that keeps the lease until `release()`; `started` resolves once it holds it. */+function hold(engine: BrainEngine, sourceId: string, kind: 'serve' | 'cli' | 'job' = 'serve') {+ let release!: () => void, started!: () => void;+ const gate = new Promise<void>(resolve => { release = resolve; });+ const ready = new Promise<void>(resolve => { started = resolve; });+ const result = withDrainLease(engine, sourceId, { holder: { kind, id: kind === 'job' ? '4242' : `${kind}-example` } }, async () => { started(); await gate; return done(); });+ return { ready, release: () => { release(); return result; } };+}+const managedRows = async (engine: BrainEngine, id: string) => ({+ cursors: (await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [id])).length,+ requests: (await engine.executeRaw('SELECT 1 FROM persistence_requests WHERE source_id=$1', [id])).length,+});++test('the lease is the per-source sync lock with a short TTL a dead holder loses inside one cron tick', async () => isolated(async engine => {+ const id = await fixture(engine);+ const holder = hold(engine, id);+ await holder.ready;+ const [row] = await engine.executeRaw<{ ttl_seconds: number }>('SELECT extract(epoch from ttl_expires_at - acquired_at)::int AS ttl_seconds FROM gbrain_cycle_locks WHERE id=$1', [syncLockId(id)]);+ expect(row!.ttl_seconds).toBe(DRAIN_LEASE_TTL_MINUTES * 60);+ expect(DRAIN_LEASE_TTL_MINUTES * 60_000 + 60_000).toBeLessThan(15 * 60_000);+ expect(await readDrainHolder(engine, id)).toMatchObject({ kind: 'serve', id: 'serve-example', pid: process.pid, version: expect.any(String), progress: { committed: 0 } });+ await holder.release();+ expect(await engine.executeRaw('SELECT 1 FROM gbrain_cycle_locks WHERE id=$1', [syncLockId(id)])).toHaveLength(0);+}), 120_000);++test('a job, the cycle and sync_brain skip a busy lease with SyncLockBusyError; a nested pass inside the lease runs under it', async () => isolated(async engine => {+ const id = await fixture(engine);+ const holder = hold(engine, id);+ await holder.ready;+ await expect(performSync(engine, plain(id, { drainHolder: { kind: 'job', id: '7' } }))).rejects.toBeInstanceOf(SyncLockBusyError);+ await holder.release();+ // Reentrancy: a pass inside a held lease (a drain's passes, staged stages) never follows itself.+ const nested = await withDrainLease(engine, id, { holder: { kind: 'cli' } }, () => performManagedSync(engine, plain(id)));+ expect(nested.status).toBe('first_sync');+}), 120_000);++test('a plain sync follows a live holder, takes the lease when it releases and drains', async () => isolated(async engine => {+ const id = await fixture(engine);+ const holder = hold(engine, id);+ await holder.ready;+ const lines: string[] = [];+ const origError = console.error;+ console.error = (...args: unknown[]) => { lines.push(args.map(String).join(' ')); };+ let followed: Promise<SyncResult>;+ try {+ followed = performSync(engine, plain(id, { followDrainLease: true, drainHolder: { kind: 'cli', id: null } }));+ await new Promise(resolve => setTimeout(resolve, 3000));+ expect(await managedRows(engine, id)).toEqual({ cursors: 0, requests: 0 });+ await holder.release();+ expect((await followed).status).toBe('first_sync');+ } finally { console.error = origError; }+ expect(lines.join('')).toContain('is being drained by a serve drainer');+ expect(lines.join('')).toContain('Ctrl-C stops following and leaves it running');+ expect(await engine.getPage('c', { sourceId: id })).not.toBeNull();+}), 120_000);++test('out of budget the follower is resumable with sync_drain_lease_held, the holder, and a wait fix', async () => isolated(async engine => {+ const id = await fixture(engine);+ const holder = hold(engine, id);+ await holder.ready;+ const result = await performSync(engine, plain(id, { followDrainLease: true, deadlineAtMs: Date.now() + 3000 }));+ expect(result).toMatchObject({ status: 'partial', reason: 'drain_lease_held', drain: { outcome: 'resumable', stop_reason: 'drain_lease_held' },+ leaseHeld: { code: 'sync_drain_lease_held', safe_to_loop: true, retry_after_ms: 60_000,+ holder: { kind: 'serve', id: 'serve-example', pid: process.pid, host: expect.any(String), started_at: expect.any(String), last_heartbeat_at: expect.any(String),+ version: expect.any(String), progress: { committed: 0 } } } });+ expect(result.leaseHeld!.fix.why).toContain('--break-lock');+ const next = drainNext(result, `gbrain sync --source ${id} --no-pull`, id);+ expect(next).toMatchObject({ code: 'sync_drain_lease_held', safe_to_loop: true, retry_after_ms: 60_000, fix: { next: 'wait' } });+ expect(await managedRows(engine, id)).toEqual({ cursors: 0, requests: 0 });+ await holder.release();+}), 120_000);++test('Ctrl-C stops following at once and leaves the holder holding the lease', async () => isolated(async engine => {+ const id = await fixture(engine);+ const holder = hold(engine, id);+ await holder.ready;+ const token = async () => (await engine.executeRaw<{ t: string }>('SELECT acquisition_token::text AS t FROM gbrain_cycle_locks WHERE id=$1', [syncLockId(id)]))[0]?.t;+ const before = await token();+ const interrupt = new AbortController();+ setTimeout(() => interrupt.abort(new Error('SIGINT')), 500);+ const started = Date.now();+ const result = await performSync(engine, plain(id, { followDrainLease: true, signal: interrupt.signal }));+ expect(Date.now() - started).toBeLessThan(10_000);+ expect(result.leaseHeld?.code).toBe('sync_drain_lease_held');+ expect(await token()).toBe(before!);+ await holder.release();+}), 120_000);++test('a holder that heartbeats but makes no progress for the stall window stops the follower blocked, not resumable', async () => isolated(async engine => {+ const id = await fixture(engine);+ const holder = hold(engine, id, 'cli');+ await holder.ready;+ await engine.executeRaw(`UPDATE gbrain_cycle_locks SET acquired_at=now()-make_interval(secs => $2) WHERE id=$1`, [syncLockId(id), HOLDER_STALL_MS / 1000 + 60]);+ const result = await performSync(engine, plain(id, { followDrainLease: true, deadlineAtMs: Date.now() + 30_000 }));+ expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled', stall: { cause: 'no_progress', owner_kind: 'cli', lease_holder: { kind: 'cli' } } });+ const next = drainNext(result, `gbrain sync --source ${id} --no-pull`, id);+ expect(next).toMatchObject({ code: 'drain_stalled', cause: 'no_progress', safe_to_loop: false });+ expect(next?.why).toContain('--break-lock');+ await holder.release();+}), 120_000);++test('fencing: a pass whose lease was taken over after its TTL admits nothing and advances no checkpoint', async () => isolated(async engine => {+ const id = await fixture(engine);+ let thief: Awaited<ReturnType<typeof tryAcquireDbLock>> = null;+ installFaultHook(async (point, detail) => {+ if (point !== 'sync:lease_acquired' || detail.sourceId !== id || thief) return;+ // The holder pauses past its TTL (no heartbeat inside the steal grace) and another process takes the lease over.+ await engine.executeRaw(`UPDATE gbrain_cycle_locks SET ttl_expires_at=now()-interval '1 minute', last_refreshed_at=now()-interval '1 hour' WHERE id=$1`, [syncLockId(id)]);+ thief = await tryAcquireDbLock(engine, syncLockId(id), DRAIN_LEASE_TTL_MINUTES);+ expect(thief).not.toBeNull();+ });+ const stale = await performSync(engine, plain(id));+ installFaultHook(undefined);+ expect(stale).toMatchObject({ reason: 'drain_lease_held', leaseHeld: { lost: true } });+ expect(await managedRows(engine, id)).toEqual({ cursors: 0, requests: 0 });+ await thief!.release();+ expect((await performSync(engine, plain(id))).status).toBe('first_sync');+}), 120_000);++test('the follower stops before the process watchdog: the lesser of its deadline and the hard deadline, less a margin', () => {+ const now = Date.now();+ registerRunDeadline({ atMs: now + 13 * 60_000, strict: true });+ expect(followStopAt(now)).toBe(now + 13 * 60_000 - 30_000);+ expect(followStopAt(now, now + 60_000)).toBe(now + 60_000 - 30_000);+ expect(followStopAt(now, now + 20_000)).toBe(now + 10_000);+ // The non-TTY window extends while progress arrives (a holder's commits count as this run's progress).+ registerRunDeadline({ atMs: now + 60_000, strict: false, progressWindowMs: 10 * 60_000 });+ noteForwardProgress();+ expect(followStopAt(now)).toBeGreaterThan(now + 9 * 60_000);+});++// The cron recipe doctor prints (`gbrain sync --all --no-pull --hard-deadline 13m`) against a live serve holder: it follows the+// serve instead of refusing or draining beside it, and finishes the source once the serve's drain ends.+test('doctor\'s cron recipe follows a live serve holder and finishes the source; --no-delegate does not bypass the lease', async () => isolated(async engine => {+ const id = await fixture(engine);+ await engine.executeRaw("UPDATE sources SET config=jsonb_set(config,'{syncEnabled}','false'::jsonb) WHERE id<>$1", [id]);+ const holder = hold(engine, id, 'serve');+ await holder.ready;+ const { runSync } = await import('../src/commands/sync.ts');+ const lines: string[] = [], exits: number[] = [];+ const origError = console.error, origLog = console.log, origExit = process.exit;+ console.error = (...args: unknown[]) => { lines.push(args.map(String).join(' ')); };+ console.log = (...args: unknown[]) => { lines.push(args.map(String).join(' ')); };+ process.exit = ((code?: number) => { exits.push(code ?? 0); throw new Error(`process.exit(${code})`); }) as typeof process.exit;+ try {+ // The recipe as doctor prints it, plus --no-embed (this test brain has no embedding provider key) and --no-delegate.+ const cron = runSync(engine, ['--all', '--no-pull', '--hard-deadline', '13m', '--no-embed', '--no-delegate']).catch((error: unknown) => error);+ await new Promise(resolve => setTimeout(resolve, 3000));+ expect(await managedRows(engine, id)).toEqual({ cursors: 0, requests: 0 });+ await holder.release();+ await cron;+ } finally { console.error = origError; console.log = origLog; process.exit = origExit; }+ expect({ exits, lines: exits.length ? lines : [] }).toEqual({ exits: [], lines: [] });+ expect(await engine.getPage('c', { sourceId: id })).not.toBeNull();+}), 180_000);++// Older binaries take no lease, but their autopilot and sync jobs back off from a live `sync` job row (#6713). The+// query below is master's `liveSyncJob` before this change, verbatim.+test('a holder that is not a sync job is visible to an older binary\'s liveSyncJob, and only while it holds the lease', async () => isolated(async engine => {+ const id = await fixture(engine);+ const legacyLiveSyncJob = async () => (await engine.executeRaw<{ id: number }>(`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`, [id]))[0]?.id ?? null;+ expect(await legacyLiveSyncJob()).toBeNull();+ const holder = hold(engine, id, 'cli');+ await holder.ready;+ expect(await legacyLiveSyncJob()).not.toBeNull();+ // This build reads the lease itself; the beacon is not a job it reports.+ expect(await liveSyncJob(engine, id)).toBeNull();+ await holder.release();+ expect(await legacyLiveSyncJob()).toBeNull();+ expect(await engine.executeRaw('SELECT 1 FROM minion_jobs WHERE queue=$1', [LEASE_BEACON_QUEUE])).toHaveLength(0);+ // A sync job holder's record names the job, and liveSyncJob reports the job itself, not the record row.+ const job = hold(engine, id, 'job');+ await job.ready;+ expect(await engine.executeRaw("SELECT data->'drain_lease_beacon'->>'id' AS id FROM minion_jobs WHERE queue=$1", [LEASE_BEACON_QUEUE])).toEqual([{ id: '4242' }]);+ expect(await liveSyncJob(engine, id)).toBe(4242);+ await job.release();+ expect(await engine.executeRaw('SELECT 1 FROM minion_jobs WHERE queue=$1', [LEASE_BEACON_QUEUE])).toHaveLength(0);+}), 120_000);