Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(persistence): create and lock persistence counters in two statements for any key count (#5984)
garrytand1f4a2c0f580
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex 5952f4b0c0..675acdadf1 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -73,15 +73,11 @@ export async function assertLifetimeIdHeadroom(engine: SqlEngine, principal: Priif (used + needed > limit) throw await cumulativeCapacityError(engine, `${scope} permanent request IDs`, key, `${scope}LifetimeIds`, used, limit);}}+/** Creates and locks the counter rows in key order: two statements for any number of keys (#5984 round-trip diet). */export async function lockCounters(tx: SqlEngine, keys: string[]): Promise<Counter[]> {const sorted = [...new Set(keys)].sort();- for (const key of sorted) await tx.executeRaw('INSERT INTO persistence_counters(key) VALUES ($1) ON CONFLICT DO NOTHING', [key]);- const result: Counter[] = [];- for (const key of sorted) {- const [row] = await tx.executeRaw<Counter>('SELECT * FROM persistence_counters WHERE key=$1 FOR UPDATE', [key]);- result.push(row);- }- return result;+ await tx.executeRaw('INSERT INTO persistence_counters(key) SELECT k FROM unnest($1::text[]) WITH ORDINALITY AS u(k,n) ORDER BY n ON CONFLICT DO NOTHING', [sorted]);+ return tx.executeRaw<Counter>('SELECT * FROM persistence_counters WHERE key=ANY($1::text[]) ORDER BY key COLLATE "C" FOR UPDATE', [sorted]);}export async function getWriteRequest(engine: SqlEngine, principal: Principal, requestId: string): Promise<WriteRequest | null> {const [row] = await engine.executeRaw<WriteRequest>(diff --git a/test/persistence-journal.test.ts b/test/persistence-journal.test.tsindex b9b9e0e25f..ad64d698d8 100644--- a/test/persistence-journal.test.ts+++ b/test/persistence-journal.test.ts@@ -196,7 +196,7 @@ describe('durable mutation journal', () => {const observed = new Proxy(engine, { get(target, property) {if (property === 'transaction') return (run: (tx: BrainEngine) => Promise<unknown>) => target.transaction(tx => run(new Proxy(tx, { get(t, p) {if (p === 'executeRaw') return (sql: string, params?: unknown[], opts?: { signal?: AbortSignal }) => {- if (sql.startsWith('INSERT INTO persistence_counters') && params?.[0] === 'brain') {+ if (sql.startsWith('INSERT INTO persistence_counters') && (params?.[0] === 'brain' || (Array.isArray(params?.[0]) && params[0].includes('brain')))) {attempts.add(input.requestId!);if (attempts.size === inputs.length) attempted();}