Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): lane groups validate while their predecessor still publishes; report lane fallbacks

garrytand4aff4e02ee2
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index 7345d0ca3c..522727917c 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -329,7 +329,7 @@ export interface SyncOpts {
* breadcrumbs already cover that surface).
*/
onProgress?: (p: { phase: string; bankedFiles?: number; total?: number; waived?: boolean; group?: number;
- /** #5984 lanes (phase `managed_sync.lanes`). */ lanes?: { effective: number; stepDown: string | null; overlapped: number } }) => void;
+ /** #5984 lanes (phase `managed_sync.lanes`). */ lanes?: { effective: number; stepDown: string | null; overlapped: number; fallbacks: number } }) => void;
/**
* #5984: managed sync only. Re-enter the single-pass managed sync until the
* cursor is done, the caller's signal/deadline stops it, or it is blocked
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index c7c21d46ef..c5e5557971 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -245,6 +245,7 @@ function groupFailure(error: unknown): GroupFailure {
* cost one lane for the rest of the drain.
*/
async function laneFallback(engine: BrainEngine, rows: WriteRequest[], reason: GroupFailure | undefined, run: GroupExecution): Promise<boolean | null> {
+ if (run.lane) run.lane.fallbacks++;
if (reason === 'lock_timeout' || reason === 'statement_timeout') stepDownLanes(rows[0]!.worktree_id!, `${reason} on a lane group`);
const after = windowPredecessor(rows[0]!);
const prior = after ? await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=$3::uuid',
diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.ts
index 80bcbd29dd..d103f88a8b 100644
--- a/src/core/persistence/sync-drain.ts
+++ b/src/core/persistence/sync-drain.ts
@@ -53,7 +53,7 @@ export interface DrainReport {
/** #5984 admit-ahead: groups admitted while the previous group was still publishing. */
admitted_ahead: number;
/** #5984 lanes: groups published at once, as asked and as in effect at the end, and why fewer. */
- lanes: { configured: number; effective: number; reason: string | null; step_down: string | null; overlapped_groups: number } };
+ lanes: { configured: number; effective: number; reason: string | null; step_down: string | null; overlapped_groups: number; fallbacks: number } };
}
const TERMINAL_STATUSES = new Set(['synced', 'first_sync', 'up_to_date', 'dry_run']);
@@ -164,7 +164,7 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
const signal = coop.signal && input.signal ? AbortSignal.any([input.signal, coop.signal]) : coop.signal ?? input.signal;
let passes = 0, attempt = 0, readFailures = 0, refreshWaitedMs = 0, written = 0, waived = 0, index = 0, total: number | null = null;
let announcedStart = false, lastLine = 0, groups = 0, groupedPages = 0, largestGroup = 0, admittedAhead = 0;
- let lanes: { effective: number; stepDown: string | null; overlapped: number } | null = null;
+ let lanes: { effective: number; stepDown: string | null; overlapped: number; fallbacks: number } | null = null;
let stall: { key: string; since: number; passes: number } | null = null;
const remaining = () => total === null ? null : Math.max(0, total - index);
const onProgress: NonNullable<SyncOpts['onProgress']> = event => {
@@ -178,7 +178,7 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
}
if (event.phase === 'managed_sync.group' && typeof event.group === 'number') { groups++; groupedPages += event.group; largestGroup = Math.max(largestGroup, event.group); }
if (event.phase === 'managed_sync.group_ahead') admittedAhead += typeof event.group === 'number' ? 1 : 0;
- if (event.phase === 'managed_sync.lanes' && event.lanes) lanes = { effective: event.lanes.effective, stepDown: event.lanes.stepDown, overlapped: event.lanes.overlapped };
+ if (event.phase === 'managed_sync.lanes' && event.lanes) lanes = { effective: event.lanes.effective, stepDown: event.lanes.stepDown, overlapped: event.lanes.overlapped, fallbacks: event.lanes.fallbacks };
if (event.phase !== 'managed_sync.page_committed') return;
if (event.waived) waived++; else written++;
noteForwardProgress();
@@ -196,7 +196,7 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
return { ...result, drain: { outcome, ...(stopReason ? { stop_reason: stopReason } : {}), passes, processed: written + waived, written, waived,
remaining: left, ...drainEstimate(left, written + waived, Date.now() - startedAt),
...(input.bulk ? { bulk: { enabled: input.bulk.enabled, reason: input.bulk.reason, groups, grouped_pages: groupedPages, largest_group: largestGroup, admitted_ahead: admittedAhead,
- lanes: { configured: input.bulk.lanes ?? 1, effective: lanes?.effective ?? input.bulk.lanes ?? 1, reason: input.bulk.lanesReason ?? null, step_down: lanes?.stepDown ?? null, overlapped_groups: lanes?.overlapped ?? 0 } } } : {}), ...extra } };
+ lanes: { configured: input.bulk.lanes ?? 1, effective: lanes?.effective ?? input.bulk.lanes ?? 1, reason: input.bulk.lanesReason ?? null, step_down: lanes?.stepDown ?? null, overlapped_groups: lanes?.overlapped ?? 0, fallbacks: lanes?.fallbacks ?? 0 } } } : {}), ...extra } };
};
try {
for (;;) {
diff --git a/src/core/persistence/sync-lanes.ts b/src/core/persistence/sync-lanes.ts
index 8f8889a960..34b878ff45 100644
--- a/src/core/persistence/sync-lanes.ts
+++ b/src/core/persistence/sync-lanes.ts
@@ -21,13 +21,15 @@ import { leaseDraining, leaseWounded } from './worktree-lease.ts';
export interface LanePolicy { run: string; asked: number; effective: number; stepDown: string | null;
/** Groups whose transaction began while the group before them was still publishing in this process. */
- overlapped: number }
+ overlapped: number;
+ /** Lane groups that did not commit as a group (cancelled, released for the FIFO head, or published singly). */
+ fallbacks: number }
export 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, overlapped: 0, coordinationPath, claimed: new Set(), begun: new Set() });
+ policies.set(worktreeId, { run, asked: lanes, effective: lanes, stepDown: null, overlapped: 0, fallbacks: 0, coordinationPath, claimed: new Set(), begun: new Set() });
}
/** Ends a drain's lane run on every worktree it opened; its unclaimed groups go back to the FIFO claim. */
export function closeLaneRun(run: string): void {
@@ -35,7 +37,7 @@ export function closeLaneRun(run: string): void {
}
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 } : null;
+ return state ? { run: state.run, asked: state.asked, effective: state.effective, stepDown: state.stepDown, overlapped: state.overlapped, fallbacks: state.fallbacks } : 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 }> {
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index e194c301f0..eb5f9ef3f1 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -38,7 +38,7 @@ import { frontmatterSlugConflictMessage } from './verb-errors.ts';
import { CHUNKER_VERSION } from '../chunkers/code.ts';
import { clearGitHold, countGitHolds, recordSyncImportProvenance } from './sync-holds.ts';
import { VERSION } from '../../version.ts';
-import { windowPredecessor, windowPredecessorCommitted } from './sync-window.ts';
+import { windowPredecessor, windowPredecessorAllows } from './sync-window.ts';
/** The options that select a managed sync cursor (its key), recorded so a refusal can print the exact retry. */
export interface SyncCursorOptions { full: boolean; workingTree: boolean; srcSubpath: string | null; exclude: string[]; includeHidden: string[]; strategy: string | null }
@@ -245,7 +245,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
const [configuredSource] = await tx.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1 FOR SHARE', [row.source_id]);
assertConfiguredSyncRoot(root, configuredSource?.local_path ?? null);
const held = await readSyncCursorFence(tx, p.cursorKey);
- if (after && !await windowPredecessorCommitted(tx, row)) throw syncPublicationRefusal('revision_conflict', 'An earlier page of this sync did not commit.', row, p,
+ if (after && !await windowPredecessorAllows(tx, row)) throw syncPublicationRefusal('revision_conflict', 'An earlier page of this sync did not commit.', row, p,
`Request ${row.request_id} was admitted ahead of request ${after} of the same sync run, which did not commit, so this page must not publish after it.`);
const current = await getWorktreeBinding(tx, row.source_id);
if (!current || String(current.owner_epoch) !== p.ownerEpoch) throw syncPublicationRefusal('owner_unavailable', 'The accepted sync owner epoch changed.', row, p,
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 780108f2a9..3c67277dd8 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -550,7 +550,7 @@ async function groupStep(engine: BrainEngine, cursor: Cursor, key: string, bulk:
const last = rows.find(row => row.request_id === members.at(-1)!.requestId)!;
const waited = await awaitWrite(engine, last, config, wait);
const policy = ahead ? lanePolicy(cursor.binding.worktree_id) : null;
- if (policy && policy.run === bulk.settings.laneRun) onProgress?.({ phase: 'managed_sync.lanes', lanes: { effective: policy.effective, stepDown: policy.stepDown, overlapped: policy.overlapped } });
+ if (policy && policy.run === bulk.settings.laneRun) onProgress?.({ phase: 'managed_sync.lanes', lanes: { effective: policy.effective, stepDown: policy.stepDown, overlapped: policy.overlapped, fallbacks: policy.fallbacks } });
assertSyncDispatchActive();
const states = new Map((await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=ANY($1::uuid[])', [rows.map(row => row.id)])).map(row => [row.request_id, row]));
const next: Cursor = { ...cursor, counts: { ...cursor.counts } };
diff --git a/src/core/persistence/sync-window.ts b/src/core/persistence/sync-window.ts
index 2234876e98..9f43ff14a3 100644
--- a/src/core/persistence/sync-window.ts
+++ b/src/core/persistence/sync-window.ts
@@ -22,6 +22,20 @@ export function windowPredecessor(row: Pick<WriteRequest, 'intent'>): string | n
return typeof after === 'string' ? after : null;
}
+/**
+ * Whether a window group may still publish: its predecessor committed, or, for a lane group (`intent.lane`),
+ * is still publishing, since the lane commits only after it (sync-lanes.ts `awaitLaneTurn`). A predecessor
+ * that ended without committing, or is missing, never lets it publish.
+ */
+export async function windowPredecessorAllows(engine: Pick<BrainEngine, 'executeRaw'>, row: Pick<WriteRequest, 'intent' | 'principal_kind' | 'principal_id'>): Promise<boolean> {
+ const after = windowPredecessor(row);
+ if (!after) return true;
+ const [prior] = await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=$3::uuid',
+ [row.principal_kind, row.principal_id, after]);
+ if (prior?.state === 'committed') return true;
+ return typeof (row.intent as Record<string, unknown> | null | undefined)?.lane === 'string' && ['queued', 'running'].includes(prior?.state ?? '');
+}
+
/** Whether the predecessor of a window group committed (true for requests outside a window). */
export async function windowPredecessorCommitted(engine: Pick<BrainEngine, 'executeRaw'>, row: Pick<WriteRequest, 'intent' | 'principal_kind' | 'principal_id'>): Promise<boolean> {
const after = windowPredecessor(row);
diff --git a/test/managed-sync-lanes.test.ts b/test/managed-sync-lanes.test.ts
index 740682657f..99801bcaf4 100644
--- a/test/managed-sync-lanes.test.ts
+++ b/test/managed-sync-lanes.test.ts
@@ -86,6 +86,7 @@ test('lanes publish several groups at once and every page still commits, attribu
const result = await performSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true, drain: true, lanes: 4 });
expect(result.drain).toMatchObject({ outcome: 'synced', bulk: { enabled: true, lanes: { configured: 4 } } });
expect(result.drain!.bulk!.lanes.overlapped_groups).toBeGreaterThan(0);
+ expect(result.drain!.bulk!.lanes.fallbacks).toBe(0);
const rows = await imports(engine, f.id);
expect(rows).toHaveLength(80);
expect(rows.every(row => row.state === 'committed')).toBe(true);