Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): validation producer retries contention-blocked admission with the same request ID (#5485)
time-attack5f4cc50d031a
diff --git a/scripts/persistence/producer-admission.ts b/scripts/persistence/producer-admission.tsnew file mode 100644index 0000000000..a6e9059f48--- /dev/null+++ b/scripts/persistence/producer-admission.ts@@ -0,0 +1,20 @@+import { OperationError } from '../../src/core/ops/contract.ts';++const MAX_ADMISSION_ATTEMPTS = 3;+const ADMISSION_RETRY_BACKOFF_MS = 25;++/**+ * Retry an admission whose contention outlasted the engine's retry window+ * (retryWriteAdmission's storage_error with detail database_contention),+ * reusing its request ID. Any other error, and the last attempt, rethrow.+ */+export async function submitWithAdmissionRetry<T>(submit: () => Promise<T>, onRetry: () => void = () => {}): Promise<T> {+ for (let attempt = 1; ; attempt++) {+ try { return await submit(); }+ catch (error) {+ if (!(error instanceof OperationError && error.detail === 'database_contention') || attempt >= MAX_ADMISSION_ATTEMPTS) throw error;+ onRetry();+ await Bun.sleep(ADMISSION_RETRY_BACKOFF_MS);+ }+ }+}diff --git a/scripts/persistence/validate.ts b/scripts/persistence/validate.tsindex de376e06b2..e4964ad148 100644--- a/scripts/persistence/validate.ts+++ b/scripts/persistence/validate.ts@@ -186,6 +186,7 @@ export async function runValidation(options: ValidationOptions) {producer_admission: options.engine === 'postgres' ? 'independent database clients' : 'resident fixture loopback endpoint',duration_ms: duration, operations_per_second: counts.operations / (duration / 1000),duplicate_replays: results.reduce((sum, row) => sum + row.result.replays, 0),+ admission_contention_retries: results.reduce((sum, row) => sum + (row.result.admission_contention_retries ?? 0), 0),admission: distribution(results.flatMap(row => row.result.admission_ms)),caller_completion: distribution(results.flatMap(row => row.result.completion_ms)),concurrent_canonical_read: distribution(ownerResults.flatMap(owner => owner.concurrent_read_ms)),diff --git a/scripts/persistence/worker.ts b/scripts/persistence/worker.tsindex 59b2907f0f..aebb47f721 100644--- a/scripts/persistence/worker.ts+++ b/scripts/persistence/worker.ts@@ -10,6 +10,7 @@ import { admission, assertCommittedSnapshot, assertConservation, distribution, fimport { runSchedules } from './schedules.ts';import type { WriteRequest } from '../../src/core/persistence/model.ts';import { boundedDiagnostic, diagnosticError, ownerDatabaseDiagnostic, soakFailureDiagnostic, type ActiveSoakRequest } from './failure-diagnostics.ts';+import { submitWithAdmissionRetry } from './producer-admission.ts';const [mode, configPath, argument, extra] = process.argv.slice(2);const config: HarnessConfig = JSON.parse(readFileSync(configPath, 'utf8'));@@ -151,9 +152,9 @@ if (mode === 'initialize') {const principal = Number(argument); const ownerUrl = extra;const engine = config.kind === 'postgres' ? await openEngine(config) : undefined;const sources = engine ? await fixtures(engine, config) : undefined;- const admissionMs: number[] = []; const completionMs: number[] = []; let replays = 0;+ const admissionMs: number[] = []; const completionMs: number[] = []; let replays = 0; let contentionRetries = 0;async function submit(index: number, requestId: string): Promise<WriteRequest> {- if (engine) return admitWrite(engine, admission(config, sources![principal % sources!.length], `soak-${index}`, `body-${index}`, principal, { requestId }));+ if (engine) return submitWithAdmissionRetry(() => admitWrite(engine, admission(config, sources![principal % sources!.length], `soak-${index}`, `body-${index}`, principal, { requestId })), () => { contentionRetries++; });const response = await fetch(new URL('submit', ownerUrl), { method: 'POST', body: JSON.stringify({ index, principal, requestId }) });assert(response.ok, `resident fixture admission failed: ${response.status}`); return response.json() as Promise<WriteRequest>;}@@ -188,7 +189,7 @@ if (mode === 'initialize') {if (completed % 250 === 0) process.stderr.write(`[persistence] ${config.kind}: producer ${principal} verified ${completed} committed writes\n`);}}));- emit({ event: 'done', result: { principal, completed, replays, admission_ms: admissionMs, completion_ms: completionMs } });+ emit({ event: 'done', result: { principal, completed, replays, admission_contention_retries: contentionRetries, admission_ms: admissionMs, completion_ms: completionMs } });} catch (error) {// Publish cached state before disconnect: a stuck connection must not hide// the original failure while the driver collects bounded owner diagnostics.diff --git a/test/persistence-validation-worker.test.ts b/test/persistence-validation-worker.test.tsnew file mode 100644index 0000000000..5d3743cf6a--- /dev/null+++ b/test/persistence-validation-worker.test.ts@@ -0,0 +1,58 @@+/**+ * Persistence validation producer admission (#5485). Protects: the soak+ * producer retries an admission whose contention outlasted the engine's+ * retry window, with the same request ID, a bounded number of times, and+ * counts each retry so the contention stays visible in the report. Fails+ * when: the producer gives up on the first exhausted-contention refusal, or+ * retries anything else (a terminal refusal, an unrelated storage error).+ */+import { beforeAll, describe, expect, test } from 'bun:test';+import { submitWithAdmissionRetry } from '../scripts/persistence/producer-admission.ts';+import { retryWriteAdmission } from '../src/core/persistence/admission-retry.ts';+import { OperationError } from '../src/core/ops/contract.ts';++let exhausted: unknown;+beforeAll(async () => {+ exhausted = await retryWriteAdmission('11111111-1111-4111-8111-111111111111',+ async () => { throw Object.assign(new Error('serialization failure'), { code: '40001' }); }, 30).then(() => null, error => error);+});++describe('persistence validation producer admission', () => {+ test('the engine helper\'s exhausted-contention refusal is what the producer retries', () => {+ expect(exhausted).toBeInstanceOf(OperationError);+ expect(exhausted).toMatchObject({ code: 'storage_error', writeError: 'storage_error', detail: 'database_contention' });+ });++ test('retries a contention-blocked admission with the same request ID and counts the retry', async () => {+ const requestIds: string[] = []; let retries = 0;+ const accepted = { request_id: '11111111-1111-4111-8111-111111111111', state: 'queued' };+ const row = await submitWithAdmissionRetry(async () => {+ requestIds.push(accepted.request_id);+ if (requestIds.length === 1) throw exhausted;+ return accepted;+ }, () => { retries++; });+ expect(row).toBe(accepted);+ expect(requestIds).toEqual([accepted.request_id, accepted.request_id]);+ expect(retries).toBe(1);+ });++ test('stops after three attempts and rethrows when contention persists', async () => {+ let attempts = 0; let retries = 0;+ await expect(submitWithAdmissionRetry(async () => { attempts++; throw exhausted; }, () => { retries++; })).rejects.toBe(exhausted);+ expect([attempts, retries]).toEqual([3, 2]);+ });++ test('never retries a terminal refusal, another storage error or a non-contention detail', async () => {+ const others = [+ new OperationError('storage_error', 'The write did not commit.'),+ Object.assign(new OperationError('storage_error', 'Admission failed.'), { detail: 'unbound_source' }),+ new OperationError('conflict', 'The page changed since the expected revision.'),+ Object.assign(new Error('look-alike'), { code: 'storage_error', detail: 'database_contention' }),+ ];+ for (const other of others) {+ let attempts = 0; let retries = 0;+ await expect(submitWithAdmissionRetry(async () => { attempts++; throw other; }, () => { retries++; })).rejects.toBe(other);+ expect([attempts, retries]).toEqual([1, 0]);+ }+ });+});