Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(persistence-gate): lock-order trace for every robot transaction

garrytan3d2db395e0d6
diff --git a/scripts/persistence/crash-robot.ts b/scripts/persistence/crash-robot.ts
index c5638737a7..5a23349706 100644
--- a/scripts/persistence/crash-robot.ts
+++ b/scripts/persistence/crash-robot.ts
@@ -19,6 +19,7 @@ import { installFaultHook, type FaultPoint } from '../../src/core/persistence/fa
import { assertSafeE2eDatabaseUrl } from '../../test/helpers/db-guard.ts';
import postgres from '#postgres';
import { prepareTopology } from './history-fixture.ts';
+import { installLockOrderTrace, lockOrderReport } from './lock-order.ts';
import { executeOp, type OpDescriptor, type OpObservation, type World } from './ops.ts';
import { ReferenceModel, SAFETY_CLASSES, type Violation } from './model.ts';
import type { Schedule } from './generator.ts';
@@ -162,6 +163,8 @@ function freeze(event: Record<string, unknown>): never {
}
function finalize(config: RobotConfig, model: ReferenceModel, extra: Partial<RobotOutcome>): RobotOutcome {
+ const locks = lockOrderReport();
+ for (const v of locks.violations) model.violate({ class: 'lock_order', detail: `${v.rule}: ${v.detail}` });
const trace = model.violations.length ? [...model.world.observations.values()].map(o =>
`${o.id} ${o.kind} ${o.actor}@${o.source} ${o.status}${o.code ? `/${o.code}` : ''}${o.values.revision ? ` rev=${o.values.revision}` : ''}`
+ `${o.receipt ? ` receipt=${o.receipt.state}` : ''}${o.status === 'refused' ? ` ${JSON.stringify(o.raw).slice(0, 300)}` : ''}`) : undefined;
@@ -267,6 +270,7 @@ export async function robotWorker(role: 'count' | 'run' | 'recover', config: Rob
checkouts = state.checkouts; model = ReferenceModel.fromJSON(world, state.model);
}
world.descriptors = new Map(config.schedule.ops.map(d => [d.id, d]));
+ installLockOrderTrace();
const counts: Record<string, number> = {};
if (role === 'count') installFaultHook(point => { counts[point] = (counts[point] ?? 0) + 1; });
if (role === 'run' && config.fault) {
diff --git a/scripts/persistence/lock-order.ts b/scripts/persistence/lock-order.ts
new file mode 100644
index 0000000000..6a0f19e5df
--- /dev/null
+++ b/scripts/persistence/lock-order.ts
@@ -0,0 +1,103 @@
+/**
+ * Lock-order tracing for the crash robot. A worker patches both engines'
+ * transaction entry points so every row lock taken inside one transaction
+ * (`SELECT ... FROM <table> ... FOR UPDATE|SHARE`) is recorded in order, then
+ * checks the cross-path lock order the write path relies on to stay
+ * deadlock-free:
+ * - worktree rows are locked before source rows;
+ * - source rows are locked in id order (a multi-source lock such as
+ * `id = ANY($1) ORDER BY id`, or several single-source locks);
+ * - a publication (a transaction that locks its request row) never takes
+ * an exclusive lock on the brain row (shared reads by the writer guard
+ * and company receipts are counted, not refused).
+ * The core-memory source lock (`lockCoreSources`, when present) is a
+ * multi-source `sources` lock and is checked by the same rules.
+ */
+import { AsyncLocalStorage } from 'node:async_hooks';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+
+interface Lock { table: string; ids: string[]; sql: string; exclusive: boolean }
+interface Trace { locks: Lock[]; publication: boolean }
+export interface LockOrderViolation { rule: 'worktrees_before_sources' | 'sources_in_id_order' | 'publication_locks_brain'; detail: string }
+
+const LOCK = /^\s*SELECT\b[\s\S]*?\bFROM\s+([a-z_]+)\b(?:\s+[a-z]\b)?[\s\S]*\bFOR\s+(UPDATE|SHARE|NO KEY UPDATE|KEY SHARE)\b(?!\s+OF\b)/i;
+const store = new AsyncLocalStorage<Trace>();
+const violations: LockOrderViolation[] = [];
+let installed = false;
+let enabled = false;
+let traced = 0;
+let sharedBrainPublications = 0;
+
+function record(sql: string, params: unknown[] | undefined): void {
+ const trace = store.getStore();
+ if (!trace) return;
+ const match = LOCK.exec(sql);
+ if (!match) return;
+ const table = match[1].toLowerCase();
+ // The locked ids: the parameter bound to `id = $n` or `id = ANY($n)`.
+ const position = /\bid\s*=\s*(?:ANY\s*\(\s*)?\$(\d+)/i.exec(sql)?.[1];
+ const bound = position ? params?.[Number(position) - 1] : undefined;
+ const ids = Array.isArray(bound) ? bound.map(String) : bound === undefined ? [] : [String(bound)];
+ trace.locks.push({ table, ids, sql: sql.replace(/\s+/g, ' ').slice(0, 140), exclusive: /UPDATE/i.test(match[2]) });
+ if (table === 'persistence_requests' && /\bWHERE\s+id\s*=\s*\$1/i.test(sql)) trace.publication = true;
+}
+
+function check(trace: Trace): void {
+ traced++;
+ const firstSource = trace.locks.findIndex(l => l.table === 'sources');
+ const worktrees = new Set<string>();
+ for (const [i, lock] of trace.locks.entries()) {
+ if (lock.table !== 'persistence_worktrees') continue;
+ const fresh = lock.ids.some(id => !worktrees.has(id)) || !lock.ids.length;
+ if (firstSource >= 0 && i > firstSource && fresh) violations.push({ rule: 'worktrees_before_sources',
+ detail: `${trace.locks[firstSource].sql} [${trace.locks[firstSource].ids}] before ${lock.sql} [${lock.ids}]` });
+ for (const id of lock.ids) worktrees.add(id);
+ }
+ // Re-locking a row this transaction already holds acquires nothing new, so only first locks count.
+ const held = new Set<string>(); let previous = '';
+ for (const lock of trace.locks.filter(l => l.table === 'sources')) {
+ const fresh = lock.ids.filter(id => !held.has(id)).sort();
+ if (fresh.length && previous && fresh[0] < previous) violations.push({ rule: 'sources_in_id_order', detail: `${previous} locked before ${fresh[0]}` });
+ for (const id of fresh) held.add(id);
+ previous = fresh.at(-1) ?? previous;
+ }
+ // The writer guard's trigger and company receipts read the brain row FOR SHARE inside publications;
+ // an exclusive brain lock there would serialize every write behind topology changes.
+ const brain = trace.locks.find(l => l.table === 'persistence_brain' && l.exclusive);
+ if (trace.publication && brain) violations.push({ rule: 'publication_locks_brain', detail: brain.sql });
+ if (trace.publication && trace.locks.some(l => l.table === 'persistence_brain')) sharedBrainPublications++;
+}
+
+/**
+ * Patch both engines once per worker process and start tracing. Nested
+ * transactions extend the outer trace. Call it after fixture setup: an
+ * unmanaged pre-activation claim runs no publication to order against.
+ */
+export function installLockOrderTrace(): void {
+ enabled = true;
+ if (installed) return;
+ installed = true;
+ for (const Engine of [PGLiteEngine, PostgresEngine] as const) {
+ const proto = Engine.prototype as unknown as Record<string, (...args: unknown[]) => Promise<unknown>>;
+ for (const method of ['transaction', 'transactionDirect']) {
+ const original = proto[method];
+ proto[method] = function (this: unknown, fn: unknown) {
+ if (!enabled || store.getStore()) return original.call(this, fn);
+ const trace: Trace = { locks: [], publication: false };
+ return store.run(trace, async () => {
+ try { return await original.call(this, fn); } finally { check(trace); }
+ });
+ };
+ }
+ const execute = proto.executeRaw;
+ proto.executeRaw = function (this: unknown, sql: unknown, params?: unknown) {
+ record(String(sql), params as unknown[] | undefined);
+ return execute.call(this, sql, params, ...[...arguments].slice(2));
+ };
+ }
+}
+
+export function lockOrderReport(): { transactions: number; publications_reading_brain_for_share: number; violations: LockOrderViolation[] } {
+ return { transactions: traced, publications_reading_brain_for_share: sharedBrainPublications, violations: [...violations] };
+}
diff --git a/scripts/persistence/model.ts b/scripts/persistence/model.ts
index 66caf05cb2..7271f6498c 100644
--- a/scripts/persistence/model.ts
+++ b/scripts/persistence/model.ts
@@ -33,7 +33,7 @@ export const EFFECT_SEAMS = {
export type ViolationClass = 'lost_write' | 'duplicate_apply' | 'untrue_receipt' | 'wedge' | 'withdrawal_permanence'
| 'source_isolation' | 'authorization' | 'caller_bound_replay' | 'projection_drift' | 'missing_attribution' | 'orphan_rows' | 'effects_not_terminal'
- | 'untyped_error';
+ | 'untyped_error' | 'lock_order';
/** Violations that always block a ship (see the plan's bug-fix bound). */
export const SAFETY_CLASSES: ReadonlySet<ViolationClass> = new Set(['lost_write', 'duplicate_apply', 'untrue_receipt', 'wedge',
'withdrawal_permanence', 'source_isolation', 'authorization', 'caller_bound_replay']);
diff --git a/test/persistence-crash-robot.test.ts b/test/persistence-crash-robot.test.ts
index 9c3db769c4..29e9de5cb3 100644
--- a/test/persistence-crash-robot.test.ts
+++ b/test/persistence-crash-robot.test.ts
@@ -22,6 +22,7 @@ import { crossBoundarySequences, randomSchedule } from '../scripts/persistence/g
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 { installLockOrderTrace, lockOrderReport } from '../scripts/persistence/lock-order.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';
@@ -95,6 +96,25 @@ describe('reference model on master behavior', () => {
}, 180_000);
});
+describe('lock order', () => {
+ test('real publications keep worktree > sources-by-id order; an inversion is reported', async () => {
+ await robotBrain(async ({ world }) => {
+ installLockOrderTrace();
+ const before = lockOrderReport().violations.length;
+ await runSchedule(world, crossBoundarySequences(ROBOT_TOPOLOGY)[1]);
+ const clean = lockOrderReport();
+ expect(clean.transactions).toBeGreaterThan(10);
+ expect(clean.violations.slice(before)).toEqual([]);
+ await world.engine.transaction(async tx => {
+ await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR UPDATE', ['robot-1']);
+ await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR UPDATE', ['robot-0']);
+ await tx.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', ['00000000-0000-4000-8000-000000000000']);
+ });
+ expect(lockOrderReport().violations.slice(before).map(v => v.rule)).toEqual(['worktrees_before_sources', 'sources_in_id_order']);
+ });
+ }, 120_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 }) => {