#![cfg(test)]
use std::error::Error;
use std::fmt;
use std::num::NonZeroU64;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use crate::cancel::Token;
use super::hook::{
self, AfterToolCommitScope, CallbackResources, DispatchError, Emitter, HookError, HookResult,
ReadScope, StepSnapshot, ToolCallDecision, ToolCallScope, ToolHooks, ToolResultDecision,
ToolResultScope, TranscriptHooks, TranscriptMutation, TranscriptReservation,
};
use super::model::{Info, RequestPlan};
use super::session::{Lease, LeaseError, Session};
use super::tool::{
self, CallDisposition, Descriptor, Executor, ExecutorError, ExposeAll, Invocation,
};
use super::tool_batch_commit::{ToolBatchCommitError, commit_tool_batch};
use super::tool_batch_prepare::prepare_tool_calls;
use super::tool_batch_route::{RoutedToolBatch, ToolRouteBinding, route_and_execute};
use crate::audit;
use crate::opaque::Payload;
use crate::state::run_state::{self};
use crate::state::session_state::{self};
use crate::transcript::controller::{ControllerError, ReservationResources, TranscriptController};
use crate::transcript::item::{Assistant, Item, ModelVisibility};
use crate::transcript::store::{Snapshot, Version};
use crate::value::content::{Segment, SegmentExtensions};
use crate::value::lifecycle::{Coord, StepIndex};
use crate::value::tool_call::{self, Id, ToolCall, ToolResult};
#[derive(Debug)]
struct TestError(&'static str);
impl fmt::Display for TestError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.0)
}
}
impl Error for TestError {}
struct SilentEmitter;
impl Emitter for SilentEmitter {
fn emit_audit(&self, _event: audit::Event) {}
fn emit_error(&self, _error: Arc<dyn Error + Send + Sync>) {}
}
fn call(id: &str, name: &str) -> ToolCall {
ToolCall::new(
Id::new(id.to_owned()),
tool_call::Name::new(name.to_owned()),
Payload::copy_from_slice(b"{}"),
)
}
fn result_text(result: &ToolResult) -> &str {
result.output().unwrap().user_view().unwrap()
}
struct RewriteCalls;
impl ToolHooks for RewriteCalls {
fn before_tool_call(&self, scope: &ToolCallScope<'_>) -> HookResult<ToolCallDecision> {
Ok(ToolCallDecision::Modify(call(
&format!("spoof-{}", scope.call().id().as_str()),
&format!("effective-{}", scope.call().name().as_str()),
)))
}
fn before_tool_result(&self, _scope: &ToolResultScope<'_>) -> HookResult<ToolResultDecision> {
Ok(ToolResultDecision::Continue)
}
fn after_tool_commit(&self, _scope: &AfterToolCommitScope<'_>) -> Vec<Item> {
Vec::new()
}
}
struct SettleCalls;
impl ToolHooks for SettleCalls {
fn before_tool_call(&self, scope: &ToolCallScope<'_>) -> HookResult<ToolCallDecision> {
Ok(ToolCallDecision::ShortCircuit(ToolResult::success_text(
format!("base-{}", scope.call().name().as_str()),
)))
}
fn before_tool_result(&self, _scope: &ToolResultScope<'_>) -> HookResult<ToolResultDecision> {
Ok(ToolResultDecision::Continue)
}
fn after_tool_commit(&self, _scope: &AfterToolCommitScope<'_>) -> Vec<Item> {
Vec::new()
}
}
enum ResultAction {
Modify(&'static str),
FailAfterCancel(Token),
Cancel(Token),
}
struct ResultHook {
label: &'static str,
log: Arc<Mutex<Vec<String>>>,
action: ResultAction,
}
impl ResultHook {
fn decide(&self, scope: &ToolResultScope<'_>) -> HookResult<ToolResultDecision> {
self.log.lock().unwrap().push(format!(
"{}:{}:{}",
self.label,
scope.call().name().as_str(),
result_text(scope.result())
));
match &self.action {
ResultAction::Modify(suffix) => Ok(ToolResultDecision::Modify(
ToolResult::success_text(format!("{}-{suffix}", result_text(scope.result()))),
)),
ResultAction::FailAfterCancel(cancellation) => {
cancellation.cancel();
Err(HookError::new(TestError("result rewrite failed")))
}
ResultAction::Cancel(cancellation) => {
cancellation.cancel();
Ok(ToolResultDecision::Continue)
}
}
}
}
impl ToolHooks for ResultHook {
fn before_tool_call(&self, _scope: &ToolCallScope<'_>) -> HookResult<ToolCallDecision> {
Ok(ToolCallDecision::Continue)
}
fn before_tool_result(&self, scope: &ToolResultScope<'_>) -> HookResult<ToolResultDecision> {
self.decide(scope)
}
fn after_tool_commit(&self, _scope: &AfterToolCommitScope<'_>) -> Vec<Item> {
Vec::new()
}
}
struct CoordProbe {
key: run_state::Key<String>,
observations: Arc<Mutex<Vec<(String, String, String)>>>,
}
impl ToolHooks for CoordProbe {
fn before_tool_call(&self, _scope: &ToolCallScope<'_>) -> HookResult<ToolCallDecision> {
Ok(ToolCallDecision::Continue)
}
fn before_tool_result(&self, scope: &ToolResultScope<'_>) -> HookResult<ToolResultDecision> {
assert_eq!(scope.coord().generation(), 1);
let registration = scope.run_state().load(&self.key).unwrap();
self.observations.lock().unwrap().push((
scope.coord().call_id().to_owned(),
scope.coord().tool_name().to_owned(),
registration.as_str().to_owned(),
));
Ok(ToolResultDecision::Continue)
}
fn after_tool_commit(&self, _scope: &AfterToolCommitScope<'_>) -> Vec<Item> {
Vec::new()
}
}
struct MixedHook;
impl ToolHooks for MixedHook {
fn before_tool_call(&self, scope: &ToolCallScope<'_>) -> HookResult<ToolCallDecision> {
Ok(match scope.call().id().as_str() {
"executed" => ToolCallDecision::Modify(call("spoofed", "effective")),
"settled" => {
ToolCallDecision::ShortCircuit(ToolResult::success_text("settled".to_owned()))
}
_ => ToolCallDecision::Continue,
})
}
fn before_tool_result(&self, _scope: &ToolResultScope<'_>) -> HookResult<ToolResultDecision> {
Ok(ToolResultDecision::Continue)
}
fn after_tool_commit(&self, _scope: &AfterToolCommitScope<'_>) -> Vec<Item> {
Vec::new()
}
}
struct EchoExecutor;
impl Executor for EchoExecutor {
type Output = String;
async fn execute(
&self,
_invocation: &Invocation,
call: &ToolCall,
_cancellation: Token,
) -> Result<Self::Output, ExecutorError> {
Ok(call.name().as_str().to_owned())
}
}
struct ProbeReservation {
published: Arc<AtomicUsize>,
aborted: Arc<AtomicUsize>,
}
impl TranscriptReservation for ProbeReservation {
fn publish(self: Box<Self>) {
self.published.fetch_add(1, Ordering::SeqCst);
}
fn abort(self: Box<Self>) {
self.aborted.fetch_add(1, Ordering::SeqCst);
}
}
struct TranscriptProbe {
reject: bool,
mutations: Mutex<Vec<TranscriptMutation>>,
published: Arc<AtomicUsize>,
aborted: Arc<AtomicUsize>,
}
impl TranscriptProbe {
fn new(reject: bool) -> Arc<Self> {
Arc::new(Self {
reject,
mutations: Mutex::new(Vec::new()),
published: Arc::new(AtomicUsize::new(0)),
aborted: Arc::new(AtomicUsize::new(0)),
})
}
}
impl TranscriptHooks for TranscriptProbe {
fn reserve(
&self,
_scope: &ReadScope<'_>,
mutation: &TranscriptMutation,
) -> HookResult<Box<dyn TranscriptReservation>> {
self.mutations.lock().unwrap().push(mutation.clone());
if self.reject {
return Err(HookError::new(TestError("mutation rejected")));
}
Ok(Box::new(ProbeReservation {
published: Arc::clone(&self.published),
aborted: Arc::clone(&self.aborted),
}))
}
}
struct Fixture {
session: Session,
lease: Lease,
coord: Coord,
emitter: SilentEmitter,
}
impl Fixture {
fn new() -> Self {
let session = Session::new("session".into(), None);
let lease = session.try_acquire().unwrap();
lease.admit().unwrap();
let one = NonZeroU64::MIN;
let step = StepIndex::new(one, one, one).unwrap();
Self {
session,
lease,
coord: Coord::at_generation("session".into(), "run".into(), step, one).unwrap(),
emitter: SilentEmitter,
}
}
fn controller<'a>(
&'a self,
registry: &'a hook::RuntimeRegistry,
resources: &'a ReservationResources,
) -> TranscriptController<'a> {
TranscriptController::new(&self.lease, registry, resources, &self.coord, &self.emitter)
}
}
fn registry(registrations: Vec<hook::Registration>) -> hook::RuntimeRegistry {
let mut builder = hook::RegistryBuilder::new();
for registration in registrations {
builder.register(registration);
}
builder.build_runtime().unwrap()
}
fn callback_resources<'a>(
fixture: &'a Fixture,
states: &'a [run_state::Store],
reader: &'a session_state::Reader,
) -> Vec<CallbackResources<'a>> {
states
.iter()
.map(|state| CallbackResources::new(&fixture.coord, state, reader, None, &fixture.emitter))
.collect()
}
fn step_snapshot() -> Arc<StepSnapshot> {
let tools = tool::RegistryBuilder::new()
.build()
.unwrap()
.resolve_step_without_providers(
Snapshot::new(Version::ZERO, Vec::new()),
&Token::new(),
&ExposeAll,
)
.unwrap()
.into_snapshot();
StepSnapshot::freeze(
Info::new("model".into(), 1024).with_tools(true),
RequestPlan::new(),
tools,
)
}
fn execution_snapshot() -> Arc<super::tool::StepToolSnapshot> {
let mut builder = tool::RegistryBuilder::new();
builder.register(tool::Registration::client(
Descriptor::new(
tool::Name::local("effective".to_owned()).unwrap(),
"effective test tool".to_owned(),
Payload::copy_from_slice(b"{}"),
),
Arc::new(EchoExecutor),
Arc::new(|output: String| Ok(ToolResult::success_text(output))),
));
Arc::new(
builder
.build()
.unwrap()
.resolve_step_without_providers(
Snapshot::new(Version::ZERO, Vec::new()),
&Token::new(),
&ExposeAll,
)
.unwrap()
.into_snapshot(),
)
}
async fn make_records(
registry: &hook::RuntimeRegistry,
resources: &[CallbackResources<'_>],
) -> RoutedToolBatch {
let plan = prepare_tool_calls(
vec![call("original-1", "alpha"), call("original-2", "beta")],
registry,
resources,
step_snapshot(),
&Token::new(),
)
.unwrap();
let route_tools = Arc::new(
tool::RegistryBuilder::new()
.build()
.unwrap()
.resolve_step_without_providers(
Snapshot::new(Version::ZERO, Vec::new()),
&Token::new(),
&ExposeAll,
)
.unwrap()
.into_snapshot(),
);
route_and_execute(
plan,
route_tools,
None,
&mut |_call| -> ToolRouteBinding { panic!("all test calls are settled before routing") },
&Token::new(),
)
.await
.unwrap()
}
fn registrations(
result_hooks: Vec<(&str, Arc<dyn ToolHooks>)>,
transcript: Option<Arc<dyn TranscriptHooks>>,
) -> Vec<hook::Registration> {
let mut registrations = vec![
hook::Registration::new("rewrite".into()).tool(Arc::new(RewriteCalls)),
hook::Registration::new("inert".into()),
];
registrations.extend(
result_hooks
.into_iter()
.map(|(name, hook)| hook::Registration::new(name.to_owned()).tool(hook)),
);
registrations.push(hook::Registration::new("settle".into()).tool(Arc::new(SettleCalls)));
if let Some(transcript) = transcript {
registrations.push(hook::Registration::new("transcript".into()).transcript(transcript));
}
registrations
}
fn assert_empty(fixture: &Fixture) {
let snapshot = fixture.lease.transcript_snapshot().unwrap();
assert_eq!(snapshot.version(), Version::ZERO);
assert!(snapshot.items().is_empty());
}
#[tokio::test(flavor = "current_thread")]
async fn rewrites_chain_in_source_order_and_one_append_returns_finalized_records() {
let log = Arc::new(Mutex::new(Vec::new()));
let first: Arc<dyn ToolHooks> = Arc::new(ResultHook {
label: "first",
log: Arc::clone(&log),
action: ResultAction::Modify("first"),
});
let second: Arc<dyn ToolHooks> = Arc::new(ResultHook {
label: "second",
log: Arc::clone(&log),
action: ResultAction::Modify("second"),
});
let probe = TranscriptProbe::new(false);
let registry = registry(registrations(
vec![("first", first), ("second", second)],
Some(Arc::clone(&probe) as Arc<dyn TranscriptHooks>),
));
let fixture = Fixture::new();
let reader = fixture.lease.state().reader();
let states = (0..registry.len())
.map(|_| run_state::Store::new())
.collect::<Vec<_>>();
let callback_resources = callback_resources(&fixture, &states, &reader);
let records = make_records(®istry, &callback_resources).await;
let reservation_resources =
ReservationResources::new(registry.len(), fixture.lease.state().reader());
let controller = fixture.controller(®istry, &reservation_resources);
let assistant = Assistant::new(
vec![
Segment::ToolCall {
call: call("original-1", "alpha"),
extensions: SegmentExtensions::new(String::new(), None, None),
},
Segment::ToolCall {
call: call("original-2", "beta"),
extensions: SegmentExtensions::new(String::new(), None, None),
},
],
None,
);
let committed = commit_tool_batch(
records,
assistant,
&fixture.coord,
®istry,
&callback_resources,
step_snapshot(),
&controller,
&Token::new(),
)
.unwrap();
assert_eq!(committed.version(), Version::from_u64(3));
assert_eq!(committed.finalized().len(), 2);
assert_eq!(
*log.lock().unwrap(),
[
"first:effective-alpha:base-effective-alpha",
"second:effective-alpha:base-effective-alpha-first",
"first:effective-beta:base-effective-beta",
"second:effective-beta:base-effective-beta-first",
]
);
for (index, expected) in [
(
"original-1",
"effective-alpha",
"base-effective-alpha-first-second",
),
(
"original-2",
"effective-beta",
"base-effective-beta-first-second",
),
]
.into_iter()
.enumerate()
{
let finalized = &committed.finalized()[index];
assert_eq!(finalized.original_call().id().as_str(), expected.0);
assert_eq!(finalized.effective_call().name().as_str(), expected.1);
assert_eq!(finalized.disposition(), CallDisposition::ShortCircuited);
assert_eq!(finalized.item().call_id().as_str(), expected.0);
assert_eq!(finalized.item().tool_name().as_str(), expected.1);
assert_eq!(result_text(finalized.item().result()), expected.2);
}
let cloned_parts = committed.finalized()[0].clone().into_parts();
assert_eq!(cloned_parts.0.id().as_str(), "original-1");
assert_eq!(cloned_parts.1.name().as_str(), "effective-alpha");
assert_eq!(cloned_parts.2, CallDisposition::ShortCircuited);
assert_eq!(cloned_parts.3.call_id().as_str(), "original-1");
let snapshot = fixture.lease.transcript_snapshot().unwrap();
assert_eq!(snapshot.version(), Version::from_u64(3));
let Item::Assistant(assistant) = &snapshot.items()[0] else {
panic!("the exchange starts with its assistant record");
};
assert!(matches!(
&assistant.content()[0],
Segment::ToolCall { call, .. }
if call.id().as_str() == "original-1" && call.name().as_str() == "effective-alpha"
));
assert!(matches!(
&assistant.content()[1],
Segment::ToolCall { call, .. }
if call.id().as_str() == "original-2" && call.name().as_str() == "effective-beta"
));
assert!(
matches!(&snapshot.items()[1], Item::ToolResult(item) if item.call_id().as_str() == "original-1")
);
assert!(
matches!(&snapshot.items()[2], Item::ToolResult(item) if item.call_id().as_str() == "original-2")
);
let mutations = probe.mutations.lock().unwrap();
assert_eq!(
mutations.len(),
1,
"the exchange uses one controller append"
);
assert_eq!(mutations[0].previous_version(), Version::ZERO);
assert_eq!(mutations[0].version(), Version::from_u64(3));
assert_eq!(mutations[0].items().len(), 3);
assert_eq!(probe.published.load(Ordering::SeqCst), 1);
assert_eq!(probe.aborted.load(Ordering::SeqCst), 0);
drop(mutations);
let (version, finalized) = committed.into_parts();
assert_eq!(version, Version::from_u64(3));
assert_eq!(finalized.len(), 2);
assert_eq!(fixture.session.id(), "session");
}
#[tokio::test(flavor = "current_thread")]
async fn a_user_only_assistant_record_hides_every_result_committed_with_it() {
let registry = registry(registrations(Vec::new(), None));
let fixture = Fixture::new();
let reader = fixture.lease.state().reader();
let states = (0..registry.len())
.map(|_| run_state::Store::new())
.collect::<Vec<_>>();
let callback_resources = callback_resources(&fixture, &states, &reader);
let records = make_records(®istry, &callback_resources).await;
let reservation_resources =
ReservationResources::new(registry.len(), fixture.lease.state().reader());
let controller = fixture.controller(®istry, &reservation_resources);
let committed = commit_tool_batch(
records,
Assistant::new(Vec::new(), None).with_visibility(ModelVisibility::Hidden),
&fixture.coord,
®istry,
&callback_resources,
step_snapshot(),
&controller,
&Token::new(),
)
.unwrap();
assert!(
committed
.finalized()
.iter()
.all(|finalized| finalized.item().visibility() == ModelVisibility::Hidden),
"every reported record carries the record-level decision"
);
let snapshot = fixture.lease.transcript_snapshot().unwrap();
assert!(
snapshot.items().iter().all(|item| match item {
Item::Assistant(item) => item.visibility() == ModelVisibility::Hidden,
Item::ToolResult(item) => item.visibility() == ModelVisibility::Hidden,
Item::User(_) | Item::System(_) => panic!("the exchange commits only these two"),
}),
"the committed exchange is hidden whole"
);
let (_, items) = snapshot.into_parts();
assert!(
RequestPlan::new()
.try_into_request(items)
.expect("a hidden exchange still projects")
.messages()
.is_empty()
);
}
#[tokio::test(flavor = "current_thread")]
async fn before_tool_result_uses_per_source_coord_and_registration_resources() {
let key = run_state::Key::<String>::new();
let observations = Arc::new(Mutex::new(Vec::new()));
let hook: Arc<dyn ToolHooks> = Arc::new(CoordProbe {
key: key.clone(),
observations: Arc::clone(&observations),
});
let registry = registry(registrations(vec![("coord-probe", hook)], None));
let fixture = Fixture::new();
let reader = fixture.lease.state().reader();
let states = (0..registry.len())
.map(|_| run_state::Store::new())
.collect::<Vec<_>>();
states[2].set(&key, Arc::new("coord-probe-resource".to_owned()));
let callback_resources = callback_resources(&fixture, &states, &reader);
let batch = make_records(®istry, &callback_resources).await;
let reservation_resources =
ReservationResources::new(registry.len(), fixture.lease.state().reader());
let controller = fixture.controller(®istry, &reservation_resources);
commit_tool_batch(
batch,
Assistant::new(Vec::new(), None),
&fixture.coord,
®istry,
&callback_resources,
step_snapshot(),
&controller,
&Token::new(),
)
.unwrap();
assert_eq!(
*observations.lock().unwrap(),
[
(
"original-1".to_owned(),
"effective-alpha".to_owned(),
"coord-probe-resource".to_owned(),
),
(
"original-2".to_owned(),
"effective-beta".to_owned(),
"coord-probe-resource".to_owned(),
),
]
);
}
#[tokio::test(flavor = "current_thread")]
async fn mixed_settled_and_executed_batch_commits_end_to_end_in_source_order() {
let registry = registry(vec![
hook::Registration::new("mixed".to_owned()).tool(Arc::new(MixedHook)),
]);
let fixture = Fixture::new();
let reader = fixture.lease.state().reader();
let states = [run_state::Store::new()];
let callback_resources = callback_resources(&fixture, &states, &reader);
let plan = prepare_tool_calls(
vec![call("settled", "short"), call("executed", "original")],
®istry,
&callback_resources,
step_snapshot(),
&Token::new(),
)
.unwrap();
let batch = route_and_execute(
plan,
execution_snapshot(),
Some("session".to_owned()),
&mut |_call| ToolRouteBinding::new(super::event::ToolEmitter::closed()),
&Token::new(),
)
.await
.unwrap();
let reservation_resources =
ReservationResources::new(registry.len(), fixture.lease.state().reader());
let controller = fixture.controller(®istry, &reservation_resources);
let committed = commit_tool_batch(
batch,
Assistant::new(Vec::new(), None),
&fixture.coord,
®istry,
&callback_resources,
step_snapshot(),
&controller,
&Token::new(),
)
.unwrap();
assert_eq!(
committed
.finalized()
.iter()
.map(|finalized| (
finalized.item().call_id().as_str(),
finalized.item().tool_name().as_str(),
result_text(finalized.item().result()),
))
.collect::<Vec<_>>(),
[
("settled", "short", "settled"),
("executed", "effective", "effective"),
]
);
let snapshot = fixture.lease.transcript_snapshot().unwrap();
assert!(matches!(snapshot.items()[0], Item::Assistant(_)));
assert!(
matches!(&snapshot.items()[1], Item::ToolResult(item) if item.call_id().as_str() == "settled")
);
assert!(
matches!(&snapshot.items()[2], Item::ToolResult(item) if item.call_id().as_str() == "executed")
);
}
#[tokio::test(flavor = "current_thread")]
async fn pre_cancel_and_callback_cancel_or_failure_commit_nothing() {
for callback_case in [false, true] {
let token = Token::new();
let log = Arc::new(Mutex::new(Vec::new()));
let action = if callback_case {
ResultAction::FailAfterCancel(token.clone())
} else {
ResultAction::Cancel(token.clone())
};
let hook: Arc<dyn ToolHooks> = Arc::new(ResultHook {
label: "failing",
log,
action,
});
let registry = registry(registrations(vec![("failing", hook)], None));
let fixture = Fixture::new();
let reader = fixture.lease.state().reader();
let states = (0..registry.len())
.map(|_| run_state::Store::new())
.collect::<Vec<_>>();
let callback_resources = callback_resources(&fixture, &states, &reader);
let records = make_records(®istry, &callback_resources).await;
let reservation_resources =
ReservationResources::new(registry.len(), fixture.lease.state().reader());
let controller = fixture.controller(®istry, &reservation_resources);
let error = commit_tool_batch(
records,
Assistant::new(Vec::new(), None),
&fixture.coord,
®istry,
&callback_resources,
step_snapshot(),
&controller,
&token,
)
.err()
.expect("commit must fail");
let (source, dispatch) = error.rewrite().unwrap();
assert_eq!(source, 0);
if callback_case {
assert!(
matches!(dispatch, DispatchError::Callback(failure) if failure.name() == "failing")
);
} else {
assert!(matches!(dispatch, DispatchError::Cancelled));
}
assert!(error.controller().is_none());
assert_empty(&fixture);
}
let registry = registry(registrations(Vec::new(), None));
let fixture = Fixture::new();
let reader = fixture.lease.state().reader();
let states = (0..registry.len())
.map(|_| run_state::Store::new())
.collect::<Vec<_>>();
let callback_resources = callback_resources(&fixture, &states, &reader);
let records = make_records(®istry, &callback_resources).await;
let reservation_resources =
ReservationResources::new(registry.len(), fixture.lease.state().reader());
let controller = fixture.controller(®istry, &reservation_resources);
let token = Token::new();
token.cancel();
let error = commit_tool_batch(
records,
Assistant::new(Vec::new(), None),
&fixture.coord,
®istry,
&callback_resources,
step_snapshot(),
&controller,
&token,
)
.err()
.expect("commit must fail");
assert!(matches!(error, ToolBatchCommitError::Cancelled));
assert!(error.rewrite().is_none());
assert!(error.controller().is_none());
assert_empty(&fixture);
}
#[tokio::test(flavor = "current_thread")]
async fn controller_reservation_reject_and_released_cas_commit_nothing() {
{
let rejecting = TranscriptProbe::new(true);
let registry = registry(registrations(
Vec::new(),
Some(Arc::clone(&rejecting) as Arc<dyn TranscriptHooks>),
));
let fixture = Fixture::new();
let reader = fixture.lease.state().reader();
let states = (0..registry.len())
.map(|_| run_state::Store::new())
.collect::<Vec<_>>();
let callback_resources = callback_resources(&fixture, &states, &reader);
let records = make_records(®istry, &callback_resources).await;
let reservation_resources =
ReservationResources::new(registry.len(), fixture.lease.state().reader());
let controller = fixture.controller(®istry, &reservation_resources);
let error = commit_tool_batch(
records,
Assistant::new(Vec::new(), None),
&fixture.coord,
®istry,
&callback_resources,
step_snapshot(),
&controller,
&Token::new(),
)
.err()
.expect("commit must fail");
assert!(matches!(
error.controller(),
Some(ControllerError::Dispatch(DispatchError::Callback(failure)))
if failure.name() == "transcript"
));
assert!(error.rewrite().is_none());
assert_eq!(rejecting.mutations.lock().unwrap().len(), 1);
assert_eq!(rejecting.published.load(Ordering::SeqCst), 0);
assert_eq!(rejecting.aborted.load(Ordering::SeqCst), 0);
assert_empty(&fixture);
}
let registry = registry(registrations(Vec::new(), None));
let fixture = Fixture::new();
let reader = fixture.lease.state().reader();
let states = (0..registry.len())
.map(|_| run_state::Store::new())
.collect::<Vec<_>>();
let callback_resources = callback_resources(&fixture, &states, &reader);
let records = make_records(®istry, &callback_resources).await;
fixture.lease.release();
let reservation_resources =
ReservationResources::new(registry.len(), fixture.lease.state().reader());
let controller = fixture.controller(®istry, &reservation_resources);
let error = commit_tool_batch(
records,
Assistant::new(Vec::new(), None),
&fixture.coord,
®istry,
&callback_resources,
step_snapshot(),
&controller,
&Token::new(),
)
.err()
.expect("commit must fail");
assert!(matches!(
error.controller(),
Some(ControllerError::Lease(LeaseError::Released))
));
assert!(error.rewrite().is_none());
assert_empty(&fixture);
}