Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): a restarted PGLite owner resumes claims its dead predecessor held
garrytan85bb1906b5f3
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 6f31975cb6..1925876df3 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -16,9 +16,12 @@ import { AsyncLocalStorage } from 'node:async_hooks';import { monitorEventLoopDelay, type IntervalHistogram } from 'node:perf_hooks';import { maybeRefreshPlannerStats } from '../planner-stats.ts';import { faultPoint } from './fault-points.ts';+import { releaseAbandonedClaims } from './effect-journal.ts';type PhaseObservation = { name: string; started_at: string; deadline_exceeded: boolean; attempt: number; first_conn_ms?: number };/** #5801: the phase a connection checkout belongs to, carried through its async chain. */+/** When this process started; on PGLite no claim written earlier can belong to a live owner. */+const PROCESS_STARTED_AT = new Date(performance.timeOrigin);const phaseScope = new AsyncLocalStorage<{ observation: PhaseObservation; startedAt: number }>();/** #5233: one-line, redacted, length-capped error text for the consumer's stderr line. */@@ -86,6 +89,7 @@ export class PersistenceConsumer {private preparationAttempts = 0;private preparing = new Map<string, { request_id: string; started_at: string; deadline_exceeded: boolean; attempt: number }>();private executing = new Set<string>();+ private abandonedReleased = false;readonly hostId: string;constructor(readonly engine: BrainEngine, readonly config: GBrainConfig, readonly prepare: PrepareMutation,private opts: { hostId?: string; concurrency?: number; pollMs?: number; idleMaxMs?: number; phaseMs?: number; preparationMs?: number; onError?: (error: unknown) => void;@@ -294,6 +298,10 @@ export class PersistenceConsumer {.catch(error => this.report(error)).finally(() => { this.projectionWorker = undefined; });// Recover only our owner roots. Kernel exclusion, not elapsed heartbeat,// proves that a previous process can no longer be publishing this root.+ if (scan && this.engine.kind === 'pglite' && !this.abandonedReleased) {+ await this.phase('abandoned_claims', () => releaseAbandonedClaims(this.engine, PROCESS_STARTED_AT));+ this.abandonedReleased = true;+ }const now = Date.now();for (const [root, retryAt] of this.rootRetryAfter) if (retryAt <= now) this.rootRetryAfter.delete(root);if (scan) {diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.tsindex d54af074ec..c932f45668 100644--- a/src/core/persistence/effect-journal.ts+++ b/src/core/persistence/effect-journal.ts@@ -115,6 +115,25 @@ export async function claimCoalescedGitEffects(engine: BrainEngine, hostId: strireturn rows.sort((a, b) => Number(a.id) - Number(b.id));}+/**+ * PGLite only: the datastore admits one process, and this one opened it at+ * `processStartedAt`, so a claim last written before then was held by an owner+ * that has exited (a crash or SIGKILL). Release those claims now instead of+ * waiting out their leases (effects 2 minutes, requests 30 s); a withdrawal+ * mirror left running would otherwise also hold back writes to its pages.+ * Claims with a recovery record stay with the recovery path.+ */+export async function releaseAbandonedClaims(engine: BrainEngine, processStartedAt: Date): Promise<number> {+ if (engine.kind !== 'pglite') return 0;+ const effects = await engine.executeRaw(`UPDATE persistence_effects SET state='queued',execution_token=NULL,claim_expires_at=NULL,+ next_attempt_at=LEAST(next_attempt_at,now()) WHERE state='running' AND recovery IS NULL AND updated_at<$1::timestamptz+ AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING id`, [processStartedAt.toISOString()]);+ const requests = await engine.executeRaw(`UPDATE persistence_requests SET state='queued',execution_token=NULL,claim_expires_at=NULL+ WHERE state='running' AND recovery IS NULL AND publication_started=false AND updated_at<$1::timestamptz+ AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING id`, [processStartedAt.toISOString()]);+ return effects.length + requests.length;+}+export async function renewPersistenceEffectClaim(engine: SqlEngine, effect: PersistenceEffect): Promise<boolean> {const rows = await engine.executeRaw(`UPDATE persistence_effects SET claim_expires_at=now()+interval '2 minutes',updated_at=now()WHERE id=$1 AND execution_token=$2::uuid AND state='running' AND recovery IS NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING id`, [effect.id, effect.execution_token]);diff --git a/test/fixtures/crash-robot/abandoned-withdrawal-mirror-claim.json b/test/fixtures/crash-robot/abandoned-withdrawal-mirror-claim.jsonnew file mode 100644index 0000000000..58ead89608--- /dev/null+++ b/test/fixtures/crash-robot/abandoned-withdrawal-mirror-claim.json@@ -0,0 +1,24 @@+{+ "description": "A PGLite owner SIGKILLed inside a withdrawal-mirror effect (after its side effect, before completion) left the effect claimed for its 2-minute lease; the restarted owner neither ran the effect nor published writes to the withdrawn page until the lease expired. Fixed by releaseAbandonedClaims (src/core/persistence/effect-journal.ts).",+ "engine": "pglite",+ "shrunk_from": 8,+ "reproduced_before_fix": "3/3",+ "failing_runs": [+ {+ "schedule": "withdrawal_then_stale_publication",+ "seed": 5105,+ "length": 8,+ "fault": {+ "point": "effect:withdrawal-mirror:mid",+ "nth": 1+ },+ "crashed": true,+ "violations": [],+ "ops": [+ "wd0",+ "wd1",+ "wd2"+ ]+ }+ ]+}diff --git a/test/persistence-crash-robot.slow.test.ts b/test/persistence-crash-robot.slow.test.tsnew file mode 100644index 0000000000..5ccebc5b9e--- /dev/null+++ b/test/persistence-crash-robot.slow.test.ts@@ -0,0 +1,36 @@+/**+ * Shrunk crash-robot failures, replayed as regression tests. Each fixture in+ * test/fixtures/crash-robot/ is a minimal sequence plus the seam where the+ * worker is SIGKILLed; it reproduced 3/3 before its fix. The replay runs the+ * real process-separated crash and recovery (scripts/persistence/robot-driver.ts)+ * and requires zero reference-model violations.+ *+ * Protects: every safety-class bug the crash robot found stays fixed.+ * Fails when: the fix named in a fixture's description is reverted.+ * Seams: the gate's fault hook (src/core/persistence/fault-points.ts), installed only in the spawned workers.+ */+import { expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runRobotPhase, type RobotRun } from '../scripts/persistence/robot-driver.ts';+import { spawnWorker } from '../scripts/persistence/validate.ts';++const dir = join(import.meta.dir, 'fixtures', 'crash-robot');+for (const file of readdirSync(dir).filter(name => name.endsWith('.json')).sort()) {+ const fixture = JSON.parse(readFileSync(join(dir, file), 'utf8')) as { engine: 'pglite' | 'postgres'; failing_runs: RobotRun[] };+ test(`${fixture.engine}: ${file.replace(/\.json$/, '')} stays fixed`, async () => {+ const scratch = mkdtempSync(join(tmpdir(), 'gbrain-crash-robot-regression-'));+ const home = join(scratch, 'home'); mkdirSync(home);+ const children: ReturnType<typeof spawnWorker>[] = [];+ try {+ const result = await runRobotPhase({ engine: fixture.engine, seed: 0, seconds: 0, scratch, home, databases: [],+ spawn: spawnWorker, track: child => { children.push(child); }, replay: fixture.failing_runs, log: () => {} });+ expect(result.crashed_runs).toBe(fixture.failing_runs.filter(run => run.fault).length);+ expect(result.violations).toEqual([]);+ } finally {+ await Promise.allSettled(children.map(child => child.kill()));+ rmSync(scratch, { recursive: true, force: true });+ }+ }, 300_000);+}diff --git a/test/persistence-crash-robot.test.ts b/test/persistence-crash-robot.test.tsindex 593ef56e5a..97c56e890f 100644--- a/test/persistence-crash-robot.test.ts+++ b/test/persistence-crash-robot.test.ts@@ -1,7 +1,7 @@/*** The crash robot's in-process contracts (scripts/persistence/ops.ts,* generator.ts, model.ts, robot-driver.ts, shrink.ts) and the PGLite release- *+ * of claims a dead owner left behind (effect-journal.ts releaseAbandonedClaims).** Protects: the op-descriptor protocol refuses malformed descriptors; the five* cross-boundary sequences exist and pass the reference model through the real@@ -14,15 +14,16 @@* Seams: none (the fault hook stays uninstalled); PGLite.*/import { describe, expect, test } from 'bun:test';-import { mkdtempSync, rmSync } from 'node:fs';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { descriptor, parseDescriptor } from '../scripts/persistence/ops.ts';+import { descriptor, executeOp, parseDescriptor } from '../scripts/persistence/ops.ts';import { crossBoundarySequences, randomSchedule } from '../scripts/persistence/generator.ts';import { ROBOT_TOPOLOGY, restrict } from '../scripts/persistence/robot-driver.ts';import { shrinkRun } from '../scripts/persistence/shrink.ts';import { runSchedule } from '../scripts/persistence/crash-robot.ts';import { prepareTopology } from '../scripts/persistence/history-fixture.ts';+import { claimPersistenceEffect, releaseAbandonedClaims } from '../src/core/persistence/effect-journal.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';import { withEnv } from './helpers/with-env.ts';@@ -92,3 +93,29 @@ describe('reference model on master behavior', () => {}}, 180_000);});++describe('PGLite releases claims a dead owner left behind', () => {+ test('a claim written before this owner started is released; a newer one is kept', async () => {+ await robotBrain(async ({ world, checkouts }) => {+ const engine = world.engine;+ // A Git effect that failed on a stale index.lock is queued for a later attempt.+ const lock = join(checkouts[0], '.git', 'index.lock'); writeFileSync(lock, '');+ const seen = await executeOp(world, descriptor('p', 'put_page', 'local', 'robot-0', { slug: 'notes/claim', content: '---\ntype: note\ntitle: c\n---\n\nBody.\n' }));+ expect(seen.status).toBe('committed');+ let effect: { id: string } | undefined;+ for (let i = 0; i < 200 && !effect; i++) {+ [effect] = await engine.executeRaw<{ id: string }>("SELECT id::text FROM persistence_effects WHERE kind='git' AND state='queued' AND attempts>0");+ if (!effect) await Bun.sleep(50);+ }+ await disposePersistenceConsumer(engine); rmSync(lock);+ await engine.executeRaw('UPDATE persistence_effects SET next_attempt_at=now() WHERE id=$1', [effect!.id]); // what retry-effects does+ const [owner] = await engine.executeRaw<{ host: string }>('SELECT owner_host_id::text AS host FROM persistence_worktrees LIMIT 1');+ const claimed = await claimPersistenceEffect(engine, owner.host);+ expect({ id: String(claimed?.id), state: claimed?.state }).toEqual({ id: effect!.id, state: 'running' });+ expect(await releaseAbandonedClaims(engine, new Date(Date.now() - 60_000))).toBe(0);+ expect(await releaseAbandonedClaims(engine, new Date(Date.now() + 1_000))).toBe(1);+ const [row] = await engine.executeRaw<{ state: string; token: string | null }>('SELECT state,execution_token AS token FROM persistence_effects WHERE id=$1', [effect!.id]);+ expect(row).toEqual({ state: 'queued', token: null });+ });+ }, 60_000);+});