Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(persistence): consumer statements take the direct route when the engine has one; pooler exposure in status; Postgres tests for heartbeat rows, probe and doctor checks (#6317)

garrytanfaeac0e12362
diff --git a/src/commands/doctor/checks/persistence-consumers.ts b/src/commands/doctor/checks/persistence-consumers.ts
index dc45194909..c57bef802a 100644
--- a/src/commands/doctor/checks/persistence-consumers.ts
+++ b/src/commands/doctor/checks/persistence-consumers.ts
@@ -75,16 +75,19 @@ export async function hostIdentityMismatchCheck(engine: BrainEngine): Promise<Ch
// The ok details carry no `minted_under`: the machine id and hostname differ per machine, and the doctor goldens pin this shape.
const details = { count: mismatches.length, host_id: me.id, host_json_path: me.path, mismatches, docs: IDENTITY_DOCS };
if (!mismatches.length) return { name: 'host_identity_mismatch', status: 'ok', details, message: `This process's host identity (${me.path}) owns every binding this filesystem holds.` };
- const first = mismatches[0]!;
+ // The owners whose identity file is known (a heartbeat row) come first: they carry the one-line fix.
+ const ordered = [...mismatches].sort((a, b) => Number(b.fix_env !== null) - Number(a.fix_env !== null) || Number(b.reason === 'same_machine_id') - Number(a.reason === 'same_machine_id'));
const minted = (value: Record<string, unknown> | 'unknown' | null) => value && value !== 'unknown'
? `HOME=${String(value.home ?? '')} GBRAIN_HOME=${value.gbrain_home == null ? '(unset)' : String(value.gbrain_home)}` : 'minted_under: unknown';
+ const fix = ordered.find(m => m.fix_env)?.fix_env;
return { name: 'host_identity_mismatch', status: 'warn', details: { ...details, minted_under: me.minted_under ?? 'unknown' },
message: `host_identity_mismatch: ${mismatches.length} managed worktree(s) on this filesystem belong to another host identity. `
- + `This process reads ${me.path} (host ${me.id}, ${minted(me.minted_under)}); the binding for ${first.source_ids.join(', ') || first.worktree_id} at ${first.local_path} `
- + `is owned by host ${first.owner_host_id} (${first.owner_host.host_json_path}, ${minted(first.owner_host.minted_under)})`
- + `${first.reason === 'same_machine_id' ? ', minted on this same machine' : ', and this process\'s identity was minted after that binding under a different home'}. `
- + 'Every write from this process on that source reports owner_unavailable (host_mismatch) and its maintenance never runs. '
- + `Fix on the supervisor of this process: ${first.fix_env ?? 'set GBRAIN_HOME to the owner\'s home (the parent of its .gbrain directory)'}, then restart it; never delete or regenerate either host.json.`,
+ + `This process reads ${me.path} (host ${me.id}, ${minted(me.minted_under)}). `
+ + ordered.slice(0, 3).map(m => `The binding for ${m.source_ids.join(', ') || m.worktree_id} at ${m.local_path} is owned by host ${m.owner_host_id} (${m.owner_host.host_json_path}, ${minted(m.owner_host.minted_under)})`
+ + `${m.reason === 'same_machine_id' ? ', minted on this same machine' : ', and this process\'s identity was minted after that binding under a different home'}.`).join(' ')
+ + `${mismatches.length > 3 ? ` (first 3 of ${mismatches.length} shown.)` : ''} `
+ + 'Every write from this process on those sources reports owner_unavailable (host_mismatch) and their maintenance never runs. '
+ + `Fix on the supervisor of this process: ${fix ?? 'set GBRAIN_HOME to the owner\'s home (the parent of its .gbrain directory)'}, then restart it; never delete or regenerate either host.json.`,
fix: agentFix(STATUS_ARGV, 'Read-only: shows local_host_id, each binding\'s owner_host_id and host.consumers with the owner\'s identity file path.', 'host_identity_mismatch', { docs: IDENTITY_DOCS }) };
} catch (error) {
return checkError('host_identity_mismatch', 'compare the host identity with the binding owners', error, { details: { count: 'unknown', health: 'unknown', docs: IDENTITY_DOCS } });
diff --git a/src/core/persistence/consumer-election.ts b/src/core/persistence/consumer-election.ts
index 60f83a19e1..b9cb0956b3 100644
--- a/src/core/persistence/consumer-election.ts
+++ b/src/core/persistence/consumer-election.ts
@@ -47,6 +47,7 @@ import {
type ConsumerHeartbeat, type ConsumerPool, type ConsumerProcessIdentity, type ListedConsumer,
} from './consumer-heartbeat.ts';
import { DEFAULT_PREPARATION_POLICY } from './preparation-budget.ts';
+import { consumerConnectionRoute, consumerStatementEngine } from './consumer-lane.ts';
import { readWriteSwitchSnapshot } from './switches.ts';
export type ConsumerMode = 'probing' | 'full' | 'waiter_only' | 'promoted';
@@ -116,8 +117,11 @@ export class WaiterOnlyConsumer implements PersistenceConsumerLike {
private delayMs: number;
private wakeRequested = false;
private readonly self = consumerIdentity();
+ /** The probe reads through the consumer's statement route (the direct lane when the engine has one). */
+ private readonly statements: BrainEngine;
constructor(readonly engine: BrainEngine, readonly config: GBrainConfig, private readonly makeConsumer: () => PersistenceConsumer, private readonly opts: WaiterOnlyConsumerOpts) {
this.delayMs = opts.pollMs ?? 250;
+ this.statements = consumerStatementEngine(engine);
}
get mode(): ConsumerMode { return this._mode; }
/** The owner this process defers to (waiter-only), or null. */
@@ -160,16 +164,23 @@ export class WaiterOnlyConsumer implements PersistenceConsumerLike {
if (ownConsumerForced !== null) { await this.becomeFull('full', `forced:${ownConsumerForced}`); return; }
const cancel = new AbortController();
const timer = setTimeout(() => cancel.abort(new Error('probe_timeout')), this.opts.phaseMs ?? 5000);
+ // The deadline settles the await itself: a round-trip the pooler never completes (the #6278 class) must not park the probe.
+ const bounded = <T>(work: Promise<T>): Promise<T> => new Promise<T>((resolve, reject) => {
+ const onAbort = () => reject(cancel.signal.reason);
+ if (cancel.signal.aborted) { onAbort(); return; }
+ cancel.signal.addEventListener('abort', onAbort, { once: true });
+ work.then(resolve, reject).finally(() => cancel.signal.removeEventListener('abort', onAbort));
+ });
let rows: ListedConsumer[];
let ceiling: number;
try {
if (this._mode === 'probing') {
- const on = await (this.opts.singleConsumer ? this.opts.singleConsumer() : readWriteSwitchSnapshot(this.engine, { signal: cancel.signal }).then(s => s.switches.single_consumer));
+ const on = await bounded(this.opts.singleConsumer ? this.opts.singleConsumer() : readWriteSwitchSnapshot(this.statements, { signal: cancel.signal }).then(s => s.switches.single_consumer));
if (this.stopping) return;
if (!on) { await this.becomeFull('full', 'single_consumer_off'); return; }
}
- ceiling = await (this.opts.ceilingMs ? this.opts.ceilingMs() : readWriteSwitchSnapshot(this.engine, { signal: cancel.signal }).then(s => s.preparation.ceilingMs, () => DEFAULT_PREPARATION_POLICY.ceilingMs));
- rows = await (this.opts.readConsumers ? this.opts.readConsumers(cancel.signal) : listHostConsumers(this.engine, this.opts.hostId, { signal: cancel.signal }));
+ ceiling = await bounded(this.opts.ceilingMs ? this.opts.ceilingMs() : readWriteSwitchSnapshot(this.statements, { signal: cancel.signal }).then(s => s.preparation.ceilingMs, () => DEFAULT_PREPARATION_POLICY.ceilingMs));
+ rows = await bounded(this.opts.readConsumers ? this.opts.readConsumers(cancel.signal) : listHostConsumers(this.statements, this.opts.hostId, { signal: cancel.signal }));
} catch (error) {
if (this.stopping) return;
if (cancel.signal.aborted) {
@@ -257,7 +268,7 @@ export class WaiterOnlyConsumer implements PersistenceConsumerLike {
const election = { mode: this._mode, kind: this.opts.kind, owner: this.electedOwner(), heartbeat_failures: this.heartbeat?.failures ?? 0 };
if (this.inner) return { ...this.inner.status(), consumer_election: election };
return { accepting: !this.stopping, active_preparations: 0, active_worktrees: 0, restart_required: false, sampled_at: new Date().toISOString(),
- observation_scope: 'current_process_reset_on_restart', consumer_election: election };
+ observation_scope: 'current_process_reset_on_restart', connection: consumerConnectionRoute(this.engine), consumer_election: election };
}
async stop(): Promise<void> {
this.stopping = true;
diff --git a/src/core/persistence/consumer-heartbeat.ts b/src/core/persistence/consumer-heartbeat.ts
index ca95b028ef..dcea487bc9 100644
--- a/src/core/persistence/consumer-heartbeat.ts
+++ b/src/core/persistence/consumer-heartbeat.ts
@@ -206,19 +206,23 @@ export function startConsumerHeartbeat(engine: DirectEngine, hostId: string, opt
process.stderr.write(`[persistence] phase=consumer_heartbeat reason=renewal_failed message="${message}"; this process keeps consuming; `
+ 'other consumers on this host may stop deferring to it after 60 s; fix: gbrain sources writer status --json; docs: docs/ENGINES.md#persistence-consumer-log\n');
};
+ // The deadline settles the await itself (a round-trip a pooler never completes must not park the heartbeat); a late result is dropped.
+ const bounded = <T>(work: Promise<T>, cancel: AbortController, ms: number): Promise<T> => new Promise<T>((resolve, reject) => {
+ const timer = setTimeout(() => { cancel.abort(new Error(`consumer heartbeat statement exceeded ${ms} ms`)); reject(cancel.signal.reason); }, ms);
+ work.then(resolve, reject).finally(() => clearTimeout(timer));
+ });
const renewOnce = async (): Promise<void> => {
const cancel = new AbortController();
- const timer = setTimeout(() => cancel.abort(new Error(`consumer heartbeat renewal exceeded ${deadlineMs} ms`)), deadlineMs);
try {
const status = opts.report();
const mode = typeof opts.mode === 'function' ? opts.mode() : opts.mode;
- await execute(RENEW_SQL, [hostId, self.pid, self.nonce, self.pid_ns, opts.kind, mode, status.restart_required, status.root_barrier_age_ms,
+ await bounded(execute(RENEW_SQL, [hostId, self.pid, self.nonce, self.pid_ns, opts.kind, mode, status.restart_required, status.root_barrier_age_ms,
status.pool ? JSON.stringify(status.pool) : null, paths.host_json_path, paths.persistence_home,
- paths.minted_under ? JSON.stringify(paths.minted_under) : null, VERSION, CONSUMER_PURGE_MS], cancel.signal);
+ paths.minted_under ? JSON.stringify(paths.minted_under) : null, VERSION, CONSUMER_PURGE_MS], cancel.signal), cancel, deadlineMs);
streak = 0;
} catch (error) {
if (!stopped) report(error);
- } finally { clearTimeout(timer); }
+ }
};
const renew = (): Promise<void> => {
if (stopped) return Promise.resolve();
@@ -239,10 +243,8 @@ export function startConsumerHeartbeat(engine: DirectEngine, hostId: string, opt
clearInterval(cadence);
await inFlight;
const cancel = new AbortController();
- const timer = setTimeout(() => cancel.abort(), 1_000);
- try { await execute('DELETE FROM persistence_consumers WHERE host_id=$1::uuid AND pid=$2::integer AND nonce=$3', [hostId, self.pid, self.nonce], cancel.signal); }
+ try { await bounded(execute('DELETE FROM persistence_consumers WHERE host_id=$1::uuid AND pid=$2::integer AND nonce=$3', [hostId, self.pid, self.nonce], cancel.signal), cancel, 1_000); }
catch { /* the row lapses on its own; the next renewal on this host purges it */ }
- finally { clearTimeout(timer); }
},
};
}
diff --git a/src/core/persistence/consumer-lane.ts b/src/core/persistence/consumer-lane.ts
new file mode 100644
index 0000000000..88d6ed0392
--- /dev/null
+++ b/src/core/persistence/consumer-lane.ts
@@ -0,0 +1,73 @@
+/**
+ * #6317 (reporter ask 2 on #6278): which connection the persistence consumer's
+ * own statements take.
+ *
+ * The production wedge reproduced with one process: through a transaction-mode
+ * pooler (Supavisor :6543) the consumer's `expired_claims` round-trip never
+ * completed (backend `active` in `ClientRead` for minutes), while the same
+ * drain on the session-mode URL ran clean. So when the engine has a direct
+ * route (the dual pool: `GBRAIN_DIRECT_DATABASE_URL`, or the Supabase
+ * auto-derived direct URL; postgres-engine.ts `executeRawDirect` and
+ * `transactionDirect` take it when `connectionManager.isDualPoolActive()`),
+ * the consumer's tick statements (the idle probe, switch read, recovery and
+ * expired-claim scans, capacity marking, claims and releases) run on it,
+ * beside the claim renewals and the heartbeat that already do. The
+ * publication transactions and the preparers keep their routes; this module
+ * is connection selection only (the bounded client-side settle of a hung
+ * round-trip lives in postgres-engine.ts).
+ *
+ * When only a transaction-mode pooler URL exists (`prepare: false` is the
+ * detectable sign, db.ts `resolvePrepare`: port 6543 or `?prepare=false`),
+ * the consumer logs one loud line at start and `status()` reports
+ * `connection.pooler_mode: 'transaction'`, so an operator sees the exposure in
+ * `gbrain sources writer status --json` before the first stall.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { registerEngineView, viewedEngine } from './switches.ts';
+
+export interface ConsumerConnectionRoute {
+ /** Where the consumer's statements run: the direct/session route, or the ordinary pool. */
+ lane: 'direct' | 'pool';
+ /** What the ordinary pool's URL is: a transaction-mode pooler (heuristic: `prepare: false`), a session-mode or direct server, or not Postgres. */
+ pooler_mode: 'transaction' | 'session_or_direct' | 'not_postgres' | 'unknown';
+ direct_host?: string;
+}
+
+type RoutedEngine = BrainEngine & {
+ connectionManager?: { isDualPoolActive(): boolean; describeMode(): { direct_host?: string } } | null;
+ sql?: { options?: { prepare?: boolean } };
+};
+
+/** The route this engine gives the consumer right now (the dual pool initializes lazily and can fall back, so this is read per call). */
+export function consumerConnectionRoute(engine: BrainEngine): ConsumerConnectionRoute {
+ if (engine.kind !== 'postgres') return { lane: 'pool', pooler_mode: 'not_postgres' };
+ const routed = engine as RoutedEngine;
+ let direct = false, directHost: string | undefined, prepare: boolean | undefined;
+ try { direct = routed.connectionManager?.isDualPoolActive() === true; directHost = direct ? routed.connectionManager?.describeMode().direct_host : undefined; } catch { direct = false; }
+ try { prepare = routed.sql?.options?.prepare; } catch { prepare = undefined; }
+ return { lane: direct ? 'direct' : 'pool', pooler_mode: prepare === false ? 'transaction' : prepare === undefined ? 'unknown' : 'session_or_direct', ...(directHost ? { direct_host: directHost } : {}) };
+}
+
+/**
+ * The engine the consumer's own statements run through: `executeRaw` goes to `executeRawDirect` while the direct route is
+ * active, every other member reaches the engine unchanged. Non-Postgres engines and engines without a direct route are
+ * returned as they are.
+ */
+export function consumerStatementEngine(engine: BrainEngine): BrainEngine {
+ if (engine.kind !== 'postgres' || typeof engine.executeRawDirect !== 'function') return engine;
+ return registerEngineView(new Proxy(engine, { get(target, key) {
+ if (key === 'executeRaw') return (sql: string, params?: unknown[], opts?: { signal?: AbortSignal; timeoutMs?: number }) =>
+ consumerConnectionRoute(target).lane === 'direct' && opts?.timeoutMs === undefined ? target.executeRawDirect(sql, params, opts) : target.executeRaw(sql, params, opts);
+ const member = Reflect.get(target, key, target);
+ return typeof member === 'function' ? member.bind(target) : member;
+ } }), viewedEngine(engine));
+}
+
+/** The one loud line a consumer prints when it starts on a transaction-mode pooler with no direct route. */
+export function poolerExposureLine(route: ConsumerConnectionRoute): string | null {
+ if (route.lane === 'direct' || route.pooler_mode !== 'transaction') return null;
+ return '[persistence] phase=start reason=transaction_pooler message="the persistence consumer runs its statements through a transaction-mode pooler '
+ + '(prepare=false, port 6543) with no direct route; a round-trip the pooler never completes cannot be ended by any server timeout"; '
+ + 'fix: set GBRAIN_DIRECT_DATABASE_URL to the session-mode (port 5432) or direct URL of the same database and restart; verify: gbrain sources writer status --json (connection.lane: direct); '
+ + 'docs: docs/ENGINES.md#persistence-consumer-log';
+}
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index 6d765243dc..60be3038a8 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -28,6 +28,7 @@ import { refreshFenceClear } from './worktree-refresh-schema.ts';
import { faultPoint } from './fault-points.ts';
import { releaseAbandonedClaims } from './effect-journal.ts';
import { readWriteSwitchSnapshot, writeSwitchOn } from './switches.ts';
+import { consumerConnectionRoute, consumerStatementEngine, poolerExposureLine } from './consumer-lane.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. */
@@ -175,6 +176,9 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
private preparing = new Map<string, { request_id: string; started_at: string; deadline_exceeded: boolean; attempt: number }>();
private executing = new Set<string>();
private abandonedReleased = false;
+ /** #6317: the engine the tick's own statements run through (the direct route when the engine has one; consumer-lane.ts). */
+ private readonly statements: BrainEngine;
+ private routeLogged = 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;
@@ -190,6 +194,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
/** #6278: abandoned preparations past the ceiling before this process stops claiming (default DEFAULT_ZOMBIE_CAP). */
zombieCap?: number } = {}) {
this.hostId = opts.hostId ?? localHostId();
+ this.statements = consumerStatementEngine(engine);
}
private get checkoutObservable(): ((listener: () => void) => () => void) | undefined {
const engine = this.engine as { onCheckout?: unknown };
@@ -197,6 +202,9 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
}
start(): void {
this.stopping = false; this.abort = new AbortController(); this.fullTickRequested = true; this.idleDelayMs = this.pollMs;
+ // #6317: one loud line when every round-trip of this consumer goes through a transaction-mode pooler with no direct route.
+ const exposure = poolerExposureLine(consumerConnectionRoute(this.engine));
+ if (exposure && !this.routeLogged && !this.opts.onError) { this.routeLogged = true; process.stderr.write(`${exposure}\n`); }
if (this.opts.requestsOnly) this.projectionWorker = this.effectsWorker = this.topologyWorker = this.maintenanceWorker = PARKED_WORKER;
this.schedule(0);
}
@@ -245,7 +253,9 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
const excluded = [...this.activeRoots, ...[...this.rootRetryAfter].filter(([, at]) => at > now).map(([root]) => root)];
for (const [id, at] of this.topologyRetryAfter) if (at <= now) this.topologyRetryAfter.delete(id);
const retryingTopologies = [...this.topologyRetryAfter.keys()];
- const [row] = await this.phase('idle_probe', async signal => this.probeQuery<{ work: boolean }>(this.laneInUse ? undefined : await this.acquireIdleLane(signal), `SELECT (
+ // On the direct route the probe needs no reserved pool lane: the direct pool is small and keeps its connections.
+ const direct = consumerConnectionRoute(this.engine).lane === 'direct';
+ const [row] = await this.phase('idle_probe', async signal => this.probeQuery<{ work: boolean }>(this.laneInUse || direct ? undefined : await this.acquireIdleLane(signal), `SELECT (
EXISTS (SELECT 1 FROM persistence_requests r LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id
WHERE ${claimableWriteSql(foregroundPrioritySql(), '$5::text[]')}
AND ($3::boolean OR r.blocked_reason IS DISTINCT FROM 'writer_pool_capacity'))
@@ -355,8 +365,8 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
} finally { this.laneInUse = false; }
}
private async probeQuery<T>(lane: ReservedConnection | undefined, sql: string, params: unknown[], signal?: AbortSignal): Promise<T[]> {
- if (!lane) return this.engine.executeRaw<T>(sql, params, { signal });
- if (this.laneInUse) return this.engine.executeRaw<T>(sql, params, { signal });
+ if (!lane) return this.statements.executeRaw<T>(sql, params, { signal });
+ if (this.laneInUse) return this.statements.executeRaw<T>(sql, params, { signal });
this.probeOnLane = true;
const query = lane.executeRaw<T>(sql, params);
void query.then(() => { this.probeOnLane = false; }, () => { this.probeOnLane = false; });
@@ -419,7 +429,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
}
// Lane runs size themselves to the pool's long-hold budget; a single write keeps its warm lane.
// The switches are read under the tick's phase deadline, so a saturated pool cannot hold the tick.
- const fast = await this.phase('switches', signal => readWriteSwitchSnapshot(this.engine, { signal }))
+ const fast = await this.phase('switches', signal => readWriteSwitchSnapshot(this.statements, { signal }))
.then(snapshot => {
this.policy = { ...snapshot.preparation, deadlines: snapshot.switches.preparation_deadlines, ...this.opts.preparationBudgets };
return snapshot.switches.single_write_group;
@@ -465,7 +475,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
for (const [root, retryAt] of this.rootRetryAfter) if (retryAt <= now) this.rootRetryAfter.delete(root);
if (scan) {
const excluded = [...this.activeRoots, ...this.rootRetryAfter.keys()];
- const recovery = await this.phase('recovery_scan', signal => this.engine.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests r
+ const recovery = await this.phase('recovery_scan', signal => this.statements.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests r
JOIN persistence_worktrees w ON w.id=r.worktree_id
WHERE w.owner_host_id=$1::uuid AND r.recovery IS NOT NULL AND NOT(r.worktree_id::text=ANY($2::text[]))
AND NOT EXISTS (SELECT 1 FROM persistence_requests earlier WHERE earlier.worktree_id=r.worktree_id
@@ -488,7 +498,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
}
}
// #6278: a claim that expired while its owner was preparing (the kill case) counts one preparation attempt.
- await this.phase('expired_claims', signal => this.engine.executeRaw(`WITH expired AS (
+ await this.phase('expired_claims', signal => this.statements.executeRaw(`WITH expired AS (
SELECT r.id FROM persistence_requests r WHERE r.state='running' AND r.recovery IS NULL
AND r.publication_started=false AND r.claim_expires_at<now() AND ${PERSISTENCE_PROTOCOL_PREDICATE}
AND (r.worktree_id IS NULL OR EXISTS (SELECT 1 FROM persistence_worktrees w WHERE w.id=r.worktree_id AND w.owner_host_id=$1::uuid))
@@ -498,7 +508,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
FROM expired WHERE r.id=expired.id`, [this.hostId, this.policy.deadlines], { signal }));
}
if (publicationConcurrency(this.engine) === 0) {
- await this.phase('capacity', signal => this.engine.executeRaw(`UPDATE persistence_requests SET blocked_reason='writer_pool_capacity'
+ await this.phase('capacity', signal => this.statements.executeRaw(`UPDATE persistence_requests SET blocked_reason='writer_pool_capacity'
WHERE state='queued' AND blocked_reason IS DISTINCT FROM 'writer_pool_capacity' AND ${PERSISTENCE_PROTOCOL_PREDICATE}`, undefined, { signal }));
return;
}
@@ -517,12 +527,12 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
if (!row) break;
if (String(row.intent?.kind ?? '').startsWith('managed_sync_')) this.owesSyncTurn.delete(row.worktree_id ?? `db:${row.source_incarnation}`);
else if (row.passed_sync) this.passedSync.add(row.id);
- if (this.stopping) { await releaseUnpublishedClaim(this.engine, row, 'consumer_stopping'); break; }
+ if (this.stopping) { await releaseUnpublishedClaim(this.statements, row, 'consumer_stopping'); break; }
const key = row.worktree_id ?? `db:${row.source_incarnation}`;
attemptedRoots.add(key);
// #5984 lanes: the FIFO head of an open lane run runs as the run's first lane.
if (laneOf(row)) { this.startLaneTask(row, key); continue; }
- if (this.activeRoots.has(key)) { await releaseUnpublishedClaim(this.engine, row, 'writer_busy'); break; }
+ if (this.activeRoots.has(key)) { await releaseUnpublishedClaim(this.statements, row, 'writer_busy'); break; }
this.activeRoots.add(key);
// Lane heads keep being claimed beside a foreground write on a lane root (it joins their lease).
if (laneRootKeys.includes(key)) this.besideLanes.add(key);
@@ -598,6 +608,8 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
abandoned_preparations: this.abandoned.size,
outlived_ceiling: [...this.zombies.values()].map(value => ({ ...value })),
restart_required: this.restartRequired(),
+ // #6317: which connection this consumer's statements take, and whether the ordinary pool is a transaction-mode pooler.
+ connection: consumerConnectionRoute(this.engine),
...(this.lastError ? { last_error: { ...this.lastError } } : {}) };
}
/**
@@ -724,7 +736,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
claimed_at: new Date(clock.claimedAt).toISOString(), abandoned_at: at, outlived_ceiling_at: at });
void settled.then(() => { this.zombies.delete(row.id); });
this.log('preparation', 'ceiling_exceeded', `request ${row.request_id} step=${clock.step ?? 'none'} waiting_on=${clock.waitingOn}${this.restartRequired() ? ' restart_required' : ''}`);
- await floorPreparationAttempts(this.engine, row.id, this.policy.maxAttempts).catch(error => this.report(error));
+ await floorPreparationAttempts(this.statements, row.id, this.policy.maxAttempts).catch(error => this.report(error));
});
}
private async execute(row: WriteRequest, root: RootHold): Promise<boolean> {
@@ -769,13 +781,13 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
// whether or not the preparer settles; its late result never publishes (#6278).
const deadline = async (): Promise<boolean> => {
root.until = this.abandonedRootBlock(row, clock, this.keepAbandoned(prep.work, clock.claimedAt));
- if (!lease.held || this.stopping) { await releaseUnpublishedClaim(this.engine, row, releaseReason()); return false; }
+ if (!lease.held || this.stopping) { await releaseUnpublishedClaim(this.statements, row, releaseReason()); return false; }
if ((row.preparation_attempts ?? 0) + 1 >= policy.maxAttempts) {
const done = await finishPreparationStalled(this.engine, row, stallInfo(), true);
this.log('preparation', 'preparation_stalled', failureLogText(done));
return this.settled(done);
}
- await releaseUnpublishedClaim(this.engine, row, 'preparation_deadline', { charge: true });
+ await releaseUnpublishedClaim(this.statements, row, 'preparation_deadline', { charge: true });
return false;
};
try {
@@ -784,14 +796,14 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
if (raced === CLAIM_LOST) {
root.until = this.abandonedRootBlock(row, clock, this.keepAbandoned(prep.work, clock.claimedAt));
await endLostLease(lease);
- await releaseUnpublishedClaim(this.engine, row, 'claim_lost');
+ await releaseUnpublishedClaim(this.statements, row, 'claim_lost');
return false;
}
if ('deadline' in raced) return deadline();
const prepared = raced.result;
if (budget !== undefined && !prep.signal.aborted && prep.late()) prep.expire();
if (!lease.held || this.stopping || prep.signal.aborted) {
- await releaseUnpublishedClaim(this.engine, row, releaseReason()); return false;
+ await releaseUnpublishedClaim(this.statements, row, releaseReason()); return false;
}
this.preparing.delete(row.id);
preparationActive = false;
@@ -812,7 +824,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
}
// #6278: the preparer's rejection on our own abort (its reason, an AbortError, a cancelled statement) is a release, never a receipt.
if (preparationActive && (prep.signal.aborted || observation.deadline_exceeded || preparationAbortReason(error, prep.signal))) {
- await releaseUnpublishedClaim(this.engine, row, releaseReason());
+ await releaseUnpublishedClaim(this.statements, row, releaseReason());
return false;
}
const current = await getWriteRequestById(this.engine, row.id);
@@ -835,7 +847,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
// A bulk-sync group member released mid-group follows the member before it, not only the previous group (#6153 class).
const lane = laneOf(row);
const order = await claimedHeadOrder(this.engine, row, lane !== null);
- if (order === 'wait') { await releaseUnpublishedClaim(this.engine, row, 'group_member_waiting'); return false; }
+ if (order === 'wait') { await releaseUnpublishedClaim(this.statements, row, 'group_member_waiting'); return false; }
if (order) { for (const done of order) this.settled(done); return true; }
const group = publicationGroupKey(row);
if (!group || this.engine.kind !== 'postgres') return this.execute(row, root);
diff --git a/test/e2e/persistence-consumers-postgres.test.ts b/test/e2e/persistence-consumers-postgres.test.ts
new file mode 100644
index 0000000000..cd6143eac3
--- /dev/null
+++ b/test/e2e/persistence-consumers-postgres.test.ts
@@ -0,0 +1,297 @@
+/**
+ * #6317 on Postgres (T1d, T3): the consumer heartbeat rows and what doctor
+ * reads from them. Protects: a full consumer's row appears within one renewal
+ * carrying the process identity (pid, nonce, pid namespace), kind, mode and
+ * wedge report, and leaves on stop(); a row lapsed 90 s is deleted by the next
+ * renewal of any consumer on the host while a merely stale row stays; the
+ * probe sees a live full resident row and ignores this process, a `put`
+ * row, a lapsed row, a `restart_required` row and a root barrier past the
+ * ceiling; doctor `two_consumers_on_host` lists a 10 s old `put` row beside a
+ * `serve` without warning and warns for two resident rows alive over 30 s;
+ * `consumers_without_heartbeat` names a running claim's owner that has no
+ * row (an older build); `host_identity_mismatch` names both identity files
+ * when two `GBRAIN_HOME`s mint two `host.json` files on one machine against
+ * one brain, and flags the container shape (no machine id, worktree at the
+ * binding's path, identity minted later under another home); `writer status
+ * --json` carries `host.consumers`; the v221 table has PGLite/Postgres parity.
+ * Fails on the base branch: the table, the module and the checks do not exist.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import {
+ CONSUMER_LAPSED_MS, CONSUMER_LIVE_MS, CONSUMER_PURGE_MS, consumerIdentity, listHostConsumers, probeLiveFullConsumer, resetConsumerIdentityForTest, startConsumerHeartbeat,
+ type ConsumerProcessIdentity,
+} from '../../src/core/persistence/consumer-heartbeat.ts';
+import { consumerOverlap, hostIdentityMismatches, ownersWithoutHeartbeat } from '../../src/core/persistence/consumer-diagnostics.ts';
+import { localHostIdentity, readMachineId, registerLocalWriter } from '../../src/core/persistence/identity.ts';
+import { claimWorktree } from '../../src/core/persistence/ownership.ts';
+import { admitWrite } from '../../src/core/persistence/journal.ts';
+import { claimPhaseStamp, startClaimPhase } from '../../src/core/persistence/claim-phase.ts';
+import { runPersistenceAdministration } from '../../src/core/persistence/administration.ts';
+import { consumersWithoutHeartbeatCheck, hostIdentityMismatchCheck, twoConsumersOnHostCheck } from '../../src/commands/doctor/checks/persistence-consumers.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { hasDatabase } from './helpers.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { waitFor } from '../helpers/wait-for.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-consumers-e2e-'));
+let engine: BrainEngine;
+let close: (() => Promise<void>) | undefined;
+let hostId: string;
+const original = consumerIdentity();
+
+const rows = (host = hostId) => listHostConsumers(engine, host);
+const identity = (pid: number, nonce = `n-${pid}`): ConsumerProcessIdentity => ({ pid, nonce, pid_ns: original.pid_ns });
+/** Writes a row for another process with the given age and renewal age (seconds), as that process's heartbeat would have left it. */
+async function seedRow(id: ConsumerProcessIdentity, over: { kind?: string; mode?: string; ageS?: number; renewedAgoS?: number; restart_required?: boolean; root_barrier_age_ms?: number | null; host?: string } = {}) {
+ await engine.executeRaw(`INSERT INTO persistence_consumers(host_id,pid,nonce,pid_ns,kind,mode,started_at,renewed_at,restart_required,root_barrier_age_ms,host_json_path,persistence_home,version)
+ VALUES($1::uuid,$2,$3,$4,$5,$6,now()-($7::integer*interval '1 second'),now()-($8::integer*interval '1 second'),$9,$10,$11,$12,'0.60.100.0')
+ ON CONFLICT (host_id,pid,nonce) DO UPDATE SET renewed_at=EXCLUDED.renewed_at,started_at=EXCLUDED.started_at,mode=EXCLUDED.mode,restart_required=EXCLUDED.restart_required,root_barrier_age_ms=EXCLUDED.root_barrier_age_ms`,
+ [over.host ?? hostId, id.pid, id.nonce, id.pid_ns, over.kind ?? 'serve', over.mode ?? 'full', over.ageS ?? 600, over.renewedAgoS ?? 1, over.restart_required ?? false, over.root_barrier_age_ms ?? null,
+ `/other/${id.pid}/.gbrain/persistence/host.json`, `/other/${id.pid}/.gbrain/persistence`]);
+}
+const clear = () => engine.executeRaw('DELETE FROM persistence_consumers');
+
+beforeAll(async () => {
+ if (!hasDatabase()) return;
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!, 'instance', 6);
+ engine = pg.engine; close = pg.close;
+ await withEnv({ GBRAIN_HOME: home }, () => { hostId = localHostIdentity().id; });
+}, 120_000);
+afterAll(async () => {
+ resetConsumerIdentityForTest(original);
+ await close?.();
+ rmSync(home, { recursive: true, force: true });
+});
+
+describe.skipIf(!hasDatabase())('consumer heartbeat rows (Postgres, #6317)', () => {
+ test('a full consumer writes its row at once with its identity and wedge report, renews it, and removes it on stop()', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ await clear();
+ let restartRequired = false;
+ const heartbeat = startConsumerHeartbeat(engine, hostId, { kind: 'serve', mode: 'full', everyMs: 100, report: () => ({ restart_required: restartRequired, root_barrier_age_ms: restartRequired ? 650_000 : null, pool: { checked_out: 2, max: 6, waiters: 0 } }) });
+ await waitFor(async () => (await rows()).length === 1, { timeoutMs: 5_000, label: 'the row appears' });
+ const [row] = await rows();
+ const me = localHostIdentity();
+ expect(row).toMatchObject({ host_id: hostId, pid: process.pid, nonce: original.nonce, pid_ns: original.pid_ns, kind: 'serve', mode: 'full', restart_required: false, root_barrier_age_ms: null,
+ pool: { checked_out: 2, max: 6, waiters: 0 }, host_json_path: me.path, persistence_home: me.persistence_home, liveness: 'live', self: true });
+ expect(row!.minted_under).toMatchObject({ home: process.env.HOME ?? null, gbrain_home: home });
+ expect(readFileSync(me.path, 'utf8')).toContain('"minted_under"');
+ const first = row!.renewed_at;
+ restartRequired = true;
+ await waitFor(async () => { const [r] = await rows(); return r?.renewed_at !== first && r?.restart_required === true; }, { timeoutMs: 5_000, label: 'a renewal carries the wedge report' });
+ expect((await rows())[0]).toMatchObject({ restart_required: true, root_barrier_age_ms: 650_000 });
+ expect(heartbeat.failures).toBe(0);
+ await heartbeat.stop();
+ expect(await rows()).toEqual([]);
+ }), 30_000);
+
+ test('a renewal purges rows lapsed over 90 s on this host and leaves stale, live and other-host rows', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ await clear();
+ const otherHost = randomUUID();
+ await seedRow(identity(101), { renewedAgoS: CONSUMER_PURGE_MS / 1000 + 1 });
+ await seedRow(identity(102), { renewedAgoS: CONSUMER_LAPSED_MS / 1000 + 5 });
+ await seedRow(identity(103), { renewedAgoS: 1 });
+ await seedRow(identity(104), { renewedAgoS: CONSUMER_PURGE_MS / 1000 + 100, host: otherHost });
+ const heartbeat = startConsumerHeartbeat(engine, hostId, { kind: 'sync', mode: 'full', everyMs: 1_000_000, report: () => ({ restart_required: false, root_barrier_age_ms: null }) });
+ await heartbeat.renew();
+ const after = await rows();
+ expect(after.map(row => row.pid).sort()).toEqual([102, 103, process.pid].sort());
+ expect(after.find(row => row.pid === 102)!.liveness).toBe('lapsed');
+ expect(after.find(row => row.pid === 103)!.liveness).toBe('live');
+ expect((await rows(otherHost)).map(row => row.pid)).toEqual([104]);
+ await heartbeat.stop();
+ await engine.executeRaw('DELETE FROM persistence_consumers WHERE host_id=$1::uuid', [otherHost]);
+ }), 30_000);
+
+ test('the probe finds the first live full resident row that is not this process and ignores put rows, lapsed, wedged and restart_required owners', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ await clear();
+ const self = consumerIdentity();
+ expect(await probeLiveFullConsumer(engine, hostId, self)).toBeNull();
+ await seedRow(identity(201), { kind: 'put' });
+ await seedRow(identity(202), { renewedAgoS: CONSUMER_LIVE_MS / 1000 + 1 });
+ await seedRow(identity(203), { restart_required: true });
+ await seedRow(identity(204), { root_barrier_age_ms: 600_000 });
+ await seedRow({ pid: self.pid, nonce: self.nonce, pid_ns: self.pid_ns }, { kind: 'serve' });
+ expect(await probeLiveFullConsumer(engine, hostId, self, { ceilingMs: 600_000 })).toBeNull();
+ await seedRow(identity(205), { kind: 'jobs', ageS: 5 });
+ expect((await probeLiveFullConsumer(engine, hostId, self, { ceilingMs: 600_000 }))?.pid).toBe(205);
+ // The ceiling is the brain's: a barrier under a raised ceiling is not wedged.
+ expect((await probeLiveFullConsumer(engine, hostId, self, { ceilingMs: 700_000 }))?.pid).toBe(204);
+ // The same pid with another nonce is another process (a container reusing the pid), so it can be an owner.
+ await clear();
+ await seedRow({ pid: self.pid, nonce: 'reused-pid-other-process', pid_ns: 'pid:[1]' }, { kind: 'serve' });
+ expect((await probeLiveFullConsumer(engine, hostId, self))?.nonce).toBe('reused-pid-other-process');
+ }), 30_000);
+
+ test('doctor two_consumers_on_host: a put row 10 s old beside a serve is listed, not warned; two resident rows alive over 30 s warn; a young second row does not', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ await clear();
+ await seedRow(identity(301), { kind: 'serve', ageS: 600 });
+ await seedRow(identity(302), { kind: 'put', ageS: 10 });
+ let check = await twoConsumersOnHostCheck(engine, hostId);
+ expect(check.status).toBe('ok');
+ expect((check.details as { consumers: unknown[] }).consumers).toHaveLength(2);
+ await seedRow(identity(303), { kind: 'sync', ageS: 10 });
+ check = await twoConsumersOnHostCheck(engine, hostId);
+ expect(check.status).toBe('ok');
+ await seedRow(identity(303), { kind: 'sync', ageS: 60 });
+ check = await twoConsumersOnHostCheck(engine, hostId);
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('two_consumers_on_host');
+ expect(check.message).toContain('serve pid 301');
+ expect(check.message).toContain('sync pid 303');
+ expect(check.details).toMatchObject({ count: 2 });
+ expect(check.fix?.argv).toEqual(['gbrain', 'sources', 'writer', 'status', '--json']);
+ expect(consumerOverlap(await rows()).map(row => row.pid)).toEqual([301, 303]);
+ // A lapsed second resident row is no overlap.
+ await seedRow(identity(303), { kind: 'sync', ageS: 60, renewedAgoS: CONSUMER_LIVE_MS / 1000 + 1 });
+ expect((await twoConsumersOnHostCheck(engine, hostId)).status).toBe('ok');
+ }), 30_000);
+
+ test('doctor consumers_without_heartbeat names the owner of a live running claim that wrote no row (an older build) and clears once its row exists', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_PERSISTENCE_FIXTURE_HOME: home }, async () => {
+ await clear();
+ const sourceId = `hb-${randomUUID().slice(0, 8)}`;
+ const root = join(home, sourceId); mkdirSync(root, { recursive: true });
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [sourceId, root]);
+ const binding = await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const [incarnation] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [sourceId]);
+ const principal = { kind: 'local_cli' as const, id: (await registerLocalWriter(engine, 'cli')).id };
+ const row = await admitWrite(engine, { principal, requestId: randomUUID(), operation: 'put_page', sourceId, sourceIncarnation: incarnation!.incarnation, pageId: null,
+ slug: 'notes/alice-example', worktreeId: binding.worktree_id, topologyGeneration: binding.topology_generation, intent: { content: 'x' }, callerIntent: { content: 'x' },
+ authority: { version: 1, principal, remote: false, sourceId, sourceIncarnation: incarnation!.incarnation, scopes: ['read', 'write'], operations: null, slugPrefixes: null } });
+ const token = randomUUID();
+ const stamp = claimPhaseStamp(startClaimPhase(), token, { kind: 'sync', pid: 4242, version: '0.60.100.0' });
+ await engine.executeRaw(`UPDATE persistence_requests SET state='running',execution_token=$2::uuid,claim_expires_at=now()+interval '30 seconds',claim_phase=$3::text::jsonb WHERE id=$1::uuid`, [row.id, token, stamp]);
+ const owners = await ownersWithoutHeartbeat(engine, hostId);
+ expect(owners).toEqual([{ kind: 'sync', pid: 4242, nonce: null, version: '0.60.100.0', requests: 1, sources: [sourceId], lapsed: false }]);
+ const check = await consumersWithoutHeartbeatCheck(engine, hostId);
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('sync pid 4242 v0.60.100.0');
+ await seedRow(identity(4242, 'any'), { kind: 'sync' });
+ expect((await consumersWithoutHeartbeatCheck(engine, hostId)).status).toBe('ok');
+ // A lapsed claim's owner is gone; that is persistence_write_stall's and the drain's finding, not this one.
+ await clear();
+ await engine.executeRaw("UPDATE persistence_requests SET claim_expires_at=now()-interval '1 second' WHERE id=$1::uuid", [row.id]);
+ expect(await ownersWithoutHeartbeat(engine, hostId)).toEqual([]);
+ await engine.executeRaw("UPDATE persistence_requests SET state='cancelled',execution_token=NULL,claim_expires_at=NULL WHERE id=$1::uuid", [row.id]);
+ }), 60_000);
+
+ test('T3: two GBRAIN_HOMEs against one brain mint two identities; doctor host_identity_mismatch names both files and the GBRAIN_HOME fix', async () => {
+ await clear();
+ const ownerHome = mkdtempSync(join(tmpdir(), 'gbrain-owner-home-'));
+ const workerHome = mkdtempSync(join(tmpdir(), 'gbrain-worker-home-'));
+ const sourceId = `id-${randomUUID().slice(0, 8)}`;
+ const root = join(ownerHome, 'content'); mkdirSync(root, { recursive: true });
+ try {
+ // The owner (a serve under its own GBRAIN_HOME) claims the source and leaves a heartbeat row carrying its identity file.
+ await withEnv({ GBRAIN_HOME: ownerHome, GBRAIN_PERSISTENCE_FIXTURE_HOME: ownerHome }, async () => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [sourceId, root]);
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const owner = localHostIdentity();
+ resetConsumerIdentityForTest({ pid: 777, nonce: 'owner-serve' });
+ const heartbeat = startConsumerHeartbeat(engine, owner.id, { kind: 'serve', mode: 'full', everyMs: 1_000_000, report: () => ({ restart_required: false, root_barrier_age_ms: null }) });
+ await heartbeat.renew();
+ expect((await listHostConsumers(engine, owner.id)).map(row => row.host_json_path)).toEqual([owner.path]);
+ resetConsumerIdentityForTest(original);
+ });
+ // A worker started with another GBRAIN_HOME on the same machine mints a second host.json.
+ await withEnv({ GBRAIN_HOME: workerHome, GBRAIN_PERSISTENCE_FIXTURE_HOME: workerHome }, async () => {
+ const me = localHostIdentity();
+ const ownerPath = join(ownerHome, '.gbrain', 'persistence', 'host.json');
+ expect(me.path).toBe(join(workerHome, '.gbrain', 'persistence', 'host.json'));
+ expect(me.id).not.toBe(JSON.parse(readFileSync(ownerPath, 'utf8')).id);
+ // Earlier tests' worktrees under the test home are other-host bindings on this filesystem too; this case is about the owner's.
+ const found = (await hostIdentityMismatches(engine, me)).filter(m => m.source_ids.includes(sourceId));
+ expect(found).toHaveLength(1);
+ expect(found[0]).toMatchObject({ source_ids: [sourceId], local_path: root, reason: readMachineId() ? 'same_machine_id' : 'worktree_on_this_filesystem',
+ this_host: { host_id: me.id, host_json_path: me.path }, owner_host: { host_json_path: ownerPath, persistence_home: join(ownerHome, '.gbrain', 'persistence') }, fix_env: `GBRAIN_HOME=${ownerHome}` });
+ const check = await hostIdentityMismatchCheck(engine);
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain(me.path);
+ expect(check.message).toContain(ownerPath);
+ expect(check.message).toContain(`GBRAIN_HOME=${ownerHome}`);
+ expect(check.message).toContain('never delete or regenerate either host.json');
+ expect((check.details as { count: number }).count).toBeGreaterThanOrEqual(1);
+ expect(check.fix?.argv).toEqual(['gbrain', 'sources', 'writer', 'status', '--json']);
+ });
+ // The owner itself does not see its own binding as a mismatch.
+ await withEnv({ GBRAIN_HOME: ownerHome }, async () => {
+ expect((await hostIdentityMismatches(engine, localHostIdentity())).filter(m => m.source_ids.includes(sourceId))).toEqual([]);
+ });
+ } finally {
+ await engine.executeRaw('DELETE FROM persistence_consumers');
+ rmSync(ownerHome, { recursive: true, force: true }); rmSync(workerHome, { recursive: true, force: true });
+ }
+ }, 60_000);
+
+ test('T3 container shape: no machine id, the managed worktree at the binding path, an identity minted after the binding under another home', async () => {
+ await clear();
+ const ownerHome = mkdtempSync(join(tmpdir(), 'gbrain-owner-home-'));
+ const workerHome = mkdtempSync(join(tmpdir(), 'gbrain-worker-home-'));
+ const sourceId = `ct-${randomUUID().slice(0, 8)}`;
+ const root = join(ownerHome, 'content'); mkdirSync(root, { recursive: true });
+ try {
+ await withEnv({ GBRAIN_HOME: ownerHome, GBRAIN_PERSISTENCE_FIXTURE_HOME: ownerHome }, async () => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [sourceId, root]);
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ });
+ // No heartbeat row from the owner (an older serve) and no machine id on either side: only the filesystem evidence remains.
+ await withEnv({ GBRAIN_HOME: workerHome, GBRAIN_PERSISTENCE_FIXTURE_HOME: workerHome }, async () => {
+ const me = { ...localHostIdentity(), minted_under: { home: '/root', gbrain_home: null, hostname: 'container', machine_id: null } };
+ const mine = (found: Awaited<ReturnType<typeof hostIdentityMismatches>>) => found.filter(m => m.source_ids.includes(sourceId));
+ const found = mine(await hostIdentityMismatches(engine, me, { marked: () => true, hostJsonMintedAt: Date.now() + 60_000 }));
+ expect(found).toHaveLength(1);
+ expect(found[0]).toMatchObject({ reason: 'worktree_on_this_filesystem', source_ids: [sourceId], owner_host: { host_json_path: 'unknown', minted_under: 'unknown' }, fix_env: null });
+ // Minted before the binding (the identity predates the claim): not this shape.
+ expect(mine(await hostIdentityMismatches(engine, me, { marked: () => true, hostJsonMintedAt: Date.now() - 86_400_000 }))).toEqual([]);
+ // The path exists but holds no managed marker: not this shape either.
+ expect(mine(await hostIdentityMismatches(engine, me, { marked: () => false, hostJsonMintedAt: Date.now() + 60_000 }))).toEqual([]);
+ });
+ } finally { rmSync(ownerHome, { recursive: true, force: true }); rmSync(workerHome, { recursive: true, force: true }); }
+ }, 60_000);
+
+ test('writer status --json carries host.consumers from the rows', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ await clear();
+ await seedRow(identity(401), { kind: 'serve' });
+ const status = await runPersistenceAdministration(engine, 'writer_status', {}) as { host: { host_id: string; consumers: Array<{ pid: number; kind: string; mode: string }>; overlap: unknown[]; lapsed_after_ms: number } };
+ expect(status.host.host_id).toBe(hostId);
+ expect(status.host.consumers.map(row => ({ pid: row.pid, kind: row.kind, mode: row.mode }))).toEqual([{ pid: 401, kind: 'serve', mode: 'full' }]);
+ expect(status.host).toMatchObject({ overlap: [], lapsed_after_ms: CONSUMER_LAPSED_MS });
+ }), 30_000);
+});
+
+describe('persistence_consumers on PGLite (#6317)', () => {
+ test('the migration creates the table and the watermark index on both engines; the heartbeat and probe are inert on PGLite', async () => {
+ const pglite = new PGLiteEngine();
+ await pglite.connect({} as never);
+ await pglite.initSchema();
+ try {
+ const [table] = await pglite.executeRaw<{ present: boolean }>("SELECT to_regclass('persistence_consumers') IS NOT NULL AS present");
+ const [index] = await pglite.executeRaw<{ present: boolean }>("SELECT to_regclass('persistence_requests_committed_watermark') IS NOT NULL AS present");
+ expect(table?.present).toBe(true);
+ expect(index?.present).toBe(true);
+ const heartbeat = startConsumerHeartbeat(pglite, randomUUID(), { kind: 'serve', mode: 'full', report: () => ({ restart_required: false, root_barrier_age_ms: null }) });
+ await heartbeat.renew();
+ expect(await pglite.executeRaw('SELECT 1 FROM persistence_consumers')).toEqual([]);
+ expect(await probeLiveFullConsumer(pglite, randomUUID())).toBeNull();
+ expect(await listHostConsumers(pglite, randomUUID())).toEqual([]);
+ await heartbeat.stop();
+ if (hasDatabase()) {
+ const [pg] = await engine.executeRaw<{ present: boolean }>("SELECT to_regclass('persistence_requests_committed_watermark') IS NOT NULL AS present");
+ expect(pg?.present).toBe(true);
+ const [def] = await engine.executeRaw<{ def: string }>("SELECT indexdef AS def FROM pg_indexes WHERE indexname='persistence_requests_committed_watermark'");
+ expect(def?.def).toContain("(worktree_id, completed_at DESC) WHERE (state = 'committed'::text)");
+ }
+ } finally { await pglite.disconnect(); }
+ }, 120_000);
+});
diff --git a/test/persistence-consumer-election.test.ts b/test/persistence-consumer-election.test.ts
new file mode 100644
index 0000000000..e9298bcf66
--- /dev/null
+++ b/test/persistence-consumer-election.test.ts
@@ -0,0 +1,275 @@
+/**
+ * #6317 (B1, T1b unit half): the consumer mode machine in
+ * `consumer-election.ts`, driven through its seams (the host's consumer rows,
+ * the switch, the ceiling) with a stub full consumer, so every transition is
+ * pinned without a database: probing settles to full when the switch is off
+ * or no live owner exists, to waiter-only beside a live full resident owner
+ * (the whole external surface answers inertly meanwhile); a waiter promotes
+ * when its owner lapses 60 s, reports `restart_required`, carries a root
+ * barrier past the ceiling or disappears, and stays put while the owner is
+ * merely stale; only a promoted consumer drains back, after three healthy
+ * ticks of a `full` owner, never for another promoted peer; `stop()` during
+ * an unanswered probe returns and the late answer is dropped; the forced
+ * own-consumer flag wins; a probe the database cannot answer falls back to a
+ * full consumer with one log line; the heartbeat row carries the mode. The
+ * Postgres half (real rows, a spawned `serve`) is
+ * test/e2e/persistence-two-consumers-postgres.test.ts.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { LANE_BUSY, type PersistenceConsumer } from '../src/core/persistence/consumer.ts';
+import { DRAIN_BACK_HEALTHY_TICKS, electOwner, forceOwnConsumer, PROBE_TIMEOUT_MISSES, resetOwnConsumerForTest, WaiterOnlyConsumer } from '../src/core/persistence/consumer-election.ts';
+import { CONSUMER_LAPSED_MS, CONSUMER_LIVE_MS, consumerIdentity, type ListedConsumer } from '../src/core/persistence/consumer-heartbeat.ts';
+
+const CEILING = 600_000;
+
+function fakeEngine(kind: 'postgres' | 'pglite' = 'postgres') {
+ const statements: Array<{ sql: string; params: unknown[] }> = [];
+ const engine = { kind, executeRaw: async (sql: string, params: unknown[] = []) => { statements.push({ sql, params }); return []; },
+ executeRawDirect: async (sql: string, params: unknown[] = []) => { statements.push({ sql, params }); return []; } } as unknown as BrainEngine;
+ return { engine, statements, heartbeatModes: () => statements.filter(s => s.sql.includes('INSERT INTO persistence_consumers')).map(s => s.params[5]) };
+}
+
+function stubConsumer() {
+ const calls: string[] = [];
+ let stopped = false;
+ const consumer = {
+ start() { calls.push('start'); }, async stop() { calls.push('stop'); stopped = true; }, wake(own?: boolean) { calls.push(`wake:${own ?? false}`); },
+ async tick() { calls.push('tick'); }, holds: () => false, foregroundCompletions: () => 0, async onLane() { return LANE_BUSY; },
+ restartRequired: () => false, oldestRootBarrierAgeMs: () => null,
+ status: () => ({ accepting: !stopped, active_preparations: 0, active_worktrees: 0, restart_required: false, from_inner: true }),
+ };
+ return { consumer: consumer as unknown as PersistenceConsumer, calls };
+}
+
+function row(over: Partial<ListedConsumer> = {}): ListedConsumer {
+ return { host_id: 'h', pid: 4242, nonce: 'owner-nonce', pid_ns: null, kind: 'serve', mode: 'full', started_at: '2026-10-08T00:00:00Z', renewed_at: '2026-10-08T00:10:00Z',
+ restart_required: false, root_barrier_age_ms: null, pool: null, host_json_path: '/owner/.gbrain/persistence/host.json', persistence_home: '/owner/.gbrain/persistence', minted_under: null,
+ version: '0.60.200.0', renewed_age_ms: 1_000, age_ms: 600_000, liveness: 'live', self: false, ...over };
+}
+
+function harness(opts: { rows?: () => ListedConsumer[] | Promise<ListedConsumer[]>; switchOn?: boolean; kind?: string; engineKind?: 'postgres' | 'pglite' } = {}) {
+ const fake = fakeEngine(opts.engineKind);
+ const made: ReturnType<typeof stubConsumer>[] = [];
+ const logs: string[] = [];
+ const consumer = new WaiterOnlyConsumer(fake.engine, { engine: 'postgres' }, () => { const stub = stubConsumer(); made.push(stub); return stub.consumer; },
+ { kind: opts.kind ?? 'jobs', hostId: 'h', pollMs: 1_000_000, idleMaxMs: 1_000_000, phaseMs: 200, readConsumers: async () => opts.rows ? opts.rows() : [],
+ singleConsumer: async () => opts.switchOn ?? true, ceilingMs: async () => CEILING, heartbeatEveryMs: 1_000_000, log: line => logs.push(line) });
+ return { consumer, made, logs, fake };
+}
+
+afterEach(() => resetOwnConsumerForTest());
+
+describe('electOwner', () => {
+ const self = consumerIdentity();
+ test('a live full resident row that is not this process wins; put/cli rows, this process, wedged and stale rows do not', () => {
+ expect(electOwner([row()], null, CEILING, self)?.pid).toBe(4242);
+ expect(electOwner([row({ kind: 'put' })], null, CEILING, self)).toBeNull();
+ expect(electOwner([row({ pid: self.pid, nonce: self.nonce })], null, CEILING, self)).toBeNull();
+ expect(electOwner([row({ pid: self.pid, nonce: 'another-process-with-my-pid' })], null, CEILING, self)?.pid).toBe(self.pid);
+ expect(electOwner([row({ restart_required: true })], null, CEILING, self)).toBeNull();
+ expect(electOwner([row({ root_barrier_age_ms: CEILING })], null, CEILING, self)).toBeNull();
+ expect(electOwner([row({ root_barrier_age_ms: CEILING - 1 })], null, CEILING, self)?.pid).toBe(4242);
+ expect(electOwner([row({ renewed_age_ms: CONSUMER_LIVE_MS })], null, CEILING, self)).toBeNull();
+ expect(electOwner([row({ mode: 'promoted', kind: 'sync' })], null, CEILING, self)?.kind).toBe('sync');
+ });
+ test('the current owner is kept while merely stale (under 60 s) and dropped once lapsed', () => {
+ const current = { pid: 4242, nonce: 'owner-nonce' };
+ expect(electOwner([row({ renewed_age_ms: 45_000 })], current, CEILING, self)?.pid).toBe(4242);
+ expect(electOwner([row({ renewed_age_ms: CONSUMER_LAPSED_MS })], current, CEILING, self)).toBeNull();
+ expect(electOwner([row({ renewed_age_ms: 45_000 }), row({ pid: 7, nonce: 'n7', kind: 'sync' })], null, CEILING, self)?.pid).toBe(7);
+ });
+});
+
+describe('WaiterOnlyConsumer mode machine', () => {
+ test('switch off: full on the first tick without reading the rows; the heartbeat row says full', async () => {
+ let reads = 0;
+ const h = harness({ switchOn: false, rows: () => { reads++; return [row()]; } });
+ h.consumer.start();
+ await h.consumer.probeTick();
+ expect(h.consumer.mode).toBe('full');
+ expect(reads).toBe(0);
+ expect(h.made).toHaveLength(1);
+ expect(h.made[0]!.calls).toEqual(['start']);
+ expect(h.fake.heartbeatModes()).toEqual(['full']);
+ await h.consumer.stop();
+ expect(h.made[0]!.calls).toContain('stop');
+ });
+ test('PGLite: full at start, no probe, no heartbeat statement', async () => {
+ const h = harness({ engineKind: 'pglite', rows: () => { throw new Error('never read'); } });
+ h.consumer.start();
+ expect(h.consumer.mode).toBe('full');
+ await h.consumer.stop();
+ expect(h.fake.statements).toEqual([]);
+ });
+ test('no live owner: full after the probe; a put-kind row beside it is not an owner', async () => {
+ const h = harness({ rows: () => [row({ kind: 'put', pid: 9 }), row({ renewed_age_ms: CONSUMER_LIVE_MS + 1 })] });
+ h.consumer.start();
+ await h.consumer.probeTick();
+ expect(h.consumer.mode).toBe('full');
+ await h.consumer.stop();
+ });
+ test('a live full serve: waiter-only with the consumer surface answering inertly and the owner in status', async () => {
+ const h = harness({ rows: () => [row()] });
+ h.consumer.start();
+ await h.consumer.probeTick();
+ expect(h.consumer.mode).toBe('waiter_only');
+ expect(h.made).toHaveLength(0);
+ expect(h.consumer.holds('x')).toBe(false);
+ expect(h.consumer.foregroundCompletions('w')).toBe(0);
+ expect(await h.consumer.onLane(async () => 'ran')).toBe(LANE_BUSY);
+ expect(h.consumer.restartRequired()).toBe(false);
+ h.consumer.wake(true);
+ expect(h.made).toHaveLength(0);
+ const status = h.consumer.status();
+ expect(status).toMatchObject({ accepting: true, active_preparations: 0, active_worktrees: 0, consumer_election: { mode: 'waiter_only', kind: 'jobs', owner: { kind: 'serve', pid: 4242, nonce: 'owner-nonce' } } });
+ expect(h.consumer.electedOwner()?.pid).toBe(4242);
+ expect(h.fake.heartbeatModes()).toEqual([]);
+ expect(h.logs.some(line => line.includes('reason=waiter_only') && line.includes('pid 4242'))).toBe(true);
+ await h.consumer.stop();
+ expect(h.made).toHaveLength(0);
+ });
+ for (const [label, lapsedRows] of [
+ ['lapsed 60 s', () => [row({ renewed_age_ms: CONSUMER_LAPSED_MS })]],
+ ['restart_required while its heartbeat is live', () => [row({ restart_required: true })]],
+ ['a root barrier past the ceiling while its heartbeat is live', () => [row({ root_barrier_age_ms: CEILING + 1 })]],
+ ['gone', () => []],
+ ['no longer full', () => [row({ mode: 'waiter_only' })]],
+ ] as const) {
+ test(`a waiter promotes on its next tick when the owner is ${label}; the heartbeat row says promoted`, async () => {
+ let rows: ListedConsumer[] = [row()];
+ const h = harness({ rows: () => rows });
+ h.consumer.start();
+ await h.consumer.probeTick();
+ expect(h.consumer.mode).toBe('waiter_only');
+ rows = lapsedRows();
+ await h.consumer.probeTick();
+ expect(h.consumer.mode).toBe('promoted');
+ expect(h.made).toHaveLength(1);
+ expect(h.made[0]!.calls).toEqual(['start']);
+ expect(h.fake.heartbeatModes()).toEqual(['promoted']);
+ expect(h.logs.some(line => line.includes('owner_lapsed promoted_to_consumer'))).toBe(true);
+ await h.consumer.stop();
+ });
+ }
+ test('a stale owner (30-60 s) keeps its waiter; a live replacement owner is adopted without a promotion', async () => {
+ let rows: ListedConsumer[] = [row()];
+ const h = harness({ rows: () => rows });
+ h.consumer.start();
+ await h.consumer.probeTick();
+ rows = [row({ renewed_age_ms: 45_000 })];
+ await h.consumer.probeTick();
+ expect(h.consumer.mode).toBe('waiter_only');
+ rows = [row({ renewed_age_ms: 45_000 }), row({ pid: 7, nonce: 'n7', kind: 'mcp' })];
+ await h.consumer.probeTick();
+ expect(h.consumer.mode).toBe('waiter_only');
+ rows = [row({ pid: 7, nonce: 'n7', kind: 'mcp' })];
+ await h.consumer.probeTick();
+ expect(h.consumer.mode).toBe('waiter_only');
+ expect(h.consumer.electedOwner()?.pid).toBe(7);
+ expect(h.made).toHaveLength(0);
+ await h.consumer.stop();
+ });
+ test('a promoted consumer drains back after three healthy ticks of a full owner, then defers again; a promoted peer never drains it back', async () => {
+ let rows: ListedConsumer[] = [row()];
+ const h = harness({ rows: () => rows });
+ h.consumer.start();
+ await h.consumer.probeTick();
+ rows = [];
+ await h.consumer.probeTick();
+ expect(h.consumer.mode).toBe('promoted');
+ // Another waiter that promoted at the same time is not an elected owner: both stay promoted (doctor names the overlap).
+ rows = [row({ mode: 'promoted', kind: 'sync', pid: 8, nonce: 'n8' })];
+ for (let i = 0; i < DRAIN_BACK_HEALTHY_TICKS + 1; i++) await h.consumer.probeTick();
+ expect(h.consumer.mode).toBe('promoted');
+ expect(h.made[0]!.calls).not.toContain('stop');
+ // The elected owner recovers: two healthy ticks are not enough, the third drains back; in-flight work finishes through stop().
+ rows = [row()];
+ await h.consumer.probeTick(); await h.consumer.probeTick();
+ expect(h.consumer.mode).toBe('promoted');
+ await h.consumer.probeTick();
+ expect(h.consumer.mode).toBe('waiter_only');
+ expect(h.made[0]!.calls).toContain('stop');
+ expect(h.consumer.electedOwner()?.pid).toBe(4242);
+ // A heartbeat outage resets the count: healthy, unhealthy, healthy ticks do not add up.
+ rows = [];
+ await h.consumer.probeTick();
+ expect(h.consumer.mode).toBe('promoted');
+ expect(h.made).toHaveLength(2);
+ rows = [row()]; await h.consumer.probeTick(); await h.consumer.probeTick();
+ rows = [row({ renewed_age_ms: CONSUMER_LAPSED_MS })]; await h.consumer.probeTick();
+ rows = [row()]; await h.consumer.probeTick(); await h.consumer.probeTick();
+ expect(h.consumer.mode).toBe('promoted');
+ await h.consumer.probeTick();
+ expect(h.consumer.mode).toBe('waiter_only');
+ await h.consumer.stop();
+ expect(h.fake.heartbeatModes()).toEqual(['promoted', 'promoted']);
+ expect(h.fake.statements.filter(s => s.sql.startsWith('DELETE FROM persistence_consumers'))).toHaveLength(2);
+ });
+ test('stop() during an unanswered probe returns cleanly and the late answer is dropped', async () => {
+ const pending = Promise.withResolvers<ListedConsumer[]>();
+ const h = harness({ rows: () => pending.promise });
+ h.consumer.start();
+ const tick = h.consumer.probeTick();
+ const stopped = h.consumer.stop();
+ pending.resolve([]);
+ await tick;
+ await stopped;
+ expect(h.consumer.mode).toBe('probing');
+ expect(h.made).toHaveLength(0);
+ expect(h.fake.statements).toEqual([]);
+ });
+ test('the forced own-consumer flag: full at start, and a waiter already made promotes to full (never drains back)', async () => {
+ let rows: ListedConsumer[] = [row()];
+ const waiter = harness({ rows: () => rows });
+ waiter.consumer.start();
+ await waiter.consumer.probeTick();
+ expect(waiter.consumer.mode).toBe('waiter_only');
+ forceOwnConsumer('no_delegate');
+ await waiter.consumer.probeTick();
+ expect(waiter.consumer.mode).toBe('full');
+ for (let i = 0; i < DRAIN_BACK_HEALTHY_TICKS + 1; i++) await waiter.consumer.probeTick();
+ expect(waiter.consumer.mode).toBe('full');
+ expect(waiter.made[0]!.calls).not.toContain('stop');
+ await waiter.consumer.stop();
+ const forced = harness({ rows: () => [row()] });
+ forced.consumer.start();
+ expect(forced.consumer.mode).toBe('full');
+ await forced.consumer.stop();
+ });
+ test('promote() turns a waiter into a full consumer in place', async () => {
+ const h = harness({ rows: () => [row()] });
+ h.consumer.start();
+ await h.consumer.probeTick();
+ await h.consumer.promote('skew_fallback');
+ expect(h.consumer.mode).toBe('full');
+ expect(h.made).toHaveLength(1);
+ await h.consumer.stop();
+ });
+ test('a probe the database cannot answer: full with one log line; a probe that times out stays probing until the third miss', async () => {
+ const failing = harness({ rows: () => { throw new Error('relation "persistence_consumers" does not exist'); } });
+ failing.consumer.start();
+ await failing.consumer.probeTick();
+ expect(failing.consumer.mode).toBe('full');
+ expect(failing.logs.filter(line => line.includes('reason=probe_failed'))).toHaveLength(1);
+ await failing.consumer.stop();
+ const slow = harness({ rows: () => new Promise<ListedConsumer[]>(() => {}) });
+ slow.consumer.start();
+ for (let i = 1; i < PROBE_TIMEOUT_MISSES; i++) { await slow.consumer.probeTick(); expect(slow.consumer.mode).toBe('probing'); }
+ await slow.consumer.probeTick();
+ expect(slow.consumer.mode).toBe('full');
+ expect(slow.logs.filter(line => line.includes('reason=probe_timeout'))).toHaveLength(1);
+ await slow.consumer.stop();
+ });
+ test('tick() forwards to the full consumer once one exists', async () => {
+ const h = harness({ switchOn: false });
+ h.consumer.start();
+ await h.consumer.tick();
+ await h.consumer.tick(true);
+ expect(h.made[0]!.calls).toEqual(['start', 'tick']);
+ h.consumer.wake(true);
+ expect(h.made[0]!.calls).toContain('wake:true');
+ expect(h.consumer.status()).toMatchObject({ from_inner: true, consumer_election: { mode: 'full' } });
+ await h.consumer.stop();
+ });
+});