Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
sync groups: one budget resolver (first group of 2, 5 s lane budget, 2 s while foreground writes, explicit max only lowers) and lane apply time per member (#5984)
garrytan672e5136a031
diff --git a/src/core/persistence/sync-group.ts b/src/core/persistence/sync-group.tsindex d6ea24a30e..f36c1649fd 100644--- a/src/core/persistence/sync-group.ts+++ b/src/core/persistence/sync-group.ts@@ -24,6 +24,8 @@ import type { SyncAuthority } from './sync-authority.ts';/** What sets a drain's lane ceiling: lanes off, the configured maximum, or the connection pool. */export type LanesCap = 'disabled' | 'maximum' | 'pool';export interface BulkSettings { enabled: boolean; reason: string | null; size: number; maxTxnMs: number;+ /** Whether `sync.bulk_max_txn_ms` (or its env) was set; an explicit budget only ever lowers the group budget. */+ maxTxnExplicit?: boolean;/** #5984 lanes: groups published at once (1 = one at a time), and why it is lower than asked when it is. */lanes?: number; lanesMax?: number; lanesReason?: string | null; lanesCap?: LanesCap;/** The drain's lane run (set by the drain when lanes > 1); lane groups carry it as `intent.lane`. */@@ -40,11 +42,12 @@ async function resolveGrouping(engine: BrainEngine, noBulk: boolean | undefined)const configured = await engine.getConfig('sync.bulk').catch(() => null);const size = await whole(engine, 'GBRAIN_SYNC_BULK_SIZE', 'sync.bulk_size', 16, 1, 64);const maxTxnMs = await whole(engine, 'GBRAIN_SYNC_BULK_MAX_TXN_MS', 'sync.bulk_max_txn_ms', 15_000, 100, 300_000);+ const maxTxnExplicit = !!process.env.GBRAIN_SYNC_BULK_MAX_TXN_MS || await engine.getConfig('sync.bulk_max_txn_ms').then(v => v != null).catch(() => false);const reason = noBulk ? 'disabled by --no-bulk' : env === '0' || env === 'false' ? 'disabled by GBRAIN_SYNC_BULK=0': env === undefined || env === '' ? (configured === 'false' || configured === '0' ? 'disabled by config sync.bulk=false' : null) : null;- if (reason) return { enabled: false, reason, size, maxTxnMs };- if (engine.kind !== 'postgres') return { enabled: false, reason: 'PGLite publishes without network round trips; bulk applies to Postgres', size, maxTxnMs };- return { enabled: true, reason: null, size, maxTxnMs };+ if (reason) return { enabled: false, reason, size, maxTxnMs, maxTxnExplicit };+ if (engine.kind !== 'postgres') return { enabled: false, reason: 'PGLite publishes without network round trips; bulk applies to Postgres', size, maxTxnMs, maxTxnExplicit };+ return { enabled: true, reason: null, size, maxTxnMs, maxTxnExplicit };}/** The most groups a drain publishes at once: what `--lanes`, `sync.lanes` and `GBRAIN_SYNC_LANES` accept, and their default. */export const MAX_SYNC_LANES = 16;@@ -79,16 +82,26 @@ export function groupableIntent(intent: SyncIntent): boolean {return (intent.kind === 'managed_sync_import' || intent.kind === 'managed_sync_delete') && !intent.renameFrom && !intent.companyApproval;}+/** Apply budgets for a lane group: normally, and while a foreground write on the worktree is queued or just committed. */+export const LANE_GROUP_BUDGET_MS = 5_000;+export const FOREGROUND_GROUP_BUDGET_MS = 2_000;/**- * Adaptive group size: as many members as fit the time budget at the last- * observed per-member time from admission to commit, within the configured- * maximum. Foreground writes queued behind a group wait at most about this- * budget (sync.bulk_max_txn_ms); while a foreground write is queued on the- * worktree, no group forms, so it is served before the next page (ENG-A5).+ * Adaptive group size: as many members as fit the time budget at the last observed time per member, within+ * the configured maximum. The budget is, in order: the first group of a drain is small (2 pages) so its first+ * commit lands early; with lanes a group gets `LANE_GROUP_BUDGET_MS` of apply time (`FOREGROUND_GROUP_BUDGET_MS`+ * while a foreground write is queued or just committed), without lanes `sync.bulk_max_txn_ms`; an explicit+ * `sync.bulk_max_txn_ms` only ever lowers it. With lanes the time per member is the lanes' measured apply time+ * (transaction begin to the commit-turn wait), which does not grow with how long a group waited in the window;+ * without a measurement a group takes the configured size. Foreground writes queued behind a group wait at+ * most about this budget (ENG-A5).*/-export function nextGroupSize(settings: BulkSettings, perMemberMs: number | null): number {- if (perMemberMs === null || perMemberMs <= 0) return Math.min(4, settings.size);- return Math.max(1, Math.min(settings.size, Math.floor(settings.maxTxnMs / perMemberMs)));+export function nextGroupSize(settings: BulkSettings, perMemberMs: number | null, opts: { first?: boolean; foreground?: boolean } = {}): number {+ if (opts.first) return Math.min(2, settings.size);+ const lanes = (settings.lanes ?? 1) > 1;+ let budget = lanes ? opts.foreground ? FOREGROUND_GROUP_BUDGET_MS : LANE_GROUP_BUDGET_MS : settings.maxTxnMs;+ if (lanes && settings.maxTxnExplicit) budget = Math.min(budget, settings.maxTxnMs);+ if (perMemberMs === null || perMemberMs <= 0) return lanes ? settings.size : Math.min(4, settings.size);+ return Math.max(1, Math.min(settings.size, Math.floor(budget / perMemberMs)));}/**diff --git a/src/core/persistence/sync-lanes.ts b/src/core/persistence/sync-lanes.tsindex a10c6b446a..64d218af48 100644--- a/src/core/persistence/sync-lanes.ts+++ b/src/core/persistence/sync-lanes.ts@@ -29,7 +29,9 @@ export interface LaneState extends LanePolicy { coordinationPath: string | null;tasks: number; closing: boolean; timing: LaneTiming }/** Lane group transactions of a run in this process: how many are open, and where their time went. */interface LaneTiming { open: number; since: number; openArea: number; activeMs: number;- applyMs: number; appliedMembers: number; turnWaitMs: number; transactionMs: number }+ applyMs: number; appliedMembers: number; turnWaitMs: number; transactionMs: number;+ /** Apply time per member of the recent lane groups (each new group weighs half), for group sizing. */+ recentPerMember: number | null }/*** #5984 lanes: what a drain's lanes did, for its report. `busy` is the mean number of lane transactions open* while at least one was; `applyMsPerPage` the time from a group's transaction begin to its commit-turn wait,@@ -42,7 +44,7 @@ let claiming = 0;/** The drain's lane policy for a worktree; replaces any earlier one. */export function openLanes(worktreeId: string, run: string, lanes: number, coordinationPath: string | null): void {policies.set(worktreeId, { run, asked: lanes, effective: lanes, stepDown: null, overlapped: 0, fallbacks: 0, coordinationPath, claimed: new Set(), begun: new Set(), tasks: 0, closing: false,- timing: { open: 0, since: Date.now(), openArea: 0, activeMs: 0, applyMs: 0, appliedMembers: 0, turnWaitMs: 0, transactionMs: 0 } });+ timing: { open: 0, since: Date.now(), openArea: 0, activeMs: 0, applyMs: 0, appliedMembers: 0, turnWaitMs: 0, transactionMs: 0, recentPerMember: null } });}/*** Ends a drain's lane run on every worktree it opened: no new lane claims, then waits (up to `maxMs`) for the@@ -58,7 +60,7 @@ export async function closeLaneRun(run: string, maxMs = 90_000): Promise<LaneStareturn open.length ? laneStats(open.map(([, state]) => state.timing)) : null;}function laneStats(timings: LaneTiming[]): LaneStats {- const sum = (key: keyof LaneTiming) => timings.reduce((total, timing) => total + timing[key], 0);+ const sum = (key: Exclude<keyof LaneTiming, 'recentPerMember'>) => timings.reduce((total, timing) => total + timing[key], 0);const round = (value: number, places: number) => Math.round(value * 10 ** places) / 10 ** places;const active = sum('activeMs'), members = sum('appliedMembers'), transactions = sum('transactionMs');return { busy: active > 0 ? round(sum('openArea') / active, 2) : null, applyMsPerPage: members > 0 ? Math.round(sum('applyMs') / members) : null,@@ -90,6 +92,8 @@ export function laneApplyBegin(state: LaneState): { turn(): void; turned(): voidif (turnAt === null) return;timing.applyMs += turnAt - began;timing.appliedMembers += members;+ const perMember = (turnAt - began) / Math.max(1, members);+ timing.recentPerMember = timing.recentPerMember === null ? perMember : (timing.recentPerMember + perMember) / 2;timing.turnWaitMs += waited || Date.now() - turnAt;},};@@ -114,6 +118,10 @@ export function lanePolicy(worktreeId: string): LanePolicy | null {const state = policies.get(worktreeId);return state ? { run: state.run, asked: state.asked, effective: state.effective, stepDown: state.stepDown, overlapped: state.overlapped, fallbacks: state.fallbacks } : null;}+/** The recent apply time per member of a worktree's open lane run in this process; null before a lane group reached its turn. */+export function laneApplyMsPerMember(worktreeId: string): number | null {+ return policies.get(worktreeId)?.timing.recentPerMember ?? null;+}/** The open lane runs and how many lanes each may run now (0 while the worktree's lease drains for an exclusive writer). */export function laneRoots(): Array<{ worktreeId: string; run: string; capacity: number }> {return [...policies].map(([worktreeId, state]) => ({ worktreeId, run: state.run,diff --git a/test/managed-sync-bulk.test.ts b/test/managed-sync-bulk.test.tsindex 579788f368..4c8ee0ed47 100644--- a/test/managed-sync-bulk.test.ts+++ b/test/managed-sync-bulk.test.ts@@ -52,6 +52,13 @@ test('group sizing follows the transaction budget and bulk settings follow flagexpect(nextGroupSize(settings, 2000)).toBe(5);expect(nextGroupSize(settings, 100)).toBe(16);expect(nextGroupSize(settings, 60_000)).toBe(1);+ const laned = { ...settings, maxTxnMs: 15_000, lanes: 6 };+ expect(nextGroupSize(laned, 1400, { first: true })).toBe(2);+ expect(nextGroupSize(laned, null)).toBe(16);+ expect(nextGroupSize(laned, 400)).toBe(12);+ expect(nextGroupSize(laned, 400, { foreground: true })).toBe(5);+ expect(nextGroupSize({ ...laned, maxTxnMs: 1_000, maxTxnExplicit: true }, 400)).toBe(2);+ expect(nextGroupSize({ ...laned, maxTxnMs: 60_000, maxTxnExplicit: true }, 400)).toBe(12);if (!engine) return;expect(await resolveBulkSettings(engine, true)).toMatchObject({ enabled: false, reason: 'disabled by --no-bulk' });await withEnv({ GBRAIN_SYNC_BULK: '0' }, async () => expect(await resolveBulkSettings(engine!, false)).toMatchObject({ enabled: false, reason: 'disabled by GBRAIN_SYNC_BULK=0' }));