Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(agent-contract): a rolled-back write admission reads retryable on a mutating op

garrytana475710f99e3
diff --git a/src/core/agent-output.ts b/src/core/agent-output.ts
index c141f8ea18..8602b82a5e 100644
--- a/src/core/agent-output.ts
+++ b/src/core/agent-output.ts
@@ -13,7 +13,7 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { VERSION } from '../version.ts';
-import { OperationError, __registerOperationErrorRenderer, type WithdrawnDetail } from './ops/contract.ts';
+import { OperationError, __registerOperationErrorRenderer, provesNotAdmitted, type WithdrawnDetail } from './ops/contract.ts';
import { StructuredAgentError } from './errors.ts';
import { canonicalCodeFor, codeEntry, codeClass, codeRetryable, exitCodeForCode } from './error-catalogue.ts';
import { VERB_NAMES } from './verbs.ts';
@@ -831,7 +831,7 @@ export function toAgentError(e: unknown, ctx: AgentErrorContext): AgentEnvelope
if (!parts.fix && (codeClass(parts.code) === 'server' || codeClass(parts.code) === 'unavailable')) {
parts = { ...parts, fix: diagnosticFix(ctx, 'Doctor reports what is missing or failing on the brain host.') };
}
- if (ctx.mutating === true && ctx.idempotent !== true) parts = { ...parts, retryable: false };
+ if (ctx.mutating === true && ctx.idempotent !== true && !provesNotAdmitted(e)) parts = { ...parts, retryable: false };
const env = buildEnvelope(parts, ctx.render);
if (env.code === 'internal_error' || env.code === 'internal' || !env.suggestion) {
recordAgentContractEvent({ transport: ctx.transport, op: ctx.op, command: ctx.command, code: env.code, has_suggestion: !!env.suggestion, outcome: ctx.outcome });
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index ad86004427..124bec4f4a 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -188,6 +188,14 @@ export interface OpErrorOpts {
* positional and required. Use `OperationError.bare()` only when no next step
* can be named at the throw site.
*/
+const notAdmittedWrites = new WeakSet<OperationError>();
+/**
+ * A write refusal raised after its admission transaction rolled back, so nothing was admitted: the agent contract's
+ * safe-recovery rule (only idempotent mutations read retryable) gives way for it. Only write admission marks errors.
+ */
+export function markNotAdmitted(error: OperationError): OperationError { notAdmittedWrites.add(error); return error; }
+export function provesNotAdmitted(error: unknown): boolean { return error instanceof OperationError && notAdmittedWrites.has(error); }
+
export function opError(code: RegistryCode, message: string, suggestion: string, opts: OpErrorOpts = {}): OperationError {
const e = new OperationError(opts.legacy_error ?? code, message, suggestion, opts.docs);
if (opts.legacy_error !== undefined) e.canonical = code;
diff --git a/src/core/persistence/admission-retry.ts b/src/core/persistence/admission-retry.ts
index 5f8f2c1fe9..e4e103d3b8 100644
--- a/src/core/persistence/admission-retry.ts
+++ b/src/core/persistence/admission-retry.ts
@@ -1,5 +1,5 @@
import { setTimeout as delay } from 'node:timers/promises';
-import { OperationError, opError } from '../ops/contract.ts';
+import { markNotAdmitted, OperationError, opError } from '../ops/contract.ts';
import { getCode, isConnectionLoss } from '../retry-matcher.ts';
/** #6355: how many times an admission attempt is re-run after the session dropped under it, and the pauses before each re-run. */
@@ -57,7 +57,7 @@ export async function retryWriteAdmission<T>(requestId: string, attempt: (remain
unavailable.writeError = 'storage_error';
unavailable.detail = 'database_contention';
unavailable.reason = 'database_contention';
- throw unavailable;
+ throw markNotAdmitted(unavailable);
}
// The transaction has rolled back and released its connection before any
// backoff. Jitter keeps independent ingress processes from retrying in step.
diff --git a/test/admission-contention-retryable.test.ts b/test/admission-contention-retryable.test.ts
new file mode 100644
index 0000000000..f1fc323afb
--- /dev/null
+++ b/test/admission-contention-retryable.test.ts
@@ -0,0 +1,42 @@
+/**
+ * The agent contract's safe-recovery rule reads a failed non-idempotent mutation as not retryable, because its outcome
+ * may be unknown. A write admission that database contention kept refusing rolled its transaction back, so nothing was
+ * admitted: that error proves it (`provesNotAdmitted`), and only it lifts the rule. Any other mutating error, including
+ * one with the same code, detail and reason but no proof, still reads not retryable.
+ */
+import { describe, expect, test } from 'bun:test';
+import { toAgentError, type RenderContext } from '../src/core/agent-output.ts';
+import { OperationError, provesNotAdmitted } from '../src/core/ops/contract.ts';
+import { retryWriteAdmission } from '../src/core/persistence/admission-retry.ts';
+
+const render = (over: Partial<RenderContext> = {}): RenderContext => ({
+ transport: 'stdio', isCallable: () => true, preapproved: () => false, ...over,
+});
+
+describe('a rolled-back write admission on a mutating op', () => {
+ async function admissionContention(): Promise<OperationError> {
+ const error = await retryWriteAdmission('req-example', async () => { throw Object.assign(new Error('deadlock detected'), { code: '40P01' }); }, 30)
+ .then(() => null, (e: unknown) => e);
+ expect(error).toBeInstanceOf(OperationError);
+ return error as OperationError;
+ }
+
+ test('reads retryable on a non-idempotent mutation, because nothing was admitted', async () => {
+ const error = await admissionContention();
+ expect(provesNotAdmitted(error)).toBe(true);
+ for (const transport of ['stdio', 'cli'] as const) {
+ const env = toAgentError(error, { transport, op: 'restore_page', mutating: true, idempotent: false, render: render({ transport }) });
+ expect(env).toMatchObject({ code: 'storage_error', retryable: true });
+ }
+ });
+
+ test('an unknown-outcome mutating error with the same code and detail still reads not retryable', () => {
+ const unknown = new OperationError('storage_error', 'write failed mid-flight', 'Read the receipt before resubmitting.');
+ unknown.writeError = 'storage_error'; unknown.detail = 'database_contention'; unknown.reason = 'database_contention';
+ expect(provesNotAdmitted(unknown)).toBe(false);
+ for (const outcome of ['unknown', undefined] as const) {
+ const env = toAgentError(unknown, { transport: 'stdio', op: 'restore_page', mutating: true, idempotent: false, ...(outcome ? { outcome } : {}), render: render() });
+ expect(env.retryable).toBe(false);
+ }
+ });
+});