Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): a deadline-stopped pass resumes its scheduled re-screens; hold writes are holder progress (#7327)

garrytan7519846d049c
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 6ffe6f86e4..19bedd816e 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1120,6 +1120,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.366.0', id: 'concepts_hold_before_spend', text: '`synthesize_concepts` now checks an existing concept page before the model call: a page whose fences it cannot republish losslessly (`concept_preservation_hold`) or whose body is stored in segments (`page_body_segmented`) is listed under `publication_held` with no model spend, every cycle, and a segmented concept no longer stops the phase. A concept\'s failed-attempt count is cleared only after its narrative is published.' },
{ since: '0.60.366.0', id: 'calibration_profile_unchanged_skip', text: '`calibration_profile` makes no model call and writes no new profile row when the holder\'s resolved count, Brier score, accuracy, partial rate and model all equal the latest stored profile (`skipped: unchanged_scorecard`); a new profile prompt takes effect at the next scorecard change.' },
{ since: '0.60.366.0', id: 'grade_takes_window', text: '`grade_takes` now reads unresolved takes oldest-first, leaves takes too recent to grade (or with no date) out of its 50-take window, and puts takes with no verdict for the current prompt and judge ahead of graded ones, so with auto-resolve off older takes beyond the first 50 are graded on later passes. Its `too_recent` count now covers only takes whose date it could not read in SQL.' },
+ // #7327: a deadline-stopped pass resumes its scheduled re-screens; hold writes are holder progress
+ { since: 'TBD', text: 'A managed sync pass that stops at its deadline, a yield or a block now consumes the scheduled re-screens (`gbrain sources retry-held`) of the held files it already passed. The next pass resumes after them instead of re-screening every scheduled hold again; before, a scheduled re-screen larger than one job\'s budget never finished. A follower `gbrain sync` and the drain holder\'s `stalled` flag in status output now count the holder\'s hold writes as progress, so a holder that is screening held files is no longer reported `drain_stalled` / `no_progress` after 5 minutes.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/sync-lease.ts b/src/core/persistence/sync-lease.ts
index 3054ed6a52..c970cb22a4 100644
--- a/src/core/persistence/sync-lease.ts
+++ b/src/core/persistence/sync-lease.ts
@@ -108,8 +108,9 @@ export async function readDrainHolder(engine: BrainEngine, sourceId: string): Pr
}
/**
- * The source's managed-sync commits since `since`, and its last commit, cursor save or (#6712 PR 4b, design v3.2 §3.7)
- * pass row write at all: a pass writes its row at the pin, per batch and at the stamp.
+ * The source's managed-sync commits since `since`, and its last commit, cursor save, (#6712 PR 4b, design v3.2 §3.7)
+ * pass row write or (#7327) hold write at all: a pass writes its row at the pin, per batch and at the stamp, and every
+ * hold it writes or re-screens touches the source's hold summary row, so a pass screening only holds is progressing.
*/
async function holderProgress(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, since: Date | null): Promise<DrainHolderProgress> {
const [row] = await engine.executeRaw<{ committed: number | string; last_committed_at: Date | string | null; last_saved_at: Date | string | null }>(`
@@ -118,7 +119,8 @@ async function holderProgress(engine: Pick<BrainEngine, 'executeRaw'>, sourceId:
(SELECT max(r.completed_at) FROM persistence_requests r WHERE r.worktree_id=b.worktree_id AND r.source_incarnation=b.source_incarnation
AND r.state='committed' AND COALESCE(r.intent->>'kind','') LIKE 'managed_sync_%') AS last_committed_at,
GREATEST((SELECT max(c.updated_at) FROM op_checkpoints c WHERE c.op='managed-sync' AND c.completed_keys->0->>'sourceId'=$1),
- (SELECT c.updated_at FROM op_checkpoints c WHERE c.op=$3 AND c.fingerprint=b.source_id||':'||b.source_incarnation::text)) AS last_saved_at
+ (SELECT c.updated_at FROM op_checkpoints c WHERE c.op=$3 AND c.fingerprint=b.source_id||':'||b.source_incarnation::text),
+ (SELECT c.updated_at FROM op_checkpoints c WHERE c.op='sync-hold-summary' AND c.fingerprint=b.source_id||':'||b.source_incarnation::text)) AS last_saved_at
FROM persistence_source_bindings b WHERE b.source_id=$1`, [sourceId, (since ?? new Date(0)).toISOString(), MANAGED_SYNC_PASS_OP]);
const at = (value: Date | string | null | undefined) => value == null ? null : new Date(value).toISOString();
const committedAt = at(row?.last_committed_at), savedAt = at(row?.last_saved_at);
@@ -126,7 +128,7 @@ async function holderProgress(engine: Pick<BrainEngine, 'executeRaw'>, sourceId:
last_progress_at: [committedAt, savedAt].filter((value): value is string => !!value).sort().pop() ?? null };
}
-/** A holder that has held the lease, and made no commit or cursor save, for `HOLDER_STALL_MS`. */
+/** A holder that has held the lease, and made no commit, cursor save or hold write, for `HOLDER_STALL_MS`. */
export function holderStalled(holder: DrainHolder | null, now = Date.now()): boolean {
if (!holder?.started_at || !holder.progress) return false;
const since = Math.max(Date.parse(holder.started_at), holder.progress.last_progress_at ? Date.parse(holder.progress.last_progress_at) : 0);
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index 3b4e46c664..f78fdbc739 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -752,6 +752,9 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
foldReport(c.sizeStates);
return null;
}
+ // #7327: a batch that stops (a deadline, a yield, a block) settled the entries its cursor passed; their requested
+ // re-screens are consumed now, so the next pass resumes after them instead of re-screening every one again.
+ await consumeRetry(entries.slice(0, drained.managedCursor?.index ?? 0).map(entry => entry.path));
return drained;
};
/** The pass ended on its stamp; a folded one (sync-pass-fold.ts) saves the round's telemetry beside the obligations it wrote. */
diff --git a/test/persistence-sync-lease.test.ts b/test/persistence-sync-lease.test.ts
index 197daec3f4..4ad6f910c8 100644
--- a/test/persistence-sync-lease.test.ts
+++ b/test/persistence-sync-lease.test.ts
@@ -11,7 +11,8 @@ import { performSync } from '../src/commands/sync/perform.ts';
import { claimWorktree } from '../src/core/persistence/ownership.ts';
import { performManagedSync } from '../src/core/persistence/sync-run.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
-import { DRAIN_LEASE_TTL_MINUTES, HOLDER_STALL_MS, LEASE_BEACON_QUEUE, followStopAt, readDrainHolder, withDrainLease } from '../src/core/persistence/sync-lease.ts';
+import { DRAIN_LEASE_TTL_MINUTES, HOLDER_STALL_MS, LEASE_BEACON_QUEUE, followStopAt, holderStalled, readDrainHolder, withDrainLease } from '../src/core/persistence/sync-lease.ts';
+import { writeGitHold } from '../src/core/persistence/sync-holds.ts';
import { drainNext } from '../src/core/persistence/sync-drain.ts';
import { liveSyncJob } from '../src/core/persistence/sync-movement.ts';
import { installFaultHook } from '../src/core/persistence/fault-points.ts';
@@ -158,6 +159,24 @@ test('a holder that heartbeats but makes no progress for the stall window stops
await holder.release();
}), 120_000);
+test('#7327: a holder writing only holds is progressing; the follower waits instead of stopping drain_stalled', async () => isolated(async engine => {
+ const id = await fixture(engine);
+ const holder = hold(engine, id, 'job');
+ await holder.ready;
+ await engine.executeRaw(`UPDATE gbrain_cycle_locks SET acquired_at=now()-make_interval(secs => $2) WHERE id=$1`, [syncLockId(id), HOLDER_STALL_MS / 1000 + 60]);
+ const [binding] = await engine.executeRaw<{ incarnation: string }>('SELECT source_incarnation::text AS incarnation FROM persistence_source_bindings WHERE source_id=$1', [id]);
+ await engine.transaction(tx => writeGitHold(tx, { source_id: id, incarnation: binding!.incarnation, path: 'linked/a.md', source_path: 'linked/a.md', slug: 'linked/a', page_id: null,
+ code: 'file_unreadable', message: 'Sync did not read linked/a.md: it is a symlink.', upstream_version: null, observed_at: new Date().toISOString(), run_id: 'run-1', mode: 'managed',
+ meta: { reason: 'symlink_dangling', recovery_version: 1 } } as Parameters<typeof writeGitHold>[1]));
+ const seen = await readDrainHolder(engine, id);
+ expect(seen?.progress?.committed).toBe(0);
+ expect(Date.now() - Date.parse(seen!.progress!.last_progress_at!)).toBeLessThan(HOLDER_STALL_MS);
+ expect(holderStalled(seen)).toBe(false);
+ const result = await performSync(engine, plain(id, { followDrainLease: true, deadlineAtMs: Date.now() + 3_000 }));
+ expect(result.drain).toMatchObject({ outcome: 'resumable', stop_reason: 'drain_lease_held' });
+ await holder.release();
+}), 120_000);
+
test('fencing: a pass whose lease was taken over after its TTL admits nothing and advances no checkpoint', async () => isolated(async engine => {
const id = await fixture(engine);
let thief: Awaited<ReturnType<typeof tryAcquireDbLock>> = null;
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index eefa5ac111..9a7acd7e4f 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -429,6 +429,7 @@ test/sync-full-cursor-slices-6349.test.ts
test/sync-full-untracked-import-5459.test.ts
test/sync-group-member-order.test.ts
test/sync-handler-drain-6706.test.ts
+test/sync-holds-only-converge-7327.test.ts
test/sync-import-provenance-disk.test.ts
test/sync-inexact-rename-6729.test.ts
test/sync-landing-gaps.test.ts
diff --git a/test/sync-holds-only-converge-7327.test.ts b/test/sync-holds-only-converge-7327.test.ts
new file mode 100644
index 0000000000..8be863a648
--- /dev/null
+++ b/test/sync-holds-only-converge-7327.test.ts
@@ -0,0 +1,75 @@
+import { expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, symlinkSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { SyncResult } from '../src/commands/sync.ts';
+import { drainManagedSync } from '../src/core/persistence/sync-drain.ts';
+import { readDrainHolder } from '../src/core/persistence/sync-lease.ts';
+import { readGitHoldRetryPaths } from '../src/core/persistence/sync-holds.ts';
+import { retryHeld } from '../src/commands/sources-retry-held.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+// #7327: a managed pass that only re-screens holds. A requested re-screen (`sources retry-held`) of more holds than one
+// job's deadline covers used to restart from zero on every pass: the pass consumed the retry rows only after a whole
+// batch drained, so each deadline stop left all of them due and the next pass re-screened every one again, writing no
+// pass row meanwhile, so a follower judged the holder stalled. Both fail on the base.
+
+const N = 240, STOP_AFTER = 60;
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]', '-c', 'commit.gpgsign=false', ...args],
+ { encoding: 'utf8' }).trim();
+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+const holdCount = async (engine: BrainEngine) => Number((await engine.executeRaw<{ n: number }>(
+ "SELECT count(*)::int AS n FROM op_checkpoints WHERE op='sync-hold' AND fingerprint LIKE 'default:%'"))[0]!.n);
+
+/** One pass that stops once it has screened `stopAfter` entries (a job deadline mid-batch), sampling the holder's progress. */
+async function pass(engine: BrainEngine, stopAfter?: number) {
+ const abort = new AbortController();
+ let screened = 0;
+ const samples: Array<Promise<string | null>> = [];
+ const onProgress = (event: { phase: string }) => {
+ if (event.phase !== 'managed_sync.page_committed') return;
+ screened++;
+ if (screened === 5 || screened === Math.floor((stopAfter ?? N) * 0.8)) samples.push(readDrainHolder(engine, 'default').then(holder => holder?.progress?.last_progress_at ?? null));
+ if (stopAfter && screened >= stopAfter) abort.abort(new Error('job deadline'));
+ };
+ const result: SyncResult = await drainManagedSync(engine, { ...OPTS, signal: abort.signal, onProgress } as Parameters<typeof drainManagedSync>[1], false);
+ return { result, progress: await Promise.all(samples) };
+}
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ test(`#7327 [${backend}]: a re-screen of held symlinks cut short by deadlines resumes, converges with its holds, and shows progress`, () => managedBrain(async ({ engine, root }) => {
+ mkdirSync(join(root, 'linked'));
+ for (let i = 0; i < N; i++) symlinkSync(`/nonexistent-other-checkout/x${i}.md`, join(root, `linked/s${i}.md`));
+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'symlinks');
+ expect((await pass(engine)).result.status).toBe('first_sync');
+ expect(await holdCount(engine)).toBe(N);
+ expect((await pass(engine)).result.status).toBe('up_to_date');
+
+ expect((await retryHeld(engine, 'default')).scheduled).toBe(N);
+ const candidates: number[] = [];
+ let last: SyncResult | null = null;
+ for (let i = 0; i < Math.ceil(N / STOP_AFTER) + 2; i++) {
+ const { result, progress } = await pass(engine, STOP_AFTER);
+ last = result;
+ candidates.push(result.pass!.candidates);
+ if (result.status === 'synced') break;
+ expect(result.pass).toMatchObject({ kind: 'full', outcome: 'resumable', stop_reason: 'timeout' });
+ // The holder's progress moves while it screens holds, so a follower never reads it as stalled.
+ expect(progress).toHaveLength(2);
+ expect(Date.parse(progress[1]!)).toBeGreaterThan(Date.parse(progress[0]!));
+ }
+ expect(candidates[0]).toBe(N);
+ for (let i = 1; i < candidates.length; i++) expect(candidates[i]!).toBeLessThan(candidates[i - 1]!);
+ expect(last?.status).toBe('synced');
+ expect(await readGitHoldRetryPaths(engine, 'default', (await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'"))[0]!.incarnation)).toEqual([]);
+ expect(await holdCount(engine)).toBe(N);
+ expect((await pass(engine)).result.status).toBe('up_to_date');
+ }, { databaseUrl, setup: ({ root }) => {
+ mkdirSync(join(root, 'notes')); git(root, 'init', '-q');
+ writeFileSync(join(root, 'notes/a.md'), '---\ntype: concept\ntitle: A\n---\n\nAn observation about acme-example.\n');
+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'init');
+ } }), 300_000);
+}