Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): a level read on a large source reports progress to the drain, a running history walk is shared, and status names passes that keep stopping before they end (#7355)

garrytanc02766bcd142
diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.md
index 90e5ba22bc..cccc2e6e19 100644
--- a/docs/guides/sync-unblock-runbook.md
+++ b/docs/guides/sync-unblock-runbook.md
@@ -363,6 +363,7 @@ run converges on the next plain sync with no flag.
| Status `reason` | `state` | What it means | `next` |
|---|---|---|---|
| `pass_unfinished` | resumable | The newest pass is open or stopped at a deadline. | The plain sync (`resume_argv`); safe to loop. |
+| `pass_abandoned` | blocked | Two passes in a row never ended: the drain stopped them for making no progress, or their process was killed. The newest open pass counts once its row has not moved for 5 minutes. | `gbrain doctor --json` and a report with the gbrain version and the newest run's `drain.stall`; another plain sync is likely to stop the same way. |
| `not_converged` | resumable | The pass used its four rounds while another writer kept changing the level. Everything it admitted stands. | The plain sync; after three such passes in a row `next` is `gbrain doctor --json` and a report, because another sync will not change it. |
| `settle_mismatch` | resumable | A path keeps settling without reading settled. The next pass re-admits it once; after three passes at one level it is a `settle_mismatch` hold that needs a person. | The plain sync, then report the hold. |
| `deletes_withheld` | blocked | The pass's deletes crossed the mass-delete threshold (#2828) or an absolute cap (#7130: `sync.max_deletes`, default 500; `sync.max_delete_ratio`, default 0.01 above 50 deletes; per source `<key>.source.<id>`). The record's `trip` names which. It wrote one withheld record and synced everything else; no per-page hold is written. | Ask the user: restore the checkout if it is wrong; when the deletion is intended, raise the cap for that source (`gbrain config set sync.max_deletes.source.<id> <n>`) or run `GBRAIN_ALLOW_MASS_RECONCILE=1 gbrain sync --source <id>` on the brain host. `gbrain sync --source <id> --dry-run --json` lists the set and its hash. |
diff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.ts
index 659960bbf3..9c307f4762 100644
--- a/src/commands/sync/operator.ts
+++ b/src/commands/sync/operator.ts
@@ -211,6 +211,7 @@ export function syncStatusHeadline(status: Pick<SyncStatus, 'source_id' | 'state
case 'head_blocked': return `Source ${status.source_id} is blocked: its oldest write waits on something only an operator clears.`;
case 'recovery_blocked': return `Source ${status.source_id} is blocked: a write's recovery record found changed bytes on disk.`;
case 'pass_unfinished': return `Source ${status.source_id} is resumable: the newest sync pass did not finish; the next sync continues it.`;
+ case 'pass_abandoned': return `Source ${status.source_id} is blocked: its sync passes keep stopping before they end; another plain sync will not change that (report what doctor shows).`;
case 'not_converged': return `Source ${status.source_id} is resumable: the newest sync pass ran out of rounds before every path settled.`;
case 'settle_mismatch': return `Source ${status.source_id} is resumable: a path keeps settling without reading settled; three passes in a row hold it.`;
case 'deletes_withheld': return `Source ${status.source_id} is blocked: sync withheld a mass delete; the rest of the source is synced.`;
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 5d416f75f3..4190074512 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1129,6 +1129,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.372.0', text: 'MCP `find_anomalies` and `gbrain anomalies --json` list at most 20 slugs per anomalous cohort; `count` still covers the whole cohort and `page_slugs_complete: false` marks a row that left slugs out. `gbrain anomalies --json --all` lists every slug on a local brain.' },
{ since: '0.60.372.0', text: 'When `gbrain serve`\'s stdout or stderr is a regular file (the `gbrain mcp expose` service installs, or any `>>` redirect), serve rotates that file at 10 MiB, keeping 5 copies (`<log>.1` to `<log>.5`), and writes a line repeated within 10 minutes once, followed by one "[gbrain serve-log] repeated N more time(s)" line. `GBRAIN_SERVE_LOG_MAX_BYTES` (0 turns rotation off), `GBRAIN_SERVE_LOG_MAX_FILES` and `GBRAIN_SERVE_LOG_DEDUPE_SECONDS` (0 turns dedupe off) change it.' },
{ since: '0.60.372.0', text: '`gbrain sources status --json` no longer prints every held file of a source by default: `git_holds` now carries `count`, `by_code` (each hold code with its count and one example item, whose `fix` applies to the rest), and the first 10 items with `items_complete: false` and an `items_command`. `--holds` lists every held file read, as before, and `--limit <n> [--cursor <c>]` pages them by path (the cursor needs the source id). The text output is unchanged.' },
+ // #7355: a level read reports progress; pass_abandoned; racy floor
+ { since: 'TBD', text: 'A managed `gbrain sync` pass no longer stops `drain_stalled` / `no_progress` on a large source while it is still reading and classifying the level before its first commit: the level read reports progress to the drain as it works (its loops and the history walk for the origin evidence of files a page lost), writes the open pass row every 30 s so a follower and `gbrain sync status` see it working, and a pass that asks for a history walk already running joins it. A hung read still stops after 5 minutes. When two passes in a row never end (abandoned by the drain or killed; the newest open one counts after 5 quiet minutes), `gbrain sync status` reads `blocked` with the new reason `pass_abandoned` and `next` is `gbrain doctor --json` and a report, instead of the plain sync. The stat caches of the dirtiness probe and the working level now take the racy window from the earlier of the process clock and the filesystem clock (a file written in the Git directory), so a mount whose clock lags the process no longer keeps a stale `clean` verdict.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.ts
index 29615a2a52..2fd9cb24ca 100644
--- a/src/core/persistence/sync-drain.ts
+++ b/src/core/persistence/sync-drain.ts
@@ -425,8 +425,8 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
if (event.phase === 'managed_sync.lanes' && event.lanes) lanes = { effective: event.lanes.effective, stepDown: event.lanes.stepDown, overlapped: event.lanes.overlapped, fallbacks: event.lanes.fallbacks };
// #6696 C4: the checkpoint commit is a commit; the tail after it is governed by its own budget.
if (event.phase === 'managed_sync.finish') { lastCommitAt = clock(); drops = 0; noteForwardProgress(); return; }
- // GBRA-108: a pass's committed legacy-sweep slice (sync-pass-apply.ts) is progress, though it publishes no page.
- if (event.phase === 'managed_sync.legacy_swept') { lastCommitAt = clock(); noteForwardProgress(); return; }
+ // GBRA-108: a committed legacy-sweep slice is progress, though it publishes no page; #7355: so is a level read still working.
+ if (event.phase === 'managed_sync.legacy_swept' || event.phase === 'managed_sync.level_progress') { lastCommitAt = clock(); noteForwardProgress(); return; }
if (event.phase !== 'managed_sync.page_committed') return;
if (event.waived) waived++; else written++;
lastCommitAt = clock(); drops = 0;
diff --git a/src/core/persistence/sync-git-stream.ts b/src/core/persistence/sync-git-stream.ts
index 0fd2769980..f328469d47 100644
--- a/src/core/persistence/sync-git-stream.ts
+++ b/src/core/persistence/sync-git-stream.ts
@@ -7,8 +7,9 @@
* is parsed as it streams; nothing but the result maps is held, so a
* 600k-path tree costs its map and one chunk.
*/
-import { lstatSync, realpathSync, type BigIntStats } from 'node:fs';
-import { join, relative, sep } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { lstatSync, readFileSync, realpathSync, rmSync, writeFileSync, type BigIntStats } from 'node:fs';
+import { join, relative, resolve, sep } from 'node:path';
import { hardenedGitStream, hardenedStreamComplete, NulRecordSplitter, type HardenedGitStreamResult } from '../hardened-git.ts';
import { gitBlobOid, sha256 } from './digest.ts';
import { readSyncFile } from './sync-discovery.ts';
@@ -313,7 +314,8 @@ interface ReadFile { path: string; sha256: string; localOid: string; foldedOid:
* is the tree's: a clean verdict depends on the raw bytes alone, so it needs no
* read, hash or attribute lookup. A probe is vouched only when the stat taken
* before the read is unchanged after the batch's hash and its `mtime` and
- * `ctime` are older than 2 s before the call began (the working stat cache's
+ * `ctime` are older than 2 s before the call began, by the earlier of the
+ * process's and the filesystem's clocks (`racyFloor`, the working stat cache's
* racy window), so an edit made during or after the read always rehashes.
*/
export async function probeDirtiness(root: string, gitRoot: string, paths: string[], tree: Map<string, GitTreeEntry>,
@@ -328,7 +330,7 @@ export async function probeDirtiness(root: string, gitRoot: string, paths: strin
const step = opts.step ?? loopYield();
const cleanKey = !opts.working && realRoot !== null && realGitRoot !== null ? `${realRoot}\0${realGitRoot}` : null;
const vouched = cleanKey === null ? null : new Map(cleanProbes.get(cleanKey));
- const racyFrom = BigInt(Date.now()) * 1_000_000n - WORKING_RACY_WINDOW_NS;
+ const racyFrom = vouched ? racyFloor(realGitRoot!) : 0n;
for (let start = 0; start < paths.length; start += batch) {
const decided = new Map<string, Dp | null>();
const read: ReadFile[] = [];
@@ -450,6 +452,25 @@ async function readAttributes(gitRoot: string, paths: string[]): Promise<Map<str
export interface WorkingStatCache { v: 1; root: string; entries: Record<string, string> }
const WORKING_RACY_WINDOW_NS = 2_000_000_000n;
+
+/**
+ * The newest time a vouched stat may carry: 2 s before the earlier of this process's clock and the filesystem's, read as
+ * the mtime of a file just written in the Git directory (Git anchors its racy entries to the index's mtime). On a mount
+ * whose clock lags the process's, the process clock alone vouched a file written a moment ago, and a same-size edit in
+ * the same timestamp tick then kept its stale verdict. The process clock alone when the Git directory cannot be written.
+ */
+function racyFloor(gitRoot: string): bigint {
+ const local = BigInt(Date.now()) * 1_000_000n;
+ let fs: bigint | null = null;
+ try {
+ const dotGit = join(gitRoot, '.git');
+ const dir = lstatSync(dotGit).isDirectory() ? dotGit : resolve(gitRoot, /^gitdir: (.+)$/m.exec(readFileSync(dotGit, 'utf8'))?.[1]?.trim() ?? '.git');
+ const clock = join(dir, `gbrain-clock-${process.pid}-${randomUUID()}`);
+ writeFileSync(clock, '');
+ try { fs = lstatSync(clock, { bigint: true }).mtimeNs; } finally { rmSync(clock, { force: true }); }
+ } catch {}
+ return (fs !== null && fs < local ? fs : local) - WORKING_RACY_WINDOW_NS;
+}
const WORKING_HASH_ATTEMPTS = 3;
const WORKING_STAT_CACHES_REMEMBERED = 64;
const ABSENT = 'absent';
@@ -501,7 +522,8 @@ export function workingChanged(cache: WorkingStatCache | null, paths: Iterable<s
* stat'd before and after its bytes are hashed; a path whose stat moved is
* discarded and rehashed, up to three attempts, and one still moving keeps its
* last probe but no entry. An entry is written only for a stable stat whose
- * `mtime` and `ctime` are older than 2 s before that attempt began (a racy entry is
+ * `mtime` and `ctime` are older than 2 s before that attempt began, by the earlier of
+ * the process's and the filesystem's clocks (`racyFloor`; a racy entry is
* left out, so the next pass rehashes it), and only for a probe with a level
* (raw bytes read, or `deleted` with nothing at the path). `afterHash` runs between
* the hash and the re-stat (tests inject an edit there).
@@ -515,7 +537,7 @@ export async function hashWorkingLevel(root: string, gitRoot: string, paths: str
const entries = new Map<string, string>();
let pending = [...new Set(paths)];
for (let attempt = 0; attempt < WORKING_HASH_ATTEMPTS && pending.length > 0; attempt++) {
- const racyFrom = BigInt(Date.now()) * 1_000_000n - WORKING_RACY_WINDOW_NS;
+ const racyFrom = realGitRoot === null ? BigInt(Date.now()) * 1_000_000n - WORKING_RACY_WINDOW_NS : racyFloor(realGitRoot);
const before = new Map(pending.map(path => [path, statOf(path)]));
const probed = await probeDirtiness(root, gitRoot, pending, tree, new Map(), { batch: opts.batch, working: true });
await opts.afterHash?.(pending);
diff --git a/src/core/persistence/sync-origin-evidence.ts b/src/core/persistence/sync-origin-evidence.ts
index d3c53cbaf5..836969bc15 100644
--- a/src/core/persistence/sync-origin-evidence.ts
+++ b/src/core/persistence/sync-origin-evidence.ts
@@ -123,12 +123,27 @@ async function isAncestor(gitRoot: string, ancestor: string, commit: string): Pr
/**
* The history of the commit `tip` (a full object id) in the work tree at `gitRoot`: a cached walk, a cached walk of an
* ancestor extended by the commits after it (those are newer, so their deletions win), or one full walk. Null when Git
- * could not answer.
+ * could not answer. #7355: a caller that asks while that walk runs joins it (and hears its commits) instead of starting
+ * another, so a pass that follows an abandoned one waits for the walk already under way rather than walking from the start.
*/
async function historyIndex(gitRoot: string, tip: string, onCommit?: (commits: number) => void): Promise<HistoryIndex | null> {
- const cached = historyIndexes.get(gitRoot) ?? [];
- const exact = cached.find(index => index.tip === tip);
+ const exact = (historyIndexes.get(gitRoot) ?? []).find(index => index.tip === tip);
if (exact) return exact;
+ const key = `${gitRoot}\0${tip}`;
+ let running = historyWalks.get(key);
+ if (!running) {
+ const listeners = new Set<(commits: number) => void>();
+ running = { listeners, index: indexAt(gitRoot, tip, commits => { for (const listener of listeners) listener(commits); }).finally(() => historyWalks.delete(key)) };
+ historyWalks.set(key, running);
+ }
+ if (onCommit) running.listeners.add(onCommit);
+ try { return await running.index; } finally { if (onCommit) running!.listeners.delete(onCommit); }
+}
+
+const historyWalks = new Map<string, { listeners: Set<(commits: number) => void>; index: Promise<HistoryIndex | null> }>();
+
+async function indexAt(gitRoot: string, tip: string, onCommit: (commits: number) => void): Promise<HistoryIndex | null> {
+ const cached = historyIndexes.get(gitRoot) ?? [];
let base: HistoryIndex | undefined;
for (const index of cached) if (await isAncestor(gitRoot, index.tip, tip)) { base = index; break; }
const walked = await walkHistory(gitRoot, base ? [tip, `^${base.tip}`] : [tip], onCommit);
@@ -153,9 +168,10 @@ async function commitId(gitRoot: string, rev: string): Promise<string | null> {
/**
* The evidence for each Git-root-relative path in `gitPaths`, read in the work tree at `gitRoot`. `commits` are the
* history tips to search (the pinned target and the pass's baseline); a path any commit reachable from one of them
- * touched was committed. `.gitignore` is read as the checkout has it now.
+ * touched was committed. `.gitignore` is read as the checkout has it now. `onCommit` hears every 1,000 commits a walk reads.
*/
-export async function readOriginEvidence(gitRoot: string, commits: ReadonlyArray<string | null | undefined>, gitPaths: readonly string[]): Promise<Map<string, OriginEvidence>> {
+export async function readOriginEvidence(gitRoot: string, commits: ReadonlyArray<string | null | undefined>, gitPaths: readonly string[],
+ opts: { onCommit?: (commits: number) => void } = {}): Promise<Map<string, OriginEvidence>> {
const evidence = new Map<string, OriginEvidence>();
const tips = [...new Set(commits.filter((commit): commit is string => typeof commit === 'string' && commit.length > 0))];
const paths = [...new Set(gitPaths)];
@@ -170,7 +186,7 @@ export async function readOriginEvidence(gitRoot: string, commits: ReadonlyArray
}
const indexes: HistoryIndex[] = [];
for (const id of walked) {
- const index = await historyIndex(gitRoot, id);
+ const index = await historyIndex(gitRoot, id, opts.onCommit);
if (index) indexes.push(index); else historyKnown = false;
}
for (let i = 0; i < paths.length; i += BATCH) {
diff --git a/src/core/persistence/sync-pass-row.ts b/src/core/persistence/sync-pass-row.ts
index f820e5a0f6..40d8040172 100644
--- a/src/core/persistence/sync-pass-row.ts
+++ b/src/core/persistence/sync-pass-row.ts
@@ -72,6 +72,8 @@ export interface ManagedSyncPassValue {
converged?: PassConverged;
mismatch: Record<string, { level: string | null; streak: number }>;
not_converged_streak: number;
+ /** #7355: at this pass's pin, how many passes in a row before it never ended (their row was left `open`: a pass the drain's governor abandoned, or a killed process). Status counts it only while this pass's row is open. */
+ abandoned_streak?: number;
/** When the current run of unhealthy endings (`blocked`, `not_converged`) began; kept across them, cleared at `synced`/`up_to_date`. The §3.7 readers age a stuck source from it. */
stuck_since?: string | null;
faults: Record<string, { level: string | null; class: string; attempts: number }>;
@@ -132,6 +134,10 @@ export const OPEN_AT_STAMP_CAP = 256;
export const SETTLE_MISMATCH_STREAK = 3;
/** Consecutive `not_converged` passes after which `fix.next` becomes `report` (design §3.1, DX R9). */
export const NOT_CONVERGED_REPORT_STREAK = 3;
+/** #7355: passes in a row that never ended (the newest counted once its row has been quiet for ABANDONED_QUIET_MS) before status stops sending the plain sync. */
+export const ABANDONED_REPORT_STREAK = 2;
+/** The drain's in-pass no-progress window: an open row quiet this long belongs to no live pass. */
+export const ABANDONED_QUIET_MS = 5 * 60_000;
export const passFingerprint = (sourceId: string, incarnation: string) => `${sourceId}:${incarnation}`;
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index c0b98c9486..ace2a5972b 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -70,6 +70,8 @@ export const PASS_MAX_ROUNDS = 4;
export const PASS_BATCH_MAX = 10_000;
/** Waits for in-flight work a pass makes before it stops `writer_pending`, each bounded by the wait budget. */
const IN_FLIGHT_WAITS = 4;
+/** #7355: how often a long level read writes the open pass row, so a follower and `sync status` see it working. */
+const PASS_HEARTBEAT_MS = 30_000;
export interface SyncPassInput {
opts: SyncOpts; slice?: { maxPages: number; maxMs: number }; context: ManagedSyncContext; authority: SyncAuthority;
@@ -387,6 +389,8 @@ async function pinPass(engine: BrainEngine, input: SyncPassInput, lease: NonNull
const obligations: ManagedSyncPassValue['obligations'] = prior ? structuredClone(prior.value.obligations)
: { baseline_commit: context.source.last_commit, mismatch: {}, not_converged_streak: 0, faults: {} };
obligations.mismatch ??= {}; obligations.faults ??= {}; obligations.not_converged_streak ??= 0;
+ const abandoned = prior?.value.telemetry.outcome === 'open' ? (obligations.abandoned_streak ?? 0) + 1 : 0;
+ if (abandoned) obligations.abandoned_streak = abandoned; else delete obligations.abandoned_streak;
if (handover.episode && !obligations.episode) obligations.episode = handover.episode;
const passId = randomUUID();
// #6696: a cost-gate deferral rides as noEmbed but is this run's constraint (its requests carry embedDeferred), never an opt-out an episode keeps.
@@ -436,6 +440,24 @@ async function pinPass(engine: BrainEngine, input: SyncPassInput, lease: NonNull
processingOptions, inherited, pack, converged, cacheKey, kindStarted, working, kind, value, markersOwed };
}
+/**
+ * #7355: a level read that screens a large source for minutes before its first commit is progress too. `report` tells the
+ * drain's governor it is working and, every PASS_HEARTBEAT_MS, saves the open row (what a follower and `sync status` read);
+ * `pending` is that save, which the pass's next save waits for so an older row never lands over a newer one.
+ */
+function levelBeat(opts: SyncOpts, sliceBase: { pages: number }, save: () => Promise<void>): { report: () => void; readonly pending: Promise<void> | null } {
+ let at = Date.now(), pending: Promise<void> | null = null;
+ return {
+ report: () => {
+ opts.onProgress?.({ phase: 'managed_sync.level_progress', bankedFiles: sliceBase.pages });
+ if (Date.now() - at < PASS_HEARTBEAT_MS || pending) return;
+ at = Date.now();
+ pending = save().catch(() => undefined).finally(() => { pending = null; });
+ },
+ get pending() { return pending; },
+ };
+}
+
/** A pass result that imported nothing, at the source's last commit. */
function emptyPassResult(context: ManagedSyncContext, remote: boolean, status: SyncResult['status'], reason?: SyncResult['reason']): SyncResult {
return { status, fromCommit: remote ? null : context.source.last_commit, toCommit: remote ? '' : context.source.last_commit ?? '',
@@ -705,7 +727,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
pack, full: kind === 'full', counts, extract: !processingOptions.noExtract, since: value.telemetry.started_at, rescreen: legacyWaived.size > 0, closures });
const save = async (outcome: PassOutcome, stopReason: string | null, pin = false) => {
- const ended = outcome !== 'open';
+ await beat.pending; const ended = outcome !== 'open';
if (ended && outcome !== 'synced') {
const open = await openPassRequests(engine, { sourceId, passId, carried: value.obligations.pending_requests ?? [] });
if (open.length) value.obligations.pending_requests = open; else delete value.obligations.pending_requests;
@@ -716,8 +738,8 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
if (outcome === 'blocked' || stopReason === 'not_converged') value.obligations.stuck_since ??= new Date().toISOString();
await engine.transaction(async tx => { await assertDrainLease(tx, sourceId); await writePassRow(tx, value, { pin }); });
};
- // GBRA-108: a committed legacy-sweep slice is progress: the row a follower watches and the drain's in-pass governor see it.
- const onSwept = async () => { assertActive(); await save('open', null); opts.onProgress?.({ phase: 'managed_sync.legacy_swept', bankedFiles: sliceBase.pages }); };
+ // GBRA-108: a committed legacy-sweep slice is progress the row and the drain's governor see; #7355: so is a level read still working (`levelBeat`).
+ const onSwept = async () => { assertActive(); await save('open', null); opts.onProgress?.({ phase: 'managed_sync.legacy_swept', bankedFiles: sliceBase.pages }); }, beat = levelBeat(opts, sliceBase, () => save('open', null));
const identityDowngrades: DowngradedRename[] = [];
const fileRefusals = new Map<string, SyncFileRefusal>();
const keptCount = () => lastLevel?.paths.filter(entry => entry.result.cls === 'kept').length ?? 0;
@@ -813,7 +835,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
writeIds: value.obligations.converged?.writeback ?? [] })) return synced(true);
const levelInput = { sourceId, context, workingTree: mode === 'working',
pass: { noSchemaPack: processingOptions.noSchemaPack, episodeFullId: episode?.full_id ?? null, retryConsumed: round > 1 ? retryConsumed : undefined, exclude: opts.exclude, includeHidden: opts.includeHidden, strategy: opts.strategy, bootstrap: markersOwed(),
- slugMode: value.obligations.slug_mode, cache: levelCache, passId, recorded: applied.recorded } };
+ slugMode: value.obligations.slug_mode, cache: levelCache, passId, recorded: applied.recorded, onProgress: beat.report } };
const level = await readShadowLevel(engine, levelInput);
await faultPoint('sync:level_read', { sourceId, round, level: level ? { statements: level.statements, confirm: level.confirm ?? null, reused: level.reused ?? 0, shadow: level, input: levelInput } : undefined });
assertActive();
diff --git a/src/core/persistence/sync-pass-status.ts b/src/core/persistence/sync-pass-status.ts
index 666a8be82e..6a410de2e6 100644
--- a/src/core/persistence/sync-pass-status.ts
+++ b/src/core/persistence/sync-pass-status.ts
@@ -10,7 +10,7 @@ import type { SyncAdmissionStatus } from './sync-admission.ts';
import { digest } from './digest.ts';
import { fileDriftSide, type GitHoldRecord } from './sync-holds.ts';
import { readDeletesWithheld, type DeletesWithheld } from './sync-markers.ts';
-import { NOT_CONVERGED_REPORT_STREAK, passHealth, type PassRoundSummary, type PassRow } from './sync-pass-row.ts';
+import { ABANDONED_QUIET_MS, ABANDONED_REPORT_STREAK, NOT_CONVERGED_REPORT_STREAK, passHealth, type PassRoundSummary, type PassRow } from './sync-pass-row.ts';
export interface PassConvergence {
schema: 'convergence/1'; dry_run: false; source_id: string;
@@ -52,7 +52,13 @@ export async function passConvergence(engine: Pick<BrainEngine, 'executeRaw'>, i
duration_ms: t.duration_ms, timings_ms: t.timings_ms, last_full_at: o.converged?.last_full_at ?? null };
}
-export type PassStatusReason = 'pass_unfinished' | 'not_converged' | 'settle_mismatch' | 'deletes_withheld' | 'selection_scoped' | 'admission_paused' | 'writeback_failed';
+export type PassStatusReason = 'pass_unfinished' | 'pass_abandoned' | 'not_converged' | 'settle_mismatch' | 'deletes_withheld' | 'selection_scoped' | 'admission_paused' | 'writeback_failed';
+
+/** #7355: passes in a row that never ended, the newest open one included once its row has been quiet past the no-progress window. */
+export function abandonedPasses(row: PassRow, now = Date.now()): number {
+ const quiet = row.value.telemetry.outcome === 'open' && now - Date.parse(row.updated_at) >= ABANDONED_QUIET_MS;
+ return row.value.telemetry.outcome === 'open' ? (row.value.obligations.abandoned_streak ?? 0) + (quiet ? 1 : 0) : 0;
+}
/**
* The state the newest pass puts the source in (design §9): never `synced` while it is open or ended unconverged, or while a
@@ -60,6 +66,7 @@ export type PassStatusReason = 'pass_unfinished' | 'not_converged' | 'settle_mis
*/
export function passStatusState(row: PassRow, withheld: DeletesWithheld | null, writebackFailed: string | null = null, now = Date.now()): ['synced' | 'resumable' | 'blocked', PassStatusReason] | null {
const t = row.value.telemetry;
+ if (abandonedPasses(row, now) >= ABANDONED_REPORT_STREAK) return ['blocked', 'pass_abandoned'];
if (t.outcome === 'open' || (t.outcome === 'resumable' && t.stop_reason !== 'not_converged' && t.stop_reason !== 'admission_paused')) return ['resumable', 'pass_unfinished'];
if (t.stop_reason === 'admission_paused') return ['resumable', 'admission_paused'];
if (t.stop_reason === 'not_converged' || (row.value.obligations.not_converged_streak ?? 0) > 0) return ['resumable', 'not_converged'];
@@ -93,6 +100,9 @@ export function passStatusNext(sourceId: string, reason: PassStatusReason, row:
return { argv: ['gbrain', 'sources', 'writer', 'retry-effects', sourceId, '--request-id', writebackFailed ?? '<id>', '--dry-run'], consent: [], actor: 'agent', requires_exclusive: false, verify,
user_message: `The Git effect of a file sync rewrote in ${sourceId} (request ${writebackFailed}) failed and is parked, so the checkout does not hold what the brain holds. Fix the cause doctor's parked_effects names, then retry it with the same command without --dry-run.`,
why: 'The preview names the parked effect and what a retry runs (read-only); until it commits, the source is never idle.' };
+ case 'pass_abandoned':
+ return { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false, verify,
+ why: `The last ${abandonedPasses(row)} sync passes of ${sourceId} stopped before they ended (the drain abandoned them for making no progress, or their process was killed), so another plain sync is likely to stop the same way. Report what doctor shows, with the gbrain version and the newest sync run's drain.stall (read-only).` };
case 'selection_scoped':
return { ...sync, why: 'The last pass converged at a narrower selection and did not advance last_commit; the plain sync runs the configured selection.' };
default:
diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.ts
index 9c0c88c76e..e9c994aa73 100644
--- a/src/core/persistence/sync-pass.ts
+++ b/src/core/persistence/sync-pass.ts
@@ -43,7 +43,7 @@ import { buildConvergenceReceipt, readOnlySameContentScreen, type ConvergenceRec
import { readManagedMode } from './ownership.ts';
import { MANAGED_SYNC_PASS_OP, SYNC_ORIGIN_DELETED_OP, type SyncSelection } from './sync-pass-row.ts';
import { faultPoint } from './fault-points.ts';
-import { filterYielding, loopYield, sortYielding, turnYield, type LoopYield } from './sync-yield.ts';
+import { filterYielding, loopYield, progressYield, sortYielding, turnYield, type LoopYield } from './sync-yield.ts';
import { countsMatch, proveConfirm, readLevelMark, type ConfirmProof, type LevelMark } from './sync-pass-confirm.ts';
import { domainCache, levelDomain, narrowedWalk, walkAttestations, type LevelDomainCache } from './sync-pass-narrow.ts';
@@ -74,6 +74,8 @@ export interface PassLevelInput {
passId?: string;
/** The pages whose import record the pass's previous round wrote (sync-pass-apply.ts `recorded`). */
recorded?: ReadonlySet<number>;
+ /** #7355: called while the read works (its loops' pauses, at most once a second, and the origin history walk), so the drain sees progress before the first commit. */
+ onProgress?: () => void;
}
/** PGLite's keyset page size (design v3.2 §2.1). */
const PGLITE_KEYSET_ROWS = 2_000;
@@ -567,10 +569,10 @@ async function readUntracked(gitRoot: string, scope: string): Promise<string[]>
const timer = () => { const started = performance.now(); return () => Math.round((performance.now() - started) * 10) / 10; };
/** #7130: an absent file is deletion evidence only when Git once committed it (sync-origin-evidence.ts); read for those paths alone. */
-async function reclassifyByOrigin(gitRoot: string, tips: Array<string | null | undefined>, paths: ShadowPath[], step: LoopYield): Promise<boolean> {
+async function reclassifyByOrigin(gitRoot: string, tips: Array<string | null | undefined>, paths: ShadowPath[], step: LoopYield, onProgress?: () => void): Promise<boolean> {
const absent = await filterYielding(paths, entry => (entry.result.cls === 'delete' || entry.result.cls === 'delete_drift') && entry.state.originEvidence === undefined, step);
if (!absent.length) return false;
- const evidence = await readOriginEvidence(gitRoot, tips, absent.map(entry => entry.path));
+ const evidence = await readOriginEvidence(gitRoot, tips, absent.map(entry => entry.path), { onCommit: onProgress });
for (const entry of absent) {
const state = { ...entry.state, originEvidence: evidence.get(entry.path) ?? 'unknown' as const };
Object.assign(entry, { state, result: classifySyncPath(state) });
@@ -613,7 +615,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
// the one rule discovery and preparation use (sameSyncOrigin; it refuses an origin that could name two files).
const originScope = { sourceId, root, scope, slugMode };
const pageOrigin = (sourcePath: string, slug: string): string => scopedPageOrigin(originPath(sourcePath), slug, originScope);
- const step = turnYield();
+ const step = progressYield(turnYield(), input.pass?.onProgress);
t = timer();
const { head, detached } = await readLevelHead(gitRoot, sourceId);
@@ -847,7 +849,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
}
t = timer();
- if (await reclassifyByOrigin(gitRoot, [head, baselineCommit], paths, step)) timings.origin = t();
+ if (await reclassifyByOrigin(gitRoot, [head, baselineCommit], paths, step, input.pass?.onProgress)) timings.origin = t();
// Adoption by hash needs the level's bytes: committed mode reads the blobs of the candidates that could adopt.
const needBytes = await filterYielding(paths, entry => !['matched', 'held', 'dirty'].includes(entry.result.cls) && entry.state.levelSha256 === null && entry.state.level !== null
diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.ts
index 26dbb9d00f..cca122321f 100644
--- a/src/core/persistence/sync-status.ts
+++ b/src/core/persistence/sync-status.ts
@@ -175,7 +175,9 @@ export type SyncStatusState = 'synced' | 'resumable' | 'blocked';
export const SYNC_STATUS_REASONS = ['nothing_pending', 'held_by_design', 'held_needs_human', 'cursor_unfinished', 'live_job', 'last_error', 'holds_actionable', 'recovery_pending', 'request_pending',
'status_unknown', 'needs_human', 'head_blocked', 'recovery_blocked',
// #6712 PR 4b (design v3.2 §9): the live pass's reasons.
- 'pass_unfinished', 'not_converged', 'settle_mismatch', 'deletes_withheld', 'selection_scoped', 'admission_paused', 'writeback_failed'] as const;
+ 'pass_unfinished', 'not_converged', 'settle_mismatch', 'deletes_withheld', 'selection_scoped', 'admission_paused', 'writeback_failed',
+ // #7355: passes keep stopping before they end.
+ 'pass_abandoned'] as const;
export type SyncStatusReason = typeof SYNC_STATUS_REASONS[number];
export type SyncStatusRead = { status: 'read' } | { status: 'not_read'; fix: Action };
/** The bound of each default probe (the oldest blocker, the recovery records). */
diff --git a/src/core/persistence/sync-yield.ts b/src/core/persistence/sync-yield.ts
index 5f0190c495..f6211251f6 100644
--- a/src/core/persistence/sync-yield.ts
+++ b/src/core/persistence/sync-yield.ts
@@ -29,6 +29,16 @@ export function loopYield(): LoopYield {
};
}
+/**
+ * #7355: `step` that also reports from its pauses, at most once per `everyMs`: a level read that screens a large source for
+ * minutes before its first commit tells the drain's in-pass governor it is working, as a commit does.
+ */
+export function progressYield(step: LoopYield, onProgress: (() => void) | undefined, everyMs = 1_000): LoopYield {
+ if (!onProgress) return step;
+ let last = performance.now();
+ return { due: step.due, over: step.over, pause: async () => { await step.pause(); if (performance.now() - last >= everyMs) { last = performance.now(); onProgress(); } } };
+}
+
/** How often the shared budget's clock notes that timers ran, and for how many ticks it keeps going once nothing asks. */
const TURN_TICK_MS = 4, TURN_QUIET_TICKS = 25;
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 843333938c..0e3487b9c9 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -441,6 +441,7 @@ test/sync-legacy-sweep-resume-7189.test.ts
test/sync-origin-live-wins-6517.test.ts
test/sync-page-identity-hold-gbra130.test.ts
test/sync-page-write-failed-gbra130.test.ts
+test/sync-pass-abandoned-7355.test.ts
test/sync-pass-cost-grouping-gbra130.test.ts
test/sync-pass-dirty-after-freeze-gbra130.test.ts
test/sync-prescreen-both-delta-6712.test.ts
diff --git a/test/sync-pass-abandoned-7355.test.ts b/test/sync-pass-abandoned-7355.test.ts
new file mode 100644
index 0000000000..14b4a0ad88
--- /dev/null
+++ b/test/sync-pass-abandoned-7355.test.ts
@@ -0,0 +1,148 @@
+/**
+ * #7355: on a large managed source the first full pass read and classified the whole level, including one walk of the
+ * whole Git history for the origin evidence of files a page lost, before its first commit. The drain's in-pass governor
+ * counts only commits and committed sweep slices as progress, so a level read past its 5-minute window was abandoned with
+ * nothing banked, and every following pass started the same read again. `sync status` kept sending the plain sync.
+ * The level read now reports progress while it works (its loops' pauses and the history walk's commits), a pass asking
+ * for a history walk already under way joins it, and status names passes that keep stopping before they end.
+ */
+import { describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { SyncResult } from '../src/commands/sync.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { runDrain } from '../src/core/persistence/sync-drain.ts';
+import { __resetHistoryIndexesForTest, readOriginEvidence } from '../src/core/persistence/sync-origin-evidence.ts';
+import { abandonedPasses, passStatusNext, passStatusState } from '../src/core/persistence/sync-pass-status.ts';
+import { MANAGED_SYNC_PASS_OP, readPassRow, type PassRow } from '../src/core/persistence/sync-pass-row.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+const git = (root: string, args: string[], input?: string) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]', '-c', 'commit.gpgsign=false', ...args],
+ { encoding: 'utf8', input, stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'] }).trim();
+const done: SyncResult = { status: 'synced', fromCommit: 'a', toCommit: 'b', added: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [] };
+const page = (title: string) => `---\ntype: concept\ntitle: ${title}\n---\n\nA note about ${title}.\n`;
+
+/** `count` empty commits on top of HEAD through one `git fast-import`, so the history walk has thousands of commits to read. */
+function emptyCommits(root: string, count: number): void {
+ const branch = git(root, ['symbolic-ref', 'HEAD']);
+ let stream = '';
+ for (let i = 0; i < count; i++) stream += `commit ${branch}\ncommitter Example <[email protected]> ${1_700_000_000 + i} +0000\ndata 2\nc\n${i === 0 ? `from ${branch}^0\n` : ''}\n`;
+ git(root, ['fast-import', '--quiet', '--force'], stream);
+}
+
+function repo(): string {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-7355-'));
+ git(root, ['init', '-q']);
+ writeFileSync(join(root, 'a.md'), page('a'));
+ git(root, ['add', '-A']); git(root, ['commit', '-qm', 'a']);
+ return root;
+}
+
+describe('#7355: the drain hears a level read that is still working', () => {
+ test('a pass that reports level progress past the no-progress window is not abandoned', async () => {
+ const result = await runDrain({ governMs: 10, noProgressMs: 80, publicationCeilingMs: 60_000,
+ pass: async (_signal, onProgress) => {
+ for (let i = 0; i < 20; i++) { onProgress?.({ phase: 'managed_sync.level_progress' }); await Bun.sleep(20); }
+ return done;
+ } });
+ expect(result.drain).toMatchObject({ outcome: 'synced', passes: 1 });
+ }, 15_000);
+
+ test('a pass that goes quiet is still stopped no_progress', async () => {
+ const result = await runDrain({ governMs: 10, noProgressMs: 80, publicationCeilingMs: 60_000,
+ pass: async (_signal, onProgress) => { onProgress?.({ phase: 'managed_sync.level_progress' }); return new Promise<SyncResult>(() => undefined); } });
+ expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled', stall: { cause: 'no_progress', in_pass: true } });
+ }, 15_000);
+});
+
+describe('#7355: the origin history walk reports its commits and is shared', () => {
+ test('two callers asking while one walk runs both hear its commits and get the same evidence', async () => {
+ const root = repo();
+ try {
+ emptyCommits(root, 2_500);
+ unlinkSync(join(root, 'a.md')); git(root, ['commit', '-qam', 'remove a']);
+ __resetHistoryIndexesForTest();
+ const head = git(root, ['rev-parse', 'HEAD']);
+ const heard = [0, 0];
+ const [first, second] = await Promise.all([0, 1].map(i => readOriginEvidence(root, [head], ['a.md', 'never.md'], { onCommit: () => { heard[i]!++; } })));
+ expect(heard[0]).toBeGreaterThan(0);
+ expect(heard[1]).toBeGreaterThan(0);
+ expect(Object.fromEntries(first!)).toEqual({ 'a.md': 'committed', 'never.md': 'never_committed' });
+ expect(Object.fromEntries(second!)).toEqual(Object.fromEntries(first!));
+ } finally { rmSync(root, { recursive: true, force: true }); __resetHistoryIndexesForTest(); }
+ }, 60_000);
+});
+
+describe('#7355: status names passes that keep stopping before they end', () => {
+ const row = (outcome: string, streak: number | undefined, quietMs: number, now: number): PassRow => ({ updated_at: new Date(now - quietMs).toISOString(),
+ value: { source_id: 's', incarnation: 'i', lease_token: 't', obligations: { baseline_commit: null, mismatch: {}, not_converged_streak: 0, faults: {}, ...(streak ? { abandoned_streak: streak } : {}) },
+ telemetry: { pass_id: 'p', target: 'h', started_at: '', ended_at: null, kind: 'full', round: 0, outcome: outcome as never, stop_reason: null, candidates: 0, settled: 0, remaining: 0, counts: {}, duration_ms: null, timings_ms: {} } } });
+ const now = Date.parse('2026-10-22T12:00:00Z');
+
+ test('an open pass after an abandoned one, quiet past the window, is blocked pass_abandoned and next is a report', () => {
+ const stuck = row('open', 1, 6 * 60_000, now);
+ expect(abandonedPasses(stuck, now)).toBe(2);
+ expect(passStatusState(stuck, null, null, now)).toEqual(['blocked', 'pass_abandoned']);
+ const next = passStatusNext('s', 'pass_abandoned', stuck, ['--source', 's']);
+ expect(next.argv).toEqual(['gbrain', 'doctor', '--json']);
+ expect(next.why).toContain('another plain sync is likely to stop the same way');
+ });
+
+ test('a pass that is still moving, or the first one abandoned, keeps sending the plain sync', () => {
+ expect(passStatusState(row('open', 1, 10_000, now), null, null, now)).toEqual(['resumable', 'pass_unfinished']);
+ expect(passStatusState(row('open', undefined, 6 * 60_000, now), null, null, now)).toEqual(['resumable', 'pass_unfinished']);
+ expect(passStatusState(row('synced', 3, 6 * 60_000, now), null, null, now)).toBeNull();
+ });
+});
+
+describe('#7354 review: the racy window follows the filesystem clock, not only the process clock', () => {
+ test('a file written just now is not vouched when the process clock runs ahead of the filesystem', async () => {
+ const { probeDirtiness, readIndexLevel, readTreeLevel } = await import('../src/core/persistence/sync-git-stream.ts');
+ const root = repo();
+ const realNow = Date.now;
+ try {
+ const tree = await readTreeLevel(root, 'HEAD', ''), index = await readIndexLevel(root);
+ Date.now = () => realNow() + 3_000;
+ expect((await probeDirtiness(root, root, ['a.md'], tree, index)).get('a.md')?.dp).toBe('clean');
+ Date.now = realNow;
+ const { renameSync } = await import('node:fs');
+ renameSync(join(root, '.git'), join(root, '.git-away'));
+ try { expect((await probeDirtiness(root, root, ['a.md'], tree, index)).get('a.md')?.dp).toBe('unknown'); }
+ finally { renameSync(join(root, '.git-away'), join(root, '.git')); }
+ } finally { Date.now = realNow; rmSync(root, { recursive: true, force: true }); }
+ }, 30_000);
+});
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ test(`#7355 [${backend}]: a live pass reports level progress, and a pass after one left open counts it until it ends`, () => managedBrain(async ({ engine, root }) => {
+ const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+ expect((await performManagedSync(engine, OPTS)).status).toMatch(/^(first_sync|synced)$/);
+
+ // A file the page lost behind a long history: the pass reads the origin evidence from one walk of it.
+ emptyCommits(root, 2_500);
+ unlinkSync(join(root, 'b.md')); git(root, ['commit', '-qam', 'remove b']);
+ __resetHistoryIndexesForTest();
+ // The previous pass never ended: its row is left open, as the governor or a killed process leaves it.
+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,telemetry,outcome}','"open"') WHERE op=$1`, [MANAGED_SYNC_PASS_OP]);
+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");
+ let pinnedStreak: number | undefined;
+ installFaultHook(async point => { if (point === 'sync:round_start' && pinnedStreak === undefined) pinnedStreak = (await readPassRow(engine, 'default', incarnation!))?.value.obligations.abandoned_streak; });
+ const phases: string[] = [];
+ const result = await performManagedSync(engine, { ...OPTS, onProgress: event => { phases.push(event.phase); } }).finally(() => installFaultHook(undefined));
+ expect(result.status).toBe('synced');
+ expect(pinnedStreak).toBe(1);
+ expect(phases).toContain('managed_sync.level_progress');
+ const ended = (await readPassRow(engine, 'default', incarnation!))!;
+ expect(abandonedPasses(ended)).toBe(0);
+ expect(passStatusState(ended, null)).toBeNull();
+ }, { databaseUrl, setup: ({ root }) => {
+ git(root, ['init', '-q']);
+ for (const name of ['a', 'b']) writeFileSync(join(root, `${name}.md`), page(name));
+ git(root, ['add', '-A']); git(root, ['commit', '-qm', 'pages']);
+ } }), 120_000);
+}