Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): #6278 B6 the stall progress line prints during a live stall inside a pass

garrytanc238bedb5bab
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index 5d456e96dc..5542337186 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -15,7 +15,7 @@
- **`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. Active Git holds of the source are re-screened when their blob or working bytes changed, the file left, a `sources retry-held` request names them, the hold predates the current `RECOVERY_VERSION`, or the code is `frontmatter_slug_conflict`, `file_too_large`, `rename_held` or `parser_regression`; holds of now-excluded paths are released at the checkpoint. A held rename destination (or a held path renamed again) carries the hold's `renameFrom` when the old page is unchanged, else `renameHeld` (held as `rename_held` / `rename_source_changed`), and a full walk never deletes an origin a hold's `rename_from` names. 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`, 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. Tests: `test/sync-drain.test.ts`, `test/sync-drain-claims.test.ts`, `test/managed-sync-drain.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`) 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). Tests: `test/sync-drain.test.ts`, `test/sync-drain-claims.test.ts`, `test/managed-sync-drain.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`.
- **`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.
diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.md
index ba8e64f757..09512b51e0 100644
--- a/docs/guides/live-sync.md
+++ b/docs/guides/live-sync.md
@@ -35,6 +35,15 @@ every 10 seconds on stderr:
[sync] 1240/9382 processed (1200 written, 40 waived this run) · 42.1 pages/min · indexing ETA 3h13m
```
+When nothing commits for 10 seconds while a write is unfinished, the line names
+the stall instead of an ETA: the head write's step, what it waits on, and how
+long a preparation is allowed. It reads the head's claim while the pass runs, so
+it prints during a stall inside a bulk group too:
+
+```
+[sync] 1240/9382 processed · stalled 95s on origin_check (waiting on db) · allowed 2m30s
+```
+
On Postgres the drain publishes in **bulk groups** of up to 16 page imports and
deletes, each admitted with the cursor step that records it and published in one
transaction. Every page still gets its own write request, receipt, attribution
diff --git a/llms-full.txt b/llms-full.txt
index 37a0272117..003d1eb366 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -6307,6 +6307,15 @@ every 10 seconds on stderr:
[sync] 1240/9382 processed (1200 written, 40 waived this run) · 42.1 pages/min · indexing ETA 3h13m
```
+When nothing commits for 10 seconds while a write is unfinished, the line names
+the stall instead of an ETA: the head write's step, what it waits on, and how
+long a preparation is allowed. It reads the head's claim while the pass runs, so
+it prints during a stall inside a bulk group too:
+
+```
+[sync] 1240/9382 processed · stalled 95s on origin_check (waiting on db) · allowed 2m30s
+```
+
On Postgres the drain publishes in **bulk groups** of up to 16 page imports and
deletes, each admitted with the cursor step that records it and published in one
transaction. Every page still gets its own write request, receipt, attribution
diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.ts
index 39e86912ce..22479c45d8 100644
--- a/src/core/persistence/sync-drain.ts
+++ b/src/core/persistence/sync-drain.ts
@@ -182,6 +182,8 @@ export interface StallProbe {
* columns a renewal bumps, so a renewed-forever claim still reads as no progress. `claim` describes the head's claim.
*/
fingerprint(result: SyncResult): Promise<{ key: string; stall: Omit<DrainStall, 'stalled_seconds'>; claim?: DrainClaim | null } | null>;
+ /** #6278: the source's head while a pass runs (its oldest running request, else its oldest queued one); null when nothing is unfinished. Bounded; may reject. */
+ head?(): Promise<{ head_state: string; claim: DrainClaim | null } | null>;
}
export interface DrainInput {
@@ -193,10 +195,18 @@ export interface DrainInput {
announce?: boolean;
/** Publication mode for the report and the start line. */
bulk?: { enabled: boolean; reason: string | null; lanes?: number; lanesMax?: number; lanesReason?: string | null; lanesCap?: LanesCap };
- /** Test seams: the no-progress window, the pause after a pending write and the transient backoff base. */
+ /** Test seams: the no-progress window, the pause after a pending write, the transient backoff base and the progress-line interval. */
stallMs?: number;
pauseMs?: number;
backoffMs?: number;
+ progressMs?: number;
+}
+
+/** #6278: the line the drain prints while nothing commits, naming the head's step, wait cause and allowance. */
+function stallText(index: number, total: number | null, stalledMs: number, claim: DrainClaim | null, headState: string | null): string {
+ return `[sync] ${index}/${total ?? '?'} processed · stalled ${Math.round(stalledMs / 1000)}s on ${claim?.step ?? claim?.phase ?? headState ?? 'the writer head'}`
+ + `${claim?.waiting_on && claim.waiting_on !== 'unknown' ? ` (waiting on ${claim.waiting_on})` : ''}${claim?.lapsed ? ' (claim lapsed: owner missing)' : ''}`
+ + `${claim && !claim.lapsed && claim.phase === 'preparing' ? ` · allowed ${formatDuration(Math.round(claim.allowance_ms / 1000))}` : ''}`;
}
/** Re-enter `pass` until the managed cursor is done, the caller stops it, or it is blocked. */
@@ -208,18 +218,29 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
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;
let stall: { key: string; since: number; passes: number; claim: DrainClaim | null; stallInfo: Omit<DrainStall, 'stalled_seconds'> } | null = null;
- let lastCommitAt = startedAt;
+ let lastCommitAt = startedAt, inPass = false, readingHead = false;
const remaining = () => total === null ? null : Math.max(0, total - index);
+ const every = input.progressMs ?? PROGRESS_EVERY_MS;
// #6278: the progress line prints on commits; while nothing commits, a timer names the stall instead of an ETA that assumes none.
+ // Between passes the stall comes from the probe's fingerprint; inside a pass (a grouped publish parked in preparation never
+ // returns to this loop) the timer reads the source's head claim itself, bounded, and prints nothing when nothing is unfinished.
const stallLine = input.announce ? setInterval(() => {
- if (!stall || Date.now() - lastCommitAt < PROGRESS_EVERY_MS || Date.now() - lastLine < PROGRESS_EVERY_MS) return;
- lastLine = Date.now();
- const claim = stall.claim;
- const seconds = Math.round(Math.max(Date.now() - stall.since, claim?.step_age_ms ?? 0) / 1000);
- serr(`[sync] ${index}/${total ?? '?'} processed · stalled ${seconds}s on ${claim?.step ?? claim?.phase ?? stall.stallInfo.head_state ?? 'the writer head'}`
- + `${claim?.waiting_on && claim.waiting_on !== 'unknown' ? ` (waiting on ${claim.waiting_on})` : ''}${claim?.lapsed ? ' (claim lapsed: owner missing)' : ''}`
- + `${claim && !claim.lapsed && claim.phase === 'preparing' ? ` · allowed ${formatDuration(Math.round(claim.allowance_ms / 1000))}` : ''}`);
- }, PROGRESS_EVERY_MS) : null;
+ const tickAt = Date.now();
+ if (tickAt - lastCommitAt < every || tickAt - lastLine < every) return;
+ if (stall) {
+ lastLine = tickAt;
+ serr(stallText(index, total, Math.max(tickAt - stall.since, stall.claim?.step_age_ms ?? 0), stall.claim, stall.stallInfo.head_state));
+ return;
+ }
+ if (!inPass || !input.probe?.head || readingHead) return;
+ readingHead = true;
+ const probe = input.probe;
+ Promise.resolve().then(() => probe.head!()).then(head => {
+ if (!head || !inPass || stall || Date.now() - lastCommitAt < every || tickAt - lastLine < every) return;
+ lastLine = tickAt;
+ serr(stallText(index, total, head.claim?.step_age_ms ?? Date.now() - lastCommitAt, head.claim, head.head_state));
+ }).catch(() => undefined).finally(() => { readingHead = false; });
+ }, every) : null;
stallLine?.unref?.();
const onProgress: NonNullable<SyncOpts['onProgress']> = event => {
input.onProgress?.(event);
@@ -259,7 +280,8 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
passes++;
let result: SyncResult;
try {
- result = await input.pass(signal, onProgress);
+ inPass = true;
+ try { result = await input.pass(signal, onProgress); } finally { inPass = false; }
attempt = 0;
} catch (error) {
const delay = transientDelay(error, ++attempt, refreshWaitedMs, input.backoffMs ?? 250);
@@ -343,8 +365,11 @@ async function readPreparationBudgets(engine: Pick<BrainEngine, 'getConfig'>): P
ceilingMs: await read('persistence.preparation_ceiling_ms', PREPARATION_CEILING_DEFAULT_MS) };
}
-/** Engine-backed stall checks: the awaited request, the oldest unfinished request on its worktree, and claimability here. */
-export function engineStallProbe(engine: BrainEngine): StallProbe {
+/** The live head read's bound: the ticker must not hang on the lock that stalls the pass it reports on. */
+const HEAD_READ_TIMEOUT_MS = 2_000;
+
+/** Engine-backed stall checks: the awaited request, the oldest unfinished request on its worktree, and claimability here; with `sourceId`, the live head read. */
+export function engineStallProbe(engine: BrainEngine, sourceId?: string): StallProbe {
const read = async (result: SyncResult) => {
const requestId = result.managedWrite?.write_request.request_id;
if (!requestId) return null;
@@ -387,6 +412,17 @@ export function engineStallProbe(engine: BrainEngine): StallProbe {
return { key: [row.state, row.blocked_reason, row.head_id, row.head_state, claim?.phase ?? '', claim?.step ?? '', stamp?.since ?? '', row.head_lapsed ? 'lapsed' : ''].join('|'),
stall: await describe(found.requestId, row), claim };
},
+ ...(sourceId ? { async head() {
+ const [row] = await engine.executeRaw<{ head_state: string; head_claim_phase: unknown; head_token: string | null; head_lapsed: boolean | null; head_kind: string | null }>(
+ `SELECT h.state AS head_state, h.claim_phase AS head_claim_phase, h.execution_token::text AS head_token,
+ (h.claim_expires_at IS NOT NULL AND h.claim_expires_at < now()) AS head_lapsed, h.intent->>'kind' AS head_kind
+ FROM persistence_source_bindings b
+ JOIN sources s ON s.id = b.source_id AND s.incarnation = b.source_incarnation
+ JOIN LATERAL (SELECT e.state, e.claim_phase, e.execution_token, e.claim_expires_at, e.intent FROM persistence_requests e
+ WHERE e.worktree_id = b.worktree_id AND e.state IN ('queued','running','recovering') ORDER BY (e.state <> 'running'), e.sequence LIMIT 1) h ON true
+ WHERE b.source_id = $1`, [sourceId], { timeoutMs: HEAD_READ_TIMEOUT_MS, signal: AbortSignal.timeout(HEAD_READ_TIMEOUT_MS + 500) });
+ return row ? { head_state: row.head_state, claim: drainClaimOf(row, await (budgets ??= readPreparationBudgets(engine))) } : null;
+ } } : {}),
};
}
@@ -405,7 +441,7 @@ export async function drainManagedSync(engine: BrainEngine, opts: SyncOpts, anno
const { closeLaneRun } = await import('./sync-lanes.ts');
let result: SyncResult | undefined;
try {
- result = await runDrain({ signal: opts.signal, onProgress: opts.onProgress, probe: engineStallProbe(engine), announce,
+ result = await runDrain({ signal: opts.signal, onProgress: opts.onProgress, probe: engineStallProbe(engine, opts.sourceId), announce,
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 {
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index db9257d22c..900f2e949c 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -102,6 +102,7 @@ test/shared-skills-source-opt-out.test.ts
test/shared-skills-writer-boundary.test.ts
test/source-retire-missing-checkout.test.ts
test/stats-health-source-scope.test.ts
+test/sync-drain-claims.test.ts
test/sync-frontmatter-recovery.test.ts
test/sync-frontmatter-slug-conflict.test.ts
test/sync-group-member-order.test.ts
diff --git a/test/sync-drain-claims.test.ts b/test/sync-drain-claims.test.ts
index a0f39b0974..15902fb46d 100644
--- a/test/sync-drain-claims.test.ts
+++ b/test/sync-drain-claims.test.ts
@@ -8,12 +8,27 @@
* window; a preparation this process's own consumer holds past its allowance
* ends the drain `resumable` / `preparation_abandoned`; a tripped breaker ends
* it `blocked` / `preparation_systemic`. The stall object and the timer line
- * name the step and wait cause.
+ * name the step and wait cause. B6: the timer line also prints during a pass
+ * (a grouped publish parked in preparation never returns to the drain loop),
+ * from a bounded read of the source's head claim, and never while commits flow.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { resolveBulkSettings } from '../src/core/persistence/sync-group.ts';
+import { preparationConfigView } from '../src/core/persistence/config-snapshot.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
import { drainClaimOf, drainJsonFields, drainNext, engineStallProbe, formatDrainSummary, runDrain, STALL_GRACE_MS, syncOutcome, type DrainClaim, type StallProbe } from '../src/core/persistence/sync-drain.ts';
import { ERROR_CATALOGUE } from '../src/core/error-catalogue.ts';
import type { SyncResult } from '../src/commands/sync.ts';
@@ -148,3 +163,125 @@ describe('engineStallProbe fingerprint', () => {
expect(lapsed.key).not.toBe(second.key);
});
});
+
+/** Captures the drain's stderr lines (`serr` writes through console.error without a source prefix). */
+function captureStderr(): { lines: string[]; stalled: () => string[]; restore(): void } {
+ const lines: string[] = [];
+ const spy = spyOn(console, 'error').mockImplementation((...args: unknown[]) => { lines.push(args.map(String).join(' ')); });
+ return { lines, stalled: () => lines.filter(line => line.includes('· stalled ')), restore: () => spy.mockRestore() };
+}
+const until = async (check: () => boolean, ms: number) => { const end = Date.now() + ms; while (!check() && Date.now() < end) await new Promise(r => setTimeout(r, 10)); return check(); };
+const committed = { phase: 'managed_sync.page_committed' } as Parameters<NonNullable<Parameters<typeof runDrain>[0]['onProgress']>>[0];
+
+describe('live stall line during a pass (B6)', () => {
+ const PROGRESS = 200;
+ const headProbe = (head: StallProbe['head']): StallProbe => ({ blockedHead: async () => null, fingerprint: async () => null, head });
+
+ test('while commits flow nothing prints; once they stop, the head claim is read and named; an empty head prints nothing', async () => {
+ const err = captureStderr();
+ try {
+ let reads = 0;
+ const head: StallProbe['head'] = async () => { reads++; return { head_state: 'running', claim: claim({ step_age_ms: 42_000 }) }; };
+ // A wider interval here, so a loaded runner's timer gap between 75 ms commits never reads as a stall.
+ const every = 500;
+ await runDrain({ announce: true, progressMs: every, probe: headProbe(head), pass: async (_signal, onProgress) => {
+ // Commits every 75 ms for three intervals: the ticker never reads the head and never prints a stall.
+ for (let i = 0; i < 20; i++) { onProgress({ ...committed, total: 30, bankedFiles: i + 1 }); await new Promise(r => setTimeout(r, 75)); }
+ expect(err.stalled()).toEqual([]);
+ expect(reads).toBe(0);
+ // Then nothing commits: within about two intervals the line names the head's step, wait cause, stall age and allowance.
+ expect(await until(() => err.stalled().length > 0, 4 * every)).toBe(true);
+ return done(30);
+ } });
+ expect(err.stalled()[0]).toBe('[sync] 20/30 processed · stalled 42s on origin_check (waiting on db) · allowed 2m30s');
+ // Rate-limited to one line per interval.
+ expect(err.stalled()).toHaveLength(1);
+ err.lines.length = 0;
+ await runDrain({ announce: true, progressMs: PROGRESS, probe: headProbe(async () => null), pass: async () => { await new Promise(r => setTimeout(r, 4 * PROGRESS)); return done(); } });
+ expect(err.stalled()).toEqual([]);
+ } finally { err.restore(); }
+ });
+
+ test('a head read that rejects or hangs never escapes the ticker or stacks; announce off never reads', async () => {
+ const err = captureStderr();
+ try {
+ let reads = 0;
+ const rejecting = await runDrain({ announce: true, progressMs: PROGRESS, probe: headProbe(async () => { reads++; throw new Error('lock timeout'); }),
+ pass: async () => { await new Promise(r => setTimeout(r, 4 * PROGRESS)); return done(); } });
+ expect(rejecting.drain?.outcome).toBe('synced');
+ expect(reads).toBeGreaterThanOrEqual(1);
+ reads = 0;
+ await runDrain({ announce: true, progressMs: PROGRESS, probe: headProbe(() => { reads++; return new Promise(() => {}); }),
+ pass: async () => { await new Promise(r => setTimeout(r, 5 * PROGRESS)); return done(); } });
+ expect(reads).toBe(1);
+ reads = 0;
+ await runDrain({ announce: false, progressMs: PROGRESS, probe: headProbe(async () => { reads++; return null; }),
+ pass: async () => { await new Promise(r => setTimeout(r, 3 * PROGRESS)); return done(); } });
+ expect(reads).toBe(0);
+ expect(err.stalled()).toEqual([]);
+ } finally { err.restore(); }
+ });
+
+ describe('forced probe: a real managed sync parked in preparation', () => {
+ // PGLite parks the single-write path; Postgres (DATABASE_URL set) parks a member of the grouped publish, the reporter's case.
+ const engines: BrainEngine[] = [];
+ let closePostgres: (() => Promise<void>) | undefined;
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-drain-live-'));
+ beforeAll(async () => {
+ if (testBackends().includes('pglite')) { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite); }
+ if (testBackends().includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }
+ }, 120_000);
+ afterAll(async () => {
+ installFaultHook(undefined);
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });
+ });
+
+ test('the line names the parked member\'s step within about two intervals, then the sync finishes once it is released', () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
+ for (const engine of engines) {
+ const id = `live-${randomUUID().replace(/-/g, '').slice(0, 20)}`, root = join(home, id);
+ const git = (...args: string[]) => execFileSync('git', ['-C', root, ...args], { stdio: ['ignore', 'pipe', 'pipe'] });
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ git('init', '-q');
+ for (const name of ['a', 'b', 'c']) writeFileSync(join(root, 'notes', `${name}.md`), `---\ntitle: ${name}\n---\nA synthetic observation about ${name}.\n`);
+ git('add', '-A'); git('-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'fixture');
+ 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');
+ let release!: () => void;
+ const released = new Promise<void>(resolve => { release = resolve; });
+ let parkedAt = 0, linesBeforePark = 0;
+ const err = captureStderr();
+ // Lines printed before the park (a request still queued at startup) are not the parked member's.
+ const parkedLines = () => err.stalled().slice(linesBeforePark);
+ // The first member parks in preparation, honouring its signal; the stamp gains the step a preparer would enter (the keys a renewal writes).
+ installFaultHook(async (at, detail) => {
+ if (at !== 'consumer:preparing' || detail.sourceId !== id || parkedAt) return;
+ await engine.executeRaw(`UPDATE persistence_requests SET claim_phase = claim_phase || '{"step":"origin_check","waiting_on":"db"}'::jsonb WHERE request_id=$1::uuid`, [detail.requestId]);
+ parkedAt = Date.now();
+ linesBeforePark = err.stalled().length;
+ await new Promise<void>(resolve => { void released.then(resolve); detail.signal?.addEventListener('abort', () => resolve(), { once: true }); });
+ });
+ try {
+ const bulk = await resolveBulkSettings(await preparationConfigView(engine), false);
+ expect(bulk.enabled).toBe(engine.kind === 'postgres');
+ const drain = runDrain({ announce: true, progressMs: PROGRESS, probe: engineStallProbe(engine, id), bulk: { enabled: bulk.enabled, reason: bulk.reason },
+ pass: (signal, onProgress) => performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true, signal, onProgress, ...(bulk.enabled ? { bulk } : {}) }) });
+ expect(await until(() => parkedAt > 0, 30_000)).toBe(true);
+ const seen = await until(() => parkedLines().length > 0, 10 * PROGRESS);
+ const seenAfterMs = Date.now() - parkedAt;
+ release();
+ const result = await drain;
+ expect(seen).toBe(true);
+ expect(seenAfterMs).toBeLessThanOrEqual(2 * PROGRESS + 400);
+ expect(parkedLines()[0]).toMatch(/^\[sync\] \d+\/3 processed · stalled \d+s on origin_check \(waiting on db\) · allowed \d/);
+ // One pass: the stall never returned to the drain loop, so only the live read could have named it.
+ expect(result.drain).toMatchObject({ outcome: 'synced', written: 3, passes: 1 });
+ if (bulk.enabled) expect(result.drain!.bulk!.grouped_pages).toBeGreaterThan(0);
+ expect(await engine.getPage('notes/a', { sourceId: id })).not.toBeNull();
+ } finally { err.restore(); release(); installFaultHook(undefined); await disposePersistenceConsumer(engine); }
+ }
+ }), 120_000);
+ });
+});