Retry and idempotency cache (#67)
Two opt-in runtime stages, both off when their runtime key is absent. Nothing is retried or cached unless the tool is listed in tools.
runtime.retry = { tools, maxAttempts = 3, baseDelayMs = 200, maxDelayMs = 5000, jitter = 0.5, allowSideEffects = false, sleep?, random? }
runtime.idempotency = { tools, ttlMs = 60000, allowSideEffects = false }
tools is a non-empty list of exact names, domain.* or *. Invalid values (maxAttempts outside 1..10, jitter outside 0..1, ttlMs <= 0, empty tools) make create() throw. sleep(ms) and random() are host-only hooks (never from JSON) so tests can run without waiting and with jitter: 0.
Pipeline order: resolve -> enabled -> approval -> cache.lookup -> budget.reserve -> retry(dispatch) -> budget.commit -> cache.store -> envelope.
Retry
- Only transient failures are retried:
RATE_LIMITED(HTTP 429),UPSTREAM_UNAVAILABLE(502/503/504),TIMEOUTandHTTP_REQUEST_FAILEDfromweb.*. Everything else (validation, sandbox,INVALID_JSON_RESPONSE, ...) fails on the first attempt. - Backoff after failed attempt
n:floor(min(maxDelayMs, baseDelayMs * 2^(n-1)) * (1 - jitter * random())). Withjitter: 0it is fully deterministic and identical in Node, Python and .NET. - Tools flagged
sideEffectsin the manifest (fs.write_file,kv.set,kv.delete,kv.incr,scratchpad.*writes,state.checkpoint,trace.log_event) are never retried unlessallowSideEffects: true. meta.attemptsis set for opted-in tools, on success and on failure.- The whole retry loop counts as one call for the budget guard.
Idempotency cache
- Key:
(sessionId, tool, argsHash), whereargsHashis the canonical hash of the args withoutsessionId/approvalId(see the approval gate). Key order does not matter. - Only successful results are cached, for
ttlMs. A hit skips dispatch and the budget (meta.cacheHit: true, nometa.attempts); a miss on an opted-in tool reportsmeta.cacheHit: false. - Hits return an independent copy of the data;
meta.truncatedis recomputed. sideEffectstools are never cached unlessallowSideEffects: true.- Values live only in the
PolicyStateStore(memory by default), never inKvStore, snapshots, checkpoints or traces. A custompolicyStorethat persists will persist cached results too. - Approval still runs first: a cached
fs.write_fileresult cannot bypass the gate.