rusty_agent_runtime/effects.rs
1//! Effect kernel v2 (R0.7): retry-safety moves from runtime convention into
2//! the type system.
3//!
4//! R0.5 froze the [`Effect`] taxonomy as a wire contract and R0.6 made it a
5//! runtime convention — [`crate::durable::classify_retry`] refuses to silently
6//! retry anything that is not [`Effect::is_freely_repeatable`]. That gate is a
7//! function call away from being ignored: nothing in the type of a node,
8//! tool, or durable task says what its failure modes are. This module adds
9//! the compile-time half. An effect type declares its safety class by
10//! implementing one of the marker traits below; generic infrastructure (a
11//! retry loop, a speculator, the R0.7 race pattern) can then *require* a
12//! class at the type level instead of re-checking a convention at runtime.
13//!
14//! The marker traits **compose with** the wire enum, they do not replace it:
15//! [`Effect`] stays the serde/golden-pinned contract journals and envelopes
16//! are written in; the typed kernel is the in-process API that enforcement
17//! points are built from. The mapping is one-to-one, with one deliberate
18//! naming reconciliation:
19//!
20//! | Marker trait | Wire [`Effect`] | What the class unlocks |
21//! |-------------------------|-------------------|------------------------|
22//! | [`PureEffect`] | `Pure` | caching, speculation, unrestricted retry |
23//! | [`ReadOnlyEffect`] | `ReadOnly` | unrestricted retry; replay serves the journaled value |
24//! | [`IdempotentEffect`] | `Idempotent` | automatic retry under a stable idempotency key |
25//! | [`CompensatableEffect`] | `Compensatable` | execution only with a registered rollback handler |
26//! | [`IrreversibleEffect`] | `NonIdempotent` | execution only behind an explicit [`ApprovalToken`] |
27//!
28//! The 2026-08-08 review names the last rung *Irreversible*; the wire enum
29//! calls it `NonIdempotent`. We keep the wire name for two reasons: the
30//! enum's serde shape is golden-pinned evidence (an additive rename would
31//! churn every journal for zero semantic gain), and `NonIdempotent` states
32//! what the runtime can actually *verify* — the absence of a declared
33//! idempotency story — whereas irreversibility is a claim about the world it
34//! cannot check. The typed API adopts the review's vocabulary
35//! ([`IrreversibleEffect`]) because that is the word that makes the approval
36//! boundary legible at a call site; the two names denote one class.
37//!
38//! Two further mechanisms close the loop with the R0.6 receipt ledger:
39//!
40//! - **Deterministic effect ids** ([`derive_effect_id`], [`EffectId`]) — a
41//! content-addressed identity derived from the run scope, the effect kind,
42//! the input hash, and the idempotency key. On recovery the runtime asks
43//! "did this exact effect already commit?" and the journal answers through
44//! [`crate::journal::JournalSnapshot::find_effect_receipt_by_effect_id`].
45//! - **The approval boundary** ([`ApprovalToken`], [`admit_irreversible`]) —
46//! an irreversible effect executes only when presented with a token scoped
47//! to its derived effect id. The token is a proof-of-explicit-decision
48//! *within the process*: it makes approval a value that must be
49//! constructed, not a boolean that can be silently defaulted. Cross-process
50//! attestation of approvals is R0.9's signed-receipt work.
51//!
52//! Runtime enforcement is opt-in: enabling effect admission on an executor
53//! propagates a scoped [`EffectAdmissionContext`] through
54//! [`crate::node::NodeContext`]. The prebuilt ReAct tools node carries it into
55//! [`crate::tool::ToolExecutor`] automatically; custom nodes must do the same
56//! when they construct a tool executor. Calls on that guarded path are
57//! admitted after middleware has finalized their name and arguments but
58//! before the tool body runs. Direct calls to [`crate::tool::Tool::call`] are
59//! outside this cooperative boundary. Executors that do not enable it keep
60//! the pre-R0.7 behavior, so existing graphs remain source-compatible.
61
62use std::collections::BTreeMap;
63use std::sync::{Arc, Mutex};
64
65use serde::{Deserialize, Serialize};
66use serde_json::Value;
67use thiserror::Error;
68
69use crate::record::{sha256_hex, Effect};
70
71/// Domain-separation and versioning prefix for [`derive_effect_id`].
72///
73/// Effect ids are content addresses; the prefix keeps them collision-free
74/// against every other SHA-256 digest in the system (artifact references,
75/// journal heads, topology hashes) and gives the derivation formula an
76/// explicit version handle if it ever needs to change.
77pub const EFFECT_ID_DOMAIN: &str = "rusty/effect-id/v1";
78
79/// A deterministic, content-addressed identity for one logical effect
80/// within a run scope.
81///
82/// Derived — never minted — by [`derive_effect_id`]: the same `(scope, kind,
83/// input hash, idempotency key)` tuple always yields the same id, so a
84/// recovered run re-derives the id of the effect it was about to perform and
85/// asks the journal whether a receipt already exists for it. That lookup is
86/// what turns "retry carefully" into "do not re-execute what already
87/// committed" — exactly-once *business outcomes* where the effect protocol
88/// supports it, never a pretend exactly-once execution.
89///
90/// Transparent newtype over the lowercase hex digest: serializes as a bare
91/// string, consistent with [`crate::record::ArtifactRef`].
92#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
93#[serde(transparent)]
94pub struct EffectId(String);
95
96impl EffectId {
97 /// The hex digest.
98 pub fn as_str(&self) -> &str {
99 &self.0
100 }
101}
102
103impl std::fmt::Display for EffectId {
104 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105 f.write_str(&self.0)
106 }
107}
108
109/// Derive the deterministic id of an effect occurrence.
110///
111/// The formula is `SHA-256` over the newline-joined, domain-prefixed tuple:
112///
113/// ```text
114/// EFFECT_ID_DOMAIN "\n" scope "\n" kind "\n" input_hash "\n" (idempotency_key | "-")
115/// ```
116///
117/// - `scope` is the run (or sub-run) identity the effect belongs to — two
118/// runs performing the same call get different ids, so a receipt from one
119/// run can never masquerade as another's.
120/// - `kind` is the effect type's stable identifier ([`TypedEffect::kind`]).
121/// - `input_hash` is the lowercase hex SHA-256 of the canonical input (the
122/// same canonical `serde_json` serialization [`crate::record::PayloadRef::content_hash`]
123/// uses), precomputed by the caller so this function stays IO-free.
124/// - `idempotency_key` distinguishes intentional replays under one key from
125/// distinct effects that happen to share an input; `-` fills the slot when
126/// the effect has no key, so keyed and unkeyed derivations can never
127/// collide.
128///
129/// Newline-joining (rather than concatenation) keeps the tuple unambiguous
130/// without a length prefix — the same framing [`crate::graph::Graph::topology_hash`]
131/// uses for topology lines.
132pub fn derive_effect_id(
133 scope: &str,
134 kind: &str,
135 input_hash: &str,
136 idempotency_key: Option<&str>,
137) -> EffectId {
138 let material = [
139 EFFECT_ID_DOMAIN,
140 scope,
141 kind,
142 input_hash,
143 idempotency_key.unwrap_or("-"),
144 ]
145 .join("\n");
146 EffectId(sha256_hex(material.as_bytes()))
147}
148
149/// The runtime description of one effect occurrence awaiting admission.
150///
151/// [`TypedEffect`] is the compile-time declaration surface; this value is its
152/// object-safe dispatch counterpart. A [`crate::tool::Tool`] produces one for
153/// each call after middleware has finalized the call. Its input hash is
154/// computed with the same canonical JSON convention as journal payloads, so
155/// approval tokens derived before execution match the id the dispatcher
156/// re-derives at the boundary.
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub struct EffectRequest {
159 kind: String,
160 effect: Effect,
161 input_hash: String,
162 idempotency_key: Option<String>,
163}
164
165impl EffectRequest {
166 /// Describe an effect over canonical JSON `input`.
167 pub fn new(
168 kind: impl Into<String>,
169 effect: Effect,
170 input: &Value,
171 idempotency_key: Option<String>,
172 ) -> Self {
173 let input_hash = crate::record::PayloadRef::inline(input.clone())
174 .content_hash()
175 .expect("a serde_json::Value always serializes");
176 Self {
177 kind: kind.into(),
178 effect,
179 input_hash,
180 idempotency_key,
181 }
182 }
183
184 /// Bridge a typed declaration into the runtime admission surface.
185 pub fn from_typed<E: TypedEffect>(effect: &E) -> Self {
186 Self {
187 kind: effect.kind().to_owned(),
188 effect: E::EFFECT,
189 input_hash: effect.input_hash().to_owned(),
190 idempotency_key: effect.idempotency_key().map(str::to_owned),
191 }
192 }
193
194 /// Stable application-defined effect kind.
195 pub fn kind(&self) -> &str {
196 &self.kind
197 }
198
199 /// Wire-level safety class recorded for this occurrence.
200 pub fn effect(&self) -> Effect {
201 self.effect
202 }
203
204 /// Canonical input digest used in the deterministic effect id.
205 pub fn input_hash(&self) -> &str {
206 &self.input_hash
207 }
208
209 /// Stable idempotency key, when the declaration requires one.
210 pub fn idempotency_key(&self) -> Option<&str> {
211 self.idempotency_key.as_deref()
212 }
213
214 /// This occurrence's deterministic id in `scope`.
215 pub fn effect_id(&self, scope: &str) -> EffectId {
216 derive_effect_id(
217 scope,
218 self.kind(),
219 self.input_hash(),
220 self.idempotency_key(),
221 )
222 }
223}
224
225/// The typed half of the effect taxonomy: an effect type's contract with the
226/// kernel.
227///
228/// Implement this trait plus exactly one marker trait ([`PureEffect`],
229/// [`ReadOnlyEffect`], [`IdempotentEffect`], [`CompensatableEffect`],
230/// [`IrreversibleEffect`]) to declare an effect's safety class. The marker is
231/// the compile-time claim; [`TypedEffect::EFFECT`] is the wire-level class it
232/// must agree with — every admission helper checks the two against each
233/// other, so a type whose marker and declared class disagree is rejected at
234/// the enforcement point, not silently misclassified.
235pub trait TypedEffect {
236 /// The wire-level [`Effect`] class this type records in journals and
237 /// envelopes. Must agree with the marker trait the type implements (see
238 /// the module-level mapping table); the admission helpers enforce the
239 /// agreement.
240 const EFFECT: Effect;
241
242 /// The effect kind: a stable, application-chosen identifier
243 /// (`"charge_card"`, `"index_document"`). Part of the effect id and the
244 /// key under which rollback handlers are registered, so it must not
245 /// change between deployments that share a journal.
246 fn kind(&self) -> &str;
247
248 /// Lowercase hex SHA-256 of the effect's canonical input. Two calls with
249 /// equal inputs must hash equal — use the canonical `serde_json`
250 /// serialization, as [`crate::record::PayloadRef::content_hash`] does.
251 fn input_hash(&self) -> &str;
252
253 /// The idempotency key the effect commits under, when it has one. The
254 /// key participates in the effect id, so retried derivation under the
255 /// same key converges on the id a recovery pass looks up. `None` is
256 /// honest only for effects that are freely repeatable without a key.
257 fn idempotency_key(&self) -> Option<&str> {
258 None
259 }
260
261 /// This effect's deterministic id within `scope` (usually the run id) —
262 /// [`derive_effect_id`] over the type's own contract fields.
263 fn effect_id(&self, scope: &str) -> EffectId {
264 derive_effect_id(
265 scope,
266 self.kind(),
267 self.input_hash(),
268 self.idempotency_key(),
269 )
270 }
271}
272
273/// Marker: a pure function of its inputs with no observable effect beyond
274/// its return value (wire class [`Effect::Pure`]).
275///
276/// Pure work may be cached, memoized, and speculated freely: re-execution is
277/// always safe and always equivalent, so a speculative result and an
278/// on-demand result are indistinguishable. Declare it by implementing this
279/// trait; [`admit_speculation`] is the enforcement point speculators call.
280pub trait PureEffect: TypedEffect {}
281
282/// Marker: reads external state but writes nothing (wire class
283/// [`Effect::ReadOnly`]).
284///
285/// Re-execution is safe but not necessarily equivalent — the world may have
286/// changed — so exact replay serves the journaled value while live replay
287/// re-reads. Retries are unconstrained, which is why there is no admission
288/// helper for this class: nothing needs gating.
289pub trait ReadOnlyEffect: TypedEffect {}
290
291/// Marker: repeating the call under the same idempotency key has the same
292/// effect as calling once (wire class [`Effect::Idempotent`]).
293///
294/// This is the class that unlocks automatic retry — the typed form of the
295/// gate [`crate::durable::classify_retry`] applies to the untyped enum.
296/// [`admit_retry`] additionally requires the key itself: retrying an
297/// "idempotent" effect with no key is the exact unsoundness the taxonomy
298/// exists to prevent, and the helper refuses it.
299pub trait IdempotentEffect: TypedEffect {}
300
301/// Marker: repeating the call duplicates the effect, but a declared
302/// compensating action can logically undo it — charge/refund (wire class
303/// [`Effect::Compensatable`]).
304///
305/// The compensation is not optional coloring: [`admit_compensatable`]
306/// requires a rollback handler registered for the effect's kind before the
307/// effect may execute, and returns that handler so the caller holds the undo
308/// path from the start. Automatic compensation remains out of scope
309/// (unchanged from R0.6: `Compensatable` fails closed in the untyped retry
310/// path) — the handler is invoked by policy, not by the kernel.
311pub trait CompensatableEffect: TypedEffect {}
312
313/// Marker: no safe automatic repetition and no logical undo — send the
314/// email, fire the charge without a key (wire class [`Effect::NonIdempotent`];
315/// see the module docs for the deliberate naming reconciliation).
316///
317/// Execution requires an explicit [`ApprovalToken`] scoped to the effect's
318/// derived id, presented to [`admit_irreversible`]. Unknown or undeclared
319/// effects belong here by default: the wire enum already defaults to
320/// `NonIdempotent`, and the typed kernel keeps that convention — what is not
321/// declared is never silently retried and never executes without approval.
322pub trait IrreversibleEffect: TypedEffect {}
323
324/// Why the kernel refused an admission decision.
325///
326/// A dedicated error type (not [`crate::error::RustyError`]) because these
327/// are contract violations surfaced by the typed API, not runtime execution
328/// failures; the executor maps them into its own error path when the
329/// enforcement wave lands.
330#[derive(Debug, Clone, PartialEq, Eq, Error)]
331pub enum EffectViolation {
332 /// The marker trait and [`TypedEffect::EFFECT`] disagree — a type-level
333 /// bug, caught at the enforcement point rather than trusted.
334 #[error(
335 "effect kind `{kind}` is marked with the {marker:?} marker trait but declares \
336 {declared:?}: the marker and TypedEffect::EFFECT must agree"
337 )]
338 DeclarationMismatch {
339 /// The effect's kind identifier.
340 kind: String,
341 /// The wire class the marker trait implies.
342 marker: Effect,
343 /// The wire class the type actually declared.
344 declared: Effect,
345 },
346
347 /// An [`IdempotentEffect`] presented for retry admission without the
348 /// idempotency key the declaration is meaningless without.
349 #[error(
350 "idempotent effect kind `{kind}` has no idempotency key: a stable key is what the \
351 idempotency declaration means at the wire"
352 )]
353 MissingIdempotencyKey {
354 /// The effect's kind identifier.
355 kind: String,
356 },
357
358 /// A [`CompensatableEffect`] with no rollback handler registered for its
359 /// kind.
360 #[error(
361 "compensatable effect kind `{kind}` has no registered rollback handler: register one \
362 in a CompensationRegistry before executing it"
363 )]
364 MissingCompensation {
365 /// The effect's kind identifier.
366 kind: String,
367 },
368
369 /// An [`IrreversibleEffect`] presented for execution with no approval
370 /// token at all.
371 #[error(
372 "irreversible effect kind `{kind}` ({effect_id}) requires an explicit approval token \
373 scoped to its effect id"
374 )]
375 MissingApproval {
376 /// The effect's kind identifier.
377 kind: String,
378 /// The effect id the approval must be scoped to.
379 effect_id: EffectId,
380 },
381
382 /// A token was presented, but it approves a different effect id — an
383 /// approval is scoped to exactly one effect occurrence and is not
384 /// transferable.
385 #[error(
386 "approval token for {presented} does not admit irreversible effect kind `{kind}` \
387 ({required})"
388 )]
389 ApprovalScopeMismatch {
390 /// The effect's kind identifier.
391 kind: String,
392 /// The effect id the admission requires.
393 required: EffectId,
394 /// The effect id the presented token approves.
395 presented: EffectId,
396 },
397
398 /// An effect above [`Effect::ReadOnly`] was attempted under a shadow
399 /// admission context (R0.12 Operations Plane, wave 4). The shadow's
400 /// whole promise is that the candidate's effects never reach the
401 /// world, and "idempotent" means safe to retry under one key — not
402 /// safe to execute twice from two revisions — so `Idempotent` is
403 /// refused alongside the classes above it. The violation carries the
404 /// classification and the derived id because it is evidence, not a
405 /// stack trace: the shadow's report shows which effects the candidate
406 /// would have attempted, classified, never executed.
407 #[error(
408 "shadow admission refused {effect:?} effect kind `{kind}` ({effect_id}): a shadow \
409 admits Pure and ReadOnly effects only — the candidate's effects never reach the world"
410 )]
411 ShadowRefused {
412 /// The effect's kind identifier.
413 kind: String,
414 /// The wire-level safety class the shadow refused.
415 effect: Effect,
416 /// The effect id the occurrence derived.
417 effect_id: EffectId,
418 },
419}
420
421/// An explicit, scoped approval to execute one irreversible effect
422/// occurrence.
423///
424/// The token is the approval *boundary made into a value*: constructing one
425/// is the decision, and [`admit_irreversible`] accepts it only for the exact
426/// [`EffectId`] it was minted against, so an approval for one charge cannot
427/// launder another. Within a process this is a proof of explicit decision —
428/// it cannot stop code that is determined to forge one, and it is not meant
429/// to; cross-process attestation is R0.9's signed-receipt work. What it does
430/// guarantee is structural: there is no code path through the typed kernel
431/// that executes an irreversible effect on a defaulted or forgotten
432/// approval.
433///
434/// Tokens ride the run via [`crate::executor::RunConfig::with_effect_approvals`]
435/// so the approval set travels with the run's configuration.
436#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
437pub struct ApprovalToken {
438 /// The effect occurrence this token approves.
439 effect_id: EffectId,
440
441 /// Who approved — a human operator id, a policy name, a supervision
442 /// decision reference. Evidence, not authentication: recorded so the
443 /// journal can attribute the boundary when approval journaling lands.
444 approved_by: String,
445}
446
447impl ApprovalToken {
448 /// Mint an approval for exactly one effect id. This constructor is the
449 /// approval act: call sites should read as decisions (`let approval =
450 /// ApprovalToken::approve(id, "ops:amjad")`), not as plumbing.
451 pub fn approve(effect_id: EffectId, approved_by: impl Into<String>) -> Self {
452 Self {
453 effect_id,
454 approved_by: approved_by.into(),
455 }
456 }
457
458 /// Mint an approval scoped to `effect`'s derived id within `scope` — the
459 /// common case, approving the occurrence a run is about to execute.
460 pub fn for_effect<E: IrreversibleEffect>(
461 effect: &E,
462 scope: &str,
463 approved_by: impl Into<String>,
464 ) -> Self {
465 Self::approve(effect.effect_id(scope), approved_by)
466 }
467
468 /// The effect id this token approves.
469 pub fn effect_id(&self) -> &EffectId {
470 &self.effect_id
471 }
472
473 /// Who approved.
474 pub fn approved_by(&self) -> &str {
475 &self.approved_by
476 }
477
478 /// Whether this token admits `effect_id`. Scoped, not transferable: only
479 /// the exact occurrence it was minted against.
480 pub fn admits(&self, effect_id: &EffectId) -> bool {
481 &self.effect_id == effect_id
482 }
483}
484
485/// A registered rollback handler for a [`CompensatableEffect`] kind.
486///
487/// The handler receives the journaled output of the effect occurrence to
488/// undo and returns a compensation record (what was done to undo it) for
489/// journaling. Errors are plain strings because compensation failures cross
490/// the retry taxonomy's string-classified boundary — a failed compensation
491/// is an operator signal, classified and surfaced, never silently retried by
492/// the kernel (automatic compensation stays out of scope, as in R0.6).
493///
494/// `Arc`-wrapped so an admission can hand the caller a cheap clone of the
495/// registered undo path.
496pub type CompensationHandler = Arc<dyn Fn(&Value) -> Result<Value, String> + Send + Sync>;
497
498/// The registry of rollback handlers backing [`admit_compensatable`].
499///
500/// Registration is the mechanism that makes a `Compensatable` declaration
501/// meaningful: the handler for an effect kind must exist *before* the effect
502/// executes, so the undo path is a precondition, not a postmortem. Handlers
503/// are keyed by [`TypedEffect::kind`]; re-registering a kind replaces its
504/// handler (and returns the old one) so deployments can evolve compensation
505/// logic deliberately.
506#[derive(Default, Clone)]
507pub struct CompensationRegistry {
508 handlers: BTreeMap<String, CompensationHandler>,
509}
510
511impl std::fmt::Debug for CompensationRegistry {
512 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
513 // Handlers are opaque closures; the registered kinds are the useful
514 // debug surface.
515 f.debug_set().entries(self.handlers.keys()).finish()
516 }
517}
518
519impl CompensationRegistry {
520 /// An empty registry: every `Compensatable` admission fails until a
521 /// handler is registered — the fail-closed default.
522 pub fn new() -> Self {
523 Self::default()
524 }
525
526 /// Register `handler` as the rollback path for `kind`, returning the
527 /// handler it replaced, if any.
528 pub fn register(
529 &mut self,
530 kind: impl Into<String>,
531 handler: CompensationHandler,
532 ) -> Option<CompensationHandler> {
533 self.handlers.insert(kind.into(), handler)
534 }
535
536 /// The handler registered for `kind`, if any.
537 pub fn handler_for(&self, kind: &str) -> Option<&CompensationHandler> {
538 self.handlers.get(kind)
539 }
540}
541
542/// One shadow refusal, structured for journaling (R0.12 wave 4): the
543/// effect the candidate would have attempted, classified, with the
544/// recorded-outcome disposition. The shadow's report is built from these
545/// — which effects it refused, and which of them the source run's journal
546/// could answer for.
547#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
548pub struct ShadowRefusal {
549 /// The refused effect's kind identifier.
550 pub kind: String,
551
552 /// The wire-level safety class the shadow refused.
553 pub effect: Effect,
554
555 /// The effect id the occurrence derived in the shadow's scope.
556 pub effect_id: EffectId,
557
558 /// The canonical input digest of the refused call.
559 pub input_hash: String,
560
561 /// Whether the recorded world answered for the refused effect: the
562 /// source run's journal held a matching outcome, and the shadow
563 /// served it (the hybrid-replay rule — pin the effect, re-run the
564 /// decision). `false` means the candidate diverged from the
565 /// recording at this call: the journal has no answer to a call the
566 /// recorded world never received.
567 pub served: bool,
568}
569
570/// The recorded world a shadow serves refused effects from (R0.12
571/// wave 4). Implemented over a source run's journal
572/// ([`crate::replay::JournalShadowSource`]); the kernel owns the
573/// boundary, the journal owns the evidence.
574///
575/// `recorded_request` is the request payload in the *recorded* shape the
576/// journal holds (for tools, [`crate::replay::tool_call_request`]) — the
577/// caller builds it from the live call so the source can match name and
578/// arguments, not merely the effect kind.
579pub trait ShadowOutcomeSource: Send + Sync + std::fmt::Debug {
580 /// The recorded outcome of one refused call, when the source run
581 /// recorded it. `None` is a divergence, not an error: the candidate
582 /// attempted something the recorded world never saw.
583 fn serve(&self, kind: &str, recorded_request: &Value) -> Option<Value>;
584}
585
586/// Where a shadow's refusals go the moment they happen: the shadow run's
587/// own journal, in the server's construction. A refusal the shadow did
588/// not record is a refusal that can be retroactively denied.
589pub type ShadowRefusalSink = Arc<dyn Fn(&ShadowRefusal) + Send + Sync>;
590
591/// A run-scoped, fail-closed admission boundary for runtime effect requests.
592///
593/// The scope is normally a thread id. Approvals are indexed by their exact
594/// deterministic [`EffectId`], and compensations are captured when a request
595/// is admitted so the rollback path remains alive for the entire call.
596///
597/// A context built by [`EffectAdmissionContext::shadow`] is the R0.12
598/// shadow boundary: it admits [`Effect::Pure`] and [`Effect::ReadOnly`]
599/// and refuses everything above — `Idempotent` included, because
600/// "idempotent" means safe to retry under one key, not safe to execute
601/// twice from two revisions, and a shadowed charge is a charge. The
602/// shadow holds no approval tokens to consume and no retry path around
603/// the refusal: there is no code path through a shadow context that
604/// executes an effect above `ReadOnly`.
605#[derive(Clone)]
606pub struct EffectAdmissionContext {
607 scope: String,
608 approvals: Arc<Mutex<BTreeMap<EffectId, ApprovalToken>>>,
609 compensations: CompensationRegistry,
610 /// Present only for shadow contexts: the recorded world refused
611 /// effects are served from, and the sink refusals report to.
612 shadow: Option<ShadowBoundary>,
613}
614
615/// The shadow half of an [`EffectAdmissionContext`], cloned cheaply.
616#[derive(Clone)]
617struct ShadowBoundary {
618 source: Arc<dyn ShadowOutcomeSource>,
619 sink: ShadowRefusalSink,
620}
621
622impl std::fmt::Debug for EffectAdmissionContext {
623 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
624 let approvals = self.approvals.lock().unwrap_or_else(|e| e.into_inner());
625 f.debug_struct("EffectAdmissionContext")
626 .field("scope", &self.scope)
627 .field("approval_effect_ids", &approvals.keys())
628 .field("compensations", &self.compensations)
629 .field("shadow", &self.shadow.is_some())
630 .finish()
631 }
632}
633
634impl EffectAdmissionContext {
635 /// Start an admission boundary for `scope` with no approvals or rollback
636 /// handlers. This is intentionally fail-closed for compensatable and
637 /// irreversible effects.
638 pub fn new(scope: impl Into<String>) -> Self {
639 Self {
640 scope: scope.into(),
641 approvals: Arc::new(Mutex::new(BTreeMap::new())),
642 compensations: CompensationRegistry::new(),
643 shadow: None,
644 }
645 }
646
647 /// Start a shadow admission boundary for `scope` (R0.12 wave 4):
648 /// admits `Pure` and `ReadOnly`, refuses everything above with
649 /// [`EffectViolation::ShadowRefused`]. `source` is the recorded world
650 /// refused effects are served from; `sink` receives every refusal the
651 /// moment it happens, served or not — the refusal is the shadow's
652 /// primary evidence.
653 pub fn shadow(
654 scope: impl Into<String>,
655 source: Arc<dyn ShadowOutcomeSource>,
656 sink: ShadowRefusalSink,
657 ) -> Self {
658 Self {
659 scope: scope.into(),
660 approvals: Arc::new(Mutex::new(BTreeMap::new())),
661 compensations: CompensationRegistry::new(),
662 shadow: Some(ShadowBoundary { source, sink }),
663 }
664 }
665
666 /// Attach the exact approval tokens available to this run.
667 pub fn with_approvals(mut self, approvals: impl IntoIterator<Item = ApprovalToken>) -> Self {
668 self.approvals = Arc::new(Mutex::new(
669 approvals
670 .into_iter()
671 .map(|token| (token.effect_id().clone(), token))
672 .collect(),
673 ));
674 self
675 }
676
677 /// Attach the run's registered rollback handlers.
678 pub fn with_compensations(mut self, compensations: CompensationRegistry) -> Self {
679 self.compensations = compensations;
680 self
681 }
682
683 /// The run scope used to derive effect ids.
684 pub fn scope(&self) -> &str {
685 &self.scope
686 }
687
688 /// Whether this is a shadow boundary (built by
689 /// [`EffectAdmissionContext::shadow`]).
690 pub fn is_shadow(&self) -> bool {
691 self.shadow.is_some()
692 }
693
694 /// Admit one effect occurrence, or reject it before its body runs.
695 ///
696 /// Pure and read-only calls require no additional evidence. Idempotent
697 /// calls require a stable key, compensatable calls require a registered
698 /// rollback handler, and non-idempotent calls atomically consume an
699 /// approval token for this exact content-addressed occurrence. Cloned
700 /// contexts share the same approval ledger, so one token admits one call
701 /// across parallel nodes and later super-steps.
702 ///
703 /// Under a shadow boundary every class above `ReadOnly` refuses with
704 /// [`EffectViolation::ShadowRefused`] — the idempotency-key,
705 /// compensation, and approval rules never come into play, because the
706 /// shadow executes nothing above `ReadOnly` however well-declared it
707 /// is.
708 pub fn admit(&self, request: &EffectRequest) -> Result<EffectPermit, EffectViolation> {
709 let effect_id = request.effect_id(self.scope());
710 if self.is_shadow() && !matches!(request.effect(), Effect::Pure | Effect::ReadOnly) {
711 return Err(EffectViolation::ShadowRefused {
712 kind: request.kind().to_owned(),
713 effect: request.effect(),
714 effect_id,
715 });
716 }
717 let (compensation, approval) = match request.effect() {
718 Effect::Pure | Effect::ReadOnly => (None, None),
719 Effect::Idempotent => {
720 if request.idempotency_key().is_none() {
721 return Err(EffectViolation::MissingIdempotencyKey {
722 kind: request.kind().to_owned(),
723 });
724 }
725 (None, None)
726 }
727 Effect::Compensatable => (
728 Some(
729 self.compensations
730 .handler_for(request.kind())
731 .cloned()
732 .ok_or_else(|| EffectViolation::MissingCompensation {
733 kind: request.kind().to_owned(),
734 })?,
735 ),
736 None,
737 ),
738 Effect::NonIdempotent => {
739 let approval = self
740 .approvals
741 .lock()
742 .unwrap_or_else(|e| e.into_inner())
743 .remove(&effect_id)
744 .ok_or_else(|| EffectViolation::MissingApproval {
745 kind: request.kind().to_owned(),
746 effect_id: effect_id.clone(),
747 })?;
748 (None, Some(approval))
749 }
750 };
751 Ok(EffectPermit {
752 effect_id,
753 compensation,
754 approval,
755 })
756 }
757
758 /// Serve a refused effect from the recorded world (R0.12 wave 4, the
759 /// hybrid-replay rule): only meaningful for a shadow boundary and a
760 /// [`EffectViolation::ShadowRefused`] violation — anything else is not
761 /// the shadow's to serve, and answers `None`.
762 ///
763 /// Every shadow refusal reports to the sink, served or not, because
764 /// the refusal is the evidence; the recorded outcome is the
765 /// convenience that lets the shadow's decisions continue against the
766 /// recorded world. Returns the recorded outcome when the source run's
767 /// journal held one (`None`: the candidate diverged — the journal has
768 /// no answer to a call the recorded world never received, and the
769 /// caller surfaces the violation instead).
770 pub fn serve_shadow(
771 &self,
772 request: &EffectRequest,
773 recorded_request: &Value,
774 violation: &EffectViolation,
775 ) -> Option<Value> {
776 let Some(boundary) = &self.shadow else {
777 return None;
778 };
779 let EffectViolation::ShadowRefused {
780 kind,
781 effect,
782 effect_id,
783 } = violation
784 else {
785 return None;
786 };
787 let served = boundary.source.serve(kind, recorded_request);
788 (boundary.sink)(&ShadowRefusal {
789 kind: kind.clone(),
790 effect: *effect,
791 effect_id: effect_id.clone(),
792 input_hash: request.input_hash().to_owned(),
793 served: served.is_some(),
794 });
795 served
796 }
797}
798
799/// Evidence that one runtime effect occurrence passed admission.
800///
801/// The permit deliberately owns the selected compensation handler. The tool
802/// dispatcher keeps it alive until the call completes, preventing a registry
803/// update from removing the rollback path after admission but before the
804/// effect finishes.
805#[derive(Clone)]
806pub struct EffectPermit {
807 effect_id: EffectId,
808 compensation: Option<CompensationHandler>,
809 approval: Option<ApprovalToken>,
810}
811
812impl std::fmt::Debug for EffectPermit {
813 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
814 f.debug_struct("EffectPermit")
815 .field("effect_id", &self.effect_id)
816 .field("has_compensation", &self.compensation.is_some())
817 .field(
818 "approved_by",
819 &self.approval.as_ref().map(ApprovalToken::approved_by),
820 )
821 .finish()
822 }
823}
824
825impl EffectPermit {
826 /// The admitted occurrence's deterministic id.
827 pub fn effect_id(&self) -> &EffectId {
828 &self.effect_id
829 }
830
831 /// The rollback handler captured for a compensatable occurrence.
832 pub fn compensation(&self) -> Option<&CompensationHandler> {
833 self.compensation.as_ref()
834 }
835
836 /// The one-shot approval consumed for an irreversible occurrence.
837 pub fn approval(&self) -> Option<&ApprovalToken> {
838 self.approval.as_ref()
839 }
840}
841
842/// The marker/class agreement check every admission helper runs first.
843///
844/// The marker traits carry no methods, so a mismatched pair (`impl
845/// IrreversibleEffect` with `EFFECT = Effect::Pure`) compiles; it must not
846/// *pass*. Checking at admission keeps the typed API honest without needing
847/// compile-fail machinery: a lying declaration is rejected where it would be
848/// exploited.
849fn check_declaration<E: TypedEffect>(effect: &E, marker: Effect) -> Result<(), EffectViolation> {
850 if E::EFFECT != marker {
851 return Err(EffectViolation::DeclarationMismatch {
852 kind: effect.kind().to_owned(),
853 marker,
854 declared: E::EFFECT,
855 });
856 }
857 Ok(())
858}
859
860/// Admit a [`PureEffect`] to caching/speculation.
861///
862/// Always succeeds for an honestly declared type — the helper exists so the
863/// speculator's call site names the precondition it relies on, and so a
864/// mismatched declaration (marker trait disagreeing with
865/// [`TypedEffect::EFFECT`]) is caught here rather than after a speculated
866/// side effect.
867pub fn admit_speculation<E: PureEffect>(effect: &E) -> Result<(), EffectViolation> {
868 check_declaration::<E>(effect, Effect::Pure)
869}
870
871/// Admit an [`IdempotentEffect`] to automatic retry.
872///
873/// The typed form of the [`crate::durable::classify_retry`] effect gate, with
874/// the convention made checkable: the effect must carry the idempotency key
875/// its declaration means nothing without. Untyped `Effect` values keep their
876/// R0.6 behavior exactly — this helper gates only the typed path.
877pub fn admit_retry<E: IdempotentEffect>(effect: &E) -> Result<(), EffectViolation> {
878 check_declaration::<E>(effect, Effect::Idempotent)?;
879 if effect.idempotency_key().is_none() {
880 return Err(EffectViolation::MissingIdempotencyKey {
881 kind: effect.kind().to_owned(),
882 });
883 }
884 Ok(())
885}
886
887/// Admit a [`CompensatableEffect`] to execute, returning its registered
888/// rollback handler.
889///
890/// The handler is returned — not merely checked — so the caller holds the
891/// undo path from the moment the effect is admitted; an effect whose kind
892/// has no registered handler is rejected.
893pub fn admit_compensatable<E: CompensatableEffect>(
894 effect: &E,
895 registry: &CompensationRegistry,
896) -> Result<CompensationHandler, EffectViolation> {
897 check_declaration::<E>(effect, Effect::Compensatable)?;
898 registry.handler_for(effect.kind()).cloned().ok_or_else(|| {
899 EffectViolation::MissingCompensation {
900 kind: effect.kind().to_owned(),
901 }
902 })
903}
904
905/// Admit an [`IrreversibleEffect`] to execute behind an explicit approval.
906///
907/// `scope` must be the run scope the effect id was (and will be) derived in
908/// — the same value recovery uses to re-derive the id. The presented token
909/// must be scoped to exactly that id; anything else — no token, or a token
910/// for another occurrence — is rejected. The approval boundary this wave
911/// lands as a helper becomes an executor enforcement point in a later wave.
912pub fn admit_irreversible<E: IrreversibleEffect>(
913 effect: &E,
914 scope: &str,
915 approval: Option<&ApprovalToken>,
916) -> Result<(), EffectViolation> {
917 check_declaration::<E>(effect, Effect::NonIdempotent)?;
918 let required = effect.effect_id(scope);
919 let token = approval.ok_or_else(|| EffectViolation::MissingApproval {
920 kind: effect.kind().to_owned(),
921 effect_id: required.clone(),
922 })?;
923 if !token.admits(&required) {
924 return Err(EffectViolation::ApprovalScopeMismatch {
925 kind: effect.kind().to_owned(),
926 required,
927 presented: token.effect_id().clone(),
928 });
929 }
930 Ok(())
931}
932
933#[cfg(test)]
934mod tests {
935 use super::*;
936
937 #[test]
938 fn effect_id_derivation_is_deterministic_and_scoped() {
939 let a = derive_effect_id("run-1", "charge_card", "abc123", Some("key-7"));
940 let b = derive_effect_id("run-1", "charge_card", "abc123", Some("key-7"));
941 assert_eq!(a, b, "same inputs must derive the same id");
942 assert_eq!(a.as_str().len(), 64, "ids are hex SHA-256 digests");
943
944 // Every tuple component is load-bearing.
945 assert_ne!(
946 a,
947 derive_effect_id("run-2", "charge_card", "abc123", Some("key-7"))
948 );
949 assert_ne!(
950 a,
951 derive_effect_id("run-1", "refund", "abc123", Some("key-7"))
952 );
953 assert_ne!(
954 a,
955 derive_effect_id("run-1", "charge_card", "def456", Some("key-7"))
956 );
957 assert_ne!(
958 a,
959 derive_effect_id("run-1", "charge_card", "abc123", Some("key-8"))
960 );
961 assert_ne!(a, derive_effect_id("run-1", "charge_card", "abc123", None));
962 }
963
964 #[test]
965 fn effect_id_is_serde_transparent() {
966 let id = derive_effect_id("run-1", "charge_card", "abc123", None);
967 let value = serde_json::to_value(&id).unwrap();
968 assert_eq!(value, serde_json::json!(id.as_str()));
969 let back: EffectId = serde_json::from_value(value).unwrap();
970 assert_eq!(back, id);
971 }
972
973 // ---------- the shadow boundary (R0.12 wave 4) ----------
974
975 #[derive(Debug)]
976 struct MapSource {
977 outcomes: BTreeMap<String, Value>,
978 }
979
980 impl ShadowOutcomeSource for MapSource {
981 fn serve(&self, kind: &str, _recorded_request: &Value) -> Option<Value> {
982 self.outcomes.get(kind).cloned()
983 }
984 }
985
986 fn shadow_context() -> (EffectAdmissionContext, Arc<Mutex<Vec<ShadowRefusal>>>) {
987 let refusals = Arc::new(Mutex::new(Vec::new()));
988 let sink = {
989 let refusals = Arc::clone(&refusals);
990 Arc::new(move |refusal: &ShadowRefusal| {
991 refusals.lock().unwrap().push(refusal.clone());
992 }) as ShadowRefusalSink
993 };
994 let source = Arc::new(MapSource {
995 outcomes: BTreeMap::from([(
996 "charge_card".to_owned(),
997 serde_json::json!({"id": "ch_1"}),
998 )]),
999 });
1000 (
1001 EffectAdmissionContext::shadow("shadow-run", source, sink),
1002 refusals,
1003 )
1004 }
1005
1006 #[test]
1007 fn shadow_admits_pure_and_read_only_and_refuses_everything_above() {
1008 let (shadow, _refusals) = shadow_context();
1009 for effect in [Effect::Pure, Effect::ReadOnly] {
1010 let request = EffectRequest::new("lookup", effect, &serde_json::json!({}), None);
1011 assert!(
1012 shadow.admit(&request).is_ok(),
1013 "{effect:?} is admitted under a shadow"
1014 );
1015 }
1016 // Idempotent included: "safe to retry under one key" is not "safe
1017 // to execute twice from two revisions". No key, handler, or
1018 // approval changes the answer — the shadow holds none of them.
1019 for effect in [
1020 Effect::Idempotent,
1021 Effect::Compensatable,
1022 Effect::NonIdempotent,
1023 ] {
1024 let request = EffectRequest::new(
1025 "charge_card",
1026 effect,
1027 &serde_json::json!({"amount": 5}),
1028 Some("key-1".to_owned()),
1029 );
1030 match shadow.admit(&request) {
1031 Err(EffectViolation::ShadowRefused {
1032 kind,
1033 effect: refused,
1034 ..
1035 }) => {
1036 assert_eq!(kind, "charge_card");
1037 assert_eq!(refused, effect);
1038 }
1039 other => panic!("{effect:?} must refuse under a shadow, got {other:?}"),
1040 }
1041 }
1042 }
1043
1044 #[test]
1045 fn shadow_refusals_report_and_serve_only_from_the_recorded_world() {
1046 let (shadow, refusals) = shadow_context();
1047 let request = EffectRequest::new(
1048 "charge_card",
1049 Effect::NonIdempotent,
1050 &serde_json::json!({"amount": 5}),
1051 None,
1052 );
1053 let violation = shadow.admit(&request).unwrap_err();
1054 let served = shadow.serve_shadow(&request, &serde_json::json!({}), &violation);
1055 assert_eq!(served, Some(serde_json::json!({"id": "ch_1"})));
1056
1057 // A kind the recorded world never saw is a divergence: the
1058 // refusal still reports, with `served: false`.
1059 let unknown = EffectRequest::new(
1060 "send_email",
1061 Effect::NonIdempotent,
1062 &serde_json::json!({}),
1063 None,
1064 );
1065 let violation = shadow.admit(&unknown).unwrap_err();
1066 assert_eq!(
1067 shadow.serve_shadow(&unknown, &serde_json::json!({}), &violation),
1068 None
1069 );
1070
1071 let refusals = refusals.lock().unwrap();
1072 assert_eq!(refusals.len(), 2);
1073 assert!(refusals[0].served);
1074 assert!(!refusals[1].served);
1075 assert_eq!(refusals[1].kind, "send_email");
1076
1077 // Non-shadow contexts and non-shadow violations are not the
1078 // shadow's to serve.
1079 let plain = EffectAdmissionContext::new("run-1");
1080 let violation = EffectViolation::ShadowRefused {
1081 kind: "charge_card".to_owned(),
1082 effect: Effect::NonIdempotent,
1083 effect_id: request.effect_id("run-1"),
1084 };
1085 assert_eq!(
1086 plain.serve_shadow(&request, &serde_json::json!({}), &violation),
1087 None
1088 );
1089 }
1090}