Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(sync): a foreground write publishes beside the running lane groups; effects defer to lanes instead of wounding them (#5984 G6/G7)

garrytan394ca1008eb5
diff --git a/src/core/persistence/activation.ts b/src/core/persistence/activation.ts
index 5e21b3c819..6ed70270b7 100644
--- a/src/core/persistence/activation.ts
+++ b/src/core/persistence/activation.ts
@@ -126,7 +126,7 @@ export async function activatePersistence(engine: BrainEngine, opts: { confirmQu
const local = [...new Map(initial.filter(binding => binding.owner_host_id === hostId).map(binding => [binding.worktree_id, binding])).values()]
.sort((a, b) => a.worktree_id.localeCompare(b.worktree_id));
for (const binding of local) {
- const lock = await acquireWorktree(binding);
+ const lock = await acquireWorktree(binding, 0, undefined, undefined, { yieldLanes: true });
if (!lock) throw quiescence();
locks.push(lock);
}
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index c52af2eb5c..2f28679d44 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -93,6 +93,8 @@ export class PersistenceConsumer {
/** #5373: preparations and renewals that outlived their claim; stop() drains them before the engine closes. */
private outlived = new Set<Promise<void>>();
private activeRoots = new Set<string>();
+ /** #5984 Phase 4.5: active roots whose only task is a foreground write publishing beside this process's lane groups. */
+ private besideLanes = new Set<string>();
/** #5984 lanes: running lane tasks per worktree. */
private laneTasks = new Map<string, number>();
private foregroundCounts = new Map<string, number>();
@@ -196,7 +198,7 @@ export class PersistenceConsumer {
const retryingTopologies = [...this.topologyRetryAfter.keys()];
const [row] = await this.phase('idle_probe', async signal => this.probeQuery<{ work: boolean }>(this.laneInUse ? undefined : await this.acquireIdleLane(signal), `SELECT (
EXISTS (SELECT 1 FROM persistence_requests r LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id
- WHERE ${claimableWriteSql(foregroundPrioritySql())}
+ WHERE ${claimableWriteSql(foregroundPrioritySql(), '$5::text[]')}
AND ($3::boolean OR r.blocked_reason IS DISTINCT FROM 'writer_pool_capacity'))
OR EXISTS (SELECT 1 FROM persistence_requests r JOIN persistence_worktrees w ON w.id=r.worktree_id
WHERE w.owner_host_id=$1::uuid AND r.recovery IS NOT NULL AND NOT (r.worktree_id::text=ANY($2::text[])))
@@ -219,7 +221,7 @@ export class PersistenceConsumer {
OR EXISTS (SELECT 1 FROM persistence_topology_changes c
JOIN persistence_worktrees w ON w.id=(c.recovery->>'worktreeId')::uuid
WHERE c.recovery IS NOT NULL AND w.owner_host_id=$1::uuid AND NOT (c.id::text=ANY($4::text[])))
- ) AS work`, [this.hostId, excluded, publicationConcurrency(this.engine) > 0, retryingTopologies], signal));
+ ) AS work`, [this.hostId, excluded, publicationConcurrency(this.engine) > 0, retryingTopologies, [...this.laneTasks.keys()]], signal));
return row?.work === true;
}
/**
@@ -447,11 +449,15 @@ export class PersistenceConsumer {
return;
}
const concurrency = this.opts.concurrency ?? 2;
- const attemptedRoots = new Set([...this.activeRoots, ...this.laneTasks.keys(), ...this.rootRetryAfter.keys()]);
+ // #5984: on a root whose lane groups run here, only a foreground write is claimed, to publish beside them.
+ const laneRootKeys = [...this.laneTasks.keys()];
+ const attemptedRoots = new Set([...this.activeRoots, ...this.rootRetryAfter.keys()]);
while (!this.stopping && this.active.size - this.laneTaskCount() < concurrency) {
const claimed = laneClaim();
try {
- const row = await this.phase('claim', () => claimNextWrite(this.engine, this.hostId, this.opts.claimLeaseMs ?? 30_000, [...attemptedRoots], [...this.owesSyncTurn]));
+ // A root where lanes run here owes the sync side no FIFO turn: the write publishes beside its groups.
+ const row = await this.phase('claim', () => claimNextWrite(this.engine, this.hostId, this.opts.claimLeaseMs ?? 30_000, [...attemptedRoots],
+ [...this.owesSyncTurn].filter(key => !laneRootKeys.includes(key)), laneRootKeys.filter(key => !attemptedRoots.has(key))));
if (!row) break;
if (String(row.intent?.kind ?? '').startsWith('managed_sync_')) this.owesSyncTurn.delete(row.worktree_id ?? `db:${row.source_incarnation}`);
else if (row.passed_sync) this.passedSync.add(row.id);
@@ -462,7 +468,9 @@ export class PersistenceConsumer {
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);
- this.track(row, () => this.activeRoots.delete(key), key);
+ // Lane heads keep being claimed beside a foreground write on a lane root (it joins their lease).
+ if (laneRootKeys.includes(key)) this.besideLanes.add(key);
+ this.track(row, () => { this.activeRoots.delete(key); this.besideLanes.delete(key); }, key);
} finally { claimed(); }
}
await this.claimLanes();
@@ -470,7 +478,7 @@ export class PersistenceConsumer {
/** #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;
+ if (this.rootRetryAfter.has(worktreeId) || this.activeRoots.has(worktreeId) && !this.besideLanes.has(worktreeId)) continue;
while (!this.stopping && (this.laneTasks.get(worktreeId) ?? 0) < capacity) {
const claimed = laneClaim();
try {
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index f74069c0e5..bc1b86bcab 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -224,7 +224,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
await releaseUnpublishedClaim(engine, row, 'owner_unavailable');
return (await getWriteRequestById(engine, row.id))!;
}
- lock = await acquireWorktree(binding, 0, undefined, engine);
+ lock = await acquireWorktree(binding, 0, undefined, engine, { yieldLanes: true });
if (!lock) {
await releaseUnpublishedClaim(engine, row, 'writer_busy');
return (await getWriteRequestById(engine, row.id))!;
@@ -390,7 +390,7 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostId
if (!binding || binding.owner_host_id !== hostId) throw opError('owner_unavailable', 'Recovery requires the canonical owner.',
`Request ${row.request_id} in source ${row.source_id} holds a publication recovery record that only the host owning the source's canonical worktree can finish, and this host does not own it. Inspect the owner; its resident writer finishes the recovery.`,
{ fix: ownerStatusFix(row.source_id) });
- const lock = alreadyLocked ? null : await acquireWorktree(binding, 0, undefined, engine);
+ const lock = alreadyLocked ? null : await acquireWorktree(binding, 0, undefined, engine, { yieldLanes: true });
if (!alreadyLocked && !lock) return row;
const releaseCapacity = capacityAlreadyHeld ? null : tryAcquirePublicationCapacity(engine);
try {
diff --git a/src/core/persistence/deactivation.ts b/src/core/persistence/deactivation.ts
index 9cddb93a28..397e0e8bb5 100644
--- a/src/core/persistence/deactivation.ts
+++ b/src/core/persistence/deactivation.ts
@@ -212,7 +212,7 @@ export async function deactivatePersistence(engine: BrainEngine, opts: { dryRun?
if (binding && binding.owner_host_id === hostId && binding.local_path) local.set(binding.worktree_id, binding);
}
for (const binding of [...local.values()].sort((a, b) => a!.worktree_id.localeCompare(b!.worktree_id))) {
- const lock = await acquireWorktree(binding!);
+ const lock = await acquireWorktree(binding!, 0, undefined, undefined, { yieldLanes: true });
if (!lock) throw new OperationError('writer_lock_unavailable', `A local process holds the canonical worktree lock of source '${binding!.source_id}'.`,
'Stop the resident owner on this host (gbrain serve or autopilot), then rerun deactivate.');
locks.push(lock);
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index 0af4272676..71a3f0706e 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -3,8 +3,8 @@
* seam sits at a point where a process death leaves durable state the
* recovery path must finish: publication boundaries, after an effect's side
* effect but before its completion is recorded, before a recovery record is
- * cleared, between sync checkpoints, and after the consumer prepared a
- * claimed request. Production never installs a hook, so every call is a
+ * cleared, between sync checkpoints, after the consumer prepared a
+ * claimed request, and (`lane:applied`) when a lane group has applied its pages and waits for its commit turn. Production never installs a hook, so every call is a
* no-op there; the gate's workers install one that SIGKILLs or stalls the
* process at a chosen point.
*/
@@ -14,7 +14,8 @@ import type { WriteRequest } from './model.ts';
export type PublicationBoundary = Parameters<NonNullable<PublicationHooks['boundary']>>[0];
export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${EffectKind}:mid`
- | 'effect_recovery:before_clear' | 'publication_recovery:before_clear' | 'sync:mid_checkpoint' | 'sync:before_group_admission' | 'sync:mid_waiver_run' | 'consumer:prepared';
+ | 'effect_recovery:before_clear' | 'publication_recovery:before_clear' | 'sync:mid_checkpoint' | 'sync:before_group_admission' | 'sync:mid_waiver_run' | 'consumer:prepared'
+ | 'lane:applied';
export interface FaultDetail { requestId?: string; effectId?: string | number; sourceId?: string; operation?: string | null }
type FaultHook = (point: FaultPoint, detail: FaultDetail) => Promise<void> | void;
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index d8273c2e54..0406dd94fa 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -35,11 +35,11 @@ import type { BrainEngine } from '../engine.ts';
import { OperationError } from '../ops/contract.ts';
import { authorizeStoredRequest, storedAuthorizationReads } from './authority.ts';
import { localHostId } from './identity.ts';
-import { acquireWorktree, acquireWorktreeShared, getWorktreeBinding, guardOwnership } from './ownership.ts';
-import { awaitLaneBegin, awaitLaneTurn, LaneAbort, laneApplyBegin, laneClaimed, laneFinished, stepDownLanes, type LaneState } from './sync-lanes.ts';
+import { acquireWorktree, acquireWorktreeShared, getWorktreeBinding, guardOwnership, joinWorktreeLease } from './ownership.ts';
+import { awaitLaneBegin, awaitLaneTurn, LaneAbort, laneApplyBegin, laneClaimed, laneFinished, lanePolicy, 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';
+ foregroundPriority, publicationGroupKey, reclaimReleasedWrite, releaseUnpublishedClaim, renewGroupClaims } from './journal.ts';
import { principalKey, requestPrincipal, type FileRecoveryRecord, type WriteRequest } from './model.ts';
import { CLAIM_LOST, DEFAULT_CLAIM_LEASE_TIMING, endLostLease, startClaimLease, type ClaimLeaseTiming } from './claim-lease.ts';
import { claimPhaseStamp, enterClaimPhase, startClaimPhase } from './claim-phase.ts';
@@ -178,6 +178,9 @@ export interface GroupHooks {
/** Runs one transaction: `engine.transaction`, or a reserved connection's (Phase 4.4). */
export type TransactionRunner = <T>(fn: (tx: BrainEngine) => Promise<T>) => Promise<T>;
+/** #5984 Phase 4.5: foreground writes publishing beside this process's lane groups, until their recovery record is cleared. */
+const publishingBeside = new Set<string>();
+
export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prepared: PreparedMutation[], hostId = localHostId(),
hooks: GroupHooks = {}, lane: LaneState | null = null, transaction: TransactionRunner = fn => engine.transaction(fn)): Promise<{ done: WriteRequest[] | null; requeued: string[]; reason?: GroupFailure }> {
const head = rows[0];
@@ -186,9 +189,14 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
|| rows.length > 1 && singleWrite(row))) return none;
const binding = await getWorktreeBinding(engine, head.source_id, hostId);
if (!binding || binding.owner_host_id !== hostId || !binding.local_path) 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);
+ // #5984 lanes: lane groups share this process's native lock; a foreground page write (Phase 4.5) joins their
+ // lease and publishes beside them; everything else takes it exclusively.
+ // With this process's lanes open on the worktree but none publishing, it opens the lease for them to join.
+ const beside = !lane && rows.length === 1 && singleWrite(head) && await foregroundPriority(engine);
+ const joined = beside ? joinWorktreeLease(binding) ?? ((lanePolicy(head.worktree_id)?.effective ?? 1) > 1 ? await acquireWorktreeShared(binding, engine) : null) : null;
+ const lock = lane ? await acquireWorktreeShared(binding, engine) : joined ?? await acquireWorktree(binding, 0, undefined, engine, { yieldLanes: true });
if (!lock) return { ...none, reason: 'busy' };
+ if (joined) publishingBeside.add(head.id);
if (lane) lane.coordinationPath ??= binding.coordination_path;
let releaseCapacity: (() => void) | null = null;
const recorded = new Map<number, { row: WriteRequest; record: FileRecoveryRecord; bytes: number }>();
@@ -196,13 +204,16 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
const timed: { apply: ReturnType<typeof laneApplyBegin> | null } = { apply: null };
try {
// The recovery check and the journal limits the recovery record is sized against go out together.
+ // A lane group passes the recovery record of a foreground write this process publishes beside it (Phase 4.5,
+ // another page); any other record still blocks it, and the group releases its claims to retry.
const [blocked, limits] = await pipelined(engine, [
() => 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)]),
+ 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), ...(lane ? publishingBeside : [])]]),
() => prepared.some(member => member.file && !member.noop) ? readJournalLimits(engine) : Promise.resolve(undefined),
]) as [unknown[], JournalLimits | undefined];
- if (blocked.length) return none;
- releaseCapacity = tryAcquirePublicationCapacity(engine, lane ? lane.effective + 1 : undefined);
+ if (blocked.length) return lane ? { ...none, reason: 'busy' } : none;
+ releaseCapacity = tryAcquirePublicationCapacity(engine, lane ? lane.effective + 1 : joined ? Number.POSITIVE_INFINITY : 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++) {
@@ -308,7 +319,7 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
await effects?.();
}, requestAttribution(head));
// #5984 lanes: applied concurrently, committed in manifest order.
- if (lane) { timed.apply?.turn(); await awaitLaneTurn(tx, lane, rows); timed.apply?.turned(); }
+ if (lane) { timed.apply?.turn(); await faultPoint('lane:applied', { requestId: head.request_id, sourceId: head.source_id, operation: head.operation }); await awaitLaneTurn(tx, lane, rows); timed.apply?.turned(); }
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]!;
@@ -346,6 +357,7 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
} finally {
timed.apply?.end(rows.length);
releaseCapacity?.();
+ publishingBeside.delete(head.id);
await lock.release();
}
}
@@ -401,7 +413,9 @@ async function laneFallback(engine: BrainEngine, rows: WriteRequest[], reason: G
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;
+ // A group that found the worktree busy (another holder or no publication capacity) releases its claims and is
+ // claimed again as a lane head; publishing its members one at a time would hold the lanes back.
+ if (prior === 'committed' && reason !== 'busy') return null;
if (prior !== null && ['failed', 'conflict', 'cancelled'].includes(prior)) {
for (const done of await cancelRows(engine, rows)) run.settled(done);
return true;
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index 146d7ee78d..ef0e27f804 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -414,15 +414,19 @@ const NAMES_PAGE = (sync: string, write: string) => `(${sync}.source_id=${write}
* sync row that has not started and does not name its page. Running and recovering rows, recovery records and
* a sync row naming the page still come first; a passed sync row waits until the foreground request finishes.
*/
-const PASSES_QUEUED_SYNC = (earlier: string, r: string, priority: string) => `((${priority}) AND NOT ${SYNC_KIND(r)}
- AND ${earlier}.state='queued' AND ${earlier}.recovery IS NULL AND ${SYNC_KIND(earlier)} AND NOT ${NAMES_PAGE(earlier, r)})`;
+const PASSES_QUEUED_SYNC = (earlier: string, r: string, priority: string, laneRoots: string) => `((${priority}) AND NOT ${SYNC_KIND(r)}
+ AND (${earlier}.state='queued' OR (${earlier}.state='running' AND ${earlier}.intent ? 'lane'
+ AND ${earlier}.worktree_id::text=ANY(${laneRoots})))
+ AND ${earlier}.recovery IS NULL AND ${SYNC_KIND(earlier)} AND NOT ${NAMES_PAGE(earlier, r)})`;
/**
* The rows `claimNextWrite` may claim, over `persistence_requests r LEFT JOIN
* persistence_worktrees w`, with $1 = host id and $2 = excluded root keys and
* `priority` the SQL condition of the `foreground_priority` switch. An
- * unresolved head blocks its entire root.
+ * unresolved head blocks its entire root. `laneRoots` (an SQL text[]) names the worktrees whose lane groups
+ * run in the claiming process: there a foreground write also passes running lane groups that do not name its
+ * page and publishes beside them on the process's shared worktree lock (group-publish.ts).
*/
-export const claimableWriteSql = (priority: string) => `r.state='queued' AND (r.worktree_id IS NULL OR (w.owner_host_id=$1::uuid AND w.state='active'))
+export const claimableWriteSql = (priority: string, laneRoots = "'{}'::text[]") => `r.state='queued' AND (r.worktree_id IS NULL OR (w.owner_host_id=$1::uuid AND w.state='active'))
AND (r.worktree_id IS NULL OR ${refreshFenceClear('r')})
AND NOT (COALESCE(r.worktree_id::text,'db:'||r.source_incarnation::text)=ANY($2::text[]))
AND NOT EXISTS (SELECT 1 FROM persistence_effects blocked WHERE blocked.worktree_id=r.worktree_id AND blocked.recovery IS NOT NULL)
@@ -434,7 +438,7 @@ export const claimableWriteSql = (priority: string) => `r.state='queued' AND (r.
WHERE COALESCE(earlier.worktree_id::text,'db:'||earlier.source_incarnation::text)
=COALESCE(r.worktree_id::text,'db:'||r.source_incarnation::text)
AND earlier.sequence<r.sequence AND earlier.state IN ('queued','running','recovering')
- AND NOT ${PASSES_QUEUED_SYNC('earlier', 'r', priority)})
+ AND NOT ${PASSES_QUEUED_SYNC('earlier', 'r', priority, laneRoots)})
AND NOT ((${priority}) AND ${SYNC_KIND('r')} AND EXISTS (SELECT 1 FROM persistence_requests ahead
WHERE ahead.worktree_id=r.worktree_id AND ahead.sequence>r.sequence AND ahead.state IN ('running','recovering') AND NOT ${SYNC_KIND('ahead')}))`;
/** With the switch on, a claimable foreground request is claimed before the sync rows it passes. */
@@ -466,7 +470,8 @@ export async function hasClaimableWrite(engine: SqlEngine, hostId: string, exclu
* `fifoRoots` (#5984 Phase 4.5) are roots where this consumer owes the sync side a turn: a foreground write it
* claimed ahead of a queued sync row (`passed_sync`) committed since it last claimed a sync row, so there the claim is plain FIFO.
*/
-export async function claimNextWrite(engine: BrainEngine, hostId: string, leaseMs = 30_000, excludeRoots: string[] = [], fifoRoots: string[] = []): Promise<(WriteRequest & { passed_sync?: boolean }) | null> {
+export async function claimNextWrite(engine: BrainEngine, hostId: string, leaseMs = 30_000, excludeRoots: string[] = [], fifoRoots: string[] = [],
+ laneRoots: string[] = []): Promise<(WriteRequest & { passed_sync?: boolean }) | null> {
const first = `(${foregroundPrioritySql()}) AND NOT (COALESCE(r.worktree_id::text,'db:'||r.source_incarnation::text)=ANY($3::text[]))`;
return engine.transactionDirect(async tx => {
// The protocol declaration and the FIFO head read are sent together.
@@ -474,8 +479,10 @@ export async function claimNextWrite(engine: BrainEngine, hostId: string, leaseM
() => declarePersistenceProtocol(tx),
() => tx.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests r
LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id
- WHERE ${claimableWriteSql(`(${first})`)}
- ORDER BY ${CLAIM_ORDER(`(${first})`)} LIMIT 1 FOR UPDATE OF r SKIP LOCKED`, [hostId, excludeRoots, fifoRoots]),
+ WHERE ${claimableWriteSql(`(${first})`, '$4::text[]')}
+ -- On a root whose lane groups run in this process only a foreground write is claimed (beside them).
+ AND NOT (r.worktree_id::text=ANY($4::text[]) AND (${SYNC_KIND('r')} OR NOT (${first})))
+ ORDER BY ${CLAIM_ORDER(`(${first})`)} LIMIT 1 FOR UPDATE OF r SKIP LOCKED`, [hostId, excludeRoots, fifoRoots, laneRoots]),
]) as [unknown, WriteRequest[]];
if (!row) return null;
// `passed_sync`: the claimed row went ahead of a queued sync row of its root.
@@ -516,9 +523,10 @@ export async function claimNextLaneHead(engine: BrainEngine, hostId: string, wor
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)))
- -- #5984 Phase 4.5: no new lane head while a foreground write that may go first is unfinished, except one head
- -- after each foreground commit since this run's last head claim, so a stream of writes cannot starve the drain.
- AND NOT ((${foregroundPrioritySql()}) AND EXISTS (SELECT 1 FROM persistence_requests f WHERE f.worktree_id=r.worktree_id AND f.state IN ('queued','running','recovering')
+ -- #5984 Phase 4.5: no new lane head while a foreground write that may go first waits to be claimed (a claimed
+ -- one publishes beside the lanes), except one head after each foreground commit since this run's last head
+ -- claim, so a stream of writes cannot starve the drain.
+ AND NOT ((${foregroundPrioritySql()}) AND EXISTS (SELECT 1 FROM persistence_requests f WHERE f.worktree_id=r.worktree_id AND f.state IN ('queued','recovering')
AND f.recovery IS NULL AND NOT ${SYNC_KIND('f')}
AND NOT EXISTS (SELECT 1 FROM persistence_requests named WHERE named.worktree_id=f.worktree_id AND named.sequence<f.sequence
AND named.state IN ('queued','running','recovering') AND ${SYNC_KIND('named')} AND ${NAMES_PAGE('named', 'f')}))
@@ -797,9 +805,9 @@ export async function writeHealthFacts(engine: BrainEngine, rows: WriteRequest[]
const roots = [...new Set(pending.map(row => row.worktree_id ?? `db:${row.source_incarnation}`))];
const abort = new AbortController();
const observed_at = new Date().toISOString();
- const query = engine.executeRaw<{ root: string; sequence: string | null; started_sequence: string | null; recovery_required: boolean; owner_unavailable: boolean; inspect_owner: boolean }>(`
+ const query = engine.executeRaw<{ root: string; sequence: string | null; started_sequence: string | null; started_unlaned: string | null; recovery_required: boolean; owner_unavailable: boolean; inspect_owner: boolean }>(`
WITH roots AS (SELECT unnest($1::text[]) AS root)
- SELECT roots.root,head.sequence::text,head.started_sequence::text,COALESCE(head.inspect_owner,false) AS inspect_owner,
+ SELECT roots.root,head.sequence::text,head.started_sequence::text,head.started_unlaned::text,COALESCE(head.inspect_owner,false) AS inspect_owner,
COALESCE(head.recovering,false) OR EXISTS (SELECT 1 FROM persistence_effects e
WHERE e.worktree_id=w.id AND e.recovery IS NOT NULL) AS recovery_required,
w.id IS NOT NULL AND (w.state<>'active' OR w.owner_host_id IS NULL) AS owner_unavailable
@@ -807,13 +815,16 @@ export async function writeHealthFacts(engine: BrainEngine, rows: WriteRequest[]
LEFT JOIN LATERAL (
(SELECT r.sequence,(SELECT s.sequence FROM persistence_requests s WHERE s.worktree_id=w.id
AND (s.state IN ('running','recovering') OR s.recovery IS NOT NULL) ORDER BY s.sequence LIMIT 1) AS started_sequence,
+ (SELECT s.sequence FROM persistence_requests s WHERE s.worktree_id=w.id
+ AND (s.state IN ('running','recovering') OR s.recovery IS NOT NULL)
+ AND NOT (s.state='running' AND s.recovery IS NULL AND s.intent ? 'lane') ORDER BY s.sequence LIMIT 1) AS started_unlaned,
${STUCK_RECOVERY('r')} AS recovering,
r.blocked_reason IN ('unexpected_file_bytes','unexpected_staging_bytes') AS inspect_owner FROM persistence_requests r
WHERE r.worktree_id=w.id AND (r.state IN ('queued','running','recovering') OR r.recovery IS NOT NULL)
ORDER BY r.sequence LIMIT 1)
UNION ALL
(SELECT r.sequence,(SELECT s.sequence FROM persistence_requests s WHERE s.worktree_id IS NULL AND s.source_incarnation=r.source_incarnation
- AND s.state IN ('running','recovering') ORDER BY s.sequence LIMIT 1) AS started_sequence,
+ AND s.state IN ('running','recovering') ORDER BY s.sequence LIMIT 1) AS started_sequence,NULL::bigint AS started_unlaned,
${STUCK_RECOVERY('r')} AS recovering,
r.blocked_reason IN ('unexpected_file_bytes','unexpected_staging_bytes') AS inspect_owner FROM persistence_requests r
WHERE r.worktree_id IS NULL AND r.source_incarnation=CASE WHEN roots.root LIKE 'db:%' THEN substring(roots.root FROM 4)::uuid END
@@ -830,7 +841,8 @@ export async function writeHealthFacts(engine: BrainEngine, rows: WriteRequest[]
for (const row of pending) {
const fact = byRoot.get(row.worktree_id ?? `db:${row.source_incarnation}`);
if (!fact) continue;
- const head = row.state === 'queued' ? fact.sequence : fact.started_sequence;
+ // #5984 Phase 4.5: a foreground write publishing beside running lane groups is not waiting on them.
+ const head = row.state === 'queued' ? fact.sequence : row.worktree_id && !String(row.intent?.kind ?? '').startsWith('managed_sync_') ? fact.started_unlaned : fact.started_sequence;
result.set(row.id, { observed_at, recovery_required: fact.recovery_required,
owner_unavailable: fact.owner_unavailable,
inspect_owner: fact.inspect_owner,
diff --git a/src/core/persistence/ownership.ts b/src/core/persistence/ownership.ts
index 698e99ffd1..ef90fbf429 100644
--- a/src/core/persistence/ownership.ts
+++ b/src/core/persistence/ownership.ts
@@ -13,7 +13,7 @@ import { detectManifestScope, storedManifestScope, worktreeManifest, type Stored
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 { acquireShared, deferToLease, exclusiveAcquired, joinLease, yieldLease } from './worktree-lease.ts';
import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots } from './filesystem-guard.ts';
import { assertPhysicalRoot, claimPhysicalRoot, preparePhysicalRootTransfer, readPhysicalRootReservation, restampPhysicalRoot } from './physical-root.ts';
import { readPhysicalRootStamp } from './physical-root-record.ts';
@@ -131,17 +131,29 @@ export async function claimWorktree(engine: BrainEngine, sourceId: string, path:
* this native lock after database ownership is verified; otherwise it refuses
* with the filled self-transfer commands.
*/
-export async function acquireWorktree(binding: WorktreeBinding, waitMs = 0, signal?: AbortSignal, engine?: BrainEngine): Promise<NativeLockHandle | null> {
+/**
+ * `yieldLanes`: a request publication, recovery or topology change wounds this process's lane lease and waits for
+ * it (worktree-lease.ts `yieldLease`). Without it a try-acquire (no wait) is a background writer (effects): it
+ * reports busy while lanes hold the lease, and the lease drains for it after `DEFER_WAIT_MS`.
+ */
+export async function acquireWorktree(binding: WorktreeBinding, waitMs = 0, signal?: AbortSignal, engine?: BrainEngine,
+ opts: { yieldLanes?: boolean } = {}): 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);
+ if (waitMs <= 0 && !opts.yieldLanes ? !deferToLease(binding.coordination_path) : !await yieldLease(binding.coordination_path, waitMs, signal)) return null;
+ const lock = await lockWorktree(binding, waitMs, signal, engine);
+ if (lock) exclusiveAcquired(binding.coordination_path);
+ return lock;
}
/** #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));
}
+/** #5984 Phase 4.5: joins this process's live lane lease (worktree-lease.ts `joinLease`), or null. */
+export function joinWorktreeLease(binding: WorktreeBinding): NativeLockHandle | null {
+ return binding.local_path && binding.coordination_path ? joinLease(binding.coordination_path) : null;
+}
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 })
diff --git a/src/core/persistence/pre-activation-release.ts b/src/core/persistence/pre-activation-release.ts
index 0fc28d12fc..dd7951e699 100644
--- a/src/core/persistence/pre-activation-release.ts
+++ b/src/core/persistence/pre-activation-release.ts
@@ -62,7 +62,7 @@ export async function releasePreActivationClaims(engine: BrainEngine, opts: { ex
const binding = await getWorktreeBinding(engine, claim.source_id, hostId);
if (!binding || binding.owner_host_id !== hostId || !binding.local_path || locked.has(binding.worktree_id)) continue;
locked.add(binding.worktree_id);
- const lock = await acquireWorktree(binding);
+ const lock = await acquireWorktree(binding, 0, undefined, undefined, { yieldLanes: true });
if (!lock) throw new OperationError('writer_lock_unavailable', `A local process holds the worktree lock of claimed source '${claim.source_id}'.`,
'Stop the gbrain process on this host that holds it (gbrain serve or autopilot), then rerun deactivate.');
locks.push(lock);
diff --git a/src/core/persistence/skill-activation.ts b/src/core/persistence/skill-activation.ts
index ae668d09b5..086c7fa314 100644
--- a/src/core/persistence/skill-activation.ts
+++ b/src/core/persistence/skill-activation.ts
@@ -41,7 +41,7 @@ export async function activateSharedSkillPersistence(engine: BrainEngine,
const locks: NativeLockHandle[] = [];
try {
for (const binding of [...new Map(initial.map(row => [row.worktree_id, row])).values()]) {
- const lock = await acquireWorktree(binding);
+ const lock = await acquireWorktree(binding, 0, undefined, undefined, { yieldLanes: true });
if (!lock) throw quiescence();
locks.push(lock);
}
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 45323cc6ad..80ca557156 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -564,8 +564,10 @@ type FreezeAt = (base: Cursor) => (index: number) => Promise<Pending | null>;
/** The most consecutive no-op entries one waiver transaction passes. */
const WAIVER_RUN_MAX = 64;
+/** How many entries after a waived head are frozen and screened at once. */
+const WAIVER_SCREEN_WIDTH = 8;
/**
- * #5984 Phase 3: when the frozen head would be waived, freezes and screens the entries after it four at a time
+ * #5984 Phase 3: when the frozen head would be waived, freezes and screens the entries after it eight at a time
* (stopping at the first that would not be waived, is held, is overtaken, refuses to freeze, or at the checkpoint)
* and waives the run in one transaction, without a `pending` cursor save per entry. Returns null to take the
* per-entry path for the head (its screen admits it, or the run's transaction validated nothing or timed out);
@@ -579,14 +581,19 @@ async function waiveRun(engine: BrainEngine, cursor: Cursor, head: Pending, key:
assertActive();
const run: WaiverRunEntry[] = [{ pending: head, waived: first }];
const max = Math.max(1, Math.min(WAIVER_RUN_MAX, limit));
+ // Each entry is frozen and screened in its own chain, WAIVER_SCREEN_WIDTH at a time (reads only, so the entries
+ // past the first that is not waived are discarded unused).
extend: for (let next = cursor.index + 1; run.length < max && next < cursor.entries.length;) {
- const batch = Array.from({ length: Math.min(4, max - run.length, cursor.entries.length - next) }, (_, i) => next + i);
- const frozen = await Promise.all(batch.map(index => freezeEntry(engine, { ...cursor, index }, key, assertActive, frozenRun).catch(() => null)));
- const screened = await Promise.all(frozen.map((entry, i) => entry && !('hold' in entry) && !entry.rebound
- ? screenWaiver(engine, { ...cursor, index: batch[i]! }, entry, config).catch(() => null) : null));
- for (const [i, waived] of screened.entries()) {
- if (!waived) break extend;
- run.push({ pending: frozen[i] as Pending, waived });
+ const batch = Array.from({ length: Math.min(WAIVER_SCREEN_WIDTH, max - run.length, cursor.entries.length - next) }, (_, i) => next + i);
+ const screened = await Promise.all(batch.map(async index => {
+ const entry = await freezeEntry(engine, { ...cursor, index }, key, assertActive, frozenRun).catch(() => null);
+ if (!entry || 'hold' in entry || entry.rebound) return null;
+ const waived = await screenWaiver(engine, { ...cursor, index }, entry, config).catch(() => null);
+ return waived ? { pending: entry as Pending, waived } : null;
+ }));
+ for (const member of screened) {
+ if (!member) break extend;
+ run.push(member);
}
next += batch.length;
}
@@ -634,7 +641,9 @@ function groupSize(cursor: Cursor, bulk: BulkPass): number {
const first = !bulk.formed && !(cursor.counts.added + cursor.counts.modified + cursor.counts.deleted);
bulk.formed = (bulk.formed ?? 0) + 1;
return nextGroupSize(bulk.settings, lanes ? laneApplyMsPerMember(cursor.binding.worktree_id) : bulk.perMemberMs,
- { first, foreground: bulk.foregroundAt !== undefined && performance.now() - bulk.foregroundAt < FOREGROUND_BUDGET_RECENT_MS });
+ // With foreground priority a foreground write publishes beside lane groups instead of waiting for them, so
+ // groups keep their full budget; without it they shrink while foreground writes are recent.
+ { first, foreground: !bulk.foregroundFirst && bulk.foregroundAt !== undefined && performance.now() - bulk.foregroundAt < FOREGROUND_BUDGET_RECENT_MS });
}
/**
* #5984 Phase 1: admits a group's requests and saves the cursor that records them in one transaction: the
diff --git a/src/core/persistence/worktree-lease.ts b/src/core/persistence/worktree-lease.ts
index eba637d1dc..fae7e86579 100644
--- a/src/core/persistence/worktree-lease.ts
+++ b/src/core/persistence/worktree-lease.ts
@@ -28,14 +28,42 @@ const leases = new Map<string, Lease>();
/** A native lock acquisition in flight per path: lanes arriving meanwhile wait for it and join the lease it creates. */
const opening = new Map<string, Promise<unknown>>();
+/**
+ * Background writers (effects) that found a live lease: since when each waits. They never wound the lanes; the
+ * lease drains once one has waited `DEFER_WAIT_MS`, and no new lease starts until the writer took the lock (or
+ * `DEFER_HOLD_MS` passed without it retrying).
+ */
+const deferred = new Map<string, number>();
+/** How long a background writer waits for running lanes before the lease drains for it. */
+export const DEFER_WAIT_MS = 10_000;
+const DEFER_HOLD_MS = 5_000;
+
/** 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;
+ const waiting = deferred.get(path);
+ if (!lease) {
+ if (waiting === undefined) return false;
+ if (Date.now() - waiting < DEFER_WAIT_MS + DEFER_HOLD_MS) return true;
+ deferred.delete(path);
+ return false;
+ }
+ if (!lease.draining && (Date.now() - lease.since >= LEASE_TURN_MS || waiting !== undefined && Date.now() - waiting >= DEFER_WAIT_MS)) lease.draining = true;
return lease.draining;
}
+/**
+ * #5984: a background writer's try-acquire (no wait, no yield) on a worktree whose lanes hold this process's
+ * lease. Records that it waits and reports busy, without wounding the lanes; true when there is no lease.
+ */
+export function deferToLease(path: string): boolean {
+ if (!leases.has(path)) return true;
+ if (!deferred.has(path)) deferred.set(path, Date.now());
+ return false;
+}
+/** An exclusive writer took the native lock: a deferred writer no longer holds back new lanes. */
+export function exclusiveAcquired(path: string): void { deferred.delete(path); }
+
/** 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;
@@ -73,6 +101,18 @@ export async function acquireShared(path: string, acquire: () => Promise<NativeL
return share(path, lease);
}
+/**
+ * #5984 Phase 4.5: a foreground page write joins this process's live lane lease and publishes beside the lane
+ * groups (they are database-only, so its file is the only one written under the lease). Null without a live,
+ * unwounded lease; the caller then takes the lock exclusively.
+ */
+export function joinLease(path: string): NativeLockHandle | null {
+ const live = leases.get(path);
+ if (!live || live.wounded || live.holders === 0 || live.lock.released) return null;
+ live.holders++;
+ return share(path, live);
+}
+
function share(path: string, lease: Lease): NativeLockHandle {
let released = false;
return {
diff --git a/test/managed-sync-foreground-priority.test.ts b/test/managed-sync-foreground-priority.test.ts
index 4c630eb897..8ab3253ba9 100644
--- a/test/managed-sync-foreground-priority.test.ts
+++ b/test/managed-sync-foreground-priority.test.ts
@@ -89,12 +89,26 @@ afterAll(async () => {
* Starts a drain, waits until it has sync groups queued that nobody claimed, then writes `slug` from another
* process. Returns the queued sync rows admitted before the write, the drain's claims and the final rows.
*/
-async function writeDuringDrain(lanes: number, slug: (queued: Row[]) => string) {
+async function writeDuringDrain(lanes: number, slug: (queued: Row[]) => string, laneHold = 0) {
const e = engine!, source = await fixture(e, 64);
const recorder = recordClaims(e);
- // Each sync page holds its group open a little before commit, so groups stay queued while the writer starts.
- const hold = 150;
- installFaultHook(async (point, detail) => { if (point === 'publication:before_commit' && detail.sourceId === source) await Bun.sleep(hold); });
+ // Each sync page holds its group open a little before commit, so groups stay queued while the writer starts. With
+ // `laneHold`, once the write is sent each lane group that has applied its pages holds before its commit turn (no
+ // counter lock held) until the write commits or `laneHold` ms pass, and `beside` records, for each foreground
+ // publication in this process, whether a lane group was then open.
+ let laneOpen = 0, armed = false;
+ const beside: boolean[] = [];
+ const written = Promise.withResolvers<void>();
+ installFaultHook(async (point, detail) => {
+ if (detail.sourceId !== source) return;
+ if (point === 'publication:before_commit' && detail.operation !== 'submit_job') beside.push(laneOpen > 0);
+ if (point === 'publication:after_commit' && detail.operation !== 'submit_job') written.resolve();
+ if (laneHold && armed && point === 'lane:applied') {
+ laneOpen++;
+ try { await Promise.race([written.promise, Bun.sleep(laneHold)]); } finally { laneOpen--; }
+ }
+ if (!laneHold && point === 'publication:before_commit' && detail.operation === 'submit_job') await Bun.sleep(150);
+ });
try {
const drain = performSync(e, { sourceId: source, noPull: true, noEmbed: true, noExtract: true, drain: true, lanes });
let queued: Row[] = [];
@@ -109,6 +123,9 @@ async function writeDuringDrain(lanes: number, slug: (queued: Row[]) => string)
return all.some(row => row.state === 'committed') && (lanes > 1 ? queued.length >= 4 : all.some(row => row.state === 'running' && row.kind?.startsWith('managed_sync_')));
});
const target = slug(queued.length ? queued : await rows(e, source).then(all => all.filter(row => row.state === 'queued')));
+ armed = true;
+ // With `laneHold`, the write is sent while a lane group holds the worktree lease, so only the drain's process can publish it.
+ if (laneHold) await until(async () => laneOpen > 0);
writeFileSync(go, target);
let before: Row[] = [];
await until(async () => {
@@ -123,7 +140,7 @@ async function writeDuringDrain(lanes: number, slug: (queued: Row[]) => string)
});
const [written] = await finish();
const result = await drain;
- return { source, target, before, written: written!, result, claims: recorder.claims, final: await rows(e, source) };
+ return { source, target, before, written: written!, result, claims: recorder.claims, final: await rows(e, source), beside };
} finally { recorder.restore(); installFaultHook(undefined); }
}
@@ -137,16 +154,30 @@ for (const lanes of [2, 1]) {
// With lanes, groups admitted ahead were queued when the write arrived; it still went first.
if (lanes > 1) expect(run.before.length).toBeGreaterThan(0);
const put = run.final.find(row => row.slug === run.target)!;
- // No sync group started (its head chosen) after the write's admission committed and before the write committed.
- // `created` is the admission transaction's start: a claim choosing its row before the commit cannot see the write.
+ // No sync group started (its head chosen) after the write's admission committed and before the write was claimed
+ // (with lanes, a claimed write publishes beside the lane groups, so they may start again) or, without lanes,
+ // committed. `created` is the admission transaction's start: a claim choosing its row before the commit cannot see the write.
expect(run.written.admitted).toBeGreaterThanOrEqual(put.created - 5);
+ const windowEnd = lanes > 1 ? run.claims.get(put.id) ?? put.completed! : put.completed!;
const heads = run.final.filter(row => row.kind?.startsWith('managed_sync_') && (row.grp ?? row.request_id) === row.request_id);
- const early = heads.filter(row => { const claimed = run.claims.get(row.id) ?? Infinity; return claimed >= run.written.admitted! && claimed < put.completed!; }).map(row => row.slug);
+ const early = heads.filter(row => { const claimed = run.claims.get(row.id) ?? Infinity; return claimed >= run.written.admitted! && claimed < windowEnd; }).map(row => row.slug);
expect(early).toEqual([]);
expect(run.final.filter(row => row.kind?.startsWith('managed_sync_import')).every(row => row.state === 'committed')).toBe(true);
}), 300_000);
}
+test('a write publishes beside the running lane groups instead of waiting for them, and the lanes keep starting groups', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_BULK_SIZE: '4' }, async () => {
+ if (!engine) return;
+ resetWriteSwitches();
+ const run = await writeDuringDrain(2, () => 'notes/beside-lanes', 20_000);
+ expect(run.written.state).toBe('committed');
+ expect(run.result.status).toBe('first_sync');
+ const put = run.final.find(row => row.slug === run.target)!;
+ // The drain's process published the write while a lane group's transaction was open in it.
+ expect(run.beside).toEqual([true]);
+ expect(run.final.filter(row => row.kind?.startsWith('managed_sync_import')).every(row => row.state === 'committed')).toBe(true);
+}), 300_000);
+
test('a write to a page a queued group names waits for that group and settles after it, in order', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_BULK_SIZE: '4' }, async () => {
if (!engine) return;
resetWriteSwitches();
diff --git a/test/managed-sync-lanes.test.ts b/test/managed-sync-lanes.test.ts
index 87c73a2885..6384c37dd8 100644
--- a/test/managed-sync-lanes.test.ts
+++ b/test/managed-sync-lanes.test.ts
@@ -15,7 +15,7 @@ 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 { acquireShared, DEFER_WAIT_MS, deferToLease, exclusiveAcquired, joinLease, 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';
import { installFaultHook } from '../src/core/persistence/fault-points.ts';
@@ -118,6 +118,42 @@ test('a lease is shared by lanes; an exclusive writer drains and wounds it and g
expect(leaseDraining(path)).toBe(false);
});
+test('a background writer never wounds the lanes: the lease drains for it after the defer wait, and no new lease starts until it has the lock', async () => {
+ const native = (): Promise<NativeLockHandle> => { let done = false; return Promise.resolve({ get released() { return done; }, async release() { done = true; } }); };
+ const path = join(home, 'lease-defer');
+ const start = Date.now();
+ try {
+ const lane = (await acquireShared(path, native))!;
+ expect(deferToLease(path)).toBe(false);
+ expect(leaseWounded(path) || leaseDraining(path)).toBe(false);
+ setSystemTime(new Date(start + DEFER_WAIT_MS));
+ expect(leaseDraining(path)).toBe(true);
+ expect(leaseWounded(path)).toBe(false);
+ await lane.release();
+ // Between leases the waiting writer goes first: lanes do not open a new lease until it took the lock.
+ expect(leaseDraining(path)).toBe(true);
+ expect(deferToLease(path)).toBe(true);
+ exclusiveAcquired(path);
+ expect(leaseDraining(path)).toBe(false);
+ } finally { setSystemTime(); }
+});
+
+test('a foreground write joins a live lane lease and keeps it open until it leaves; it never takes a wounded or absent one', async () => {
+ let released = 0;
+ const native = (): Promise<NativeLockHandle> => { let done = false; return Promise.resolve({ get released() { return done; }, async release() { done = true; released++; } }); };
+ const path = join(home, 'lease-join');
+ expect(joinLease(path)).toBeNull();
+ const lane = (await acquireShared(path, native))!;
+ const write = joinLease(path)!;
+ expect(write).not.toBeNull();
+ await lane.release(); expect(released).toBe(0);
+ await write.release(); expect(released).toBe(1);
+ const again = (await acquireShared(path, native))!;
+ expect(await yieldLease(path, 0)).toBe(false);
+ expect(joinLease(path)).toBeNull();
+ await again.release();
+});
+
test('lanes that start together share one native lock instead of all but one reporting busy', async () => {
let held = false, locks = 0;
const native = async (): Promise<NativeLockHandle | null> => {
diff --git a/test/persistence-diagnostics.test.ts b/test/persistence-diagnostics.test.ts
index 86379b72c2..7bf5581e14 100644
--- a/test/persistence-diagnostics.test.ts
+++ b/test/persistence-diagnostics.test.ts
@@ -182,6 +182,37 @@ test('#5984 4.5: health never reports an overtaking claimed write as waiting, no
}
});
+test('#5984 4.5: a foreground write publishing beside running lane groups is not reported waiting on them', async () => {
+ for (const engine of engines) {
+ await disposePersistenceConsumer(engine);
+ const ctx: OperationContext = { engine, config: { engine: engine.kind }, sourceId: 'default',
+ remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } };
+ await initializeLocalPersistence(ctx);
+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'persistence.limits.%'");
+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation FROM sources WHERE id='default'");
+ const admit = async (slug: string, intent: Record<string, unknown>) => {
+ const authority = await submissionAuthority(ctx, 'put_page', 'default', source.incarnation, slug);
+ return admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId: 'default',
+ sourceIncarnation: source.incarnation, slug, requestId: randomUUID(), callerIntent: {}, intent });
+ };
+ const lane = await admit('inbox/lane-group', { kind: 'managed_sync_import', content: 'a', lane: randomUUID() });
+ const foreground = await admit('inbox/beside-foreground', { content: 'b' });
+ const worktree = randomUUID();
+ await engine.executeRaw("INSERT INTO persistence_worktrees(id,owner_host_id,state) VALUES($1,$2,'active')", [worktree, randomUUID()]);
+ await engine.executeRaw('UPDATE persistence_requests SET worktree_id=$2 WHERE id=ANY($1::uuid[])', [[lane.id, foreground.id], worktree]);
+ await engine.executeRaw("UPDATE persistence_requests SET state='running',execution_token=gen_random_uuid() WHERE id=ANY($1::uuid[])", [[lane.id, foreground.id]]);
+ const earlier = async () => {
+ const rows = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid', [foreground.id]);
+ return (await writeHealthFacts(engine, rows)).get(foreground.id)?.earlier_write;
+ };
+ expect(await earlier()).toBe(false);
+ // A running sync row outside a lane run (the single path, which holds the worktree alone) still comes first.
+ await engine.executeRaw("UPDATE persistence_requests SET intent=intent-'lane' WHERE id=$1::uuid", [lane.id]);
+ expect(await earlier()).toBe(true);
+ await engine.executeRaw("UPDATE persistence_requests SET state='cancelled',execution_token=NULL,completed_at=now() WHERE id=ANY($1::uuid[])", [[lane.id, foreground.id]]);
+ }
+});
+
test('#6275: a publication in progress with its before-image record is not recovery; a recovering head or a lost claim is', async () => {
for (const engine of engines) {
await disposePersistenceConsumer(engine);