Effects, operation identities and retries
An operation is one intended external change. An attempt is one authorized effort to perform it. Keeping those identities separate lets the application retry safely without pretending that a second attempt represents a different business action.
An interactive operation effect lifecycle diagram shows every effect state, UNKNOWN reconciliation and epoch fencing.
Adapter responsibilities
Section titled “Adapter responsibilities”Implement execute(operation, attempt) and reconcile(operation, attempt). Execution may change the external world; reconciliation must discover external truth without repeating that change. Both return an effect disposition and decimal-string actual cost. Exceptions during execution become UNKNOWN in the coordinator. They do not prove that nothing happened.
Use a stable operation ID as the basis for an external idempotency key where the target supports it. Include material/precondition checks so that changed requests cannot reuse a key silently. A target’s idempotency retention period is an integration contract; the SDK cannot discover it for you. If no safe target deduplication or reliable readback exists, do not retry an uncertain effect.
| Disposition | Meaning | Permitted next step |
|---|---|---|
| NOT_DISPATCHED | No dispatch has been committed for this operation | Current prepared owner may dispatch after checks |
| UNKNOWN | Dispatch occurred or its outcome cannot be established | Human-controlled reconciliation; retain reservation |
| CONFIRMED_NOT_APPLIED | The intended effect is known not to have occurred | Checked retry if authority and limits still permit |
| CONFIRMED_APPLIED | Intended effect is known to have occurred | Record dependent work; do not replay as a retry |
An adapter reports an effect, never an attempt status. FAILED and SUCCEEDED are what the reducer records when it settles the attempt: CONFIRMED_NOT_APPLIED produces FAILED and opens a checked retry, so an adapter reports it only with proof that nothing changed.
Write the adapter first
Section titled “Write the adapter first”Write the operation contract (STANDARD E-01) before the adapter code: the effect, its preconditions and postconditions, the target’s timeout, what each exit means, how to reconcile and when a retry is safe. Then derive the idempotency key from the operation, not the attempt, so a retry reuses it. Inject the transport so tests can replace the target. Keep reconcile read-only: it looks the key and the target revision up and never resubmits.
Write an effect adapter first: contract, idempotency key, injected transport, read-only reconcile · Executable local adapter demonstration; SDK 0.4.0 APIs; fixed demo identity and an in-memory target
import assert from 'node:assert/strict';import { mkdtempSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { canonical, parseCommand, parseContract } from '@aiws/sdk';import { SqliteStore } from '@aiws/sdk/sqlite';import { Coordinator, type EffectAdapter, type Outcome } from '@aiws/sdk/runtime';
/* * Operation contract (STANDARD E-01, E-04) for `write` on `doc`, the KeyedWriteAdapter below. * - Effect: sets the document to `action.payload`. Idempotent under the key: the target records * the key with the change in one transaction, applies a key at most once, and refuses a key * whose fingerprint differs. It keeps a key record for 24 hours. * - Precondition: the document is at `action.preconditions.revision`. Postcondition: the payload * is stored and the revision has advanced. Every change advances the revision. * - Timeout: 30 seconds. Exit 0 means applied, at a cost of 3. Exit 3 means the target refused the * request before changing anything, at no cost. Any other exit, a timeout or a transport error * proves nothing: the outcome is UNKNOWN. * - Reconciliation: read-only `lookup` of the key and the revision. A recorded key proves the * change; an absent key with the revision unchanged proves nothing changed. Anything else * stays UNKNOWN for a human. * - Retry: the key comes from the operation, not the attempt, so a retry reuses it and the target * absorbs a late original. Retry only after CONFIRMED_NOT_APPLIED, inside the retention window. */type Submission = { exitCode: number } | { timedOut: true };/** Own-property check on the transport's plain reply object, never `in`. */const timedOut = (reply: Submission): reply is { timedOut: true } => Object.hasOwn(reply, 'timedOut');interface Lookup { keyRecorded: boolean; revision: number }interface WriteRequest { key: string; fingerprint: string; resource: string; payload: unknown; expectedRevision: number; timeoutMs: number }/** Injected by the host: the real client in production, a fake target in tests. */interface Transport { submit(request: WriteRequest): Promise<Submission>; /** Read-only: never changes the target. */ lookup(key: string, resource: string): Promise<Lookup>;}/** Mission, operation and action fingerprint: stable across attempts, different for a changed action. */const idempotencyKey = (missionId: string, operation: Readonly<Record<string, any>>): string => `${missionId}/${operation.id}/${operation.fingerprint}`;const applied: Outcome = { effect: 'CONFIRMED_APPLIED', actualCost: '3' };const notApplied: Outcome = { effect: 'CONFIRMED_NOT_APPLIED', actualCost: '0' };const unknown: Outcome = { effect: 'UNKNOWN', actualCost: '0' };class KeyedWriteAdapter implements EffectAdapter { private missionId: string; private transport: Transport; constructor(missionId: string, transport: Transport) { this.missionId = missionId; this.transport = transport; } async execute(operation: Readonly<Record<string, any>>, _attempt: Readonly<Record<string, any>>): Promise<Outcome> { const { resource, payload, preconditions } = operation.action; let reply: Submission; try { reply = await this.transport.submit({ key: idempotencyKey(this.missionId, operation), fingerprint: operation.fingerprint, resource, payload, expectedRevision: preconditions.revision, timeoutMs: 30_000 }); } catch { return unknown; // A thrown transport error does not show whether the target applied the write. } if (timedOut(reply)) return unknown; // A timeout never proves the action did not happen. if (reply.exitCode === 0) return applied; if (reply.exitCode === 3) return notApplied; // The contract: exit 3 is a refusal before any change. return unknown; // Other nonzero exits carry no proof that nothing changed. } async reconcile(operation: Readonly<Record<string, any>>, _attempt: Readonly<Record<string, any>>): Promise<Outcome> { let found: Lookup; try { found = await this.transport.lookup(idempotencyKey(this.missionId, operation), operation.action.resource); } catch { return unknown; } if (found.keyRecorded) return applied; if (found.revision === operation.action.preconditions.revision) return notApplied; return unknown; // The target moved without our key: an expired key record or another writer. }}
// ---- A local target that applies a write and then loses the response. ----class LossyTarget implements Transport { revision = 1; document: unknown = null; keys = new Map<string, string>(); async submit(request: WriteRequest): Promise<Submission> { const recorded = this.keys.get(request.key); if (recorded !== undefined) return { exitCode: recorded === request.fingerprint ? 0 : 3 }; if (request.expectedRevision !== this.revision) return { exitCode: 3 }; this.document = request.payload; this.revision++; this.keys.set(request.key, request.fingerprint); return { timedOut: true }; // Applied, but the response never arrived. } async lookup(key: string): Promise<Lookup> { return { keyRecorded: this.keys.has(key), revision: this.revision }; }}
// Demo identity only: replace with authenticated, versioned policy and a human for settle.const contract = parseContract(canonical({ id: 'c', missionId: 'm', aiwsEdition: '0.4', profile: 'finite-v1', budget: '100', deadline: '10000', criteria: ['review'], actions: ['write'], resources: ['doc'], requiresApproval: false, maxAttempts: '2', maxAuthorizationAgeMs: '10', features: [] }));const directory = mkdtempSync(join(tmpdir(), 'aiws-effect-adapter-'));const store = new SqliteStore(join(directory, 'mission.db'), contract);const coordinator = new Coordinator(store, async (command) => ({ allowed: true, policy: 'ALLOW', mandatoryChecksOk: true, context: { actor: command.type === 'settle' ? 'demo:reviewer' : 'demo:operator', policyRevision: 'policy:1', decisionClass: command.type === 'settle' ? 'HUMAN' : 'DETERMINISTIC' } }), () => '10');const target = new LossyTarget();const adapter = new KeyedWriteAdapter(contract.missionId, target);try { await coordinator.apply(parseCommand(canonical({ type: 'startRun', runId: 'r' }))); await coordinator.apply(parseCommand(canonical({ type: 'grant', grant: { id: 'g', subject: 'agent', profile: 'finite-v1', actions: ['write'], resources: ['doc'], notBefore: '0', expiresAt: '10000', limit: '100', canDelegate: false, depth: '0' } }))); await coordinator.apply(parseCommand(canonical({ type: 'admit', runId: 'r', operationId: 'o', attemptId: 'a', grantId: 'g', subject: 'agent', action: { capability: 'write', resource: 'doc', payload: { value: 1 }, preconditions: { revision: 1 } }, amount: '10', authorizationCheckedAt: '10', policy: 'ALLOW', mandatoryChecksOk: true }))); let state = await coordinator.dispatch('a', adapter); assert.equal(state.attempts.a.status, 'UNKNOWN'); // The write applied, but a timeout proves nothing. assert.equal(state.reserved, '10'); // UNKNOWN keeps the reservation. state = await coordinator.reconcile('a', adapter); // Read-only: looks the key up, never resubmits. assert.equal(state.attempts.a.status, 'SUCCEEDED'); assert.equal(state.operations.o.effect, 'CONFIRMED_APPLIED'); assert.equal(state.spent, '3'); assert.equal(state.reserved, '0'); assert.equal(target.revision, 2); // Applied exactly once. assert.deepEqual(target.document, { value: 1 }); assert.deepEqual([...target.keys.keys()], [idempotencyKey('m', state.operations.o)]); console.log('PASS: effect-adapter');} finally { store.close();}use aiws_sdk::runtime::*;use aiws_sdk::sqlite::SqliteStore;use aiws_sdk::*;use serde_json::{json, Value};
// Operation contract (STANDARD E-01, E-04) for `write` on `doc`, the KeyedWriteAdapter below.// - Effect: sets the document to `action.payload`. Idempotent under the key: the target records// the key with the change in one transaction, applies a key at most once, and refuses a key// whose fingerprint differs. It keeps a key record for 24 hours.// - Precondition: the document is at `action.preconditions.revision`. Postcondition: the payload// is stored and the revision has advanced. Every change advances the revision.// - Timeout: 30 seconds. Exit 0 means applied, at a cost of 3. Exit 3 means the target refused the// request before changing anything, at no cost. Any other exit, a timeout or a transport error// proves nothing: the outcome is UNKNOWN.// - Reconciliation: read-only `lookup` of the key and the revision. A recorded key proves the// change; an absent key with the revision unchanged proves nothing changed. Anything else// stays UNKNOWN for a human.// - Retry: the key comes from the operation, not the attempt, so a retry reuses it and the target// absorbs a late original. Retry only after CONFIRMED_NOT_APPLIED, inside the retention window.pub enum Submission { Exited(i32), TimedOut,}pub struct Lookup { pub key_recorded: bool, pub revision: i64,}/// Injected by the host: the real client in production, a fake target in tests.pub trait Transport { fn submit(&mut self, request: &Value) -> std::result::Result<Submission, String>; /// Read-only: never changes the target. fn lookup(&mut self, key: &str, resource: &str) -> std::result::Result<Lookup, String>;}/// Mission, operation and action fingerprint: stable across attempts, different for a changed action.pub fn idempotency_key(mission_id: &str, operation: &Value) -> String { format!( "{}/{}/{}", mission_id, operation["id"].as_str().unwrap_or_default(), operation["fingerprint"].as_str().unwrap_or_default() )}fn outcome(effect: &str, actual_cost: &str) -> Outcome { Outcome { effect: effect.into(), actual_cost: actual_cost.into(), }}fn applied() -> Outcome { outcome("CONFIRMED_APPLIED", "3")}fn not_applied() -> Outcome { outcome("CONFIRMED_NOT_APPLIED", "0")}fn unknown() -> Outcome { outcome("UNKNOWN", "0")}pub struct KeyedWriteAdapter<T: Transport> { pub mission_id: String, pub transport: T,}impl<T: Transport> EffectAdapter for KeyedWriteAdapter<T> { fn execute(&mut self, operation: &Value, _attempt: &Value) -> Result<Outcome> { let action = &operation["action"]; let request = json!({ "key": idempotency_key(&self.mission_id, operation), "fingerprint": operation["fingerprint"], "resource": action["resource"], "payload": action["payload"], "expectedRevision": action["preconditions"]["revision"], "timeoutMs": 30000 }); Ok(match self.transport.submit(&request) { // A thrown transport error does not show whether the target applied the write. Err(_) => unknown(), // A timeout never proves the action did not happen. Ok(Submission::TimedOut) => unknown(), Ok(Submission::Exited(0)) => applied(), // The contract: exit 3 is a refusal before any change. Ok(Submission::Exited(3)) => not_applied(), // Other nonzero exits carry no proof that nothing changed. Ok(Submission::Exited(_)) => unknown(), }) } fn reconcile(&mut self, operation: &Value, _attempt: &Value) -> Result<Outcome> { let key = idempotency_key(&self.mission_id, operation); let resource = operation["action"]["resource"].as_str().unwrap_or_default(); let expected = operation["action"]["preconditions"]["revision"].as_i64(); Ok(match self.transport.lookup(&key, resource) { Err(_) => unknown(), Ok(found) if found.key_recorded => applied(), Ok(found) if Some(found.revision) == expected => not_applied(), // The target moved without our key: an expired key record or another writer. Ok(_) => unknown(), }) }}
// ---- A local target that applies a write and then loses the response. ----struct LossyTarget { revision: i64, document: Value, keys: std::collections::BTreeMap<String, String>,}impl Transport for LossyTarget { fn submit(&mut self, request: &Value) -> std::result::Result<Submission, String> { let key = request["key"].as_str().ok_or("key")?.to_owned(); let fingerprint = request["fingerprint"].as_str().ok_or("fingerprint")?.to_owned(); if let Some(recorded) = self.keys.get(&key) { return Ok(Submission::Exited(if *recorded == fingerprint { 0 } else { 3 })); } if request["expectedRevision"].as_i64() != Some(self.revision) { return Ok(Submission::Exited(3)); } self.document = request["payload"].clone(); self.revision += 1; self.keys.insert(key, fingerprint); Ok(Submission::TimedOut) // Applied, but the response never arrived. } fn lookup(&mut self, key: &str, _: &str) -> std::result::Result<Lookup, String> { Ok(Lookup { key_recorded: self.keys.contains_key(key), revision: self.revision, }) }}// Demo identity only: replace with authenticated, versioned policy and a human for settle.struct DemoIdentity;impl Authorizer for DemoIdentity { fn authorize(&mut self, command: &Command, _: &Snapshot, _: &str) -> Result<Authorization> { let (actor, class) = if command.as_value()["type"] == "settle" { ("demo:reviewer", "HUMAN") } else { ("demo:operator", "DETERMINISTIC") }; Ok(Authorization { allowed: true, policy: "ALLOW".into(), mandatory_checks_ok: true, context: json!({"actor":actor,"policyRevision":"policy:1","decisionClass":class}), }) }}struct Fixed;impl Clock for Fixed { fn now_ms(&self) -> String { "10".into() }}fn main() -> std::result::Result<(), Box<dyn std::error::Error>> { let contract = Contract::parse(&json!({"id":"c","missionId":"m","aiwsEdition":"0.4","profile":"finite-v1","budget":"100","deadline":"10000","criteria":["review"],"actions":["write"],"resources":["doc"],"requiresApproval":false,"maxAttempts":"2","maxAuthorizationAgeMs":"10","features":[]}).to_string())?; let directory = std::env::temp_dir().join(format!( "aiws-effect-adapter-{}-{}", std::process::id(), std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH)? .as_nanos() )); std::fs::create_dir(&directory)?; let store = SqliteStore::open(directory.join("mission.db").to_str().unwrap(), Some(&contract))?; let mut c = Coordinator::new(store, DemoIdentity, Fixed); let mut adapter = KeyedWriteAdapter { mission_id: "m".into(), transport: LossyTarget { revision: 1, document: Value::Null, keys: Default::default() }, }; for raw in [ json!({"type":"startRun","runId":"r"}), json!({"type":"grant","grant":{"id":"g","subject":"agent","profile":"finite-v1","actions":["write"],"resources":["doc"],"notBefore":"0","expiresAt":"10000","limit":"100","canDelegate":false,"depth":"0"}}), json!({"type":"admit","runId":"r","operationId":"o","attemptId":"a","grantId":"g","subject":"agent","action":{"capability":"write","resource":"doc","payload":{"value":1},"preconditions":{"revision":1}},"amount":"10","authorizationCheckedAt":"10","policy":"ALLOW","mandatoryChecksOk":true}), ] { c.apply(&Command::from_value(raw)?, None)?; } let state = c.dispatch("a", &mut adapter, None)?; assert_eq!(state.as_value()["attempts"]["a"]["status"], "UNKNOWN"); // The write applied, but a timeout proves nothing. assert_eq!(state.as_value()["reserved"], "10"); // UNKNOWN keeps the reservation. let state = c.reconcile("a", &mut adapter)?; // Read-only: looks the key up, never resubmits. assert_eq!(state.as_value()["attempts"]["a"]["status"], "SUCCEEDED"); assert_eq!(state.as_value()["operations"]["o"]["effect"], "CONFIRMED_APPLIED"); assert_eq!(state.as_value()["spent"], "3"); assert_eq!(state.as_value()["reserved"], "0"); assert_eq!(adapter.transport.revision, 2); // Applied exactly once. assert_eq!(adapter.transport.document, json!({"value":1})); assert_eq!( adapter.transport.keys.keys().cloned().collect::<Vec<_>>(), [idempotency_key("m", &state.as_value()["operations"]["o"])] ); println!("PASS: effect-adapter"); Ok(())}"""Write an effect adapter first, then run it through the coordinator with a lossy local target."""import jsonimport tempfilefrom pathlib import Pathfrom typing import Protocol, TypedDict, Unionfrom aiws.core import parse_contractfrom aiws.sqlite import SqliteStorefrom aiws.runtime import Coordinator, Outcome
# Operation contract (STANDARD E-01, E-04) for `write` on `doc`, the KeyedWriteAdapter below.# - Effect: sets the document to `action.payload`. Idempotent under the key: the target records# the key with the change in one transaction, applies a key at most once, and refuses a key# whose fingerprint differs. It keeps a key record for 24 hours.# - Precondition: the document is at `action.preconditions.revision`. Postcondition: the payload# is stored and the revision has advanced. Every change advances the revision.# - Timeout: 30 seconds. Exit 0 means applied, at a cost of 3. Exit 3 means the target refused the# request before changing anything, at no cost. Any other exit, a timeout or a transport error# proves nothing: the outcome is UNKNOWN.# - Reconciliation: read-only `lookup` of the key and the revision. A recorded key proves the# change; an absent key with the revision unchanged proves nothing changed. Anything else# stays UNKNOWN for a human.# - Retry: the key comes from the operation, not the attempt, so a retry reuses it and the target# absorbs a late original. Retry only after CONFIRMED_NOT_APPLIED, inside the retention window.class Exited(TypedDict): exitCode: intclass TimedOut(TypedDict): timedOut: boolSubmission = Union[Exited, TimedOut]class Lookup(TypedDict): keyRecorded: bool revision: intclass Transport(Protocol): """Injected by the host: the real client in production, a fake target in tests.""" def submit(self, request: dict) -> Submission: ... def lookup(self, key: str, resource: str) -> Lookup: """Read-only: never changes the target.""" ...def idempotency_key(mission_id: str, operation: dict) -> str: """Mission, operation and action fingerprint: stable across attempts, different for a changed action.""" return f"{mission_id}/{operation['id']}/{operation['fingerprint']}"APPLIED: Outcome = {'effect': 'CONFIRMED_APPLIED', 'actualCost': '3'}NOT_APPLIED: Outcome = {'effect': 'CONFIRMED_NOT_APPLIED', 'actualCost': '0'}UNKNOWN: Outcome = {'effect': 'UNKNOWN', 'actualCost': '0'}class KeyedWriteAdapter: def __init__(self, mission_id: str, transport: Transport): self.mission_id, self.transport = mission_id, transport def execute(self, operation: dict, attempt: dict) -> Outcome: action = operation['action'] try: reply = self.transport.submit({'key': idempotency_key(self.mission_id, operation), 'fingerprint': operation['fingerprint'], 'resource': action['resource'], 'payload': action['payload'], 'expectedRevision': action['preconditions']['revision'], 'timeoutMs': 30000}) except Exception: return dict(UNKNOWN) # A thrown transport error does not show whether the target applied the write. if 'timedOut' in reply: return dict(UNKNOWN) # A timeout never proves the action did not happen. if reply['exitCode'] == 0: return dict(APPLIED) if reply['exitCode'] == 3: return dict(NOT_APPLIED) # The contract: exit 3 is a refusal before any change. return dict(UNKNOWN) # Other nonzero exits carry no proof that nothing changed. def reconcile(self, operation: dict, attempt: dict) -> Outcome: try: found = self.transport.lookup(idempotency_key(self.mission_id, operation), operation['action']['resource']) except Exception: return dict(UNKNOWN) if found['keyRecorded']: return dict(APPLIED) if found['revision'] == operation['action']['preconditions']['revision']: return dict(NOT_APPLIED) return dict(UNKNOWN) # The target moved without our key: an expired key record or another writer.
# ---- A local target that applies a write and then loses the response. ----class LossyTarget: def __init__(self): self.revision, self.document, self.keys = 1, None, {} def submit(self, request): if request['key'] in self.keys: return {'exitCode': 0 if self.keys[request['key']] == request['fingerprint'] else 3} if request['expectedRevision'] != self.revision: return {'exitCode': 3} self.document, self.revision = request['payload'], self.revision + 1 self.keys[request['key']] = request['fingerprint'] return {'timedOut': True} # Applied, but the response never arrived. def lookup(self, key, resource): return {'keyRecorded': key in self.keys, 'revision': self.revision}
def demo_identity(command, state, now): """Demo identity only: replace with authenticated, versioned policy and a human for settle.""" settle = command['type'] == 'settle' return dict(allowed=True, policy='ALLOW', mandatoryChecksOk=True, context=dict(actor='demo:reviewer' if settle else 'demo:operator', policyRevision='policy:1', decisionClass='HUMAN' if settle else 'DETERMINISTIC'))contract = parse_contract(json.dumps({'id': 'c', 'missionId': 'm', 'aiwsEdition': '0.4', 'profile': 'finite-v1', 'budget': '100', 'deadline': '10000', 'criteria': ['review'], 'actions': ['write'], 'resources': ['doc'], 'requiresApproval': False, 'maxAttempts': '2', 'maxAuthorizationAgeMs': '10', 'features': []}))directory = Path(tempfile.mkdtemp(prefix='aiws-python-effect-adapter-'))target = LossyTarget()adapter = KeyedWriteAdapter(contract['missionId'], target)with SqliteStore(str(directory / 'mission.db'), contract) as store: c = Coordinator(store, demo_identity, lambda: '10') c.apply({'type': 'startRun', 'runId': 'r'}) c.apply({'type': 'grant', 'grant': {'id': 'g', 'subject': 'agent', 'profile': 'finite-v1', 'actions': ['write'], 'resources': ['doc'], 'notBefore': '0', 'expiresAt': '10000', 'limit': '100', 'canDelegate': False, 'depth': '0'}}) c.apply({'type': 'admit', 'runId': 'r', 'operationId': 'o', 'attemptId': 'a', 'grantId': 'g', 'subject': 'agent', 'action': {'capability': 'write', 'resource': 'doc', 'payload': {'value': 1}, 'preconditions': {'revision': 1}}, 'amount': '10', 'authorizationCheckedAt': '10', 'policy': 'ALLOW', 'mandatoryChecksOk': True}) state = c.dispatch('a', adapter) assert state['attempts']['a']['status'] == 'UNKNOWN' # The write applied, but a timeout proves nothing. assert state['reserved'] == '10' # UNKNOWN keeps the reservation. state = c.reconcile('a', adapter) # Read-only: looks the key up, never resubmits. assert state['attempts']['a']['status'] == 'SUCCEEDED' assert state['operations']['o']['effect'] == 'CONFIRMED_APPLIED' assert state['spent'] == '3' and state['reserved'] == '0' assert target.revision == 2 and target.document == {'value': 1} # Applied exactly once. assert list(target.keys) == [idempotency_key('m', state['operations']['o'])]print('PASS: effect-adapter')The program dispatches through the coordinator to a local target that applies the write and then loses the response. The adapter reports UNKNOWN, the attempt keeps its reservation, and a read-only reconcile finds the key and settles CONFIRMED_APPLIED, with the write applied once. It uses only SDK 0.5.1 APIs. The demo identity, the in-memory target and its exit codes stand in for an authenticated host and a real target’s documented contract.
Test outcome classification
Section titled “Test outcome classification”Each outcome rule gets its own case, driven through the adapter’s execute and reconcile with a scripted transport:
| Case | Outcome |
|---|---|
| Success: exit 0 | CONFIRMED_APPLIED |
| Proven non-application: an exit the contract defines as a refusal before any change | CONFIRMED_NOT_APPLIED |
| Timeout | UNKNOWN |
| Thrown transport error | UNKNOWN |
| Nonzero exit the contract does not cover | UNKNOWN |
| Reconcile finds the key | CONFIRMED_APPLIED |
| Reconcile shows the target unchanged after a nonzero exit | CONFIRMED_NOT_APPLIED |
| Reconcile cannot decide: the target moved without the key, or the read-back failed | UNKNOWN |
A timeout, a signal, a null exit code or a thrown error never proves the action did not happen. A nonzero exit reports CONFIRMED_NOT_APPLIED only with evidence that nothing changed: the operation contract saying so for that exit, or a read-only reconcile showing the target unchanged. Without either, it is UNKNOWN. These are the SDK forms of NG-01 and NG-02 from the governance rule set. The tests also check that reconcile never calls the mutating transport and that no outcome is FAILED or SUCCEEDED.
Test outcome classification: success, non-application, timeout, transport error, nonzero exit, reconcile · Executable adapter test program; SDK 0.4.0 APIs; scripted transports, no external calls
import assert from 'node:assert/strict';import type { EffectAdapter, Outcome } from '@aiws/sdk/runtime';
/* * Operation contract (STANDARD E-01, E-04) for `write` on `doc`, the KeyedWriteAdapter below. * - Effect: sets the document to `action.payload`. Idempotent under the key: the target records * the key with the change in one transaction, applies a key at most once, and refuses a key * whose fingerprint differs. It keeps a key record for 24 hours. * - Precondition: the document is at `action.preconditions.revision`. Postcondition: the payload * is stored and the revision has advanced. Every change advances the revision. * - Timeout: 30 seconds. Exit 0 means applied, at a cost of 3. Exit 3 means the target refused the * request before changing anything, at no cost. Any other exit, a timeout or a transport error * proves nothing: the outcome is UNKNOWN. * - Reconciliation: read-only `lookup` of the key and the revision. A recorded key proves the * change; an absent key with the revision unchanged proves nothing changed. Anything else * stays UNKNOWN for a human. * - Retry: the key comes from the operation, not the attempt, so a retry reuses it and the target * absorbs a late original. Retry only after CONFIRMED_NOT_APPLIED, inside the retention window. */type Submission = { exitCode: number } | { timedOut: true };/** Own-property check on the transport's plain reply object, never `in`. */const timedOut = (reply: Submission): reply is { timedOut: true } => Object.hasOwn(reply, 'timedOut');interface Lookup { keyRecorded: boolean; revision: number }interface WriteRequest { key: string; fingerprint: string; resource: string; payload: unknown; expectedRevision: number; timeoutMs: number }/** Injected by the host: the real client in production, a fake target in tests. */interface Transport { submit(request: WriteRequest): Promise<Submission>; /** Read-only: never changes the target. */ lookup(key: string, resource: string): Promise<Lookup>;}/** Mission, operation and action fingerprint: stable across attempts, different for a changed action. */const idempotencyKey = (missionId: string, operation: Readonly<Record<string, any>>): string => `${missionId}/${operation.id}/${operation.fingerprint}`;const applied: Outcome = { effect: 'CONFIRMED_APPLIED', actualCost: '3' };const notApplied: Outcome = { effect: 'CONFIRMED_NOT_APPLIED', actualCost: '0' };const unknown: Outcome = { effect: 'UNKNOWN', actualCost: '0' };class KeyedWriteAdapter implements EffectAdapter { private missionId: string; private transport: Transport; constructor(missionId: string, transport: Transport) { this.missionId = missionId; this.transport = transport; } async execute(operation: Readonly<Record<string, any>>, _attempt: Readonly<Record<string, any>>): Promise<Outcome> { const { resource, payload, preconditions } = operation.action; let reply: Submission; try { reply = await this.transport.submit({ key: idempotencyKey(this.missionId, operation), fingerprint: operation.fingerprint, resource, payload, expectedRevision: preconditions.revision, timeoutMs: 30_000 }); } catch { return unknown; // A thrown transport error does not show whether the target applied the write. } if (timedOut(reply)) return unknown; // A timeout never proves the action did not happen. if (reply.exitCode === 0) return applied; if (reply.exitCode === 3) return notApplied; // The contract: exit 3 is a refusal before any change. return unknown; // Other nonzero exits carry no proof that nothing changed. } async reconcile(operation: Readonly<Record<string, any>>, _attempt: Readonly<Record<string, any>>): Promise<Outcome> { let found: Lookup; try { found = await this.transport.lookup(idempotencyKey(this.missionId, operation), operation.action.resource); } catch { return unknown; } if (found.keyRecorded) return applied; if (found.revision === operation.action.preconditions.revision) return notApplied; return unknown; // The target moved without our key: an expired key record or another writer. }}// ---- Outcome-classification tests: one scripted transport per case. ----interface Script { submit?: Submission | Error; lookup?: Lookup | Error }class ScriptedTarget implements Transport { submits = 0; private script: Script; constructor(script: Script) { this.script = script; } async submit(): Promise<Submission> { this.submits++; const reply = this.script.submit; if (reply === undefined) throw Error('submit was not scripted'); if (reply instanceof Error) throw reply; return reply; } async lookup(): Promise<Lookup> { const reply = this.script.lookup; if (reply === undefined) throw Error('lookup was not scripted'); if (reply instanceof Error) throw reply; return reply; }}const operation = { id: 'o', fingerprint: 'sha256:example', action: { capability: 'write', resource: 'doc', payload: { value: 1 }, preconditions: { revision: 1 } } };const attempt = { id: 'a', operationId: 'o' };const key = idempotencyKey('m', operation);const executeCases: [string, Script, Outcome][] = [ ['success: exit 0', { submit: { exitCode: 0 } }, { effect: 'CONFIRMED_APPLIED', actualCost: '3' }], ['proven non-application: exit 3 is contracted as refused before any change', { submit: { exitCode: 3 } }, { effect: 'CONFIRMED_NOT_APPLIED', actualCost: '0' }], ['timeout', { submit: { timedOut: true } }, { effect: 'UNKNOWN', actualCost: '0' }], ['thrown transport error', { submit: Error('connection reset') }, { effect: 'UNKNOWN', actualCost: '0' }], ['nonzero exit the contract does not cover', { submit: { exitCode: 1 } }, { effect: 'UNKNOWN', actualCost: '0' }],];const reconcileCases: [string, Script, Outcome][] = [ ['reconcile finds the effect', { lookup: { keyRecorded: true, revision: 2 } }, { effect: 'CONFIRMED_APPLIED', actualCost: '3' }], ['reconcile proves nothing changed after a nonzero exit', { lookup: { keyRecorded: false, revision: 1 } }, { effect: 'CONFIRMED_NOT_APPLIED', actualCost: '0' }], ['reconcile cannot decide: the target moved and the key is not recorded', { lookup: { keyRecorded: false, revision: 2 } }, { effect: 'UNKNOWN', actualCost: '0' }], ['reconcile cannot decide: the read-back failed', { lookup: Error('target unavailable') }, { effect: 'UNKNOWN', actualCost: '0' }],];const seen = new Set<string>();for (const [name, script, expected] of executeCases) { const target = new ScriptedTarget(script); const outcome = await new KeyedWriteAdapter('m', target).execute(operation, attempt); assert.deepEqual(outcome, expected, name); assert.equal(target.submits, 1, name + ': one submission per attempt'); seen.add(outcome.effect);}for (const [name, script, expected] of reconcileCases) { const target = new ScriptedTarget(script); const outcome = await new KeyedWriteAdapter('m', target).reconcile(operation, attempt); assert.deepEqual(outcome, expected, name); assert.equal(target.submits, 0, name + ': reconcile is read-only'); seen.add(outcome.effect);}// No adapter outcome is an attempt status: FAILED and SUCCEEDED are the reducer's to record.assert.deepEqual([...seen].sort(), ['CONFIRMED_APPLIED', 'CONFIRMED_NOT_APPLIED', 'UNKNOWN']);assert.equal(key, 'm/o/sha256:example');console.log('PASS: effect-outcomes');use aiws_sdk::runtime::{EffectAdapter, Outcome};use aiws_sdk::Result;use serde_json::{json, Value};
// Operation contract (STANDARD E-01, E-04) for `write` on `doc`, the KeyedWriteAdapter below.// - Effect: sets the document to `action.payload`. Idempotent under the key: the target records// the key with the change in one transaction, applies a key at most once, and refuses a key// whose fingerprint differs. It keeps a key record for 24 hours.// - Precondition: the document is at `action.preconditions.revision`. Postcondition: the payload// is stored and the revision has advanced. Every change advances the revision.// - Timeout: 30 seconds. Exit 0 means applied, at a cost of 3. Exit 3 means the target refused the// request before changing anything, at no cost. Any other exit, a timeout or a transport error// proves nothing: the outcome is UNKNOWN.// - Reconciliation: read-only `lookup` of the key and the revision. A recorded key proves the// change; an absent key with the revision unchanged proves nothing changed. Anything else// stays UNKNOWN for a human.// - Retry: the key comes from the operation, not the attempt, so a retry reuses it and the target// absorbs a late original. Retry only after CONFIRMED_NOT_APPLIED, inside the retention window.pub enum Submission { Exited(i32), TimedOut,}pub struct Lookup { pub key_recorded: bool, pub revision: i64,}/// Injected by the host: the real client in production, a fake target in tests.pub trait Transport { fn submit(&mut self, request: &Value) -> std::result::Result<Submission, String>; /// Read-only: never changes the target. fn lookup(&mut self, key: &str, resource: &str) -> std::result::Result<Lookup, String>;}/// Mission, operation and action fingerprint: stable across attempts, different for a changed action.pub fn idempotency_key(mission_id: &str, operation: &Value) -> String { format!( "{}/{}/{}", mission_id, operation["id"].as_str().unwrap_or_default(), operation["fingerprint"].as_str().unwrap_or_default() )}fn outcome(effect: &str, actual_cost: &str) -> Outcome { Outcome { effect: effect.into(), actual_cost: actual_cost.into(), }}fn applied() -> Outcome { outcome("CONFIRMED_APPLIED", "3")}fn not_applied() -> Outcome { outcome("CONFIRMED_NOT_APPLIED", "0")}fn unknown() -> Outcome { outcome("UNKNOWN", "0")}pub struct KeyedWriteAdapter<T: Transport> { pub mission_id: String, pub transport: T,}impl<T: Transport> EffectAdapter for KeyedWriteAdapter<T> { fn execute(&mut self, operation: &Value, _attempt: &Value) -> Result<Outcome> { let action = &operation["action"]; let request = json!({ "key": idempotency_key(&self.mission_id, operation), "fingerprint": operation["fingerprint"], "resource": action["resource"], "payload": action["payload"], "expectedRevision": action["preconditions"]["revision"], "timeoutMs": 30000 }); Ok(match self.transport.submit(&request) { // A thrown transport error does not show whether the target applied the write. Err(_) => unknown(), // A timeout never proves the action did not happen. Ok(Submission::TimedOut) => unknown(), Ok(Submission::Exited(0)) => applied(), // The contract: exit 3 is a refusal before any change. Ok(Submission::Exited(3)) => not_applied(), // Other nonzero exits carry no proof that nothing changed. Ok(Submission::Exited(_)) => unknown(), }) } fn reconcile(&mut self, operation: &Value, _attempt: &Value) -> Result<Outcome> { let key = idempotency_key(&self.mission_id, operation); let resource = operation["action"]["resource"].as_str().unwrap_or_default(); let expected = operation["action"]["preconditions"]["revision"].as_i64(); Ok(match self.transport.lookup(&key, resource) { Err(_) => unknown(), Ok(found) if found.key_recorded => applied(), Ok(found) if Some(found.revision) == expected => not_applied(), // The target moved without our key: an expired key record or another writer. Ok(_) => unknown(), }) }}
// ---- Outcome-classification tests: one scripted transport per case. ----type Reply<T> = Option<std::result::Result<T, String>>;struct ScriptedTarget { submit: Reply<Submission>, lookup: Reply<Lookup>, submits: usize,}impl Transport for ScriptedTarget { fn submit(&mut self, _: &Value) -> std::result::Result<Submission, String> { self.submits += 1; self.submit.take().expect("submit was not scripted") } fn lookup(&mut self, _: &str, _: &str) -> std::result::Result<Lookup, String> { self.lookup.take().expect("lookup was not scripted") }}fn adapter(submit: Reply<Submission>, lookup: Reply<Lookup>) -> KeyedWriteAdapter<ScriptedTarget> { KeyedWriteAdapter { mission_id: "m".into(), transport: ScriptedTarget { submit, lookup, submits: 0 }, }}fn found(key_recorded: bool, revision: i64) -> Reply<Lookup> { Some(Ok(Lookup { key_recorded, revision }))}fn main() -> Result<()> { let operation = json!({"id":"o","fingerprint":"sha256:example","action":{"capability":"write","resource":"doc","payload":{"value":1},"preconditions":{"revision":1}}}); let attempt = json!({"id":"a","operationId":"o"}); let execute_cases = [ ("success: exit 0", Ok(Submission::Exited(0)), ("CONFIRMED_APPLIED", "3")), ("proven non-application: exit 3 is contracted as refused before any change", Ok(Submission::Exited(3)), ("CONFIRMED_NOT_APPLIED", "0")), ("timeout", Ok(Submission::TimedOut), ("UNKNOWN", "0")), ("thrown transport error", Err("connection reset".to_string()), ("UNKNOWN", "0")), ("nonzero exit the contract does not cover", Ok(Submission::Exited(1)), ("UNKNOWN", "0")), ]; let mut seen = std::collections::BTreeSet::new(); for (name, submit, (effect, cost)) in execute_cases { let mut a = adapter(Some(submit), None); let result = a.execute(&operation, &attempt)?; assert_eq!((result.effect.as_str(), result.actual_cost.as_str()), (effect, cost), "{name}"); assert_eq!(a.transport.submits, 1, "{name}: one submission per attempt"); seen.insert(result.effect); } let reconcile_cases = [ ("reconcile finds the effect", found(true, 2), ("CONFIRMED_APPLIED", "3")), ("reconcile proves nothing changed after a nonzero exit", found(false, 1), ("CONFIRMED_NOT_APPLIED", "0")), ("reconcile cannot decide: the target moved and the key is not recorded", found(false, 2), ("UNKNOWN", "0")), ("reconcile cannot decide: the read-back failed", Some(Err("target unavailable".to_string())), ("UNKNOWN", "0")), ]; for (name, lookup, (effect, cost)) in reconcile_cases { let mut a = adapter(None, lookup); let result = a.reconcile(&operation, &attempt)?; assert_eq!((result.effect.as_str(), result.actual_cost.as_str()), (effect, cost), "{name}"); assert_eq!(a.transport.submits, 0, "{name}: reconcile is read-only"); seen.insert(result.effect); } // No adapter outcome is an attempt status: FAILED and SUCCEEDED are the reducer's to record. assert_eq!(seen.into_iter().collect::<Vec<_>>(), ["CONFIRMED_APPLIED", "CONFIRMED_NOT_APPLIED", "UNKNOWN"]); assert_eq!(idempotency_key("m", &operation), "m/o/sha256:example"); println!("PASS: effect-outcomes"); Ok(())}"""Test how an effect adapter classifies each outcome, with scripted transports."""from typing import Protocol, TypedDict, Unionfrom aiws.runtime import Outcome
# Operation contract (STANDARD E-01, E-04) for `write` on `doc`, the KeyedWriteAdapter below.# - Effect: sets the document to `action.payload`. Idempotent under the key: the target records# the key with the change in one transaction, applies a key at most once, and refuses a key# whose fingerprint differs. It keeps a key record for 24 hours.# - Precondition: the document is at `action.preconditions.revision`. Postcondition: the payload# is stored and the revision has advanced. Every change advances the revision.# - Timeout: 30 seconds. Exit 0 means applied, at a cost of 3. Exit 3 means the target refused the# request before changing anything, at no cost. Any other exit, a timeout or a transport error# proves nothing: the outcome is UNKNOWN.# - Reconciliation: read-only `lookup` of the key and the revision. A recorded key proves the# change; an absent key with the revision unchanged proves nothing changed. Anything else# stays UNKNOWN for a human.# - Retry: the key comes from the operation, not the attempt, so a retry reuses it and the target# absorbs a late original. Retry only after CONFIRMED_NOT_APPLIED, inside the retention window.class Exited(TypedDict): exitCode: intclass TimedOut(TypedDict): timedOut: boolSubmission = Union[Exited, TimedOut]class Lookup(TypedDict): keyRecorded: bool revision: intclass Transport(Protocol): """Injected by the host: the real client in production, a fake target in tests.""" def submit(self, request: dict) -> Submission: ... def lookup(self, key: str, resource: str) -> Lookup: """Read-only: never changes the target.""" ...def idempotency_key(mission_id: str, operation: dict) -> str: """Mission, operation and action fingerprint: stable across attempts, different for a changed action.""" return f"{mission_id}/{operation['id']}/{operation['fingerprint']}"APPLIED: Outcome = {'effect': 'CONFIRMED_APPLIED', 'actualCost': '3'}NOT_APPLIED: Outcome = {'effect': 'CONFIRMED_NOT_APPLIED', 'actualCost': '0'}UNKNOWN: Outcome = {'effect': 'UNKNOWN', 'actualCost': '0'}class KeyedWriteAdapter: def __init__(self, mission_id: str, transport: Transport): self.mission_id, self.transport = mission_id, transport def execute(self, operation: dict, attempt: dict) -> Outcome: action = operation['action'] try: reply = self.transport.submit({'key': idempotency_key(self.mission_id, operation), 'fingerprint': operation['fingerprint'], 'resource': action['resource'], 'payload': action['payload'], 'expectedRevision': action['preconditions']['revision'], 'timeoutMs': 30000}) except Exception: return dict(UNKNOWN) # A thrown transport error does not show whether the target applied the write. if 'timedOut' in reply: return dict(UNKNOWN) # A timeout never proves the action did not happen. if reply['exitCode'] == 0: return dict(APPLIED) if reply['exitCode'] == 3: return dict(NOT_APPLIED) # The contract: exit 3 is a refusal before any change. return dict(UNKNOWN) # Other nonzero exits carry no proof that nothing changed. def reconcile(self, operation: dict, attempt: dict) -> Outcome: try: found = self.transport.lookup(idempotency_key(self.mission_id, operation), operation['action']['resource']) except Exception: return dict(UNKNOWN) if found['keyRecorded']: return dict(APPLIED) if found['revision'] == operation['action']['preconditions']['revision']: return dict(NOT_APPLIED) return dict(UNKNOWN) # The target moved without our key: an expired key record or another writer.
# ---- Outcome-classification tests: one scripted transport per case. ----class ScriptedTarget: def __init__(self, submit=None, lookup=None): self.script, self.submits = {'submit': submit, 'lookup': lookup}, 0 def _reply(self, name): reply = self.script[name] if reply is None: raise AssertionError(name + ' was not scripted') if isinstance(reply, Exception): raise reply return reply def submit(self, request): self.submits += 1 return self._reply('submit') def lookup(self, key, resource): return self._reply('lookup')operation = {'id': 'o', 'fingerprint': 'sha256:example', 'action': {'capability': 'write', 'resource': 'doc', 'payload': {'value': 1}, 'preconditions': {'revision': 1}}}attempt = {'id': 'a', 'operationId': 'o'}execute_cases = [ ('success: exit 0', {'exitCode': 0}, {'effect': 'CONFIRMED_APPLIED', 'actualCost': '3'}), ('proven non-application: exit 3 is contracted as refused before any change', {'exitCode': 3}, {'effect': 'CONFIRMED_NOT_APPLIED', 'actualCost': '0'}), ('timeout', {'timedOut': True}, {'effect': 'UNKNOWN', 'actualCost': '0'}), ('thrown transport error', ConnectionResetError('connection reset'), {'effect': 'UNKNOWN', 'actualCost': '0'}), ('nonzero exit the contract does not cover', {'exitCode': 1}, {'effect': 'UNKNOWN', 'actualCost': '0'}),]reconcile_cases = [ ('reconcile finds the effect', {'keyRecorded': True, 'revision': 2}, {'effect': 'CONFIRMED_APPLIED', 'actualCost': '3'}), ('reconcile proves nothing changed after a nonzero exit', {'keyRecorded': False, 'revision': 1}, {'effect': 'CONFIRMED_NOT_APPLIED', 'actualCost': '0'}), ('reconcile cannot decide: the target moved and the key is not recorded', {'keyRecorded': False, 'revision': 2}, {'effect': 'UNKNOWN', 'actualCost': '0'}), ('reconcile cannot decide: the read-back failed', OSError('target unavailable'), {'effect': 'UNKNOWN', 'actualCost': '0'}),]seen = set()for name, submit, expected in execute_cases: target = ScriptedTarget(submit=submit) outcome = KeyedWriteAdapter('m', target).execute(operation, attempt) assert outcome == expected, name assert target.submits == 1, name + ': one submission per attempt' seen.add(outcome['effect'])for name, lookup, expected in reconcile_cases: target = ScriptedTarget(lookup=lookup) outcome = KeyedWriteAdapter('m', target).reconcile(operation, attempt) assert outcome == expected, name assert target.submits == 0, name + ': reconcile is read-only' seen.add(outcome['effect'])# No adapter outcome is an attempt status: FAILED and SUCCEEDED are the reducer's to record.assert sorted(seen) == ['CONFIRMED_APPLIED', 'CONFIRMED_NOT_APPLIED', 'UNKNOWN']assert idempotency_key('m', operation) == 'm/o/sha256:example'print('PASS: effect-outcomes')Retry a known failure
Section titled “Retry a known failure”Retry confirmed nonapplication and handle duplicate results · Executable control simulation
import assert from 'node:assert/strict';import { createMission, parseContract, parseCommand, reduce } from '@aiws/sdk';
// Trusted simulation: this example makes no external calls.const contract = parseContract(JSON.stringify({ "id": "c", "missionId": "m", "aiwsEdition": "0.4", "profile": "finite-v1", "budget": "100", "deadline": "10000", "criteria": [ "review" ], "actions": [ "write" ], "resources": [ "doc" ], "requiresApproval": false, "maxAttempts": "2", "maxAuthorizationAgeMs": "10", "features": [ "triggers", "graphs" ]}));let state = createMission(contract);
// Step 1state = reduce(state, parseCommand(JSON.stringify({ "type": "startRun", "runId": "r"})), '10');
// Step 2state = reduce(state, parseCommand(JSON.stringify({ "type": "grant", "grant": { "id": "g", "subject": "agent", "profile": "finite-v1", "actions": [ "write" ], "resources": [ "doc" ], "notBefore": "0", "expiresAt": "10000", "limit": "100", "canDelegate": true, "depth": "2" }})), '10');
// Step 3state = reduce(state, parseCommand(JSON.stringify({ "type": "admit", "runId": "r", "operationId": "o", "attemptId": "a", "grantId": "g", "subject": "agent", "action": { "capability": "write", "resource": "doc", "payload": { "value": 1 }, "preconditions": { "revision": 1 } }, "amount": "10", "authorizationCheckedAt": "10", "policy": "ALLOW", "mandatoryChecksOk": true})), '10');
// Step 4state = reduce(state, parseCommand(JSON.stringify({ "type": "dispatch", "attemptId": "a", "authorizationCheckedAt": "10", "policy": "ALLOW", "mandatoryChecksOk": true})), '10');
// Step 5state = reduce(state, parseCommand(JSON.stringify({ "type": "settle", "attemptId": "a", "effect": "CONFIRMED_NOT_APPLIED", "actualCost": "0"})), '10');
// Step 6state = reduce(state, parseCommand(JSON.stringify({ "type": "retry", "operationId": "o", "attemptId": "a2", "amount": "10", "authorizationCheckedAt": "10", "policy": "ALLOW", "mandatoryChecksOk": true})), '10');
// Step 7state = reduce(state, parseCommand(JSON.stringify({ "type": "dispatch", "attemptId": "a2", "authorizationCheckedAt": "10", "policy": "ALLOW", "mandatoryChecksOk": true})), '10');
// Step 8state = reduce(state, parseCommand(JSON.stringify({ "type": "settle", "attemptId": "a", "effect": "CONFIRMED_NOT_APPLIED", "actualCost": "0"})), '10');
// Step 9state = reduce(state, parseCommand(JSON.stringify({ "type": "settle", "attemptId": "a2", "effect": "CONFIRMED_APPLIED", "actualCost": "2"})), '10');assert.deepEqual(state["spent"], "2");assert.deepEqual(state["reserved"], "0");console.log('PASS: retry');use aiws_sdk::*;use serde_json::json;
fn main() -> Result<()> { // Trusted simulation: no external calls. let contract = Contract::parse(&json!({ "id": "c", "missionId": "m", "aiwsEdition": "0.4", "profile": "finite-v1", "budget": "100", "deadline": "10000", "criteria": [ "review" ], "actions": [ "write" ], "resources": [ "doc" ], "requiresApproval": false, "maxAttempts": "2", "maxAuthorizationAgeMs": "10", "features": [ "triggers", "graphs" ]}).to_string())?; let mut state = create_mission(&contract)?;
// Step 1 state = reduce(&state, &Command::from_value(json!({ "type": "startRun", "runId": "r"}))?, "10")?;
// Step 2 state = reduce(&state, &Command::from_value(json!({ "type": "grant", "grant": { "id": "g", "subject": "agent", "profile": "finite-v1", "actions": [ "write" ], "resources": [ "doc" ], "notBefore": "0", "expiresAt": "10000", "limit": "100", "canDelegate": true, "depth": "2" }}))?, "10")?;
// Step 3 state = reduce(&state, &Command::from_value(json!({ "type": "admit", "runId": "r", "operationId": "o", "attemptId": "a", "grantId": "g", "subject": "agent", "action": { "capability": "write", "resource": "doc", "payload": { "value": 1 }, "preconditions": { "revision": 1 } }, "amount": "10", "authorizationCheckedAt": "10", "policy": "ALLOW", "mandatoryChecksOk": true}))?, "10")?;
// Step 4 state = reduce(&state, &Command::from_value(json!({ "type": "dispatch", "attemptId": "a", "authorizationCheckedAt": "10", "policy": "ALLOW", "mandatoryChecksOk": true}))?, "10")?;
// Step 5 state = reduce(&state, &Command::from_value(json!({ "type": "settle", "attemptId": "a", "effect": "CONFIRMED_NOT_APPLIED", "actualCost": "0"}))?, "10")?;
// Step 6 state = reduce(&state, &Command::from_value(json!({ "type": "retry", "operationId": "o", "attemptId": "a2", "amount": "10", "authorizationCheckedAt": "10", "policy": "ALLOW", "mandatoryChecksOk": true}))?, "10")?;
// Step 7 state = reduce(&state, &Command::from_value(json!({ "type": "dispatch", "attemptId": "a2", "authorizationCheckedAt": "10", "policy": "ALLOW", "mandatoryChecksOk": true}))?, "10")?;
// Step 8 state = reduce(&state, &Command::from_value(json!({ "type": "settle", "attemptId": "a", "effect": "CONFIRMED_NOT_APPLIED", "actualCost": "0"}))?, "10")?;
// Step 9 state = reduce(&state, &Command::from_value(json!({ "type": "settle", "attemptId": "a2", "effect": "CONFIRMED_APPLIED", "actualCost": "2"}))?, "10")?; assert_eq!(state.as_value()["spent"], json!("2")); assert_eq!(state.as_value()["reserved"], json!("0")); println!("PASS: retry"); Ok(())}import jsonfrom aiws import create_mission, parse_contract, reduce, AiwsError
# Trusted simulation: this example makes no external calls.contract = parse_contract(json.dumps({'id': 'c', 'missionId': 'm', 'aiwsEdition': '0.4', 'profile': 'finite-v1', 'budget': '100', 'deadline': '10000', 'criteria': ['review'], 'actions': ['write'], 'resources': ['doc'], 'requiresApproval': False, 'maxAttempts': '2', 'maxAuthorizationAgeMs': '10', 'features': ['triggers', 'graphs']}))state = create_mission(contract)
# Step 1state = reduce(state, {'type': 'startRun', 'runId': 'r'}, '10')
# Step 2state = reduce(state, {'type': 'grant', 'grant': {'id': 'g', 'subject': 'agent', 'profile': 'finite-v1', 'actions': ['write'], 'resources': ['doc'], 'notBefore': '0', 'expiresAt': '10000', 'limit': '100', 'canDelegate': True, 'depth': '2'}}, '10')
# Step 3state = reduce(state, {'type': 'admit', 'runId': 'r', 'operationId': 'o', 'attemptId': 'a', 'grantId': 'g', 'subject': 'agent', 'action': {'capability': 'write', 'resource': 'doc', 'payload': {'value': 1}, 'preconditions': {'revision': 1}}, 'amount': '10', 'authorizationCheckedAt': '10', 'policy': 'ALLOW', 'mandatoryChecksOk': True}, '10')
# Step 4state = reduce(state, {'type': 'dispatch', 'attemptId': 'a', 'authorizationCheckedAt': '10', 'policy': 'ALLOW', 'mandatoryChecksOk': True}, '10')
# Step 5state = reduce(state, {'type': 'settle', 'attemptId': 'a', 'effect': 'CONFIRMED_NOT_APPLIED', 'actualCost': '0'}, '10')
# Step 6state = reduce(state, {'type': 'retry', 'operationId': 'o', 'attemptId': 'a2', 'amount': '10', 'authorizationCheckedAt': '10', 'policy': 'ALLOW', 'mandatoryChecksOk': True}, '10')
# Step 7state = reduce(state, {'type': 'dispatch', 'attemptId': 'a2', 'authorizationCheckedAt': '10', 'policy': 'ALLOW', 'mandatoryChecksOk': True}, '10')
# Step 8state = reduce(state, {'type': 'settle', 'attemptId': 'a', 'effect': 'CONFIRMED_NOT_APPLIED', 'actualCost': '0'}, '10')
# Step 9state = reduce(state, {'type': 'settle', 'attemptId': 'a2', 'effect': 'CONFIRMED_APPLIED', 'actualCost': '2'}, '10')assert state["spent"] == '2'assert state["reserved"] == '0'print('PASS: retry')The example also checks a late duplicate settlement. An identical result is accepted without charging again, while inconsistent results are rejected. Accepted duplicates still produce a new control event; semantic idempotence does not mean the event count stays unchanged.
The retry must reuse the operation identity but have a fresh attempt identity. maxAttempts includes the initial attempt. Every attempt reserves exposure; prior recorded costs remain spent. Retrying never renews an expired grant, approval or contract deadline.
Lost-response procedure
Section titled “Lost-response procedure”Keep the task under human review when the external outcome is uncertain. Read target-side receipts, repository state or provider request status using the original identity. If evidence proves the action applied, settle that attempt with its actual cost. If evidence proves nonapplication, settle accordingly before requesting a retry. If evidence remains ambiguous, keep UNKNOWN. Human intervention must record evidence and a decision; it must not fabricate certainty.
Compensation
Section titled “Compensation”A compensating action is a new governed operation with its own cost, permission and outcome. It references an earlier applied operation but does not delete history or claim that the original action never happened. Some changes are not reversible. Verify the resulting state of the target rather than assuming successful compensation restored every property.
Record reconciliation and a separate compensating effect · Executable control simulation
import assert from 'node:assert/strict';import { createMission, parseContract, parseCommand, reduce } from '@aiws/sdk';
// Trusted simulation: this example makes no external calls.const contract = parseContract(JSON.stringify({ "id": "c", "missionId": "m", "aiwsEdition": "0.4", "profile": "finite-v1", "budget": "100", "deadline": "10000", "criteria": [ "review" ], "actions": [ "write" ], "resources": [ "doc" ], "requiresApproval": false, "maxAttempts": "2", "maxAuthorizationAgeMs": "10", "features": [ "triggers", "graphs" ]}));let state = createMission(contract);
// Step 1state = reduce(state, parseCommand(JSON.stringify({ "type": "startRun", "runId": "r"})), '10');
// Step 2state = reduce(state, parseCommand(JSON.stringify({ "type": "registerGraph", "graph": { "id": "graph", "revision": "1", "nodes": [ { "id": "task", "kind": "TASK", "dependsOn": [], "config": { "executionKind": "FUNCTION" } }, { "id": "reconcile", "kind": "RECONCILIATION", "dependsOn": [ "task" ], "config": {} }, { "id": "undo", "kind": "COMPENSATION", "dependsOn": [ "reconcile" ], "config": {} }, { "id": "end", "kind": "END", "dependsOn": [ "undo" ], "config": {} } ] }})), '10');
// Step 3state = reduce(state, parseCommand(JSON.stringify({ "type": "attachGraph", "runId": "r", "graphId": "graph"})), '10');
// Step 4state = reduce(state, parseCommand(JSON.stringify({ "type": "grant", "grant": { "id": "g", "subject": "agent", "profile": "finite-v1", "actions": [ "write" ], "resources": [ "doc" ], "notBefore": "0", "expiresAt": "10000", "limit": "100", "canDelegate": true, "depth": "2" }})), '10');
// Step 5state = reduce(state, parseCommand(JSON.stringify({ "type": "admit", "runId": "r", "operationId": "o", "attemptId": "a", "grantId": "g", "subject": "agent", "action": { "capability": "write", "resource": "doc", "payload": { "value": 1 }, "preconditions": { "revision": 1 } }, "amount": "10", "authorizationCheckedAt": "10", "policy": "ALLOW", "mandatoryChecksOk": true})), '10');
// Step 6state = reduce(state, parseCommand(JSON.stringify({ "type": "dispatch", "attemptId": "a", "authorizationCheckedAt": "10", "policy": "ALLOW", "mandatoryChecksOk": true, "nodeId": "task"})), '10');
// Step 7state = reduce(state, parseCommand(JSON.stringify({ "type": "settle", "attemptId": "a", "effect": "CONFIRMED_APPLIED", "actualCost": "3"})), '10');
// Step 8state = reduce(state, parseCommand(JSON.stringify({ "type": "completeNode", "runId": "r", "nodeId": "task", "result": { "operationId": "o" }})), '10');
// Step 9state = reduce(state, parseCommand(JSON.stringify({ "type": "completeNode", "runId": "r", "nodeId": "reconcile", "result": { "operationId": "o" }})), '10');
// Step 10state = reduce(state, parseCommand(JSON.stringify({ "type": "admit", "runId": "r", "operationId": "undo", "attemptId": "au", "grantId": "g", "subject": "agent", "action": { "capability": "write", "resource": "doc", "payload": { "value": 1 }, "preconditions": { "revision": 1 } }, "amount": "10", "authorizationCheckedAt": "10", "policy": "ALLOW", "mandatoryChecksOk": true})), '10');
// Step 11state = reduce(state, parseCommand(JSON.stringify({ "type": "dispatch", "attemptId": "au", "authorizationCheckedAt": "10", "policy": "ALLOW", "mandatoryChecksOk": true, "nodeId": "undo"})), '10');
// Step 12state = reduce(state, parseCommand(JSON.stringify({ "type": "settle", "attemptId": "au", "effect": "CONFIRMED_APPLIED", "actualCost": "2"})), '10');
// Step 13state = reduce(state, parseCommand(JSON.stringify({ "type": "completeNode", "runId": "r", "nodeId": "undo", "result": { "operationId": "undo", "originalOperationId": "o" }})), '10');console.log('PASS: compensation');use aiws_sdk::*;use serde_json::json;
fn main() -> Result<()> { // Trusted simulation: no external calls. let contract = Contract::parse(&json!({ "id": "c", "missionId": "m", "aiwsEdition": "0.4", "profile": "finite-v1", "budget": "100", "deadline": "10000", "criteria": [ "review" ], "actions": [ "write" ], "resources": [ "doc" ], "requiresApproval": false, "maxAttempts": "2", "maxAuthorizationAgeMs": "10", "features": [ "triggers", "graphs" ]}).to_string())?; let mut state = create_mission(&contract)?;
// Step 1 state = reduce(&state, &Command::from_value(json!({ "type": "startRun", "runId": "r"}))?, "10")?;
// Step 2 state = reduce(&state, &Command::from_value(json!({ "type": "registerGraph", "graph": { "id": "graph", "revision": "1", "nodes": [ { "id": "task", "kind": "TASK", "dependsOn": [], "config": { "executionKind": "FUNCTION" } }, { "id": "reconcile", "kind": "RECONCILIATION", "dependsOn": [ "task" ], "config": {} }, { "id": "undo", "kind": "COMPENSATION", "dependsOn": [ "reconcile" ], "config": {} }, { "id": "end", "kind": "END", "dependsOn": [ "undo" ], "config": {} } ] }}))?, "10")?;
// Step 3 state = reduce(&state, &Command::from_value(json!({ "type": "attachGraph", "runId": "r", "graphId": "graph"}))?, "10")?;
// Step 4 state = reduce(&state, &Command::from_value(json!({ "type": "grant", "grant": { "id": "g", "subject": "agent", "profile": "finite-v1", "actions": [ "write" ], "resources": [ "doc" ], "notBefore": "0", "expiresAt": "10000", "limit": "100", "canDelegate": true, "depth": "2" }}))?, "10")?;
// Step 5 state = reduce(&state, &Command::from_value(json!({ "type": "admit", "runId": "r", "operationId": "o", "attemptId": "a", "grantId": "g", "subject": "agent", "action": { "capability": "write", "resource": "doc", "payload": { "value": 1 }, "preconditions": { "revision": 1 } }, "amount": "10", "authorizationCheckedAt": "10", "policy": "ALLOW", "mandatoryChecksOk": true}))?, "10")?;
// Step 6 state = reduce(&state, &Command::from_value(json!({ "type": "dispatch", "attemptId": "a", "authorizationCheckedAt": "10", "policy": "ALLOW", "mandatoryChecksOk": true, "nodeId": "task"}))?, "10")?;
// Step 7 state = reduce(&state, &Command::from_value(json!({ "type": "settle", "attemptId": "a", "effect": "CONFIRMED_APPLIED", "actualCost": "3"}))?, "10")?;
// Step 8 state = reduce(&state, &Command::from_value(json!({ "type": "completeNode", "runId": "r", "nodeId": "task", "result": { "operationId": "o" }}))?, "10")?;
// Step 9 state = reduce(&state, &Command::from_value(json!({ "type": "completeNode", "runId": "r", "nodeId": "reconcile", "result": { "operationId": "o" }}))?, "10")?;
// Step 10 state = reduce(&state, &Command::from_value(json!({ "type": "admit", "runId": "r", "operationId": "undo", "attemptId": "au", "grantId": "g", "subject": "agent", "action": { "capability": "write", "resource": "doc", "payload": { "value": 1 }, "preconditions": { "revision": 1 } }, "amount": "10", "authorizationCheckedAt": "10", "policy": "ALLOW", "mandatoryChecksOk": true}))?, "10")?;
// Step 11 state = reduce(&state, &Command::from_value(json!({ "type": "dispatch", "attemptId": "au", "authorizationCheckedAt": "10", "policy": "ALLOW", "mandatoryChecksOk": true, "nodeId": "undo"}))?, "10")?;
// Step 12 state = reduce(&state, &Command::from_value(json!({ "type": "settle", "attemptId": "au", "effect": "CONFIRMED_APPLIED", "actualCost": "2"}))?, "10")?;
// Step 13 state = reduce(&state, &Command::from_value(json!({ "type": "completeNode", "runId": "r", "nodeId": "undo", "result": { "operationId": "undo", "originalOperationId": "o" }}))?, "10")?; println!("PASS: compensation"); Ok(())}import jsonfrom aiws import create_mission, parse_contract, reduce, AiwsError
# Trusted simulation: this example makes no external calls.contract = parse_contract(json.dumps({'id': 'c', 'missionId': 'm', 'aiwsEdition': '0.4', 'profile': 'finite-v1', 'budget': '100', 'deadline': '10000', 'criteria': ['review'], 'actions': ['write'], 'resources': ['doc'], 'requiresApproval': False, 'maxAttempts': '2', 'maxAuthorizationAgeMs': '10', 'features': ['triggers', 'graphs']}))state = create_mission(contract)
# Step 1state = reduce(state, {'type': 'startRun', 'runId': 'r'}, '10')
# Step 2state = reduce(state, {'type': 'registerGraph', 'graph': {'id': 'graph', 'revision': '1', 'nodes': [{'id': 'task', 'kind': 'TASK', 'dependsOn': [], 'config': {'executionKind': 'FUNCTION'}}, {'id': 'reconcile', 'kind': 'RECONCILIATION', 'dependsOn': ['task'], 'config': {}}, {'id': 'undo', 'kind': 'COMPENSATION', 'dependsOn': ['reconcile'], 'config': {}}, {'id': 'end', 'kind': 'END', 'dependsOn': ['undo'], 'config': {}}]}}, '10')
# Step 3state = reduce(state, {'type': 'attachGraph', 'runId': 'r', 'graphId': 'graph'}, '10')
# Step 4state = reduce(state, {'type': 'grant', 'grant': {'id': 'g', 'subject': 'agent', 'profile': 'finite-v1', 'actions': ['write'], 'resources': ['doc'], 'notBefore': '0', 'expiresAt': '10000', 'limit': '100', 'canDelegate': True, 'depth': '2'}}, '10')
# Step 5state = reduce(state, {'type': 'admit', 'runId': 'r', 'operationId': 'o', 'attemptId': 'a', 'grantId': 'g', 'subject': 'agent', 'action': {'capability': 'write', 'resource': 'doc', 'payload': {'value': 1}, 'preconditions': {'revision': 1}}, 'amount': '10', 'authorizationCheckedAt': '10', 'policy': 'ALLOW', 'mandatoryChecksOk': True}, '10')
# Step 6state = reduce(state, {'type': 'dispatch', 'attemptId': 'a', 'authorizationCheckedAt': '10', 'policy': 'ALLOW', 'mandatoryChecksOk': True, 'nodeId': 'task'}, '10')
# Step 7state = reduce(state, {'type': 'settle', 'attemptId': 'a', 'effect': 'CONFIRMED_APPLIED', 'actualCost': '3'}, '10')
# Step 8state = reduce(state, {'type': 'completeNode', 'runId': 'r', 'nodeId': 'task', 'result': {'operationId': 'o'}}, '10')
# Step 9state = reduce(state, {'type': 'completeNode', 'runId': 'r', 'nodeId': 'reconcile', 'result': {'operationId': 'o'}}, '10')
# Step 10state = reduce(state, {'type': 'admit', 'runId': 'r', 'operationId': 'undo', 'attemptId': 'au', 'grantId': 'g', 'subject': 'agent', 'action': {'capability': 'write', 'resource': 'doc', 'payload': {'value': 1}, 'preconditions': {'revision': 1}}, 'amount': '10', 'authorizationCheckedAt': '10', 'policy': 'ALLOW', 'mandatoryChecksOk': True}, '10')
# Step 11state = reduce(state, {'type': 'dispatch', 'attemptId': 'au', 'authorizationCheckedAt': '10', 'policy': 'ALLOW', 'mandatoryChecksOk': True, 'nodeId': 'undo'}, '10')
# Step 12state = reduce(state, {'type': 'settle', 'attemptId': 'au', 'effect': 'CONFIRMED_APPLIED', 'actualCost': '2'}, '10')
# Step 13state = reduce(state, {'type': 'completeNode', 'runId': 'r', 'nodeId': 'undo', 'result': {'operationId': 'undo', 'originalOperationId': 'o'}}, '10')print('PASS: compensation')The example exercises current checkpoint semantics. It is not an automatic rollback manager. Your application chooses and authorizes a compensating adapter and must handle uncertainty or failure in that operation too.