Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(sync): parallel lanes for managed bulk sync (#5984 Phase 2)

garrytanf4fb315836ac
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index 5b8051f302..7345d0ca3c 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -328,7 +328,8 @@ export interface SyncOpts {
* `sync_status` IPC polls read. Absent for direct CLI runs (stderr
* breadcrumbs already cover that surface).
*/
- onProgress?: (p: { phase: string; bankedFiles?: number; total?: number; waived?: boolean; group?: number }) => void;
+ 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: 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
@@ -339,6 +340,7 @@ export interface SyncOpts {
/** #5984: wall-clock ms the current drain started; managed cursors measure their rate from it. */
drainStartedAt?: number;
/** #5984: `--no-bulk`; and the drain's resolved bulk settings (internal; absent = one request per pass step). */ noBulk?: boolean; bulk?: import('../core/persistence/sync-group.ts').BulkSettings;
+ /** #5984 lanes: `--lanes N` (1..8) or `--no-lanes` (1). */ lanes?: number;
}
// The git-plumbing cluster (git(), discoverGitRoot, createSyncBaselineCommit,
diff --git a/src/commands/sync/args.ts b/src/commands/sync/args.ts
index cd95fa73a1..15b5f00105 100644
--- a/src/commands/sync/args.ts
+++ b/src/commands/sync/args.ts
@@ -94,6 +94,11 @@ Options:
'gbrain config set sync.bulk false' or
GBRAIN_SYNC_BULK=0; tune with sync.bulk_size and
sync.bulk_max_txn_ms.
+ --lanes N Managed Postgres sync: publish up to N bulk groups at
+ once (1-8, default 4, capped by the connection pool).
+ Pages still commit in file order. Persist with
+ 'gbrain config set sync.lanes N' or GBRAIN_SYNC_LANES.
+ --no-lanes Same as --lanes 1: one bulk group at a time.
--no-delegate On a PGLite brain with a live 'gbrain serve', sync
normally delegates the run to the serve process over
its IPC socket (the lock owner does the work; embeds
@@ -183,6 +188,8 @@ export function parseSyncFlags(args: string[]) {
const full = args.includes('--full');
const noPull = args.includes('--no-pull');
const noBulk = args.includes('--no-bulk');
+ const lanesAt = args.indexOf('--lanes');
+ const lanes = args.includes('--no-lanes') ? 1 : lanesAt === -1 ? undefined : intFlagValue(args[lanesAt + 1], '--lanes', { min: 1, max: 8, example: 4 });
let noEmbed = resolveNoEmbed(args, loadConfig());
const noExtract = args.includes('--no-extract'); // v0.42.7 #1696
const skipFailed = args.includes('--skip-failed');
@@ -241,7 +248,7 @@ export function parseSyncFlags(args: string[]) {
console.error(`--max-age cannot be combined with --force-break-lock (force skips all guards).`);
process.exit(1);
}
- return { repoPath, watch, interval, dryRun, full, noPull, noBulk, noEmbed, noExtract, skipFailed, retryFailed, resetCheckpoint, noSchemaPack, explicitProcessing, includeGitignored, workingTree, syncAll, missingPathMode, jsonOut, yesFlag, breakLock, forceBreakLock, maxAgeSeconds };
+ return { repoPath, watch, interval, dryRun, full, noPull, noBulk, lanes, noEmbed, noExtract, skipFailed, retryFailed, resetCheckpoint, noSchemaPack, explicitProcessing, includeGitignored, workingTree, syncAll, missingPathMode, jsonOut, yesFlag, breakLock, forceBreakLock, maxAgeSeconds };
}
export type SyncFlags = ReturnType<typeof parseSyncFlags>;
diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.ts
index e0dc5e0d68..b8bd3372b9 100644
--- a/src/commands/sync/run.ts
+++ b/src/commands/sync/run.ts
@@ -282,7 +282,7 @@ async function runSyncAll(
input: { noEmbed: boolean; embeddingCredentialError: Error | undefined; resumeCommand: string },
): Promise<void> {
const {
- dryRun, full, noPull, noBulk, noExtract, skipFailed, retryFailed, noSchemaPack, explicitProcessing, includeGitignored,
+ dryRun, full, noPull, noBulk, lanes, noExtract, skipFailed, retryFailed, noSchemaPack, explicitProcessing, includeGitignored,
workingTree, missingPathMode, jsonOut, yesFlag, serialFlag, noAutoEmbed, maxSources, concurrency, timeoutSeconds,
} = flags;
const { noEmbed, embeddingCredentialError, resumeCommand } = input;
@@ -460,7 +460,7 @@ async function runSyncAll(
strategy: cfg.strategy,
concurrency,
signal: composeAbortSignals(allInterrupt.signal, controller?.signal),
- drain: true, noBulk,
+ drain: true, noBulk, lanes,
};
// v0.40.6.0 (D6): wrap performSync in withSourcePrefix so every slog /
// serr line emitted from inside the sync code path gets prefixed with
@@ -715,7 +715,7 @@ async function runSingleSourceSync(
input: { sourceId: string; companyPolicy: Awaited<ReturnType<typeof getCompanyBrainProfile>> | null; noEmbed: boolean; resumeCommand: string },
): Promise<void> {
const {
- repoPath, watch, interval, dryRun, full, noPull, noBulk, noExtract, skipFailed, retryFailed, resetCheckpoint, noSchemaPack,
+ repoPath, watch, interval, dryRun, full, noPull, noBulk, lanes, noExtract, skipFailed, retryFailed, resetCheckpoint, noSchemaPack,
explicitProcessing, includeGitignored, workingTree, jsonOut, yesFlag, noAutoEmbed, strategyArg, srcSubpath,
excludePatterns, includeHiddenPatterns, concurrency, timeoutSeconds,
} = flags;
@@ -742,7 +742,7 @@ async function runSingleSourceSync(
exclude: excludePatterns.length > 0 ? excludePatterns : undefined,
includeHidden: includeHiddenPatterns.length > 0 ? includeHiddenPatterns : undefined,
signal: composeAbortSignals(singleSourceInterrupt.signal, singleSourceController?.signal),
- drain: true, noBulk,
+ drain: true, noBulk, lanes,
};
// v0.42.42.0 (#2139, Step 4b): single-source `gbrain sync` gets the SAME
diff --git a/src/core/config.ts b/src/core/config.ts
index 098aff1f81..51aea41380 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1621,6 +1621,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'sync.bulk',
'sync.bulk_size',
'sync.bulk_max_txn_ms',
+ 'sync.lanes',
// Persisted indexing scope (comma/newline-separated glob list; trailing '/'
// normalizes to a '/**' subtree glob). Read best-effort at the top of
// performSyncInner and UNIONED with any per-call --exclude so internal
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index 01d7e07bca..782b146e7c 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -1,6 +1,6 @@
import type { BrainEngine, ReservedConnection } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
-import { CLAIMABLE_WRITE_SQL, claimGroupFollowers, claimNextWrite, publicationGroupKey, compactWriteReceipts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues } from './journal.ts';
+import { CLAIMABLE_WRITE_SQL, claimGroupFollowers, claimNextLaneHead, claimNextWrite, publicationGroupKey, compactWriteReceipts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues } from './journal.ts';
import { finishUnpublishedFailure, publishMutation, recoverPublication, type PreparedMutation } from './coordinator.ts';
import { localHostId } from './identity.ts';
import { executeClaimedGroup, PAGE_BATCH_GROUP_MAX } from './group-publish.ts';
@@ -9,6 +9,7 @@ import { refreshManagedFilesystemRoots } from './filesystem-guard.ts';
import { PROJECTION_RETRY_READY_SQL, rebuildPendingPageProjections } from '../page-state/projections.ts';
import { publicationConcurrency } from './pool-capacity.ts';
import { cancelOrphanedWindowGroup } from './sync-window.ts';
+import { laneOf, laneRoots } from './sync-lanes.ts';
import { runPersistenceEffects } from './effects.ts';
import { PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import { isWriteErrorCode } from './types.ts';
@@ -69,6 +70,8 @@ export class PersistenceConsumer {
private idleLaneRetryAt = 0;
private active = new Set<Promise<void>>();
private activeRoots = new Set<string>();
+ /** #5984 lanes: running lane tasks per worktree. */
+ private laneTasks = new Map<string, number>();
private foregroundCounts = new Map<string, number>();
private rootRetryAfter = new Map<string, number>();
private projectionWorker: Promise<unknown> | undefined;
@@ -352,23 +355,45 @@ export class PersistenceConsumer {
return;
}
const concurrency = this.opts.concurrency ?? 2;
- const attemptedRoots = new Set([...this.activeRoots, ...this.rootRetryAfter.keys()]);
- while (!this.stopping && this.active.size < concurrency) {
+ const attemptedRoots = new Set([...this.activeRoots, ...this.laneTasks.keys(), ...this.rootRetryAfter.keys()]);
+ while (!this.stopping && this.active.size - this.laneTaskCount() < concurrency) {
const row = await this.phase('claim', () => claimNextWrite(this.engine, this.hostId, 30_000, [...attemptedRoots]));
if (!row) break;
if (this.stopping) { await releaseUnpublishedClaim(this.engine, row, 'consumer_stopping'); break; }
const key = row.worktree_id ?? `db:${row.source_incarnation}`;
attemptedRoots.add(key);
+ // #5984 lanes: the FIFO head of an open lane run runs as the run's first lane.
+ if (laneOf(row)) { this.startLaneTask(row, key); continue; }
if (this.activeRoots.has(key)) { await releaseUnpublishedClaim(this.engine, row, 'writer_busy'); break; }
this.activeRoots.add(key);
- let progressed = false;
- const task = this.executeOrGroup(row).then(result => { progressed = result; }).catch(error => this.report(error)).finally(() => {
- if (!progressed) this.rootRetryAfter.set(key, Date.now() + (this.opts.pollMs ?? 250));
- else { this.progressWake = true; this.publishedSinceMaintenance++; }
- this.active.delete(task); this.activeRoots.delete(key); this.schedule(progressed ? 0 : this.opts.pollMs ?? 250);
- });
- this.active.add(task);
+ this.track(row, () => this.activeRoots.delete(key), key);
}
+ await this.claimLanes();
+ }
+ /** #5984 lanes: claims the next group heads of every open lane run in this process, up to its effective lane count. */
+ private async claimLanes(): Promise<void> {
+ for (const { worktreeId, run, capacity } of laneRoots()) {
+ if (this.rootRetryAfter.has(worktreeId) || this.activeRoots.has(worktreeId)) continue;
+ while (!this.stopping && (this.laneTasks.get(worktreeId) ?? 0) < capacity) {
+ const row = await this.phase('claim', () => claimNextLaneHead(this.engine, this.hostId, worktreeId, run));
+ if (!row) break;
+ this.startLaneTask(row, worktreeId);
+ }
+ }
+ }
+ private laneTaskCount(): number { let count = 0; for (const n of this.laneTasks.values()) count += n; return count; }
+ private startLaneTask(row: WriteRequest, key: string): void {
+ this.laneTasks.set(key, (this.laneTasks.get(key) ?? 0) + 1);
+ this.track(row, () => { const n = (this.laneTasks.get(key) ?? 1) - 1; if (n > 0) this.laneTasks.set(key, n); else this.laneTasks.delete(key); }, key);
+ }
+ private track(row: WriteRequest, done: () => void, key: string): void {
+ let progressed = false;
+ const task = this.executeOrGroup(row).then(result => { progressed = result; }).catch(error => this.report(error)).finally(() => {
+ if (!progressed) this.rootRetryAfter.set(key, Date.now() + (this.opts.pollMs ?? 250));
+ else { this.progressWake = true; this.publishedSinceMaintenance++; }
+ this.active.delete(task); done(); this.schedule(progressed ? 0 : this.opts.pollMs ?? 250);
+ });
+ this.active.add(task);
}
/** Effects keep pace with publication: full batches continue without waiting for the next tick. */
private async drainEffects(): Promise<void> {
@@ -529,17 +554,19 @@ export class PersistenceConsumer {
/** #5984: a claimed bulk sync head takes its directly following group members along; one row runs the single path. */
private async executeOrGroup(row: WriteRequest): Promise<boolean> {
// #5984 admit-ahead: a window group whose predecessor did not commit is cancelled, never published after it.
- const orphaned = await cancelOrphanedWindowGroup(this.engine, row);
+ // A lane group may be claimed while its predecessor still publishes; its commit wait decides instead.
+ const lane = laneOf(row);
+ const orphaned = lane ? null : await cancelOrphanedWindowGroup(this.engine, row);
if (orphaned) { for (const done of orphaned) this.settled(done); return true; }
const group = publicationGroupKey(row);
if (!group || this.engine.kind !== 'postgres') return this.execute(row);
// #6007: a put_pages batch publishes in groups of at most PAGE_BATCH_GROUP_MAX pages.
const followers = await claimGroupFollowers(this.engine, row, group, group.startsWith('batch:') ? PAGE_BATCH_GROUP_MAX - 1 : 63);
- if (!followers.length) return this.execute(row);
+ if (!followers.length && !lane) return this.execute(row);
const rows = [row, ...followers];
for (const member of rows) this.executing.add(member.id);
try {
- return await executeClaimedGroup(this.engine, rows, { hostId: this.hostId, prepare: member => this.prepare(this.engine, member, this.config),
+ return await executeClaimedGroup(this.engine, rows, { hostId: this.hostId, lane, prepare: member => this.prepare(this.engine, member, this.config),
settled: done => {
this.executing.delete(done.id);
if (done.state === 'committed' && done.worktree_id && !String(done.intent?.kind).startsWith('managed_sync_')) {
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index 9ffc56beb4..c7c21d46ef 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -30,7 +30,9 @@ import type { BrainEngine } from '../engine.ts';
import { OperationError } from '../ops/contract.ts';
import { authorizeStoredRequest } from './authority.ts';
import { localHostId } from './identity.ts';
-import { acquireWorktree, getWorktreeBinding, guardOwnership } from './ownership.ts';
+import { acquireWorktree, acquireWorktreeShared, getWorktreeBinding, guardOwnership } from './ownership.ts';
+import { awaitLaneBegin, awaitLaneTurn, LaneAbort, laneClaimed, laneFinished, stepDownLanes, type LaneState } from './sync-lanes.ts';
+import { cancelRows, windowPredecessor } from './sync-window.ts';
import { clearResolvedRecoveries, completeWrite, ENSURE_COUNTERS_SQL, getWriteRequestById, LOCK_COUNTERS_SQL, markRecovering, prepareRecoveries,
publicationGroupKey, reclaimReleasedWrite, releaseUnpublishedClaim, renewGroupClaims } from './journal.ts';
import { principalKey, requestPrincipal, type FileRecoveryRecord, type WriteRequest } from './model.ts';
@@ -113,14 +115,16 @@ export interface GroupHooks {
* released, which the caller may claim again while it holds the worktree.
*/
export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prepared: PreparedMutation[], hostId = localHostId(),
- hooks: GroupHooks = {}): Promise<{ done: WriteRequest[] | null; requeued: string[] }> {
+ hooks: GroupHooks = {}, lane: LaneState | null = null): Promise<{ done: WriteRequest[] | null; requeued: string[]; reason?: GroupFailure }> {
const head = rows[0];
- const none = { done: null, requeued: [] };
+ const none: { done: null; requeued: string[]; reason?: GroupFailure } = { done: null, requeued: [] };
if (!head?.worktree_id || rows.some((row, i) => row.worktree_id !== head.worktree_id || row.source_id !== head.source_id || !groupable(row, prepared[i]!))) return none;
const binding = await getWorktreeBinding(engine, head.source_id, hostId);
if (!binding || binding.owner_host_id !== hostId || !binding.local_path) return none;
- const lock = await acquireWorktree(binding, 0, undefined, engine);
- if (!lock) return none;
+ // #5984 lanes: lane groups share this process's native lock; everything else takes it exclusively.
+ const lock = lane ? await acquireWorktreeShared(binding, engine) : await acquireWorktree(binding, 0, undefined, engine);
+ if (!lock) return { ...none, reason: 'busy' };
+ if (lane) lane.coordinationPath ??= binding.coordination_path;
let releaseCapacity: (() => void) | null = null;
const recorded = new Map<number, { row: WriteRequest; record: FileRecoveryRecord; bytes: number }>();
let committed = false;
@@ -128,8 +132,8 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
const blocked = await engine.executeRaw(`SELECT 1 FROM persistence_requests WHERE worktree_id=$1::uuid AND NOT (id=ANY($2::uuid[])) AND recovery IS NOT NULL
UNION ALL SELECT 1 FROM persistence_effects WHERE worktree_id=$1::uuid AND recovery IS NOT NULL LIMIT 1`, [head.worktree_id, rows.map(row => row.id)]);
if (blocked.length) return none;
- releaseCapacity = tryAcquirePublicationCapacity(engine);
- if (!releaseCapacity) return none;
+ releaseCapacity = tryAcquirePublicationCapacity(engine, lane ? lane.effective + 1 : undefined);
+ if (!releaseCapacity) return { ...none, reason: 'busy' };
const files = new Map<number, { row: WriteRequest; record: FileRecoveryRecord; bytes: number }>();
for (let i = 0; i < rows.length; i++) {
const file = prepared[i]!.file;
@@ -144,6 +148,7 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
await prepareRecoveries(engine, [...files.values()]);
for (const [i, member] of files) recorded.set(i, member);
}
+ if (lane) await awaitLaneBegin(lane, rows);
const done = await engine.transaction(async transaction => {
const tx = groupReads(transaction);
await declareDurablePersistence(tx);
@@ -186,6 +191,8 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
outcomes.push(outcome);
}
}, requestAttribution(head));
+ // #5984 lanes: applied concurrently, committed in manifest order.
+ if (lane) await awaitLaneTurn(tx, lane, rows);
const done = await completeGroup(tx, rows, outcomes);
// Every member is complete in this transaction: the batch's last page re-arms the batch's mention links once.
const last = rows[rows.length - 1]!;
@@ -204,8 +211,8 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
}
}
return { done, requeued: [] };
- } catch {
- if (committed || !recorded.size) { await hooks.rolledBack?.(rows); return none; }
+ } catch (error) {
+ if (committed || !recorded.size) { await hooks.rolledBack?.(rows); return { ...none, reason: groupFailure(error) }; }
// Restore every file this group may have published and release those claims; a committed member (an uncertain commit) only cleans up.
const requeued: string[] = [];
for (const { row } of recorded.values()) {
@@ -223,6 +230,34 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
}
}
+/** Why a group transaction did not commit, for the lane fallback and step-down. */
+export type GroupFailure = 'busy' | 'predecessor_failed' | 'wounded' | 'order_timeout' | 'lock_timeout' | 'statement_timeout' | 'failed';
+function groupFailure(error: unknown): GroupFailure {
+ if (error instanceof LaneAbort) return error.reason;
+ const code = (error as { code?: unknown } | null)?.code;
+ return code === '55P03' ? 'lock_timeout' : code === '57014' ? 'statement_timeout' : 'failed';
+}
+
+/**
+ * #5984 lanes: a lane group that did not commit. A group whose predecessor ended without committing is
+ * cancelled; one whose predecessor committed takes the single path like any FIFO head (null); one whose
+ * predecessor still publishes releases its claims so the FIFO head runs first. Lock and statement timeouts
+ * 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 (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',
+ [rows[0]!.principal_kind, rows[0]!.principal_id, after]).then(found => found[0]?.state ?? null) : 'committed';
+ if (prior === 'committed') return null;
+ if (prior === null || ['failed', 'conflict', 'cancelled'].includes(prior)) {
+ for (const done of await cancelRows(engine, rows)) run.settled(done);
+ return true;
+ }
+ for (const row of rows) await releaseUnpublishedClaim(engine, row, 'group_member_waiting');
+ return false;
+}
+
/**
* #5984: completes every member's request row in one statement. Each member's
* queued effect bytes are read (and missing counter rows created) before the
@@ -270,6 +305,8 @@ export async function completeGroup(tx: BrainEngine, rows: WriteRequest[], outco
}
export interface GroupExecution {
+ /** #5984 lanes: the open lane run this group belongs to in this process. */
+ lane?: LaneState | null;
prepare(row: WriteRequest): Promise<PreparedMutation>;
settled(row: WriteRequest): void;
hostId: string;
@@ -288,6 +325,7 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteReques
let renewing: Promise<unknown> | undefined;
const interval = setInterval(() => { renewing ??= renewGroupClaims(engine, rows).catch(() => undefined).finally(() => { renewing = undefined; }); }, 10_000);
interval.unref?.();
+ if (run.lane) laneClaimed(run.lane, rows);
try {
const prepared: Array<{ ok: PreparedMutation } | { error: unknown }> = new Array(rows.length);
// A put_pages group prepares all of its (at most PAGE_BATCH_GROUP_MAX) pages at once.
@@ -301,9 +339,13 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteReques
const independent = publicationGroupKey(rows[0]!)?.startsWith('batch:') === true;
let requeued = new Set<string>();
if (prepared.every(p => 'ok' in p)) {
- const result = await publishGroup(engine, rows, prepared.map(p => (p as { ok: PreparedMutation }).ok), run.hostId, run.hooks);
+ const result = await publishGroup(engine, rows, prepared.map(p => (p as { ok: PreparedMutation }).ok), run.hostId, run.hooks, run.lane ?? null);
if (result.done) { for (const row of result.done) run.settled(row); return true; }
requeued = new Set(result.requeued);
+ if (run.lane) { const settled = await laneFallback(engine, rows, result.reason, run); if (settled !== null) return settled; }
+ } else if (run.lane) {
+ const settled = await laneFallback(engine, rows, 'failed', run);
+ if (settled !== null) return settled;
}
let progressed = false, stop: 'cancel' | 'release' | null = null;
for (let i = 0; i < rows.length; i++) {
@@ -333,6 +375,7 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteReques
}
return progressed;
} finally {
+ if (run.lane) laneFinished(run.lane, rows);
clearInterval(interval);
await renewing;
}
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index 0fb1834956..39d235fce3 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -414,6 +414,37 @@ export async function claimNextWrite(engine: BrainEngine, hostId: string, leaseM
return claimed;
});
}
+/**
+ * #5984 lanes: claims the head of the next admitted group of lane run `run` in
+ * worktree `worktreeId` while earlier groups of the same run still publish.
+ * Every request before it must already be claimed (none queued, so heads are
+ * claimed in manifest order), and an unfinished earlier request must be a
+ * running request of the same run: a foreground write, a recovering request,
+ * a request of another run or any recovery record still blocks it, exactly
+ * as under the FIFO claim. Followers are claimed with their head by
+ * `claimGroupFollowers`.
+ */
+export async function claimNextLaneHead(engine: BrainEngine, hostId: string, worktreeId: string, run: string, leaseMs = 30_000): Promise<WriteRequest | null> {
+ return engine.transactionDirect(async tx => {
+ await declarePersistenceProtocol(tx);
+ const [row] = await tx.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests r
+ JOIN persistence_worktrees w ON w.id=r.worktree_id
+ WHERE r.worktree_id=$2::uuid AND r.state='queued' AND r.intent->>'lane'=$3 AND r.intent->>'group'=r.request_id::text
+ AND w.owner_host_id=$1::uuid AND w.state='active' AND ${refreshFenceClear('r')}
+ AND NOT EXISTS (SELECT 1 FROM persistence_effects blocked WHERE blocked.worktree_id=r.worktree_id AND blocked.recovery IS NOT NULL)
+ AND NOT EXISTS (SELECT 1 FROM persistence_effects mirror WHERE mirror.worktree_id=r.worktree_id
+ AND mirror.kind='withdrawal-mirror' AND mirror.state IN ('queued','running'))
+ AND NOT EXISTS (SELECT 1 FROM persistence_requests blocked WHERE blocked.worktree_id=r.worktree_id AND blocked.recovery IS NOT NULL)
+ AND NOT EXISTS (SELECT 1 FROM persistence_requests earlier WHERE earlier.worktree_id=r.worktree_id AND earlier.sequence<r.sequence
+ AND (earlier.state IN ('queued','recovering') OR (earlier.state='running' AND COALESCE(earlier.intent->>'lane','')<>$3)))
+ ORDER BY r.sequence LIMIT 1 FOR UPDATE OF r SKIP LOCKED`, [hostId, worktreeId, run]);
+ if (!row) return null;
+ const [claimed] = await tx.executeRaw<WriteRequest>(`UPDATE persistence_requests SET state='running',
+ execution_token=$2::uuid,claim_expires_at=now()+($3::double precision*interval '1 millisecond'),
+ updated_at=now(),blocked_reason=NULL WHERE id=$1::uuid RETURNING *`, [row.id, randomUUID(), leaseMs]);
+ return claimed;
+ });
+}
export async function renewWriteClaim(engine: SqlEngine, id: string, token: string, leaseMs = 30_000, signal?: AbortSignal): Promise<boolean> {
const rows = await engine.executeRaw(`UPDATE persistence_requests SET
claim_expires_at=now()+($3::double precision*interval '1 millisecond'),updated_at=now()
diff --git a/src/core/persistence/pool-capacity.ts b/src/core/persistence/pool-capacity.ts
index 59d394ed4c..3427b3a6cf 100644
--- a/src/core/persistence/pool-capacity.ts
+++ b/src/core/persistence/pool-capacity.ts
@@ -9,12 +9,15 @@ function ordinaryPool(engine: BrainEngine): BudgetPool {
export function publicationConcurrency(engine: BrainEngine): number {
return engine.kind === 'pglite' ? 1 : Math.min(2, poolLongHoldCapacity(ordinaryPool(engine)));
}
-/** Acquire before checking out a connection; there is no asynchronous wait here. */
-export function tryAcquirePublicationCapacity(engine: BrainEngine): (() => void) | null {
+/**
+ * Acquire before checking out a connection; there is no asynchronous wait here. #5984 lanes pass a higher
+ * `limit` (their lane count), still bounded by the pool's long-hold capacity.
+ */
+export function tryAcquirePublicationCapacity(engine: BrainEngine, limit?: number): (() => void) | null {
if (engine.kind === 'postgres') {
const pool = ordinaryPool(engine);
const count = publishing.get(pool) ?? 0;
- if (count >= publicationConcurrency(engine)) return null;
+ if (count >= (limit === undefined ? publicationConcurrency(engine) : Math.min(limit, poolLongHoldCapacity(pool)))) return null;
const release = tryAcquirePoolLongHold(pool);
if (!release) return null;
publishing.set(pool, count + 1);
diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.ts
index 7bc8b15a82..80bcbd29dd 100644
--- a/src/core/persistence/sync-drain.ts
+++ b/src/core/persistence/sync-drain.ts
@@ -11,6 +11,7 @@
* ends in one outcome (`synced`, `resumable`, `blocked`) carried on
* `SyncResult.drain`; the CLI turns it into the exit code and `next`.
*/
+import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
import type { SyncOpts, SyncResult } from '../../commands/sync.ts';
import { OperationError } from '../ops/contract.ts';
@@ -50,7 +51,9 @@ export interface DrainReport {
/** DX-A5: whether pages were published in bulk groups, and why not when they were not. */
bulk?: { enabled: boolean; reason: string | null; groups: number; grouped_pages: number; largest_group: number;
/** #5984 admit-ahead: groups admitted while the previous group was still publishing. */
- admitted_ahead: number };
+ 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 } };
}
const TERMINAL_STATUSES = new Set(['synced', 'first_sync', 'up_to_date', 'dry_run']);
@@ -147,7 +150,7 @@ export interface DrainInput {
/** Throttled progress lines on stderr (CLI). */
announce?: boolean;
/** Publication mode for the report and the start line. */
- bulk?: { enabled: boolean; reason: string | null };
+ bulk?: { enabled: boolean; reason: string | null; lanes?: number; lanesReason?: string | null };
/** Test seams: the no-progress window, the pause after a pending write and the transient backoff base. */
stallMs?: number;
pauseMs?: number;
@@ -161,6 +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 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 => {
@@ -173,7 +177,8 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
+ (input.bulk?.enabled ? 'publishing in bulk groups (each page keeps its own request).' : `one write request per page${input.bulk?.reason ? ` (bulk off: ${input.bulk.reason})` : ''}.`));
}
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++;
+ 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.page_committed') return;
if (event.waived) waived++; else written++;
noteForwardProgress();
@@ -190,7 +195,8 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
if (stopReason === 'deadline' && continues(result)) result = { ...result, reason: 'timeout' };
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: { ...input.bulk, groups, grouped_pages: groupedPages, largest_group: largestGroup, admitted_ahead: admittedAhead } } : {}), ...extra } };
+ ...(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 } };
};
try {
for (;;) {
@@ -286,9 +292,15 @@ export async function drainManagedSync(engine: BrainEngine, opts: SyncOpts, anno
const { 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);
- return runDrain({ signal: opts.signal, onProgress: opts.onProgress, probe: engineStallProbe(engine), announce, bulk: { enabled: bulk.enabled, reason: bulk.reason },
- pass: (signal, onProgress) => performManagedSync(engine, { ...opts, signal, onProgress, drainStartedAt, ...(bulk.enabled ? { bulk } : {}) }) });
+ const bulk = await resolveBulkSettings(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');
+ try {
+ return await runDrain({ signal: opts.signal, onProgress: opts.onProgress, probe: engineStallProbe(engine), announce,
+ bulk: { enabled: bulk.enabled, reason: bulk.reason, lanes: bulk.lanes ?? 1, lanesReason: bulk.lanesReason ?? null },
+ pass: (signal, onProgress) => performManagedSync(engine, { ...opts, signal, onProgress, drainStartedAt, ...(bulk.enabled ? { bulk: { ...bulk, laneRun } } : {}) }) });
+ } finally { if (laneRun) closeLaneRun(laneRun); }
}
export interface DrainNext {
diff --git a/src/core/persistence/sync-group.ts b/src/core/persistence/sync-group.ts
index 5986ff1ce2..f95af526ac 100644
--- a/src/core/persistence/sync-group.ts
+++ b/src/core/persistence/sync-group.ts
@@ -23,7 +23,9 @@ import type { SyncAuthority } from './sync-authority.ts';
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 }
+ lanes?: number; lanesReason?: string | null;
+ /** The drain's lane run (set by the drain when lanes > 1); lane groups carry it as `intent.lane`. */
+ laneRun?: string }
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). */
diff --git a/src/core/persistence/sync-lanes.ts b/src/core/persistence/sync-lanes.ts
index 1e1e205ea8..8f8889a960 100644
--- a/src/core/persistence/sync-lanes.ts
+++ b/src/core/persistence/sync-lanes.ts
@@ -19,20 +19,23 @@ 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> }
+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 }
+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, coordinationPath, claimed: new Set(), begun: new Set() });
+ policies.set(worktreeId, { run, asked: lanes, effective: lanes, stepDown: null, overlapped: 0, coordinationPath, claimed: new Set(), begun: new Set() });
}
-export function closeLanes(worktreeId: string, run: string): void {
- if (policies.get(worktreeId)?.run === run) policies.delete(worktreeId);
+/** 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 {
+ for (const [worktreeId, state] of policies) if (state.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;
+ return state ? { run: state.run, asked: state.asked, effective: state.effective, stepDown: state.stepDown, overlapped: state.overlapped } : 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 }> {
@@ -72,6 +75,7 @@ export async function awaitLaneBegin(state: LaneState, rows: WriteRequest[], max
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);
+ if (after && state.claimed.has(after)) state.overlapped++;
state.begun.add(groupKey(rows));
}
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 14c925d8f7..780108f2a9 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -32,6 +32,7 @@ import { assertManagedSyncAllowed } from './worktree-refresh.ts';
import type { GBrainConfig } from '../config.ts';
import { admitGroup, freezeFollowers, groupableIntent, nextGroupSize, type BulkSettings } from './sync-group.ts';
import { cancelWindow } from './sync-window.ts';
+import { lanePolicy, openLanes } from './sync-lanes.ts';
import { isContentRefusal } from '../import-screen.ts';
import { SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';
import { dryRunScreen, isSyncReadBound, loadSyncScreenRun, pinnedBlob, screenFrozenImport, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';
@@ -450,51 +451,73 @@ async function formGroup(engine: BrainEngine, head: Cursor, pending: Pending, ke
const followers = await freezeFollowers(engine, head, config, nextGroupSize(bulk.settings, bulk.perMemberMs) - 1, freezeAt(head));
if (!followers.length) return head;
// Members name their group (the head's request ID), so a consumer can claim them together.
- const members = [pending, ...followers].map(member => ({ ...member, intent: { ...member.intent, group: pending.requestId } }));
+ const lane = laneRunOf(head, bulk);
+ const members = [pending, ...followers].map(member => ({ ...member, intent: { ...member.intent, group: pending.requestId, ...(lane ? { lane } : {}) } }));
return saveCursor(engine, key, head, { ...head, pending: members[0], group: members }, false, assertActive);
}
+/** #5984 lanes: the drain's lane run, opened for this cursor's worktree on first use; null when lanes are off. */
+function laneRunOf(cursor: Cursor, bulk: BulkPass): string | null {
+ const run = bulk.settings.laneRun, lanes = bulk.settings.lanes ?? 1;
+ if (!run || lanes <= 1) return null;
+ if (lanePolicy(cursor.binding.worktree_id)?.run !== run) openLanes(cursor.binding.worktree_id, run, lanes, null);
+ return run;
+}
+
/**
- * #5984 admit-ahead (one lane, window depth 2): while the cursor's group publishes, freeze and admit the
- * next group so it is queued behind it (per-worktree FIFO) and the consumer claims it as soon as the group
- * commits. Nothing is admitted ahead while foreground writes are recent (one was queued on the worktree in
- * the last minute), or when the next
+ * #5984 admit-ahead: while the cursor's group publishes, freeze and admit the next groups so they are queued
+ * behind it and the consumer starts each one as soon as it may: under the per-worktree FIFO claim one at a
+ * time (window depth 1), or, with lanes, up to the effective lane count at once (sync-lanes.ts). Each window
+ * group names the request before it (`after`), so groups commit in manifest order. Nothing is admitted ahead
+ * while foreground writes are recent (one was queued on the worktree in the last minute), or when the next
* entry is not groupable (renames, holds, waivers, the checkpoint and overtaken entries stay on the single path).
*/
async function admitAhead(engine: BrainEngine, cursor: Cursor, key: string, bulk: BulkPass, config: GBrainConfig, freezeAt: FreezeAt,
assertActive: () => void): Promise<Cursor> {
if (!bulk.settings.enabled || !cursor.group?.length) return cursor;
- let current = cursor;
- if (!current.window?.length) {
- const start = cursor.index + cursor.group.length;
- if (start >= cursor.entries.length) return cursor;
- const [foreground] = await engine.executeRaw(`SELECT id FROM persistence_requests WHERE worktree_id=$1::uuid
- AND state IN ('queued','running','recovering') AND NOT(COALESCE(intent->>'kind','') LIKE 'managed_sync_%') LIMIT 1`, [cursor.binding.worktree_id]);
- if (foreground) bulk.foregroundAt = performance.now();
- if (bulk.foregroundAt !== undefined && performance.now() - bulk.foregroundAt < FOREGROUND_RECENT_MS) return cursor;
- const base: Cursor = { ...cursor, index: start - 1 };
- // A freeze refusal here is left for the single path to raise in order, after the publishing group.
+ const lane = laneRunOf(cursor, bulk);
+ const depth = lane ? Math.max(1, lanePolicy(cursor.binding.worktree_id)?.effective ?? 1) : 1;
+ let current = cursor, foregroundChecked = false;
+ for (let slot = 0; ; slot++) {
+ const window = current.window ?? [];
+ if (slot < window.length) { await admitWindowGroup(engine, current, key, slot); continue; }
+ if (window.length >= depth) break;
+ const start = current.index + current.group!.length + window.reduce((sum, group) => sum + group.length, 0);
+ if (start >= current.entries.length) break;
+ if (!foregroundChecked) {
+ foregroundChecked = true;
+ const [foreground] = await engine.executeRaw(`SELECT id FROM persistence_requests WHERE worktree_id=$1::uuid
+ AND state IN ('queued','running','recovering') AND NOT(COALESCE(intent->>'kind','') LIKE 'managed_sync_%') LIMIT 1`, [current.binding.worktree_id]);
+ if (foreground) bulk.foregroundAt = performance.now();
+ }
+ if (bulk.foregroundAt !== undefined && performance.now() - bulk.foregroundAt < FOREGROUND_RECENT_MS) break;
+ const base: Cursor = { ...current, index: start - 1 };
+ // A freeze refusal here is left for the single path to raise in order, after the publishing groups.
const frozen = await freezeFollowers(engine, base, config, nextGroupSize(bulk.settings, bulk.perMemberMs), freezeAt(base)).catch(() => []);
- if (!frozen.length) return cursor;
- const after = cursor.group.at(-1)!.requestId;
- const members = frozen.map(member => ({ ...member, intent: { ...member.intent, group: frozen[0]!.requestId, after } }));
- current = await saveCursor(engine, key, cursor, { ...cursor, window: [members] }, false, assertActive);
- }
- const members = current.window?.[0];
- if (!members?.length) return current;
- const principal = current.authority.writer.principal;
- const admitted = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=ANY($3::uuid[])',
- [principal.kind, principal.id, members.map(member => member.requestId)]);
- if ((admitted[0]?.n ?? 0) < members.length) {
- // An admission that fails here is retried when the group becomes the cursor's group.
- await admitGroup(engine, members, current, async tx => {
- const [held] = await tx.executeRaw<{ request_id: string | null }>(`SELECT completed_keys->0->'window'->0->0->>'requestId' AS request_id FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 FOR SHARE`, [OP, key]);
- return held?.request_id === members[0]!.requestId;
- }).catch(() => null);
+ if (!frozen.length) break;
+ const after = (window.at(-1) ?? current.group!).at(-1)!.requestId;
+ const members = frozen.map(member => ({ ...member, intent: { ...member.intent, group: frozen[0]!.requestId, after, ...(lane ? { lane } : {}) } }));
+ const saved = await saveCursor(engine, key, current, { ...current, window: [...window, members] }, false, assertActive);
+ if (saved.window?.[window.length]?.[0]?.requestId !== members[0]!.requestId) return saved;
+ current = saved;
+ slot--;
}
assertActive();
return current;
}
+/** Admits window group `slot` when its requests are missing (a failed admission is retried when it becomes the cursor's group). */
+async function admitWindowGroup(engine: BrainEngine, cursor: Cursor, key: string, slot: number): Promise<void> {
+ const members = cursor.window![slot]!;
+ const principal = cursor.authority.writer.principal;
+ const admitted = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=ANY($3::uuid[])',
+ [principal.kind, principal.id, members.map(member => member.requestId)]);
+ if ((admitted[0]?.n ?? 0) >= members.length) return;
+ const rows = await admitGroup(engine, members, cursor, async tx => {
+ const [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();
+}
/**
* #5984 bulk: admits the cursor's group, waits for it and advances over the
* committed prefix. A terminal failure leaves that member as the single
@@ -520,13 +543,14 @@ async function groupStep(engine: BrainEngine, cursor: Cursor, key: string, bulk:
await validateSyncAuthority(engine, cursor.authority, members[0]!.slug);
assertSyncDispatchActive();
if (ahead) {
- const before = cursor.window?.[0]?.[0]?.requestId;
+ const before = new Set((cursor.window ?? []).map(group => group[0]!.requestId));
cursor = await ahead(cursor);
- const formed = cursor.window?.[0];
- if (formed?.length && formed[0]!.requestId !== before) onProgress?.({ phase: 'managed_sync.group_ahead', bankedFiles: cursor.index, total: cursor.entries.length, group: formed.length });
+ for (const formed of cursor.window ?? []) if (!before.has(formed[0]!.requestId)) onProgress?.({ phase: 'managed_sync.group_ahead', bankedFiles: cursor.index, total: cursor.entries.length, group: formed.length });
}
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 } });
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 d036f6e24f..2234876e98 100644
--- a/src/core/persistence/sync-window.ts
+++ b/src/core/persistence/sync-window.ts
@@ -53,7 +53,8 @@ export async function cancelWindow(engine: BrainEngine, window: Array<Array<{ re
await cancelRows(engine, rows);
}
-async function cancelRows(engine: BrainEngine, rows: WriteRequest[]): Promise<WriteRequest[]> {
+/** Cancels unpublished rows (queued, or claimed with the given token) with the window reason. */
+export async function cancelRows(engine: BrainEngine, rows: WriteRequest[]): Promise<WriteRequest[]> {
const settled: WriteRequest[] = [];
for (const row of rows) {
const done = await engine.transaction(async tx => {
diff --git a/test/helpers/persistence-postgres.ts b/test/helpers/persistence-postgres.ts
index 8cdb14686b..cc32e41933 100644
--- a/test/helpers/persistence-postgres.ts
+++ b/test/helpers/persistence-postgres.ts
@@ -4,7 +4,7 @@ import { PostgresEngine } from '../../src/core/postgres-engine.ts';
import { assertSafeE2eDatabaseUrl } from './db-guard.ts';
/** Permanent receipt IDs deliberately survive source deletion; use a fresh test brain. */
-export async function isolatedPersistencePostgres(databaseUrl:string, connectionStyle:'instance'|'module'='instance'):Promise<{engine:PostgresEngine;databaseUrl:string;close:()=>Promise<void>}> {
+export async function isolatedPersistencePostgres(databaseUrl:string, connectionStyle:'instance'|'module'='instance', poolSize=4):Promise<{engine:PostgresEngine;databaseUrl:string;close:()=>Promise<void>}> {
assertSafeE2eDatabaseUrl(databaseUrl);
const database=`gbrain_test_persistence_${randomUUID().replace(/-/g,'')}`;
const admin=postgres(databaseUrl,{max:1,prepare:false});
@@ -12,6 +12,6 @@ export async function isolatedPersistencePostgres(databaseUrl:string, connection
const url=new URL(databaseUrl);url.pathname=`/${database}`;
const engine=new PostgresEngine();
const close=async()=>{await engine.disconnect();await admin.unsafe(`DROP DATABASE ${database} WITH (FORCE)`);await admin.end();};
- try {await engine.connect({database_url:url.toString(),poolSize:connectionStyle==='module'?undefined:4});await engine.initSchema();return{engine,databaseUrl:url.toString(),close};}
+ try {await engine.connect({database_url:url.toString(),poolSize:connectionStyle==='module'?undefined:poolSize});await engine.initSchema();return{engine,databaseUrl:url.toString(),close};}
catch(error){await close();throw error;}
}
diff --git a/test/managed-sync-lanes.test.ts b/test/managed-sync-lanes.test.ts
new file mode 100644
index 0000000000..740682657f
--- /dev/null
+++ b/test/managed-sync-lanes.test.ts
@@ -0,0 +1,133 @@
+/**
+ * #5984 lanes (Postgres only): several bulk groups of one draining managed
+ * sync publish at once and still commit in manifest order.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { execFileSync } from 'node:child_process';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { performSync } from '../src/commands/sync/perform.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { resolveBulkSettings } from '../src/core/persistence/sync-group.ts';
+import { WINDOW_CANCEL_MESSAGE } from '../src/core/persistence/sync-window.ts';
+import { acquireShared, leaseDraining, leaseWounded, yieldLease } from '../src/core/persistence/worktree-lease.ts';
+import type { NativeLockHandle } from '../src/core/persistence/native-lock.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-lanes-'));
+let engine: BrainEngine | undefined;
+let closePostgres: (() => Promise<void>) | undefined;
+const sources: string[] = [];
+function git(root: string, ...args: string[]): string { return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); }
+async function fixture(e: BrainEngine, files: Record<string, string>) {
+ const id = `lanes-${randomUUID().replace(/-/g, '').slice(0, 20)}`; sources.push(id);
+ const root = join(home, id); mkdirSync(root); git(root, 'init', '-q');
+ for (const [path, body] of Object.entries(files)) { const full = join(root, path); mkdirSync(join(full, '..'), { recursive: true }); writeFileSync(full, body); }
+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes');
+ await e.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await e.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);
+ await claimWorktree(e, id, root);
+ await e.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return { id, root };
+}
+const pad = (i: number) => String(i).padStart(3, '0');
+const notes = (count: number, edit: (i: number) => string | null = () => null) => Object.fromEntries(Array.from({ length: count }, (_, i) =>
+ [`notes/n${pad(i)}.md`, edit(i) ?? `---\ntitle: Note ${i}\n---\nA durable observation number ${i}, see [[notes/n${pad((i + 7) % count)}]].\n`]));
+const imports = (e: BrainEngine, source: string) => e.executeRaw<{ slug: string; state: string; grp: string | null; lane: string | null; error_message: string | null }>(
+ `SELECT slug,state,intent->>'group' AS grp,intent->>'lane' AS lane,error_message FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import' ORDER BY sequence`, [source]);
+
+beforeAll(async () => {
+ if (!process.env.DATABASE_URL) return;
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL, 'instance', 12); engine = pg.engine; closePostgres = pg.close;
+}, 120_000);
+afterAll(async () => {
+ if (engine) await withEnv({ GBRAIN_HOME: home }, async () => {
+ await disposePersistenceConsumer(engine!); await engine!.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ for (const id of sources) await engine!.executeRaw('DELETE FROM sources WHERE id=$1', [id]);
+ });
+ await closePostgres?.();
+ rmSync(home, { recursive: true, force: true });
+});
+
+test('lane settings follow flag > env > config > 4, clamp to the pool and need bulk groups', async () => {
+ if (!engine) return;
+ expect(await resolveBulkSettings(engine, false)).toMatchObject({ enabled: true, lanes: 4, lanesReason: null });
+ expect(await resolveBulkSettings(engine, false, 1)).toMatchObject({ lanes: 1, lanesReason: 'disabled by --no-lanes' });
+ expect(await resolveBulkSettings(engine, false, 8)).toMatchObject({ lanes: 8, lanesReason: null });
+ expect(await resolveBulkSettings(engine, true, 4)).toMatchObject({ enabled: false, lanes: 1 });
+ await withEnv({ GBRAIN_SYNC_LANES: '2' }, async () => expect(await resolveBulkSettings(engine!, false)).toMatchObject({ lanes: 2 }));
+ await expect(resolveBulkSettings(engine, false, 9)).rejects.toMatchObject({ code: 'invalid_params' });
+});
+
+test('a lease is shared by lanes; an exclusive writer drains and wounds it and gets the lock once the lanes leave', async () => {
+ let locks = 0, released = 0;
+ const native = (): Promise<NativeLockHandle> => { locks++; let done = false; return Promise.resolve({ get released() { return done; }, async release() { done = true; released++; } }); };
+ const path = join(home, 'lease-probe');
+ const a = (await acquireShared(path, native))!, b = (await acquireShared(path, native))!;
+ expect(locks).toBe(1);
+ expect(await yieldLease(path, 0)).toBe(false);
+ expect(leaseDraining(path) && leaseWounded(path)).toBe(true);
+ expect(await acquireShared(path, native)).toBeNull();
+ const waiting = yieldLease(path, 5000);
+ await a.release(); expect(released).toBe(0);
+ await b.release(); expect(released).toBe(1);
+ expect(await waiting).toBe(true);
+ expect(leaseDraining(path)).toBe(false);
+});
+
+test('lanes publish several groups at once and every page still commits, attributed to its own request, in manifest order', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_BULK_SIZE: '4' }, async () => {
+ if (!engine) return;
+ const f = await fixture(engine, notes(80));
+ 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);
+ const rows = await imports(engine, f.id);
+ expect(rows).toHaveLength(80);
+ expect(rows.every(row => row.state === 'committed')).toBe(true);
+ expect(rows.some(row => row.lane)).toBe(true);
+ const attributed = await engine.executeRaw<{ mismatched: boolean }>(`SELECT p.revision_write_request_id IS DISTINCT FROM r.id AS mismatched
+ FROM pages p JOIN persistence_requests r ON r.source_id=p.source_id AND r.slug=p.slug AND r.intent->>'kind'='managed_sync_import' WHERE p.source_id=$1`, [f.id]);
+ expect(attributed).toHaveLength(80);
+ expect(attributed.filter(row => row.mismatched)).toEqual([]);
+ const [cursor] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM op_checkpoints WHERE op='managed-sync' AND (completed_keys->0 ? 'window' OR completed_keys->0 ? 'group') AND completed_keys->0->>'sourceId'=$1", [f.id]);
+ expect(cursor!.n).toBe(0);
+}), 300_000);
+
+test('a failed page under lanes stops the run: earlier pages commit, nothing after it publishes', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SYNC_BULK_SIZE: '4' }, async () => {
+ if (!engine) return;
+ const f = await fixture(engine, notes(60, i => i === 30 ? '---\ntitle: Conflict\nslug: notes/other\n---\nA conflicting identity must not be imported.\n' : null));
+ await engine.setConfig('sync.holds', 'fail');
+ const result = await performSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true, drain: true, lanes: 4 })
+ .finally(() => engine!.unsetConfig('sync.holds'));
+ expect(result.drain).toMatchObject({ outcome: 'blocked' });
+ expect(result.managedWrite?.slug).toBe('notes/n030');
+ const rows = await imports(engine, f.id);
+ const failedAt = rows.findIndex(row => row.slug === 'notes/n030');
+ expect(rows[failedAt]!.state).toBe('failed');
+ expect(rows.slice(0, failedAt).every(row => row.state === 'committed')).toBe(true);
+ expect(rows.slice(failedAt + 1).every(row => row.state === 'cancelled')).toBe(true);
+ for (const row of rows.slice(failedAt + 1)) expect(await engine.getPage(row.slug, { sourceId: f.id })).toBeNull();
+ const laterGroups = rows.slice(failedAt + 1).filter(row => row.grp !== rows[failedAt]!.grp);
+ for (const row of laterGroups) expect(row.error_message).toBe(WINDOW_CANCEL_MESSAGE);
+}), 300_000);
+
+test('lanes and --no-lanes build the same pages and the same links from a cross-linked corpus', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_BULK_SIZE: '4' }, async () => {
+ if (!engine) return;
+ const corpus = notes(48);
+ const laned = await fixture(engine, corpus), serial = await fixture(engine, corpus);
+ const a = await performSync(engine, { sourceId: laned.id, noPull: true, noEmbed: true, drain: true, lanes: 4 });
+ const b = await performSync(engine, { sourceId: serial.id, noPull: true, noEmbed: true, drain: true, lanes: 1 });
+ expect(a.drain).toMatchObject({ outcome: 'synced', bulk: { lanes: { configured: 4 } } });
+ expect(b.drain).toMatchObject({ outcome: 'synced', bulk: { lanes: { configured: 1, reason: 'disabled by --no-lanes' } } });
+ const graph = (source: string) => engine!.executeRaw<{ edge: string }>(`SELECT f.slug||'>'||t.slug AS edge FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id
+ WHERE f.source_id=$1 ORDER BY 1`, [source]).then(rows => rows.map(row => row.edge));
+ const pages = (source: string) => engine!.executeRaw<{ slug: string; hash: string }>('SELECT slug,content_hash AS hash FROM pages WHERE source_id=$1 AND deleted_at IS NULL ORDER BY slug', [source]);
+ expect(await graph(laned.id)).toEqual(await graph(serial.id));
+ expect((await graph(laned.id)).length).toBeGreaterThan(0);
+ expect(await pages(laned.id)).toEqual(await pages(serial.id));
+}), 300_000);