Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(persistence): consumer heartbeat rows, one-full-consumer-per-host election and process identity in claim stamps (#6317 T-02)

garrytan9c25ecdb0717
diff --git a/src/core/config.ts b/src/core/config.ts
index bee29ad515..f9cf377ea1 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1725,6 +1725,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'persistence.limits.brain_recovery_bytes', 'persistence.limits.worktree_recovery_bytes',
'persistence.receipt_retention_days', 'persistence.unbound_write', 'persistence.max_claim_ms', // #5254: persistence/unbound-source.ts; #6176: persistence/claim-phase.ts
'persistence.sync_preparation_ms', 'persistence.maintenance_preparation_ms', 'persistence.preparation_ceiling_ms', 'persistence.max_preparation_attempts', 'persistence.preparation_deadlines', // #6278: persistence/preparation-budget.ts, switches.ts
+ 'persistence.single_consumer', // #6317: persistence/switches.ts, consumer-election.ts (one full consumer per host; off by default)
// shared-skills migration inventory bounds (src/core/shared-skills/inventory-limits.ts)
'shared_skills.inventory.max_files', 'shared_skills.inventory.max_total_bytes', 'shared_skills.inventory.max_file_bytes', 'shared_skills.inventory.max_entries',
'persistence.write_wait_ms', // #5232: file plane, persistence/write-wait.ts
diff --git a/src/core/persistence/claim-phase.ts b/src/core/persistence/claim-phase.ts
index 78abdff319..d29660ac85 100644
--- a/src/core/persistence/claim-phase.ts
+++ b/src/core/persistence/claim-phase.ts
@@ -31,6 +31,7 @@
*/
import type { BrainEngine } from '../engine.ts';
import { VERSION } from '../../version.ts';
+import { consumerIdentity, sameProcess } from './consumer-heartbeat.ts';
export type ClaimPhaseName = 'preparing' | 'publishing';
export const WAITING_ON = ['git', 'fs', 'db', 'pool', 'unknown'] as const;
@@ -58,8 +59,11 @@ export interface ClaimPhaseClock {
*/
deadlineAt?: number;
}
-/** The process that holds a claim, as the stamp records it. */
-export interface ClaimOwner { kind: string; pid: number; version: string }
+/**
+ * The process that holds a claim, as the stamp records it. #6317: `nonce` (random per process) and `pid_ns` (the pid
+ * namespace where readable) tell a reused pid or another container's pid from this process; an older owner stamps neither.
+ */
+export interface ClaimOwner { kind: string; pid: number; version: string; nonce?: string; pid_ns?: string | null }
export function startClaimPhase(now = Date.now(), signal?: AbortSignal, budgetMs?: number): ClaimPhaseClock {
return { phase: 'preparing', claimedAt: now, since: now, step: null, stepSince: now, waitingOn: 'unknown', ...(signal ? { signal } : {}),
@@ -89,11 +93,21 @@ export function enterClaimStep(clock: ClaimPhaseClock | undefined, step: string,
const OWNER_COMMANDS = new Set(['sync', 'serve', 'jobs', 'autopilot', 'mcp', 'dream', 'cycle', 'sources', 'migrate-graduation', 'put', 'import']);
let ownerOverride: ClaimOwner | undefined;
-/** The owning process for the stamp: the gbrain command this process runs (`cli` when none is recognisable), its pid and build. */
+/** The gbrain command this process runs (`cli` when none is recognisable). */
+export function claimOwnerKind(): string {
+ if (ownerOverride) return ownerOverride.kind;
+ const command = process.argv.slice(2).find(arg => !arg.startsWith('-'));
+ return command && OWNER_COMMANDS.has(command) ? command : 'cli';
+}
+/** The owning process for the stamp: the gbrain command this process runs (`cli` when none is recognisable), its pid, nonce, pid namespace and build. */
export function claimOwner(): ClaimOwner {
if (ownerOverride) return ownerOverride;
- const command = process.argv.slice(2).find(arg => !arg.startsWith('-'));
- return { kind: command && OWNER_COMMANDS.has(command) ? command : 'cli', pid: process.pid, version: VERSION };
+ const { pid, nonce, pid_ns } = consumerIdentity();
+ return { kind: claimOwnerKind(), pid, version: VERSION, nonce, pid_ns };
+}
+/** Whether a stamped owner is this process: the pid and, when the stamp carries one, the nonce (#6317: `owner_pid === process.pid` alone is not enough). */
+export function claimOwnerIsThisProcess(owner: Pick<ClaimOwner, 'pid' | 'nonce'> | null | undefined): boolean {
+ return sameProcess(owner);
}
/** Test seam. */
export function setClaimOwnerForTest(owner: ClaimOwner | undefined): void { ownerOverride = owner; }
diff --git a/src/core/persistence/consumer-election.ts b/src/core/persistence/consumer-election.ts
new file mode 100644
index 0000000000..60f83a19e1
--- /dev/null
+++ b/src/core/persistence/consumer-election.ts
@@ -0,0 +1,270 @@
+/**
+ * #6317 (B1): one full persistence consumer per host, as a preference.
+ *
+ * A resident process (`sync`, `jobs`, `autopilot`, `mcp`) that would start a
+ * consumer first asks the database whether a live full consumer already runs
+ * on this host (consumer-heartbeat.ts). If one does, this process becomes a
+ * waiter: it keeps the consumer's whole external surface so `awaitWrite` and
+ * every other caller work unchanged, but it claims nothing and writes no
+ * heartbeat row; its writes are published by the owner and reach it through
+ * the ordinary receipt polls. A `serve` always starts full and short-lived
+ * foreground commands (`put`, `import`, `cli`, ...) keep their own consumer
+ * (service.ts decides; this class never sees them).
+ *
+ * Mode machine (`ConsumerMode`):
+ *
+ * start()
+ * │
+ * ┌────▼────┐ switch off · no live owner · probe error · 3 probe timeouts · forced
+ * │ probing ├──────────────────────────────────────────────────────────────┐
+ * └────┬────┘ │
+ * │ live full resident owner (not this process, not wedged) │
+ * ┌──────▼──────┐ owner lapsed 60 s · wedged · not full · gone ┌───▼───┐
+ * ┌───►│ waiter_only ├────────────────────────────────────────────────────►┐ │ full │ (never demoted)
+ * │ └──────▲──────┘ │ └───▲───┘
+ * │ │ promote() (forced: --no-delegate, skew fallback) ─────────────────┘
+ * │ │ │
+ * │ owner's row `full`, live and healthy for 3 consecutive ticks ┌─────▼────┐
+ * └──────────────────────────────────────────────────────────────────┤ promoted │
+ * drain back (finish in-flight, claim nothing) └──────────┘
+ *
+ * Every transition is decided by one indexed read of `persistence_consumers`
+ * per tick, single-flight under the consumer's phase deadline, backing off
+ * with the consumer's idle delay. `stop()` cancels and awaits the in-flight
+ * probe before the engine closes; a result that lands after `stop()` is
+ * dropped. Only a consumer that was promoted drains back, and only for an
+ * owner whose row says `full` (an elected owner, never another promoted
+ * waiter), so a promotion storm after a heartbeat outage converges and two
+ * consumers that both started full stay full until one exits (doctor names
+ * them). PGLite admits one process, so the probe is inert there and the
+ * consumer goes full on its first tick.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { GBrainConfig } from '../config.ts';
+import { LANE_BUSY, type ConsumerStatus, type PersistenceConsumer, type PersistenceConsumerLike } from './consumer.ts';
+import {
+ CONSUMER_LAPSED_MS, CONSUMER_LIVE_MS, consumerIdentity, consumerWedged, listHostConsumers, RESIDENT_CONSUMER_KINDS, startConsumerHeartbeat,
+ type ConsumerHeartbeat, type ConsumerPool, type ConsumerProcessIdentity, type ListedConsumer,
+} from './consumer-heartbeat.ts';
+import { DEFAULT_PREPARATION_POLICY } from './preparation-budget.ts';
+import { readWriteSwitchSnapshot } from './switches.ts';
+
+export type ConsumerMode = 'probing' | 'full' | 'waiter_only' | 'promoted';
+/** Consecutive ticks a recovered owner must look healthy before a promoted consumer drains back. */
+export const DRAIN_BACK_HEALTHY_TICKS = 3;
+/** Consecutive probe timeouts before the consumer stops waiting for an answer and starts full. */
+export const PROBE_TIMEOUT_MISSES = 3;
+
+let ownConsumerForced: string | null = null;
+/**
+ * B1d: the process-level escape hatch (`gbrain sync --no-delegate`, or the skew fallback when an older `serve` cannot take a
+ * hand-off): every consumer this process starts from now on is full, and a waiter-only consumer already made promotes.
+ */
+export function forceOwnConsumer(reason: string): void { ownConsumerForced = reason; }
+export function ownConsumerForcedReason(): string | null { return ownConsumerForced; }
+/** Test seam. */
+export function resetOwnConsumerForTest(): void { ownConsumerForced = null; }
+
+/** The owner a waiter defers to, as its status and the `writer_pending` envelope name it. */
+export interface ElectedOwner { kind: string; pid: number; nonce: string; pid_ns: string | null; version: string; started_at: string; renewed_age_ms: number;
+ restart_required: boolean; root_barrier_age_ms: number | null; mode: string }
+
+/**
+ * The owner to defer to among `rows`, or null: a resident-kind row that is not this process, in mode `full` or `promoted`,
+ * not wedged and live (renewed within `CONSUMER_LIVE_MS`); the current owner is kept while it is merely stale (under
+ * `CONSUMER_LAPSED_MS`), so one slow renewal does not promote every waiter on the host.
+ */
+export function electOwner(rows: readonly ListedConsumer[], current: Pick<ListedConsumer, 'pid' | 'nonce'> | null, ceilingMs: number,
+ self: ConsumerProcessIdentity = consumerIdentity()): ListedConsumer | null {
+ const eligible = rows.filter(row => !(row.pid === self.pid && row.nonce === self.nonce) && RESIDENT_CONSUMER_KINDS.includes(row.kind)
+ && (row.mode === 'full' || row.mode === 'promoted') && !consumerWedged(row, ceilingMs));
+ const kept = current ? eligible.find(row => row.pid === current.pid && row.nonce === current.nonce && row.renewed_age_ms < CONSUMER_LAPSED_MS) : undefined;
+ if (kept) return kept;
+ return eligible.find(row => row.renewed_age_ms < CONSUMER_LIVE_MS) ?? null;
+}
+const ownerOf = (row: ListedConsumer): ElectedOwner => ({ kind: row.kind, pid: row.pid, nonce: row.nonce, pid_ns: row.pid_ns, version: row.version, started_at: row.started_at,
+ renewed_age_ms: row.renewed_age_ms, restart_required: row.restart_required, root_barrier_age_ms: row.root_barrier_age_ms, mode: row.mode });
+
+export interface WaiterOnlyConsumerOpts {
+ /** The gbrain command this process runs (`claimOwnerKind()`); resident kinds only reach this class. */
+ kind: string;
+ hostId: string;
+ pollMs?: number;
+ idleMaxMs?: number;
+ /** Deadline of one probe (the consumer's phase deadline). */
+ phaseMs?: number;
+ /** Test seams: the consumer rows of this host, the switch, the ceiling, the heartbeat cadence and the log sink. */
+ readConsumers?: (signal: AbortSignal) => Promise<ListedConsumer[]>;
+ singleConsumer?: () => Promise<boolean>;
+ ceilingMs?: () => Promise<number>;
+ heartbeatEveryMs?: number;
+ pool?: () => ConsumerPool | null;
+ log?: (line: string) => void;
+}
+
+export class WaiterOnlyConsumer implements PersistenceConsumerLike {
+ private _mode: ConsumerMode = 'probing';
+ private inner: PersistenceConsumer | undefined;
+ private heartbeat: ConsumerHeartbeat | undefined;
+ private owner: ListedConsumer | null = null;
+ private healthyOwnerTicks = 0;
+ private probeTimeouts = 0;
+ private stopping = false;
+ private timer: ReturnType<typeof setTimeout> | undefined;
+ private tickPromise: Promise<void> | undefined;
+ private transition: Promise<void> | undefined;
+ private delayMs: number;
+ private wakeRequested = false;
+ private readonly self = consumerIdentity();
+ constructor(readonly engine: BrainEngine, readonly config: GBrainConfig, private readonly makeConsumer: () => PersistenceConsumer, private readonly opts: WaiterOnlyConsumerOpts) {
+ this.delayMs = opts.pollMs ?? 250;
+ }
+ get mode(): ConsumerMode { return this._mode; }
+ /** The owner this process defers to (waiter-only), or null. */
+ electedOwner(): ElectedOwner | null { return this.owner ? ownerOf(this.owner) : null; }
+ start(): void {
+ this.stopping = false;
+ if (this.engine.kind !== 'postgres' || ownConsumerForced !== null) { this.becomeFull('full', this.engine.kind !== 'postgres' ? 'single_process_engine' : `forced:${ownConsumerForced}`); return; }
+ this.schedule(0);
+ }
+ private schedule(ms: number): void {
+ if (this.stopping || this._mode === 'full') return;
+ if (this.tickPromise) { if (ms === 0) this.wakeRequested = true; return; }
+ if (this.timer) clearTimeout(this.timer);
+ this.timer = setTimeout(() => { this.timer = undefined; void this.probeTick(); }, ms);
+ this.timer.unref?.();
+ }
+ /** The full consumer's tick once this process consumes; a probe tick while it decides. */
+ tick(afterProgress = false): Promise<void> {
+ return this.inner ? this.inner.tick(afterProgress) : this.probeTick();
+ }
+ /** One probe tick (single-flight); the timer calls it. */
+ probeTick(): Promise<void> {
+ if (this.tickPromise) return this.tickPromise;
+ this.tickPromise = this.doTick().catch(() => undefined).finally(() => {
+ this.tickPromise = undefined;
+ if (this.stopping || this._mode === 'full') return;
+ const next = this.wakeRequested ? 0 : this.delayMs;
+ this.wakeRequested = false;
+ this.schedule(next);
+ });
+ return this.tickPromise;
+ }
+ private backoff(): void { this.delayMs = Math.min(Math.max(this.delayMs, this.opts.pollMs ?? 250) * 2, Math.max(this.opts.pollMs ?? 250, this.opts.idleMaxMs ?? 5000)); }
+ private log(line: string): void {
+ if (this.opts.log) { this.opts.log(line); return; }
+ process.stderr.write(`[persistence] ${line}; fix: gbrain sources writer status --json; docs: docs/guides/live-sync.md#one-consumer-per-host\n`);
+ }
+ private async doTick(): Promise<void> {
+ if (this.stopping || this._mode === 'full') return;
+ 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);
+ 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));
+ 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 }));
+ } catch (error) {
+ if (this.stopping) return;
+ if (cancel.signal.aborted) {
+ // The database did not answer in time: stay in this mode for this tick; after three misses a probing consumer starts full.
+ if (++this.probeTimeouts >= PROBE_TIMEOUT_MISSES && this._mode === 'probing') { this.log(`phase=consumer_probe reason=probe_timeout message="no answer in ${PROBE_TIMEOUT_MISSES} probes; running own consumer"`); await this.becomeFull('full', 'probe_timeout'); }
+ else this.backoff();
+ return;
+ }
+ // A read the database cannot answer (an older schema, a refused statement): today's behaviour, one log line.
+ if (this._mode === 'probing') { this.log(`phase=consumer_probe reason=probe_failed message="${error instanceof Error ? error.message.replace(/\s+/g, ' ').slice(0, 200) : String(error)}; running own consumer"`); await this.becomeFull('full', 'probe_failed'); }
+ else this.backoff();
+ return;
+ } finally { clearTimeout(timer); }
+ if (this.stopping) return;
+ this.probeTimeouts = 0;
+ const owner = electOwner(rows, this.owner, ceiling, this.self);
+ if (this._mode === 'probing') {
+ if (!owner) { await this.becomeFull('full', 'no_live_owner'); return; }
+ this.owner = owner; this._mode = 'waiter_only';
+ this.log(`phase=consumer_probe reason=waiter_only message="deferring to ${owner.kind} pid ${owner.pid} on this host; this process claims nothing"`);
+ this.backoff();
+ return;
+ }
+ if (this._mode === 'waiter_only') {
+ if (owner) { this.owner = owner; this.backoff(); return; }
+ const was = this.owner;
+ this.log(`phase=consumer_probe reason=owner_lapsed promoted_to_consumer message="${was ? `${was.kind} pid ${was.pid} is ${was.renewed_age_ms >= CONSUMER_LAPSED_MS ? 'lapsed' : was.restart_required ? 'restart_required' : 'wedged or gone'}` : 'no live owner'}"`);
+ await this.becomeFull('promoted', 'owner_lapsed');
+ return;
+ }
+ // promoted: drain back once an elected (`full`) owner has been live and healthy for three consecutive ticks.
+ if (owner && owner.mode === 'full') {
+ this.owner = owner;
+ if (++this.healthyOwnerTicks >= DRAIN_BACK_HEALTHY_TICKS) { await this.drainBack(owner); return; }
+ } else { this.healthyOwnerTicks = 0; if (owner) this.owner = owner; }
+ this.backoff();
+ }
+ private becomeFull(mode: 'full' | 'promoted', reason: string): Promise<void> {
+ if (this.transition) return this.transition;
+ this.transition = (async () => {
+ if (this.stopping || this.inner) return;
+ this._mode = mode;
+ this.healthyOwnerTicks = 0;
+ const inner = this.makeConsumer();
+ this.inner = inner;
+ this.heartbeat = startConsumerHeartbeat(this.engine, this.opts.hostId, { kind: this.opts.kind, mode: () => this._mode, everyMs: this.opts.heartbeatEveryMs, deadlineMs: this.opts.phaseMs,
+ report: () => ({ restart_required: inner.restartRequired(), root_barrier_age_ms: inner.oldestRootBarrierAgeMs(), pool: this.opts.pool?.() ?? null }) });
+ inner.start();
+ if (mode === 'full') { if (this.timer) clearTimeout(this.timer); this.timer = undefined; }
+ if (reason !== 'no_live_owner' && reason !== 'single_consumer_off' && reason !== 'single_process_engine') this.log(`phase=consumer_probe reason=${mode} message="${reason}"`);
+ })().finally(() => { this.transition = undefined; });
+ return this.transition;
+ }
+ private drainBack(owner: ListedConsumer): Promise<void> {
+ if (this.transition) return this.transition;
+ this.transition = (async () => {
+ const inner = this.inner;
+ if (!inner || this.stopping) return;
+ this.log(`phase=consumer_probe reason=drained_back message="${owner.kind} pid ${owner.pid} is live again; finishing in-flight work, then deferring"`);
+ // stop() finishes in-flight tasks and claims nothing new; the heartbeat row goes with it.
+ await inner.stop();
+ await this.heartbeat?.stop();
+ if (this.inner === inner) { this.inner = undefined; this.heartbeat = undefined; this._mode = 'waiter_only'; this.owner = owner; this.healthyOwnerTicks = 0; }
+ })().finally(() => { this.transition = undefined; });
+ return this.transition;
+ }
+ /** B1d: a waiter-only (or probing) consumer becomes full now and never drains back. */
+ promote(reason = 'promote'): Promise<void> {
+ if (this.inner) { this._mode = 'full'; if (this.timer) clearTimeout(this.timer); this.timer = undefined; return Promise.resolve(); }
+ return this.becomeFull('full', reason);
+ }
+ wake(ownAdmission = false): void {
+ if (this.inner) { this.inner.wake(ownAdmission); return; }
+ // A waiter claims nothing; the wake only brings the next probe forward so a lapsed owner is noticed sooner.
+ this.delayMs = this.opts.pollMs ?? 250;
+ this.schedule(0);
+ }
+ holds(id: string): boolean { return this.inner?.holds(id) ?? false; }
+ foregroundCompletions(worktreeId: string): number { return this.inner?.foregroundCompletions(worktreeId) ?? 0; }
+ onLane<T>(run: (transaction: <R>(fn: (tx: BrainEngine) => Promise<R>) => Promise<R>) => Promise<T>): Promise<T | typeof LANE_BUSY> {
+ return this.inner ? this.inner.onLane(run) : Promise.resolve(LANE_BUSY);
+ }
+ restartRequired(): boolean { return this.inner?.restartRequired() ?? false; }
+ status(): ConsumerStatus {
+ 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 };
+ }
+ async stop(): Promise<void> {
+ this.stopping = true;
+ if (this.timer) { clearTimeout(this.timer); this.timer = undefined; }
+ await this.tickPromise;
+ await this.transition;
+ await this.inner?.stop();
+ await this.heartbeat?.stop();
+ }
+}
diff --git a/src/core/persistence/consumer-heartbeat.ts b/src/core/persistence/consumer-heartbeat.ts
new file mode 100644
index 0000000000..ca95b028ef
--- /dev/null
+++ b/src/core/persistence/consumer-heartbeat.ts
@@ -0,0 +1,248 @@
+/**
+ * #6317 (B1a, B3): the per-process heartbeat of a full persistence consumer and
+ * the probe a resident process runs before starting its own.
+ *
+ * One row per process in `persistence_consumers` (migration v221), keyed by
+ * `(host_id, pid, nonce)`: the nonce is random per process and `pid_ns` is the
+ * pid-namespace inode, so a reused pid after a container restart, or the same
+ * pid in two namespaces sharing one `GBRAIN_HOME`, is never mistaken for the
+ * same consumer. `renewed_at` is the liveness signal: live within
+ * `CONSUMER_LIVE_MS`, lapsed at `CONSUMER_LAPSED_MS`, and each renewal deletes
+ * this host's rows lapsed longer than `CONSUMER_PURGE_MS` in the same statement
+ * (a data-modifying CTE; idempotent, no lock). The row also carries the owner's
+ * own wedge report (`restart_required`, the age of its oldest abandoned root
+ * barrier) and its identity file paths, so a waiter and doctor judge the owner
+ * from the database alone, never from a socket or its filesystem.
+ *
+ * The heartbeat is single-flight on its own timer (default every 10 s, each
+ * renewal under its own deadline), independent of claim renewal: an idle
+ * `serve` holds no claim and still has to prove it is alive. Renewals run on
+ * the engine's direct lane (`executeRawDirect`, as the claim lease does). On
+ * Postgres that lane leaves the ordinary pool only when the dual pool is
+ * active (postgres-engine.ts `executeRawDirect`: `connectionManager.ddl()` is
+ * taken only when `isDualPoolActive()`), so with a single URL the heartbeat
+ * shares the ordinary pool and a starved pool stops it. That is acceptable: the
+ * row is a liveness signal, not a progress signal, and a starved owner losing
+ * its suppression is the wanted outcome. A failed renewal is logged once per
+ * failure streak and never stops the consumer. PGLite admits one process, so
+ * the probe answers "no owner" and the heartbeat writes nothing there.
+ */
+import { randomBytes } from 'node:crypto';
+import { readlinkSync } from 'node:fs';
+import type { BrainEngine } from '../engine.ts';
+import { VERSION } from '../../version.ts';
+import { localHostIdentity } from './identity.ts';
+import type { SqlEngine } from './model.ts';
+
+/** Kinds whose process stays resident: they defer to the first live full consumer of their host (`serve` always starts full). */
+export const RESIDENT_CONSUMER_KINDS: readonly string[] = ['serve', 'sync', 'jobs', 'autopilot', 'mcp'];
+/** A row renewed within this window is live. */
+export const CONSUMER_LIVE_MS = 30_000;
+/** A row not renewed for this long is lapsed: its process is gone or starved; a waiter promotes itself. */
+export const CONSUMER_LAPSED_MS = 60_000;
+/** A row lapsed this long is deleted by the next renewal of any consumer on the host. */
+export const CONSUMER_PURGE_MS = 90_000;
+/** Renewal cadence of a full consumer's heartbeat. */
+export const CONSUMER_RENEWAL_MS = 10_000;
+/** How long one renewal or probe may take before it is dropped (the consumer's phase deadline). */
+export const CONSUMER_DEADLINE_MS = 5_000;
+
+export type ConsumerRowMode = 'probing' | 'full' | 'waiter_only' | 'promoted';
+/** Process identity: `{ pid, nonce, pid_ns }`; `kind` names the gbrain command. */
+export interface ConsumerProcessIdentity { pid: number; nonce: string; pid_ns: string | null }
+export interface ConsumerPool { checked_out: number; max: number; waiters: number }
+export interface ConsumerRow {
+ host_id: string;
+ pid: number;
+ nonce: string;
+ pid_ns: string | null;
+ kind: string;
+ mode: ConsumerRowMode;
+ started_at: string;
+ renewed_at: string;
+ restart_required: boolean;
+ root_barrier_age_ms: number | null;
+ pool: ConsumerPool | null;
+ host_json_path: string;
+ persistence_home: string;
+ minted_under: Record<string, unknown> | null;
+ version: string;
+}
+/** A row as `listHostConsumers` returns it: the row plus its liveness, read on the database clock. */
+export interface ListedConsumer extends ConsumerRow {
+ /** Milliseconds since the last renewal. */
+ renewed_age_ms: number;
+ /** Milliseconds since the process started its consumer. */
+ age_ms: number;
+ liveness: 'live' | 'stale' | 'lapsed';
+ /** Whether this row belongs to the calling process. */
+ self: boolean;
+}
+
+let identity: ConsumerProcessIdentity | undefined;
+/** This process's identity for stamps and rows: pid, a random per-process nonce, and the pid namespace where readable. */
+export function consumerIdentity(): ConsumerProcessIdentity {
+ if (identity) return identity;
+ let pidNs: string | null = null;
+ try { pidNs = readlinkSync('/proc/self/ns/pid'); } catch { pidNs = null; }
+ identity = { pid: process.pid, nonce: randomBytes(8).toString('hex'), pid_ns: pidNs };
+ return identity;
+}
+/** Test seam: a fresh identity, so one test process can play several consumers. */
+export function resetConsumerIdentityForTest(next?: Partial<ConsumerProcessIdentity>): ConsumerProcessIdentity {
+ identity = undefined;
+ identity = { ...consumerIdentity(), ...next };
+ return identity;
+}
+/** Whether `owner` (a claim stamp's or a row's identity) is this process: the pid and, when both sides carry one, the nonce. */
+export function sameProcess(owner: { pid?: number | null; nonce?: string | null } | null | undefined, self: ConsumerProcessIdentity = consumerIdentity()): boolean {
+ if (!owner || owner.pid !== self.pid) return false;
+ return owner.nonce == null || owner.nonce === self.nonce;
+}
+
+const ROW_COLUMNS = `host_id::text AS host_id,pid,nonce,pid_ns,kind,mode,started_at::text AS started_at,renewed_at::text AS renewed_at,restart_required,root_barrier_age_ms,pool,
+ host_json_path,persistence_home,minted_under,version,(EXTRACT(EPOCH FROM (now()-renewed_at))*1000)::bigint::text AS renewed_age_ms,
+ (EXTRACT(EPOCH FROM (now()-started_at))*1000)::bigint::text AS age_ms`;
+type RawRow = Omit<ConsumerRow, 'pool' | 'minted_under'> & { pool: unknown; minted_under: unknown; renewed_age_ms: string; age_ms: string };
+
+function parseJson(value: unknown): Record<string, unknown> | null {
+ if (value == null) return null;
+ if (typeof value === 'string') { try { return JSON.parse(value) as Record<string, unknown>; } catch { return null; } }
+ return typeof value === 'object' ? value as Record<string, unknown> : null;
+}
+function listed(row: RawRow, self: ConsumerProcessIdentity): ListedConsumer {
+ const renewedAge = Number(row.renewed_age_ms);
+ return { ...row, pool: parseJson(row.pool) as ConsumerPool | null, minted_under: parseJson(row.minted_under),
+ renewed_age_ms: renewedAge, age_ms: Number(row.age_ms),
+ liveness: renewedAge < CONSUMER_LIVE_MS ? 'live' : renewedAge < CONSUMER_LAPSED_MS ? 'stale' : 'lapsed',
+ self: row.pid === self.pid && row.nonce === self.nonce };
+}
+
+/** Every consumer row of `hostId`, oldest first, with liveness on the database clock. Empty on PGLite. */
+export async function listHostConsumers(engine: SqlEngine & Partial<Pick<BrainEngine, 'kind'>>, hostId: string, opts: { signal?: AbortSignal } = {}): Promise<ListedConsumer[]> {
+ if (engine.kind === 'pglite') return [];
+ const rows = await engine.executeRaw<RawRow>(`SELECT ${ROW_COLUMNS} FROM persistence_consumers WHERE host_id=$1::uuid ORDER BY started_at,pid`, [hostId], { signal: opts.signal });
+ const self = consumerIdentity();
+ return rows.map(row => listed(row, self));
+}
+
+/** A live owner's wedge report: `restart_required`, or a root barrier older than the preparation ceiling (the owner stops suppressing). */
+export function consumerWedged(row: Pick<ConsumerRow, 'restart_required' | 'root_barrier_age_ms'>, ceilingMs: number): boolean {
+ return row.restart_required || (row.root_barrier_age_ms !== null && row.root_barrier_age_ms >= ceilingMs);
+}
+
+/**
+ * The first live, full, resident-kind consumer of `hostId` that is not `self`
+ * and is not wedged (B1a), or null. Liveness is judged on the database clock
+ * (renewed within `CONSUMER_LIVE_MS`), so two hosts' clocks never enter it.
+ * PGLite admits one process: always null there. A read the database cannot
+ * answer rejects; the caller decides whether that means "no owner".
+ */
+export async function probeLiveFullConsumer(engine: SqlEngine & Partial<Pick<BrainEngine, 'kind'>>, hostId: string, self: ConsumerProcessIdentity = consumerIdentity(),
+ opts: { signal?: AbortSignal; ceilingMs?: number } = {}): Promise<ListedConsumer | null> {
+ if (engine.kind === 'pglite') return null;
+ const rows = await engine.executeRaw<RawRow>(`SELECT ${ROW_COLUMNS} FROM persistence_consumers
+ WHERE host_id=$1::uuid AND mode IN ('full','promoted') AND kind=ANY($2::text[]) AND NOT (pid=$3::integer AND nonce=$4)
+ AND renewed_at > now() - ($5::integer * interval '1 millisecond') AND NOT restart_required
+ ORDER BY started_at,pid LIMIT 8`, [hostId, [...RESIDENT_CONSUMER_KINDS], self.pid, self.nonce, CONSUMER_LIVE_MS], { signal: opts.signal });
+ const ceiling = opts.ceilingMs ?? 600_000;
+ const live = rows.map(row => listed(row, self)).find(row => !consumerWedged(row, ceiling));
+ return live ?? null;
+}
+
+export interface ConsumerHeartbeatOpts {
+ kind: string;
+ mode: ConsumerRowMode | (() => ConsumerRowMode);
+ /** The owner's own wedge report and pool numbers, read at each renewal. */
+ report: () => { restart_required: boolean; root_barrier_age_ms: number | null; pool?: ConsumerPool | null };
+ everyMs?: number;
+ deadlineMs?: number;
+ identity?: ConsumerProcessIdentity;
+ /** Receives each renewal failure (the default logs once per failure streak). */
+ onError?: (error: unknown) => void;
+ /** The file paths the row carries (default: this process's host.json and persistence home). */
+ paths?: { host_json_path: string; persistence_home: string; minted_under: Record<string, unknown> | null };
+}
+export interface ConsumerHeartbeat {
+ /** Renews now (single-flight: a renewal already in flight is awaited instead). Never rejects. */
+ renew(): Promise<void>;
+ /** The renewal failures so far, for status. */
+ readonly failures: number;
+ /** Stops renewing, awaits the in-flight renewal, then deletes this process's row (bounded). */
+ stop(): Promise<void>;
+}
+
+type DirectEngine = SqlEngine & Partial<Pick<BrainEngine, 'kind' | 'executeRawDirect'>>;
+const RENEW_SQL = `WITH purged AS (
+ DELETE FROM persistence_consumers WHERE host_id=$1::uuid AND renewed_at < now() - ($14::integer * interval '1 millisecond') AND NOT (pid=$2::integer AND nonce=$3))
+ INSERT INTO persistence_consumers(host_id,pid,nonce,pid_ns,kind,mode,restart_required,root_barrier_age_ms,pool,host_json_path,persistence_home,minted_under,version)
+ VALUES($1::uuid,$2::integer,$3,$4,$5,$6,$7::boolean,$8::integer,$9::text::jsonb,$10,$11,$12::text::jsonb,$13)
+ ON CONFLICT (host_id,pid,nonce) DO UPDATE SET renewed_at=now(),mode=EXCLUDED.mode,restart_required=EXCLUDED.restart_required,
+ root_barrier_age_ms=EXCLUDED.root_barrier_age_ms,pool=EXCLUDED.pool,version=EXCLUDED.version`;
+
+/**
+ * Starts this process's heartbeat row for `hostId` and renews it every
+ * `everyMs` (default 10 s). The first renewal runs at once. Each renewal is
+ * bounded by `deadlineMs`; an overrun is cancelled through its signal and
+ * counted as a failure. Inert on PGLite (`stop()` resolves at once).
+ */
+export function startConsumerHeartbeat(engine: DirectEngine, hostId: string, opts: ConsumerHeartbeatOpts): ConsumerHeartbeat {
+ if (engine.kind === 'pglite') return { renew: async () => {}, get failures() { return 0; }, stop: async () => {} };
+ const self = opts.identity ?? consumerIdentity();
+ const paths = opts.paths ?? (() => { const id = localHostIdentity(); return { host_json_path: id.path, persistence_home: id.persistence_home, minted_under: id.minted_under }; })();
+ const execute = (sql: string, params: unknown[], signal: AbortSignal) =>
+ engine.executeRawDirect ? engine.executeRawDirect(sql, params, { signal }) : engine.executeRaw(sql, params, { signal });
+ const everyMs = opts.everyMs ?? CONSUMER_RENEWAL_MS;
+ const deadlineMs = opts.deadlineMs ?? CONSUMER_DEADLINE_MS;
+ let stopped = false;
+ let failures = 0;
+ let streak = 0;
+ let inFlight: Promise<void> | undefined;
+ const report = (error: unknown) => {
+ failures++;
+ if (opts.onError) { opts.onError(error); return; }
+ if (streak++ > 0) return;
+ const message = error instanceof Error ? error.message.replace(/\s+/g, ' ').slice(0, 200) : String(error);
+ 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');
+ };
+ 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,
+ 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);
+ streak = 0;
+ } catch (error) {
+ if (!stopped) report(error);
+ } finally { clearTimeout(timer); }
+ };
+ const renew = (): Promise<void> => {
+ if (stopped) return Promise.resolve();
+ if (inFlight) return inFlight;
+ const attempt = renewOnce().finally(() => { if (inFlight === attempt) inFlight = undefined; });
+ inFlight = attempt;
+ return attempt;
+ };
+ const cadence = setInterval(() => { void renew(); }, everyMs);
+ cadence.unref?.();
+ void renew();
+ return {
+ renew,
+ get failures() { return failures; },
+ async stop() {
+ if (stopped) return;
+ stopped = true;
+ 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); }
+ 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.ts b/src/core/persistence/consumer.ts
index 7a17031a8f..6d765243dc 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -90,7 +90,30 @@ export const LANE_BUSY = Symbol('gbrain.laneBusy');
/** `clock` (#6278): the claim's phase clock, for `enterClaimStep` at the preparer's await boundaries. */
export type PrepareMutation = (engine: BrainEngine, row: WriteRequest, config: GBrainConfig, signal?: AbortSignal, clock?: ClaimPhaseClock) => Promise<PreparedMutation>;
-export class PersistenceConsumer {
+/** What `status()` always carries; the full consumer adds its sampled phases and preparations. */
+export interface ConsumerStatus extends Record<string, unknown> { accepting: boolean; active_preparations: number; active_worktrees: number; restart_required: boolean }
+/**
+ * #6317: the consumer's whole external surface, as `service.ts` and every
+ * `awaitWrite` caller use it. `PersistenceConsumer` is the full consumer;
+ * `WaiterOnlyConsumer` (consumer-election.ts) is the same surface for a
+ * process that defers to a live owner on its host and claims nothing.
+ */
+export interface PersistenceConsumerLike {
+ readonly engine: BrainEngine;
+ readonly config: GBrainConfig;
+ start(): void;
+ /** Mandatory barrier: engine.close must be sequenced AFTER this promise. */
+ stop(): Promise<void>;
+ wake(ownAdmission?: boolean): void;
+ /** One tick now (single-flight); tests drive the consumer with it. */
+ tick(afterProgress?: boolean): Promise<void>;
+ holds(id: string): boolean;
+ foregroundCompletions(worktreeId: string): number;
+ onLane<T>(run: (transaction: <R>(fn: (tx: BrainEngine) => Promise<R>) => Promise<R>) => Promise<T>): Promise<T | typeof LANE_BUSY>;
+ status(): ConsumerStatus;
+ restartRequired(): boolean;
+}
+export class PersistenceConsumer implements PersistenceConsumerLike {
private stopping = false;
private timer: ReturnType<typeof setTimeout> | undefined;
private tickPromise: Promise<void> | undefined;
@@ -109,8 +132,8 @@ export class PersistenceConsumer {
private active = new Set<Promise<void>>();
/** #5373: preparations and renewals that outlived their claim; stop() drains them before the engine closes. */
private outlived = new Set<Promise<void>>();
- /** #6278: preparations whose claim the budget (or a lost claim, with the switch on) released; stop() gives them ABANDONED_STOP_GRACE_MS. */
- private abandoned = new Set<Promise<void>>();
+ /** #6278: preparations whose claim the budget (or a lost claim, with the switch on) released, by the claim start they block their root from; stop() gives them ABANDONED_STOP_GRACE_MS. */
+ private abandoned = new Map<Promise<void>, number>();
/** #6278: abandoned preparations past the ceiling, by request row id. */
private zombies = new Map<string, AbandonedPreparation>();
private policy: EffectivePreparationPolicy = { ...DEFAULT_PREPARATION_POLICY, deadlines: true };
@@ -661,13 +684,24 @@ export class PersistenceConsumer {
* grace); off, to `outlived` as before (stop() waits for it). The returned
* promise never rejects.
*/
- private keepAbandoned(work: Promise<unknown>): Promise<void> {
+ private keepAbandoned(work: Promise<unknown>, claimedAt = Date.now()): Promise<void> {
if (!this.policy.deadlines) return this.keepUntilSettled(work);
const settled = work.then(() => undefined, () => undefined);
- this.abandoned.add(settled);
+ this.abandoned.set(settled, claimedAt);
void settled.then(() => { this.abandoned.delete(settled); });
return settled;
}
+ /**
+ * #6317: the age, from its claim start, of the oldest abandoned preparation still holding a root barrier (or a zombie past
+ * the ceiling); null when none. The heartbeat row carries it so a waiter-only consumer can see a wedged owner
+ * (a barrier older than `persistence.preparation_ceiling_ms`) that keeps renewing its heartbeat.
+ */
+ oldestRootBarrierAgeMs(now = Date.now()): number | null {
+ let oldest: number | undefined;
+ for (const claimedAt of this.abandoned.values()) if (oldest === undefined || claimedAt < oldest) oldest = claimedAt;
+ for (const zombie of this.zombies.values()) { const at = Date.parse(zombie.claimed_at); if (oldest === undefined || at < oldest) oldest = at; }
+ return oldest === undefined ? null : Math.max(0, now - oldest);
+ }
/**
* #6278: the #5373 root barrier for an abandoned preparation, bounded by the
* hard ceiling measured from the claim. At the ceiling the root is freed, the
@@ -734,7 +768,7 @@ export class PersistenceConsumer {
// The budget passed (on the timer, or reported by a bounded read the server ended): the claim is released now, charged,
// 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));
+ 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 ((row.preparation_attempts ?? 0) + 1 >= policy.maxAttempts) {
const done = await finishPreparationStalled(this.engine, row, stallInfo(), true);
@@ -748,7 +782,7 @@ export class PersistenceConsumer {
// With the switch on the budget wins the race even against a preparer that ignores its signal; off, the preparer's own settlement decides.
const raced = await lease.whileHeld(policy.deadlines ? prep.outcome : prep.work.then(result => ({ result })));
if (raced === CLAIM_LOST) {
- root.until = this.abandonedRootBlock(row, clock, this.keepAbandoned(prep.work));
+ root.until = this.abandonedRootBlock(row, clock, this.keepAbandoned(prep.work, clock.claimedAt));
await endLostLease(lease);
await releaseUnpublishedClaim(this.engine, row, 'claim_lost');
return false;
@@ -817,7 +851,7 @@ export class PersistenceConsumer {
leftRunning: (work, blocksRoot, abandoned) => {
if (!blocksRoot) { this.keepUntilSettled(work); return; }
// #6278: an abandoned member blocks its root until it settles or the ceiling passes; several abandoned members all hold it.
- const settled = this.keepAbandoned(work);
+ const settled = this.keepAbandoned(work, abandoned?.clock.claimedAt);
const block = abandoned ? this.abandonedRootBlock(abandoned.row, abandoned.clock, settled) : settled;
root.until = root.until ? Promise.all([root.until, block]).then(() => undefined) : block;
},
@@ -843,7 +877,7 @@ export class PersistenceConsumer {
// renewals and publications in `outlived` keep their bounded waits.
if (this.abandoned.size) {
let timer: ReturnType<typeof setTimeout> | undefined;
- await Promise.race([Promise.allSettled([...this.abandoned]), new Promise<void>(resolve => { timer = setTimeout(resolve, ABANDONED_STOP_GRACE_MS); })]);
+ await Promise.race([Promise.allSettled([...this.abandoned.keys()]), new Promise<void>(resolve => { timer = setTimeout(resolve, ABANDONED_STOP_GRACE_MS); })]);
if (timer) clearTimeout(timer);
}
while (this.outlived.size) await Promise.all([...this.outlived]);
diff --git a/src/core/persistence/identity.ts b/src/core/persistence/identity.ts
index a7c5fb2214..9373d1a2e5 100644
--- a/src/core/persistence/identity.ts
+++ b/src/core/persistence/identity.ts
@@ -2,6 +2,7 @@ import { randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
import { AsyncLocalStorage } from 'node:async_hooks';
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, writeFileSync, fsyncSync, linkSync, unlinkSync, renameSync } from 'node:fs';
import { join } from 'node:path';
+import { hostname } from 'node:os';
import type { BrainEngine } from '../engine.ts';
import { configDir } from '../config.ts';
import { flushDirectory } from '../fs-durable.ts';
@@ -52,18 +53,47 @@ function privateJson<T>(path: string, create: () => T): T {
return JSON.parse(readFileSync(path, 'utf8')) as T;
} finally { closeSync(fd); unlinkSync(temporary); }
}
-export function localHostId(): string {
- const path = join(persistenceHome(), 'host.json');
- const value = privateJson<{ version: number; id: string }>(path, () => ({ version: 1, id: randomUUID() }));
+/**
+ * #6317 (I1): where a `host.json` was minted, recorded at mint time only so
+ * doctor `host_identity_mismatch` can say which `HOME`/`GBRAIN_HOME` each of
+ * two identities came from. Optional on the version-1 document (both readers
+ * reject any other version, so the version never changes); a file minted
+ * before this release reads as `minted_under: null`, reported as unknown.
+ */
+export interface HostIdentityMintedUnder { home: string | null; gbrain_home: string | null; hostname: string; machine_id: string | null }
+export interface HostIdentityFile { version: number; id: string; minted_under?: HostIdentityMintedUnder }
+export interface LocalHostIdentity { id: string; path: string; persistence_home: string; minted_under: HostIdentityMintedUnder | null }
+const MACHINE_ID_FILES = ['/etc/machine-id', '/var/lib/dbus/machine-id'];
+/** The stable machine id of a Linux host (`/etc/machine-id`), or null where none is readable (containers, macOS). */
+export function readMachineId(): string | null {
+ for (const file of MACHINE_ID_FILES) {
+ try { const text = readFileSync(file, 'utf8').trim(); if (/^[0-9a-f]{32}$/i.test(text)) return text.toLowerCase(); } catch { /* next candidate */ }
+ }
+ return null;
+}
+function mintedUnderNow(): HostIdentityMintedUnder {
+ return { home: process.env.HOME ?? null, gbrain_home: process.env.GBRAIN_HOME ?? null, hostname: hostname(), machine_id: readMachineId() };
+}
+function readHostIdentity(path: string, create: boolean): HostIdentityFile | null {
+ if (!create && !existsSync(path)) return null;
+ const value = privateJson<HostIdentityFile>(path, () => ({ version: 1, id: randomUUID(), minted_under: mintedUnderNow() }));
if (value.version !== 1 || typeof value.id !== 'string') throw invalidIdentityFile('The local writer identity is invalid.', path, 'host identity');
- return value.id;
+ return value;
+}
+export function localHostId(): string {
+ return readHostIdentity(join(persistenceHome(), 'host.json'), true)!.id;
+}
+/** This process's host identity with its file path and mint metadata (minting the file when absent, as `localHostId` does). */
+export function localHostIdentity(): LocalHostIdentity {
+ const home = persistenceHome();
+ const path = join(home, 'host.json');
+ const value = readHostIdentity(path, true)!;
+ const minted = value.minted_under;
+ return { id: value.id, path, persistence_home: home,
+ minted_under: minted && typeof minted === 'object' ? { home: minted.home ?? null, gbrain_home: minted.gbrain_home ?? null, hostname: String(minted.hostname ?? ''), machine_id: minted.machine_id ?? null } : null };
}
export function existingLocalHostId(): string | null {
- const path = join(persistenceHome(), 'host.json');
- if (!existsSync(path)) return null;
- const value = JSON.parse(readFileSync(path, 'utf8')) as { version: number; id: string };
- if (value.version !== 1 || typeof value.id !== 'string') throw invalidIdentityFile('The local writer identity is invalid.', path, 'host identity');
- return value.id;
+ return readHostIdentity(join(persistenceHome(), 'host.json'), false)?.id ?? null;
}
async function brainIdentity(engine: SqlEngine): Promise<string> {
const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index 3365ced348..5bce8d18b9 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -15,7 +15,7 @@ import { computeContentHash } from '../ingestion/types.ts';
import { resolveSlugForPath } from '../sync.ts';
import { scannerSlugRootMode, scannerSourcePath } from '../write-through.ts';
import { sha256 } from './digest.ts';
-import { assertPersistenceAccepting, estimatedRetryAfterMs, onPersistenceLane, waitForWrite, writeResponse } from './service.ts';
+import { assertPersistenceAccepting, estimatedRetryAfterMs, waiterOnlyOwner, onPersistenceLane, waitForWrite, writeResponse } from './service.ts';
import { parseWireWriteWaitMs } from './write-wait.ts';
import { assertTimelineNotOmitted, isTimelineSection, timelineSectionOf, type TimelineSection } from './timeline-omission.ts';
import { admitWrite, assertPageRequestIdentity, assertReplayIntent, getWriteRequest, intentDigest, type WriteAdmission } from './journal.ts';
@@ -153,7 +153,7 @@ async function resolveCaptureFile(ctx: OperationContext, sourceId: string, p: Re
}
function pendingAwareResponse(ctx: OperationContext, row: WriteRequest): Record<string, unknown> {
- try { return writeResponse(row, { retryAfterMs: estimatedRetryAfterMs(ctx.engine, 1) }); } catch (error) {
+ try { return writeResponse(row, { retryAfterMs: estimatedRetryAfterMs(ctx.engine, 1), waiterOnlyOwner: waiterOnlyOwner(ctx.engine) }); } catch (error) {
// #5929: a trusted local caller is told when an owner on another build ran the failed attempt.
const mismatch = ctx.remote === false ? ownerBuildMismatch(row.error_detail, VERSION) : null;
if (mismatch && error instanceof OperationError) { error.why = mismatch.why; error.fix = mismatch.fix; }
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.ts
index 332f9ddce1..baa45d36b6 100644
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@ -1,13 +1,17 @@
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import { OperationError } from '../ops/contract.ts';
-import { LANE_BUSY, PersistenceConsumer, type PrepareMutation } from './consumer.ts';
+import { LANE_BUSY, PersistenceConsumer, type PersistenceConsumerLike, type PrepareMutation } from './consumer.ts';
+import { WaiterOnlyConsumer, type ElectedOwner } from './consumer-election.ts';
+import { RESIDENT_CONSUMER_KINDS, startConsumerHeartbeat, type ConsumerHeartbeat } from './consumer-heartbeat.ts';
+import { claimOwnerKind } from './claim-phase.ts';
import { preparePageMutation } from './page-prepare.ts';
import { prepareSemanticPageMutation } from './semantic-pages.ts';
import { getWriteRequestById, getWriteRequestProgress, receiptFor, type WriteRequestProgress } from './journal.ts';
import { isTerminal, type WriteRequest } from './model.ts';
import { isWriteErrorCode, type WriteReceipt } from './types.ts';
import { registerPgliteReopen } from '../pglite-lifecycle.ts';
+import { localHostId } from './identity.ts';
import { assertMutationProtocol } from './protocol.ts';
import { writeSwitchOn } from './switches.ts';
import { pendingWriteHint } from './health.ts';
@@ -19,7 +23,7 @@ import { fenceIssuesFromDetail, fenceLocationFromDetail } from '../fence-repair/
import { heldFileDiagnostic } from './verb-errors.ts';
import { isMissingPageMessage } from './page-identity.ts';
-interface Service { consumer: PersistenceConsumer; stopping: boolean; unregisterStop?: () => void; unregisterReopen?: () => void; }
+interface Service { consumer: PersistenceConsumerLike; heartbeat?: ConsumerHeartbeat; stopping: boolean; unregisterStop?: () => void; unregisterReopen?: () => void; }
const services = new WeakMap<BrainEngine, Service>();
type ProgressRead = { row: WriteRequestProgress | null } | { error: unknown } | { cancelled: true };
const receiptReads = new WeakMap<BrainEngine, Map<string, { read: Promise<ProgressRead>; abort: AbortController }>>();
@@ -85,7 +89,13 @@ export async function preparePersistedMutation(e: BrainEngine, row: WriteRequest
{ coordinated: await writeSwitchOn(e, 'single_write_group').catch(() => true), clock });
throw new OperationError('unsupported_mutation_protocol', 'No compatible mutation preparer is registered for this operation.', `Request ${row.request_id} (${row.operation}) was accepted by a gbrain version whose preparer this one lacks, so it has not run. Run gbrain upgrade on every host that serves this brain; the request stays journaled and resumes after the upgrade.`);
}
-export function startPersistenceConsumer(engine: BrainEngine, config: GBrainConfig): PersistenceConsumer {
+/**
+ * #6317 (B1): starts this process's consumer, synchronously. A `serve` and every short-lived foreground command (`put`,
+ * `import`, `cli`, ...) get a full consumer at once, with its heartbeat row; the other resident kinds (`sync`, `jobs`,
+ * `autopilot`, `mcp`) get a `WaiterOnlyConsumer` that probes the host's consumer rows on its first tick and settles to
+ * full or waiter-only (consumer-election.ts). Either way the returned object has the consumer's whole surface.
+ */
+export function startPersistenceConsumer(engine: BrainEngine, config: GBrainConfig): PersistenceConsumerLike {
const prior = services.get(engine);
if (prior) {
if (prior.stopping) {
@@ -94,9 +104,14 @@ export function startPersistenceConsumer(engine: BrainEngine, config: GBrainConf
}
return prior.consumer;
}
- const consumer = new PersistenceConsumer(engine, config, preparePersistedMutation,
+ const full = () => new PersistenceConsumer(engine, config, preparePersistedMutation,
{ onSettled: row => { recordSettlement(engine); for (const listener of settledWaiters.get(engine)?.get(row.id) ?? []) listener(row); } });
- const service: Service = { consumer, stopping: false };
+ const kind = claimOwnerKind();
+ const service: Service = kind !== 'serve' && RESIDENT_CONSUMER_KINDS.includes(kind) && engine.kind === 'postgres'
+ ? { consumer: new WaiterOnlyConsumer(engine, config, full, { kind, hostId: localHostId() }), stopping: false }
+ : (() => { const consumer = full(); return { consumer, stopping: false, heartbeat: startConsumerHeartbeat(engine, consumer.hostId,
+ { kind, mode: 'full', report: () => ({ restart_required: consumer.restartRequired(), root_barrier_age_ms: consumer.oldestRootBarrierAgeMs() }) }) }; })();
+ const { consumer } = service;
services.set(engine, service);
const lifecycle = engine as BrainEngine & { registerBeforeDisconnect?: (run: () => Promise<void>) => unknown };
const unregister = lifecycle.registerBeforeDisconnect?.(() => stopPersistenceConsumer(engine));
@@ -117,8 +132,14 @@ export async function stopPersistenceConsumer(engine: BrainEngine): Promise<void
const pending = [...(receiptReads.get(engine)?.values() ?? [])];
for (const entry of pending) entry.abort.abort();
await service.consumer.stop();
+ await service.heartbeat?.stop();
await Promise.all(pending.map(entry => entry.read));
}
+/** #6317: the owner a waiter-only consumer in this process defers to, for the `writer_pending` envelope; null when this process consumes itself. */
+export function waiterOnlyOwner(engine: BrainEngine): ElectedOwner | null {
+ const consumer = services.get(engine)?.consumer;
+ return consumer instanceof WaiterOnlyConsumer && consumer.mode === 'waiter_only' ? consumer.electedOwner() : null;
+}
/** Reset fixtures and drained lifecycle owners may discard a stopped service. */
export async function disposePersistenceConsumer(engine: BrainEngine): Promise<void> {
const service = services.get(engine);
@@ -277,7 +298,7 @@ function terminalReceiptHint(row: WriteRequest, reason: string): string {
? `${what} Submit again only if the change is still wanted, with a new request_id.`
: `${what} Read the receipt and the current state before deciding to submit again; a new attempt needs a new request_id.`;
}
-export function writeResponse(row: WriteRequest, hints: { retryAfterMs?: number | null } = {}): Record<string, unknown> {
+export function writeResponse(row: WriteRequest, hints: { retryAfterMs?: number | null; waiterOnlyOwner?: ElectedOwner | null } = {}): Record<string, unknown> {
const receipt = receiptFor(row);
// #6007: an in-process estimate beats the fixed fallback, never an owner-inspection hold.
if (!isTerminal(row) && hints.retryAfterMs != null && receipt.diagnostic?.next_action !== 'inspect_owner') receipt.retry_after_ms = hints.retryAfterMs;
@@ -293,6 +314,15 @@ export function writeResponse(row: WriteRequest, hints: { retryAfterMs?: number
? pendingWriteHint(receipt, row.operation)
: delivered?.suggestion ?? content?.suggestion ?? held?.suggestion ?? terminalReceiptHint(row, reason), delivered?.docs);
if (delivered?.detail ?? held?.reason) error.detail = delivered?.detail ?? held?.reason;
+ // #6317 (B1b): a waiter-only process names the owner that publishes for it, so the caller is told who holds the write instead of polling blind.
+ if (!isTerminal(row) && hints.waiterOnlyOwner) {
+ const owner = hints.waiterOnlyOwner;
+ const claim = receipt.diagnostic as { claim?: { stall?: { step?: string | null } } } | undefined;
+ error.why = `${error.why} This process runs no consumer of its own: the ${owner.kind} process (pid ${owner.pid}) on this host owns publication${claim?.claim?.stall?.step ? `, and its claim is stalled on step ${claim.claim.stall.step}` : ''}.`;
+ error.fix = { argv: ['gbrain', 'sources', 'writer', 'status', '--source', row.source_id, '--json'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Read-only: names the owner process, the running claim\'s step and every write waiting behind it.',
+ verify: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', row.source_id, '--json'] } };
+ }
if (content) {
if (content.code !== reason) error.canonical = content.code;
if (content.reason) error.reason = content.reason;
diff --git a/src/core/persistence/switches.ts b/src/core/persistence/switches.ts
index 221de777f3..5caf8bb11a 100644
--- a/src/core/persistence/switches.ts
+++ b/src/core/persistence/switches.ts
@@ -1,8 +1,9 @@
/**
* Kill switches for write-path behaviors, read from one per-process snapshot.
*
- * Every switch is on by default. An environment variable overrides the brain
- * config key; `0` or `false` (either source) turns a switch off. The snapshot
+ * Every switch is on by default unless its entry says `defaultOn: false`. An
+ * environment variable overrides the brain config key; `0` or `false` (either
+ * source) turns a switch off, `1` or `true` turns it on. The snapshot
* reads every switch key in one statement and is reused for SWITCH_TTL_MS, so
* `gbrain config set <key> false` reaches a running `serve` within that time
* without a round trip per write. Config writes are trusted-local only (no
@@ -22,6 +23,11 @@ export const WRITE_SWITCHES = {
foreground_priority: { key: 'sync.foreground_priority', env: 'GBRAIN_SYNC_FOREGROUND_PRIORITY' },
/** #6278: every preparation has a deadline and a counted attempt; off restores the 30 s budget for remember/put_page/edit_page only and never counts. */
preparation_deadlines: { key: 'persistence.preparation_deadlines', env: 'GBRAIN_PREPARATION_DEADLINES' },
+ /**
+ * #6317 (B1): resident processes (`sync`, `jobs`, `autopilot`, `mcp`) defer to the first live full consumer of their host
+ * (consumer-election.ts) instead of starting their own. Off by default until Phase 0's preregistered reading sets it.
+ */
+ single_consumer: { key: 'persistence.single_consumer', env: 'GBRAIN_SINGLE_CONSUMER', defaultOn: false },
} as const;
export type WriteSwitch = keyof typeof WRITE_SWITCHES;
export type WriteSwitches = Record<WriteSwitch, boolean>;
@@ -38,9 +44,10 @@ const SNAPSHOT_KEYS: readonly string[] = [...WRITE_SWITCH_KEYS, ...PREPARATION_B
function resolve(configured: Map<string, string>): WriteSwitchSnapshot {
const out = {} as WriteSwitches;
- for (const [name, { key, env }] of Object.entries(WRITE_SWITCHES) as Array<[WriteSwitch, { key: string; env: string }]>) {
+ for (const [name, { key, env, defaultOn }] of Object.entries(WRITE_SWITCHES) as Array<[WriteSwitch, { key: string; env: string; defaultOn?: boolean }]>) {
const fromEnv = process.env[env];
- out[name] = off(fromEnv) ? false : on(fromEnv) ? true : !off(configured.get(key));
+ const fromConfig = configured.get(key);
+ out[name] = off(fromEnv) ? false : on(fromEnv) ? true : fromConfig === undefined ? defaultOn ?? true : !off(fromConfig);
}
return { switches: out, preparation: resolvePreparationPolicy(configured) };
}
diff --git a/test/persistence-claim-step.test.ts b/test/persistence-claim-step.test.ts
index a6e3ec2263..4a5ddf5a9b 100644
--- a/test/persistence-claim-step.test.ts
+++ b/test/persistence-claim-step.test.ts
@@ -11,7 +11,7 @@
* when a publishing or lapsed claim is reported as overdue preparation.
*/
import { afterEach, describe, expect, test } from 'bun:test';
-import { claimOwner, claimPhaseStamp, claimStall, claimStateOf, enterClaimPhase, enterClaimStep, setClaimOwnerForTest, startClaimPhase } from '../src/core/persistence/claim-phase.ts';
+import { claimOwner, claimOwnerIsThisProcess, claimPhaseStamp, claimStall, claimStateOf, enterClaimPhase, enterClaimStep, setClaimOwnerForTest, startClaimPhase } from '../src/core/persistence/claim-phase.ts';
import { VERSION } from '../src/version.ts';
afterEach(() => setClaimOwnerForTest(undefined));
@@ -50,9 +50,14 @@ describe('claimPhaseStamp and claimStateOf', () => {
expect(JSON.parse(claimPhaseStamp(clock, 'tok-1'))).toEqual({ phase: 'preparing', claimed_at: '2026-10-08T03:00:00.000Z', since: '2026-10-08T03:00:00.000Z', token: 'tok-1',
step: 'origin_check', step_since: '2026-10-08T03:01:00.000Z', waiting_on: 'db', owner: { kind: 'sync', pid: 4242, version: '0.60.200.0' } });
});
- test('the default owner is this process: the gbrain command (cli when none), pid and build', () => {
+ test('the default owner is this process: the gbrain command (cli when none), pid, build and (#6317) its nonce and pid namespace', () => {
const owner = claimOwner();
- expect(owner).toEqual({ kind: expect.any(String), pid: process.pid, version: VERSION });
+ expect(owner).toEqual({ kind: expect.any(String), pid: process.pid, version: VERSION, nonce: expect.stringMatching(/^[0-9a-f]{16}$/), pid_ns: process.platform === 'linux' ? expect.stringMatching(/^pid:\[\d+\]$/) : null });
+ expect(claimOwner().nonce).toBe(owner.nonce);
+ expect(claimOwnerIsThisProcess(owner)).toBe(true);
+ expect(claimOwnerIsThisProcess({ pid: process.pid, nonce: 'another-process-reusing-the-pid' })).toBe(false);
+ expect(claimOwnerIsThisProcess({ pid: process.pid })).toBe(true);
+ expect(claimOwnerIsThisProcess({ pid: process.pid + 1, nonce: owner.nonce })).toBe(false);
});
test('claimStateOf reads step, step age, waiting_on and owner from the current claim\'s stamp', () => {
const now = Date.parse('2026-10-08T03:12:00Z');