Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(sync): the managed no-op fast path: an idle tick skips the settles its pin read nothing for (GBRA-133 2b)
garrytanfda2a7e111fc
diff --git a/src/commands/sync/perform.ts b/src/commands/sync/perform.tsindex 27c9542d29..488d1da400 100644--- a/src/commands/sync/perform.ts+++ b/src/commands/sync/perform.ts@@ -22,6 +22,7 @@ import { assertSyncApplicable } from '../../core/sync-applicability.ts';import { noteIdentityDowngrades } from '../../core/sync-identity-downgrades.ts';import { SyncLockBusyError, formatLockBusyMessage, buildPartialResult } from '../../core/sync-lock.ts';import type { SyncOpts, SyncResult } from '../sync.ts';+import type { IdleSkip } from '../../core/persistence/sync-idle-skips.ts';import { runConnectorSync } from './connector.ts';import { performSyncInner } from './incremental.ts';@@ -111,6 +112,8 @@ async function performManagedBranch(engine: BrainEngine, outer: SyncOpts): Promiconst sourceId = outer.sourceId ?? 'default';const { withDrainLease } = await import('../../core/persistence/sync-lease.ts');const lockKey = syncLockId(sourceId);+ // GBRA-133: the settles an idle-clear tick leaves nothing to do (persistence/sync-idle-skips.ts), read inside the lease.+ let skips: ReadonlySet<IdleSkip> = new Set();const work = async (leaseSignal: AbortSignal | undefined): Promise<SyncResult> => {const opts: SyncOpts = leaseSignal ? { ...outer, signal: outer.signal ? AbortSignal.any([outer.signal, leaseSignal]) : leaseSignal } : outer;let result = opts.drain@@ -135,16 +138,18 @@ async function performManagedBranch(engine: BrainEngine, outer: SyncOpts): Promiif (!next.staged) serr(`[sync] staged catch-up reached HEAD after ${stages} stages.`);}printInheritedOptions(result);- if (!opts.dryRun) await recordUpstreamObservation(engine, opts.sourceId ?? 'default', opts.repoPath);- if (!opts.dryRun && ['synced', 'first_sync', 'up_to_date'].includes(result.status)) await clearSettledFailures(engine, opts.sourceId ?? 'default');- if (!opts.dryRun) {- const replayed = await replayImportedRemembers(engine, opts.sourceId ?? 'default');- if (replayed) result = { ...result, replayedRemembers: replayed };- const ghosts = await reportSyncGhosts(engine, opts.sourceId ?? 'default');- if (ghosts) result = { ...result, ghostPages: ghosts };- // #6712 PR 2: holds that turned needs_human (or file_drift content decisions) since the last count, for the soak counters.- await (await import('../../core/persistence/soak-counters.ts')).sweepNeedsHumanHolds(engine, opts.sourceId ?? 'default').catch(() => undefined);- }+ if (opts.dryRun) return result;+ skips = (await import('../../core/persistence/sync-idle-skips.ts')).idleSkips(sourceId);+ // GBRA-133: the ghost-page scan reads only pages and the source's config, so it runs beside the settles before it; its line still prints after theirs.+ const ghostScan = countSyncGhosts(engine, sourceId);+ await recordUpstreamObservation(engine, sourceId, opts.repoPath);+ if (['synced', 'first_sync', 'up_to_date'].includes(result.status) && !skips.has('settled_failures')) await clearSettledFailures(engine, sourceId);+ const replayed = await replayImportedRemembers(engine, sourceId);+ if (replayed) result = { ...result, replayedRemembers: replayed };+ const ghosts = reportSyncGhosts(await ghostScan);+ if (ghosts) result = { ...result, ghostPages: ghosts };+ // #6712 PR 2: holds that turned needs_human (or file_drift content decisions) since the last count, for the soak counters.+ if (!skips.has('needs_human_sweep')) await (await import('../../core/persistence/soak-counters.ts')).sweepNeedsHumanHolds(engine, sourceId).catch(() => undefined);return result;};// A dry run reads and previews only; it never waits for, or keeps out, a drainer.@@ -152,7 +157,8 @@ async function performManagedBranch(engine: BrainEngine, outer: SyncOpts): Promiconst { withSyncTail } = await import('../../core/persistence/sync-tail.ts');try {const { healOriginTwinsAfterManagedSync } = await import('../../core/repair/origin-twins-heal.ts');- return await healOriginTwinsAfterManagedSync(engine, outer, await (await import('../../core/repair/slug-autoheal.ts')).healAfterManagedSync(engine, outer, await withSyncTail(engine, sourceId, await withDrainLease(engine, sourceId, {+ const { healAfterManagedSync } = await import('../../core/repair/slug-autoheal.ts');+ const drained = await withDrainLease(engine, sourceId, {holder: outer.drainHolder ?? { kind: 'cli', id: null }, remote: currentSubmissionAuthority()?.kind === 'remote_generic',...(outer.followDrainLease ? { follow: { signal: outer.signal, deadlineAtMs: outer.deadlineAtMs } } : {}),tty: process.stderr.isTTY === true,@@ -163,7 +169,10 @@ async function performManagedBranch(engine: BrainEngine, outer: SyncOpts): Promi? `[sync] source ${sourceId} is being drained by ${who}; following it until it finishes or this run's budget ends (one drainer per source; it resumes the same cursor). Ctrl-C stops following and leaves it running.`: `[sync] following ${who}: ${done}.`);},- }, work), { signal: outer.signal, deadlineAtMs: outer.deadlineAtMs })));+ }, work);+ const tailed = skips.has('sync_tail') ? drained : await withSyncTail(engine, sourceId, drained, { signal: outer.signal, deadlineAtMs: outer.deadlineAtMs });+ const healed = skips.has('slug_heal') ? tailed : await healAfterManagedSync(engine, outer, tailed);+ return skips.has('origin_heal') ? healed : await healOriginTwinsAfterManagedSync(engine, outer, healed);} catch (err) {if (err instanceof LockUnavailableError && err.lockId === lockKey) throw new SyncLockBusyError(await formatLockBusyMessage(engine, lockKey), lockKey);throw err;@@ -202,8 +211,12 @@ async function replayImportedRemembers(engine: BrainEngine, sourceId: string): P}/** #6712 PR 2 (L4): the source's ghost pages (live pages whose file is gone), counted and named, never deleted by sync. */-async function reportSyncGhosts(engine: BrainEngine, sourceId: string): Promise<SyncResult['ghostPages'] | null> {- const ghosts = await (await import('../../core/persistence/sync-ghosts.ts')).countSyncGhosts(engine, sourceId).catch(() => null);+async function countSyncGhosts(engine: BrainEngine, sourceId: string): Promise<{ sourceId: string; ghosts: SyncResult['ghostPages'] | null }> {+ return { sourceId, ghosts: await (await import('../../core/persistence/sync-ghosts.ts')).countSyncGhosts(engine, sourceId).catch(() => null) };+}++/** Prints the ghost-page line of a scan and returns its report. */+function reportSyncGhosts({ sourceId, ghosts }: Awaited<ReturnType<typeof countSyncGhosts>>): SyncResult['ghostPages'] | null {if (ghosts) serr(`[sync] ${ghosts.count}${ghosts.truncated ? '+' : ''} live page(s) of ${sourceId} have no canonical file (ghost pages${ghosts.samples.length ? `, e.g. ${ghosts.samples.join(', ')}` : ''}); `+ `sync leaves them in place. Preview with ${ghosts.fix.argv!.join(' ')} (read-only), or restore the files and sync.`);return ghosts;diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 57ff04688d..073c113f5e 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -292,7 +292,7 @@ export function gitHoldFingerprint(sourceId: string, incarnation: string, path:return `${sourceId}:${incarnation}:${path}`;}-const summaryFingerprint = (sourceId: string, incarnation: string) => `${sourceId}:${incarnation}`;+export const summaryFingerprint = (sourceId: string, incarnation: string) => `${sourceId}:${incarnation}`;/** Locks the source's summary row (creating it), so hold writes of one source serialize. */async function lockSummary(tx: Exec, sourceId: string, incarnation: string): Promise<number> {diff --git a/src/core/persistence/sync-idle-skips.ts b/src/core/persistence/sync-idle-skips.tsnew file mode 100644index 0000000000..d2e4b9a003--- /dev/null+++ b/src/core/persistence/sync-idle-skips.ts@@ -0,0 +1,55 @@+/**+ * GBRA-133 (PR 2b): the managed no-op fast path. An idle tick (sync-pass-run.ts `stampIdlePass`, the pass kind+ * `syncPassKind` decides) stamps `last_sync_at` and the pass row under the drain lease and changes nothing else, yet the+ * managed branch still ran every settle after it: each one reads the state it would act on, finds nothing and returns.+ * The pin already reads most of that state, so the tick records here what it read, and each settle below is skipped when+ * the fact it acts on is absent. The tick itself, its lease, its pass row and its result are unchanged, and every settle+ * that can still find work on an idle tick (the upstream observation, the remember replay, the ghost-page report) runs.+ *+ * `GBRAIN_SYNC_IDLE_FAST_PATH=0` runs every settle again.+ */+import type { BrainEngine } from '../engine.ts';+import { loadSyncFailures } from '../sync-failure-ledger.ts';+import { GIT_HOLD_SUMMARY_OP, summaryFingerprint } from './sync-holds.ts';+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',+ 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',+ slug_heal: 'no hold of the incarnation, so no frontmatter_slug_conflict hold to heal',+ origin_heal: 'no hold of the incarnation, so no origin_conflict hold to heal',+} as const;+export type IdleSkip = keyof typeof IDLE_SKIPS;++/** What an idle tick's pin read: an owed tail, the incarnation's holds, its hold summary count and any failure row of the source. */+export interface IdleFacts { tail: boolean; holds: number; holdSummary: number; failures: boolean }++/** The facts the pin's other reads do not carry, read in the same round trip as them. */+export async function readIdleFacts(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, incarnation: string): Promise<Pick<IdleFacts, 'holdSummary' | 'failures'>> {+ const [row] = await engine.executeRaw<{ failures: boolean; hold_summary: number | string }>(+ `SELECT EXISTS(SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND completed_keys->0->>'source_id'=$1) AS failures,+ COALESCE((SELECT (completed_keys->0->>'count')::int FROM op_checkpoints WHERE op=$2 AND fingerprint=$3),0) AS hold_summary`,+ [sourceId, GIT_HOLD_SUMMARY_OP, summaryFingerprint(sourceId, incarnation)]);+ return { failures: row?.failures === true, holdSummary: Number(row?.hold_summary ?? 0) };+}++/** Whether an idle tick with these facts leaves the settles in IDLE_SKIPS nothing to do. */+export function idleClear(facts: IdleFacts): boolean {+ return process.env.GBRAIN_SYNC_IDLE_FAST_PATH !== '0' && !facts.tail && facts.holds === 0 && facts.holdSummary === 0 && !facts.failures;+}++/**+ * The settles the last pass under this source's drain lease leaves nothing to do; empty outside the lease or after any+ * pass that was not an idle-clear tick. Read inside the lease: a caller that settles after releasing it keeps the set.+ */+export function idleSkips(sourceId: string): ReadonlySet<IdleSkip> {+ const lease = currentDrainLease(sourceId);+ if (!lease?.idleClear) return new Set();+ const skips = new Set<IdleSkip>(['hold_report', 'needs_human_sweep', 'slug_heal', 'origin_heal']);+ if (lease.tailClear) skips.add('sync_tail');+ if (!loadSyncFailures().some(row => row.source_id === sourceId)) skips.add('settled_failures');+ return skips;+}diff --git a/src/core/persistence/sync-lease.ts b/src/core/persistence/sync-lease.tsindex 97e85401e3..8c5101a0e5 100644--- a/src/core/persistence/sync-lease.ts+++ b/src/core/persistence/sync-lease.ts@@ -65,8 +65,12 @@ export interface DrainHolder { kind: DrainHolderKind | 'unknown'; id: string | nversion: string | null; progress: DrainHolderProgress | null }/** `safe_to_loop` and `retry_after_ms` are the `next` fields of the drain's other owner stops (`owner_wedged_here`). */export interface DrainLeaseHeld { code: typeof SYNC_DRAIN_LEASE_HELD; holder: DrainHolder | null; retry_after_ms: number; safe_to_loop: true; lost?: true; fix: Action }-/** `tailClear`: a pass under this lease read that no tail is owed, and nothing under it owed one since (`withSyncTail` reads none). */-interface DrainLease { lockId: string; sourceId: string; token: string; signal: AbortSignal; tailClear?: boolean }+/**+ * `tailClear`: a pass under this lease read that no tail is owed, and nothing under it owed one since (`withSyncTail` reads none).+ * `idleClear` (GBRA-133): the last pass under this lease was an idle tick whose pin read no hold, no hold summary, no+ * recorded failure of the source and no owed tail, so the settles that only act on those (sync-idle-skips.ts) have nothing to do.+ */+interface DrainLease { lockId: string; sourceId: string; token: string; signal: AbortSignal; tailClear?: boolean; idleClear?: boolean }const leases = new AsyncLocalStorage<ReadonlyMap<string, DrainLease>>();diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex 84c40ab0c7..36fddaf126 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -39,6 +39,7 @@ import { recallWorkingStatCache, rememberWorkingStatCache, SyncTreeReadIncompletimport { syncPassKind } from './sync-classify.ts';import { PASS_BATCH_KEY_PREFIX, readConvergedWatermark, SyncAdmissionPaused, type PassEntry } from './sync-pass-batch.ts';import { assertDrainLease, currentDrainLease } from './sync-lease.ts';+import { idleClear, readIdleFacts } from './sync-idle-skips.ts';import { digest } from './digest.ts';import { readSyncTail } from './sync-tail-record.ts';import { clearGitHold, holdRescreenDue, readGitHoldRetryPaths, readSyncHoldPolicy, readGitSourceHolds, readSyncImportProvenances, syncImportParserFor } from './sync-holds.ts';@@ -346,13 +347,14 @@ async function pinPass(engine: BrainEngine, input: SyncPassInput, lease: NonNullinput.processingOptions.noSchemaPack ? null : loadActivePackForEngine(engine, { remote: false, sourceId }).catch(() => null),readSyncTail(engine, sourceId), readGitHoldRetryPaths(engine, sourceId, incarnation), readGitSourceHolds(engine, { sourceIds: [sourceId] }),passIdleProbe(engine, { sourceId, incarnation, worktreeId: context.binding.worktree_id, requestHwm: null, openAtStamp: null }),- engine.executeRaw(`SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=ANY($1::text[]) LIMIT 1`, [passFailureKeys(sourceId, incarnation)])] as const);+ engine.executeRaw(`SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=ANY($1::text[]) LIMIT 1`, [passFailureKeys(sourceId, incarnation)]),+ readIdleFacts(engine, sourceId, incarnation)] as const);pin.catch(() => undefined);const handover = await retireLegacyCursors(engine, { sourceId, incarnation, remote, assertActive });const empty = (status: SyncResult['status'], reason?: SyncResult['reason']) => emptyPassResult(context, remote, status, reason);if (handover.wait) return { ended: { ...empty('partial', 'writer_pending'), ...(remote ? {} : { retryWait: handover.wait }) } };if (handover.hostRequired) return { ended: empty('blocked_by_failures', 'reconcile_host_required') };- const [prior, admission, configuredWorking, patterns, loadedPack, tail, retry, sourceHolds, rowProbe, failed] = await pin;+ const [prior, admission, configuredWorking, patterns, loadedPack, tail, retry, sourceHolds, rowProbe, failed, idleFacts] = await pin;assertActive();const [headLine, refLine] = syncGit(context.gitRoot, ['rev-parse', 'HEAD', '--abbrev-ref', 'HEAD']).split('\n');const head = headLine!.trim();@@ -411,7 +413,7 @@ async function pinPass(engine: BrainEngine, input: SyncPassInput, lease: NonNullcounts: {}, duration_ms: null, timings_ms: {} } };// The incarnation's legacy markers (§2.7 b1) are owed until a local pass wrote them, not only by its first row.const markersOwed = () => remote ? !prior : !value.obligations.legacy_markers_at;- return { prior, admission, tail, retry, failed, head, mode, selection, configured, selectionFp, parserFp, obligations, passId, optOutEpisode, episode,+ return { prior, admission, tail, retry, failed, holds, idleFacts, head, mode, selection, configured, selectionFp, parserFp, obligations, passId, optOutEpisode, episode,processingOptions, inherited, pack, converged, cacheKey, kindStarted, working, kind, value, markersOwed };}@@ -426,7 +428,7 @@ async function stampIdlePass(engine: BrainEngine, input: SyncPassInput, lease: Nconst { opts, context, authority, assertActive } = input;const { sourceId, incarnation } = context;const remote = authority.writer.remote;- const { value, converged, episode, passId, kindStarted, failed, tail, head, inherited } = pinned;+ const { value, converged, episode, passId, kindStarted, failed, holds, idleFacts, tail, head, inherited } = pinned;const at = new Date().toISOString();value.obligations.converged = { ...converged!, passes_since_full: converged!.passes_since_full + 1 };value.obligations.stuck_since = null;@@ -445,6 +447,7 @@ async function stampIdlePass(engine: BrainEngine, input: SyncPassInput, lease: Nif (failed.length) await clearPassFailures(engine, sourceId, incarnation);// Nor can a tail be owed since the pin read none: the lease's holder reads none after it (sync-run.ts).lease.tailClear = !tail;+ lease.idleClear = idleClear({ tail: !!tail, holds: holds.length, ...idleFacts });return { ...emptyPassResult(context, remote, 'up_to_date'), toCommit: remote ? '' : head, ...(inherited.length ? { inherited_options: inherited } : {}) };}diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 62b826484d..05cd60a5e2 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -67,6 +67,7 @@ import { receiptClass, recordedStop, replaysContentRefusal, resumableStop, stopRimport { 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';@@ -1266,9 +1267,11 @@ 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') return synced;+ if (!state.sourceId || !state.incarnation || synced.status === 'dry_run' || idleSkips(state.sourceId).has('hold_report')) 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/e2e/sync-idle-skips-gbra133-postgres.test.ts b/test/e2e/sync-idle-skips-gbra133-postgres.test.tsnew file mode 100644index 0000000000..0bfceb7090--- /dev/null+++ b/test/e2e/sync-idle-skips-gbra133-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../sync-idle-skips-gbra133.test.ts'));diff --git a/test/sync-idle-skips-gbra133.test.ts b/test/sync-idle-skips-gbra133.test.tsnew file mode 100644index 0000000000..cf21f1d500--- /dev/null+++ b/test/sync-idle-skips-gbra133.test.ts@@ -0,0 +1,161 @@+/**+ * GBRA-133 (PR 2b): the managed no-op fast path. An idle tick under the drain lease records what its pin read; each settle+ * after it that only acts on a hold, a hold summary, a recorded failure, a ledger row or an owed tail is skipped when the+ * pin read none (src/core/persistence/sync-idle-skips.ts). The tick's result, lease and pass row are unchanged. Both+ * backends; test/e2e/sync-idle-skips-gbra133-postgres.test.ts runs the Postgres arm in the E2E lane.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+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 type { SyncOpts, SyncResult } from '../src/commands/sync.ts';+import { performSync } from '../src/commands/sync/perform.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { GIT_HOLD_OP, GIT_HOLD_SUMMARY_OP, summaryFingerprint, writeGitHold } from '../src/core/persistence/sync-holds.ts';+import { SYNC_TAIL_OP, recordPassTail } from '../src/core/persistence/sync-tail-record.ts';+import { MANAGED_SYNC_PASS_OP, passFingerprint } from '../src/core/persistence/sync-pass-row.ts';+import { IDLE_SKIPS, idleClear, type IdleFacts, type IdleSkip } from '../src/core/persistence/sync-idle-skips.ts';+import { clearFailures, recordFailures } from '../src/core/sync-failure-ledger.ts';+import { buildSingleSyncJsonEnvelope } from '../src/core/sync-embed-backfill.ts';+import { freshBrainFactory } from './helpers/persistence-request-fixture.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const cliOpts = (sourceId: string): SyncOpts => ({ sourceId, noPull: true, noEmbed: true, noExtract: true, drain: true, followDrainLease: true, drainHolder: { kind: 'cli', id: null } });++/** The statements (text and parameters) the engine's top-level executeRaw sends while `fn` runs. */+async function recordStatements<T>(engine: BrainEngine, fn: () => Promise<T>): Promise<{ result: T; sent: Array<{ sql: string; params: unknown[] }> }> {+ const sent: Array<{ sql: string; params: unknown[] }> = [];+ const target = engine as unknown as Record<string, (...args: unknown[]) => Promise<unknown>>;+ const original = target.executeRaw!;+ target.executeRaw = function (this: unknown, ...args: unknown[]) {+ sent.push({ sql: String(args[0]).replace(/\s+/g, ' ').trim(), params: (args[1] as unknown[] | undefined) ?? [] });+ return original.apply(this, args);+ };+ try { return { result: await fn(), sent }; }+ finally { delete target.executeRaw; }+}++/** What each settle in IDLE_SKIPS sends when it runs, counted in a run's statements. */+const settles = (sent: Array<{ sql: string; params: unknown[] }>, sourceId: string) => ({+ holdReads: sent.filter(s => s.sql.startsWith('SELECT h.completed_keys->0 AS record FROM op_checkpoints h') && s.params[0] === GIT_HOLD_OP && s.params[2] === null).length,+ holdReport: sent.filter(s => s.sql.includes("COALESCE((completed_keys->0->>'count')::int,0) AS count") && s.params[0] === GIT_HOLD_SUMMARY_OP).length,+ failureRows: sent.filter(s => s.sql.includes("f.op='managed-sync-failure' AND f.completed_keys->0->>'source_id'=$1")).length,+ needsHuman: sent.filter(s => s.sql === 'SELECT incarnation::text AS incarnation FROM sources WHERE id=$1' && s.params[0] === sourceId).length,+ tailReads: sent.filter(s => s.params[0] === SYNC_TAIL_OP && s.params[1] === sourceId && s.sql.startsWith('SELECT completed_keys FROM op_checkpoints')).length,+});++const databaseUrl = process.env.DATABASE_URL;++for (const kind of testBackends()) {+ describe('GBRA-133 managed no-op fast path (' + kind + ')', () => {+ let factory: Awaited<ReturnType<typeof freshBrainFactory>>;+ let home: string;+ beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-idle-skips-'));+ factory = await freshBrainFactory(kind, databaseUrl);+ }, 120_000);+ afterAll(async () => {+ await factory?.dispose();+ if (home) rmSync(home, { recursive: true, force: true });+ });++ /** A managed source of three committed pages, synced until its pass row records an idle tick. */+ async function idleSource(engine: BrainEngine): Promise<{ id: string; incarnation: string }> {+ const id = 'idle-' + randomUUID().slice(0, 12), root = join(home, id);+ mkdirSync(root); git(root, 'init', '-q');+ for (const name of ['alice-example', 'acme-example', 'fund-a']) writeFileSync(join(root, name + '.md'), '---\ntitle: ' + name + '\n---\nA durable observation about ' + name + '.\n');+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'seed');+ await disposePersistenceConsumer(engine);+ 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');+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [id]);+ for (let run = 0; run < 4; run++) {+ const result = await performSync(engine, cliOpts(id));+ const [row] = await engine.executeRaw<{ kind: string | null }>("SELECT completed_keys->0->'telemetry'->>'kind' AS kind FROM op_checkpoints WHERE op=$1 AND fingerprint=$2",+ [MANAGED_SYNC_PASS_OP, passFingerprint(id, incarnation)]);+ if (result.status === 'up_to_date' && row?.kind === 'idle') return { id, incarnation };+ }+ throw new Error('the source never reached an idle tick');+ }++ const check = (name: string, fn: (engine: BrainEngine) => Promise<void>) => test(name, async () => {+ const engine = await factory.fresh();+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined,+ GBRAIN_SYNC_IDLE_FAST_PATH: undefined }, () => fn(engine));+ } finally { await withEnv({ GBRAIN_HOME: home }, () => disposePersistenceConsumer(engine)); }+ }, 180_000);++ check('an idle tick skips the settles its pin read nothing for, and its result and JSON envelope are the full settles\' result', async engine => {+ const { id } = await idleSource(engine);+ const full = await withEnv({ GBRAIN_SYNC_IDLE_FAST_PATH: '0' }, () => recordStatements(engine, () => performSync(engine, cliOpts(id))));+ const fast = await recordStatements(engine, () => performSync(engine, cliOpts(id)));+ expect(settles(full.sent, id)).toEqual({ holdReads: 4, holdReport: 1, failureRows: 1, needsHuman: 1, tailReads: 2 });+ expect(settles(fast.sent, id)).toEqual({ holdReads: 1, holdReport: 0, failureRows: 0, needsHuman: 0, tailReads: 1 });+ expect(fast.sent.length).toBeLessThan(full.sent.length);+ const envelope = (result: SyncResult) => buildSingleSyncJsonEnvelope(id, result);+ expect(fast.result.status).toBe('up_to_date');+ expect(envelope(fast.result)).toEqual(envelope(full.result));+ expect(fast.result).toEqual(full.result);+ });++ /** A state that gives each skipped settle work, and the count that shows the settle ran (IDLE_SKIPS: a new skip needs a case). */+ const blocking: Record<IdleSkip, { seed: (engine: BrainEngine, source: { id: string; incarnation: string }) => Promise<void>; ran: (counts: ReturnType<typeof settles>) => boolean }> = {+ hold_report: {+ seed: (engine, { id, incarnation }) => engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,jsonb_build_array(jsonb_build_object('count',1)))",+ [GIT_HOLD_SUMMARY_OP, summaryFingerprint(id, incarnation)]).then(() => undefined),+ ran: counts => counts.holdReport === 1,+ },+ settled_failures: {+ seed: (engine, { id }) => engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync-failure',$1,jsonb_build_array(jsonb_build_object('source_id',$2::text,'path','fund-a.md')))",+ ['older-key-' + id, id]).then(() => undefined),+ ran: counts => counts.failureRows === 1,+ },+ needs_human_sweep: { seed: (engine, source) => hold(engine, source), ran: counts => counts.needsHuman === 1 },+ sync_tail: { seed: (engine, { id }) => recordPassTail(engine, id, randomUUID(), { changed: 1, extract: false }), ran: counts => counts.tailReads >= 2 },+ slug_heal: { seed: (engine, source) => hold(engine, source), ran: counts => counts.holdReads >= 4 },+ origin_heal: { seed: (engine, source) => hold(engine, source), ran: counts => counts.holdReads >= 4 },+ };+ const hold = (engine: BrainEngine, { id, incarnation }: { id: string; incarnation: string }) => engine.transaction(tx => writeGitHold(tx, {+ source_id: id, incarnation, path: 'acme-example.md', source_path: 'acme-example.md', slug: 'acme-example', page_id: null, code: 'frontmatter_slug_conflict',+ message: 'slug conflict', upstream_version: null, observed_at: new Date().toISOString(), run_id: null, mode: 'managed', meta: {} as never })).then(() => undefined);++ for (const skip of Object.keys(IDLE_SKIPS) as IdleSkip[]) {+ check('the ' + skip + ' settle runs on a tick whose pin read work for it', async engine => {+ const source = await idleSource(engine);+ await blocking[skip].seed(engine, source);+ const { sent } = await recordStatements(engine, () => performSync(engine, cliOpts(source.id)));+ expect(blocking[skip].ran(settles(sent, source.id))).toBe(true);+ });+ }++ check('a ledger row of the source keeps the settled-failures settle on an idle tick', async engine => {+ const { id } = await idleSource(engine);+ recordFailures(id, [{ path: 'fund-a.md', error: 'parse error' }], 'abc1234');+ try {+ const { sent } = await recordStatements(engine, () => performSync(engine, cliOpts(id)));+ expect(settles(sent, id).failureRows).toBe(1);+ } finally { clearFailures(id, ['fund-a.md']); }+ });+ });+}++describe('GBRA-133 idle-clear facts', () => {+ const clear: IdleFacts = { tail: false, holds: 0, holdSummary: 0, failures: false };+ const blocked: Record<keyof IdleFacts, Partial<IdleFacts>> = { tail: { tail: true }, holds: { holds: 1 }, holdSummary: { holdSummary: 2 }, failures: { failures: true } };+ test('every fact the pin reads blocks the skips on its own, and GBRAIN_SYNC_IDLE_FAST_PATH=0 blocks them all', async () => {+ await withEnv({ GBRAIN_SYNC_IDLE_FAST_PATH: undefined }, async () => {+ expect(idleClear(clear)).toBe(true);+ for (const [fact, value] of Object.entries(blocked)) expect([fact, idleClear({ ...clear, ...value })]).toEqual([fact, false]);+ });+ await withEnv({ GBRAIN_SYNC_IDLE_FAST_PATH: '0' }, async () => { expect(idleClear(clear)).toBe(false); });+ });+});