Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(sync): fewer startup round trips before the first commit (#5984 G3)
garrytane2656589d90e
diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.tsindex 9a1819a03e..7dd3fe70ad 100644--- a/src/core/persistence/sync-drain.ts+++ b/src/core/persistence/sync-drain.ts@@ -302,7 +302,8 @@ export async function drainManagedSync(engine: BrainEngine, opts: SyncOpts, annoconst { performManagedSync } = await import('./sync-run.ts');const { resolveBulkSettings } = await import('./sync-group.ts');const drainStartedAt = opts.drainStartedAt ?? Date.now();- const bulk = await resolveBulkSettings(engine, opts.noBulk, opts.lanes);+ const { preparationConfigView } = await import('./config-snapshot.ts');+ const bulk = await resolveBulkSettings(await preparationConfigView(engine), opts.noBulk, opts.lanes);// #5984 lanes: one lane run per drain; its groups carry the id and this process claims them out of FIFO order.const laneRun = bulk.enabled && (bulk.lanes ?? 1) > 1 ? randomUUID() : undefined;const { closeLaneRun } = await import('./sync-lanes.ts');diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex b9b32dca0c..f53e1b891b 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -9,6 +9,7 @@ import { currentSourceFilesystemSignal } from '../minions/source-filesystem.ts';import { throwIfAborted } from '../abort-check.ts';import { digest, sha256 } from './digest.ts';import { getWriteRequest, admitWriteInTransaction, foregroundPriority, intentDigest, receiptFor } from './journal.ts';+import { preparationConfigView } from './config-snapshot.ts';import { retryWriteAdmission } from './admission-retry.ts';import { assertPersistenceAccepting, awaitWrite, foregroundWriteCompletions, startPersistenceConsumer, type WriteWait } from './service.ts';import { assertSyncEntryOrigin, discoverManagedSync, resolveManagedSyncContext, readSyncContent, readSyncFile, syncGit, type SyncDiscovery } from './sync-discovery.ts';@@ -661,7 +662,8 @@ async function admitAndSave(engine: BrainEngine, key: string, before: Cursor, nereturn saved.length > 0;});if (!rows) return null;- startPersistenceConsumer(engine, loadConfig() ?? { engine: engine.kind }).wake();+ // The sync loop's own admission: the consumer's next tick claims it directly, leaving its scans to their cadence.+ startPersistenceConsumer(engine, loadConfig() ?? { engine: engine.kind }).wake(true);await faultPoint('sync:mid_checkpoint', { sourceId: next.sourceId });return next;}@@ -768,7 +770,7 @@ async function admitWindowGroup(engine: BrainEngine, cursor: Cursor, key: stringconst [held] = await tx.executeRaw<{ request_id: string | null }>(`SELECT completed_keys->0->'window'->($3::int)->0->>'requestId' AS request_id FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 FOR SHARE`, [OP, key, slot]);return held?.request_id === members[0]!.requestId;}).catch(() => null);- if (rows) startPersistenceConsumer(engine, loadConfig() ?? { engine: engine.kind }).wake();+ if (rows) startPersistenceConsumer(engine, loadConfig() ?? { engine: engine.kind }).wake(true);return rows !== null;}/**@@ -1021,11 +1023,12 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPreturn result(cursor, cursor.from === null ? 'first_sync' : 'synced');}if (cursor?.done) cursor = await retireCompletedCursor(engine, key, cursor, assertActive);+ const startupConfig = await preparationConfigView(engine); // #5984 G3: one config read answers the startup's config readsif (!cursor) {assertActive();phase = 'discovery';discoveryTarget = company?.plan.revision?.commit ?? syncGit(context.gitRoot, ['rev-parse', 'HEAD']).trim();- const discovery = await discoverManagedSync(engine, opts, context);+ const discovery = await discoverManagedSync(startupConfig, opts, context);assertActive();const fresh: Cursor = { ...discovery, authority, processingOptions, syncOptions, runId: discoveryRun, index: 0, counts: { added: 0, modified: 0, deleted: 0, chunks: 0 }, ...(company ? { companyReceiptId: company.receiptId } : {}) };if (opts.dryRun) return dryRun(fresh);@@ -1054,19 +1057,18 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP}assertCursorProcessingOptions(cursor, processingOptions, opts.explicitProcessing);if (opts.dryRun) return dryRun(cursor);- frozenRun.screen = company ? null : await loadSyncScreenRun(engine, cursor.sourceId, cursor.processingOptions ?? processingOptions, authority.writer.remote);+ frozenRun.screen = company ? null : await loadSyncScreenRun(startupConfig, cursor.sourceId, cursor.processingOptions ?? processingOptions, authority.writer.remote);const observedAt = frozenRun.observedAt = cursor.discoveredAt ?? runStartedAt;if (frozenRun.screen && !opts.retryFailed && cursor.pending && !cursor.done) {phase = 'freeze';cursor = await convertBlockedCursor(engine, cursor, key, assertActive, frozenRun);}- const config = loadConfig() ?? { engine: engine.kind };- const analyzeEvery = await importAnalyzeEveryPages(engine);+ const config = loadConfig() ?? { engine: engine.kind }, analyzeEvery = await importAnalyzeEveryPages(engine);let batchStart = performance.now(), batchPages = 0, foregroundWaitStart = 0, foregroundBaseline = 0;let creditedPages = 0, creditStarted = 0, foregroundQueued = false;const sliceStarted = performance.now(), sliceFirstIndex = cursor.index, drainStartedAt = opts.drainStartedAt ?? Date.now();const bulk: BulkPass = { settings: opts.bulk && !company ? opts.bulk : { enabled: false, reason: null, size: 1, maxTxnMs: 0 }, perMemberMs: null, foregroundFirst: await foregroundPriority(engine) };- const waiveBatch = noopWaiversEnabled() && await waiverBatchEnabled(engine);+ const waiveBatch = noopWaiversEnabled() && await waiverBatchEnabled(startupConfig);opts.onProgress?.({ phase: 'managed_sync.start', bankedFiles: cursor.index, total: cursor.entries.length });while (!cursor.done) {assertActive();diff --git a/src/core/persistence/sync-waivers.ts b/src/core/persistence/sync-waivers.tsindex 6e00186386..fec05be6ec 100644--- a/src/core/persistence/sync-waivers.ts+++ b/src/core/persistence/sync-waivers.ts@@ -76,17 +76,22 @@ export async function screenWaiver(engine: BrainEngine, cursor: WaiverCursor, peconst intent = pending.intent;if (intent.kind === 'managed_sync_delete') {if (intent.unownedDeletion || intent.renameFrom || intent.rawHash !== null || typeof intent.path !== 'string' || typeof intent.sourcePath !== 'string') return null;- const snapshot = await engine.readPageSnapshot(pending.slug, { sourceId: cursor.sourceId, includeDeleted: true });+ // The authority check runs beside the snapshot read; its refusal counts only for an entry that would be waived.+ const [snapshot, denied] = await Promise.all([engine.readPageSnapshot(pending.slug, { sourceId: cursor.sourceId, includeDeleted: true }), authorityRefusal(engine, cursor, pending)]);if (!softDeletedAt(snapshot, pending)) return null;- await validateSyncAuthority(engine, cursor.authority, pending.slug);+ if (denied) throw denied.error;return { kind: 'delete', kernel: [] };}- const kernel = await unchangedSyncImport(engine, cursor, pending, config);+ const [kernel, denied] = await Promise.all([unchangedSyncImport(engine, cursor, pending, config), authorityRefusal(engine, cursor, pending)]);if (!kernel) return null;- await validateSyncAuthority(engine, cursor.authority, pending.slug);+ if (denied) throw denied.error;return { kind: 'import', kernel };}+function authorityRefusal(engine: BrainEngine, cursor: WaiverCursor, pending: WaiverEntry): Promise<{ error: unknown } | null> {+ return validateSyncAuthority(engine, cursor.authority, pending.slug).then(() => null, (error: unknown) => ({ error }));+}+/** #5984: `GBRAIN_SYNC_WAIVE_BATCH=0` (or `sync.waive_batch=false`) waives one entry per transaction, as before. */export async function waiverBatchEnabled(engine: BrainEngine, env: NodeJS.ProcessEnv = process.env): Promise<boolean> {const value = env.GBRAIN_SYNC_WAIVE_BATCH ?? await engine.getConfig('sync.waive_batch').catch(() => null);