Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

persistence: take the publication_started stamp on the request-row lock, one statement instead of two

garrytan4e6ee49071c2
diff --git a/scripts/persistence/lock-order.ts b/scripts/persistence/lock-order.ts
index 7020c6ff2e..57705d7b5c 100644
--- a/scripts/persistence/lock-order.ts
+++ b/scripts/persistence/lock-order.ts
@@ -31,6 +31,8 @@ const LOCK = /^\s*SELECT\b[\s\S]*?\bFROM\s+([a-z_]+)\b(?:\s+[a-z]\b)?[\s\S]*\bFO
/** A statement writing a journal table fires its protocol trigger's brain-row FOR SHARE read; counters it updates are locked first. */
const TRIGGERED_BRAIN = /\b(?:INSERT\s+INTO|UPDATE|DELETE\s+FROM)\s+persistence_(?:requests|effects)\b/i;
const COUNTER_WRITE = /\b(?:INSERT\s+INTO|UPDATE)\s+persistence_counters\b/i;
+/** A file publication takes its request-row lock with the `publication_started` stamp (coordinator.ts) instead of a bare FOR UPDATE. */
+const PUBLICATION_STAMP = /^\s*UPDATE\s+persistence_requests\s+SET\s+publication_started\s*=\s*true\s+WHERE\s+id\s*=\s*\$1\b/i;
const ORDERED_ROWS = new Set(['persistence_worktrees', 'sources', 'persistence_counters']);
const store = new AsyncLocalStorage<Trace>();
const violations: LockOrderViolation[] = [];
@@ -38,6 +40,7 @@ let installed = false;
let enabled = false;
let traced = 0;
let sharedBrainPublications = 0;
+let publicationRowLockStatementsMax = 0;
function record(sql: string, params: unknown[] | undefined): void {
const trace = store.getStore();
@@ -46,6 +49,11 @@ function record(sql: string, params: unknown[] | undefined): void {
if (!/^\s*SELECT\b/i.test(sql)) {
if (COUNTER_WRITE.test(sql)) trace.locks.push({ table: 'persistence_counters', ids: [], sql: flat, exclusive: true });
if (TRIGGERED_BRAIN.test(sql)) trace.locks.push({ table: 'persistence_brain', ids: [], sql: `trigger: ${flat}`, exclusive: false });
+ if (PUBLICATION_STAMP.test(sql)) {
+ const bound = params?.[0];
+ trace.locks.push({ table: 'persistence_requests', ids: bound === undefined ? [] : [String(bound)], sql: flat, exclusive: true });
+ trace.publication = true;
+ }
}
const match = LOCK.exec(sql);
if (!match) return;
@@ -85,6 +93,8 @@ function check(trace: Trace): void {
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++;
+ // A publication locks its request row once: the `publication_started` stamp is that lock, not a second statement after it.
+ if (trace.publication) publicationRowLockStatementsMax = Math.max(publicationRowLockStatementsMax, trace.locks.filter(l => l.table === 'persistence_requests').length);
}
/**
@@ -116,6 +126,6 @@ export function installLockOrderTrace(): void {
}
}
-export function lockOrderReport(): { transactions: number; publications_reading_brain_for_share: number; violations: LockOrderViolation[] } {
- return { transactions: traced, publications_reading_brain_for_share: sharedBrainPublications, violations: [...violations] };
+export function lockOrderReport(): { transactions: number; publications_reading_brain_for_share: number; publication_row_lock_statements_max: number; violations: LockOrderViolation[] } {
+ return { transactions: traced, publications_reading_brain_for_share: sharedBrainPublications, publication_row_lock_statements_max: publicationRowLockStatementsMax, violations: [...violations] };
}
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index d9c1461cec..623fe8fee3 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -347,7 +347,11 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
// A page target's visibility is checked below, once its page is locked.
await authorizeStoredRequest(tx, row, true, { pageVisibility: skill });
await lockCounters(tx, ['brain', principalKey(requestPrincipal(row)), ...(row.worktree_id ? [`worktree:${row.worktree_id}`] : [])]);
- const [current] = await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid FOR UPDATE', [row.id]);
+ // A file publication stamps `publication_started` on the row lock it takes anyway; the stamp lives and dies
+ // with this transaction either way (control.ts reads a rolled-back stamp as "never started").
+ const [current] = await tx.executeRaw<WriteRequest>(recovery
+ ? 'UPDATE persistence_requests SET publication_started=true WHERE id=$1::uuid RETURNING *'
+ : 'SELECT * FROM persistence_requests WHERE id=$1::uuid FOR UPDATE', [row.id]);
if (!current || current.execution_token !== row.execution_token || current.state !== 'running') throw opError('write_claim_lost', 'Execution claim changed before publication.',
`Another worker took over request ${row.request_id} (its execution claim expired or was reassigned) before this attempt published, so this attempt wrote nothing and the current holder decides the outcome. Inspect the request rather than resubmitting it.`,
{ fix: requestFix(row) });
@@ -373,7 +377,6 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
for (const record of records) if ((skill ? bundleFileHash(record) : fileHash(record.path)) !== record.beforeHash) {
throw localEditRefusal('The canonical file changed during preparation.', row, skill, 'while the write was being prepared');
}
- await tx.executeRaw('UPDATE persistence_requests SET publication_started=true WHERE id=$1::uuid', [row.id]);
await hooks.boundary?.('before_publication', row);
// Mark before the call: a rename followed by an fsync error still needs recovery.
published = true;
diff --git a/test/persistence-crash-robot.test.ts b/test/persistence-crash-robot.test.ts
index af9d6c2b68..fdcbb5a363 100644
--- a/test/persistence-crash-robot.test.ts
+++ b/test/persistence-crash-robot.test.ts
@@ -237,6 +237,9 @@ describe('lock order', () => {
const clean = lockOrderReport();
expect(clean.violations.slice(before)).toEqual([]);
expect(clean.publications_reading_brain_for_share).toBeGreaterThan(0);
+ // The request row is locked by one statement per publication: the `publication_started` stamp takes the lock
+ // (two statements, a bare FOR UPDATE and then the stamp, is the shape before v0.60.141.0).
+ expect(clean.publication_row_lock_statements_max).toBe(1);
await world.engine.transaction(async tx => {
await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR SHARE', ['robot-0']);
await tx.executeRaw('SELECT singleton FROM persistence_brain WHERE singleton=1 FOR SHARE');