use std::collections::BTreeMap;
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
use async_trait::async_trait;
use crank_core::{
AdapterResponse, CacheScope, CacheStoreError, ConfirmationPolicy, CoordinationStateReservation,
CoordinationStateStore, CoordinationStateValue, ExecutionConfig, ExecutionMode, HttpMethod,
Operation, OperationId, OperationSafetyClass, OperationSafetyPolicy, OperationSecurityLevel,
OperationStatus, Protocol, ProtocolAdapter, ProtocolAdapterError, RestTarget, Target,
ToolDescription,
};
use crank_mapping::{MappingRule, MappingSet};
use crank_runtime::{
InMemoryCoordinationStateStore, RuntimeError, RuntimeExecutorBuilder, RuntimeRequestContext,
};
use crank_schema::{Schema, SchemaKind};
use futures_util::future::join_all;
use serde_json::json;
use time::OffsetDateTime;
#[tokio::test]
async fn destructive_operation_requires_single_use_confirmation() {
let call_count = Arc::new(AtomicUsize::new(0));
let executor = RuntimeExecutorBuilder::new()
.register_adapter(Arc::new(CountingAdapter {
call_count: Arc::clone(&call_count),
}))
.with_coordination_store(Arc::new(InMemoryCoordinationStateStore::default()))
.build();
let operation = destructive_delete_operation().into();
let context = RuntimeRequestContext::from_request_id("req_confirm")
.with_response_cache_scope("workspace_1", "agent_1");
let first = executor
.execute_with_context(
&operation,
&json!({ "order_id": "ord_123" }),
Some(&context),
)
.await
.expect_err("first destructive call must only stage confirmation");
let confirmation_token = match first {
RuntimeError::ConfirmationRequired {
confirmation_token, ..
} => confirmation_token,
error => panic!("expected confirmation required, got {error:?}"),
};
assert_eq!(call_count.load(Ordering::SeqCst), 0);
let confirmed_context = context
.clone()
.with_confirmation_token(confirmation_token.clone());
let confirmed = executor
.execute_with_context(
&operation,
&json!({ "order_id": "ord_123" }),
Some(&confirmed_context),
)
.await
.unwrap();
assert_eq!(confirmed, json!({ "deleted": true }));
assert_eq!(call_count.load(Ordering::SeqCst), 1);
let replay = executor
.execute_with_context(
&operation,
&json!({ "order_id": "ord_123" }),
Some(&confirmed_context),
)
.await
.expect_err("confirmation token must be single-use");
assert!(matches!(
replay,
RuntimeError::InvalidConfirmationToken { .. }
));
assert_eq!(call_count.load(Ordering::SeqCst), 1);
let approved_context = context.with_approval_granted();
let approved = executor
.execute_with_context(
&operation,
&json!({ "order_id": "ord_123" }),
Some(&approved_context),
)
.await
.unwrap();
assert_eq!(approved, json!({ "deleted": true }));
assert_eq!(call_count.load(Ordering::SeqCst), 2);
}
#[tokio::test]
async fn confirmation_token_allows_only_one_concurrent_execution() {
let call_count = Arc::new(AtomicUsize::new(0));
let executor = RuntimeExecutorBuilder::new()
.register_adapter(Arc::new(CountingAdapter {
call_count: Arc::clone(&call_count),
}))
.with_coordination_store(Arc::new(InMemoryCoordinationStateStore::default()))
.build();
let operation: crank_runtime::RuntimeOperation = destructive_delete_operation().into();
let context = RuntimeRequestContext::from_request_id("req_confirm_concurrent")
.with_response_cache_scope("workspace_1", "agent_1");
let first = executor
.execute_with_context(
&operation,
&json!({ "order_id": "ord_123" }),
Some(&context),
)
.await
.unwrap_err();
let RuntimeError::ConfirmationRequired {
confirmation_token, ..
} = first
else {
panic!("expected confirmation token")
};
let attempts = (0..16).map(|_| {
let executor = executor.clone();
let operation = operation.clone();
let context = context
.clone()
.with_confirmation_token(confirmation_token.clone());
async move {
executor
.execute_with_context(
&operation,
&json!({ "order_id": "ord_123" }),
Some(&context),
)
.await
}
});
let results = join_all(attempts).await;
let successful = results.iter().filter(|result| result.is_ok()).count();
assert_eq!(successful, 1);
assert_eq!(call_count.load(Ordering::SeqCst), 1);
assert!(
results
.iter()
.filter_map(|result| result.as_ref().err())
.all(|error| matches!(error, RuntimeError::InvalidConfirmationToken { .. }))
);
}
#[tokio::test]
async fn unavailable_confirmation_store_is_preserved_as_a_typed_error() {
let executor = RuntimeExecutorBuilder::new()
.register_adapter(Arc::new(CountingAdapter {
call_count: Arc::new(AtomicUsize::new(0)),
}))
.with_coordination_store(Arc::new(UnavailableCoordinationStore))
.build();
let operation: crank_runtime::RuntimeOperation = destructive_delete_operation().into();
let context = RuntimeRequestContext::from_request_id("req_confirm_unavailable")
.with_response_cache_scope("workspace_1", "agent_1");
let issue_error = executor
.execute_with_context(
&operation,
&json!({ "order_id": "ord_123" }),
Some(&context),
)
.await
.expect_err("unavailable store must prevent issuing a token");
assert!(matches!(
issue_error,
RuntimeError::ConfirmationStoreUnavailable { ref operation_id }
if operation_id == "op_delete_order"
));
let consume_error = executor
.execute_with_context(
&operation,
&json!({ "order_id": "ord_123" }),
Some(&context.with_confirmation_token("ct_unavailable")),
)
.await
.expect_err("unavailable store must not look like an invalid token");
assert!(matches!(
consume_error,
RuntimeError::ConfirmationStoreUnavailable { ref operation_id }
if operation_id == "op_delete_order"
));
}
struct UnavailableCoordinationStore;
impl UnavailableCoordinationStore {
fn error() -> CacheStoreError {
CacheStoreError::Unavailable {
message: "test backend unavailable".to_owned(),
}
}
}
#[async_trait]
impl CoordinationStateStore for UnavailableCoordinationStore {
async fn get_value(
&self,
_scope: CacheScope,
_key: &str,
) -> Result