Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge Lane C (honest waits, no-op waivers) into the #5984 drain; drain stops on blocked or failed waits; skip recovery cleanup reads without a recovery record

garrytan1bca62035d3a
diff --cc docs/architecture/key-files/google-and-loops-continued.md
index 4f3831d37a,b804111c2f..1dad45b15d
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@@ -16,8 -16,7 +16,8 @@@
- `src/core/persistence/diagnostics.ts` — trusted administrator counts for owners/epochs, queued bytes/age, outbox recovery, configured quota usage and actionable capacity warnings; bigint values are transport-safe strings and diagnostics exclude intent, credentials and private paths.
- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision snapshots. Reserved skillpack paths (`skills/` at any depth and `skillpack.json`, `src/core/skill-reserved-paths.ts`) never enter discovery: the shared skill publisher owns them and `managedImportContent` refuses them, so a seeded pack cannot block a sync. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Deleting a file that no page records as its origin (for example a skipped slug twin) while its slug's page keeps another origin commits an explicit no-op receipt (`unownedDeletion`, outcome reason `unowned_deleted_path`) that preserves that live page or tombstone; freeze and publication re-prove that no page owns the path and that the file is still absent. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity. On Windows a path containing `:` is reported in `SyncDiscovery.fileRefusals` (code `colon_slug_windows_write_through`, with its filled `gbrain sync --source <id> --no-pull` hint) and kept out of the run and its origin checks, so one such file no longer fails the whole sync (#5032).
+- **`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`. Tests: `test/sync-drain.test.ts`, `test/managed-sync-drain.test.ts`.
- - **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. 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`. 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.
+ - **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. 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`). #5984: the no-op screens live in `sync-waivers.ts` (unchanged imports and deletes of already soft-deleted pages); waived entries count under `waived: { imports, deletes }` in the cursor and `SyncResult`, never under `deleted`, while `legacySkips` keeps its #5751 kernel breakdown. The admission transaction re-reads the cursor row `FOR SHARE` after its counter locks and admits only while the cursor still holds the frozen entry. A still-unfinished wait returns the single-pass `partial/writer_pending` (or `timeout`) result plus `writeWait`: `pending`, `blocked` (a head whose `blocked_reason` is `recovery_required`, `owner_unavailable`, `unexpected_file_bytes` or `unexpected_staging_bytes`, with `gbrain sources writer status <source> --json`) or a classified `read_failed`, always with the request ID. A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. 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.
- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin. `noEmbed` suppresses the effect itself; `noSchemaPack` bypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. A filename-derived slug mismatch is accepted on every platform only when the page's stored canonical path is this file and the parsed slug is that page's slug; a different declared slug still refuses. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. The checkpoint validates receipts through `checkpoint-validation.ts` and, for a run whose entries another cursor imported (`overtaken`, #5522), also commits when that cursor already checkpointed the same target. Tests: `persistence-sync-origin-native.serial.test.ts`, `persistence-sync-options.serial.test.ts`, `persistence-sync-company.serial.test.ts`. A same-slug `renameFrom` accepts the page's recorded old origin. A different-slug rename prepares against the page where it stands, locks the old slug as an additional page key, and at publication moves the page with `updateSlug` (same id, inbound links and history, `old -> new` in `slug_aliases`, withdrawn claims follow), re-infers an implicit type from the new path, then re-prepares and applies the file content at the new slug, so the move never writes back to the file. Tests: `persistence-managed-lifecycle.test.ts`.
- **`src/core/persistence/links-maintenance.ts`** — `extractManagedStaleLinks` derives links for pages whose extraction watermark is stale with `prepareAutomaticLinks` (put_page's replace contract; other producers' edges stay) and adds the coordinator's unrecorded canonical timeline tuples (insert-only) and each page's watermark in the same `withCoordinatedWrite` transaction, bound to the revision it read; an edited page or unresolved attendance stays stale. A page skipped for unresolved attendance is marked attendance-blocked at that revision (`pages.links_attendance_blocked_revision` / `_at`, written by `markPagesAttendanceBlocked` in `engine-sql/pages.ts` only while the revision still matches, cleared by `markPagesExtractedBatch` with the watermark); it is still reconsidered every run, and the `links_extraction_lag` doctor check counts it apart from lag while the marker equals the page's current revision. It is the one managed extraction path: managed sync, `extractStaleFromDB` on a managed brain, and the owner delegation all run it. `runManagedStaleExtraction` backs `gbrain extract --stale` on managed brains, locally or through the `writer_extract_stale` administration operation inside a PGLite owner (`src/commands/extract-stale-delegate.ts`, trusted CLI registration only). `links-preparation.ts` retargets a link written against a renamed page's old slug to the live canonical page through `slug_aliases`, as `get_page` does. Tests: `persistence-managed-lifecycle.test.ts`, `persistence-sync-stdio-owner.serial.test.ts`.
- **`src/core/persistence/sync-authority.ts`** — trusted CLI or original remote generic job authority; rejects stdio bulk privilege promotion and runtime option expansion, intersects original grants with current principal/source policy.
diff --cc docs/guides/write-refusals.md
index a94253f549,d4532bffaa..76bc49afbb
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@@ -147,26 -146,6 +147,26 @@@ that already reached the verified upstr
reports `worktree_refresh_stuck` for a refresh active longer than 15 minutes,
with the resume command.
+## Managed sync drain stops
+
+`gbrain sync` on a managed brain keeps going until the source's cursor is done
+(see [catching up a large backlog](live-sync.md#catching-up-a-large-backlog-on-managed-postgres)).
+When it stops early, the run ends in one outcome: `resumable` (exit 0, safe to
+rerun the same command) or `blocked` (exit 1, needs a fix first). `--json`
+carries `outcome`, `drain.stop_reason` and `next: { command, safe_to_loop,
+retry_after_ms, eta_seconds, rate_pages_per_min, why, docs }`. Run
+`next.command`; loop on it only when `next.safe_to_loop` is true.
+
+**Say to your agent:** *"Catch up my managed brain's sync backlog and tell me how long it will take."*
+
+| 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-stalled"></a>`drain_stalled` | `drain_stalled` | `blocked` | The awaited page write and the oldest unfinished write on its checkout did not change for 30 s across several passes, and nothing on this host can claim it. `drain.stall` names the request, its state, `blocked_reason` and whether this host owns the checkout. | `gbrain sources writer status <source>`. When this host is not the owner, make sure the owner (`gbrain serve`) is running. Then rerun `next.command`. |
- | <a id="drain-database-contention"></a>`database_contention` | `database_contention` | error | Three consecutive passes hit database contention, a statement timeout or a dropped connection. The drain retries these with backoff before giving up. | Rerun the same command. If it repeats, check the database or pooler (`gbrain engine status --probe`). |
++| <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`. |
+| <a id="drain-blocked-by-a-failed-page"></a>`blocked_by_failures` | `blocked_by_failures` | `blocked` | A page write failed terminally. `managed_write` and `failures` name the page and cause. Rerunning without a fix returns the same failure. | Fix the cause, then run `next.command` (it adds `--retry-failed`). Ask the user before skipping content. |
+
## Unbound sources on Postgres
A source with a checkout path (`local_path`, or `sync.repo_path` for the
diff --cc src/core/persistence/consumer.ts
index a4ac6b8c27,32399a7736..4d434d8763
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@@ -485,9 -494,7 +495,9 @@@ export class PersistenceConsumer
}
const current = await getWriteRequestById(this.engine, row.id);
if (current && !isTerminal(current) && current.execution_token === row.execution_token && !current.recovery) {
- return this.settled(await finishUnpublishedFailure(this.engine, current, error));
+ const done = await finishUnpublishedFailure(this.engine, current, error, preparationActive ? 'preparation' : 'publication');
+ if (done.state === 'failed') this.log(preparationActive ? 'preparation' : 'publication', done.error_code ?? 'storage_error', done.error_message ?? undefined);
- return isTerminal(done);
++ return this.settled(done);
}
throw error;
} finally {
diff --cc src/core/persistence/coordinator.ts
index 157358d331,cc6b8f2606..d009c33b32
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@@ -262,7 -258,7 +262,7 @@@ export async function publishMutation(e
return committed;
});
await hooks.boundary?.('after_commit', done);
-- await clearResolvedRecovery(engine, row.id);
++ if (recovery) await clearResolvedRecovery(engine, row.id);
return done;
} catch (error) {
if (recovery) {
diff --cc src/core/persistence/sync-drain.ts
index e408cc14a0,0000000000..d8e14a66bd
mode 100644,000000..100644
--- a/src/core/persistence/sync-drain.ts
+++ b/src/core/persistence/sync-drain.ts
@@@ -1,368 -1,0 +1,381 @@@
+/**
+ * #5984: drain a managed sync to completion in one invocation.
+ *
+ * `performManagedSync` is single-pass by contract (ENG-A1): it returns
+ * `partial / writer_pending` when a page's write outlives its wait and
+ * `partial / writer_yield` at a slice boundary. Callers that want a whole
+ * catch-up (the CLI, `--all`, `--watch`, the PGLite owner delegate) re-enter it
+ * through `runDrain`, which owns the stop rules: the caller's signal and
+ * deadline, a cooperative stop before a strict out-of-band deadline, named
+ * transient retries, blocked heads and the no-progress detector. Every drain
+ * ends in one outcome (`synced`, `resumable`, `blocked`) carried on
+ * `SyncResult.drain`; the CLI turns it into the exit code and `next`.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { SyncOpts, SyncResult } from '../../commands/sync.ts';
+import { OperationError } from '../ops/contract.ts';
+import { getCode, isRetryableConnError, isStatementTimeoutError } from '../retry-matcher.ts';
+import { currentRunDeadline, noteForwardProgress } from '../forward-progress.ts';
+import { serr } from '../console-prefix.ts';
+import { ERROR_CATALOGUE, type CatalogueName } from '../error-catalogue.ts';
+
+export type DrainOutcome = 'synced' | 'resumable' | 'blocked';
+/** Why a drain ended short of `synced`. Each value has an error-catalogue entry (DX-A4). */
+export type DrainStopReason = 'deadline' | 'drain_stalled' | 'database_contention' | 'recovery_required' | 'owner_unavailable'
+ | 'unexpected_file_bytes' | 'unexpected_staging_bytes' | 'blocked_by_failures';
+export interface DrainStall {
+ request_id: string;
+ state: string;
+ blocked_reason: string | null;
+ head_request_id: string | null;
+ head_state: string | null;
+ claimable_here: boolean;
+ owner_is_this_host: boolean | null;
+ stalled_seconds: number;
+}
+export interface DrainReport {
+ outcome: DrainOutcome;
+ stop_reason?: DrainStopReason;
+ passes: number;
+ /** Entries processed by this drain (written + waived). */
+ processed: number;
+ written: number;
+ waived: number;
+ remaining: number | null;
+ rate_pages_per_min: number | null;
+ /** Indexing ETA for the remaining manifest at the observed rate; null while the rate is unknown. */
+ eta_seconds: number | null;
+ retry_after_ms?: number;
+ stall?: DrainStall;
+}
+
+const TERMINAL_STATUSES = new Set(['synced', 'first_sync', 'up_to_date', 'dry_run']);
+const BLOCKED_HEAD_REASONS = new Set(['recovery_required', 'owner_unavailable', 'unexpected_file_bytes', 'unexpected_staging_bytes']);
+const PENDING_PAUSE_MS = 250;
+const STALL_MS = 30_000;
+const STALL_PASSES = 3;
+const TRANSIENT_ATTEMPTS = 3;
+const REFRESH_WAIT_MS = 5 * 60_000;
+const DEADLINE_MARGIN_MS = 15_000;
+const PROGRESS_EVERY_MS = 10_000;
+
+function continues(result: SyncResult): boolean {
+ return result.status === 'partial' && (result.reason === 'writer_pending' || result.reason === 'writer_yield');
+}
+
+/**
+ * The outcome of any sync result. A drained result carries its own verdict.
+ * A single-pass result with a still-pending managed write keeps the historical
+ * failure verdict, because nothing re-enters it.
+ */
+export function syncOutcome(result: Pick<SyncResult, 'status' | 'reason' | 'managedWrite' | 'drain'>): DrainOutcome {
+ if (result.drain) return result.drain.outcome;
+ if (TERMINAL_STATUSES.has(result.status)) return 'synced';
+ if (result.status === 'blocked_by_failures' || result.managedWrite) return 'blocked';
+ if (result.reason === 'pull_failed' || result.reason === 'connector_item_failures' || result.reason === 'connector_partial') return 'blocked';
+ return 'resumable';
+}
+
+/**
+ * Remaining entries, observed rate and indexing ETA. The rate covers only this
+ * drain's window, so downtime between runs never depresses it; zero progress
+ * means the rate is unknown, never a zero or infinite ETA.
+ */
+export function drainEstimate(remaining: number | null, processed: number, elapsedMs: number): { rate_pages_per_min: number | null; eta_seconds: number | null } {
+ if (processed <= 0 || elapsedMs <= 0) return { rate_pages_per_min: null, eta_seconds: null };
+ const perMin = processed / (elapsedMs / 60_000);
+ return { rate_pages_per_min: Math.round(perMin * 10) / 10, eta_seconds: remaining === null ? null : Math.ceil(remaining / perMin * 60) };
+}
+
+export function formatDuration(seconds: number): string {
+ if (seconds < 60) return `${seconds}s`;
+ const h = Math.floor(seconds / 3600), m = Math.floor(seconds % 3600 / 60);
+ return h ? `${h}h${String(m).padStart(2, '0')}m` : `${m}m${String(seconds % 60).padStart(2, '0')}s`;
+}
+
+/** Named transient failures the drain retries; anything else ends the drain (CEO-A31). */
+function transientDelay(error: unknown, attempt: number, refreshWaitedMs: number, baseMs: number): number | null {
+ if (error instanceof OperationError && error.code === 'worktree_refreshing') {
+ if (refreshWaitedMs >= REFRESH_WAIT_MS) return null;
+ const hinted = Number(/retry_after_ms=(\d+)/.exec(String(error.detail ?? ''))?.[1]);
+ return Number.isFinite(hinted) && hinted > 0 ? hinted : 1000;
+ }
+ if (attempt > TRANSIENT_ATTEMPTS) return null;
+ const contention = error instanceof OperationError && error.code === 'database_contention';
+ if (!contention && !isRetryableConnError(error) && !isStatementTimeoutError(error) && getCode(error) !== '57014') return null;
+ return baseMs * 4 ** (attempt - 1);
+}
+
+function sleep(ms: number, signal?: AbortSignal): Promise<void> {
+ if (signal?.aborted) return Promise.resolve();
+ return new Promise(resolve => {
+ const timer = setTimeout(done, ms);
+ function done() { clearTimeout(timer); signal?.removeEventListener('abort', done); resolve(); }
+ signal?.addEventListener('abort', done, { once: true });
+ });
+}
+
+/** 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();
+ 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?.();
+ return { signal: controller.signal, dispose: () => clearTimeout(timer) };
+}
+
+export interface StallProbe {
+ /** A head that needs an operator stops the drain at once; otherwise null. */
+ blockedHead(result: SyncResult): Promise<{ reason: DrainStopReason; stall: DrainStall } | null>;
+ /** A fingerprint of the awaited request and the worktree head; unchanged across the stall window means no progress. */
+ fingerprint(result: SyncResult): Promise<{ key: string; stall: Omit<DrainStall, 'stalled_seconds'> } | null>;
+}
+
+export interface DrainInput {
+ pass(signal: AbortSignal | undefined, onProgress: NonNullable<SyncOpts['onProgress']>): Promise<SyncResult>;
+ signal?: AbortSignal;
+ onProgress?: SyncOpts['onProgress'];
+ probe?: StallProbe;
+ /** Throttled progress lines on stderr (CLI). */
+ announce?: boolean;
+ /** Test seams: the no-progress window, the pause after a pending write and the transient backoff base. */
+ stallMs?: number;
+ pauseMs?: number;
+ backoffMs?: number;
+}
+
+/** Re-enter `pass` until the managed cursor is done, the caller stops it, or it is blocked. */
+export async function runDrain(input: DrainInput): Promise<SyncResult> {
+ const startedAt = Date.now();
+ const coop = cooperativeDeadline();
+ const signal = coop.signal && input.signal ? AbortSignal.any([input.signal, coop.signal]) : coop.signal ?? input.signal;
- let passes = 0, attempt = 0, refreshWaitedMs = 0, written = 0, waived = 0, index = 0, total: number | null = null;
++ let passes = 0, attempt = 0, readFailures = 0, refreshWaitedMs = 0, written = 0, waived = 0, index = 0, total: number | null = null;
+ let announcedStart = false, lastLine = 0;
+ let stall: { key: string; since: number; passes: number } | null = null;
+ const remaining = () => total === null ? null : Math.max(0, total - index);
+ const onProgress: NonNullable<SyncOpts['onProgress']> = event => {
+ input.onProgress?.(event);
+ if (typeof event.total === 'number') total = event.total;
+ if (typeof event.bankedFiles === 'number') index = event.bankedFiles;
+ if (event.phase === 'managed_sync.start' && input.announce && !announcedStart) {
+ announcedStart = true;
+ serr(`[sync] managed catch-up: ${total ?? '?'} entries frozen, ${remaining() ?? '?'} remaining; one write request per page.`);
+ }
+ if (event.phase !== 'managed_sync.page_committed') return;
+ if (event.waived) waived++; else written++;
+ noteForwardProgress();
+ if (input.announce && Date.now() - lastLine >= PROGRESS_EVERY_MS) {
+ lastLine = Date.now();
+ const estimate = drainEstimate(remaining(), written + waived, Date.now() - startedAt);
+ serr(`[sync] ${index}/${total ?? '?'} processed (${written} written, ${waived} waived this run) · `
+ + `${estimate.rate_pages_per_min ?? '?'} pages/min · indexing ETA ${estimate.eta_seconds === null ? 'unknown' : formatDuration(estimate.eta_seconds)}`);
+ }
+ };
+ const finish = (result: SyncResult, outcome: DrainOutcome, stopReason?: DrainStopReason, extra?: Partial<DrainReport>): SyncResult => {
+ if (result.managedCursor) { index = result.managedCursor.index; total = result.managedCursor.total; }
+ const left = outcome === 'synced' ? 0 : remaining();
+ if (stopReason === 'deadline' && continues(result)) result = { ...result, reason: 'timeout' };
+ return { ...result, drain: { outcome, ...(stopReason ? { stop_reason: stopReason } : {}), passes, processed: written + waived, written, waived,
+ remaining: left, ...drainEstimate(left, written + waived, Date.now() - startedAt), ...extra } };
+ };
+ try {
+ for (;;) {
+ passes++;
+ let result: SyncResult;
+ try {
+ result = await input.pass(signal, onProgress);
+ attempt = 0;
+ } catch (error) {
+ const delay = transientDelay(error, ++attempt, refreshWaitedMs, input.backoffMs ?? 250);
+ if (delay === null || signal?.aborted) throw error;
+ if (error instanceof OperationError && error.code === 'worktree_refreshing') refreshWaitedMs += delay;
+ await sleep(delay, signal);
+ continue;
+ }
+ if (!continues(result)) {
+ if (TERMINAL_STATUSES.has(result.status)) return finish(result, 'synced');
+ if (result.status === 'blocked_by_failures') return finish(result, 'blocked', 'blocked_by_failures');
+ if (result.managedWrite && result.managedWrite.write_error !== 'write_pending') return finish(result, 'blocked', 'blocked_by_failures');
+ const outcome = syncOutcome({ ...result, drain: undefined });
+ return finish(result, outcome, outcome === 'resumable' ? 'deadline' : undefined);
+ }
+ if (signal?.aborted) return finish(result, 'resumable', 'deadline');
++ const wait = result.writeWait;
++ if (wait?.status === 'blocked') {
++ return finish(result, 'blocked', BLOCKED_HEAD_REASONS.has(wait.cause) ? wait.cause as DrainStopReason : 'recovery_required');
++ }
++ if (wait?.status === 'read_failed') {
++ if (!wait.transient || ++readFailures >= TRANSIENT_ATTEMPTS) return finish(result, 'blocked', 'database_contention');
++ } else readFailures = 0;
+ if (result.reason === 'writer_pending' && input.probe) {
+ const blocked = await input.probe.blockedHead(result);
+ if (blocked) return finish(result, 'blocked', blocked.reason, { stall: blocked.stall });
+ const print = await input.probe.fingerprint(result);
+ if (print) {
+ if (!stall || stall.key !== print.key) stall = { key: print.key, since: Date.now(), passes: 0 };
+ else if (++stall.passes >= STALL_PASSES && Date.now() - stall.since >= (input.stallMs ?? STALL_MS) && !print.stall.claimable_here) {
+ return finish(result, 'blocked', 'drain_stalled', { stall: { ...print.stall, stalled_seconds: Math.round((Date.now() - stall.since) / 1000) } });
+ }
+ }
+ } else stall = null;
+ if (result.reason === 'writer_pending') await sleep(input.pauseMs ?? PENDING_PAUSE_MS, signal);
+ }
+ } finally {
+ coop.dispose();
+ }
+}
+
+/** Engine-backed stall checks: the awaited request, the oldest unfinished request on its worktree, and claimability here. */
+export function engineStallProbe(engine: BrainEngine): StallProbe {
+ const read = async (result: SyncResult) => {
+ const requestId = result.managedWrite?.write_request.request_id;
+ if (!requestId) return null;
+ const [row] = await engine.executeRaw<{ state: string; updated_at: string; claim_expires_at: string | null; blocked_reason: string | null; recovering: boolean;
+ worktree_id: string | null; head_id: string | null; head_state: string | null; head_updated_at: string | null; owner_host_id: string | null }>(
+ `SELECT r.state, r.updated_at::text, r.claim_expires_at::text, r.blocked_reason, r.recovery IS NOT NULL AS recovering, r.worktree_id::text,
+ h.id::text AS head_id, h.state AS head_state, h.updated_at::text AS head_updated_at, w.owner_host_id::text
+ FROM persistence_requests r
+ LEFT JOIN persistence_worktrees w ON w.id = r.worktree_id
+ LEFT JOIN LATERAL (SELECT e.id, e.state, e.updated_at FROM persistence_requests e WHERE e.worktree_id = r.worktree_id
+ AND (e.state IN ('queued','running','recovering') OR e.recovery IS NOT NULL) ORDER BY e.sequence LIMIT 1) h ON r.worktree_id IS NOT NULL
+ WHERE r.id = $1::uuid`, [requestId]);
+ return row ? { requestId, row } : null;
+ };
+ const describe = async (requestId: string, row: NonNullable<Awaited<ReturnType<typeof read>>>['row']): Promise<Omit<DrainStall, 'stalled_seconds'>> => {
+ const { localHostId } = await import('./identity.ts');
+ const { hasClaimableWrite } = await import('./journal.ts');
+ const host = localHostId();
+ return { request_id: requestId, state: row.state, blocked_reason: row.blocked_reason, head_request_id: row.head_id, head_state: row.head_state,
+ claimable_here: await hasClaimableWrite(engine, host).catch(() => false), owner_is_this_host: row.owner_host_id === null ? null : row.owner_host_id === host };
+ };
+ return {
+ async blockedHead(result) {
+ const found = await read(result);
+ if (!found) return null;
+ const reason = found.row.recovering ? 'recovery_required' : found.row.blocked_reason;
+ if (!reason || !BLOCKED_HEAD_REASONS.has(reason)) return null;
+ return { reason: reason as DrainStopReason, stall: { ...await describe(found.requestId, found.row), stalled_seconds: 0 } };
+ },
+ async fingerprint(result) {
+ const found = await read(result);
+ if (!found) return null;
+ const { row } = found;
+ return { key: [row.state, row.updated_at, row.claim_expires_at, row.blocked_reason, row.head_id, row.head_state, row.head_updated_at].join('|'),
+ stall: await describe(found.requestId, row) };
+ },
+ };
+}
+
+/** 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');
+ const drainStartedAt = opts.drainStartedAt ?? Date.now();
+ return runDrain({ signal: opts.signal, onProgress: opts.onProgress, probe: engineStallProbe(engine), announce,
+ pass: (signal, onProgress) => performManagedSync(engine, { ...opts, signal, onProgress, drainStartedAt }) });
+}
+
+export interface DrainNext {
+ command: string;
+ safe_to_loop: boolean;
+ retry_after_ms: number;
+ eta_seconds: number | null;
+ rate_pages_per_min: number | null;
+ why: string;
+ docs?: string;
+}
+
+const STOP_DOCS: Record<DrainStopReason, CatalogueName> = {
+ deadline: 'sync_drain_deadline', drain_stalled: 'sync_drain_stalled', database_contention: 'sync_drain_database_contention',
+ recovery_required: 'sync_drain_writer_blocked', owner_unavailable: 'sync_drain_writer_blocked', unexpected_file_bytes: 'sync_drain_writer_blocked',
+ unexpected_staging_bytes: 'sync_drain_writer_blocked', blocked_by_failures: 'sync_drain_blocked_by_failures',
+};
+
+/** What the agent runs next, or null when the sync is done (DX-A2). */
+export function drainNext(result: SyncResult, resumeCommand: string, sourceId: string): DrainNext | null {
+ const outcome = syncOutcome(result);
+ if (outcome === 'synced') return null;
+ const d = result.drain;
+ const estimate = { eta_seconds: d?.eta_seconds ?? null, rate_pages_per_min: d?.rate_pages_per_min ?? null };
+ const docs = d?.stop_reason ? ERROR_CATALOGUE[STOP_DOCS[d.stop_reason]].docs : undefined;
+ if (outcome === 'resumable') {
+ return { command: resumeCommand, safe_to_loop: true, retry_after_ms: d?.retry_after_ms ?? 0, ...estimate,
+ why: 'The sync stopped at its deadline with its cursor and accepted writes intact; the same command resumes where it stopped.', ...(docs ? { docs } : {}) };
+ }
++ if (d?.stop_reason === 'database_contention') {
++ const wait = result.writeWait?.status === 'read_failed' ? result.writeWait : null;
++ return { command: resumeCommand, safe_to_loop: false, retry_after_ms: 0, ...estimate,
++ why: `The drain could not read its write's state from the database${wait ? ` (${wait.reason}: ${wait.remediation})` : ''}. The accepted write keeps its request ID. Fix database access, then rerun.`,
++ ...(docs ? { docs } : {}) };
++ }
+ const writerBlocked = d?.stop_reason && d.stop_reason !== 'blocked_by_failures' && d.stop_reason !== 'deadline';
+ if (writerBlocked) {
+ return { command: `gbrain sources writer status ${sourceId}`, safe_to_loop: false, retry_after_ms: 0, ...estimate,
+ why: d!.stop_reason === 'drain_stalled'
+ ? `No write for this source made progress for ${d!.stall?.stalled_seconds ?? 30}s and nothing here can claim it. Inspect the writer, fix what it names, then rerun: ${resumeCommand}`
+ : `The source's writer needs intervention (${d!.stop_reason}) before more pages can publish. Inspect it, fix what it names, then rerun: ${resumeCommand}`,
+ ...(docs ? { docs } : {}) };
+ }
+ const retry = resumeCommand.includes(' --retry-failed') ? resumeCommand : `${resumeCommand} --retry-failed`;
+ return { command: retry, safe_to_loop: false, retry_after_ms: 0, ...estimate,
+ why: 'A page failed to publish. Fix the cause named in managed_write / failures first; rerunning without a fix returns the same failure. Ask the user before skipping content.',
+ ...(docs ? { docs } : {}) };
+}
+
+/** `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 {};
+ const next = drainNext(result, resumeCommand, sourceId);
+ return { outcome: syncOutcome(result), ...(result.drain ? { drain: result.drain } : {}), ...(next ? { next } : {}) };
+}
+
+/** Human lines for the end of a managed sync. */
+export function formatDrainSummary(result: SyncResult, resumeCommand: string, sourceId: string): string[] {
+ const d = result.drain;
+ if (!d) return [];
+ const lines = [`Managed sync ${d.outcome}: ${d.processed} entries this run (${d.written} written, ${d.waived} waived)`
+ + (d.remaining ? `, ${d.remaining} remaining` : '') + (d.rate_pages_per_min !== null ? `, ${d.rate_pages_per_min} pages/min` : '')
+ + (d.remaining && d.eta_seconds !== null ? `, indexing ETA ${formatDuration(d.eta_seconds)}` : '') + '.'];
+ if (d.stall) lines.push(` Oldest unfinished request ${d.stall.head_request_id ?? d.stall.request_id} (${d.stall.head_state ?? d.stall.state})`
+ + `${d.stall.blocked_reason ? `, blocked_reason=${d.stall.blocked_reason}` : ''}; claimable here: ${d.stall.claimable_here ? 'yes' : 'no'}.`);
+ const next = drainNext(result, resumeCommand, sourceId);
+ if (next) lines.push(` Next: ${next.command}${next.safe_to_loop ? ' (safe to rerun in a loop)' : ''}`, ` Why: ${next.why}`);
+ return lines;
+}
+
+export interface ManagedSyncBacklog {
+ source_id: string;
+ index: number;
+ total: number;
+ remaining: number;
+ rate_pages_per_min: number | null;
+ eta_seconds: number | null;
+ last_progress_at: string | null;
+ resume_command: string;
+}
+
+/**
+ * Unfinished managed cursors with their remaining entries and the rate of
+ * their latest drain window (CEO-A18), readable from any process.
+ */
+export async function readManagedSyncBacklog(engine: BrainEngine, sourceIds?: string[]): Promise<ManagedSyncBacklog[]> {
+ const rows = await engine.executeRaw<{ header: { sourceId: string; index: number; total: number; done?: boolean; progress?: { startedAt: number; startIndex: number; lastAt: number; lastIndex: number };
+ processingOptions?: { noEmbed?: boolean; noExtract?: boolean; noSchemaPack?: boolean } } }>(
+ `SELECT completed_keys->0 AS header FROM op_checkpoints WHERE op='managed-sync' AND COALESCE(completed_keys->0->>'done','false')<>'true'`);
+ const flags = { noEmbed: '--no-embed', noExtract: '--no-extract', noSchemaPack: '--no-schema-pack' } as const;
+ return rows.map(({ header }) => header).filter(h => h?.sourceId && (!sourceIds || sourceIds.includes(h.sourceId))).map(h => {
+ const remaining = Math.max(0, Number(h.total) - Number(h.index));
+ const p = h.progress;
+ const estimate = p ? drainEstimate(remaining, p.lastIndex - p.startIndex, p.lastAt - p.startedAt) : { rate_pages_per_min: null, eta_seconds: null };
+ return { source_id: h.sourceId, index: Number(h.index), total: Number(h.total), remaining, ...estimate,
+ last_progress_at: p ? new Date(p.lastAt).toISOString() : null,
+ resume_command: `gbrain sync --source ${h.sourceId} --no-pull${(Object.keys(flags) as (keyof typeof flags)[]).filter(k => h.processingOptions?.[k]).map(k => ` ${flags[k]}`).join('')}` };
+ });
+}
+
+export function formatManagedSyncBacklog(b: ManagedSyncBacklog): string {
+ return `${b.source_id}: managed sync cursor at ${b.index}/${b.total} (${b.remaining} remaining`
+ + (b.rate_pages_per_min !== null ? `, last drain ${b.rate_pages_per_min} pages/min, indexing ETA ${b.eta_seconds === null ? 'unknown' : formatDuration(b.eta_seconds)}` : ', rate unknown')
+ + `). Resume: ${b.resume_command}`;
+}
diff --cc src/core/persistence/sync-run.ts
index 1a10a86424,bd01bfb039..cb11ede517
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@@ -48,16 -48,9 +48,18 @@@ interface Cursor extends SyncDiscovery
processingOptions?: SyncProcessingOptions; syncOptions?: SyncCursorOptions; overtaken?: true;
counts: { added: number; modified: number; deleted: number; chunks: number; renamed?: number;
/** #5751: unchanged working-tree files skipped only because a no-op publication could never resolve their admit reason. */
- skippedContextualMode?: number; skippedCanonicalBytes?: number };
+ skippedContextualMode?: number; skippedCanonicalBytes?: number;
+ /** DX-A7: entries advanced without an admission because their publication would change nothing. */
- waived?: { imports: number; deletes: number } }; }
++ waived?: { imports: number; deletes: number } };
+ /** #5984: the active drain window (reset when a new drain starts), so a backlog ETA never counts downtime. */
+ progress?: CursorProgress; }
+export interface CursorProgress { startedAt: number; startIndex: number; lastAt: number; lastIndex: number }
+/** #5984: the cursor's progress after advancing to `index`, in the drain window that started at `drainStartedAt`. */
+function stampProgress(prior: CursorProgress | undefined, fromIndex: number, index: number, drainStartedAt: number): CursorProgress {
+ const now = Date.now();
+ return prior && prior.startedAt === drainStartedAt ? { ...prior, lastAt: now, lastIndex: index }
+ : { startedAt: drainStartedAt, startIndex: fromIndex, lastAt: now, lastIndex: index };
+}
const OP = 'managed-sync';
type CursorHeader = Omit<Cursor, 'entries' | 'companyPlan'> & { total: number };
const header = ({ entries, companyPlan: _plan, ...value }: Cursor): CursorHeader => ({ ...value, total: entries.length });
@@@ -129,9 -152,8 +161,10 @@@ function result(cursor: Cursor | Cursor
deleted: cursor.counts.deleted, renamed: cursor.counts.renamed ?? 0, chunksCreated: cursor.counts.chunks, embedded: 0, pagesAffected: [],
...(cursor.slugCollisions?.length ? { slugCollisions: cursor.slugCollisions } : {}),
...(cursor.fileRefusals?.length ? { fileRefusals: cursor.fileRefusals } : {}),
+ waived: { imports: cursor.counts.waived?.imports ?? 0, deletes: cursor.counts.waived?.deletes ?? 0 },
- filesImported: cursor.index, bankedFiles: cursor.index, ...(cursor.uncommitted ? { uncommitted: cursor.uncommitted } : {}), ...(reason ? { reason } : {}),
+ filesImported: cursor.index, bankedFiles: cursor.index,
+ managedCursor: { index: cursor.index, total: 'total' in cursor ? cursor.total : cursor.entries.length, ...(cursor.progress ? { progress: cursor.progress } : {}) },
+ ...(cursor.uncommitted ? { uncommitted: cursor.uncommitted } : {}), ...(reason ? { reason } : {}),
...(cursor.counts.skippedContextualMode || cursor.counts.skippedCanonicalBytes ? { legacySkips: {
contextualMode: cursor.counts.skippedContextualMode ?? 0, canonicalBytes: cursor.counts.skippedCanonicalBytes ?? 0 } } : {}) };
}
@@@ -440,14 -461,13 +473,13 @@@ export async function performManagedSyn
phase = 'admission';
const prior = await getWriteRequest(engine, cursor.authority.writer.principal, pending.requestId);
assertActive();
- // #5470: a frozen import whose publication would change nothing advances the cursor without an admission.
- const waived = prior ? null : await unchangedSyncImport(engine, cursor, pending, config);
+ // #5470/#5984: a frozen entry whose publication would change nothing advances the cursor without an admission.
+ const screened: Cursor = cursor;
+ const waived: Cursor | null = prior ? null : await waiveNoopEntry(engine, screened, pending, config, key,
- (tx, noop) => writeCursor(tx, key, screened, waivedCursor(screened, noop)), tx => currentCursor(tx, key, screened));
++ (tx, noop) => writeCursor(tx, key, screened, { ...waivedCursor(screened, noop), progress: stampProgress(screened.progress, screened.index, screened.index + 1, drainStartedAt) }), tx => currentCursor(tx, key, screened));
if (waived) {
- const skipped: Cursor = { ...cursor, index: cursor.index + 1, counts: { ...cursor.counts }, progress: stampProgress(cursor.progress, cursor.index, cursor.index + 1, drainStartedAt) }; delete skipped.pending;
- if (waived.includes('contextual_mode')) skipped.counts.skippedContextualMode = (skipped.counts.skippedContextualMode ?? 0) + 1;
- if (waived.includes('canonical_file_differs')) skipped.counts.skippedCanonicalBytes = (skipped.counts.skippedCanonicalBytes ?? 0) + 1;
- cursor = await saveCursor(engine, key, cursor, skipped);
+ cursor = waived;
- opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index });
+ opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index, total: cursor.entries.length, waived: true });
assertActive();
// A skipped entry still counts toward the caller's slice, so a sliced run yields at the same positions.
if (slice && (cursor.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(cursor, 'partial', 'writer_yield');
diff --cc test/sync-drain.test.ts
index fe0f76d619,0000000000..ec635bbdb7
mode 100644,000000..100644
--- a/test/sync-drain.test.ts
+++ b/test/sync-drain.test.ts
@@@ -1,180 -1,0 +1,194 @@@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { lastForwardProgressAt, registerRunDeadline } from '../src/core/forward-progress.ts';
+import { drainEstimate, drainJsonFields, drainNext, formatDuration, runDrain, syncOutcome, type StallProbe } from '../src/core/persistence/sync-drain.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 },
+ managedWrite: { source_id: 's', slug: 'p', path: 'p.md', write_error: 'write_pending', reason: 'write_pending', message: 'm', suggestion: 's',
+ write_request: { request_id: '00000000-0000-0000-0000-000000000001', state: 'queued', retry_after_ms: 0 } as never } });
+const yielded = (index: number, total = 10): SyncResult => ({ ...base, status: 'partial', reason: 'writer_yield', managedCursor: { index, total } });
+const done = (total = 10): SyncResult => ({ ...base, managedCursor: { index: total, total } });
+const RESUME = 'gbrain sync --source s --no-pull';
+
+function scripted(results: Array<SyncResult | Error>) {
+ let i = 0;
+ return { calls: () => i, pass: async () => { const next = results[Math.min(i++, results.length - 1)]; if (next instanceof Error) throw next; return next; } };
+}
+
+afterEach(() => registerRunDeadline(null));
+
+describe('runDrain', () => {
+ test('re-enters writer_pending and writer_yield passes until the cursor is done', async () => {
+ const s = scripted([pending(1), yielded(3), pending(4), done()]);
+ const result = await runDrain({ pass: s.pass, pauseMs: 1 });
+ expect(s.calls()).toBe(4);
+ expect(result.drain).toMatchObject({ outcome: 'synced', passes: 4, remaining: 0 });
+ expect(syncOutcome(result)).toBe('synced');
+ });
+
+ test('a stopped signal ends the drain as resumable with the cursor intact', async () => {
+ const stop = new AbortController();
+ const s = scripted([pending(2)]);
+ const result = await runDrain({ pass: async () => { stop.abort(); return s.pass(); }, signal: stop.signal, pauseMs: 1 });
+ expect(result.drain).toMatchObject({ outcome: 'resumable', stop_reason: 'deadline', passes: 1, remaining: 8 });
+ expect(result.reason).toBe('timeout');
+ expect(drainNext(result, RESUME, 's')).toMatchObject({ command: RESUME, safe_to_loop: true });
+ });
+
+ test('a strict registered run deadline stops the drain before the watchdog', async () => {
+ registerRunDeadline({ atMs: Date.now() + 60, strict: true });
+ const started = Date.now();
+ const result = await runDrain({ pass: async () => pending(1), pauseMs: 5 });
+ expect(result.drain?.outcome).toBe('resumable');
+ expect(Date.now() - started).toBeLessThan(2000);
+ });
+
+ test('a progress-aware run deadline does not stop a progressing drain', async () => {
+ registerRunDeadline({ atMs: Date.now() - 1, strict: false });
+ const s = scripted([pending(1), done()]);
+ expect((await runDrain({ pass: s.pass, pauseMs: 1 })).drain?.outcome).toBe('synced');
+ });
+
+ test('blocked results end the drain as blocked with a retry command', async () => {
+ const failed = await runDrain({ pass: async () => ({ ...base, status: 'blocked_by_failures', failedFiles: 1 }) });
+ expect(failed.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'blocked_by_failures' });
+ expect(drainNext(failed, RESUME, 's')).toMatchObject({ command: `${RESUME} --retry-failed`, safe_to_loop: false });
+ const terminal = pending(3);
+ terminal.managedWrite!.write_error = 'revision_conflict';
+ terminal.status = 'blocked_by_failures';
+ expect((await runDrain({ pass: async () => terminal })).drain?.outcome).toBe('blocked');
+ });
+
+ test('named transient failures retry with bounded attempts; others stop at once', async () => {
+ const contention = () => new OperationError('database_contention', 'busy');
+ const s = scripted([contention(), contention(), done()]);
+ expect((await runDrain({ pass: s.pass, backoffMs: 1 })).drain?.outcome).toBe('synced');
+ expect(s.calls()).toBe(3);
+ const exhausted = scripted([contention(), contention(), contention(), contention(), done()]);
+ await expect(runDrain({ pass: exhausted.pass, backoffMs: 1 })).rejects.toThrow('busy');
+ const fatal = scripted([new OperationError('permission_denied', 'no'), done()]);
+ await expect(runDrain({ pass: fatal.pass })).rejects.toThrow('no');
+ expect(fatal.calls()).toBe(1);
+ });
+
+ test('worktree_refreshing waits its retry_after_ms hint', async () => {
+ const refreshing = new OperationError('worktree_refreshing', 'refreshing');
+ refreshing.detail = 'retry_after_ms=5';
+ const s = scripted([refreshing, refreshing, refreshing, refreshing, done()]);
+ expect((await runDrain({ pass: s.pass })).drain?.outcome).toBe('synced');
+ expect(s.calls()).toBe(5);
+ });
+
+ test('a recovery-blocked head stops the drain as blocked with the writer command', async () => {
+ const stall = { request_id: 'r', state: 'queued', blocked_reason: 'recovery_required', head_request_id: 'h', head_state: 'recovering',
+ claimable_here: false, owner_is_this_host: true, stalled_seconds: 0 };
+ const probe: StallProbe = { blockedHead: async () => ({ reason: 'recovery_required', stall }), fingerprint: async () => null };
+ const result = await runDrain({ pass: async () => pending(2), probe, pauseMs: 1 });
+ expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'recovery_required', stall: { head_request_id: 'h' } });
+ expect(drainNext(result, RESUME, 's')).toMatchObject({ command: 'gbrain sources writer status s', safe_to_loop: false });
+ });
+
+ test('no change in the awaited request across the stall window stops the drain as drain_stalled', async () => {
+ const stall = { request_id: 'r', state: 'queued', blocked_reason: null, head_request_id: 'r', head_state: 'queued', claimable_here: false, owner_is_this_host: false };
+ const probe: StallProbe = { blockedHead: async () => null, fingerprint: async () => ({ key: 'same', stall }) };
+ const result = await runDrain({ pass: async () => pending(2), probe, pauseMs: 1, stallMs: 20 });
+ expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled', stall: { request_id: 'r', claimable_here: false } });
+ expect(result.drain!.passes).toBeGreaterThanOrEqual(4);
+ });
+
+ test('a changing fingerprint never counts as a stall', async () => {
+ let n = 0;
+ const stall = { request_id: 'r', state: 'running', blocked_reason: null, head_request_id: 'r', head_state: 'running', claimable_here: false, owner_is_this_host: true };
+ const probe: StallProbe = { blockedHead: async () => null, fingerprint: async () => ({ key: String(n), stall }) };
+ const result = await runDrain({ pass: async () => (++n < 8 ? pending(2) : done()), probe, pauseMs: 1, stallMs: 1 });
+ expect(result.drain?.outcome).toBe('synced');
+ });
+
+ test('progress events count written and waived pages and note forward progress', async () => {
+ const before = lastForwardProgressAt();
+ const seen: string[] = [];
+ const result = await runDrain({ onProgress: e => seen.push(e.phase), pass: async (_signal, onProgress) => {
+ onProgress({ phase: 'managed_sync.start', bankedFiles: 0, total: 4 });
+ onProgress({ phase: 'managed_sync.page_committed', bankedFiles: 1, total: 4 });
+ onProgress({ phase: 'managed_sync.page_committed', bankedFiles: 2, total: 4, waived: true });
+ onProgress({ phase: 'managed_sync.page_committed', bankedFiles: 3, total: 4, waived: true });
+ return done(4);
+ } });
+ expect(result.drain).toMatchObject({ processed: 3, written: 1, waived: 2, remaining: 0 });
+ expect(seen).toContain('managed_sync.start');
+ expect(lastForwardProgressAt()).toBeGreaterThanOrEqual(before);
+ });
+});
+
+describe('estimates and outcomes', () => {
+ test('zero progress reports an unknown rate, never a zero or infinite ETA', () => {
+ expect(drainEstimate(100, 0, 60_000)).toEqual({ rate_pages_per_min: null, eta_seconds: null });
+ expect(drainEstimate(100, 10, 60_000)).toEqual({ rate_pages_per_min: 10, eta_seconds: 600 });
+ expect(drainEstimate(null, 10, 60_000)).toEqual({ rate_pages_per_min: 10, eta_seconds: null });
+ });
+
+ test('formatDuration', () => {
+ expect(formatDuration(42)).toBe('42s');
+ expect(formatDuration(125)).toBe('2m05s');
+ expect(formatDuration(3 * 3600 + 12 * 60)).toBe('3h12m');
+ });
+
+ test('a single-pass pending write keeps the historical blocked verdict; failed pulls stay blocked', () => {
+ expect(syncOutcome(pending(1))).toBe('blocked');
+ expect(syncOutcome({ ...base, status: 'partial', reason: 'pull_failed' })).toBe('blocked');
+ expect(syncOutcome({ ...base, status: 'partial', reason: 'timeout' })).toBe('resumable');
+ expect(syncOutcome({ ...base, status: 'up_to_date' })).toBe('synced');
+ });
+
+ test('JSON fields appear only for managed results', () => {
+ expect(drainJsonFields(base, RESUME, 's')).toEqual({});
+ expect(drainJsonFields(done(), RESUME, 's')).toEqual({ outcome: 'synced' });
+ });
+});
+
+describe('managed sync backlog', () => {
+ const engineWith = (headers: unknown[]) => ({ executeRaw: async () => headers.map(header => ({ header })) }) as never;
+
+ test('estimates from the latest drain window and builds the resume command from stored options', async () => {
+ const { readManagedSyncBacklog, formatManagedSyncBacklog } = await import('../src/core/persistence/sync-drain.ts');
+ const now = Date.now();
+ const [b] = await readManagedSyncBacklog(engineWith([{ sourceId: 'notes', index: 300, total: 1300,
+ progress: { startedAt: now - 120_000, startIndex: 100, lastAt: now, lastIndex: 300 }, processingOptions: { noEmbed: true } }]));
+ expect(b).toMatchObject({ source_id: 'notes', remaining: 1000, rate_pages_per_min: 100, eta_seconds: 600,
+ resume_command: 'gbrain sync --source notes --no-pull --no-embed' });
+ expect(formatManagedSyncBacklog(b!)).toContain('indexing ETA 10m00s');
+ });
+
+ test('a cursor with no drain window reports rate unknown, never an infinite ETA', async () => {
+ const { readManagedSyncBacklog, formatManagedSyncBacklog } = await import('../src/core/persistence/sync-drain.ts');
+ const [b] = await readManagedSyncBacklog(engineWith([{ sourceId: 'notes', index: 0, total: 50 }]));
+ expect(b).toMatchObject({ remaining: 50, rate_pages_per_min: null, eta_seconds: null });
+ expect(formatManagedSyncBacklog(b!)).toContain('rate unknown');
+ expect(await readManagedSyncBacklog(engineWith([{ sourceId: 'other', index: 0, total: 5 }]), ['notes'])).toEqual([]);
+ });
+
+ test('a resumed drain window resets, so downtime never depresses the rate', async () => {
+ const { readManagedSyncBacklog } = await import('../src/core/persistence/sync-drain.ts');
+ const now = Date.now();
+ const [b] = await readManagedSyncBacklog(engineWith([{ sourceId: 's', index: 500, total: 600,
+ progress: { startedAt: now - 60_000, startIndex: 440, lastAt: now, lastIndex: 500 } }]));
+ expect(b!.rate_pages_per_min).toBe(60);
+ });
+});
++
++describe('classified write waits', () => {
++ test('a blocked wait stops the drain with its cause; a repeated read failure stops it as database_contention', async () => {
++ const blocked = { ...pending(2), writeWait: { status: 'blocked' as const, request_id: 'r', cause: 'owner_unavailable', command: 'gbrain sources writer status s --json' } };
++ expect((await runDrain({ pass: async () => blocked, pauseMs: 1 })).drain).toMatchObject({ outcome: 'blocked', stop_reason: 'owner_unavailable' });
++ const failing = { ...pending(2), writeWait: { status: 'read_failed' as const, request_id: 'r', reason: 'conn_dropped', transient: true, attempts: 1, message: 'm', remediation: 'retry' } };
++ const s = scripted([failing, failing, failing, done()]);
++ const result = await runDrain({ pass: s.pass, pauseMs: 1 });
++ expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'database_contention' });
++ expect(drainNext(result, RESUME, 's')).toMatchObject({ command: RESUME, safe_to_loop: false });
++ const auth = { ...failing, writeWait: { ...failing.writeWait, reason: 'auth_failed', transient: false } };
++ expect((await runDrain({ pass: async () => auth, pauseMs: 1 })).drain?.passes).toBe(1);
++ });
++});