Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

refactor(persistence): our own implementation of the #5373 fix (#5373)

time-attackb34fc348a712
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index f64b1d5939..dc4230ca69 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -28,7 +28,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers
- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention.
-- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier. Claims are renewed every `renewalIntervalMs` (10 s) under a `phaseMs` deadline; a renewal that reports the claim gone, fails or outlives its deadline during preparation loses the claim: on the single route the preparation is raced against that loss and aborted, on the grouped and lane route (`executeClaimedGroup` in `group-publish.ts`) any member's loss abandons the group. The still-held claims are released unpublished (`claim_lost`, token-fenced, so a competing consumer's claim is never reset), the abandoned preparation is never published, its root (or lane slot) stays held until it settles so the same root cannot overtake it, and `stop()` drains abandoned preparations and renewals before engine close. Tests: `test/persistence-consumer-scheduling.test.ts`, `test/e2e/persistence-consumer-claim-loss.test.ts`.
+- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier. Both the single route and the grouped/lane route (`executeClaimedGroup` in `group-publish.ts`) prepare under a claim lease (`claim-lease.ts`: a renewal every `renewalIntervalMs`, default 10 s, each bounded by `phaseMs`); the claim is lost the first time a renewal says it is gone, throws or overruns, and `whileHeld` stops waiting on the preparation at that moment (the single route also aborts it). The claims still ours are released unpublished with `claim_lost` (token-fenced, so a consumer that took one over keeps it); the abandoned preparation is never published and keeps its root or lane slot until it settles, while the consumer slot frees at once. Renewals are never awaited on the way out: `stop()` drains abandoned preparations and in-flight renewals before engine close. Tests: `test/persistence-claim-lease.test.ts`, `test/persistence-consumer-scheduling.test.ts`, `test/e2e/persistence-consumer-claim-loss.test.ts`.
- `src/core/persistence/health.ts` — pure advisory age/reason/action policy shared by receipts and trusted diagnostics. The nested public contract is optional, validated and explicitly allowlisted; thresholds are 30/120 seconds and polls 1/5/30 seconds. The journal batches at most 100 authorized receipts into one projected root query with a 500ms caller budget, retaining one in-flight query per engine until settlement. Database-only pending lookups use a partial source-incarnation/sequence index shared by both engines. Synchronous service reads coalesce only for the same request ID, retain at most four unresolved reads per engine until settlement, and permit cancellation only by the read's initiating waiter or shutdown. No health observation changes authority or durable state. Real authenticated legacy/OAuth recovery and the synthetic three-client import live in `test/e2e/persistence-http-liveness.test.ts`.
diff --git a/src/core/persistence/claim-lease.ts b/src/core/persistence/claim-lease.ts
new file mode 100644
index 0000000000..329cdbc805
--- /dev/null
+++ b/src/core/persistence/claim-lease.ts
@@ -0,0 +1,84 @@
+/**
+ * Keeps a consumer's write claim (or a publication group's claims) alive
+ * while it prepares, and turns every way of losing it into one signal.
+ *
+ * A claim is renewed on a fixed cadence. Each renewal runs under its own
+ * deadline; the claim counts as lost the first time a renewal reports it no
+ * longer holds the claim, rejects, or outlives that deadline (the renewal is
+ * then cancelled through its signal). Callers race their preparation against
+ * `lost` so a claim another consumer has taken over (or one whose renewal
+ * hangs on a row lock) never keeps them waiting on that preparation.
+ *
+ * `end()` stops renewing and never waits. It returns the renewal still in
+ * flight, if any, so the owner can keep it tracked until it settles (the
+ * consumer drains such work in `stop()` before the engine closes).
+ */
+
+export interface ClaimLeaseTiming {
+ /** Gap between renewals. */
+ everyMs: number;
+ /** How long one renewal may take before the claim is treated as lost. */
+ deadlineMs: number;
+}
+
+export const DEFAULT_CLAIM_LEASE_TIMING: Readonly<ClaimLeaseTiming> = { everyMs: 10_000, deadlineMs: 5_000 };
+
+/** What `whileHeld` yields when the claim is lost before the work finishes. */
+export const CLAIM_LOST: unique symbol = Symbol('claim_lost');
+
+export interface ClaimLease {
+ /** Resolves (it never rejects) when the claim is first found lost. */
+ readonly lost: Promise<void>;
+ /** False from the moment the claim is found lost. */
+ readonly held: boolean;
+ /**
+ * Settles with `work`'s own outcome (a rejection propagates), or with
+ * CLAIM_LOST if the claim is lost first. `work` keeps running either way;
+ * after CLAIM_LOST the caller owns it and must never publish its result.
+ */
+ whileHeld<T>(work: Promise<T>): Promise<T | typeof CLAIM_LOST>;
+ /** Stops renewing; returns the in-flight renewal (settles, never rejects) for the owner to track. */
+ end(): Promise<void> | undefined;
+}
+
+/**
+ * Starts renewing. `renew` resolves true while every claim it covers is still
+ * ours. `onLost` runs synchronously before `lost` resolves, so a caller can
+ * abort its preparation ahead of anything awaiting `lost`.
+ */
+export function startClaimLease(renew: (signal: AbortSignal) => Promise<boolean>, timing: ClaimLeaseTiming, onLost?: () => void): ClaimLease {
+ let held = true;
+ let ended = false;
+ let inFlight: Promise<void> | undefined;
+ const signal = Promise.withResolvers<void>();
+ const markLost = () => {
+ if (!held) return;
+ held = false;
+ onLost?.();
+ signal.resolve();
+ };
+ const renewOnce = () => {
+ if (ended || inFlight) return;
+ const cancel = new AbortController();
+ const overrun = setTimeout(() => { markLost(); cancel.abort(); }, timing.deadlineMs);
+ const attempt: Promise<void> = renew(cancel.signal)
+ .then(stillOurs => { if (!stillOurs) markLost(); }, markLost)
+ .finally(() => {
+ clearTimeout(overrun);
+ if (inFlight === attempt) inFlight = undefined;
+ });
+ inFlight = attempt;
+ };
+ const cadence = setInterval(renewOnce, timing.everyMs);
+ cadence.unref?.();
+ return {
+ lost: signal.promise,
+ get held() { return held; },
+ whileHeld: <T>(work: Promise<T>) => Promise.race([work, signal.promise.then((): typeof CLAIM_LOST => CLAIM_LOST)]),
+ end() {
+ ended = true;
+ clearInterval(cadence);
+ return inFlight;
+ },
+ };
+}
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index 2f4c1a230a..2ed8420ac3 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -4,6 +4,7 @@ import { CLAIMABLE_WRITE_SQL, claimGroupFollowers, claimNextLaneHead, claimNextW
import { finishUnpublishedFailure, publishMutation, recoverPublication, type PreparedMutation } from './coordinator.ts';
import { localHostId } from './identity.ts';
import { executeClaimedGroup, PAGE_BATCH_GROUP_MAX } from './group-publish.ts';
+import { CLAIM_LOST, DEFAULT_CLAIM_LEASE_TIMING, startClaimLease, type ClaimLeaseTiming } from './claim-lease.ts';
import { isTerminal, type WriteRequest } from './model.ts';
import { refreshManagedFilesystemRoots } from './filesystem-guard.ts';
import { PROJECTION_RETRY_READY_SQL, rebuildPendingPageProjections } from '../page-state/projections.ts';
@@ -22,6 +23,8 @@ import { faultPoint } from './fault-points.ts';
import { releaseAbandonedClaims } from './effect-journal.ts';
type PhaseObservation = { name: string; started_at: string; deadline_exceeded: boolean; attempt: number; first_conn_ms?: number };
+/** #5373: set by a task that abandons a still-running preparation after losing its claim; its root is freed only once `until` settles. */
+type RootHold = { until?: Promise<void> };
/** When this process started; on PGLite no claim written earlier can belong to a live owner. */
const PROCESS_STARTED_AT = new Date(performance.timeOrigin);
/** #5801: the phase a connection checkout belongs to, carried through its async chain. */
@@ -69,10 +72,8 @@ export class PersistenceConsumer {
private idleLane: { conn: ReservedConnection; release: () => Promise<void> } | undefined;
private idleLaneRetryAt = 0;
private active = new Set<Promise<void>>();
- /** #5373: preparations and renewals left running after a claim loss; stop() drains them before engine close. */
- private abandoned = new Set<Promise<unknown>>();
- /** #5373: per claimed head row, the abandoned preparation its root (or lane slot) waits for before release. */
- private rootHolds = new Map<string, Promise<unknown>>();
+ /** #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 lanes: running lane tasks per worktree. */
private laneTasks = new Map<string, number>();
@@ -103,7 +104,9 @@ export class PersistenceConsumer {
private abandonedReleased = false;
readonly hostId: string;
constructor(readonly engine: BrainEngine, readonly config: GBrainConfig, readonly prepare: PrepareMutation,
- private opts: { hostId?: string; concurrency?: number; pollMs?: number; idleMaxMs?: number; phaseMs?: number; preparationMs?: number; renewalIntervalMs?: number; onError?: (error: unknown) => void;
+ private opts: { hostId?: string; concurrency?: number; pollMs?: number; idleMaxMs?: number; phaseMs?: number; preparationMs?: number;
+ /** Claim renewal cadence (default 10 s); each renewal runs under the `phaseMs` deadline. */
+ renewalIntervalMs?: number; onError?: (error: unknown) => void;
onSettled?: (row: WriteRequest) => void;
/** Engine graduation drain: claim, recover and publish requests only; effect, projection, topology and maintenance workers never start. */
requestsOnly?: boolean } = {}) {
@@ -394,13 +397,13 @@ export class PersistenceConsumer {
}
private track(row: WriteRequest, done: () => void, key: string): void {
let progressed = false;
- const task = this.executeOrGroup(row).then(result => { progressed = result; }).catch(error => this.report(error)).finally(() => {
+ const root: RootHold = {};
+ const task = this.executeOrGroup(row, root).then(result => { progressed = result; }).catch(error => this.report(error)).finally(() => {
if (!progressed) this.rootRetryAfter.set(key, Date.now() + (this.opts.pollMs ?? 250));
else { this.progressWake = true; this.publishedSinceMaintenance++; }
this.active.delete(task);
- const hold = this.rootHolds.get(row.id);
- this.rootHolds.delete(row.id);
- if (hold) void hold.then(() => { done(); this.schedule(0); });
+ // The slot is free now; the root (or lane slot) waits for an abandoned preparation so nothing on it overtakes that work.
+ if (root.until) void root.until.then(() => { done(); this.schedule(0); });
else done();
this.schedule(progressed ? 0 : this.opts.pollMs ?? 250);
});
@@ -495,26 +498,19 @@ export class PersistenceConsumer {
if (!this.opts.onError) process.stderr.write(`[persistence] phase=${phase} reason=${code}${detail ? ` message="${detail}"` : ''}${timing}`
+ '; unfinished work remains tracked; fix: gbrain sources writer status --json; docs: docs/ENGINES.md#persistence-consumer-log\n');
}
- /** #5373: keep a promise that outlived its claim tracked until it settles; it never rejects into the caller. */
- private abandon(work: Promise<unknown>, holdFor?: string): void {
+ /** #5373: tracks work that outlived its claim until it settles; the returned promise never rejects. */
+ private keepUntilSettled(work: Promise<unknown>): Promise<void> {
const settled = work.then(() => undefined, () => undefined);
- this.abandoned.add(settled);
- void settled.then(() => this.abandoned.delete(settled));
- if (holdFor) this.rootHolds.set(holdFor, settled);
+ this.outlived.add(settled);
+ void settled.then(() => { this.outlived.delete(settled); });
+ return settled;
}
- private async execute(row: WriteRequest): Promise<boolean> {
- let renewing: Promise<void> | undefined;
- let claimLive = true;
- let closed = false;
+ private leaseTiming(): ClaimLeaseTiming {
+ return { everyMs: this.opts.renewalIntervalMs ?? DEFAULT_CLAIM_LEASE_TIMING.everyMs, deadlineMs: this.opts.phaseMs ?? DEFAULT_CLAIM_LEASE_TIMING.deadlineMs };
+ }
+ private async execute(row: WriteRequest, root: RootHold): Promise<boolean> {
let preparationActive = true;
const abort = new AbortController();
- const claimLost = Promise.withResolvers<void>();
- const loseClaim = () => {
- if (!claimLive) return;
- claimLive = false;
- abort.abort({ code: 'claim_lost' });
- claimLost.resolve();
- };
const observation = { request_id: row.request_id, started_at: new Date().toISOString(), deadline_exceeded: false, attempt: ++this.preparationAttempts };
this.preparing.set(row.id, observation);
this.executing.add(row.id);
@@ -529,35 +525,27 @@ export class PersistenceConsumer {
abort.abort({ code: 'preparation_deadline' });
this.log('preparation', 'deadline_exceeded');
}, budget) : undefined;
- const interval = setInterval(() => {
- if (closed || renewing) return;
- const renewalAbort = new AbortController();
- const deadline = setTimeout(() => { loseClaim(); renewalAbort.abort(); }, this.opts.phaseMs ?? 5000);
- const task: Promise<void> = renewWriteClaim({ executeRaw: this.engine.executeRawDirect.bind(this.engine) }, row.id, row.execution_token!, 30_000,
- this.engine.kind === 'postgres' ? renewalAbort.signal : undefined).then(live => { if (!live) loseClaim(); })
- .catch(() => { loseClaim(); }).finally(() => { clearTimeout(deadline); if (renewing === task) renewing = undefined; });
- renewing = task;
- }, this.opts.renewalIntervalMs ?? 10_000);
- interval.unref?.();
+ const lease = startClaimLease(
+ signal => renewWriteClaim({ executeRaw: this.engine.executeRawDirect.bind(this.engine) }, row.id, row.execution_token!, 30_000,
+ this.engine.kind === 'postgres' ? signal : undefined),
+ this.leaseTiming(), () => abort.abort({ code: 'claim_lost' }));
+ const releaseReason = () => !lease.held ? 'claim_lost' : observation.deadline_exceeded ? 'preparation_deadline' : 'consumer_stopping';
try {
- const preparation = this.prepare(this.engine, row, this.config, bounded ? abort.signal : undefined)
- .then(prepared => ({ kind: 'prepared' as const, prepared }), error => ({ kind: 'error' as const, error }));
- const outcome = await Promise.race([preparation, claimLost.promise.then(() => ({ kind: 'claim_lost' as const }))]);
- if (outcome.kind === 'claim_lost') {
- this.abandon(preparation, row.id);
+ const preparation = this.prepare(this.engine, row, this.config, bounded ? abort.signal : undefined);
+ const prepared = await lease.whileHeld(preparation);
+ if (prepared === CLAIM_LOST) {
+ root.until = this.keepUntilSettled(preparation);
await releaseUnpublishedClaim(this.engine, row, 'claim_lost');
return false;
}
- if (outcome.kind === 'error') throw outcome.error;
- const prepared = outcome.prepared;
if (timeout) clearTimeout(timeout);
if (bounded && performance.now() >= deadline && !abort.signal.aborted) {
observation.deadline_exceeded = true;
abort.abort({ code: 'preparation_deadline' });
this.log('preparation', 'deadline_exceeded');
}
- if (!claimLive || this.stopping || abort.signal.aborted) {
- await releaseUnpublishedClaim(this.engine, row, !claimLive ? 'claim_lost' : observation.deadline_exceeded ? 'preparation_deadline' : 'consumer_stopping'); return false;
+ if (!lease.held || this.stopping || abort.signal.aborted) {
+ await releaseUnpublishedClaim(this.engine, row, releaseReason()); return false;
}
this.preparing.delete(row.id);
preparationActive = false;
@@ -571,7 +559,7 @@ export class PersistenceConsumer {
} catch (error) {
if (preparationActive && bounded && performance.now() >= deadline) observation.deadline_exceeded = true;
if (preparationActive && (abort.signal.aborted || observation.deadline_exceeded)) {
- await releaseUnpublishedClaim(this.engine, row, !claimLive ? 'claim_lost' : observation.deadline_exceeded ? 'preparation_deadline' : 'consumer_stopping');
+ await releaseUnpublishedClaim(this.engine, row, releaseReason());
return false;
}
const current = await getWriteRequestById(this.engine, row.id);
@@ -582,28 +570,33 @@ export class PersistenceConsumer {
}
throw error;
} finally {
- closed = true; clearInterval(interval); if (timeout) clearTimeout(timeout);
+ const renewal = lease.end();
+ if (renewal) this.keepUntilSettled(renewal);
+ if (timeout) clearTimeout(timeout);
this.abort.signal.removeEventListener('abort', stop); this.preparing.delete(row.id); this.executing.delete(row.id);
- if (renewing) this.abandon(renewing);
}
}
/** #5984: a claimed bulk sync head takes its directly following group members along; one row runs the single path. */
- private async executeOrGroup(row: WriteRequest): Promise<boolean> {
+ private async executeOrGroup(row: WriteRequest, root: RootHold): Promise<boolean> {
// #5984 admit-ahead: a window group whose predecessor did not commit is cancelled, never published after it.
// A lane group may be claimed while its predecessor still publishes; its commit wait decides instead.
const lane = laneOf(row);
const orphaned = lane ? null : await cancelOrphanedWindowGroup(this.engine, row);
if (orphaned) { for (const done of orphaned) this.settled(done); return true; }
const group = publicationGroupKey(row);
- if (!group || this.engine.kind !== 'postgres') return this.execute(row);
+ if (!group || this.engine.kind !== 'postgres') return this.execute(row, root);
// #6007: a put_pages batch publishes in groups of at most PAGE_BATCH_GROUP_MAX pages.
const followers = await claimGroupFollowers(this.engine, row, group, group.startsWith('batch:') ? PAGE_BATCH_GROUP_MAX - 1 : 63);
- if (!followers.length && !lane) return this.execute(row);
+ if (!followers.length && !lane) return this.execute(row, root);
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 => this.prepare(this.engine, member, this.config),
- claim: { intervalMs: this.opts.renewalIntervalMs, phaseMs: this.opts.phaseMs, abandon: (work, holdRoot) => this.abandon(work, holdRoot ? row.id : undefined) },
+ lease: this.leaseTiming(),
+ leftRunning: (work, blocksRoot) => {
+ const settled = this.keepUntilSettled(work);
+ if (blocksRoot) root.until = settled;
+ },
settled: done => {
this.executing.delete(done.id);
if (done.state === 'committed' && done.worktree_id && !String(done.intent?.kind).startsWith('managed_sync_')) {
@@ -621,7 +614,7 @@ export class PersistenceConsumer {
await this.tickPromise;
await this.releaseIdleLane();
await Promise.allSettled([...this.active]);
- while (this.abandoned.size) await Promise.allSettled([...this.abandoned]);
+ while (this.outlived.size) await Promise.all([...this.outlived]);
await this.projectionWorker;
await this.effectsWorker;
await this.topologyWorker;
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index a599d273a4..d4664781f3 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -36,6 +36,7 @@ import { cancelRows, windowPredecessor } from './sync-window.ts';
import { clearResolvedRecoveries, completeWrite, ENSURE_COUNTERS_SQL, getWriteRequestById, LOCK_COUNTERS_SQL, markRecovering, prepareRecoveries,
publicationGroupKey, reclaimReleasedWrite, releaseUnpublishedClaim, renewGroupClaims } from './journal.ts';
import { principalKey, requestPrincipal, type FileRecoveryRecord, type WriteRequest } from './model.ts';
+import { CLAIM_LOST, DEFAULT_CLAIM_LEASE_TIMING, startClaimLease, type ClaimLeaseTiming } from './claim-lease.ts';
import { setMemberAttribution, withCoordinatedWrite } from './context.ts';
import { requestAttribution } from './attribution.ts';
import { tryAcquirePublicationCapacity } from './pool-capacity.ts';
@@ -312,8 +313,13 @@ export interface GroupExecution {
settled(row: WriteRequest): void;
hostId: string;
hooks?: GroupHooks;
- /** #5373: renewal cadence and per-renewal deadline, and where a preparation left running after a claim loss is tracked. */
- claim?: { intervalMs?: number; phaseMs?: number; abandon?: (work: Promise<unknown>, holdRoot?: boolean) => void };
+ /** #5373: renewal timing for the group's claims (default DEFAULT_CLAIM_LEASE_TIMING). */
+ lease?: ClaimLeaseTiming;
+ /**
+ * #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.
+ */
+ leftRunning?(work: Promise<unknown>, blocksRoot: boolean): void;
}
/**
@@ -322,42 +328,30 @@ export interface GroupExecution {
* members one at a time in order. After a member ends in failure the later
* members are cancelled, and after one is released back to the queue the
* later ones are released too, so nothing overtakes it. Claims are renewed
- * for the whole group while it runs; a renewal that loses a member's claim,
- * fails or outlives its deadline during preparation abandons the group: the
- * still-held claims are released unpublished and the preparation is handed to
- * `claim.abandon`, never published. Returns whether any member settled.
+ * for the whole group while it runs (claim-lease.ts). If the group stops
+ * holding every member's claim while it is still preparing, it lets go: each
+ * member is released unpublished with `claim_lost` (token-fenced, so a member
+ * another consumer took over keeps its new claim) and the unfinished
+ * preparation goes to `leftRunning`, never to publication. Returns whether
+ * any member settled.
*/
export async function executeClaimedGroup(engine: BrainEngine, rows: WriteRequest[], run: GroupExecution): Promise<boolean> {
- let renewing: Promise<void> | undefined;
- let preparing = true;
- const claimLost = Promise.withResolvers<'claim_lost'>();
- const loseClaim = () => { if (preparing) claimLost.resolve('claim_lost'); };
- const interval = setInterval(() => {
- if (renewing) return;
- const renewalAbort = new AbortController();
- const deadline = setTimeout(() => { loseClaim(); renewalAbort.abort(); }, run.claim?.phaseMs ?? 5000);
- const task: Promise<void> = renewGroupClaims(engine, rows, 30_000, renewalAbort.signal).then(held => { if (held.size < rows.length) loseClaim(); })
- .catch(loseClaim).finally(() => { clearTimeout(deadline); if (renewing === task) renewing = undefined; });
- renewing = task;
- }, run.claim?.intervalMs ?? 10_000);
- interval.unref?.();
+ const lease = startClaimLease(async signal => (await renewGroupClaims(engine, rows, 30_000, signal)).size === rows.length,
+ run.lease ?? DEFAULT_CLAIM_LEASE_TIMING);
if (run.lane) laneClaimed(run.lane, rows);
try {
const prepared: Array<{ ok: PreparedMutation } | { error: unknown }> = new Array(rows.length);
// A put_pages group prepares all of its (at most PAGE_BATCH_GROUP_MAX) pages at once.
const width = publicationGroupKey(rows[0]!)?.startsWith('batch:') ? PAGE_BATCH_GROUP_MAX : 4;
- const preparation = (async () => {
+ 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) }; } catch (error) { prepared[start + offset] = { error }; }
}));
}
- return 'prepared' as const;
})();
- const outcome = await Promise.race([preparation, claimLost.promise]);
- preparing = false;
- if (outcome === 'claim_lost') {
- run.claim?.abandon?.(preparation, true);
+ if (await lease.whileHeld(preparing) === CLAIM_LOST) {
+ run.leftRunning?.(preparing, true);
for (const row of rows) await releaseUnpublishedClaim(engine, row, 'claim_lost');
return false;
}
@@ -402,7 +396,7 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteReques
return progressed;
} finally {
if (run.lane) laneFinished(run.lane, rows);
- clearInterval(interval);
- if (renewing) run.claim?.abandon?.(renewing);
+ const renewal = lease.end();
+ if (renewal) run.leftRunning?.(renewal, false);
}
}
diff --git a/test/persistence-claim-lease.test.ts b/test/persistence-claim-lease.test.ts
new file mode 100644
index 0000000000..0b0c49b7d2
--- /dev/null
+++ b/test/persistence-claim-lease.test.ts
@@ -0,0 +1,121 @@
+/**
+ * Protects: the claim lease every consumer route prepares under (#5373). A
+ * claim counts as lost the first time a renewal says it is gone, throws, or
+ * overruns its deadline; `whileHeld` stops waiting on preparation at that
+ * moment, and `end()` never waits on a renewal still in flight.
+ *
+ * Regression it catches: a renewal that never settles holding the caller
+ * forever, a lost claim noticed only after preparation finishes, or a
+ * healthy renewal mistaken for a loss.
+ *
+ * Why not covered elsewhere: the consumer suites drive this through real
+ * writes; these cases pin each loss path and its negative control directly,
+ * in milliseconds, with no datastore.
+ */
+import { describe, expect, test } from 'bun:test';
+import { CLAIM_LOST, startClaimLease } from '../src/core/persistence/claim-lease.ts';
+
+const FAST = { everyMs: 5, deadlineMs: 40 };
+const sleep = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms));
+const lostWithin = (lease: { lost: Promise<void> }, ms: number) =>
+ Promise.race([lease.lost.then(() => true), sleep(ms).then(() => false)]);
+
+describe('startClaimLease', () => {
+ test('healthy renewals keep the claim held and whileHeld yields the work result', async () => {
+ let renewals = 0;
+ const lease = startClaimLease(async () => { renewals++; return true; }, FAST);
+ try {
+ const result = await lease.whileHeld(sleep(80).then(() => 'prepared'));
+ expect(result).toBe('prepared');
+ expect(lease.held).toBe(true);
+ expect(renewals).toBeGreaterThan(2);
+ expect(await lostWithin(lease, 20)).toBe(false);
+ } finally { lease.end(); }
+ });
+
+ test('a renewal that reports the claim gone loses it and runs onLost exactly once', async () => {
+ let lostCalls = 0;
+ const lease = startClaimLease(async () => false, FAST, () => { lostCalls++; });
+ try {
+ const never = new Promise<string>(() => {});
+ expect(await lease.whileHeld(never)).toBe(CLAIM_LOST);
+ expect(lease.held).toBe(false);
+ await sleep(30);
+ expect(lostCalls).toBe(1);
+ } finally { lease.end(); }
+ });
+
+ test('a renewal that throws loses the claim', async () => {
+ const lease = startClaimLease(async () => { throw new Error('connection reset'); }, FAST);
+ try {
+ expect(await lostWithin(lease, 1_000)).toBe(true);
+ expect(lease.held).toBe(false);
+ } finally { lease.end(); }
+ });
+
+ test('a renewal that never settles loses the claim at its deadline and is told to cancel', async () => {
+ const signals: AbortSignal[] = [];
+ const lease = startClaimLease(signal => { signals.push(signal); return new Promise<boolean>(() => {}); }, FAST);
+ try {
+ const started = performance.now();
+ expect(await lostWithin(lease, 1_000)).toBe(true);
+ expect(performance.now() - started).toBeGreaterThanOrEqual(FAST.deadlineMs - 5);
+ expect(signals).toHaveLength(1);
+ expect(signals[0]!.aborted).toBe(true);
+ } finally { lease.end(); }
+ });
+
+ test('a slow renewal that still finishes inside its deadline is not a loss', async () => {
+ const lease = startClaimLease(() => sleep(30).then(() => true), { everyMs: 5, deadlineMs: 1_000 });
+ try {
+ expect(await lostWithin(lease, 200)).toBe(false);
+ expect(lease.held).toBe(true);
+ } finally { lease.end(); }
+ });
+
+ test('onLost runs before anything awaiting the loss resumes', async () => {
+ const order: string[] = [];
+ const lease = startClaimLease(async () => false, FAST, () => order.push('onLost'));
+ try {
+ await lease.lost;
+ order.push('awaiter');
+ expect(order).toEqual(['onLost', 'awaiter']);
+ } finally { lease.end(); }
+ });
+
+ test('a preparation failure propagates through whileHeld while the claim is held', async () => {
+ const lease = startClaimLease(async () => true, FAST);
+ try {
+ await expect(lease.whileHeld(Promise.reject(new Error('prepare failed')))).rejects.toThrow('prepare failed');
+ expect(lease.held).toBe(true);
+ } finally { lease.end(); }
+ });
+
+ test('end() hands back the hung renewal without waiting and stops renewing', async () => {
+ let renewals = 0;
+ const hung = Promise.withResolvers<boolean>();
+ const lease = startClaimLease(() => { renewals++; return hung.promise; }, { everyMs: 5, deadlineMs: 10_000 });
+ await sleep(30);
+ const inFlight = lease.end();
+ expect(inFlight).toBeInstanceOf(Promise);
+ expect(renewals).toBe(1);
+ let settled = false;
+ void inFlight!.then(() => { settled = true; });
+ await sleep(20);
+ expect(settled).toBe(false);
+ hung.reject(new Error('late failure'));
+ await inFlight;
+ expect(settled).toBe(true);
+ await sleep(20);
+ expect(renewals).toBe(1);
+ });
+
+ test('end() with no renewal in flight returns nothing and no renewal starts afterwards', async () => {
+ let renewals = 0;
+ const lease = startClaimLease(async () => { renewals++; return true; }, { everyMs: 20, deadlineMs: 40 });
+ expect(lease.end()).toBeUndefined();
+ await sleep(60);
+ expect(renewals).toBe(0);
+ expect(lease.held).toBe(true);
+ });
+});
diff --git a/test/persistence-consumer-scheduling.test.ts b/test/persistence-consumer-scheduling.test.ts
index ff88b7b26d..341524d47b 100644
--- a/test/persistence-consumer-scheduling.test.ts
+++ b/test/persistence-consumer-scheduling.test.ts
@@ -7,6 +7,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { PersistenceConsumer } from '../src/core/persistence/consumer.ts';
import { admitWrite, getWriteRequestById, WRITE_PROGRESS_SQL } from '../src/core/persistence/journal.ts';
import { cancelWriteRequest } from '../src/core/persistence/control.ts';
+import { publishMutation } from '../src/core/persistence/coordinator.ts';
import { acquireWorktree } from '../src/core/persistence/ownership.ts';
import { admission, assertCommittedSnapshot, assertConservation, fixtures, initializeFixtures, prepared, selectFixtureHost, type HarnessConfig } from '../scripts/persistence/harness.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -534,91 +535,128 @@ test('a retryable root becomes eligible again after its backoff expires', async
}
}), 15_000);
-test('a hung claim renewal abandons pending preparation and frees the consumer slot', async () => withEnv(env, async () => {
+// #5373: claim loss during preparation. The renewal statement is the one renewWriteClaim sends.
+const RENEWAL_SQL_MARK = 'claim_expires_at=now()+';
+function interceptRenewals(onRenewal: (id: string, token: string) => Promise<unknown> | undefined): () => void {
+ const direct = engine.executeRawDirect.bind(engine);
+ (engine as unknown as { executeRawDirect: unknown }).executeRawDirect = (sql: string, params?: unknown[]) =>
+ (sql.includes(RENEWAL_SQL_MARK) ? onRenewal(String(params?.[0]), String(params?.[1])) : undefined) ?? direct(sql, params);
+ return () => { (engine as unknown as { executeRawDirect: unknown }).executeRawDirect = direct; };
+}
+const pageBody = async (slug: string, sourceId: string) => (await engine.readPageSnapshot(slug, { sourceId }))?.page.compiled_truth ?? null;
+
+test('a renewal stuck past its deadline frees the slot, keeps the root until the abandoned preparation ends, then retries cleanly', async () => withEnv(env, async () => {
const sources = await fixtures(engine, config);
- const first = await admitWrite(engine, admission(config, sources[0], 'renew-hang-first', 'first body'));
- const second = await admitWrite(engine, admission(config, sources[1], 'renew-hang-second', 'second body'));
- const preparation = Promise.withResolvers<ReturnType<typeof prepared>>();
- const renewal = Promise.withResolvers<Record<string, never>[]>();
- const started: string[] = [];
- const errors: unknown[] = [];
- const originalDirect = engine.executeRawDirect.bind(engine);
- (engine as unknown as { executeRawDirect: unknown }).executeRawDirect = (sql: string, params?: unknown[]) => {
- if (sql.includes('claim_expires_at=now()+') && params?.[0] === first.id) return renewal.promise;
- return originalDirect(sql, params);
- };
+ const stuck = await admitWrite(engine, admission(config, sources[0], 'claim-lease/stuck', 'fresh body'));
+ const elsewhere = await admitWrite(engine, admission(config, sources[1], 'claim-lease/elsewhere', 'elsewhere body'));
+ const firstAttempt = Promise.withResolvers<ReturnType<typeof prepared>>();
+ const hungRenewal = Promise.withResolvers<never[]>();
+ const attempts: string[] = [];
+ let firstToken: string | undefined;
+ const restore = interceptRenewals((_id, token) => token === firstToken ? hungRenewal.promise : undefined);
const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async (_engine, row) => {
- started.push(row.id);
- if (row.id === first.id) return preparation.promise;
- return prepared(row, sources);
- }, { hostId: config.hostId, concurrency: 1, pollMs: 60_000, renewalIntervalMs: 5,
- phaseMs: 30, onError: error => errors.push(error) });
+ attempts.push(row.id);
+ if (row.id !== stuck.id) return prepared(row, sources);
+ if (firstToken) return prepared(row, sources);
+ firstToken = row.execution_token!;
+ return firstAttempt.promise;
+ }, { hostId: config.hostId, concurrency: 1, pollMs: 20, renewalIntervalMs: 5, phaseMs: 40, onError: () => {} });
try {
consumer.start();
- await waitFor(() => started[0] === first.id, { timeoutMs: 5_000 });
- await waitFor(async () => (await getWriteRequestById(engine, first.id))?.state === 'queued',
- { timeoutMs: 5_000, label: 'timed-out renewal should release the pending request' });
- await waitFor(() => consumer.status().active_preparations === 0, { timeoutMs: 5_000 });
- expect(consumer.status().active_preparations).toBe(0);
- expect((await getWriteRequestById(engine, first.id))?.state).toBe('queued');
- // The abandoned preparation still runs, so its root stays busy: the next
- // request on that worktree must not start preparing alongside it.
- expect((consumer as unknown as { activeRoots: Set<string> }).activeRoots.has(first.worktree_id!)).toBe(true);
- // Keep the released root in its retry backoff while advancing the consumer
- // once to prove the other root can use the freed slot.
- (consumer as unknown as { rootRetryAfter: Map<string, number> }).rootRetryAfter.set(first.worktree_id!, Date.now() + 60_000);
- await consumer.tick();
- await waitFor(async () => (await getWriteRequestById(engine, second.id))?.state === 'committed',
- { timeoutMs: 5_000, label: 'the next independent root should use the freed slot' });
- expect(started).toEqual([first.id, second.id]);
- // stop() is the engine-close barrier: it must still drain the abandoned
- // preparation and the hung renewal query before resolving.
+ await waitFor(() => firstToken !== undefined, { timeoutMs: 5_000 });
+ await waitFor(async () => (await getWriteRequestById(engine, stuck.id))?.state === 'queued',
+ { timeoutMs: 5_000, label: 'the stuck renewal loses the claim and the request goes back to the queue' });
+ expect((await getWriteRequestById(engine, stuck.id))?.blocked_reason).toBe('claim_lost');
+ expect(consumer.holds(stuck.id)).toBe(false);
+ await waitFor(async () => (await getWriteRequestById(engine, elsewhere.id))?.state === 'committed',
+ { timeoutMs: 5_000, label: 'the freed slot serves another root' });
+ await Bun.sleep(200);
+ expect(attempts.filter(id => id === stuck.id)).toHaveLength(1);
+ expect((await getWriteRequestById(engine, stuck.id))?.state).toBe('queued');
+
+ firstAttempt.resolve(prepared({ ...stuck, intent: { ...stuck.intent, content: 'stale body' } }, sources));
+ await waitFor(async () => (await getWriteRequestById(engine, stuck.id))?.state === 'committed',
+ { timeoutMs: 5_000, label: 'the root is released and the request is retried' });
+ expect(attempts.filter(id => id === stuck.id)).toHaveLength(2);
+ expect(await pageBody('claim-lease/stuck', sources[0].id)).toBe('fresh body');
+
let stopped = false;
const stopping = consumer.stop().then(() => { stopped = true; });
- await Bun.sleep(50);
+ await Bun.sleep(60);
expect(stopped).toBe(false);
- preparation.resolve(prepared(first, sources));
- renewal.resolve([]);
+ hungRenewal.resolve([]);
await stopping;
- expect(stopped).toBe(true);
- expect((await getWriteRequestById(engine, first.id))?.state).toBe('queued');
- await assertCommittedSnapshot(engine, (await getWriteRequestById(engine, second.id))!);
+ await assertCommittedSnapshot(engine, (await getWriteRequestById(engine, stuck.id))!);
+ await assertCommittedSnapshot(engine, (await getWriteRequestById(engine, elsewhere.id))!);
await assertConservation(engine);
- expect(errors).toEqual([]);
} finally {
- preparation.resolve(prepared(first, sources));
- renewal.resolve([]);
+ firstAttempt.resolve(prepared(stuck, sources));
+ hungRenewal.resolve([]);
await consumer.stop();
- (engine as unknown as { executeRawDirect: unknown }).executeRawDirect = originalDirect;
- for (const row of [first, second]) await cancelWriteRequest(engine, { kind: 'local_cli', id: config.principalIds[0] }, row.request_id);
+ restore();
+ for (const row of [stuck, elsewhere]) await cancelWriteRequest(engine, { kind: 'local_cli', id: config.principalIds[0] }, row.request_id).catch(() => {});
}
-}), 15_000);
+}), 20_000);
-test('ordinary claims still renew and commit while preparation continues', async () => withEnv(env, async () => {
+test('a claim another consumer took over is left alone, and the abandoned preparation never publishes', async () => withEnv(env, async () => {
const sources = await fixtures(engine, config);
- const row = await admitWrite(engine, admission(config, sources[0], 'renew-healthy', 'body'));
- const originalDirect = engine.executeRawDirect.bind(engine);
- let renewals = 0;
- (engine as unknown as { executeRawDirect: unknown }).executeRawDirect = (sql: string, params?: unknown[]) => {
- if (sql.includes('claim_expires_at=now()+')) renewals++;
- return originalDirect(sql, params);
- };
+ const row = await admitWrite(engine, admission(config, sources[0], 'claim-lease/taken', 'our body'));
+ const ours = Promise.withResolvers<ReturnType<typeof prepared>>();
+ let preparing = false;
+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async () => { preparing = true; return ours.promise; },
+ { hostId: config.hostId, concurrency: 1, pollMs: 60_000, renewalIntervalMs: 5, phaseMs: 1_000, onError: () => {} });
+ const takeover = randomUUID();
+ try {
+ consumer.start();
+ await waitFor(() => preparing, { timeoutMs: 5_000 });
+ await engine.executeRaw(`UPDATE persistence_requests SET execution_token=$2::uuid WHERE id=$1::uuid`, [row.id, takeover]);
+ await waitFor(() => !consumer.holds(row.id) && consumer.status().active_preparations === 0,
+ { timeoutMs: 5_000, label: 'the renewal sees the takeover and the consumer lets go' });
+ const after = await getWriteRequestById(engine, row.id);
+ expect([after?.state, after?.execution_token]).toEqual(['running', takeover]);
+
+ ours.resolve(prepared(row, sources));
+ await Bun.sleep(100);
+ expect(await pageBody('claim-lease/taken', sources[0].id)).toBeNull();
+ const theirs = await publishMutation(engine, after!, prepared({ ...after!, intent: { ...after!.intent, content: 'their body' } }, sources), config.hostId);
+ expect(theirs.state).toBe('committed');
+ await consumer.stop();
+ expect(await pageBody('claim-lease/taken', sources[0].id)).toBe('their body');
+ } finally {
+ ours.resolve(prepared(row, sources));
+ await consumer.stop();
+ await cancelWriteRequest(engine, { kind: 'local_cli', id: config.principalIds[0] }, row.request_id).catch(() => {});
+ }
+}), 20_000);
+
+test('healthy renewals during a long preparation keep the claim: one attempt, committed, no claim loss', async () => withEnv(env, async () => {
+ const sources = await fixtures(engine, config);
+ const row = await admitWrite(engine, admission(config, sources[0], 'claim-lease/healthy', 'healthy body'));
+ const renewed: string[] = [];
+ const restore = interceptRenewals(id => { renewed.push(id); return undefined; });
+ let attempts = 0;
+ const errors: unknown[] = [];
const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async (_engine, current) => {
- await Bun.sleep(30);
+ attempts++;
+ await Bun.sleep(120);
return prepared(current, sources);
- }, { hostId: config.hostId, pollMs: 60_000, renewalIntervalMs: 5, phaseMs: 500 });
+ }, { hostId: config.hostId, pollMs: 60_000, renewalIntervalMs: 10, phaseMs: 2_000, onError: error => errors.push(error) });
try {
consumer.start();
await waitFor(async () => (await getWriteRequestById(engine, row.id))?.state === 'committed', { timeoutMs: 5_000 });
- expect(renewals).toBeGreaterThan(0);
+ expect(attempts).toBe(1);
+ expect(renewed.filter(id => id === row.id).length).toBeGreaterThanOrEqual(3);
+ expect((await getWriteRequestById(engine, row.id))?.blocked_reason ?? null).not.toBe('claim_lost');
await assertCommittedSnapshot(engine, (await getWriteRequestById(engine, row.id))!);
await assertConservation(engine);
+ expect(errors).toEqual([]);
} finally {
await consumer.stop();
- (engine as unknown as { executeRawDirect: unknown }).executeRawDirect = originalDirect;
- await cancelWriteRequest(engine, { kind: 'local_cli', id: config.principalIds[0] }, row.request_id);
+ restore();
+ await cancelWriteRequest(engine, { kind: 'local_cli', id: config.principalIds[0] }, row.request_id).catch(() => {});
}
-}), 15_000);
+}), 20_000);
+
test('a local waiter wakes an idle owner for a claim-only tick instead of waiting for the next poll', async () => withEnv(env, async () => {
const ticks: boolean[] = [];
const consumer = startPersistenceConsumer(engine, { engine: 'pglite' });