Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(persistence): bounded preparation on the grouped route: per-member clocks, held-set lease, prefix publish, reason-preserving lane fallback (#6278)

garrytan2521bfeb1b6b
diff --git a/src/core/persistence/claim-phase.ts b/src/core/persistence/claim-phase.ts
index 58cb75e146..22dfa97e95 100644
--- a/src/core/persistence/claim-phase.ts
+++ b/src/core/persistence/claim-phase.ts
@@ -43,12 +43,19 @@ export interface ClaimPhaseClock {
step: string | null;
stepSince: number;
waitingOn: WaitingOn;
+ /**
+ * #6278: the preparation's cancellation. `enterClaimStep` checks it at every
+ * boundary; a preparer passes it to a raw statement only when that statement
+ * can block on a lock or a pool reservation and is not a shared memo read
+ * (a signalled statement reserves its own connection and skips the memo).
+ */
+ signal?: AbortSignal;
}
/** The process that holds a claim, as the stamp records it. */
export interface ClaimOwner { kind: string; pid: number; version: string }
-export function startClaimPhase(now = Date.now()): ClaimPhaseClock {
- return { phase: 'preparing', claimedAt: now, since: now, step: null, stepSince: now, waitingOn: 'unknown' };
+export function startClaimPhase(now = Date.now(), signal?: AbortSignal): ClaimPhaseClock {
+ return { phase: 'preparing', claimedAt: now, since: now, step: null, stepSince: now, waitingOn: 'unknown', ...(signal ? { signal } : {}) };
}
export function enterClaimPhase(clock: ClaimPhaseClock, phase: ClaimPhaseName, now = Date.now()): void {
if (clock.phase === phase) return;
@@ -60,11 +67,12 @@ export function enterClaimPhase(clock: ClaimPhaseClock, phase: ClaimPhaseName, n
}
/**
* A preparer's step boundary: names the step and what its await waits on,
- * and throws the preparation's abort reason once the budget has cut it off.
- * `clock` is absent for a preparation outside the consumer (the sync's
- * waiver and origin checks), which still gets the cancellation check.
+ * and throws the preparation's abort reason once the budget has cut it off
+ * (`signal` defaults to the clock's). `clock` is absent for a preparation
+ * outside the consumer (the sync's waiver and origin checks), which still
+ * gets the cancellation check from its own signal.
*/
-export function enterClaimStep(clock: ClaimPhaseClock | undefined, step: string, signal?: AbortSignal, waitingOn: WaitingOn = 'unknown', now = Date.now()): void {
+export function enterClaimStep(clock: ClaimPhaseClock | undefined, step: string, signal: AbortSignal | undefined = clock?.signal, waitingOn: WaitingOn = 'unknown', now = Date.now()): void {
signal?.throwIfAborted();
if (!clock) return;
if (clock.step !== step) { clock.step = step; clock.stepSince = now; }
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index 344222e3b8..9118f4b326 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -694,7 +694,9 @@ export class PersistenceConsumer {
// #6278: every kind has a budget with the switch on; off, only remember and intent-less put_page/edit_page (#5616) keep the 30 s one.
const foregroundMs = this.opts.preparationMs ?? 30_000;
const budget = policy.deadlines ? preparationBudgetMs(row, policy, foregroundMs) : preparationKind(row) === 'foreground' ? foregroundMs : undefined;
- const clock = startClaimPhase();
+ // #6278: the clock carries the preparation's cancellation for `enterClaimStep`; a query takes the signal only on the foreground path (as before).
+ const cancel = new AbortController();
+ const clock = startClaimPhase(Date.now(), cancel.signal);
// #6278: a request already at the attempt limit (a kill loop charged it at each reclaim) is finished without preparing again.
if (policy.deadlines && (row.preparation_attempts ?? 0) >= policy.maxAttempts) {
try {
@@ -705,11 +707,12 @@ export class PersistenceConsumer {
} finally { this.preparing.delete(row.id); this.executing.delete(row.id); }
}
const prep = startPreparation(async signal => {
+ signal.addEventListener('abort', () => cancel.abort(signal.reason), { once: true });
await faultPoint('consumer:preparing', { requestId: row.request_id, sourceId: row.source_id, operation: row.operation, signal });
// Phase 4.3: a single page write prepares against one config read instead of one per key.
return this.prepare(this.engine.kind === 'postgres' && singleWrite(row)
&& await writeSwitchOn(this.engine, 'single_write_group').catch(() => true) ? await preparationConfigView(this.engine) : this.engine,
- row, this.config, budget === undefined ? undefined : signal, clock);
+ row, this.config, budget !== undefined && preparationKind(row) === 'foreground' ? signal : undefined, clock);
}, budget, { onDeadline: () => { observation.deadline_exceeded = true; this.log('preparation', 'deadline_exceeded'); } });
const stop = () => prep.abort({ code: 'consumer_stopping' });
this.abort.signal.addEventListener('abort', stop, { once: true });
@@ -792,11 +795,15 @@ export class PersistenceConsumer {
const rows = [row, ...followers];
for (const member of rows) this.executing.add(member.id);
try {
- return await executeClaimedGroup(this.engine, rows, { hostId: this.hostId, lane, prepare: (member, engine) => this.prepare(engine, member, this.config),
- lease: this.leaseTiming(),
- leftRunning: (work, blocksRoot) => {
- const settled = this.keepUntilSettled(work);
- if (blocksRoot) root.until = settled;
+ return await executeClaimedGroup(this.engine, rows, { hostId: this.hostId, lane,
+ prepare: (member, engine, signal, clock) => this.prepare(engine, member, this.config, signal, clock),
+ lease: this.leaseTiming(), policy: this.policy, foregroundMs: this.opts.preparationMs ?? 30_000,
+ leftRunning: (work, blocksRoot, abandoned) => {
+ if (!blocksRoot) { this.keepUntilSettled(work); return; }
+ // #6278: an abandoned member blocks its root until it settles or the ceiling passes; several abandoned members all hold it.
+ const settled = this.keepAbandoned(work);
+ const block = abandoned ? this.abandonedRootBlock(abandoned.row, abandoned.clock, settled) : settled;
+ root.until = root.until ? Promise.all([root.until, block]).then(() => undefined) : block;
},
settled: done => {
this.executing.delete(done.id);
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 1656d2a40f..2ea9e5e4f5 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -147,8 +147,8 @@ export function transientDatabaseFailure(error: unknown): boolean {
* `storage_error` or an uncounted `database_contention`; classify it before
* `finishUnpublishedFailure`. Null when the error is the preparer's own.
*/
-export type PreparationAbortReason = 'preparation_deadline' | 'consumer_stopping' | 'claim_lost';
-const ABORT_REASONS: ReadonlySet<string> = new Set<PreparationAbortReason>(['preparation_deadline', 'consumer_stopping', 'claim_lost']);
+export type PreparationAbortReason = 'preparation_deadline' | 'consumer_stopping' | 'claim_lost' | 'group_member_waiting';
+const ABORT_REASONS: ReadonlySet<string> = new Set<PreparationAbortReason>(['preparation_deadline', 'consumer_stopping', 'claim_lost', 'group_member_waiting']);
export function preparationAbortReason(error: unknown, signal?: AbortSignal): PreparationAbortReason | null {
const reason = signal?.aborted ? (signal.reason as { code?: unknown } | null)?.code : undefined;
const own = typeof reason === 'string' && ABORT_REASONS.has(reason) ? reason as PreparationAbortReason : null;
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index d8273c2e54..1e32618088 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -38,11 +38,12 @@ 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 { cancelRows, windowPredecessor } from './sync-window.ts';
-import { clearResolvedRecoveries, completeWrite, ENSURE_COUNTERS_SQL, getWriteRequestById, LOCK_COUNTERS_SQL, markRecovering, prepareRecoveries,
+import { clearResolvedRecoveries, completeWrite, ENSURE_COUNTERS_SQL, getWriteRequestById, LOCK_COUNTERS_SQL, markDispatched, markRecovering, prepareRecoveries,
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';
+import { claimPhaseStamp, enterClaimPhase, startClaimPhase, type ClaimPhaseClock } from './claim-phase.ts';
+import { DEFAULT_PREPARATION_POLICY, preparationBudgetMs, startPreparation, type PreparationPolicy, type PreparationRun } from './preparation-budget.ts';
import { setMemberAttribution, withCoordinatedWrite } from './context.ts';
import { requestAttribution } from './attribution.ts';
import { tryAcquirePublicationCapacity } from './pool-capacity.ts';
@@ -54,7 +55,7 @@ import { authorizePageVisibility } from './page-visibility.ts';
import { withFilesystemPublication } from './filesystem-guard.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';
-import { decoratePublicationOutcome, finishUnpublishedFailure, pageRecoveryRecord, persistenceFileHash, publicationPostimage, publishMutation,
+import { decoratePublicationOutcome, finishPreparationStalled, finishUnpublishedFailure, pageRecoveryRecord, persistenceFileHash, preparationAbortReason, publicationPostimage, publishMutation,
publishPersistenceFile, recoverPublication, type PreparedMutation } from './coordinator.ts';
import { pipelined } from '../page-state/transactions.ts';
import { jsonBytes } from './digest.ts';
@@ -435,7 +436,7 @@ export async function completeGroup(tx: BrainEngine, rows: WriteRequest[], outco
), done AS (
UPDATE persistence_requests r SET state='committed',outcome=m.outcome::jsonb,error_code=NULL,error_message=NULL,
completed_at=now(),updated_at=now(),claim_expires_at=NULL,blocked_reason=NULL,
- consumer_version=$6,consumer_host_id=$7::uuid,published_at=now()
+ consumer_version=$6,consumer_host_id=$7::uuid,published_at=now(),preparation_attempts=0
FROM m LEFT JOIN e ON e.request_id=m.id
WHERE r.id=m.id AND r.execution_token=m.token AND r.state='running' AND m.need+COALESCE(e.bytes,0)<=r.terminal_reservation
RETURNING r.*,m.principal_key
@@ -457,20 +458,35 @@ 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;
- /** `engine` answers the members' repeated preparation reads once (see preparationReads). */
- prepare(row: WriteRequest, engine: BrainEngine): Promise<PreparedMutation>;
+ /** `engine` answers the members' repeated preparation reads once (see preparationReads); `signal` and `clock` (#6278) are the member's own. */
+ prepare(row: WriteRequest, engine: BrainEngine, signal?: AbortSignal, clock?: ClaimPhaseClock): Promise<PreparedMutation>;
settled(row: WriteRequest): void;
hostId: string;
hooks?: GroupHooks;
/** #5373: renewal timing for the group's claims (default DEFAULT_CLAIM_LEASE_TIMING). */
lease?: ClaimLeaseTiming;
+ /** #6278: the budgets, ceiling, attempt limit and switch in effect (default: the defaults with deadlines on). */
+ policy?: PreparationPolicy & { deadlines: boolean };
+ /** #6278: the foreground (remember/put_page/edit_page) budget, the consumer's `preparationMs` (default 30 s). */
+ foregroundMs?: number;
/**
* #5373: receives work still running when the group lets go of its claims: the
- * renewal in flight, or (`blocksRoot`) the preparation abandoned after a lost claim.
+ * renewal in flight, or (`blocksRoot`) a preparation abandoned after a lost claim
+ * or (#6278) a deadline; `abandoned` names the member and its clock for the ceiling.
*/
- leftRunning?(work: Promise<unknown>, blocksRoot: boolean): void;
+ leftRunning?(work: Promise<unknown>, blocksRoot: boolean, abandoned?: { row: WriteRequest; clock: ClaimPhaseClock }): void;
}
+/**
+ * The memo rule (#6278): `preparationReads` and `groupReads` answer a read
+ * once for every member, so a member's own signal never reaches a shared
+ * read (the memo skips itself for a signalled statement, and an aborted
+ * member must never reject a sibling's read). A member that must give up on a
+ * shared read races its own signal against the shared promise instead:
+ * `enterClaimStep` at its next boundary throws the member's abort reason.
+ */
+type MemberOutcome = { ok: PreparedMutation } | { error: unknown } | { released: 'preparation_deadline' | 'group_member_waiting' | 'claim_lost' };
+
/**
* Prepares a claimed group (four members at a time), publishes it in one
* transaction when every member qualifies, and otherwise publishes the
@@ -483,46 +499,124 @@ export interface GroupExecution {
* another consumer took over keeps its new claim) and the unfinished
* preparation goes to `leftRunning`, never to publication. Returns whether
* any member settled.
+ *
+ * #6278: each member's budget clock starts when its wave dispatches it (the
+ * wave is marked durably first), and the lease renews the mutable set of
+ * members still held, so one release never reads as a lost group lease. When
+ * member k expires: no later wave is dispatched, the in-flight suffix is
+ * aborted, k is released `preparation_deadline` (charged; finished
+ * `preparation_stalled` when that reaches the limit) and the later members
+ * `group_member_waiting` (not charged), and the contiguous prepared prefix
+ * 0..k-1 publishes. An independent `batch:` group releases only k. An
+ * abandoned member's preparation goes to `leftRunning` with its clock.
*/
export async function executeClaimedGroup(engine: BrainEngine, rows: WriteRequest[], run: GroupExecution): Promise<boolean> {
- const clock = startClaimPhase();
- const lease = startClaimLease(async signal => (await renewGroupClaims(engine, rows, 30_000, signal, claimPhaseStamp(clock, null))).size === rows.length,
- run.lease ?? DEFAULT_CLAIM_LEASE_TIMING);
+ const policy = run.policy ?? { ...DEFAULT_PREPARATION_POLICY, deadlines: true };
+ const foregroundMs = run.foregroundMs ?? 30_000;
+ const groupClock = startClaimPhase();
+ const clocks: Array<ClaimPhaseClock | undefined> = rows.map(() => undefined);
+ const held = new Set(rows.map(row => row.id));
+ const inFlight = new Map<number, PreparationRun<PreparedMutation>>();
+ const preps: Array<PreparationRun<PreparedMutation> | undefined> = rows.map(() => undefined);
+ const stampOf = (i: number) => clocks[i] ? claimPhaseStamp(clocks[i]!, rows[i]!.execution_token) : null;
+ const lease = startClaimLease(async signal => {
+ const live = rows.map((row, i) => [row, i] as const).filter(([row]) => held.has(row.id));
+ if (!live.length) return true;
+ return (await renewGroupClaims(engine, live.map(([row]) => row), 30_000, signal, live.map(([, i]) => stampOf(i)))).size === live.length;
+ }, run.lease ?? DEFAULT_CLAIM_LEASE_TIMING, () => { for (const prep of inFlight.values()) prep.abort({ code: 'claim_lost' }); });
if (run.lane) laneClaimed(run.lane, rows);
+ // A put_pages batch is independent page writes: one page's failure never cancels its siblings.
+ const independent = publicationGroupKey(rows[0]!)?.startsWith('batch:') === true;
+ const prepared: MemberOutcome[] = new Array(rows.length);
+ // The first member whose deadline passed in an ordered group: nothing after it is dispatched or published this pass.
+ let cut: number | null = null;
+ const abandon = (i: number, work: Promise<unknown>) => run.leftRunning?.(work, true, { row: rows[i]!, clock: clocks[i]! });
try {
- const prepared: Array<{ ok: PreparedMutation } | { error: unknown }> = new Array(rows.length);
const reads = preparationReads(engine);
// A put_pages group prepares all of its (at most PAGE_BATCH_GROUP_MAX) pages at once.
- const width = publicationGroupKey(rows[0]!)?.startsWith('batch:') ? PAGE_BATCH_GROUP_MAX : 4;
+ const width = independent ? PAGE_BATCH_GROUP_MAX : 4;
const preparing = (async () => {
- for (let start = 0; start < rows.length; start += width) {
- await Promise.all(rows.slice(start, start + width).map(async (row, offset) => {
- try { prepared[start + offset] = { ok: await run.prepare(row, reads) }; } catch (error) { prepared[start + offset] = { error }; }
+ for (let start = 0; start < rows.length && (independent || cut === null); start += width) {
+ const wave = rows.slice(start, start + width);
+ const now = Date.now();
+ const cancels = wave.map(() => new AbortController());
+ wave.forEach((_row, offset) => { clocks[start + offset] = startClaimPhase(now, cancels[offset]!.signal); });
+ if (policy.deadlines) await markDispatched(engine, wave.map((row, offset) => ({ row, stamp: stampOf(start + offset)! })));
+ const wavePreps = wave.map((row, offset) => {
+ const i = start + offset;
+ const budget = policy.deadlines ? preparationBudgetMs(row, policy, foregroundMs) : undefined;
+ // The member's signal reaches its preparer through its clock (enterClaimStep), never as a blanket statement signal: see the memo rule.
+ const prep = startPreparation(async signal => {
+ signal.addEventListener('abort', () => cancels[offset]!.abort(signal.reason), { once: true });
+ await faultPoint('consumer:preparing', { requestId: row.request_id, sourceId: row.source_id, operation: row.operation, signal });
+ return run.prepare(row, reads, undefined, clocks[i]);
+ }, budget, { onDeadline: () => {
+ if (independent) return;
+ if (cut === null || i < cut) cut = i;
+ for (const [j, other] of inFlight) if (j > i) other.abort({ code: 'group_member_waiting' });
+ } });
+ inFlight.set(i, prep);
+ preps[i] = prep;
+ return prep;
+ });
+ await Promise.all(wavePreps.map(async (prep, offset) => {
+ const i = start + offset;
+ try {
+ const outcome = policy.deadlines ? await prep.outcome : await prep.work.then(result => ({ result }));
+ prepared[i] = 'deadline' in outcome ? { released: 'preparation_deadline' } : { ok: outcome.result };
+ } catch (error) {
+ const reason = preparationAbortReason(error, prep.signal);
+ prepared[i] = reason === 'preparation_deadline' || reason === 'group_member_waiting' || reason === 'claim_lost' ? { released: reason } : { error };
+ } finally { inFlight.delete(i); }
}));
}
})();
if (await lease.whileHeld(preparing) === CLAIM_LOST) {
- run.leftRunning?.(preparing, true);
+ run.leftRunning?.(preparing, true, { row: rows[0]!, clock: groupClock });
await endLostLease(lease);
- for (const row of rows) await releaseUnpublishedClaim(engine, row, 'claim_lost');
+ for (const row of rows) if (held.has(row.id)) await releaseUnpublishedClaim(engine, row, 'claim_lost');
return false;
}
- enterClaimPhase(clock, 'publishing');
- // A put_pages batch is independent page writes: one page's failure never cancels its siblings.
- const independent = publicationGroupKey(rows[0]!)?.startsWith('batch:') === true;
+ let progressed = false;
+ // #6278: the members the deadline took off this pass leave the held set before their release statement runs.
+ const released = new Set<string>();
+ for (let i = 0; i < rows.length; i++) {
+ const row = rows[i]!, outcome = prepared[i];
+ const expired = outcome !== undefined && 'released' in outcome && outcome.released === 'preparation_deadline';
+ const after = !independent && cut !== null && i > cut;
+ if (!expired && !after) continue;
+ held.delete(row.id); released.add(row.id);
+ // A dispatched member the deadline or the suffix abort took off this pass may still run: it blocks the root until it settles or the ceiling passes.
+ if (outcome !== undefined && 'released' in outcome && preps[i]) abandon(i, preps[i]!.work);
+ if (!expired) { await releaseUnpublishedClaim(engine, row, 'group_member_waiting'); continue; }
+ if ((row.preparation_attempts ?? 0) + 1 >= policy.maxAttempts) {
+ const done = await finishPreparationStalled(engine, row, { step: clocks[i]!.step, waiting_on: clocks[i]!.waitingOn, limit: policy.maxAttempts }, true);
+ run.settled(done); progressed = true;
+ continue;
+ }
+ await releaseUnpublishedClaim(engine, row, 'preparation_deadline', { charge: true });
+ }
+ for (const clock of clocks) if (clock) enterClaimPhase(clock, 'publishing');
+ enterClaimPhase(groupClock, 'publishing');
+ const live = rows.map((row, i) => ({ row, i })).filter(({ row }) => !released.has(row.id));
+ if (!live.length) return progressed;
+ const liveRows = live.map(({ row }) => row);
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, run.lane ?? null);
+ if (live.every(({ i }) => 'ok' in prepared[i]!)) {
+ // #6278 lanes: a prefix publishes under the original group's order key, then drops its own begun mark.
+ if (run.lane && liveRows.length < rows.length) await awaitLaneBegin(run.lane, rows);
+ const result = await publishGroup(engine, liveRows, live.map(({ i }) => (prepared[i] as { ok: PreparedMutation }).ok), run.hostId, run.hooks, run.lane ?? null);
+ if (run.lane && liveRows.length < rows.length) run.lane.begun.delete(liveRows.at(-1)!.request_id);
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; }
+ if (run.lane) { const settled = await laneFallback(engine, liveRows, result.reason, run); if (settled !== null) return settled || progressed; }
} else if (run.lane) {
- const settled = await laneFallback(engine, rows, 'failed', run);
- if (settled !== null) return settled;
+ const settled = await laneFallback(engine, liveRows, 'failed', run);
+ if (settled !== null) return settled || progressed;
}
- let progressed = false, stop: 'cancel' | 'release' | null = null;
- for (let i = 0; i < rows.length; i++) {
- let row = rows[i]!;
+ let stop: 'cancel' | 'release' | null = null;
+ for (const { row: member, i } of live) {
+ let row = member;
let current = await getWriteRequestById(engine, row.id);
// A claim the group's file restoration released is taken back, in order, while this pass still owns the worktree.
if (current?.state === 'queued' && requeued.has(row.id) && stop === null) {
@@ -541,6 +635,8 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteReques
run.settled(cancelled); progressed = true; continue;
}
const p = prepared[i]!;
+ // #6278: a member aborted by our own cancellation (never a deadline here) is released, not failed.
+ if ('released' in p) { await releaseUnpublishedClaim(engine, row, p.released === 'claim_lost' ? 'claim_lost' : 'group_member_waiting'); stop ??= independent ? null : 'release'; continue; }
const done = 'ok' in p ? await publishMutation(engine, row, p.ok, run.hostId) : await finishUnpublishedFailure(engine, current, p.error, 'preparation');
run.settled(done);
if (done.state === 'committed') { progressed = true; continue; }
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index a6107daeef..00e3dfd020 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -721,7 +721,8 @@ export async function completeWrite(tx: SqlEngine, row: WriteRequest, state: 'co
error_code=$4,error_message=$5,error_detail=COALESCE($8::text::jsonb,error_detail),completed_at=now(),updated_at=now(),claim_expires_at=NULL,blocked_reason=NULL,
consumer_version=CASE WHEN $2='committed' THEN $6 ELSE consumer_version END,
consumer_host_id=CASE WHEN $2='committed' THEN $7::uuid ELSE consumer_host_id END,
- published_at=CASE WHEN $2='committed' THEN now() ELSE published_at END
+ published_at=CASE WHEN $2='committed' THEN now() ELSE published_at END,
+ preparation_attempts=CASE WHEN $2='committed' THEN 0 ELSE preparation_attempts END
WHERE id=$1::uuid AND $9::bigint+(SELECT bytes FROM effects)<=terminal_reservation RETURNING *),
released AS (UPDATE persistence_counters SET outstanding_count=outstanding_count-1,intent_bytes=intent_bytes-$11
WHERE key=ANY($10::text[]) AND EXISTS (SELECT 1 FROM done))
diff --git a/test/e2e/persistence-group-deadline-postgres.test.ts b/test/e2e/persistence-group-deadline-postgres.test.ts
new file mode 100644
index 0000000000..ed7787cc46
--- /dev/null
+++ b/test/e2e/persistence-group-deadline-postgres.test.ts
@@ -0,0 +1,221 @@
+/**
+ * #6278 on Postgres: the grouped route under preparation deadlines. Protects:
+ * each member's budget clock starts at its dispatch, the group lease keeps
+ * renewing the members still held after one is released (one release never
+ * reads as a lost group lease), member k's expiry releases k charged
+ * (`preparation_deadline`, attempts +1) and the later members uncharged
+ * (`group_member_waiting`), the contiguous prepared prefix publishes, an
+ * independent `batch:` group releases only k, `laneFallback` keeps the expired
+ * member's reason, a late result of an abandoned member never publishes and
+ * the root waits for it, and the expired-claim sweep (the kill case) charges
+ * only the members whose dispatch was marked. Fails when a mid-group release
+ * takes the whole group down as `claim_lost` (#6278's default path), when a
+ * waiting member is charged, or when an undispatched follower is charged.
+ * Pre-#6278 the group path had no deadline at all (a signal-ignoring member
+ * held its root for as long as renewals ran), so every case here failed by
+ * hanging.
+ */
+import { describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import postgres from '#postgres';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { PersistenceConsumer } from '../../src/core/persistence/consumer.ts';
+import { admitWrite, getWriteRequestById } from '../../src/core/persistence/journal.ts';
+import type { PreparedMutation } from '../../src/core/persistence/coordinator.ts';
+import type { WriteRequest } from '../../src/core/persistence/model.ts';
+import { closeLaneRun, openLanes } from '../../src/core/persistence/sync-lanes.ts';
+import { admission, fixtures, initializeFixtures, prepared, selectFixtureHost, type FixtureSource, type HarnessConfig } from '../../scripts/persistence/harness.ts';
+import { assertSafeE2eDatabaseUrl, hasDatabase } from './helpers.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { waitFor } from '../helpers/wait-for.ts';
+
+const DATABASE_URL = process.env.DATABASE_URL ?? '';
+
+async function withBrain(run: (ctx: { engine: PostgresEngine; config: HarnessConfig; sources: FixtureSource[] }) => Promise<void>) {
+ assertSafeE2eDatabaseUrl(DATABASE_URL);
+ const name = `gbrain_test_group_deadline_${randomUUID().replaceAll('-', '')}`;
+ const admin = postgres(DATABASE_URL, { max: 1, prepare: false, onnotice: () => {} });
+ await admin.unsafe(`CREATE DATABASE ${name}`);
+ const url = new URL(DATABASE_URL); url.pathname = `/${name}`;
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-group-deadline-'));
+ const config: HarnessConfig = { kind: 'postgres', root, dataDir: join(root, 'unused'), hostId: randomUUID(),
+ seed: 6278, schedules: 0, operations: 0, sourceIds: ['group-deadline', 'group-deadline-other'], principalIds: [randomUUID()] };
+ const engine = new PostgresEngine();
+ try {
+ await withEnv({ GBRAIN_HOME: root, GBRAIN_PERSISTENCE_FIXTURE_HOME: root }, async () => {
+ await engine.connect({ database_url: url.toString(), poolSize: 6 });
+ await engine.initSchema();
+ selectFixtureHost(config.hostId);
+ await initializeFixtures(engine, config);
+ await run({ engine, config, sources: await fixtures(engine, config) });
+ });
+ } finally {
+ await engine.disconnect();
+ try { await admin.unsafe(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`); } finally { await admin.end(); }
+ rmSync(root, { recursive: true, force: true });
+ }
+}
+
+/** Admits `size` members of one ordered (sync-shaped) or independent (batch) group. */
+async function admitGroup(engine: PostgresEngine, config: HarnessConfig, source: FixtureSource, name: string, size: number,
+ shape: 'ordered' | 'batch', extra: Record<string, unknown> = {}): Promise<WriteRequest[]> {
+ const rows: WriteRequest[] = [];
+ const id = randomUUID();
+ // An ordered group's key is its head's request id, as a bulk sync's is.
+ for (let i = 0; i < size; i++) {
+ const content = `${name} body ${i}`;
+ const requestId = i === 0 ? id : randomUUID();
+ const intent = shape === 'batch' ? { content, page_batch: { id, index: i, size } } : { content, group: id, ...extra };
+ rows.push(await admitWrite(engine, admission(config, source, `${name}/m${i}`, content, 0, { intent, callerIntent: { content }, requestId })));
+ }
+ return rows;
+}
+const stateOf = async (engine: PostgresEngine, rows: WriteRequest[]) => Promise.all(rows.map(async row => {
+ const current = (await getWriteRequestById(engine, row.id))!;
+ return { state: current.state, reason: current.blocked_reason ?? null, attempts: current.preparation_attempts, error: current.error_code ?? null };
+}));
+const pageExists = async (engine: PostgresEngine, slug: string) => (await engine.executeRaw('SELECT 1 FROM pages WHERE slug=$1', [slug])).length > 0;
+const activeRoots = (consumer: PersistenceConsumer) => (consumer as unknown as { activeRoots: Set<string> }).activeRoots;
+
+/** A preparer that hangs on `hung` ids, ignoring its signal, until released; counts the attempts per request. */
+function hangingPreparer(sources: FixtureSource[], hung: Set<string>, release: Promise<void>, attempts: Map<string, number>) {
+ return async (_engine: unknown, row: WriteRequest): Promise<PreparedMutation> => {
+ attempts.set(row.id, (attempts.get(row.id) ?? 0) + 1);
+ if (hung.has(row.id) && attempts.get(row.id) === 1) { await release; }
+ return prepared(row, sources);
+ };
+}
+
+describe.skipIf(!hasDatabase())('grouped preparation deadlines (Postgres, #6278)', () => {
+ for (const position of ['first', 'middle', 'last'] as const) {
+ test(`an ordered group: the ${position} member expiring releases it charged, the later members uncharged, and the prefix publishes`, () => withBrain(async ({ engine, config, sources }) => {
+ const rows = await admitGroup(engine, config, sources[0]!, `ordered-${position}`, 6, 'ordered');
+ const k = position === 'first' ? 0 : position === 'middle' ? 2 : 5;
+ const release = Promise.withResolvers<void>();
+ const attempts = new Map<string, number>();
+ const consumer = new PersistenceConsumer(engine, { engine: 'postgres' }, hangingPreparer(sources, new Set([rows[k]!.id]), release.promise, attempts),
+ { hostId: config.hostId, concurrency: 1, pollMs: 50, renewalIntervalMs: 20, phaseMs: 2_000, preparationMs: 80,
+ preparationBudgets: { maxAttempts: 5, ceilingMs: 60_000 }, onError: () => {} });
+ try {
+ consumer.start();
+ await waitFor(async () => (await getWriteRequestById(engine, rows[k]!.id))?.blocked_reason === 'preparation_deadline', { timeoutMs: 15_000, label: `member ${k} is released at its budget` });
+ await waitFor(async () => (await stateOf(engine, rows.slice(k + 1))).every(s => s.state === 'queued'), { timeoutMs: 15_000, label: 'the suffix is released' });
+ // The prefix publishes (one at a time: the harness rows are not groupable), the suffix waits uncharged, k is charged once.
+ for (let i = 0; i < k; i++) await waitFor(async () => (await getWriteRequestById(engine, rows[i]!.id))?.state === 'committed', { timeoutMs: 15_000, label: `prefix member ${i} commits` });
+ const states = await stateOf(engine, rows);
+ expect(states[k]).toEqual({ state: 'queued', reason: 'preparation_deadline', attempts: 1, error: null });
+ for (let i = k + 1; i < rows.length; i++) expect(states[i]).toEqual({ state: 'queued', reason: 'group_member_waiting', attempts: 0, error: null });
+ // Members after k were never prepared (dispatch stops at the expiry); the same wave's later members may have been aborted.
+ for (let i = Math.ceil((k + 1) / 4) * 4; i < rows.length; i++) expect(attempts.get(rows[i]!.id) ?? 0).toBe(0);
+ // The abandoned member blocks its root until it settles: nothing re-claims k meanwhile and its late result never publishes.
+ await Bun.sleep(300);
+ expect(attempts.get(rows[k]!.id)).toBe(1);
+ expect(activeRoots(consumer).has(rows[0]!.worktree_id!)).toBe(true);
+ expect(await pageExists(engine, rows[k]!.slug)).toBe(false);
+ release.resolve();
+ // Once it settles, the root is free: the released members are claimed again in order and commit on a fresh preparation.
+ for (const row of rows) await waitFor(async () => (await getWriteRequestById(engine, row.id))?.state === 'committed', { timeoutMs: 20_000, label: `${row.slug} commits after the retry` });
+ expect(attempts.get(rows[k]!.id)).toBe(2);
+ const final = await stateOf(engine, rows);
+ // A commit resets the counter.
+ expect(final.map(s => s.attempts)).toEqual(rows.map(() => 0));
+ const [page] = await engine.executeRaw<{ compiled_truth: string }>('SELECT compiled_truth FROM pages WHERE slug=$1', [rows[k]!.slug]);
+ expect(page?.compiled_truth).toBe(`ordered-${position} body ${k}`);
+ } finally { release.resolve(); await consumer.stop(); }
+ }), 90_000);
+ }
+
+ test('an independent batch group releases only the expired member; its siblings publish', () => withBrain(async ({ engine, config, sources }) => {
+ const rows = await admitGroup(engine, config, sources[0]!, 'batch', 4, 'batch');
+ const release = Promise.withResolvers<void>();
+ const attempts = new Map<string, number>();
+ const consumer = new PersistenceConsumer(engine, { engine: 'postgres' }, hangingPreparer(sources, new Set([rows[1]!.id]), release.promise, attempts),
+ { hostId: config.hostId, concurrency: 1, pollMs: 50, renewalIntervalMs: 20, phaseMs: 2_000, preparationMs: 80,
+ preparationBudgets: { maxAttempts: 5, ceilingMs: 60_000 }, onError: () => {} });
+ try {
+ consumer.start();
+ await waitFor(async () => (await getWriteRequestById(engine, rows[1]!.id))?.blocked_reason === 'preparation_deadline', { timeoutMs: 15_000 });
+ for (const i of [0, 2, 3]) await waitFor(async () => (await getWriteRequestById(engine, rows[i]!.id))?.state === 'committed', { timeoutMs: 15_000, label: `sibling ${i} commits` });
+ const states = await stateOf(engine, rows);
+ expect(states[1]).toEqual({ state: 'queued', reason: 'preparation_deadline', attempts: 1, error: null });
+ expect(states.filter((_s, i) => i !== 1).map(s => s.state)).toEqual(['committed', 'committed', 'committed']);
+ release.resolve();
+ await waitFor(async () => (await getWriteRequestById(engine, rows[1]!.id))?.state === 'committed', { timeoutMs: 20_000 });
+ expect(attempts.get(rows[1]!.id)).toBe(2);
+ } finally { release.resolve(); await consumer.stop(); }
+ }), 90_000);
+
+ test('a member whose release reaches the attempt limit is finished failed/preparation_stalled at that release', () => withBrain(async ({ engine, config, sources }) => {
+ const rows = await admitGroup(engine, config, sources[0]!, 'limit', 3, 'ordered');
+ await engine.executeRaw(`UPDATE persistence_requests SET preparation_attempts=1 WHERE id=$1::uuid`, [rows[1]!.id]);
+ const release = Promise.withResolvers<void>();
+ const attempts = new Map<string, number>();
+ const consumer = new PersistenceConsumer(engine, { engine: 'postgres' }, hangingPreparer(sources, new Set([rows[1]!.id]), release.promise, attempts),
+ { hostId: config.hostId, concurrency: 1, pollMs: 50, renewalIntervalMs: 20, phaseMs: 2_000, preparationMs: 80,
+ preparationBudgets: { maxAttempts: 2, ceilingMs: 60_000 }, onError: () => {} });
+ try {
+ consumer.start();
+ await waitFor(async () => (await getWriteRequestById(engine, rows[1]!.id))?.state === 'failed', { timeoutMs: 15_000 });
+ const failed = (await getWriteRequestById(engine, rows[1]!.id))!;
+ expect(failed).toMatchObject({ error_code: 'preparation_stalled', preparation_attempts: 2 });
+ expect(failed.error_detail).toMatchObject({ origin: 'preparation_stall', attempts: 2, limit: 2 });
+ await waitFor(async () => (await getWriteRequestById(engine, rows[0]!.id))?.state === 'committed', { timeoutMs: 15_000 });
+ expect((await stateOf(engine, [rows[2]!]))[0]).toEqual({ state: 'queued', reason: 'group_member_waiting', attempts: 0, error: null });
+ release.resolve();
+ } finally { release.resolve(); await consumer.stop(); }
+ }), 90_000);
+
+ test('under lanes, laneFallback releases the live members as waiting and keeps the expired member\'s preparation_deadline', () => withBrain(async ({ engine, config, sources }) => {
+ const run = randomUUID();
+ const worktreeId = sources[0]!.binding.worktree_id;
+ // A predecessor that is still queued makes laneFallback release the group so the predecessor runs first.
+ const predecessor = await admitWrite(engine, admission(config, sources[1]!, 'lanes/predecessor', 'predecessor body'));
+ await engine.executeRaw(`UPDATE persistence_requests SET worktree_id=NULL,source_id=$2,source_incarnation=$3::uuid WHERE id=$1::uuid`, [predecessor.id, 'group-deadline-other', sources[1]!.incarnation]);
+ const rows = await admitGroup(engine, config, sources[0]!, 'lanes', 3, 'ordered', { lane: run, after: predecessor.request_id });
+ openLanes(worktreeId, run, 2, null);
+ const release = Promise.withResolvers<void>();
+ const attempts = new Map<string, number>();
+ const consumer = new PersistenceConsumer(engine, { engine: 'postgres' }, hangingPreparer(sources, new Set([rows[2]!.id]), release.promise, attempts),
+ { hostId: config.hostId, concurrency: 1, pollMs: 50, renewalIntervalMs: 20, phaseMs: 2_000, preparationMs: 80,
+ preparationBudgets: { maxAttempts: 5, ceilingMs: 60_000 }, onError: () => {} });
+ try {
+ // The predecessor stays queued on its own (database-only) root while the group is exercised.
+ (consumer as unknown as { rootRetryAfter: Map<string, number> }).rootRetryAfter.set(`db:${sources[1]!.incarnation}`, Date.now() + 60_000);
+ consumer.start();
+ await waitFor(async () => (await getWriteRequestById(engine, rows[2]!.id))?.blocked_reason === 'preparation_deadline', { timeoutMs: 15_000 });
+ await waitFor(async () => (await stateOf(engine, rows.slice(0, 2))).every(s => s.state === 'queued'), { timeoutMs: 15_000, label: 'laneFallback releases the live prefix' });
+ const states = await stateOf(engine, rows);
+ expect(states[0]).toEqual({ state: 'queued', reason: 'group_member_waiting', attempts: 0, error: null });
+ expect(states[1]).toEqual({ state: 'queued', reason: 'group_member_waiting', attempts: 0, error: null });
+ expect(states[2]).toEqual({ state: 'queued', reason: 'preparation_deadline', attempts: 1, error: null });
+ } finally { release.resolve(); await consumer.stop(); await closeLaneRun(run, 1_000); }
+ }), 90_000);
+
+ test('the expired-claim sweep charges only the members whose dispatch was marked (the kill case)', () => withBrain(async ({ engine, config, sources }) => {
+ const rows = await admitGroup(engine, config, sources[0]!, 'kill', 6, 'ordered');
+ const release = Promise.withResolvers<void>();
+ const attempts = new Map<string, number>();
+ // Every dispatched member hangs: wave one (members 0-3) is marked preparing, members 4 and 5 are claimed but never dispatched.
+ const owner = new PersistenceConsumer(engine, { engine: 'postgres' }, hangingPreparer(sources, new Set(rows.map(row => row.id)), release.promise, attempts),
+ { hostId: config.hostId, concurrency: 1, pollMs: 60_000, renewalIntervalMs: 60_000, phaseMs: 2_000, preparationMs: 60_000,
+ preparationBudgets: { maxAttempts: 5, ceilingMs: 120_000 }, onError: () => {} });
+ const sweeper = new PersistenceConsumer(engine, { engine: 'postgres' }, async row => prepared(row as never, sources),
+ { hostId: config.hostId, concurrency: 1, pollMs: 60_000, phaseMs: 2_000, onError: () => {} });
+ try {
+ owner.start();
+ await waitFor(() => [0, 1, 2, 3].every(i => attempts.get(rows[i]!.id) === 1), { timeoutMs: 15_000, label: 'the first wave is dispatched' });
+ const stamps = await engine.executeRaw<{ slug: string; phase: string | null; own: boolean }>(`SELECT slug,claim_phase->>'phase' AS phase,
+ claim_phase->>'token'=execution_token::text AS own FROM persistence_requests WHERE id=ANY($1::uuid[]) ORDER BY sequence`, [rows.map(row => row.id)]);
+ expect(stamps.map(s => [s.phase, s.own])).toEqual([['preparing', true], ['preparing', true], ['preparing', true], ['preparing', true], [null, null], [null, null]]);
+ // The owner dies (its renewals never run again); the leases lapse and another consumer's sweep reclaims them.
+ await engine.executeRaw(`UPDATE persistence_requests SET claim_expires_at=now()-interval '1 second' WHERE id=ANY($1::uuid[])`, [rows.map(row => row.id)]);
+ (sweeper as unknown as { rootRetryAfter: Map<string, number> }).rootRetryAfter.set(rows[0]!.worktree_id!, Date.now() + 60_000);
+ await sweeper.tick();
+ const states = await stateOf(engine, rows);
+ expect(states.map(s => [s.state, s.attempts])).toEqual([['queued', 1], ['queued', 1], ['queued', 1], ['queued', 1], ['queued', 0], ['queued', 0]]);
+ } finally { release.resolve(); await owner.stop(); await sweeper.stop(); }
+ }), 90_000);
+});