use std::sync::Arc;
use serde_json::json;
use rusty_agent_runtime::effects::{
admit_compensatable, admit_irreversible, admit_retry, admit_speculation, derive_effect_id,
ApprovalToken, CompensatableEffect, CompensationRegistry, EffectViolation, IdempotentEffect,
IrreversibleEffect, PureEffect, ReadOnlyEffect, TypedEffect, EFFECT_ID_DOMAIN,
};
use rusty_agent_runtime::journal::{Clock, Journal};
use rusty_agent_runtime::record::{sha256_hex, Effect, EffectReceipt};
struct ChargeCard {
input: String,
key: Option<String>,
}
impl ChargeCard {
fn new(amount_cents: u64) -> Self {
let input = json!({"amount_cents": amount_cents, "currency": "usd"});
Self {
input: sha256_hex(&serde_json::to_vec(&input).unwrap()),
key: None,
}
}
}
impl TypedEffect for ChargeCard {
const EFFECT: Effect = Effect::NonIdempotent;
fn kind(&self) -> &str {
"charge_card"
}
fn input_hash(&self) -> &str {
&self.input
}
fn idempotency_key(&self) -> Option<&str> {
self.key.as_deref()
}
}
impl IrreversibleEffect for ChargeCard {}
struct ReserveSeat;
impl TypedEffect for ReserveSeat {
const EFFECT: Effect = Effect::Compensatable;
fn kind(&self) -> &str {
"reserve_seat"
}
fn input_hash(&self) -> &str {
"seat-input-hash"
}
}
impl CompensatableEffect for ReserveSeat {}
struct UpsertDocument {
key: Option<String>,
}
impl TypedEffect for UpsertDocument {
const EFFECT: Effect = Effect::Idempotent;
fn kind(&self) -> &str {
"upsert_document"
}
fn input_hash(&self) -> &str {
"doc-input-hash"
}
fn idempotency_key(&self) -> Option<&str> {
self.key.as_deref()
}
}
impl IdempotentEffect for UpsertDocument {}
struct RankResults;
impl TypedEffect for RankResults {
const EFFECT: Effect = Effect::Pure;
fn kind(&self) -> &str {
"rank_results"
}
fn input_hash(&self) -> &str {
"rank-input-hash"
}
}
impl PureEffect for RankResults {}
struct FetchPage;
impl TypedEffect for FetchPage {
const EFFECT: Effect = Effect::ReadOnly;
fn kind(&self) -> &str {
"fetch_page"
}
fn input_hash(&self) -> &str {
"fetch-input-hash"
}
}
impl ReadOnlyEffect for FetchPage {}
struct SneakyEffect;
impl TypedEffect for SneakyEffect {
const EFFECT: Effect = Effect::Pure;
fn kind(&self) -> &str {
"sneaky"
}
fn input_hash(&self) -> &str {
"sneaky-input-hash"
}
}
impl IrreversibleEffect for SneakyEffect {}
#[test]
fn irreversible_effect_requires_a_scoped_approval() {
let charge = ChargeCard::new(4_200);
let scope = "run-7";
let violation = admit_irreversible(&charge, scope, None).unwrap_err();
match violation {
EffectViolation::MissingApproval { kind, effect_id } => {
assert_eq!(kind, "charge_card");
assert_eq!(effect_id, charge.effect_id(scope));
}
other => panic!("expected MissingApproval, got {other:?}"),
}
let other = ChargeCard::new(9_900);
let wrong = ApprovalToken::for_effect(&other, scope, "ops:amjad");
let violation = admit_irreversible(&charge, scope, Some(&wrong)).unwrap_err();
match violation {
EffectViolation::ApprovalScopeMismatch {
required,
presented,
..
} => {
assert_eq!(required, charge.effect_id(scope));
assert_eq!(presented, other.effect_id(scope));
}
other => panic!("expected ApprovalScopeMismatch, got {other:?}"),
}
let approval = ApprovalToken::for_effect(&charge, scope, "ops:amjad");
assert!(approval.admits(&charge.effect_id(scope)));
assert_eq!(approval.approved_by(), "ops:amjad");
admit_irreversible(&charge, scope, Some(&approval)).unwrap();
assert!(admit_irreversible(&charge, "run-8", Some(&approval)).is_err());
}
#[test]
fn approval_token_is_evidence_shaped_serde() {
let charge = ChargeCard::new(4_200);
let token = ApprovalToken::for_effect(&charge, "run-7", "policy:auto-approve-v2");
let back: ApprovalToken =
serde_json::from_str(&serde_json::to_string(&token).unwrap()).unwrap();
assert_eq!(token, back);
}
#[test]
fn compensatable_effect_requires_a_registered_handler() {
let reservation = ReserveSeat;
let mut registry = CompensationRegistry::new();
let violation = match admit_compensatable(&reservation, ®istry) {
Err(violation) => violation,
Ok(_) => panic!("admission without a registered handler must fail"),
};
assert_eq!(
violation,
EffectViolation::MissingCompensation {
kind: "reserve_seat".into()
}
);
let handler: rusty_agent_runtime::effects::CompensationHandler =
Arc::new(|output| Ok(json!({"cancelled": output.get("seat")})));
assert!(registry.register("reserve_seat", handler).is_none());
let admitted = admit_compensatable(&reservation, ®istry).unwrap();
let record = admitted(&json!({"seat": "14A"})).unwrap();
assert_eq!(record, json!({"cancelled": "14A"}));
let replacement: rusty_agent_runtime::effects::CompensationHandler =
Arc::new(|_| Ok(json!({"cancelled": "all"})));
assert!(registry.register("reserve_seat", replacement).is_some());
}
#[test]
fn idempotent_effect_retries_only_under_a_key() {
let keyless = UpsertDocument { key: None };
let violation = admit_retry(&keyless).unwrap_err();
assert_eq!(
violation,
EffectViolation::MissingIdempotencyKey {
kind: "upsert_document".into()
}
);
let keyed = UpsertDocument {
key: Some("run-7:doc:3".into()),
};
admit_retry(&keyed).unwrap();
}
#[test]
fn pure_effect_is_admitted_to_speculation() {
admit_speculation(&RankResults).unwrap();
}
#[test]
fn read_only_effects_need_no_admission_gate() {
let fetch = FetchPage;
assert_eq!(FetchPage::EFFECT, Effect::ReadOnly);
assert!(FetchPage::EFFECT.is_freely_repeatable());
assert_eq!(fetch.kind(), "fetch_page");
}
#[test]
fn mismatched_marker_and_declared_class_are_rejected() {
let violation = admit_irreversible(&SneakyEffect, "run-7", None).unwrap_err();
assert_eq!(
violation,
EffectViolation::DeclarationMismatch {
kind: "sneaky".into(),
marker: Effect::NonIdempotent,
declared: Effect::Pure,
}
);
}
#[test]
fn typed_effect_ids_are_deterministic_and_scope_bound() {
let charge = ChargeCard::new(4_200);
assert_eq!(charge.effect_id("run-7"), charge.effect_id("run-7"));
assert_eq!(
charge.effect_id("run-7"),
derive_effect_id("run-7", "charge_card", charge.input_hash(), None)
);
assert_ne!(charge.effect_id("run-7"), charge.effect_id("run-8"));
assert!(EFFECT_ID_DOMAIN.ends_with("/v1"));
let manual = sha256_hex(
[
EFFECT_ID_DOMAIN,
"run-7",
"charge_card",
charge.input_hash(),
"-",
]
.join("\n")
.as_bytes(),
);
assert_eq!(charge.effect_id("run-7").as_str(), manual);
}
#[test]
fn recovery_finds_the_committed_receipt_by_effect_id() {
let mut charge = ChargeCard::new(4_200);
charge.key = Some("run-7:charge:1".into());
let id = charge.effect_id("run-7");
let journal = Journal::new("run-7", "thread-7", Clock::System);
let receipt = EffectReceipt {
provider: "stripe".into(),
provider_id: "ch_committed".into(),
idempotency_key: "run-7:charge:1".into(),
task_id: Some("task-1".into()),
effect_id: Some(id.as_str().to_owned()),
};
journal.record_effect_receipt(&receipt, None);
let snapshot = journal.snapshot();
assert_eq!(
snapshot.find_effect_receipt_by_effect_id(&id),
Some(receipt)
);
let mut next = ChargeCard::new(4_200);
next.key = Some("run-7:charge:2".into());
assert_eq!(
snapshot.find_effect_receipt_by_effect_id(&next.effect_id("run-7")),
None
);
}