Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): managed sync jobs drain to their deadline instead of one page per job (#6706)

garrytanf2d7ca67cdad
diff --git a/docs/architecture/key-files/core-minions-1.md b/docs/architecture/key-files/core-minions-1.md
index f1091a7fad..dc138f9bbb 100644
--- a/docs/architecture/key-files/core-minions-1.md
+++ b/docs/architecture/key-files/core-minions-1.md
@@ -4,7 +4,7 @@
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
- `src/core/minions/` — Minions job queue: BullMQ-inspired, Postgres-native (queue, worker, backoff, types, protected-names, quiet-hours, handlers/shell). Private dream-inline-* queues carry an explicit lifecycle: owner job id + owner token + a renewable lease (columns on minion_jobs; `queue.ts` `reconcilePrivateQueue` terminalizes one queue through the normal cancelJobs bookkeeping and stamps every cancellation with the machine-readable `private_queue_reconciled:` reason family; `renewPrivateQueueLease` is MONOTONIC — GREATEST — so a default-horizon renewal can never shrink a creation-time lease; `reconcileOrphanedPrivateQueues` cancels only provably-orphaned queues: no healthy child lock, owner terminal/missing or lease expired; legacy unowned rows are left to Doctor/retriage; `classifyPrivateQueueForRecovery` is PUBLIC so the doctor orphan check buckets through the same verdict). Recovery runs in `gbrain jobs work` after driver/selected-child readiness and `ensureSchema`, for bare AND supervised workers (including autopilot spawns/respawns); the standalone parent does not recover queues in `beforeSpawn`. `maybeRunWorkerStartupRecovery(queue, process.env, true)` keeps this worker-owned ordering even under `GBRAIN_SUPERVISED=1`. Dream-cycle start also recovers (cycle.ts, next to the cycle lock reap — the ONLY lane on PGLite, which inlines every child). `deriveWedgeSignal` is queue-aware: a dream-inline queue is never 'wedged' (no shared worker can claim it) — it reports `private_queue: true` so jobs stats / get_job_stats / doctor all point at reconciliation instead of the impossible worker restart.
-- `src/core/minions/handlers/sync.ts` (and the other built-in job handler modules: `embed`, `lint`, `lint-fix`, `extract`, `extract-conversation-facts`, `chronicle-extract`, `loops-extract`, `enrich`, `integrity`, `integrity-auto`, `sync-retry-failed`, `import`, `backlinks`, `facts-absorb`, `autopilot-cycle`, `autopilot-global-maintenance`, `reindex`, `repair-jsonb`, `orphans`, `purge`, `cycle-phase`, `extract-atoms-drain`, `extract-ner`, `extract-takes-from-pages`, `extract-timeline-from-meetings`, `embed-catch-up`, `unify-types`, plus `job-pull.ts`) — one module per built-in handler body, each a `make<Name>Handler(engine)` factory (or a `MinionHandler` const when it needs no engine). Registered in a fixed order by `registerBuiltinHandlers` in `src/commands/jobs.ts`, which keeps the registration kind (plain vs gateway-refreshing) and wrappers such as `withFactsAbsorbHaltCooldown`; `cycle-phase.ts` serves the six phase wrappers. Command cores are imported lazily inside each handler. `resolveJobPull` and the facts-absorb retry predicates are re-exported from `jobs.ts`. `autopilot-global-maintenance` runs one `runCycle` call per maintenance phase and keeps its pass position in config `autopilot.global_maintenance.progress`: it stops starting a phase whose last measured duration would cross the job deadline (minus a 60 s reserve), the next job resumes at that phase, and a phase still marked running when an earlier job died is skipped for the rest of the pass; last_global_at is stamped only when a pass completes with no blocking phase. The deadline comes from `GBRAIN_GLOBAL_MAINTENANCE_TIMEOUT_MS` > `autopilot.global_maintenance_timeout_ms` > the autopilot default (`autopilot-fanout.ts:resolveGlobalMaintenanceTimeoutMs`); doctor `global_maintenance_timeouts` (`doctor/checks/global-maintenance-timeouts.ts`) warns after three consecutive deaths and names `gbrain dream --phase <name>` (`autopilot-global-maintenance-resume-4578.test.ts`). The `sync` handler runs performSync under `job.signal` composed with `job.shutdownSignal`: under a signal owner (`jobs work`, the supervisor) SIGTERM skips the cleanup pass and aborts only the worker's shutdown signal, so the sync and its `git pull` (async `pullRepo` on `bounded-child-exec.ts`) stop and the job is handed back without burning an attempt. A queued `autopilot_freshness` sync job re-reads its source when it runs and returns `{skipped:true, reason:'sync_disabled'}` when the source now has `syncEnabled:false`; explicit sync jobs still run and a failed lookup falls through to syncing (`sync-handler-sync-enabled.test.ts`).
+- `src/core/minions/handlers/sync.ts` (and the other built-in job handler modules: `embed`, `lint`, `lint-fix`, `extract`, `extract-conversation-facts`, `chronicle-extract`, `loops-extract`, `enrich`, `integrity`, `integrity-auto`, `sync-retry-failed`, `import`, `backlinks`, `facts-absorb`, `autopilot-cycle`, `autopilot-global-maintenance`, `reindex`, `repair-jsonb`, `orphans`, `purge`, `cycle-phase`, `extract-atoms-drain`, `extract-ner`, `extract-takes-from-pages`, `extract-timeline-from-meetings`, `embed-catch-up`, `unify-types`, plus `job-pull.ts`) — one module per built-in handler body, each a `make<Name>Handler(engine)` factory (or a `MinionHandler` const when it needs no engine). Registered in a fixed order by `registerBuiltinHandlers` in `src/commands/jobs.ts`, which keeps the registration kind (plain vs gateway-refreshing) and wrappers such as `withFactsAbsorbHaltCooldown`; `cycle-phase.ts` serves the six phase wrappers. Command cores are imported lazily inside each handler. `resolveJobPull` and the facts-absorb retry predicates are re-exported from `jobs.ts`. `autopilot-global-maintenance` runs one `runCycle` call per maintenance phase and keeps its pass position in config `autopilot.global_maintenance.progress`: it stops starting a phase whose last measured duration would cross the job deadline (minus a 60 s reserve), the next job resumes at that phase, and a phase still marked running when an earlier job died is skipped for the rest of the pass; last_global_at is stamped only when a pass completes with no blocking phase. The deadline comes from `GBRAIN_GLOBAL_MAINTENANCE_TIMEOUT_MS` > `autopilot.global_maintenance_timeout_ms` > the autopilot default (`autopilot-fanout.ts:resolveGlobalMaintenanceTimeoutMs`); doctor `global_maintenance_timeouts` (`doctor/checks/global-maintenance-timeouts.ts`) warns after three consecutive deaths and names `gbrain dream --phase <name>` (`autopilot-global-maintenance-resume-4578.test.ts`). The `sync` handler runs performSync under `job.signal` composed with `job.shutdownSignal`: under a signal owner (`jobs work`, the supervisor) SIGTERM skips the cleanup pass and aborts only the worker's shutdown signal, so the sync and its `git pull` (async `pullRepo` on `bounded-child-exec.ts`) stop and the job is handed back without burning an attempt. A queued `autopilot_freshness` sync job re-reads its source when it runs and returns `{skipped:true, reason:'sync_disabled'}` when the source now has `syncEnabled:false`; explicit sync jobs still run and a failed lookup falls through to syncing (`sync-handler-sync-enabled.test.ts`). #6706: managed jobs drain via `sync-job-drain.ts`.
- `src/core/minions/admission.ts` — submit-side queue admission control (the drain-side pool-starvation half is the job-isolation work; claim fairness is a filed TODO, deliberately out of scope). Three primitives resolved per name via `resolveAdmissionPolicy` (config `minions.*` > per-name defaults tables, 60s in-process cache, fail-open with a once-per-process stderr warn; env kill-switch `GBRAIN_MINIONS_ADMISSION=0` disables all three): PARAM-COALESCING (`PARAM_COALESCE_DEFAULT` — on for `subagent`; `computeParamHash` = sha256 of stable-stringified payload excluding only `__param_hash` itself — `__owner_client_id` is deliberately INCLUDED so owner lanes never cross; parentless + waiting-only + age-bounded to ttl/2), WAITING-TTL (`WAITING_TTL_DEFAULT_HOURS` — 48h for `subagent`; swept by `MinionQueue.handleWaitingTTL` through `cancelJobs(ids, {reason, rootStatuses:['waiting']})` so descendants cancel, child_done lands, aggregator parents resolve, and the reason stamps ROOT ids only; ≤500/tick oldest-first; warn-before-act is `runWaitingTtlTick` — first tick counts affected + stamps `TTL_NOTICE_SHOWN_KEY` with an ISO timestamp, sweeping starts only after `ttlNoticeGraceMs()` (1h default, env `GBRAIN_MINIONS_TTL_NOTICE_GRACE_MS`) elapses; `gbrain upgrade` prints the same one-shot notice and starts the same clock; legacy `'true'` flag values sweep immediately), and NAME-GLOBAL QUOTA (`QUOTA_MAX_WAITING_DEFAULT` EMPTY by operator decision — activates only via `minions.quota_max_waiting.<name>`; counts the name across ALL queues so per-run `dream-inline-*` fanout queues can't dodge it, EXACT under concurrency via a `minion_quota:<name>` advisory xact lock taken only when a quota is configured; throws typed `QueueQuotaExceededError`, checked everywhere via `isQueueQuotaExceededError` — dream submitters record a phase skip, synthesize rolls back the current transcript's fresh chunks, agent fanout cancels the whole tree, `submit_agent` maps to a structured `rate_limited` OperationError). `TTL_REASON_PREFIX` is the single source for the sweep's error_text prefix and the stats/doctor LIKE patterns; `safeConfigSegment` gates untrusted job names out of copy-pasteable config hints. Alerting rides `getStats` (`drained_completed/failed/dead/cancelled` keyed on finished_at + `waiting_now` + `oldest_waiting_minutes`), the `jobs stats` DIVERGENT-QUEUE / waiting-TTL screams (`GBRAIN_QUEUE_DIVERGENCE_RATIO`=2, `GBRAIN_QUEUE_DIVERGENCE_MIN_WAITING`=50; divergence compares intake vs COMPLETED so TTL-cancel storms can't masquerade as throughput) + `--json`, and doctor `checkQueueHealth`. Pinned by `test/minions-admission.test.ts` + `test/jobs-stats-divergence.serial.test.ts`.
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index 135d3fc00a..da3c37cdff 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -12,7 +12,7 @@
- `src/core/persistence/{maintenance,root-registry,filesystem-guard,writer-guard-schema}.ts` — fail-closed legacy writer coverage: durable private refusal records and shared refusal-only root markers work before PGLite connect, resolve symlink ancestors, and retain stale roots conservatively. An unchanged per-tick refresh writes nothing: the registry directory and records are chmodded only when their mode differs and the directory is fsynced only when a record changed (`root-registry-idle-chmod-5297.test.ts`). The selected PGLite path is registered at connect/init and source claim refresh, so managed reinit refuses even offline; unmanaged backup acquires the stable sibling native lock through rename. SQL guards include free-text aliases and canonical source sync checkpoints; an update that changes only embedding, telemetry or write-attribution columns of facts/takes is a physical projection and passes without the coordinator. `docs/architecture/canonical-writers.tsv` is the finite writer census; `canonical-writer-inventory.test.ts` rejects unreviewed additions, and `persistence-writer-fences.test.ts`/`pglite-maintenance-fence.test.ts` exercise real engines, competing processes and separate homes.
-- **`src/core/persistence/sync-drain.ts`** — #5984: drains a managed sync in one invocation. `runDrain` re-enters the single-pass `performManagedSync` (which keeps returning `partial / writer_pending | writer_yield`) until the cursor is done, the caller's signal stops it, a strict registered run deadline is about 15 s away (`forward-progress.ts` `registerRunDeadline`, set by `cli.ts` when it arms the sync watchdog), a writer head needs intervention (`recovery_required`, `owner_unavailable`, unexpected bytes), or the no-progress detector sees the awaited request and its worktree head unchanged for 30 s and 3 passes with nothing claimable here. It retries only `worktree_refreshing` (its `retry_after_ms`), `database_contention`, connection errors and statement timeouts (3 attempts). Every page commit notes forward progress, so the progress-aware watchdog never stops a progressing drain. The result carries `drain: { outcome: synced | resumable | blocked, stop_reason, written, waived, remaining, rate_pages_per_min, eta_seconds, stall }`; `drainNext` builds `next` for the CLI from the shared `syncResumeCommand` (`sync-reconcile.ts`). The CLI (`sync/run.ts` single source, `--all`, `--watch`) sets `SyncOpts.drain`; the PGLite owner delegate uses `runDrain` over IPC; jobs, serve, the cycle, `sync-administration.ts` and `worktree-refresh.ts` keep their own loops. `readManagedSyncBacklog` reads unfinished cursors' `progress` window (stamped by `sync-run.ts` on each advance, reset per drain) for `gbrain doctor` (`managed_sync_backlog`) and `sources status`, with `resume_args` built by `sync-reconcile.ts` `managedSyncResumeArgs`. #6278: the no-progress fingerprint keys on state, blocked reason, head id/state and the head claim's phase/step/since (`drainClaimOf`), never on lease columns, so a renewed-forever claim reads as no progress; a live preparation is allowed its budget plus `STALL_GRACE_MS` (budgets read from `persistence.*_preparation_ms` / `preparation_ceiling_ms`), a lapsed claim keeps the plain window (`stall.cause: owner_missing`), a preparation this process's pid owns past its allowance ends `resumable` / `preparation_abandoned`, and `SyncResult.breaker` ends `blocked` / `preparation_systemic`; `stall` carries `phase`, `step`, `waiting_on`, `cause`, and a timer prints `stalled <N>s on <step>` while nothing commits: between passes from the fingerprint's claim, inside a pass (a grouped publish parked in preparation never returns to the loop) from `StallProbe.head`, a 2 s-bounded read of the source's oldest running (else queued) request that prints nothing when no write is unfinished (B6). B7: a pass refused for write capacity (`isWriteCapacityWait`, `admission-retry.ts`: a `queue_capacity` whose `detail` is `outstanding=N limit=M`) is retried with backoff up to 5 s apart while the drain prints `waiting for write capacity (N outstanding of M)`; past the no-progress window it ends `blocked` / `write_capacity` with `drain.capacity` and writer status as `next`, keeping the last pass's result (or an empty one) for the report; a cumulative cap still throws. A pass that finishes one cursor and yields for a scheduled re-screen starts a new run on the next pass, and the report sums the page counts of every run it finished. Tests: `test/sync-drain.test.ts`, `test/sync-drain-claims.test.ts`, `test/managed-sync-drain.test.ts`, `test/sync-drain-write-capacity.test.ts`.
+- **`src/core/persistence/sync-drain.ts`** — #5984: drains a managed sync in one invocation. `runDrain` re-enters the single-pass `performManagedSync` (which keeps returning `partial / writer_pending | writer_yield`) until the cursor is done, the caller's signal stops it, a strict registered run deadline is about 15 s away (`forward-progress.ts` `registerRunDeadline`, set by `cli.ts` when it arms the sync watchdog), a writer head needs intervention (`recovery_required`, `owner_unavailable`, unexpected bytes), or the no-progress detector sees the awaited request and its worktree head unchanged for 30 s and 3 passes with nothing claimable here. It retries only `worktree_refreshing` (its `retry_after_ms`), `database_contention`, connection errors and statement timeouts (3 attempts). Every page commit notes forward progress, so the progress-aware watchdog never stops a progressing drain. The result carries `drain: { outcome: synced | resumable | blocked, stop_reason, written, waived, remaining, rate_pages_per_min, eta_seconds, stall }`; `drainNext` builds `next` for the CLI from the shared `syncResumeCommand` (`sync-reconcile.ts`). The CLI (`sync/run.ts` single source, `--all`, `--watch`), serve's delegated runner and the `sync` job handler (#6706, bounded by `SyncOpts.deadlineAtMs`) set `SyncOpts.drain`; the PGLite owner delegate uses `runDrain` over IPC; the cycle, `sync-administration.ts` and `worktree-refresh.ts` keep their own loops. #6706: `runDrain` takes a caller `deadlineAtMs` (the earlier of it and the strict run deadline wins; a past deadline makes zero passes; a far one re-arms past the 2^31−1 ms timer limit), reports `resumable / deadline` when the deadline lands in a retry backoff, abandons a pass still running `DEADLINE_PASS_GRACE_MS` after it, and `deadlinePassed` stops the extra pass and the next stage; `jobDisposition` classifies a drained result for jobs (`synced`, `continue` when `drainNext` is safe to loop, `needs_operator`). `src/core/minions/handlers/sync-job-drain.ts` runs it in the `sync` job: `planJobDrain` (`drain`, `lanes: 1`, a deadline from `job.deadlineAtMs` or the row's wall-clock limit via `WALL_CLOCK_THRESHOLD_MS_SQL`, at most an hour, less 60 s; job-data controls only from trusted submitters; `sync.job_drain=false` turns it off), throttled progress, and `settleJobDrain` (the CLI's `outcome`/`drain`/`next`, `incomplete`, at most one continuation on a worker-backed brain, priority ≥ 5, whose `next` then observes it). A sync job that finds another live sync job on its source skips `sync_in_progress` (`sync-handler-drain-6706.test.ts`). `readManagedSyncBacklog` reads unfinished cursors' `progress` window (stamped by `sync-run.ts` on each advance, reset per drain) for `gbrain doctor` (`managed_sync_backlog`) and `sources status`, with `resume_args` built by `sync-reconcile.ts` `managedSyncResumeArgs`. #6278: the no-progress fingerprint keys on state, blocked reason, head id/state and the head claim's phase/step/since (`drainClaimOf`), never on lease columns, so a renewed-forever claim reads as no progress; a live preparation is allowed its budget plus `STALL_GRACE_MS` (budgets read from `persistence.*_preparation_ms` / `preparation_ceiling_ms`), a lapsed claim keeps the plain window (`stall.cause: owner_missing`), a preparation this process's pid owns past its allowance ends `resumable` / `preparation_abandoned`, and `SyncResult.breaker` ends `blocked` / `preparation_systemic`; `stall` carries `phase`, `step`, `waiting_on`, `cause`, and a timer prints `stalled <N>s on <step>` while nothing commits: between passes from the fingerprint's claim, inside a pass (a grouped publish parked in preparation never returns to the loop) from `StallProbe.head`, a 2 s-bounded read of the source's oldest running (else queued) request that prints nothing when no write is unfinished (B6). B7: a pass refused for write capacity (`isWriteCapacityWait`, `admission-retry.ts`: a `queue_capacity` whose `detail` is `outstanding=N limit=M`) is retried with backoff up to 5 s apart while the drain prints `waiting for write capacity (N outstanding of M)`; past the no-progress window it ends `blocked` / `write_capacity` with `drain.capacity` and writer status as `next`, keeping the last pass's result (or an empty one) for the report; a cumulative cap still throws. A pass that finishes one cursor and yields for a scheduled re-screen starts a new run on the next pass, and the report sums the page counts of every run it finished. Tests: `test/sync-drain.test.ts`, `test/sync-drain-claims.test.ts`, `test/managed-sync-drain.test.ts`, `test/sync-drain-write-capacity.test.ts`.
- **`src/core/persistence/sync-window.ts`** — #5984 admit-ahead for draining managed Postgres syncs. While the cursor's `group` publishes, `admitAhead` (`sync-run.ts`) freezes and admits the next group and records it in the cursor's `window` (at most one group), so the consumer claims it as soon as the publishing group commits under the unchanged per-worktree FIFO claim. Window members name the previous group's last request in `intent.after`. `cancelOrphanedWindowGroup` runs before the consumer prepares a claimed group: a window group whose predecessor did not commit is cancelled (`WINDOW_CANCEL_MESSAGE`), never published after a failed page. Publication validation (`sync-prepare.ts`) re-checks the predecessor once per transaction and reads the cursor `FOR KEY SHARE`, accepting `pending`, `group` and `window` members, so the drain's cursor saves never wait for the publishing group. After a failed page the drain cancels the window's queued members (`cancelWindow`) and drops the window; resume re-freezes those entries. Nothing is admitted ahead while foreground writes are recent (one was queued on the worktree in the last minute, `FOREGROUND_RECENT_MS`) or when the next entry is not groupable. Older binaries refuse a window member they did not admit (cursor membership), so a mixed-version drain fails closed instead of publishing twice; finish a drain before downgrading. A claimed head is ordered by `claimedPredecessorState`: a group member follows the member before it in its own group (its `after` names only the previous group), anything else follows `after`. `claimedHeadOrder` (the consumer, before claiming followers) cancels a head whose predecessor ended without committing, and under lanes a member whose predecessor is unfinished releases its claim and waits; `cancelOrphanedLaneRows` uses the same rule, so a member released mid-group (its group fell back to the single path and an earlier member went back to the queue) never publishes after that member fails. Test: `test/sync-group-member-order.test.ts`. #6402: a group head whose window predecessor was not admitted is cancelled naming it.
- **`src/core/persistence/sync-lanes.ts`** + **`worktree-lease.ts`** — #5984 lanes. The drain opens a lane policy for its worktree (`openLanes`, keyed by a per-drain run id that lane groups carry as `intent.lane`; `closeLaneRun` at drain end stops new lane claims and waits up to 90 s for the lane tasks still running, counted from the head's claim by `laneTask`; the drain then cancels its run's still-queued rows whose predecessor ended without committing, `cancelOrphanedLaneRows` in sync-window.ts, so a blocked drain never reports while one of its groups is still publishing, aborting or released). While it is open, this process's consumer claims the next admitted lane group head out of FIFO order (`claimNextLaneHead` in journal.ts: every earlier request claimed, any unfinished one a running request of the same run) up to the effective lane count (`laneRoots`), and runs it as a lane (`executeClaimedGroup` with `lane`). Lane publications share the worktree's native lock in this process (`acquireWorktreeShared` / `worktree-lease.ts`; one lane acquires the lock while lanes arriving meanwhile wait and join, and a lease stays registered until its lock is released); every exclusive `acquireWorktree` first yields the lease (marks it draining and wounded, waits up to its budget), and a lease drains for new claims after `LEASE_TURN_MS` of continuous holding. Lane transactions begin in manifest order (`awaitLaneBegin`) and commit in manifest order (`awaitLaneTurn`, inside the transaction before the counters: the predecessor `intent.after` must be committed; a failed one cancels the group, a requeued or unadmitted one releases it, a wounded lease or 60 s rolls it back). Publication validation accepts a lane group whose predecessor is still queued or running (`windowPredecessorAllows`). `laneFallback` in group-publish.ts cancels, releases or falls back to the single path, and a lock or statement timeout steps the lane count down (`stepDownLanes`). Lane settings (`--lanes`/`--no-lanes` > `GBRAIN_SYNC_LANES` > `sync.lanes` > 6, clamped to the pool's long-hold capacity minus 3) resolve in `resolveBulkSettings` (sync-group.ts); with lanes the drain keeps twice the lane count of groups admitted ahead (`admitAhead`).
- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. A completed discovery that finds nothing to do (`up_to_date`) stamps only `sources.last_sync_at`, inside `withCoordinatedWrite` and guarded by source id and incarnation, so a quiet managed source stays fresh in doctor and a run that outlived a re-added source stamps nothing; dry runs and partial runs do not stamp. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. A resume adopts the stored options for every option the caller did not set explicitly (`SyncOpts.explicitProcessing`: CLI flags, wire flags, job params; autopilot and the cycle set none); an explicit conflict refuses with `detail: cursor_processing_options_conflict`, the stored options and the exact resume command. Callers that omit `explicitProcessing` stay strict. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts, also when the run has a recorded failure and its pending write already committed before the cursor advanced; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. Content holds (#5988, `sync-screen.ts`): `freezeEntry` screens each import (company-profile cursors and `sync.holds=fail` excepted); a refused file becomes a hold written in the same transaction as the cursor step (`saveCursor`'s `inTx`), with no request admitted, and an over-bound pinned blob is held by size before it is read. A cursor whose pending request failed with a content refusal (`isContentRefusal`, old message shapes included) converts in place with its stored options: held, or re-frozen once per distinct bytes (`converted`), so a refusal the screen misses stays blocked without minting receipts. #6188: a failed fence refusal (`fenceReceiptLocation`: the durable `error_detail.fence`, the message, or an older release's message) holds the same bytes even when the screen admits them (`prepareTimeFenceHold`, reason `prepare_time`); a compacted `invalid_params` / `take_row_collision` receipt converts only when the re-screen holds. A page request of the run that fails with a fence refusal is held in the same invocation at the terminal-failure branch (single path and a bulk group's failed member) after the source's other requests settle within the run's wait budget, else the run returns `partial`; it is converted once, gets no failure-ledger row and is logged as a conversion. `sync.holds=fail` and company-profile cursors keep blocking with the typed refusal. #6278: a `preparation_stalled` receipt (the owner gave up preparing a member) is converted the same way by both converters: an import holds by its bytes, a delete as a delete hold (`meta.deleted`, `upstream_version` null), the checkpoint never holds; `preparationStalledHold` (sync-screen.ts) records the receipt's step and the resume arguments. Both converters write their hold through `holdUnderGate`, the narrowed gate: the failed entry's admitted suffix (window, later group members, this run's queued lane rows) is cancelled first, then the hold waits only for active suffix descendants and unfinished requests naming the entry's page (`UNFINISHED_PAGE_REQUEST_SQL`, now matching path and origin too), evaluated inside the transaction that writes the hold under the page-key → cursor lock order; its doc comment states the invariant the old source-wide wait protected. The cursor's `breaker` counts the run's stalled receipts (identities and streak, saved with each CAS): `holdsEscalated`'s rule over the run's screened imports or `BREAKER_STREAK` (5) in a row trips it, the run stops `blocked_by_failures` with `SyncResult.breaker` (drain `preparation_systemic`), and the next run's `convertBlockedCursor` re-freezes the entry and schedules the run's stalled holds for a re-screen instead of holding; a committed page resets the streak. `sameContentAtOrigin` and the waiver screens race the sync preparer against `persistence.sync_preparation_ms` (`raceSyncBudget`, sync-waivers.ts) and fail open. Tests: `test/managed-sync-preparation-stalled-holds.test.ts`, `test/sync-waiver-budget.test.ts`. Results carry this run's holds, the outstanding total, escalation, `converted_from_failed` and `recovered_frontmatter` (`buildHoldReport`); dry runs list `would_hold` / `screen_skipped`. After the checkpoint commits (and unless `noExtract`), the owner derives links for the source's stale pages through `links-maintenance.ts`, so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync. #6278 (B7): when the checkpoint commits while `sources retry-held` re-screens are scheduled for the source (scheduled against a backlog, or while this cursor ran), the pass returns `partial` / `writer_yield` instead of `synced`, so the drain's next pass retires the finished cursor and discovers again, taking them; a `queue_capacity` refused for outstanding requests (`isWriteCapacityWait`) is left out of the failure ledger because the drain waits it out.
diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.md
index 5b50e8a23f..5fe8392981 100644
--- a/docs/guides/live-sync.md
+++ b/docs/guides/live-sync.md
@@ -114,6 +114,7 @@ Timing knobs the drain uses:
| `persistence.max_preparation_attempts` | Deadline releases (and reclaims after a kill while preparing) one request may spend. | 2 (1–10) | The next claim finishes it `preparation_stalled` without preparing again. |
| `preparation_deadlines` write switch (`persistence.preparation_deadlines`, `GBRAIN_PREPARATION_DEADLINES`) | Kill switch for the four keys above and the attempt counter. `remember`, `put_page` and `edit_page` keep their own 30 s budget either way. | on | `gbrain config set persistence.preparation_deadlines false` (or `GBRAIN_PREPARATION_DEADLINES=0`) restores the previous behaviour exactly: no deadline on sync or maintenance writes, no counter, no `preparation_stalled` holds. A running `serve` picks the change up within 5 seconds. |
| Page write wait | One page's (or group's) publication before the drain re-checks. | 30 s inside a drain (5 s, checkpoint 8 s, for a single pass) | The drain re-enters; this is not a stop. |
+| `sync` job deadline | A managed `sync` Minions job's drain: its `timeout_ms` (autopilot stamps `max(2 × --interval, 300 s)`), or the queue's wall-clock limit for a job without one, capped at an hour, less a 60 s reserve. `sync.job_drain=false` (or job data `drain: false`) keeps the single pass. | per job | Stops as `resumable` / `deadline`; on a worker-backed brain a stop that is safe to repeat queues one follow-up job (`continuation_job_id`). |
| `sync.bulk_max_txn_ms` / `GBRAIN_SYNC_BULK_MAX_TXN_MS` | Target time per bulk group; sizes the next group from the last one's time per page. | 15000 | A smaller next group. |
| `sync.bulk_size` / `GBRAIN_SYNC_BULK_SIZE` | Largest bulk group. | 16 | — |
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index 1316fa02f0..1000a9c089 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -12,6 +12,7 @@
| Symptom | Next step | Who acts | Consent | Verify |
|---|---|---|---|---|
+| A managed source's autopilot freshness `sync` jobs each land about one page, or `sources status` says `parked` while a sync job runs | upgrade (#6706: sync jobs drain to their deadline and count as the source's live drain), then restart `gbrain jobs work` / the supervisor so the worker loads the handler; a job result with `incomplete: true` names its follow-up (`continuation_job_id`) or the next step in `next` | agent | none | `gbrain sync status --source <id> --json` shows `live_job_id` or a cursor at `done`; `gbrain jobs get <id> --json` shows `outcome` |
| Recall returns conversation facts like "Date said …", "Attendees said …" or "Summary said …" | `gbrain repair conversation-labels` previews them ([conversation labels](repair.md#conversation-labels)); apply the printed command with `--yes` | agent, after the user agrees | `destructive` | `gbrain doctor --only conversation_label_facts --json` is ok |
| Conversation facts are dated 1970-01-01 | same preview: `gbrain repair conversation-labels` (an undated page's pre-fix facts carry a `segment 1970-01-01` context); add a `date:` to the page frontmatter before re-extracting it | agent, after the user agrees | `destructive` | `gbrain doctor --only conversation_label_facts --json` is ok |
| `remember` or `put_page` refused `source_changed` "The canonical file contains an uncoordinated local edit" on many pages nobody edited, or doctor `lost_caller_writes` warns | upgrade to v0.60.157.0 or later (a database-only v0.13.1 `validate: false` stamp was read as a file edit, #6429); then `gbrain repair failed-writes --source <id>` previews the refused writes and prints the apply command ([failed writes](repair.md#failed-writes)) | agent; the apply after the user agrees | none to preview | `gbrain doctor --only lost_caller_writes --json` is ok |
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index b92e854ea5..b7c638a58c 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -474,7 +474,7 @@ retry_after_ms, eta_seconds, rate_pages_per_min, why, docs }`. Run
| Stop reason | Code | Outcome | What it means | Recovery |
| --- | --- | --- | --- | --- |
-| <a id="drain-stopped-at-its-deadline"></a>`deadline` | `writer_pending` | `resumable` | `--timeout`, `--hard-deadline`, Ctrl-C or the run deadline stopped the drain. Accepted page writes keep their request IDs and the cursor is intact. | Rerun `next.command` (the same options). It resumes where the last run stopped. |
+| <a id="drain-stopped-at-its-deadline"></a>`deadline` | `writer_pending` | `resumable` | `--timeout`, `--hard-deadline`, Ctrl-C or the run deadline stopped the drain, or a `sync` job reached its own deadline (its `timeout_ms` less a 60 s reserve). Accepted page writes keep their request IDs and the cursor is intact. | Rerun `next.command` (the same options). It resumes where the last run stopped. A `sync` job that queued a follow-up (`continuation_job_id`) names it in `next` instead: watch it, don't start a second sync beside it. |
| <a id="drain-stalled"></a>`drain_stalled` | `drain_stalled` | `blocked` | The awaited page write and the oldest unfinished write on its checkout made no progress for the whole stall window: no committed receipt and no step advance. A lease renewal is not a change: the detector keys on the head claim's phase and step. With a live owner on **this host**, the drain does not stop at the allowance (the preparation budget plus 30 s): from there it prints `stalled <N>s on <step>` with the owner's pid and kind every 10 s and keeps going, because the owner's own budget frees the root by `persistence.preparation_ceiling_ms` (600 s) and the next pass holds the entry. It stops `drain_stalled` only when the ceiling passes without the root being released, or when the owner's `persistence_consumers` row reads wedged (`restart_required`, or a root barrier older than the ceiling); the stop then carries `cause: owner_wedged_here`, the owner `{kind, pid, nonce}`, `retry_after_ms` (the time left to the ceiling, 0 once past), `next.safe_to_loop: true` while the ceiling is ahead and `next.fix.next` `wait` before it, `tell_user_to_run` (restart the named pid) after it. A lapsed claim (`owner_missing`) stops at once, unless this host owns the checkout and a live full consumer exists, which gets exactly one more window. Other causes: `preparation_overdue` / `publication_overdue` (a live owner elsewhere past its allowance) and `no_progress` (an unstamped head). A pass that never returns is stopped from inside (`drain.stall.in_pass: true`, the same rules whether or not the drain prints progress): a head claim live in `publishing` past `persistence.publication_ceiling_ms` (default 300 s) stops `publication_overdue`, and its `next` says to restart the process that owns the publication, because an unfinished publish can hold its locks until it settles and nothing reclaims it for you; a pass that admitted nothing and left no unfinished request for 5 minutes stops `no_admission` with the step it was in (`freeze`, `waiver_run`, `admission`, `await_receipt`) and the last statement label, which is what a transaction-mode pooler that never answers a round trip looks like. A serve-delegated `no_admission` continues once with the CLI's own consumer. The owner process bounds its own publish the same way: past the ceiling the claim reads `waiting_on: publication_deadline`, a Postgres publish transaction idle past it is ended by the server (nothing commits), 30 s later a Postgres publish still running is cancelled (its connection is discarded, nothing commits, and the write is queued again), and a publish that still has not settled 35 s after the ceiling makes the owner report `restart_required` (its heartbeat row carries `restart_required`, which the drain reads as `owner_wedged_here`; the consumer status lists it under `stuck_publications`); restart that process. `drain.stall` carries `phase`, `step`, `waiting_on`, `cause`, the owner and whether this host owns the checkout. | `gbrain sources writer status --source <source> --json`: its `next_action` says whether to wait (`retry_after_ms`) or which pid to restart. Before the ceiling, rerun `next.command` after `retry_after_ms` (safe in a loop). Past it, or with a wedged owner, restart the named owner process (`gbrain serve`, the jobs worker or autopilot) on the brain host, then rerun `next.command`; the held entry needs `gbrain sources retry-held <source>` afterwards. When this host is not the owner, make sure the owner's `gbrain serve` is running. |
| <a id="drain-database-contention"></a>`database_contention` | `database_contention` | `blocked` (or an error) | Three consecutive passes hit database contention, a statement timeout or a dropped connection, or reading the awaited write's state failed (an authentication or permission failure stops at once). The drain retries transient failures with backoff before giving up. Accepted writes keep their request IDs. | Fix database access (`gbrain engine status --probe`), then rerun `next.command`. |
| <a id="drain-writer-blocked"></a>`recovery_required`, `owner_unavailable`, `unexpected_file_bytes`, `unexpected_staging_bytes` | `recovery_required` | `blocked` | The checkout's writer needs intervention before more pages can publish: interrupted publication recovery, no live owner, or unexpected bytes in the file or staging area. | `gbrain sources writer status <source>` and the fix it prints. Unexpected bytes are the user's edits; ask before discarding them. Then rerun `next.command`. |
diff --git a/llms-full.txt b/llms-full.txt
index 9d6654018a..72bef2b8bf 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -6665,6 +6665,7 @@ Timing knobs the drain uses:
| `persistence.max_preparation_attempts` | Deadline releases (and reclaims after a kill while preparing) one request may spend. | 2 (1–10) | The next claim finishes it `preparation_stalled` without preparing again. |
| `preparation_deadlines` write switch (`persistence.preparation_deadlines`, `GBRAIN_PREPARATION_DEADLINES`) | Kill switch for the four keys above and the attempt counter. `remember`, `put_page` and `edit_page` keep their own 30 s budget either way. | on | `gbrain config set persistence.preparation_deadlines false` (or `GBRAIN_PREPARATION_DEADLINES=0`) restores the previous behaviour exactly: no deadline on sync or maintenance writes, no counter, no `preparation_stalled` holds. A running `serve` picks the change up within 5 seconds. |
| Page write wait | One page's (or group's) publication before the drain re-checks. | 30 s inside a drain (5 s, checkpoint 8 s, for a single pass) | The drain re-enters; this is not a stop. |
+| `sync` job deadline | A managed `sync` Minions job's drain: its `timeout_ms` (autopilot stamps `max(2 × --interval, 300 s)`), or the queue's wall-clock limit for a job without one, capped at an hour, less a 60 s reserve. `sync.job_drain=false` (or job data `drain: false`) keeps the single pass. | per job | Stops as `resumable` / `deadline`; on a worker-backed brain a stop that is safe to repeat queues one follow-up job (`continuation_job_id`). |
| `sync.bulk_max_txn_ms` / `GBRAIN_SYNC_BULK_MAX_TXN_MS` | Target time per bulk group; sizes the next group from the last one's time per page. | 15000 | A smaller next group. |
| `sync.bulk_size` / `GBRAIN_SYNC_BULK_SIZE` | Largest bulk group. | 16 | — |
@@ -10181,6 +10182,7 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro
| Symptom | Next step | Who acts | Consent | Verify |
|---|---|---|---|---|
+| A managed source's autopilot freshness `sync` jobs each land about one page, or `sources status` says `parked` while a sync job runs | upgrade (#6706: sync jobs drain to their deadline and count as the source's live drain), then restart `gbrain jobs work` / the supervisor so the worker loads the handler; a job result with `incomplete: true` names its follow-up (`continuation_job_id`) or the next step in `next` | agent | none | `gbrain sync status --source <id> --json` shows `live_job_id` or a cursor at `done`; `gbrain jobs get <id> --json` shows `outcome` |
| Recall returns conversation facts like "Date said …", "Attendees said …" or "Summary said …" | `gbrain repair conversation-labels` previews them ([conversation labels](repair.md#conversation-labels)); apply the printed command with `--yes` | agent, after the user agrees | `destructive` | `gbrain doctor --only conversation_label_facts --json` is ok |
| Conversation facts are dated 1970-01-01 | same preview: `gbrain repair conversation-labels` (an undated page's pre-fix facts carry a `segment 1970-01-01` context); add a `date:` to the page frontmatter before re-extracting it | agent, after the user agrees | `destructive` | `gbrain doctor --only conversation_label_facts --json` is ok |
| `remember` or `put_page` refused `source_changed` "The canonical file contains an uncoordinated local edit" on many pages nobody edited, or doctor `lost_caller_writes` warns | upgrade to v0.60.157.0 or later (a database-only v0.13.1 `validate: false` stamp was read as a file edit, #6429); then `gbrain repair failed-writes --source <id>` previews the refused writes and prints the apply command ([failed writes](repair.md#failed-writes)) | agent; the apply after the user agrees | none to preview | `gbrain doctor --only lost_caller_writes --json` is ok |
diff --git a/src/commands/autopilot-dispatch.ts b/src/commands/autopilot-dispatch.ts
index 6adbaf5c60..bc66f86c60 100644
--- a/src/commands/autopilot-dispatch.ts
+++ b/src/commands/autopilot-dispatch.ts
@@ -299,6 +299,8 @@ export async function dispatchFreshnessSyncs(
const lastSyncMs = src.last_sync_at ? new Date(src.last_sync_at).getTime() : 0;
const ageMs = now - lastSyncMs;
if (ageMs < intervalMs) continue; // fresh enough
+ // #6706: a live sync job (any submitter) is already draining this source; coalescing into another submitter's row is refused.
+ if (await (await import('../core/persistence/sync-movement.ts')).liveSyncJob(engine, src.id) !== null) continue;
try {
const job = await queue.add(
'sync',
@@ -314,7 +316,9 @@ export async function dispatchFreshnessSyncs(
idempotency_key: `autopilot-sync:${src.id}:${slot}`,
max_attempts: 2,
timeout_ms: timeoutMs,
- maxWaiting: 1,
+ // #6706: single-flight per source. A sync job drains until synced or its deadline, so a tick while one runs
+ // coalesces into it (waiting or live-lock active) instead of starting a second drainer on the same cursor.
+ maxPending: 1,
},
);
if (jsonMode) {
diff --git a/src/commands/jobs.ts b/src/commands/jobs.ts
index 1d83690b6f..efd2902307 100644
--- a/src/commands/jobs.ts
+++ b/src/commands/jobs.ts
@@ -233,7 +233,7 @@ USAGE
gbrain jobs supervisor --json --allow-shell-jobs # JSONL events + shell-exec on
HANDLER TYPES (built in)
- sync Pull and embed new pages from the repo
+ sync Pull and import new pages from the repo; on a managed brain it drains to the job's deadline (--timeout-ms)
embed (Re-)embed pages; --params '{"slug":...}' or '{"all":true}'
lint Run page linter; --params '{"dir":"...","fix":true}'
import Bulk import markdown; --params '{"dir":"..."}'
diff --git a/src/commands/sources-writer-movement.ts b/src/commands/sources-writer-movement.ts
index 817f885426..9ee6d91578 100644
--- a/src/commands/sources-writer-movement.ts
+++ b/src/commands/sources-writer-movement.ts
@@ -141,7 +141,7 @@ export function movementReport(before: SourceMovement | undefined, after: Source
why: 'Resumes the managed catch-up where its cursor stopped; the same command is safe to rerun in a loop.', verify }, ctx), before, after };
case 'not_moving':
return { source_id: id, state, exit: 1, code: 'managed_sync_not_moving', reason: 'movement_check',
- why: `${id}: ${after.cursor ? `${after.cursor.remaining} entries pending, ` : ''}no page committed and no step advance inside the ${Math.round(windowMs / 1000)}s window while ${after.live.drain ? `a sync (pid ${after.live.drain_pid}) holds the lock` : 'a consumer is live'}; last progress ${after.last_progress_at ?? 'unknown'}.${head}`,
+ why: `${id}: ${after.cursor ? `${after.cursor.remaining} entries pending, ` : ''}no page committed and no step advance inside the ${Math.round(windowMs / 1000)}s window while ${after.live.drain ? after.live.drain_job_id !== null && after.live.drain_pid === null ? `sync job #${after.live.drain_job_id} is draining it` : `a sync (pid ${after.live.drain_pid}) holds the lock` : 'a consumer is live'}; last progress ${after.last_progress_at ?? 'unknown'}.${head}`,
fix: renderAction({ ...status, verify }, ctx), before, after };
}
}
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index 931fd56e28..e9598df1ef 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -343,10 +343,10 @@ export interface SyncOpts {
/**
* #5984: managed sync only. Re-enter the single-pass managed sync until the
* cursor is done, the caller's signal/deadline stops it, or it is blocked
- * (src/core/persistence/sync-drain.ts). Set by the CLI; jobs and library
- * callers keep the single-pass contract.
+ * (src/core/persistence/sync-drain.ts). Set by the CLI, serve and the `sync` job (#6706); others stay single-pass.
*/
drain?: 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;
/** #5984: `--no-bulk`; and the drain's resolved bulk settings (internal; absent = one request per pass step). */ noBulk?: boolean; bulk?: import('../core/persistence/sync-group.ts').BulkSettings;
diff --git a/src/commands/sync/perform.ts b/src/commands/sync/perform.ts
index 7ba1ff0503..d373df18ff 100644
--- a/src/commands/sync/perform.ts
+++ b/src/commands/sync/perform.ts
@@ -63,7 +63,10 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<
: 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.`);
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 72773c7d8f..1d505b667a 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -570,6 +570,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.231.0', text: '`get_chunks` now returns a page\'s chunks 50 at a time in chunk_index order instead of all of them. Pass `from_index` and `limit` (up to 500 over MCP) to read further. The result is still a list; `_meta.pagination` reports `total_chunks` and `next_from_index`, and MCP callers get a `listing_truncated` notice naming the next call when more chunks remain. The local CLI prints a stderr hint when the default cut the list.' },
{ since: '0.60.231.0', text: '`get_versions` (`gbrain history`) now returns metadata only for the newest 20 versions by default: id, snapshot time, title, type, tags and frontmatter, without `compiled_truth` or `timeline`. Pass `include_body: true` for the bodies (still filtered for remote callers) and a larger `limit` for older versions (up to 100 over MCP; the local CLI honors any limit). When older versions exist, `_meta.pagination` says so and MCP callers get a `listing_truncated` notice. `gbrain history` shows each version\'s title when no body was requested; `revert_version` is unchanged.' },
{ since: '0.60.231.0', text: 'Short page leads (exact-slug and alias search snippets, relational-recall synopses, reflex pointer synopses, entity card summaries, entity-name leads, and think\'s anchor and date-window page rows) now read only the first 64 KiB of a page, respect fact withdrawals, and mask private-key text as a token. Think\'s anchor and date-window rows carry at most 64 KiB of page text instead of the whole page. Output for ordinary small pages is unchanged.' },
+ { since: '0.60.231.0', text: 'A `sync` Minions job on a managed brain (autopilot freshness and hand-submitted jobs) now drains its catch-up like `gbrain sync` instead of landing about one page per job: it keeps publishing (bulk groups, one lane) until the source is synced or the job\'s own deadline less a 60 s reserve (its `timeout_ms`, or the queue\'s wall-clock limit for a job without one, at most an hour), so a job now holds a worker slot up to that deadline. When it stops with work left and the stop is safe to repeat, it queues one follow-up `sync` job (`continuation_job_id`, priority 5, behind waiting embeds) on a worker-backed brain. Freshness dispatch is single-flight per source (`maxPending: 1`), and a sync job that starts while another is draining the same source completes as `skipped: sync_in_progress` with `running_job_id` and a `next` that watches it. The job result now carries the CLI\'s `outcome`, `drain` and `next` plus `incomplete` (a queued follow-up\'s `next` observes it; a remotely submitted job\'s `next` asks for a new job or the host operator), keeps the first 50 `pagesAffected` and `held` entries with `pages_affected_count` / `held_count`, prints one stderr line when it stops short, and `jobs get` shows progress while it runs. `sources status`, `writer movement` and `sync status` count a live sync job as the source\'s drain (`live.drain_job_id`, `live_job_id`). Classic (non-managed) sync jobs are unchanged. To go back: `gbrain config set sync.job_drain false`.' },
// GBRA-96 (default reranker). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
{ since: '0.60.228.0', text: 'The default search reranker is now Voyage `rerank-3-lite` instead of `rerank-2.5`, for brains that never set `search.reranker.model` (a brain that set one keeps it). In gbrain-evals #148 (v0.10.93) it cut rerank cost 60% at the same 50 candidates × 1,400 tokens, with retrieval quality within noise. To go back: `gbrain config set search.reranker.model voyage:rerank-2.5`.' },
// #6650 follow-up (group follower stamps). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
diff --git a/src/core/config.ts b/src/core/config.ts
index 003bc06ac9..1b84604fdc 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1716,7 +1716,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// #5984: managed Postgres sync publishes pages in bulk groups (on by default; each page keeps its own request).
'sync.bulk',
'sync.bulk_size',
- 'sync.bulk_max_txn_ms',
+ 'sync.bulk_max_txn_ms', 'sync.job_drain', // the last: #6706, `false` keeps a managed `sync` job single-pass
'sync.lanes', 'sync.waive_batch', 'persistence.single_write_group', 'persistence.preadmit_cache', // the last three: write-path kill switches (persistence/switches.ts)
// Persisted indexing scope (comma/newline-separated glob list; trailing '/'
// normalizes to a '/**' subtree glob). Read best-effort at the top of
diff --git a/src/core/minions/handler-timeouts.ts b/src/core/minions/handler-timeouts.ts
index 622a477ca8..d4dce27a19 100644
--- a/src/core/minions/handler-timeouts.ts
+++ b/src/core/minions/handler-timeouts.ts
@@ -147,3 +147,12 @@ export function resolveChatPerTurnTimeoutMs(raw: string | null | undefined): num
const n = raw == null || raw.trim() === '' ? NaN : Number(raw);
return Number.isSafeInteger(n) && n > 0 ? n : DEFAULT_CHAT_PER_TURN_TIMEOUT_MS;
}
+
+/**
+ * The wall-clock runtime (ms) past which `handleWallClockTimeouts` dead-letters an active job, regardless of its lock.
+ * `$1` is the worker's lock duration for rows without `lock_duration_ms`. Shared with handlers that budget from it (#6706).
+ */
+export const WALL_CLOCK_THRESHOLD_MS_SQL = `CASE
+ WHEN timeout_ms IS NOT NULL THEN timeout_ms * 2
+ ELSE COALESCE(lock_duration_ms, $1)::double precision * 2 * GREATEST(max_stalled, 1)
+ END`;
diff --git a/src/core/minions/handlers/sync-job-drain.ts b/src/core/minions/handlers/sync-job-drain.ts
new file mode 100644
index 0000000000..25c3349d18
--- /dev/null
+++ b/src/core/minions/handlers/sync-job-drain.ts
@@ -0,0 +1,141 @@
+/**
+ * #6706: the managed drain inside a durable `sync` job.
+ *
+ * A job drains its catch-up (the CLI's path) instead of landing one page per job, bounded by the instant the queue
+ * itself would end the job: its claim-time `timeout_at`, or for a job without `timeout_ms` the wall-clock sweep
+ * (`queue.ts` handleWallClockTimeouts), capped at an hour and less a reserve so cleanup, git and the embed submission
+ * finish first. When the drain stops with work left and the stop is safe to repeat, one follow-up job continues it
+ * behind whatever is already waiting. The job result carries the CLI's `outcome` / `drain` / `next` fields.
+ */
+import type { BrainEngine } from '../../engine.ts';
+import type { MinionJobContext } from '../types.ts';
+import type { SyncOpts, SyncResult } from '../../../commands/sync.ts';
+
+/** The smallest worker lease the wall-clock sweep can use for a row without `lock_duration_ms` (the worker default). */
+const WORKER_LOCK_DEFAULT_MS = 30_000;
+/** A job whose row cannot be read (tests, a vanished row) drains at most this long. */
+const UNKNOWN_BUDGET_MS = 5 * 60_000;
+/** The longest a single job drains; a continuation takes the rest. */
+export const JOB_DRAIN_MAX_MS = 60 * 60_000;
+/** Time kept back from the job's deadline for lane settlement, cleanup, git and the embed submission (cycle precedent). */
+export const JOB_DRAIN_RESERVE_MS = 60_000;
+const PROGRESS_EVERY_MS = 10_000;
+const LIST_KEEP = 50;
+/** A continuation runs no sooner than embed-backfill (priority 5), so it queues behind the embeds and syncs already waiting. */
+const CONTINUATION_PRIORITY = 5;
+
+interface JobRow { started_ms: number | null; wall_ms: number | null; timeout_ms: number | null; queue: string | null; priority: number | null }
+
+export interface JobDrainPlan {
+ opts: Pick<SyncOpts, 'drain' | 'deadlineAtMs' | 'lanes' | 'noBulk'>;
+ row: JobRow | null;
+ trusted: boolean;
+}
+
+/** The drain options for this job, or none when draining is off (`drain: false` from a trusted submitter, or `sync.job_drain=false`). */
+export async function planJobDrain(engine: BrainEngine, job: MinionJobContext, now = Date.now()): Promise<JobDrainPlan> {
+ const trusted = !job.submission_authority || job.submission_authority.kind === 'application';
+ const params = trusted ? job.data : {};
+ const configured = await engine.getConfig('sync.job_drain').catch(() => null);
+ if (params.drain === false || configured === 'false') return { opts: {}, row: null, trusted };
+ const { WALL_CLOCK_THRESHOLD_MS_SQL } = await import('../handler-timeouts.ts');
+ const [row] = await engine.executeRaw<JobRow>(
+ `SELECT (EXTRACT(EPOCH FROM started_at) * 1000)::float8 AS started_ms, (${WALL_CLOCK_THRESHOLD_MS_SQL})::float8 AS wall_ms,
+ timeout_ms, queue, priority
+ FROM minion_jobs WHERE id = $2`, [WORKER_LOCK_DEFAULT_MS, job.id]).catch(() => []);
+ const started = row?.started_ms ?? now;
+ const hard = job.deadlineAtMs ?? (row?.started_ms != null && row.wall_ms != null ? row.started_ms + row.wall_ms : now + UNKNOWN_BUDGET_MS);
+ const at = Math.min(hard, started + JOB_DRAIN_MAX_MS);
+ // The reserve also absorbs skew between the database clock (started_at) and this worker's clock.
+ const deadlineAtMs = at - Math.min(JOB_DRAIN_RESERVE_MS, Math.max(0, at - now) / 4);
+ const lanes = typeof params.lanes === 'number' && Number.isInteger(params.lanes) && params.lanes >= 1 && params.lanes <= 16 ? params.lanes : 1;
+ return { opts: { drain: true, deadlineAtMs, lanes, ...(params.noBulk === true ? { noBulk: true } : {}) }, row: row ?? null, trusted };
+}
+
+/** Throttled best-effort progress for `jobs get` / MCP polling while the drain commits pages. Never throws into the sync. */
+export function jobDrainProgress(job: MinionJobContext, estimate: (remaining: number | null, processed: number, elapsedMs: number) => { rate_pages_per_min: number | null; eta_seconds: number | null }):
+ { onProgress: NonNullable<SyncOpts['onProgress']>; flush(): Promise<void> } {
+ const startedAt = Date.now();
+ let index = 0, processed = 0, total: number | null = null, phase = 'managed_sync.start', lastAdvanceAt: string | null = null, wroteAt = 0;
+ const snapshot = () => {
+ const remaining = total === null ? null : Math.max(0, total - index);
+ return { phase, index, total, processed, remaining, ...estimate(remaining, processed, Date.now() - startedAt), last_advance_at: lastAdvanceAt };
+ };
+ return {
+ onProgress: event => {
+ if (!event.phase.startsWith('managed_sync.')) return;
+ phase = event.phase;
+ if (typeof event.total === 'number') total = event.total;
+ if (typeof event.bankedFiles === 'number') index = event.bankedFiles;
+ if (event.phase !== 'managed_sync.page_committed') return;
+ const now = Date.now();
+ processed++;
+ lastAdvanceAt = new Date(now).toISOString();
+ if (now - wroteAt >= PROGRESS_EVERY_MS) { wroteAt = now; job.updateProgress(snapshot()).catch(() => undefined); }
+ },
+ flush: async () => { if (lastAdvanceAt) await job.updateProgress(snapshot()).catch(() => undefined); },
+ };
+}
+
+/** Counts plus the first entries of a long list, so a drained job's result row stays small. */
+function trimList<T>(list: T[] | undefined): { list?: T[]; count?: number } {
+ if (!list || list.length <= LIST_KEEP) return list ? { list } : {};
+ return { list: list.slice(0, LIST_KEEP), count: list.length };
+}
+
+/**
+ * The drained job's result fields: the CLI's `outcome` / `drain` / `next`, an `incomplete` alias, and at most one
+ * continuation job when the stop is safe to repeat and this job committed at least one entry. Empty for a result
+ * with no drain, so classic and other syncs keep master's result.
+ */
+export async function settleJobDrain(engine: BrainEngine, job: MinionJobContext, result: SyncResult, sourceId: string, plan: JobDrainPlan): Promise<Record<string, unknown>> {
+ const { drainJsonFields, jobDisposition } = await import('../../persistence/sync-drain.ts');
+ const { managedSyncResumeArgs, syncResumeCommand } = await import('../../sync-reconcile.ts');
+ const disposition = jobDisposition(result, sourceId);
+ if (!disposition) return {};
+ const resume = syncResumeCommand(managedSyncResumeArgs({ sourceId }));
+ const fields = drainJsonFields(result, resume, sourceId) as { outcome?: string; drain?: SyncResult['drain']; next?: Record<string, unknown> & { why?: string; docs?: string } };
+ const held = trimList(result.held), pages = trimList(result.pagesAffected);
+ const out: Record<string, unknown> = { ...fields, incomplete: disposition !== 'synced',
+ ...(held.list ? { held: held.list } : {}), ...(held.count ? { held_count: held.count } : {}),
+ ...(pages.list ? { pagesAffected: pages.list } : {}), ...(pages.count ? { pages_affected_count: pages.count } : {}) };
+ if (disposition === 'synced') return out;
+ const d = result.drain!;
+ let continuationId: number | null = null;
+ const { embedBackfillWorkerSurface } = await import('../embed-backfill-admission.ts');
+ // PGLite has no resident worker to run a queued follow-up (the embed-backfill rule); its `next` stays the resume command.
+ if (disposition === 'continue' && plan.trusted && d.processed > 0 && embedBackfillWorkerSurface(engine).status === 'worker_backed') {
+ try {
+ const { MinionQueue } = await import('../queue.ts');
+ const next = await new MinionQueue(engine).add('sync', { ...job.data, sourceId, continuation_of: job.id }, {
+ idempotency_key: `sync-continue:${sourceId}:${job.id}`,
+ maxWaiting: 1,
+ ...(plan.row?.queue ? { queue: plan.row.queue } : {}),
+ priority: Math.max(plan.row?.priority ?? 0, CONTINUATION_PRIORITY),
+ ...(plan.row?.timeout_ms != null ? { timeout_ms: plan.row.timeout_ms } : {}),
+ ...(typeof fields.next?.retry_after_ms === 'number' && fields.next.retry_after_ms > 0 ? { delay: fields.next.retry_after_ms } : {}),
+ });
+ continuationId = next.id;
+ // A job cancelled while it settled leaves no runnable successor behind.
+ if ((job.signal.aborted || job.shutdownSignal?.aborted) && next.data?.continuation_of === job.id) { await new MinionQueue(engine).cancelJob(next.id).catch(() => undefined); continuationId = null; }
+ } catch { /* best-effort: the next freshness tick or the resume command continues */ }
+ }
+ const status = `gbrain sources status ${sourceId} --json`;
+ if (continuationId !== null && fields.next) {
+ // The successor owns the resume: every field observes it (no executable sync `fix` survives), polled after a short delay.
+ out.next = { command: status, safe_to_loop: true, retry_after_ms: Math.max(30_000, Number(fields.next.retry_after_ms) || 0),
+ eta_seconds: d.eta_seconds, rate_pages_per_min: d.rate_pages_per_min, ...(fields.next.docs ? { docs: fields.next.docs } : {}),
+ why: `Follow-up sync job #${continuationId} continues from the cursor (${d.remaining ?? 'an unknown number of'} entries left); this job stopped ${d.stop_reason ?? d.outcome} with its cursor and accepted writes intact. `
+ + `Watch it with \`gbrain jobs get ${continuationId} --json\` or the source's cursor; running \`${resume}\` now would start a second drainer beside it.` };
+ } else if (!plan.trusted && fields.next) {
+ // A remote job cannot run the host's CLI and may not queue its own successor: the host operator resumes, or the caller submits a new sync job.
+ out.next = { command: status, safe_to_loop: false, retry_after_ms: 0, eta_seconds: d.eta_seconds, rate_pages_per_min: d.rate_pages_per_min,
+ ...(fields.next.code ? { code: fields.next.code } : {}), ...(fields.next.docs ? { docs: fields.next.docs } : {}),
+ why: `${fields.next.why ?? ''} This job was submitted remotely, so it queued no follow-up: submit a new sync job for source ${sourceId}, or ask the brain host's operator to run \`${resume}\`.` };
+ }
+ out.continuation_job_id = continuationId;
+ const next = out.next as { why?: string; docs?: string } | undefined;
+ console.error(`[sync] job ${job.id} source ${sourceId}: ${d.outcome}/${d.stop_reason ?? 'none'}, ${d.remaining ?? 'an unknown number of'} entries left. `
+ + `${next?.why ?? ''}${next?.docs ? ` Docs: ${next.docs}` : ''}`);
+ return out;
+}
diff --git a/src/core/minions/handlers/sync.ts b/src/core/minions/handlers/sync.ts
index df4fb83ebd..9c6e3bf79c 100644
--- a/src/core/minions/handlers/sync.ts
+++ b/src/core/minions/handlers/sync.ts
@@ -80,10 +80,32 @@ export function makeSyncHandler(engine: BrainEngine): MinionHandler {
// aborts only the worker's shutdown signal, so the sync and its git pull stop on either signal.
const { composeAbortSignals } = await import('../../sync-reconcile.ts');
const signal = composeAbortSignals(job.signal, job.shutdownSignal);
+ // #6706: a managed sync drains its catch-up instead of landing one page per job, bounded by the queue's own deadline for
+ // this job less a reserve, and by its abort signal. Classic, connector and company-brain syncs ignore `drain`.
+ 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),
concurrency: concurrencyOverride,
...(githubItem ? { githubItem } : {}),
@@ -157,6 +179,8 @@ export function makeSyncHandler(engine: BrainEngine): MinionHandler {
embedSkipReason = 'no_new_content';
}
- return { ...result, embed_job_id: embedJobId, embed_skip_reason: embedSkipReason };
+ await progress.flush();
+ const drained = await settleJobDrain(engine, job, result, sourceId ?? 'default', plan);
+ return { ...result, ...drained, embed_job_id: embedJobId, embed_skip_reason: embedSkipReason };
};
}
diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.ts
index 6be9038c0f..20f2b17671 100644
--- a/src/core/minions/queue.ts
+++ b/src/core/minions/queue.ts
@@ -31,7 +31,7 @@ import {
} from './admission.ts';
import {
defaultTimeoutMsFor, HANDLER_DEFAULT_TIMEOUT_MS,
- defaultLockDurationMsFor, HANDLER_DEFAULT_LOCK_DURATION_MS, clampLockDurationMs,
+ defaultLockDurationMsFor, HANDLER_DEFAULT_LOCK_DURATION_MS, clampLockDurationMs, WALL_CLOCK_THRESHOLD_MS_SQL,
} from './handler-timeouts.ts';
import {
withRetry, BULK_RETRY_OPTS, resolveBulkRetryOpts, computeNextDelay,
@@ -1650,11 +1650,7 @@ export class MinionQueue {
`SELECT id, parent_job_id FROM minion_jobs
WHERE status = 'active'
AND started_at IS NOT NULL
- AND EXTRACT(EPOCH FROM (now() - started_at)) * 1000 >
- CASE
- WHEN timeout_ms IS NOT NULL THEN timeout_ms * 2
- ELSE COALESCE(lock_duration_ms, $1)::double precision * 2 * GREATEST(max_stalled, 1)
- END`,
+ AND EXTRACT(EPOCH FROM (now() - started_at)) * 1000 > ${WALL_CLOCK_THRESHOLD_MS_SQL}`,
[lockDurationMs]
);
if (candidates.length === 0) return [];
diff --git a/src/core/persistence/drain-step.ts b/src/core/persistence/drain-step.ts
index 854593e61c..688d7cb4d2 100644
--- a/src/core/persistence/drain-step.ts
+++ b/src/core/persistence/drain-step.ts
@@ -17,8 +17,12 @@ export class DrainPassAbandoned extends Error {}
* Enters `step`; a pass the governor abandoned throws here, so it admits and writes nothing more. The caller's own
* cancellation is not thrown here: the pass's existing cancel handling still banks work it already admitted.
*/
+const abandoned = new WeakSet<AbortSignal>();
+/** #6706: marks a pass's signal abandoned even when another abort reason (the drain's deadline) landed on it first. */
+export function markPassAbandoned(signal: AbortSignal): void { abandoned.add(signal); }
export function stampDrainStep(step: DrainStep, signal?: AbortSignal, now = Date.now()): void {
if (signal?.aborted && signal.reason instanceof DrainPassAbandoned) throw signal.reason;
+ if (signal && abandoned.has(signal)) throw new DrainPassAbandoned('pass abandoned');
current = { step, since: now, last_sql: null };
}
/** Records the statement the current step is about to send (label only, never text or parameters). */
diff --git a/src/core/persistence/sync-authority.ts b/src/core/persistence/sync-authority.ts
index 3474207341..b3b5136cdc 100644
--- a/src/core/persistence/sync-authority.ts
+++ b/src/core/persistence/sync-authority.ts
@@ -127,9 +127,13 @@ export function validateManagedSyncOptions(opts: SyncOpts): void {
assertDurableSyncCaller();
const current = currentSubmissionAuthority();
if (current?.kind !== 'remote_generic') return;
- const allowed = new Set(['repoPath','sourceId','noPull','noEmbed','noExtract','explicitProcessing','signal','concurrency','onProgress','auto_embed_backfill']);
+ // #6706: the worker's own drain controls (never read from a remote job's data) bound the run; they cannot widen what it writes.
+ const allowed = new Set(['repoPath','sourceId','noPull','noEmbed','noExtract','explicitProcessing','signal','concurrency','onProgress','auto_embed_backfill',
+ 'drain','deadlineAtMs','drainStartedAt','bulk','lanes']);
if (current.grant.jobName !== 'sync' || opts.repoPath !== current.grant.canonicalRoot || opts.sourceId !== current.grant.sourceId ||
opts.noPull !== true || opts.noEmbed !== true || opts.noExtract !== true ||
+ (opts.drain !== undefined && opts.drain !== true) || (opts.lanes !== undefined && opts.lanes !== 1) ||
+ (opts.deadlineAtMs !== undefined && !Number.isFinite(opts.deadlineAtMs)) ||
Object.entries(opts).some(([key,value]) => value !== undefined && !allowed.has(key)) ||
((opts as Record<string,unknown>).auto_embed_backfill !== undefined && (opts as Record<string,unknown>).auto_embed_backfill !== false)) {
throw opError('permission_denied', 'Sync options exceed the originally accepted remote job.',
diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.ts
index c584a5f720..48871d6352 100644
--- a/src/core/persistence/sync-drain.ts
+++ b/src/core/persistence/sync-drain.ts
@@ -23,7 +23,7 @@ import { ERROR_CATALOGUE, type CatalogueName } from '../error-catalogue.ts';
import { cliRenderContext, renderAction, type Action, type RenderedAction } from '../agent-output.ts';
import { managedSyncResumeArgs, syncResumeCommand } from '../sync-reconcile.ts';
import { isWriteCapacityWait, outstandingCapacityOf } from './admission-retry.ts';
-import { clearDrainStep, DrainPassAbandoned, readDrainStep } from './drain-step.ts';
+import { clearDrainStep, DrainPassAbandoned, markPassAbandoned, readDrainStep } from './drain-step.ts';
import { PUBLICATION_CEILING_DEFAULT_MS, readPublicationCeilingMs } from './publication-deadline.ts';
import { isOwnerThisProcess, stampLastSql, WAITING_ON, type ClaimLastSql, type WaitingOn } from './claim-phase.ts';
import { describeHostConsumer, headBlockedNext, headBlockerText, headClaimability, type HeadBlocker } from './head-blocker.ts';
@@ -167,6 +167,10 @@ type RunCounts = Pick<SyncResult, 'added' | 'modified' | 'deleted' | 'renamed' |
const NO_PASS_RESULT: SyncResult = { status: 'partial', reason: 'writer_pending', fromCommit: null, toCommit: '', added: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [] };
const REFRESH_WAIT_MS = 5 * 60_000;
const DEADLINE_MARGIN_MS = 15_000;
+/** #6706: the longest single timer delay; setTimeout fires immediately past 2^31-1 ms. */
+const MAX_TIMER_MS = 2 ** 31 - 1;
+/** #6706: how long a pass may keep running after the drain's own deadline fired before the drain abandons it and reports. */
+export const DEADLINE_PASS_GRACE_MS = 10_000;
const PROGRESS_EVERY_MS = 10_000;
/** #6405/#6423: a pass with no commit, no admission and no change at the head for this long is ended by the in-pass governor. */
const IN_PASS_NO_PROGRESS_MS = 5 * 60_000;
@@ -254,14 +258,26 @@ function sleep(ms: number, signal?: AbortSignal): Promise<void> {
});
}
-/** Aborts shortly before a strict out-of-band deadline, so the drain writes the final result instead of the watchdog. */
-function cooperativeDeadline(): { signal?: AbortSignal; dispose(): void } {
- const deadline = currentRunDeadline();
- if (!deadline?.strict) return { dispose() {} };
- const remaining = deadline.atMs - Date.now();
+/**
+ * Aborts shortly before the earlier of a strict out-of-band deadline and the caller's own deadline (#6706: a job's
+ * `timeout_at`), so the drain writes the final result instead of the watchdog.
+ */
+function cooperativeDeadline(callerAtMs?: number): { signal?: AbortSignal; dispose(): void } {
+ const run = currentRunDeadline();
+ const atMs = Math.min(run?.strict ? run.atMs : Infinity, callerAtMs ?? Infinity);
+ if (!Number.isFinite(atMs)) return { dispose() {} };
+ const remaining = atMs - Date.now();
+ const stopAt = Date.now() + Math.max(0, remaining - Math.min(DEADLINE_MARGIN_MS, remaining / 2));
const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(new Error('run deadline')), Math.max(0, remaining - Math.min(DEADLINE_MARGIN_MS, remaining / 2)));
- timer.unref?.();
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ // A past stop instant aborts now; a far one re-arms in steps, because setTimeout fires at once past 2^31-1 ms.
+ const arm = () => {
+ const wait = stopAt - Date.now();
+ if (wait <= 0) { controller.abort(new Error('run deadline')); return; }
+ timer = setTimeout(arm, Math.min(wait, MAX_TIMER_MS));
+ timer.unref?.();
+ };
+ arm();
return { signal: controller.signal, dispose: () => clearTimeout(timer) };
}
@@ -287,6 +303,8 @@ export interface DrainInput {
/** #6340: recovers the engine's pool before a connection-class retry (`engine.reconnect`); absent for callers without one. */
reconnect?(error: unknown): Promise<void>;
signal?: AbortSignal;
+ /** #6706: absolute epoch ms the drain stops before (cooperatively, `resumable / deadline`); a job passes its `timeout_at`. */
+ deadlineAtMs?: number;
onProgress?: SyncOpts['onProgress'];
probe?: StallProbe;
/** Throttled progress lines on stderr (CLI). */
@@ -304,6 +322,8 @@ export interface DrainInput {
pauseMs?: number;
backoffMs?: number;
progressMs?: number;
+ /** #6706 test seam: how long a pass may run past the drain's own deadline before it is abandoned. */
+ deadlineGraceMs?: number;
}
/**
@@ -327,8 +347,10 @@ function stallText(index: number, total: number | null, stalledMs: number, claim
export async function runDrain(input: DrainInput): Promise<SyncResult> {
const clock = input.clock ?? Date.now;
const startedAt = clock();
- const coop = cooperativeDeadline();
+ const coop = cooperativeDeadline(input.deadlineAtMs);
const signal = coop.signal && input.signal ? AbortSignal.any([input.signal, coop.signal]) : coop.signal ?? input.signal;
+ /** #6706: the drain's own deadline (not the caller's cancellation) stopped it, so the stop is a resumable report. */
+ const deadlineStop = () => !!coop.signal?.aborted && !input.signal?.aborted;
let passes = 0, attempt = 0, readFailures = 0, refreshWaitedMs = 0, written = 0, waived = 0, index = 0, total: number | null = null;
let announcedStart = false, lastLine = 0, groups = 0, groupedPages = 0, largestGroup = 0, admittedAhead = 0;
let lanes: { effective: number; stepDown: string | null; overlapped: number; fallbacks: number } | null = null;
@@ -393,7 +415,7 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
// the abandoned pass: its signal is aborted (the pass's step boundaries throw, so it admits and writes nothing more) and its
// late result or rejection is dropped.
const noProgressMs = input.noProgressMs ?? IN_PASS_NO_PROGRESS_MS, ceilingMs = input.publicationCeilingMs ?? PUBLICATION_CEILING_DEFAULT_MS;
- const governedPass = (): Promise<{ result: SyncResult } | { stall: DrainStall }> => {
+ const governedPass = (): Promise<{ result: SyncResult } | { stall: DrainStall } | { deadline: true }> => {
const controller = new AbortController(), passStartedAt = clock();
const passSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
clearDrainStep();
@@ -401,7 +423,7 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
let timer: ReturnType<typeof setInterval> | null = null, probing = false, key: string | null = null, keySince = passStartedAt, blockedKey: string | null = null;
const governEvery = input.governMs ?? Math.min(every, GOVERN_EVERY_MS), blockerAfter = input.governMs ?? GOVERN_EVERY_MS;
const stopped = new Promise<{ stall: DrainStall }>(resolve => {
- const stop = (stall: DrainStall) => { if (timer) clearInterval(timer); timer = null; controller.abort(new DrainPassAbandoned(`drain_stalled: ${stall.cause}`)); resolve({ stall }); };
+ const stop = (stall: DrainStall) => { if (timer) clearInterval(timer); timer = null; markPassAbandoned(passSignal); controller.abort(new DrainPassAbandoned(`drain_stalled: ${stall.cause}`)); resolve({ stall }); };
timer = setInterval(() => {
const quietSince = Math.max(lastCommitAt, passStartedAt);
if (probing || clock() - quietSince < Math.min(noProgressMs, ceilingMs, blockerAfter)) return;
@@ -446,7 +468,17 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
timer.unref?.();
});
running.catch(() => undefined);
- return Promise.race([running.then(result => ({ result })), stopped]).finally(() => { if (timer) clearInterval(timer); timer = null; inPass = false; });
+ // #6706: the pass already sees the deadline through its signal; one that has not returned within the grace is abandoned like a
+ // stalled pass (its signal aborted, its late result dropped), so the drain still reports before the caller's hard deadline.
+ let graceTimer: ReturnType<typeof setTimeout> | undefined, onDeadline: (() => void) | undefined;
+ const expired = coop.signal ? new Promise<{ deadline: true }>(resolve => {
+ onDeadline = () => { graceTimer = setTimeout(() => { markPassAbandoned(passSignal); controller.abort(new DrainPassAbandoned('deadline')); resolve({ deadline: true }); }, input.deadlineGraceMs ?? DEADLINE_PASS_GRACE_MS); graceTimer.unref?.(); };
+ if (coop.signal!.aborted) onDeadline(); else coop.signal!.addEventListener('abort', onDeadline, { once: true });
+ }) : null;
+ return Promise.race([running.then(result => ({ result })), stopped, ...(expired ? [expired] : [])]).finally(() => {
+ if (timer) clearInterval(timer); timer = null; inPass = false;
+ clearTimeout(graceTimer); if (onDeadline) coop.signal?.removeEventListener('abort', onDeadline);
+ });
};
const finish = (result: SyncResult, outcome: DrainOutcome, stopReason?: DrainStopReason, extra?: Partial<DrainReport>): SyncResult => {
if (result.managedCursor) { index = result.managedCursor.index; total = result.managedCursor.total; }
@@ -462,12 +494,14 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
};
try {
for (;;) {
+ if (deadlineStop()) return finish(last ?? NO_PASS_RESULT, 'resumable', 'deadline');
passes++;
let result: SyncResult;
try {
inPass = true;
const governed = await governedPass();
if ('stall' in governed) return finish(last ?? NO_PASS_RESULT, 'blocked', 'drain_stalled', { stall: governed.stall });
+ if ('deadline' in governed) return finish(last ?? NO_PASS_RESULT, 'resumable', 'deadline');
result = governed.result;
attempt = 0; capacity = null;
if (last?.runId && result.runId && result.runId !== last.runId) {
@@ -476,6 +510,10 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
}
last = result;
} catch (error) {
+ // #6706: a retryable stop or the drain's own abort that lands after its deadline is the deadline, reported resumable; a fatal error still throws.
+ const retryable = isWriteCapacityWait(error) || isConnectionDrop(error) || error === coop.signal?.reason || error instanceof DrainPassAbandoned
+ || (error instanceof Error && error.name === 'AbortError') || transientDelay(error, attempt + 1, refreshWaitedMs, input.backoffMs ?? 250) !== null;
+ if (deadlineStop() && retryable) return finish(last ?? NO_PASS_RESULT, 'resumable', 'deadline');
// #6278 (B7): other requests (another writer on the same principal, or the brain) hold the outstanding-request cap, so the pass
// could not admit its next write. They settle on their own: wait with backoff, say so, and past the no-progress window stop
// `blocked` with the counts and the writer to inspect, never an uncaught exit without a drain summary.
@@ -498,8 +536,13 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
const delay = input.backoffMs !== undefined ? input.backoffMs * 4 ** (drops - 1) : CONNECTION_RETRY_MS[drops - 1]!;
if (input.announce) serr(`[sync] ${index}/${total ?? '?'} processed · database connection dropped (${errorText(error)}); reconnecting and retrying in ${formatDuration(Math.round(delay / 1000))} (${drops} of ${CONNECTION_STRIKES})`);
await sleep(delay, signal);
+ if (deadlineStop()) return finish(last ?? NO_PASS_RESULT, 'resumable', 'deadline');
if (signal?.aborted) throw error;
- await input.reconnect?.(error).catch(() => undefined);
+ // #6706: a reconnect that hangs past the drain's deadline is not awaited; the stop is reported from the last durable result.
+ await Promise.race([input.reconnect?.(error).catch(() => undefined), ...(coop.signal ? [new Promise<void>(resolve => {
+ if (coop.signal!.aborted) resolve(); else coop.signal!.addEventListener('abort', () => resolve(), { once: true });
+ })] : [])]);
+ if (deadlineStop()) return finish(last ?? NO_PASS_RESULT, 'resumable', 'deadline');
continue;
}
const delay = transientDelay(error, ++attempt, refreshWaitedMs, input.backoffMs ?? 250);
@@ -699,6 +742,11 @@ export function engineStallProbe(engine: BrainEngine, sourceId?: string): StallP
};
}
+/** #6706: whether a caller's drain deadline is within the cooperative margin, so no further pass or stage may start. */
+export function deadlinePassed(deadlineAtMs: number | undefined, now = Date.now()): boolean {
+ return deadlineAtMs !== undefined && deadlineAtMs - now <= DEADLINE_MARGIN_MS;
+}
+
/** The managed-sync drain over one engine; the CLI's managed path. */
export async function drainManagedSync(engine: BrainEngine, opts: SyncOpts, announce: boolean): Promise<SyncResult> {
const { performManagedSync } = await import('./sync-run.ts');
@@ -721,15 +769,19 @@ export async function drainManagedSync(engine: BrainEngine, opts: SyncOpts, anno
}
let result: SyncResult | undefined;
try {
- result = await runDrain({ signal: opts.signal, onProgress: opts.onProgress, probe: engineStallProbe(engine, opts.sourceId), announce, publicationCeilingMs,
+ result = await runDrain({ signal: opts.signal, deadlineAtMs: opts.deadlineAtMs, onProgress: opts.onProgress, probe: engineStallProbe(engine, opts.sourceId), announce, publicationCeilingMs,
reconnect: error => engine.reconnect({ error }),
bulk: { enabled: bulk.enabled, reason: bulk.reason, lanes: bulk.lanes ?? 1, lanesMax: bulk.lanesMax, lanesReason: bulk.lanesReason ?? null, lanesCap: bulk.lanesCap },
pass: (signal, onProgress) => performManagedSync(engine, { ...opts, signal, onProgress, drainStartedAt, ...(bulk.enabled ? { bulk: { ...bulk, laneRun } } : {}) }) });
} finally {
if (laneRun) {
- const stats = await closeLaneRun(laneRun);
+ // #6706: a caller deadline bounds lane teardown too; stats a late close would have added are simply left out of the report.
+ const left = opts.deadlineAtMs === undefined ? null : Math.max(0, opts.deadlineAtMs - Date.now());
+ const stats = left === null ? await closeLaneRun(laneRun)
+ : await Promise.race([closeLaneRun(laneRun), new Promise<undefined>(resolve => { const t: ReturnType<typeof setTimeout> = setTimeout(() => resolve(undefined), left); t.unref?.(); })]);
const { cancelOrphanedLaneRows } = await import('./sync-window.ts');
- await cancelOrphanedLaneRows(engine, laneRun, result?.drain?.outcome === 'blocked' ? 10_000 : 0).catch(() => undefined);
+ const settleMs = opts.deadlineAtMs === undefined ? 10_000 : Math.max(0, Math.min(10_000, opts.deadlineAtMs - Date.now()));
+ await cancelOrphanedLaneRows(engine, laneRun, result?.drain?.outcome === 'blocked' ? settleMs : 0).catch(() => undefined);
const lanes = result?.drain?.bulk?.lanes;
if (lanes && stats) Object.assign(lanes, { busy: stats.busy, apply_ms_per_page: stats.applyMsPerPage, turn_wait_share: stats.turnWaitShare });
}
@@ -738,12 +790,12 @@ export async function drainManagedSync(engine: BrainEngine, opts: SyncOpts, anno
// since the pin (an incremental pin..HEAD discovery, which also re-screens holds whose file a later commit changed), so the
// invocation ends at HEAD instead of leaving the gap to the next launch. Never a second extra pass: a checkout that keeps
// committing would otherwise loop forever.
- if (result.drain?.outcome === 'synced' && result.toCommit && !opts.dryRun && !opts.signal?.aborted && result.status !== 'up_to_date' && !result.staged) {
+ if (result.drain?.outcome === 'synced' && result.toCommit && !opts.dryRun && !opts.signal?.aborted && result.status !== 'up_to_date' && !result.staged && !deadlinePassed(opts.deadlineAtMs)) {
const head = await headOfSource(engine, opts);
if (head && head !== result.toCommit) {
if (announce) serr(`[sync] HEAD moved past the pinned target ${result.toCommit.slice(0, 8)} while the run drained; one more pass imports the commits since (to ${head.slice(0, 8)}).`);
const pin = result.toCommit;
- const again = await runDrain({ signal: opts.signal, onProgress: opts.onProgress, probe: engineStallProbe(engine, opts.sourceId), announce: false, publicationCeilingMs,
+ const again = await runDrain({ signal: opts.signal, deadlineAtMs: opts.deadlineAtMs, onProgress: opts.onProgress, probe: engineStallProbe(engine, opts.sourceId), announce: false, publicationCeilingMs,
reconnect: error => engine.reconnect({ error }),
bulk: { enabled: bulk.enabled, reason: bulk.reason, lanes: bulk.lanes ?? 1, lanesMax: bulk.lanesMax, lanesReason: bulk.lanesReason ?? null, lanesCap: bulk.lanesCap },
pass: (signal, onProgress) => performManagedSync(engine, { ...opts, signal, onProgress, drainStartedAt, ...(bulk.enabled ? { bulk: { ...bulk, laneRun } } : {}) }) });
@@ -940,6 +992,19 @@ export function drainNext(result: SyncResult, resumeCommand: string, sourceId: s
...(docs ? { docs } : {}) };
}
+/**
+ * #6706: what a durable `sync` job does with a drained result. `null` when nothing drained (classic, connector and company-brain
+ * syncs keep master's result); `continue` when `drainNext` says the same run is safe to repeat (a follow-up job may take it);
+ * `needs_operator` when the next step is an inspection or a fix. Decided from `drainNext`, so a new stop reason is classified here.
+ */
+export type JobDisposition = 'synced' | 'continue' | 'needs_operator';
+export function jobDisposition(result: SyncResult, sourceId: string): JobDisposition | null {
+ if (!result.drain) return null;
+ const next = drainNext(result, 'gbrain sync', sourceId);
+ if (!next) return 'synced';
+ return next.safe_to_loop ? 'continue' : 'needs_operator';
+}
+
/** `outcome`, `drain` and `next` for a JSON envelope; empty for results that are not managed syncs. */
export function drainJsonFields(result: SyncResult, resumeCommand: string, sourceId: string): Record<string, unknown> {
if (!result.drain && !result.managedCursor) return {};
diff --git a/src/core/persistence/sync-movement.ts b/src/core/persistence/sync-movement.ts
index c0dd6233fb..de30a68417 100644
--- a/src/core/persistence/sync-movement.ts
+++ b/src/core/persistence/sync-movement.ts
@@ -67,7 +67,8 @@ export interface SourceMovement {
holds: MovementHolds;
/** Managed requests admitted on the worktree and not yet settled (queued or running). */
admitted: number;
- live: { drain: boolean; drain_pid: number | null; consumer: 'claim' | 'local' | 'heartbeat' | null };
+ /** #6706: `drain_job_id` is the active `sync` Minions job with a live lock that drives this source, when no CLI drain holds the sync lock. */
+ live: { drain: boolean; drain_pid: number | null; drain_job_id: number | null; consumer: 'claim' | 'local' | 'heartbeat' | null };
ceiling_ms: number;
owner_is_this_host: boolean | null;
writer_status_command: string;
@@ -95,6 +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. */
+export async function liveSyncJob(engine: BrainEngine, sourceId: string): Promise<number | null> {
+ 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(() => []);
+ return row ? Number(row.id) : null;
+}
+
/** The movement of every active managed source (or of `sourceIds`), one bounded read each; sources without a binding are omitted. */
export async function readSourceMovement(engine: BrainEngine, opts: { sourceIds?: string[]; now?: number } = {}): Promise<SourceMovement[]> {
const now = opts.now ?? Date.now();
@@ -129,6 +138,7 @@ export async function readSourceMovement(engine: BrainEngine, opts: { sourceIds?
const head: MovementHead | null = headRow ? { request_id: headRow.request_id, state: headRow.state, phase: claim?.phase ?? null, step: claim?.step ?? null, step_since: stampSince,
step_age_ms: claim?.step_age_ms ?? null, waiting_on: claim?.waiting_on ?? null, owner: claim?.owner ?? null, last_sql: claim?.last_sql ?? null, lapsed: headRow.claim_lapsed === true } : null;
const drain = await liveSyncStatus(engine, binding.source_id);
+ const jobDrain = drain ? null : await liveSyncJob(engine, binding.source_id);
const ownerHere = binding.owner_host_id === null ? null : binding.owner_host_id === host;
const claimLive = !!claim && (claim.phase === 'preparing' || claim.phase === 'publishing');
const consumer: SourceMovement['live']['consumer'] = claimLive ? 'claim' : ownerHere !== false && localConsumer ? 'local' : ownerHere !== false && await liveHeartbeat() ? 'heartbeat' : null;
@@ -140,7 +150,7 @@ export async function readSourceMovement(engine: BrainEngine, opts: { sourceIds?
const sampledAt = new Date(now).toISOString();
const base = { source_id: binding.source_id, sampled_at: sampledAt, last_commit_at: lastCommitAt, last_progress_at: progressAt,
cursor: cursor ? { index: cursor.index, total: cursor.total, remaining: cursor.remaining, held: cursor.held, last_progress_at: cursor.last_progress_at, resume_command: cursor.resume_command } : null,
- head, holds, admitted, live: { drain: !!drain, drain_pid: drain?.holder_pid ?? null, consumer }, ceiling_ms: policy.ceilingMs, owner_is_this_host: ownerHere,
+ head, holds, admitted, live: { drain: !!drain || !!jobDrain, drain_pid: drain?.holder_pid ?? null, drain_job_id: jobDrain, consumer }, ceiling_ms: policy.ceilingMs, owner_is_this_host: ownerHere,
writer_status_command: writerStatusCommand(binding.source_id) };
out.push({ ...base, ...verdict(base, now) });
}
diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.ts
index 16de09cc79..a7b2c381a8 100644
--- a/src/core/persistence/sync-status.ts
+++ b/src/core/persistence/sync-status.ts
@@ -74,6 +74,8 @@ export interface SyncStatus {
cursor: { index: number; total: number; pinned_target: string | null; last_advance_at: string | null; done: boolean } | null;
/** Managed sync page requests of the source committed in the last ten minutes (waived entries are not requests). */
committed_last_10m: number;
+ /** #6706: the active `sync` Minions job draining this cursor (its `next` watches it), or null. */
+ live_job_id: number | null;
rate_pages_per_min: number | null;
eta_seconds: number | null;
holds: SyncStatusHold[];
@@ -206,7 +208,12 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string): Pro
const selfHealing = lastError?.detail === 'knock_on' || lastError?.detail === 'run_replaced';
const actionable = holds.filter(hold => !hold.needs_human && hold.safe_actions[0] !== 'none');
const verify = { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'] };
- const next: Action | null = human
+ // #6706: a live sync job already drains this cursor; the agent watches it instead of starting a second drainer beside it.
+ const liveJob = unfinished && !human ? await (await import('./sync-movement.ts')).liveSyncJob(engine, sourceId) : null;
+ const next: Action | null = liveJob !== null
+ ? { argv: ['gbrain', 'jobs', 'get', String(liveJob), '--json'], consent: [], actor: 'agent', requires_exclusive: false, verify,
+ why: `Sync job #${liveJob} is draining this cursor (${header!.index}/${header!.total}); it resumes the frozen manifest on its own, so watch it rather than running a second sync beside it.` }
+ : human
? { ...('fix' in human ? human.fix : { argv: ['gbrain', 'sources', 'status', sourceId, '--json'], consent: [], actor: 'host_admin' as const, requires_exclusive: false, why: human.human_reason ?? '' }),
user_message: `Sync of source ${sourceId} needs a decision: ${'slug' in human && human.slug ? `page ${human.slug} (${('path' in human ? human.path : undefined) ?? ''})` : `code ${human.code}`}: ${human.human_reason ?? 'see the hold'}` }
: actionable.length
@@ -226,7 +233,7 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string): Pro
const { recovery_next, ...terminal } = await terminalSummary(engine, sourceId, blockers.checkpoint_blockers);
return { source_id: sourceId, run_id: header?.runId ?? null,
cursor: header ? { index: Number(header.index), total: Number(header.total), pinned_target: header.target ?? null, last_advance_at: p ? new Date(p.lastAt).toISOString() : null, done: !!header.done } : null,
- committed_last_10m: Number(committed?.n ?? 0), ...estimate, holds, last_error: lastError, needs_human: !!human, ...(human ? { human_reason: human.human_reason } : {}),
+ committed_last_10m: Number(committed?.n ?? 0), ...estimate, live_job_id: liveJob, holds, last_error: lastError, needs_human: !!human, ...(human ? { human_reason: human.human_reason } : {}),
resume_argv: resume, ...blockers, cursors: await liveCursors(engine, sourceId, source.incarnation, selected?.key ?? null, failures),
terminal_failures: terminal, next: next ?? recovery_next ?? null };
}
diff --git a/test/autopilot-freshness-not-applicable-6465.test.ts b/test/autopilot-freshness-not-applicable-6465.test.ts
index 7eb7684b3f..a7d5aedaf7 100644
--- a/test/autopilot-freshness-not-applicable-6465.test.ts
+++ b/test/autopilot-freshness-not-applicable-6465.test.ts
@@ -109,12 +109,25 @@ describe('autopilot on a brain whose source is a gbrain-owned content directory'
const first = await freshnessTick();
const second = await freshnessTick();
const jobs = await queued();
- // The checkout's two ticks coalesce on the waiting job (maxWaiting: 1); the content directory gets none.
+ // The checkout's two ticks coalesce on the pending job (maxPending: 1); the content directory gets none.
expect(jobs.map(j => [j.name, j.data.sourceId])).toEqual([['sync', 'repo-example']]);
const skips = [...first, ...second].map(l => JSON.parse(l)).filter(e => e.event === 'freshness_sync_skipped');
expect(skips).toEqual([{ event: 'freshness_sync_skipped', source_id: 'notes-example', reason: 'sync_not_applicable' }]);
}));
+ test('#6706: a tick while the source\'s sync job is draining (active, live lock) coalesces into it instead of queueing a second drainer', () => inHome(async () => {
+ const repo = checkout('repo-example');
+ await addSource('repo-example', repo);
+ await freshnessTick();
+ await engine.executeRaw(`UPDATE minion_jobs SET status='active', started_at=now(), lock_until=now() + interval '5 minutes', lock_token='drain', claim_generation=claim_generation + 1 WHERE name='sync'`);
+ await freshnessTick();
+ expect((await queued()).map(j => [j.name, j.data.sourceId])).toEqual([['sync', 'repo-example']]);
+ // A lapsed lock (a dead worker) no longer suppresses dispatch, so the source is not wedged behind it.
+ await engine.executeRaw(`UPDATE minion_jobs SET lock_until=now() - interval '1 minute' WHERE name='sync'`);
+ await freshnessTick();
+ expect((await queued()).map(j => [j.name, j.data.sourceId])).toEqual([['sync', 'repo-example'], ['sync', 'repo-example']]);
+ }));
+
test('after the user runs git init there, the next tick dispatches it', () => inHome(async () => {
const dir = ownedContentDir('notes-example');
await addSource('notes-example', dir);
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 3b0b9b20ac..0b9baf6720 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -157,6 +157,7 @@ test/sync-frontmatter-slug-conflict.test.ts
test/sync-full-cursor-slices-6349.test.ts
test/sync-full-untracked-import-5459.test.ts
test/sync-group-member-order.test.ts
+test/sync-handler-drain-6706.test.ts
test/sync-legacy-holds.test.ts
test/sync-origin-live-wins-6517.test.ts
test/sync-staged-catchup.test.ts
diff --git a/test/sync-drain-deadline-6706.test.ts b/test/sync-drain-deadline-6706.test.ts
new file mode 100644
index 0000000000..67c4d86125
--- /dev/null
+++ b/test/sync-drain-deadline-6706.test.ts
@@ -0,0 +1,140 @@
+/**
+ * #6706: a managed drain bounded by a caller deadline (the `sync` job's `timeout_at`).
+ *
+ * Protects: the drain stops `resumable / deadline` before the caller's deadline and never starts a pass after it; a past
+ * deadline makes zero passes; the earlier of the CLI run deadline and the caller deadline wins; a far deadline does not
+ * fire early (setTimeout overflow); a deadline landing in a retry backoff is a resumable report, not a throw; a pass that
+ * ignores the abort is abandoned after the grace; and `jobDisposition` classifies every drained stop.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { registerRunDeadline } from '../src/core/forward-progress.ts';
+import { deadlinePassed, jobDisposition, runDrain, type DrainReport } from '../src/core/persistence/sync-drain.ts';
+import { stampDrainStep } from '../src/core/persistence/drain-step.ts';
+import type { SyncResult } from '../src/commands/sync.ts';
+
+const base: SyncResult = { status: 'synced', fromCommit: 'a', toCommit: 'b', added: 0, modified: 0, deleted: 0, renamed: 0,
+ chunksCreated: 0, embedded: 0, pagesAffected: [] };
+const pending = (index: number, total = 10): SyncResult => ({ ...base, status: 'partial', reason: 'writer_pending', managedCursor: { index, total } });
+
+afterEach(() => registerRunDeadline(null));
+
+describe('runDrain with a caller deadline', () => {
+ test('stops resumable/deadline before the deadline and starts no pass after it', async () => {
+ const deadlineAtMs = Date.now() + 400;
+ const starts: number[] = [];
+ const result = await runDrain({ deadlineAtMs, pauseMs: 20, pass: async () => { starts.push(Date.now()); return pending(starts.length); } });
+ expect(result.drain).toMatchObject({ outcome: 'resumable', stop_reason: 'deadline' });
+ expect(result.reason).toBe('timeout');
+ expect(Date.now()).toBeLessThan(deadlineAtMs + 100);
+ expect(starts.every(at => at < deadlineAtMs)).toBe(true);
+ expect(starts.length).toBeGreaterThan(1);
+ });
+
+ test('a deadline already past makes exactly zero passes', async () => {
+ let calls = 0;
+ const result = await runDrain({ deadlineAtMs: Date.now() - 1, pass: async () => { calls++; return pending(1); } });
+ expect(calls).toBe(0);
+ expect(result.drain).toMatchObject({ outcome: 'resumable', stop_reason: 'deadline', passes: 0 });
+ });
+
+ test('the earlier of the strict run deadline and the caller deadline wins', async () => {
+ registerRunDeadline({ atMs: Date.now() + 60_000, strict: true });
+ const started = Date.now();
+ const early = await runDrain({ deadlineAtMs: Date.now() + 200, pauseMs: 10, pass: async () => pending(1) });
+ expect(early.drain?.stop_reason).toBe('deadline');
+ expect(Date.now() - started).toBeLessThan(2_000);
+ registerRunDeadline({ atMs: Date.now() + 200, strict: true });
+ const runFirst = Date.now();
+ const late = await runDrain({ deadlineAtMs: Date.now() + 60_000, pauseMs: 10, pass: async () => pending(1) });
+ expect(late.drain?.stop_reason).toBe('deadline');
+ expect(Date.now() - runFirst).toBeLessThan(2_000);
+ });
+
+ test('a deadline 30 days out does not fire early', async () => {
+ let calls = 0;
+ const result = await runDrain({ deadlineAtMs: Date.now() + 30 * 24 * 3_600_000, pauseMs: 1,
+ pass: async () => (++calls < 3 ? pending(calls) : { ...base, managedCursor: { index: 10, total: 10 } }) });
+ expect(calls).toBe(3);
+ expect(result.drain?.outcome).toBe('synced');
+ });
+
+ test('a deadline that lands in a transient retry backoff returns resumable instead of throwing', async () => {
+ let calls = 0;
+ const result = await runDrain({ deadlineAtMs: Date.now() + 150, backoffMs: 400,
+ pass: async () => { calls++; if (calls === 1) return pending(2); throw new OperationError('database_contention', 'busy'); } });
+ expect(result.drain).toMatchObject({ outcome: 'resumable', stop_reason: 'deadline', remaining: 8 });
+ });
+
+ test('a fatal error after the deadline still throws', async () => {
+ await expect(runDrain({ deadlineAtMs: Date.now() + 100, pauseMs: 1, pass: async () => {
+ await new Promise(resolve => setTimeout(resolve, 150));
+ throw new OperationError('permission_denied', 'no');
+ } })).rejects.toThrow('no');
+ });
+
+ test('a pass that ignores the abort is abandoned after the grace and its late result is dropped', async () => {
+ let lateSignal: AbortSignal | undefined;
+ const started = Date.now();
+ const result = await runDrain({ deadlineAtMs: Date.now() + 100, deadlineGraceMs: 50, pass: signal => { lateSignal = signal; return new Promise<SyncResult>(() => undefined); } });
+ expect(result.drain).toMatchObject({ outcome: 'resumable', stop_reason: 'deadline' });
+ expect(Date.now() - started).toBeLessThan(1_000);
+ expect(lateSignal?.aborted).toBe(true);
+ });
+
+ test('an abandoned pass is fenced at its next step even though the deadline aborted its signal first', async () => {
+ let passSignal: AbortSignal | undefined;
+ await runDrain({ deadlineAtMs: Date.now() + 100, deadlineGraceMs: 30, pass: signal => { passSignal = signal; return new Promise<SyncResult>(() => undefined); } });
+ expect(passSignal?.aborted).toBe(true);
+ expect((passSignal!.reason as Error).message).toBe('run deadline');
+ expect(() => stampDrainStep('admission', passSignal)).toThrow('pass abandoned');
+ });
+
+ test('a reconnect that hangs past the deadline is not awaited; the stop is resumable', async () => {
+ const drop = Object.assign(new Error('Connection terminated unexpectedly'), { code: 'ECONNRESET' });
+ let calls = 0;
+ const started = Date.now();
+ const result = await runDrain({ deadlineAtMs: Date.now() + 200, backoffMs: 1, reconnect: () => new Promise<void>(() => undefined),
+ pass: async () => { calls++; if (calls === 1) return pending(3); throw drop; } });
+ expect(result.drain).toMatchObject({ outcome: 'resumable', stop_reason: 'deadline' });
+ expect(Date.now() - started).toBeLessThan(2_000);
+ });
+
+ test('deadlinePassed is true only inside the cooperative margin', () => {
+ const now = 1_000_000;
+ expect(deadlinePassed(undefined, now)).toBe(false);
+ expect(deadlinePassed(now + 60_000, now)).toBe(false);
+ expect(deadlinePassed(now + 10_000, now)).toBe(true);
+ expect(deadlinePassed(now - 1, now)).toBe(true);
+ });
+});
+
+describe('jobDisposition', () => {
+ const drained = (drain: Partial<DrainReport>, over: Partial<SyncResult> = {}): SyncResult => ({ ...base, status: 'partial', reason: 'timeout', ...over,
+ drain: { outcome: 'resumable', passes: 1, processed: 1, written: 1, waived: 0, remaining: 3, rate_pages_per_min: null, eta_seconds: null, ...drain } });
+
+ test('a result with no drain keeps the master result (null)', () => {
+ expect(jobDisposition(base, 's')).toBeNull();
+ expect(jobDisposition({ ...base, status: 'partial', reason: 'timeout' }, 's')).toBeNull();
+ });
+
+ test.each([
+ ['synced', drained({ outcome: 'synced', remaining: 0 }, { status: 'synced', reason: undefined }), 'synced'],
+ ['deadline', drained({ stop_reason: 'deadline' }), 'continue'],
+ ['preparation_abandoned', drained({ stop_reason: 'preparation_abandoned' }), 'continue'],
+ ['connection_lost', drained({ outcome: 'blocked', stop_reason: 'connection_lost', connection: { drops: 3, last_error: 'x' } }), 'continue'],
+ ['write_capacity', drained({ outcome: 'blocked', stop_reason: 'write_capacity' }), 'needs_operator'],
+ ['database_contention', drained({ outcome: 'blocked', stop_reason: 'database_contention' }), 'needs_operator'],
+ ['preparation_systemic', drained({ outcome: 'blocked', stop_reason: 'preparation_systemic' }), 'needs_operator'],
+ ['blocked_by_failures', drained({ outcome: 'blocked', stop_reason: 'blocked_by_failures' }, { status: 'blocked_by_failures' }), 'needs_operator'],
+ ['recovery_required', drained({ outcome: 'blocked', stop_reason: 'recovery_required' }), 'needs_operator'],
+ ['owner_unavailable', drained({ outcome: 'blocked', stop_reason: 'owner_unavailable' }), 'needs_operator'],
+ ['unexpected_file_bytes', drained({ outcome: 'blocked', stop_reason: 'unexpected_file_bytes' }), 'needs_operator'],
+ ['unexpected_staging_bytes', drained({ outcome: 'blocked', stop_reason: 'unexpected_staging_bytes' }), 'needs_operator'],
+ ['drain_stalled (no progress)', drained({ outcome: 'blocked', stop_reason: 'drain_stalled', stall: { request_id: 'r', state: 'running', blocked_reason: null, head_request_id: null, head_state: null, claimable_here: null, owner_is_this_host: null, stalled_seconds: 30, cause: 'no_progress' } }), 'needs_operator'],
+ ['drain_stalled (owner wedged, ceiling ahead)', drained({ outcome: 'blocked', stop_reason: 'drain_stalled', retry_after_ms: 60_000, stall: { request_id: 'r', state: 'running', blocked_reason: null, head_request_id: null, head_state: null, claimable_here: null, owner_is_this_host: true, stalled_seconds: 300, cause: 'owner_wedged_here', past_ceiling: false, owner_pid: 1, owner_kind: 'serve' } }), 'continue'],
+ ['drain_stalled (owner wedged, past ceiling)', drained({ outcome: 'blocked', stop_reason: 'drain_stalled', retry_after_ms: 0, stall: { request_id: 'r', state: 'running', blocked_reason: null, head_request_id: null, head_state: null, claimable_here: null, owner_is_this_host: true, stalled_seconds: 700, cause: 'owner_wedged_here', past_ceiling: true, owner_pid: 1, owner_kind: 'serve' } }), 'needs_operator'],
+ ] as const)('%s', (_name, result, expected) => {
+ expect(jobDisposition(result as SyncResult, 's')).toBe(expected);
+ });
+});
diff --git a/test/sync-handler-drain-6706.test.ts b/test/sync-handler-drain-6706.test.ts
new file mode 100644
index 0000000000..026511785a
--- /dev/null
+++ b/test/sync-handler-drain-6706.test.ts
@@ -0,0 +1,208 @@
+/**
+ * #6706: the durable `sync` job drains a managed catch-up instead of landing one page per job.
+ *
+ * Forced probe: the worktree lock is held for ~6 s, so every page write outlives the single-pass 5 s wait. On master the
+ * job returned `partial / writer_pending` with no page; with the drain the same job lands every page. Also: a deadline
+ * stop with progress queues exactly one continuation; `drain: false` keeps the single pass; a job whose source already
+ * has a live sync job skips; the job result carries the CLI's outcome / drain / next fields.
+ * Runs on PGLite and, with DATABASE_URL, on an isolated Postgres (the managed-sync-drain.test.ts dual-engine pattern).
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { execFileSync } from 'node:child_process';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { MinionJobContext } from '../src/core/minions/types.ts';
+import { acquireWorktree, claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { makeSyncHandler } from '../src/core/minions/handlers/sync.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-job-drain-'));
+const engines: BrainEngine[] = [];
+const sources: string[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+function git(root: string, ...args: string[]): string { return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); }
+async function fixture(engine: BrainEngine, count: number) {
+ const id = `jobdrain-${randomUUID().replace(/-/g, '').slice(0, 16)}`; sources.push(id);
+ const root = join(home, id); mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ for (let i = 0; i < count; i++) writeFileSync(join(root, 'notes', `n${i}.md`), `---\ntitle: Note ${i}\n---\nA durable observation number ${i}.\n`);
+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return { id, root };
+}
+const progress: unknown[] = [];
+function job(id: number, data: Record<string, unknown>, deadlineAtMs: number | null = Date.now() + 120_000): MinionJobContext {
+ return { id, name: 'sync', data, attempts_made: 0, signal: new AbortController().signal, shutdownSignal: new AbortController().signal, deadlineAtMs,
+ updateProgress: async (p: unknown) => { progress.push(p); }, updateTokens: async () => undefined, log: async () => undefined,
+ isActive: async () => true, readInbox: async () => [] } as unknown as MinionJobContext;
+}
+/** A real queue row, marked active with a live lock as a worker claim would leave it. */
+async function activeJob(engine: BrainEngine, data: Record<string, unknown>, opts: { startedAgoSec?: number; timeoutMs?: number; priority?: number } = {}): Promise<number> {
+ const row = await new MinionQueue(engine).add('sync', data, { ...(opts.timeoutMs ? { timeout_ms: opts.timeoutMs } : {}), ...(opts.priority !== undefined ? { priority: opts.priority } : {}) });
+ await engine.executeRaw(`UPDATE minion_jobs SET status='active', started_at=now() - make_interval(secs => $2), lock_until=now() + interval '5 minutes', lock_token=$3, claim_generation=claim_generation + 1 WHERE id=$1`,
+ [row.id, opts.startedAgoSec ?? 0, `tok-${row.id}`]);
+ return row.id;
+}
+const pageCount = async (engine: BrainEngine, id: string) => (await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE source_id=$1', [id]))[0]!.n;
+/** Holds the source's worktree for `ms`, so each admitted page write waits longer than the single-pass 5 s. */
+async function holdWorktree(engine: BrainEngine, id: string, ms: number | null) {
+ const lock = await acquireWorktree((await getWorktreeBinding(engine, id))!);
+ expect(lock).not.toBeNull();
+ if (ms !== null) setTimeout(() => { void lock!.release(); }, ms);
+ return { release: () => lock!.release() };
+}
+
+beforeAll(async () => {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }
+}, 120_000);
+afterAll(async () => {
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ for (const id of sources) await engine.executeRaw('DELETE FROM sources WHERE id=$1', [id]); await engine.disconnect(); }
+ });
+ await closePostgres?.();
+ rmSync(home, { recursive: true, force: true });
+});
+
+test('forced probe: writes slower than the 5 s single-pass wait all land in one drained job', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ await disposePersistenceConsumer(engine);
+ const f = await fixture(engine, 4);
+ const hold = await holdWorktree(engine, f.id, 6_500);
+ try {
+ const result = await makeSyncHandler(engine)(job(910_001, { sourceId: f.id, repoPath: f.root, pull: false, auto_embed_backfill: false })) as Record<string, unknown>;
+ expect(result).toMatchObject({ outcome: 'synced', incomplete: false, drain: { outcome: 'synced', remaining: 0 } });
+ expect(await pageCount(engine, f.id)).toBe(4);
+ expect(progress.length).toBeGreaterThan(0);
+ } finally { await hold.release(); await disposePersistenceConsumer(engine); }
+ }
+}), 240_000);
+
+test('drain:false keeps the single pass: the same slow write returns writer_pending with no page', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ await disposePersistenceConsumer(engine);
+ const f = await fixture(engine, 3);
+ const hold = await holdWorktree(engine, f.id, null);
+ try {
+ const result = await makeSyncHandler(engine)(job(910_002, { sourceId: f.id, repoPath: f.root, pull: false, auto_embed_backfill: false, drain: false })) as Record<string, unknown>;
+ expect(result).toMatchObject({ status: 'partial', reason: 'writer_pending' });
+ expect(result.drain).toBeUndefined();
+ expect(result.incomplete).toBeUndefined();
+ expect(await pageCount(engine, f.id)).toBe(0);
+ } finally { await hold.release(); await disposePersistenceConsumer(engine); }
+ }
+}), 240_000);
+
+test('a deadline stop with progress queues one continuation on a worker-backed brain; no progress, or PGLite, queues none', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { settleJobDrain, planJobDrain } = await import('../src/core/minions/handlers/sync-job-drain.ts');
+ for (const engine of engines) {
+ const f = await fixture(engine, 1);
+ const data = { sourceId: f.id, repoPath: f.root, pull: false, embed_reason: 'autopilot_freshness' };
+ const parentId = await activeJob(engine, data, { timeoutMs: 600_000, priority: 0 });
+ const ctx = job(parentId, data, null);
+ const plan = await planJobDrain(engine, ctx);
+ expect(plan.opts).toMatchObject({ drain: true, lanes: 1 });
+ expect(plan.opts.deadlineAtMs!).toBeLessThan(Date.now() + 2 * 600_000);
+ const stopped = (processed: number) => ({ status: 'partial' as const, reason: 'timeout' as const, fromCommit: null, toCommit: 'b', added: processed, modified: 0, deleted: 0, renamed: 0,
+ chunksCreated: 0, embedded: 0, pagesAffected: Array.from({ length: 80 }, (_, i) => `p${i}`), managedCursor: { index: processed, total: 10 },
+ drain: { outcome: 'resumable' as const, stop_reason: 'deadline' as const, passes: 2, processed, written: processed, waived: 0, remaining: 10 - processed, rate_pages_per_min: null, eta_seconds: null } });
+ const none = await settleJobDrain(engine, ctx, stopped(0), f.id, plan);
+ expect(none).toMatchObject({ outcome: 'resumable', incomplete: true, continuation_job_id: null, next: { safe_to_loop: true } });
+ const out = await settleJobDrain(engine, ctx, stopped(4), f.id, plan);
+ expect(out).toMatchObject({ outcome: 'resumable', incomplete: true, drain: { stop_reason: 'deadline', remaining: 6 }, pages_affected_count: 80 });
+ expect((out.pagesAffected as string[]).length).toBe(50);
+ const followId = out.continuation_job_id as number | null;
+ if (engine.kind === 'pglite') {
+ expect(followId).toBeNull();
+ expect((out.next as { command: string }).command).toContain(`sync --source ${f.id}`);
+ } else {
+ expect(typeof followId).toBe('number');
+ expect(out.next).toMatchObject({ command: `gbrain sources status ${f.id} --json`, safe_to_loop: true, retry_after_ms: 30_000 });
+ expect((out.next as Record<string, unknown>).fix).toBeUndefined();
+ const [follow] = await engine.executeRaw<{ data: Record<string, unknown> | string; priority: number; timeout_ms: number; status: string }>('SELECT data, priority, timeout_ms, status FROM minion_jobs WHERE id=$1', [followId]);
+ expect(typeof follow!.data === 'string' ? JSON.parse(follow!.data) : follow!.data).toMatchObject({ sourceId: f.id, continuation_of: parentId });
+ expect(Number(follow!.priority)).toBe(5);
+ expect(Number(follow!.timeout_ms)).toBe(600_000);
+ expect(follow!.status).toBe('waiting');
+ const again = await settleJobDrain(engine, ctx, stopped(5), f.id, plan);
+ expect(again.continuation_job_id).toBe(followId);
+ }
+ await engine.executeRaw("DELETE FROM minion_jobs WHERE name='sync' AND (id=$1 OR data->>'continuation_of'=$2)", [parentId, String(parentId)]);
+ }
+}), 120_000);
+
+test('a continuation is not skipped by its own parent, which is still active while the worker records its completion', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const engine = engines[0]!;
+ const f = await fixture(engine, 1);
+ const data = { sourceId: f.id, repoPath: f.root, pull: false, auto_embed_backfill: false };
+ const parent = await activeJob(engine, data, { startedAgoSec: 60 });
+ const child = await activeJob(engine, { ...data, continuation_of: parent });
+ try {
+ const result = await makeSyncHandler(engine)(job(child, { ...data, continuation_of: parent })) as Record<string, unknown>;
+ expect(result.skipped).toBeUndefined();
+ expect(await pageCount(engine, f.id)).toBe(1);
+ } finally { await engine.executeRaw('DELETE FROM minion_jobs WHERE id = ANY($1::bigint[])', [[parent, child]]); await disposePersistenceConsumer(engine); }
+}), 120_000);
+
+test('a job for a source another live sync job is draining completes as a skip', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const engine = engines[0]!;
+ const f = await fixture(engine, 1);
+ const data = { sourceId: f.id, repoPath: f.root, pull: false };
+ const running = await activeJob(engine, data, { startedAgoSec: 60 });
+ const mine = await activeJob(engine, data);
+ try {
+ const result = await makeSyncHandler(engine)(job(mine, data));
+ expect(result).toMatchObject({ skipped: true, reason: 'sync_in_progress', source_id: f.id, running_job_id: running,
+ next: { command: `gbrain jobs get ${running} --json`, safe_to_loop: true } });
+ expect(await pageCount(engine, f.id)).toBe(0);
+ } finally { await engine.executeRaw('DELETE FROM minion_jobs WHERE id = ANY($1::bigint[])', [[running, mine]]); }
+}), 120_000);
+
+test('an accepted remote sync job drains through the handler: worker drain controls pass the remote option allowlist', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { prepareRemoteJob, withSubmissionAuthority } = await import('../src/core/minions/submission-authority.ts');
+ for (const engine of engines) {
+ await disposePersistenceConsumer(engine);
+ const f = await fixture(engine, 3);
+ const clientId = `sync-client-${randomUUID()}`;
+ await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_name,client_secret_hash,scope,source_id,allowed_operations)
+ VALUES($1,'example-client','test-only','admin',$2,ARRAY['submit_job'])`, [clientId, f.id]);
+ const ctx = { engine, remote: true, sourceId: f.id, auth: { clientId, principal: { kind: 'oauth_client', id: clientId }, scopes: ['admin'], sourceId: f.id, allowedOperations: ['submit_job'] } } as unknown as import('../src/core/ops/contract.ts').OperationContext;
+ const accepted = await prepareRemoteJob(ctx, 'sync', { noPull: true });
+ const remoteJob = { ...job(910_100, { ...accepted.data, lanes: 8, drain: false }), submission_authority: accepted.authority } as MinionJobContext;
+ try {
+ const result = await withSubmissionAuthority(accepted.authority, () => makeSyncHandler(engine)({ ...remoteJob, data: accepted.data } as MinionJobContext)) as Record<string, unknown>;
+ expect(result).toMatchObject({ outcome: 'synced', drain: { outcome: 'synced' } });
+ expect(await pageCount(engine, f.id)).toBe(3);
+ const { planJobDrain } = await import('../src/core/minions/handlers/sync-job-drain.ts');
+ // Drain controls in a remote job's data are never read: lanes stay 1 and drain stays on.
+ expect((await planJobDrain(engine, remoteJob)).opts).toMatchObject({ drain: true, lanes: 1 });
+ } finally { await disposePersistenceConsumer(engine); await engine.executeRaw('DELETE FROM oauth_clients WHERE client_id=$1', [clientId]); }
+ }
+}), 240_000);
+
+test('a live sync job reads as the source\'s live drain in movement, and a lapsed one does not', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { readSourceMovement, liveSyncJob } = await import('../src/core/persistence/sync-movement.ts');
+ for (const engine of engines) {
+ const f = await fixture(engine, 1);
+ const id = await activeJob(engine, { sourceId: f.id, repoPath: f.root, pull: false });
+ try {
+ expect(await liveSyncJob(engine, f.id)).toBe(id);
+ const [m] = await readSourceMovement(engine, { sourceIds: [f.id] });
+ expect(m!.live).toMatchObject({ drain: true, drain_pid: null, drain_job_id: id });
+ await engine.executeRaw(`UPDATE minion_jobs SET lock_until=now() - interval '1 minute' WHERE id=$1`, [id]);
+ expect(await liveSyncJob(engine, f.id)).toBeNull();
+ const [lapsed] = await readSourceMovement(engine, { sourceIds: [f.id] });
+ expect(lapsed!.live).toMatchObject({ drain: false, drain_job_id: null });
+ } finally { await engine.executeRaw('DELETE FROM minion_jobs WHERE id=$1', [id]); }
+ }
+}), 120_000);
diff --git a/test/sync-movement.test.ts b/test/sync-movement.test.ts
index 2492006f03..5138d12c4d 100644
--- a/test/sync-movement.test.ts
+++ b/test/sync-movement.test.ts
@@ -280,14 +280,14 @@ describe('gbrain sources writer movement (I2, T4)', () => {
const sampledAt = ago(0), committedAt = ago(1_000);
const base = (over: Record<string, unknown>) => ({ source_id: 's', sampled_at: sampledAt, movement_state: 'moving', data_moving: true, not_moving_since: null, last_commit_at: committedAt, last_progress_at: committedAt,
cursor: { index: 1, total: 4, remaining: 3, held: 0, last_progress_at: null, resume_command: 'gbrain sync --source s --no-pull' }, head: null, holds: { count: 0, stalled: 0, fences: 0, concurrent: 0, last_hold_at: null },
- admitted: 1, live: { drain: true, drain_pid: 1, consumer: null }, ceiling_ms: 600_000, owner_is_this_host: true, writer_status_command: 'gbrain sources writer status --source s --json', ...over }) as Parameters<typeof movementReport>[1];
+ admitted: 1, live: { drain: true, drain_pid: 1, drain_job_id: null, consumer: null }, ceiling_ms: 600_000, owner_is_this_host: true, writer_status_command: 'gbrain sources writer status --source s --json', ...over }) as Parameters<typeof movementReport>[1];
const states: Array<[ReturnType<typeof judgeMovement>, Parameters<typeof movementReport>[0], Parameters<typeof movementReport>[1]]> = [
['nothing_pending', undefined, base({ movement_state: 'nothing_pending', cursor: null, data_moving: null })],
['moved', base({ last_commit_at: ago(100_000) }), base({})],
['within_allowance', base({ head: { request_id: 'r', state: 'running', phase: 'preparing', step: 'a', step_since: ago(50_000), step_age_ms: 50_000, waiting_on: 'db', owner: null, last_sql: null, lapsed: false } }),
base({ last_commit_at: null, head: { request_id: 'r', state: 'running', phase: 'preparing', step: 'b', step_since: ago(1_000), step_age_ms: 1_000, waiting_on: 'db', owner: null, last_sql: null, lapsed: false } })],
['held', base({ holds: { count: 0, stalled: 0, fences: 0, concurrent: 0, last_hold_at: null } }), base({ holds: { count: 1, stalled: 0, fences: 1, concurrent: 0, last_hold_at: ago(0) } })],
- ['parked', base({ movement_state: 'parked', live: { drain: false, drain_pid: null, consumer: null } }), base({ movement_state: 'parked', live: { drain: false, drain_pid: null, consumer: null } })],
+ ['parked', base({ movement_state: 'parked', live: { drain: false, drain_pid: null, drain_job_id: null, consumer: null } }), base({ movement_state: 'parked', live: { drain: false, drain_pid: null, drain_job_id: null, consumer: null } })],
['not_moving', base({}), base({})],
];
for (const [expected, before, after] of states) {