Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): idle fast path keeps sync-run.ts at its ceiling, resets idleClear with tailClear; no-pull test engine in beforeAll; KEY_FILES entry (GBRA-133 2b)

garrytan2b2c36b8ed5b
diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.md
index c7874f2494..c830a80061 100644
--- a/docs/architecture/key-files/managed-sync-bookkeeping.md
+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md
@@ -15,6 +15,7 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The
- `src/core/persistence/sync-cursor-key.ts` — #6712 PR 1: one managed cursor per source. `managedCursorKey` is a digest of the source incarnation and, for a company approval only, the company; writer principal, authority and options no longer select a cursor. `resolveManagedCursor` is the one boundary that picks a run's key and folds older keys in crash-safely under the drain lease: the canonical unfinished cursor wins, else the newest older-key unfinished cursor is adopted and finished in place under its own key; every other older cursor has its queued requests cancelled and is retired through `retireManagedSyncOrphan` (reason `superseded_by_adoption`, fenced by `assertDrainLease`). A cursor with a running, recovering or publishing request or a recovery row is retained and the pass waits for that request (`writer_pending`) before it drains anything. A company brain's finished old-key cursors are kept. Pinned by `test/sync-pass-handover-6712.test.ts` (the live pass's handover of an older binary's cursors) and `test/persistence-sync-cursor-strategy-6696.test.ts`.
- `src/core/persistence/sync-lease.ts` — #6712 PR 1: the drain lease, one managed drainer per source. `withDrainLease` takes the source's sync lock (`syncLockId`) with a 2-minute TTL renewed every 20 s, so a dead holder's lease lapses inside one cron tick; it is reentrant for the holder (nested passes and the in-process lanes reuse it). The holder record (`managed-sync-lease` checkpoint: kind, id, version, start) plus the lock row give `readDrainHolder` (host, pid, heartbeat, `progress`: commits, last commit, last cursor save). A non-job holder also writes a beacon row in the `gbrain-drain-lease` minion queue (application authority, `max_stalled` 0, renewed with the lease, deleted on release) so an older binary's `liveSyncJob` backs off; downgrades are quiescent (stop serve and crons first). `assertDrainLease` is the fence inside every transaction that admits work, settles or holds an entry, folds a cursor in or swaps the cursor. Following callers (the CLI, a CLI run delegated to a serve) wait for a live holder within their budget (`followStopAt`) and take over when it releases; out of budget, or after losing the lease, they return `leaseHeldResult` (`resumable`, `sync_drain_lease_held`, `next.retry_after_ms` 60 s, `safe_to_loop`); a holder with no progress for `HOLDER_STALL_MS` (5 min) returns `leaseStalledResult` (`blocked`, `drain_stalled`, cause `no_progress`, `stall.lease_holder`). Jobs and the cycle get `SyncLockBusyError` and skip. Pinned by `test/persistence-sync-lease.test.ts`.
+- `src/core/persistence/sync-idle-skips.ts` — GBRA-133 (PR 2b): the managed no-op fast path. An idle tick (`stampIdlePass`) records on the drain lease (`idleClear`) whether its pin read no hold of the incarnation, a zero hold summary, no `managed-sync-failure` row of the source and no owed tail (`readIdleFacts` rides the pin's round trip). `idleSkips` names the settles that then have nothing to do (`IDLE_SKIPS`: the hold report in `performManagedPass`; settled failures, which also needs no ledger row of the source; the needs-human sweep, the sync tail and both heals in `perform.ts`). The tick, its lease, its pass row and its result are unchanged; the upstream observation, the remember replay and the ghost-page report still run. `GBRAIN_SYNC_IDLE_FAST_PATH=0` runs every settle. Pinned by `test/sync-idle-skips-gbra133.test.ts` (both backends; Postgres twin in `test/e2e/`).
- `src/core/wire-skew.ts` — #6712 PR 1: the one record of wire-skew windows, each a version floor plus a calendar date (`WIRE_SKEW_WINDOWS.explicitProcessing`: floor 0.60.255.0, accepted and ignored until 2026-11-14). The delegation and admin wires read the field name from here, so removing the window is one edit. #6712 PR 2: each window names the hand-offs that accept it (`wires`) and its shape (`accepts`); `retiredWireFields` / `retiredWireNotice` serve both validators. `CONFIG_ROLLBACK_WINDOWS` records the rollback config keys' windows (honored until a date, from a version floor, with the notice that named them).
- `src/core/sync-flags.ts` — #6712 PR 2: `SYNC_FLAGS`, every `gbrain sync` flag once, with its route (`forward` / `client` / `refuse`) on the serve and PGLite owner hand-offs; `syncFlagsRouted` and `syncWireFields` derive the ladder's, the IPC validator's and the owner lane's allowlists. A flag the argv parsers read must be listed (`test/sync-flag-table-6712.test.ts`). #6712 PR 3 (L7): `managed: true` marks the ten flags `gbrain sync --help` lists under "Managed brains" (`MANAGED_HELP_FLAGS`, table order; `test/sync-managed-help-l7-6712.test.ts` pins the section and runs doctor's cron recipe through the managed flag validator).
- `src/core/sync-config-keys.ts` + `src/commands/doctor/checks/sync-config-keys.ts` — #6712 PR 2: the `sync.*` keys in three kinds: `SYNC_TUNABLE_KEYS`, the rollback keys (windows in `wire-skew.ts`) and `RETIRED_SYNC_KEYS` with their `GBRAIN_SYNC_*` replacements (`retiredSyncSetting` reads one). `effectiveSyncKey` is `config get`'s value-in-effect and origin for a retired or rollback key (its resolvers mirror the readers: `resolveBulkSettings`, `waiverBatchEnabled`, `isFederatedV2Enabled`, the write switches, `planJobDrain`); `syncKeySetNotice` is `config set`'s warning (a retired key writes nothing). Doctor `sync_config_keys` reports a stored retired key as unapplied. Pinned by `test/sync-config-keys-6712.test.ts` and `test/error-registry-retired.test.ts`.
diff --git a/src/core/persistence/sync-idle-skips.ts b/src/core/persistence/sync-idle-skips.ts
index d2e4b9a003..6acf0a9478 100644
--- a/src/core/persistence/sync-idle-skips.ts
+++ b/src/core/persistence/sync-idle-skips.ts
@@ -15,7 +15,7 @@ import { currentDrainLease } from './sync-lease.ts';
/** Each settle an idle-clear tick skips, with why it has nothing to do then. */
export const IDLE_SKIPS = {
- hold_report: 'no hold of the incarnation and a zero hold summary, so buildHoldReport returns no fields',
+ hold_report: 'no hold of the incarnation and a zero hold summary, so buildHoldReport returns no fields (performManagedPass reads lease.idleClear itself)',
settled_failures: 'no managed-sync-failure row of the source and no ledger row of the source, so nothing is cleared, settled or pruned',
needs_human_sweep: 'no hold of the incarnation, so no hold turns needs_human and no soak event is counted',
sync_tail: 'the pin read no owed tail under the lease (tailClear), so withSyncTail reads none',
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index 36fddaf126..1fc21a96ff 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -616,7 +616,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
const remote = authority.writer.remote;
const lease = currentDrainLease(sourceId);
if (!lease) throw new Error(`The live sync pass of ${sourceId} runs only under the source's drain lease.`);
- lease.tailClear = false;
+ lease.tailClear = false; lease.idleClear = false;
const started = Date.now(), startedAt = new Date(started).toISOString();
const pinned = await pinPass(engine, input, lease, started);
if (pinned.ended) return pinned.ended;
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 05cd60a5e2..f5151b8f3b 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -67,7 +67,6 @@ import { receiptClass, recordedStop, replaysContentRefusal, resumableStop, stopR
import { advanceHeld, committedPast, deletionSettled, entryOf, indexOf, promoteWindow, waivedCursor, withHeldKeys, withoutPending } from './sync-cursor-moves.ts';
import { withSyncTail } from './sync-tail.ts';
import { assertDrainLease, currentDrainLease, leaseHeldResult, readDrainHolder, withDrainLease } from './sync-lease.ts';
-import { idleSkips } from './sync-idle-skips.ts';
import { LockStolenError, LockUnavailableError, syncLockId } from '../db-lock.ts';
import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
import { assertPassAdmission, isPassBatchKey, passBatchStep, passedOverBefore, passRequestId, readPassBatch, setPassBatch, type PassEntry } from './sync-pass-batch.ts';
@@ -1267,11 +1266,9 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
}
async function performManagedPass(engine: BrainEngine, opts: SyncOpts, slice?: { maxPages: number; maxMs: number }): Promise<SyncResult> {
const state: HoldRunState = {};
- const lease = currentDrainLease(opts.sourceId ?? 'default');
- if (lease) lease.idleClear = false;
// #6729: every managed entry point (CLI, drain, owner slice, worktree refresh) records the renames whose identity it did not keep.
const synced = await noteIdentityDowngrades(engine, opts.sourceId ?? 'default', await runManagedSync(engine, opts, slice, state), serr);
- if (!state.sourceId || !state.incarnation || synced.status === 'dry_run' || idleSkips(state.sourceId).has('hold_report')) return synced;
+ if (!state.sourceId || !state.incarnation || synced.status === 'dry_run' || currentDrainLease(state.sourceId)?.idleClear) return synced;
const cursor = state.cursor?.() ?? null;
try {
const report = await buildHoldReport(engine, { sourceId: state.sourceId, incarnation: state.incarnation, runId: cursor?.runId ?? '', remote: state.remote === true,
diff --git a/test/sync-no-pull-estimate-gbra133.test.ts b/test/sync-no-pull-estimate-gbra133.test.ts
index 35a918a3c0..362f37b7a1 100644
--- a/test/sync-no-pull-estimate-gbra133.test.ts
+++ b/test/sync-no-pull-estimate-gbra133.test.ts
@@ -1,9 +1,9 @@
/**
- * GBRA-133 PR 2b (lane D's run.ts hunk): \`gbrain sync --no-pull\` syncs local HEAD, so its inline cost estimate prices
+ * GBRA-133 PR 2b (lane D's run.ts hunk): `gbrain sync --no-pull` syncs local HEAD, so its inline cost estimate prices
* local HEAD and runs no git fetch. The control (the same command without --no-pull) fetches, so the check is not
* vacuous. The sync is stopped right after the cost gate, before it would pull.
*/
-import { afterAll, expect, spyOn, test } from 'bun:test';
+import { afterAll, beforeAll, expect, spyOn, test } from 'bun:test';
import { execFileSync } from 'node:child_process';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
@@ -17,7 +17,9 @@ import { withEnv } from './helpers/with-env.ts';
import { chunkerStamp } from '../src/core/chunkers/code.ts';
const home = mkdtempSync(join(tmpdir(), 'gbrain-no-pull-estimate-'));
-afterAll(() => { resetGateway(); rmSync(home, { recursive: true, force: true }); });
+let engine: PGLiteEngine;
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);
+afterAll(async () => { resetGateway(); await engine?.disconnect(); rmSync(home, { recursive: true, force: true }); });
const sh = (cwd: string, ...args: string[]) => execFileSync('git', ['-c', 'user.name=Example', '-c', '[email protected]', ...args], { cwd, encoding: 'utf8' }).trim();
const page = (name: string) => '---\ntitle: ' + name + '\n---\nA note about acme-example named ' + name + '.\n';
@@ -30,8 +32,6 @@ test('gbrain sync --no-pull runs no git fetch during the cost estimate; without
const base = sh(local, 'rev-parse', 'HEAD');
writeFileSync(join(writer, 'b.md'), page('b')); sh(writer, 'add', '-A'); sh(writer, 'commit', '-qm', 'b'); sh(writer, 'push', '-q', 'origin', 'HEAD:main');
- const engine = new PGLiteEngine();
- await engine.connect({}); await engine.initSchema();
await engine.executeRaw("INSERT INTO sources(id,name,local_path,config,last_commit,chunker_version) VALUES('estimate','estimate',$1,'{}',$2,$3)", [local, base, chunkerStamp()]);
const fetches = spyOn(gitRemote, 'fetchRemote');
const real = embedBackfill.resolveSingleSyncEmbedPlan;
@@ -55,6 +55,5 @@ test('gbrain sync --no-pull runs no git fetch during the cost estimate; without
});
} finally {
fetches.mockRestore(); gate.mockRestore();
- await engine.disconnect();
}
}, 60_000);