Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(sync): lane policy, shared worktree lease, lanes setting (#5984 Phase 2)
garrytanf9ab32127473
diff --git a/src/core/persistence/ownership.ts b/src/core/persistence/ownership.tsindex 966f42e56b..8092a77876 100644--- a/src/core/persistence/ownership.ts+++ b/src/core/persistence/ownership.ts@@ -12,6 +12,7 @@ import { digest, sha256 } from './digest.ts';import { localHostId, persistenceHome } from './identity.ts';import type { SqlEngine, WriteRequest } from './model.ts';import { acquireNativeLock, tryAcquireNativeLock, type NativeLockHandle } from './native-lock.ts';+import { acquireShared, yieldLease } from './worktree-lease.ts';import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots } from './filesystem-guard.ts';import { assertPhysicalRoot, claimPhysicalRoot, isPhysicalRootMetadata, preparePhysicalRootTransfer, readPhysicalRootReservation, restampPhysicalRoot } from './physical-root.ts';import { readPhysicalRootStamp } from './physical-root-record.ts';@@ -131,6 +132,17 @@ export async function claimWorktree(engine: BrainEngine, sourceId: string, path:*/export async function acquireWorktree(binding: WorktreeBinding, waitMs = 0, signal?: AbortSignal, engine?: BrainEngine): Promise<NativeLockHandle | null> {if (!binding.local_path || !binding.coordination_path) return null;+ // #5984 lanes: an exclusive writer drains this process's lane lease first; while lanes still hold it the worktree is busy.+ if (!await yieldLease(binding.coordination_path, waitMs, signal)) return null;+ return lockWorktree(binding, waitMs, signal, engine);+}+/** #5984 lanes: database-only lane publications share one native lock in this process (worktree-lease.ts). */+export async function acquireWorktreeShared(binding: WorktreeBinding, engine: BrainEngine): Promise<NativeLockHandle | null> {+ if (!binding.local_path || !binding.coordination_path) return null;+ return acquireShared(binding.coordination_path, () => lockWorktree(binding, 0, undefined, engine));+}+async function lockWorktree(binding: WorktreeBinding, waitMs: number, signal: AbortSignal | undefined, engine: BrainEngine | undefined): Promise<NativeLockHandle | null> {+ if (!binding.coordination_path || !binding.local_path) return null;const lock = await (waitMs > 0 ? acquireNativeLock(binding.coordination_path, { timeoutMs: waitMs, signal }): tryAcquireNativeLock(binding.coordination_path));if (!lock) return null;diff --git a/src/core/persistence/sync-group.ts b/src/core/persistence/sync-group.tsindex d3b5a8963e..5986ff1ce2 100644--- a/src/core/persistence/sync-group.ts+++ b/src/core/persistence/sync-group.ts@@ -13,6 +13,7 @@import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import { OperationError } from '../ops/contract.ts';+import { poolLongHoldCapacity, type BudgetPool } from '../pool-budget.ts';import { admitWriteGroupInTransaction } from './journal.ts';import { retryWriteAdmission } from './admission-retry.ts';import { wouldWaiveEntry, type WaiverCursor, type WaiverEntry } from './sync-waivers.ts';@@ -20,11 +21,17 @@ import type { WriteRequest } from './model.ts';import type { SyncIntent } from './sync-prepare.ts';import type { SyncAuthority } from './sync-authority.ts';-export interface BulkSettings { enabled: boolean; reason: string | null; size: number; maxTxnMs: number }+export interface BulkSettings { enabled: boolean; reason: string | null; size: number; maxTxnMs: number;+ /** #5984 lanes: groups published at once (1 = one at a time), and why it is lower than asked when it is. */+ lanes?: number; lanesReason?: string | null }export interface BulkReport { enabled: boolean; reason: string | null; groups: number; grouped_pages: number; largest_group: number }/** Flag > env > config > default (on), as for the other sync knobs (DX-A8). */-export async function resolveBulkSettings(engine: BrainEngine, noBulk: boolean | undefined): Promise<BulkSettings> {+export async function resolveBulkSettings(engine: BrainEngine, noBulk: boolean | undefined, lanesFlag?: number): Promise<BulkSettings> {+ const bulk = await resolveGrouping(engine, noBulk);+ return { ...bulk, ...await resolveLanes(engine, bulk, lanesFlag) };+}+async function resolveGrouping(engine: BrainEngine, noBulk: boolean | undefined): Promise<BulkSettings> {const env = process.env.GBRAIN_SYNC_BULK;const configured = await engine.getConfig('sync.bulk').catch(() => null);const size = await whole(engine, 'GBRAIN_SYNC_BULK_SIZE', 'sync.bulk_size', 16, 1, 64);@@ -35,6 +42,22 @@ export async function resolveBulkSettings(engine: BrainEngine, noBulk: boolean |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 };}+/**+ * #5984 lanes: `--lanes N` / `--no-lanes` > `GBRAIN_SYNC_LANES` > `sync.lanes` > 4, then clamped to what the+ * connection pool can hold at once (its long-hold capacity minus 3 for the sync loop, one foreground write and+ * the consumer's control work). Lanes need bulk groups.+ */+async function resolveLanes(engine: BrainEngine, bulk: BulkSettings, flag: number | undefined): Promise<{ lanes: number; lanesReason: string | null }> {+ if (!bulk.enabled) return { lanes: 1, lanesReason: `bulk groups are off (${bulk.reason})` };+ if (flag !== undefined && (!Number.isInteger(flag) || flag < 1 || flag > 8)) throw new OperationError('invalid_params', `--lanes must be a whole number from 1 to 8; got ${flag}.`,+ 'Pass --lanes 4 (the default), or --no-lanes to publish one group at a time.');+ const asked = flag ?? await whole(engine, 'GBRAIN_SYNC_LANES', 'sync.lanes', 4, 1, 8);+ if (asked === 1) return { lanes: 1, lanesReason: flag === 1 ? 'disabled by --no-lanes' : 'disabled by sync.lanes=1 (or GBRAIN_SYNC_LANES=1)' };+ const pool = (engine as BrainEngine & { sql?: BudgetPool }).sql;+ const capacity = pool ? poolLongHoldCapacity(pool) - 3 : 1;+ if (capacity >= asked) return { lanes: asked, lanesReason: null };+ return { lanes: Math.max(1, capacity), lanesReason: `the connection pool holds ${capacity + 3} long transactions; raise GBRAIN_POOL_SIZE for more lanes` };+}async function whole(engine: BrainEngine, env: string, key: string, fallback: number, min: number, max: number): Promise<number> {const raw = process.env[env] ? Number(process.env[env]) : await engine.getConfig(key).then(v => v == null ? undefined : Number(v)).catch(() => undefined);if (raw === undefined) return fallback;diff --git a/src/core/persistence/sync-lanes.ts b/src/core/persistence/sync-lanes.tsnew file mode 100644index 0000000000..1e1e205ea8--- /dev/null+++ b/src/core/persistence/sync-lanes.ts@@ -0,0 +1,104 @@+/**+ * #5984 lanes: several bulk groups of one draining managed sync publish at once.+ *+ * The drain opens a lane policy for its worktree (`openLanes`): the run's id,+ * the number of lanes it asked for and the number still in effect. While it+ * is open, this process's consumer claims the head of the next admitted group+ * of that run even when earlier groups of the same run are still publishing+ * (`claimNextLaneHead` in journal.ts), up to the effective number of lanes.+ * Lane publications share the worktree's native lock (worktree-lease.ts) and+ * begin their transactions in manifest order. They apply concurrently but+ * commit in manifest order: before a lane locks the counters it waits until+ * the group before it (its members' `intent.after`) has committed. A failed+ * earlier group cancels the later ones; a lock or statement timeout lowers+ * the effective number of lanes for the rest of the drain (step-down).+ * Other processes, and this one once the policy closes, claim lane rows+ * under the ordinary per-worktree FIFO.+ */+import type { BrainEngine } from '../engine.ts';+import type { WriteRequest } from './model.ts';+import { leaseDraining, leaseWounded } from './worktree-lease.ts';++export interface LanePolicy { run: string; asked: number; effective: number; stepDown: string | null }+interface LaneState extends LanePolicy { coordinationPath: string | null; claimed: Set<string>; begun: Set<string> }+const policies = new Map<string, LaneState>();++/** 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, coordinationPath, claimed: new Set(), begun: new Set() });+}+export function closeLanes(worktreeId: string, run: string): void {+ if (policies.get(worktreeId)?.run === run) policies.delete(worktreeId);+}+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 } : 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,+ capacity: state.coordinationPath && leaseDraining(state.coordinationPath) ? 0 : state.effective }));+}+/** The lane run a request belongs to, when its worktree's lane policy is open in this process. */+export function laneOf(row: Pick<WriteRequest, 'worktree_id' | 'intent'>): LaneState | null {+ const lane = (row.intent as Record<string, unknown> | null | undefined)?.lane;+ const state = row.worktree_id ? policies.get(row.worktree_id) : undefined;+ return typeof lane === 'string' && state?.run === lane && state.effective > 1 ? state : null;+}+/** A lane lock or statement timeout that survived its retry: one lane fewer for the rest of the drain. */+export function stepDownLanes(worktreeId: string, reason: string): void {+ const state = policies.get(worktreeId);+ if (!state || state.effective <= 1) return;+ state.effective--;+ state.stepDown = reason;+}++/** The last member of a group is what the next group's `after` names. */+function groupKey(rows: WriteRequest[]): string { return rows.at(-1)!.request_id; }+export function laneClaimed(state: LaneState, rows: WriteRequest[]): void { state.claimed.add(groupKey(rows)); }+export function laneFinished(state: LaneState, rows: WriteRequest[]): void { state.claimed.delete(groupKey(rows)); state.begun.delete(groupKey(rows)); }++export class LaneAbort extends Error {+ constructor(readonly reason: 'predecessor_failed' | 'wounded' | 'order_timeout') { super(`lane ${reason}`); }+}+const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));++/**+ * Lane transactions begin in manifest order: a group whose predecessor this+ * process claimed but has not begun waits for it, so the oldest unfinished+ * group always holds a connection first (transaction-mode poolers included).+ */+export async function awaitLaneBegin(state: LaneState, rows: WriteRequest[], maxMs = 10_000): Promise<void> {+ const after = predecessorOf(rows);+ const started = Date.now();+ while (after && state.claimed.has(after) && !state.begun.has(after) && Date.now() - started < maxMs) await sleep(20);+ state.begun.add(groupKey(rows));+}++/**+ * Inside the group transaction, after its members are applied and before the+ * counters are locked: waits until the previous group committed. Each poll is+ * a fresh read of the predecessor's receipt. Throws LaneAbort when the+ * predecessor ended without committing, when the worktree's lease drains for+ * an exclusive writer, or after `maxMs`.+ */+export async function awaitLaneTurn(tx: BrainEngine, state: LaneState, rows: WriteRequest[], maxMs = 60_000): Promise<void> {+ const after = predecessorOf(rows);+ if (!after) return;+ const head = rows[0]!;+ const started = Date.now();+ for (let poll = 0; ; poll++) {+ const [prior] = await tx.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=$3::uuid',+ [head.principal_kind, head.principal_id, after]);+ if (prior?.state === 'committed') return;+ if (!prior || ['failed', 'conflict', 'cancelled'].includes(prior.state)) throw new LaneAbort('predecessor_failed');+ if (state.coordinationPath && leaseWounded(state.coordinationPath)) throw new LaneAbort('wounded');+ if (Date.now() - started >= maxMs) throw new LaneAbort('order_timeout');+ await sleep(Math.min(200, 25 * (poll + 1)));+ }+}++function predecessorOf(rows: WriteRequest[]): string | null {+ const after = (rows[0]?.intent as Record<string, unknown> | null | undefined)?.after;+ return typeof after === 'string' ? after : null;+}diff --git a/src/core/persistence/worktree-lease.ts b/src/core/persistence/worktree-lease.tsnew file mode 100644index 0000000000..9ccf85dfe1--- /dev/null+++ b/src/core/persistence/worktree-lease.ts@@ -0,0 +1,96 @@+/**+ * #5984 lanes: one process's shared hold on a worktree's native lock.+ *+ * The native lock (`native-lock.ts`) is exclusive per open handle, so two+ * group publications of one worktree in the same process cannot both hold+ * it. Parallel sync lanes share one native lock through a counted lease:+ * the first lane takes the lock, later lanes join, and the last one to+ * leave releases it. Cross-process exclusion is unchanged.+ *+ * Every other worktree writer (file publications, effects, recovery,+ * refresh, transfer) keeps taking the lock exclusively through+ * `acquireWorktree`. When such a writer finds a live lease in this process,+ * it marks the lease draining and wounded: no lane joins it any more, lanes+ * waiting to commit roll back and release their claims, and the native lock+ * is released as soon as the running lanes finish, so the exclusive writer+ * gets it on its next attempt. A lease also drains (without wounding) after+ * `LEASE_TURN_MS` of continuous holding, so writers in other processes,+ * which cannot mark it, still get a turn.+ */+import type { NativeLockHandle } from './native-lock.ts';++/** A lease stops admitting lanes after this long, so other processes get the native lock between turns. */+export const LEASE_TURN_MS = 30_000;++interface Lease { lock: NativeLockHandle; holders: number; since: number; draining: boolean; wounded: boolean; ended: Promise<void>; end: () => void }+const leases = new Map<string, Lease>();++/** Whether lanes of this worktree should stop: an exclusive writer waits, or the lease used up its turn. */+export function leaseDraining(path: string): boolean {+ const lease = leases.get(path);+ if (!lease) return false;+ if (!lease.draining && Date.now() - lease.since >= LEASE_TURN_MS) lease.draining = true;+ return lease.draining;+}++/** Whether an exclusive writer in this process waits for the lease: lanes still waiting to commit roll back. */+export function leaseWounded(path: string): boolean {+ return leases.get(path)?.wounded === true;+}++/**+ * Joins this process's lease on `path`, or takes the native lock through+ * `acquire` when there is none. Null when the lock is busy elsewhere or the+ * lease is draining; the caller releases its claim and retries later.+ */+export async function acquireShared(path: string, acquire: () => Promise<NativeLockHandle | null>): Promise<NativeLockHandle | null> {+ const live = leases.get(path);+ if (live) {+ if (live.lock.released || leaseDraining(path)) return null;+ live.holders++;+ return share(path, live);+ }+ const lock = await acquire();+ if (!lock) return null;+ // Another lane may have created the lease while this one waited for the lock.+ const raced = leases.get(path);+ if (raced) { await lock.release(); return acquireShared(path, acquire); }+ let end!: () => void;+ const ended = new Promise<void>(resolve => { end = resolve; });+ const lease: Lease = { lock, holders: 1, since: Date.now(), draining: false, wounded: false, ended, end };+ leases.set(path, lease);+ return share(path, lease);+}++function share(path: string, lease: Lease): NativeLockHandle {+ let released = false;+ return {+ get released() { return released || lease.lock.released; },+ async release() {+ if (released) return;+ released = true;+ if (--lease.holders > 0) return;+ leases.delete(path);+ try { await lease.lock.release(); } finally { lease.end(); }+ },+ };+}++/**+ * Called by an exclusive writer before it takes the native lock. Without a+ * lease in this process it returns at once. With one, it marks the lease+ * draining and waits up to `waitMs` for the lanes to finish; false means the+ * lease is still held and the writer should treat the worktree as busy.+ */+export async function yieldLease(path: string, waitMs: number, signal?: AbortSignal): Promise<boolean> {+ const lease = leases.get(path);+ if (!lease) return true;+ lease.draining = true;+ lease.wounded = true;+ if (waitMs <= 0) return false;+ let timer: ReturnType<typeof setTimeout> | undefined;+ const timeout = new Promise<false>(resolve => { timer = setTimeout(() => resolve(false), waitMs); });+ const aborted = new Promise<false>(resolve => signal?.addEventListener('abort', () => resolve(false), { once: true }));+ try { return await Promise.race([lease.ended.then(() => true as const), timeout, aborted]); }+ finally { clearTimeout(timer); }+}