| /* | |
| * Licensed to the Apache Software Foundation (ASF) under one | |
| * or more contributor license agreements. See the NOTICE file | |
| * distributed with this work for additional information | |
| * regarding copyright ownership. The ASF licenses this file | |
| * to you under the Apache License, Version 2.0 (the | |
| * "License"); you may not use this file except in compliance | |
| * with the License. You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, | |
| * software distributed under the License is distributed on an | |
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | |
| * KIND, either express or implied. See the License for the | |
| * specific language governing permissions and limitations | |
| * under the License. | |
| */ | |
| use super::*; | |
| use crate::{ | |
| Engine, RunError, | |
| reconcile::tests::{apply_policy_fact, model_closure, policy_view}, | |
| }; | |
| use futures_util::FutureExt; | |
| use maka_agent_facts::{ | |
| accounting::Outcome, | |
| context::{ModelClosureProtocol, ModelPurpose}, | |
| input::RunInput, | |
| model::{ModelFinishReason, ModelPart, ModelToolCall, ModelUsage, ToolInput}, | |
| tools::ToolSemantics, | |
| }; | |
| use maka_agent_state::{ | |
| Admission, Change, ContentBlob, DriverClaim, DriverDomain, Store, | |
| fold::{ModelClosure, RunView}, | |
| }; | |
| use maka_event_log::{ | |
| root::{RootNamespaces, RootOwner}, | |
| root_store::RootStore, | |
| }; | |
| use maka_plugin_core::{ | |
| composition::InstanceId, | |
| contract::Transport, | |
| deployment::DeploymentRef, | |
| operation::{ | |
| OperationCleanup, OperationOutcome, OperationReply, OperationResult, Receipt, | |
| RecoveryContract, RecoveryProtocol, RecoveryRef, | |
| }, | |
| }; | |
| use std::{ | |
| collections::{BTreeMap, BTreeSet}, | |
| panic::AssertUnwindSafe, | |
| sync::{ | |
| Arc, Mutex, | |
| atomic::{AtomicI64, AtomicUsize, Ordering}, | |
| }, | |
| time::{Duration, Instant}, | |
| }; | |
| use tokio::sync::{Barrier, Notify}; | |
| use tokio_util::sync::CancellationToken; | |
| use uuid::Uuid; | |
| type TestResult<T> = Result<T, Box<dyn std::error::Error + Send + Sync>>; | |
| #[derive(Clone)] | |
| enum MockPrevalidateOutcome { | |
| Blocked(Box<BlockerKind>), | |
| ErrBlocked(Box<BlockerKind>), | |
| Denied(ToolRejection), | |
| } | |
| #[derive(Clone, Default)] | |
| struct ToolBehavior { | |
| semantics: Option<ToolSemantics>, | |
| approval: Option<ApprovalId>, | |
| decide_blocked: Option<Box<BlockerKind>>, | |
| prevalidate_gate: Option<Arc<Notify>>, | |
| on_prevalidate_start: Option<Arc<Notify>>, | |
| on_prevalidate_finish: Option<Arc<Notify>>, | |
| cancel_on_prevalidate_finish: Option<CancellationToken>, | |
| prevalidate_outcome: Option<MockPrevalidateOutcome>, | |
| on_dispatch: Option<Arc<Notify>>, | |
| dispatch_barrier: Option<Arc<Barrier>>, | |
| } | |
| struct MockModelStream { | |
| call_ids: Vec<String>, | |
| started: Vec<Arc<Notify>>, | |
| gate: Arc<Notify>, | |
| close_with_length: bool, | |
| } | |
| type OnNowHook = Box<dyn FnMut() + Send>; | |
| struct MockDirectPorts { | |
| clock: AtomicI64, | |
| behaviors: BTreeMap<String, ToolBehavior>, | |
| expected_dispatches: usize, | |
| dispatched_count: AtomicUsize, | |
| dispatched_calls: Mutex<Vec<(String, Instant)>>, | |
| cancel_on_all_dispatched: CancellationToken, | |
| cancel_on_prepare_step: bool, | |
| direct_tool_batching: bool, | |
| model_stream: Mutex<Option<MockModelStream>>, | |
| on_now: Mutex<Option<OnNowHook>>, | |
| } | |
| impl MockDirectPorts { | |
| fn new( | |
| behaviors: BTreeMap<String, ToolBehavior>, | |
| expected_dispatches: usize, | |
| cancel_on_all_dispatched: CancellationToken, | |
| ) -> Self { | |
| Self { | |
| clock: AtomicI64::new(100), | |
| behaviors, | |
| expected_dispatches, | |
| dispatched_count: AtomicUsize::new(0), | |
| dispatched_calls: Mutex::new(Vec::new()), | |
| cancel_on_all_dispatched, | |
| cancel_on_prepare_step: false, | |
| direct_tool_batching: true, | |
| model_stream: Mutex::new(None), | |
| on_now: Mutex::new(None), | |
| } | |
| } | |
| fn dispatched(&self) -> Vec<(String, Instant)> { | |
| self.dispatched_calls.lock().unwrap().clone() | |
| } | |
| } | |
| impl DriverPorts for MockDirectPorts { | |
| fn handoff_checkpoint<'a>( | |
| &'a self, | |
| _view: &'a RunView, | |
| _baseline: ContentBlob, | |
| _target: maka_agent_facts::configuration::ModelSelection, | |
| _candidate: Option<maka_agent_facts::context::SummaryOrigin>, | |
| ) -> BoxFuture<'a, Result<(), RunError>> { | |
| Box::pin(async { unreachable!("unexpected handoff_checkpoint") }) | |
| } | |
| fn external(&self) -> Option<Arc<dyn ExternalPorts>> { | |
| None | |
| } | |
| fn cells(&self) -> Option<Arc<dyn CellPorts>> { | |
| None | |
| } | |
| fn direct_tool_batching(&self) -> bool { | |
| self.direct_tool_batching | |
| } | |
| fn publication(&self) -> Option<Arc<dyn ExternalPublicationPorts>> { | |
| None | |
| } | |
| fn now(&self) -> UnixMillis { | |
| if let Some(hook) = self.on_now.lock().unwrap().as_mut() { | |
| hook(); | |
| } | |
| UnixMillis(self.clock.fetch_add(1, Ordering::Relaxed)) | |
| } | |
| fn prepare_step( | |
| self: Arc<Self>, | |
| _view: RunView, | |
| _preparation: Preparation, | |
| ) -> BoxFuture<'static, Result<PreparedStep, RunError>> { | |
| Box::pin(async move { | |
| if self.cancel_on_prepare_step { | |
| self.cancel_on_all_dispatched.cancel(); | |
| tokio::task::yield_now().await; | |
| return Err(RunError::InvalidInput("test retired at next step".into())); | |
| } | |
| unreachable!("unexpected prepare_step") | |
| }) | |
| } | |
| fn assess_recovery<'a>( | |
| &'a self, | |
| _view: &'a RunView, | |
| _attempt: ModelAttemptId, | |
| _request: RequestSpec, | |
| ) -> BoxFuture<'a, Result<RecoveryEvidence, RunError>> { | |
| Box::pin(async move { | |
| if self.cancel_on_prepare_step { | |
| return Ok(RecoveryEvidence { | |
| recovery: AttemptRecovery::ContinueFromHistory { not_before: None }, | |
| contents: vec![], | |
| }); | |
| } | |
| unreachable!("unexpected assess_recovery") | |
| }) | |
| } | |
| fn validate_transport_selection<'a>( | |
| &'a self, | |
| _view: &'a RunView, | |
| _attempt: ModelAttemptId, | |
| _phase: maka_agent_facts::model::retry_transport::RetryTransportPhase, | |
| ) -> BoxFuture<'a, Result<(), RunError>> { | |
| Box::pin(async { Ok(()) }) | |
| } | |
| fn start_model( | |
| &self, | |
| _run: RunId, | |
| _attempt: ModelAttemptId, | |
| _input: AdmittedModelInput, | |
| witness: crate::ModelWitness, | |
| ) -> BoxFuture<'_, Result<ModelConnection, RunError>> { | |
| let cfg = self | |
| .model_stream | |
| .lock() | |
| .unwrap() | |
| .take() | |
| .expect("start_model configured"); | |
| Box::pin(async move { | |
| let stream = futures_util::stream::once(async move { | |
| let mut last_fact = None; | |
| for (index, id) in cfg.call_ids.iter().enumerate() { | |
| let part = ModelPart::ToolCall { | |
| call: ModelToolCall { | |
| id: id.clone(), | |
| name: "read".into(), | |
| input: ToolInput::Json(serde_json::json!({"index": index})), | |
| provider_options: None, | |
| provider_executed: false, | |
| }, | |
| }; | |
| let fact = witness | |
| .part(index as u64, part, None, UnixMillis(10 + index as i64)) | |
| .await?; | |
| last_fact = Some(fact); | |
| } | |
| for notify in cfg.started { | |
| notify.notified().await; | |
| } | |
| if cfg.close_with_length { | |
| let protocol = serde_json::to_value(ModelClosureProtocol { | |
| model_time_ms: Some(10), | |
| finish_reason: ModelFinishReason::Length, | |
| provider_options: None, | |
| cache_read_reported: None, | |
| response_id: Some("resp-length".into()), | |
| model: Some("test".into()), | |
| timestamp: None, | |
| compaction: None, | |
| summary: None, | |
| }) | |
| .unwrap(); | |
| witness | |
| .closed_with_all( | |
| None, | |
| vec![], | |
| Outcome::Success, | |
| None, | |
| ModelUsage::default(), | |
| protocol, | |
| Some(OperationCleanup::Confirmed), | |
| UnixMillis(50), | |
| ) | |
| .await?; | |
| } else { | |
| witness | |
| .closed_with_all( | |
| None, | |
| vec![], | |
| Outcome::Aborted, | |
| Some(ModelClosure::STEERED_DIAGNOSTIC.into()), | |
| ModelUsage::default(), | |
| serde_json::json!({}), | |
| Some(OperationCleanup::Confirmed), | |
| UnixMillis(50), | |
| ) | |
| .await?; | |
| } | |
| cfg.gate.notify_waiters(); | |
| Ok(ModelObservation::Recorded { | |
| fact: last_fact.expect("emitted at least one tool call"), | |
| }) | |
| }) | |
| .boxed(); | |
| Ok(stream) | |
| }) | |
| } | |
| fn observe_model( | |
| &self, | |
| _run: RunId, | |
| _attempt: ModelAttemptId, | |
| _descriptor: ContentRef, | |
| _after_index: u64, | |
| _witness: crate::ModelWitness, | |
| ) -> BoxFuture<'_, Result<ModelConnection, RunError>> { | |
| Box::pin(async { unreachable!("unexpected observe_model") }) | |
| } | |
| fn decide_tool<'a>( | |
| &'a self, | |
| _view: &'a RunView, | |
| tool: &'a Tool, | |
| ) -> BoxFuture<'a, Result<PreparedDecision, RunError>> { | |
| Box::pin(async move { | |
| let behavior = self | |
| .behaviors | |
| .get(&tool.key.call) | |
| .cloned() | |
| .unwrap_or_default(); | |
| if let Some(reason) = behavior.decide_blocked { | |
| if let Some(started) = &behavior.on_prevalidate_start { | |
| started.notify_one(); | |
| } | |
| if let Some(gate) = &behavior.prevalidate_gate { | |
| gate.notified().await; | |
| } | |
| if let Some(finish) = &behavior.on_prevalidate_finish { | |
| finish.notify_one(); | |
| } | |
| return Err(RunError::Blocked(reason)); | |
| } | |
| let input = | |
| ContentBlob::json(tool.call.input.as_json().unwrap_or(&serde_json::json!({})))?; | |
| Ok(PreparedDecision { | |
| decision: ToolDecision::Approved { | |
| semantics: behavior.semantics.unwrap_or(ToolSemantics::Parallel), | |
| input: input.reference().clone(), | |
| resources: vec![], | |
| approval: behavior.approval, | |
| display: Default::default(), | |
| }, | |
| contents: vec![input], | |
| }) | |
| }) | |
| } | |
| fn prevalidate_decided_tool<'a>( | |
| &'a self, | |
| _view: &'a RunView, | |
| tool: &'a Tool, | |
| decision: &'a PreparedDecision, | |
| ) -> BoxFuture<'a, Result<Option<PrevalidatedTool>, RunError>> { | |
| Box::pin(async move { | |
| if !matches!( | |
| decision.decision, | |
| ToolDecision::Approved { approval: None, .. } | |
| ) { | |
| return Ok(None); | |
| } | |
| let behavior = self | |
| .behaviors | |
| .get(&tool.key.call) | |
| .cloned() | |
| .unwrap_or_default(); | |
| if let Some(started) = &behavior.on_prevalidate_start { | |
| started.notify_one(); | |
| } | |
| if let Some(gate) = &behavior.prevalidate_gate { | |
| gate.notified().await; | |
| } | |
| if let Some(token) = &behavior.cancel_on_prevalidate_finish { | |
| token.cancel(); | |
| } | |
| if let Some(finish) = &behavior.on_prevalidate_finish { | |
| finish.notify_one(); | |
| } | |
| match behavior.prevalidate_outcome { | |
| None => Ok(Some(PrevalidatedTool::Allowed)), | |
| Some(MockPrevalidateOutcome::Blocked(reason)) => { | |
| Ok(Some(PrevalidatedTool::Blocked(*reason))) | |
| } | |
| Some(MockPrevalidateOutcome::ErrBlocked(reason)) => Err(RunError::Blocked(reason)), | |
| Some(MockPrevalidateOutcome::Denied(rejection)) => { | |
| Ok(Some(PrevalidatedTool::Denied(rejection))) | |
| } | |
| } | |
| }) | |
| } | |
| fn validate_tool<'a>( | |
| &'a self, | |
| _view: &'a RunView, | |
| _tool: &'a Tool, | |
| ) -> BoxFuture<'a, Result<ToolValidation, RunError>> { | |
| Box::pin(async { Ok(ToolValidation::Allowed) }) | |
| } | |
| fn lookup_original( | |
| &self, | |
| _run: RunId, | |
| _key: ToolKey, | |
| ) -> BoxFuture<'_, Result<OriginalLookup, RunError>> { | |
| Box::pin(async { Ok(OriginalLookup::Absent) }) | |
| } | |
| fn dispatch_tool( | |
| &self, | |
| _run: RunId, | |
| tool: Tool, | |
| ) -> BoxFuture<'_, Result<DispatchOutcome, RunError>> { | |
| Box::pin(async move { | |
| let behavior = self | |
| .behaviors | |
| .get(&tool.key.call) | |
| .cloned() | |
| .unwrap_or_default(); | |
| self.dispatched_calls | |
| .lock() | |
| .unwrap() | |
| .push((tool.key.call.clone(), Instant::now())); | |
| if let Some(notify) = &behavior.on_dispatch { | |
| notify.notify_one(); | |
| } | |
| if let Some(barrier) = &behavior.dispatch_barrier { | |
| barrier.wait().await; | |
| } else { | |
| // Realistic async Host yield so concurrently dispatched siblings all start. | |
| tokio::task::yield_now().await; | |
| } | |
| let count = self.dispatched_count.fetch_add(1, Ordering::SeqCst) + 1; | |
| if self.expected_dispatches > 0 && count >= self.expected_dispatches { | |
| self.cancel_on_all_dispatched.cancel(); | |
| } | |
| Ok(DispatchOutcome::Original(OperationReply { | |
| reference: RecoveryRef { | |
| source: DeploymentRef { | |
| state_domain: "1".repeat(64), | |
| deployment: Uuid::new_v4(), | |
| revision: 1, | |
| }, | |
| namespace: InstanceId(vec![Uuid::new_v4()]), | |
| export: "mock".into(), | |
| method: "read".into(), | |
| operation: Uuid::new_v4(), | |
| fingerprint: format!("sha256-{}", "2".repeat(64)), | |
| contract: RecoveryContract { | |
| name: "mock.Read".into(), | |
| version: 1, | |
| transport: Transport::Remote, | |
| digest: format!("sha256-{}", "3".repeat(64)), | |
| }, | |
| recovery: RecoveryProtocol::JournalV1, | |
| }, | |
| receipt: Receipt::Recorded { | |
| outcome: OperationOutcome::Returned { | |
| result: OperationResult::Success { | |
| value: serde_json::json!({"ok": true}), | |
| }, | |
| }, | |
| cleanup: OperationCleanup::Confirmed, | |
| }, | |
| })) | |
| }) | |
| } | |
| fn observe_operation( | |
| &self, | |
| _reference: RecoveryRef, | |
| ) -> BoxFuture<'_, Result<OperationReply, RunError>> { | |
| Box::pin(async { unreachable!("unexpected observe_operation") }) | |
| } | |
| fn cancel_live(&self, _run: RunId) {} | |
| fn cancel_model( | |
| &self, | |
| _run: RunId, | |
| _attempt: ModelAttemptId, | |
| ) -> BoxFuture<'_, Result<(), RunError>> { | |
| Box::pin(async { Ok(()) }) | |
| } | |
| } | |
| async fn setup_attempt_with_tools( | |
| call_ids: &[&str], | |
| close_attempt: bool, | |
| cleanup: Option<OperationCleanup>, | |
| ) -> TestResult<( | |
| tempfile::TempDir, | |
| RootStore, | |
| Store, | |
| DriverClaim, | |
| ModelAttemptId, | |
| ModelWitness, | |
| )> { | |
| let temp = tempfile::tempdir()?; | |
| let base = temp.path().to_path_buf(); | |
| let owner = tokio::task::spawn_blocking(move || { | |
| RootOwner::create( | |
| &base.join("root"), | |
| &RootNamespaces { | |
| ownership: base.join("owners"), | |
| control: base.join("control"), | |
| }, | |
| ) | |
| }) | |
| .await??; | |
| let mut migrations = maka_event_log::ROOT_MIGRATIONS.to_vec(); | |
| migrations.extend_from_slice(maka_agent_state::MIGRATIONS); | |
| let root = RootStore::open(Arc::new(owner), &migrations).await?; | |
| let data = root.data_writer()?; | |
| let store = Store::new(data.clone(), DriverDomain::new(data)?)?; | |
| let mut policy = policy_view(None); | |
| let empty = ContentBlob::new(vec![]); | |
| let tool_selection = ContentBlob::json(&serde_json::json!({ | |
| "definitions": [], "directOnly": [], "services": [], "internalBindings": {} | |
| }))?; | |
| let input = ContentBlob::json(&RunInput::Message { | |
| content: "direct batch admission fixture".to_string().into(), | |
| request_fingerprint: None, | |
| source_messages: vec![], | |
| })?; | |
| policy.spec.tool_selection = tool_selection.reference().clone(); | |
| policy.spec.input = input.reference().clone(); | |
| let spec = ContentBlob::json(&policy.spec)?; | |
| apply_policy_fact( | |
| &mut policy, | |
| Fact::RunAdmitted { | |
| spec: spec.reference().clone(), | |
| }, | |
| ); | |
| let (_, mut request, attempt) = model_closure( | |
| policy.clone(), | |
| ModelPurpose::Main, | |
| ModelFinishReason::ToolCalls, | |
| Outcome::Success, | |
| false, | |
| ); | |
| let admission = Admission::new( | |
| policy.spec, | |
| UnixMillis(1), | |
| vec![empty, tool_selection, input], | |
| ); | |
| let run = admission.run(); | |
| store.admit(admission).await?; | |
| let claim = store.claim(run).await?; | |
| let provenance = ContentBlob::json(&serde_json::json!({ | |
| "estimatedInputTokens": 0, | |
| "breakdown": maka_agent_facts::context::PreparedContextBreakdown::default(), | |
| "modelContext": null, | |
| "previousCheckpointId": null, | |
| }))?; | |
| let surface = ContentBlob::json(&maka_agent_facts::composition::CompositionSurface { | |
| system_prompt: None, | |
| tools: vec![], | |
| sources: vec![], | |
| })?; | |
| request.composition.surface = surface.reference().clone(); | |
| request.provenance = provenance.reference().clone(); | |
| let encoded = ContentBlob::json(&request)?; | |
| let view = store.frontier(run).await?; | |
| store | |
| .append( | |
| &claim, | |
| (&view).into(), | |
| vec![ | |
| Change::new( | |
| Fact::StepPrepared { | |
| step: request.step, | |
| request: encoded.reference().clone(), | |
| adjudications: vec![], | |
| }, | |
| UnixMillis(2), | |
| ), | |
| Change::new( | |
| Fact::ModelAttemptPrepared { | |
| attempt, | |
| step: request.step, | |
| }, | |
| UnixMillis(2), | |
| ), | |
| Change::new( | |
| Fact::ModelAttemptAdmitted { | |
| attempt, | |
| upstream: serde_json::json!({"typed": "mock-model"}), | |
| }, | |
| UnixMillis(2), | |
| ), | |
| ], | |
| vec![encoded, provenance, surface], | |
| ) | |
| .await?; | |
| let witness = ModelWitness::new(store.clone(), claim.clone(), attempt); | |
| let parts: Vec<_> = call_ids | |
| .iter() | |
| .enumerate() | |
| .map(|(index, id)| { | |
| ( | |
| index as u64, | |
| ModelPart::ToolCall { | |
| call: ModelToolCall { | |
| id: (*id).to_string(), | |
| name: "read".into(), | |
| input: ToolInput::Json(serde_json::json!({"index": index})), | |
| provider_options: None, | |
| provider_executed: false, | |
| }, | |
| }, | |
| None, | |
| ) | |
| }) | |
| .collect(); | |
| if close_attempt { | |
| let protocol = serde_json::to_value(ModelClosureProtocol { | |
| model_time_ms: Some(10), | |
| finish_reason: ModelFinishReason::ToolCalls, | |
| provider_options: None, | |
| cache_read_reported: None, | |
| response_id: Some("resp-batch".into()), | |
| model: Some("test".into()), | |
| timestamp: None, | |
| compaction: None, | |
| summary: None, | |
| })?; | |
| witness | |
| .closed_with_all( | |
| Some(UnixMillis(3)), | |
| parts, | |
| Outcome::Success, | |
| None, | |
| ModelUsage { | |
| input_tokens: Some(10), | |
| output_tokens: Some(10), | |
| ..Default::default() | |
| }, | |
| protocol, | |
| cleanup, | |
| UnixMillis(3), | |
| ) | |
| .await?; | |
| } else { | |
| for (index, part, _) in parts { | |
| witness.part(index, part, None, UnixMillis(3)).await?; | |
| } | |
| } | |
| Ok((temp, root, store, claim, attempt, witness)) | |
| } | |
| #[tokio::test] | |
| async fn multi_tool_parallel_batch_admits_in_one_publish_and_dispatches_concurrently() | |
| -> TestResult<()> { | |
| let call_names: Vec<String> = (0..16).map(|i| format!("call-{i:02}")).collect(); | |
| let call_refs: Vec<&str> = call_names.iter().map(String::as_str).collect(); | |
| let (_temp, root, store, claim, _attempt, witness) = | |
| setup_attempt_with_tools(&call_refs, true, Some(OperationCleanup::Confirmed)).await?; | |
| let run = claim.run(); | |
| let cancel = CancellationToken::new(); | |
| let barrier = Arc::new(Barrier::new(16)); | |
| let mut behaviors = BTreeMap::new(); | |
| for name in &call_names { | |
| behaviors.insert( | |
| name.clone(), | |
| ToolBehavior { | |
| dispatch_barrier: Some(barrier.clone()), | |
| ..Default::default() | |
| }, | |
| ); | |
| } | |
| let ports = Arc::new(MockDirectPorts::new(behaviors, 16, cancel.clone())); | |
| let res = AssertUnwindSafe(async { | |
| let exit = tokio::time::timeout( | |
| Duration::from_secs(10), | |
| Engine::new(store.clone()).drive(claim, ports.clone(), cancel), | |
| ) | |
| .await??; | |
| assert!(matches!(exit, DriverExit::Retired { .. })); | |
| let dispatched = ports.dispatched(); | |
| assert_eq!(dispatched.len(), 16); | |
| let history = store.history(run, 0, 200).await?; | |
| let admit_batches: BTreeSet<i64> = history | |
| .iter() | |
| .filter(|f| matches!(f.fact, Fact::ToolAdmitted { .. })) | |
| .map(|f| f.at.0) | |
| .collect(); | |
| let decided_count = history | |
| .iter() | |
| .filter(|f| matches!(f.fact, Fact::ToolDecided { .. })) | |
| .count(); | |
| let admit_count = history | |
| .iter() | |
| .filter(|f| matches!(f.fact, Fact::ToolAdmitted { .. })) | |
| .count(); | |
| assert_eq!(decided_count, 16); | |
| assert_eq!(admit_count, 16); | |
| assert_eq!( | |
| admit_batches.len(), | |
| 1, | |
| "all 16 ready independent parallel tools must commit in one publish" | |
| ); | |
| Ok::<_, Box<dyn std::error::Error + Send + Sync>>(()) | |
| }) | |
| .catch_unwind() | |
| .await; | |
| drop((store, witness)); | |
| root.close().await?; | |
| match res { | |
| Ok(r) => r?, | |
| Err(p) => std::panic::resume_unwind(p), | |
| } | |
| Ok(()) | |
| } | |
| #[tokio::test] | |
| async fn single_tool_and_fast_sibling_admit_without_waiting_for_slow_sibling() -> TestResult<()> { | |
| // Part A: single tool commits immediately in 1 publish without extra wait. | |
| { | |
| let (_temp, root, store, claim, _attempt, witness) = | |
| setup_attempt_with_tools(&["single-0"], true, Some(OperationCleanup::Confirmed)) | |
| .await?; | |
| let run = claim.run(); | |
| let cancel = CancellationToken::new(); | |
| let ports = Arc::new(MockDirectPorts::new(BTreeMap::new(), 1, cancel.clone())); | |
| let res = AssertUnwindSafe(async { | |
| let exit = Engine::new(store.clone()) | |
| .drive(claim, ports.clone(), cancel) | |
| .await?; | |
| assert!(matches!(exit, DriverExit::Retired { .. })); | |
| let dispatched = ports.dispatched(); | |
| assert_eq!(dispatched.len(), 1); | |
| let history = store.history(run, 0, 64).await?; | |
| let admit_batches: BTreeSet<i64> = history | |
| .iter() | |
| .filter(|f| matches!(f.fact, Fact::ToolAdmitted { .. })) | |
| .map(|f| f.at.0) | |
| .collect(); | |
| assert_eq!(admit_batches.len(), 1); | |
| Ok::<_, Box<dyn std::error::Error + Send + Sync>>(()) | |
| }) | |
| .catch_unwind() | |
| .await; | |
| drop((store, witness)); | |
| root.close().await?; | |
| match res { | |
| Ok(r) => r?, | |
| Err(p) => std::panic::resume_unwind(p), | |
| } | |
| } | |
| // Part B: fast sibling must dispatch BEFORE slow sibling's prevalidation is unblocked. | |
| { | |
| let (_temp, root, store, claim, _attempt, witness) = | |
| setup_attempt_with_tools(&["fast", "slow"], true, Some(OperationCleanup::Confirmed)) | |
| .await?; | |
| let run = claim.run(); | |
| let cancel = CancellationToken::new(); | |
| let slow_gate = Arc::new(Notify::new()); | |
| let mut behaviors = BTreeMap::new(); | |
| // Fast sibling notifies slow_gate ONLY after fast enters dispatch_tool. | |
| behaviors.insert( | |
| "fast".into(), | |
| ToolBehavior { | |
| on_dispatch: Some(slow_gate.clone()), | |
| ..Default::default() | |
| }, | |
| ); | |
| behaviors.insert( | |
| "slow".into(), | |
| ToolBehavior { | |
| prevalidate_gate: Some(slow_gate.clone()), | |
| ..Default::default() | |
| }, | |
| ); | |
| let ports = Arc::new(MockDirectPorts::new(behaviors, 2, cancel.clone())); | |
| let res = AssertUnwindSafe(async { | |
| let exit = tokio::time::timeout( | |
| Duration::from_secs(5), | |
| Engine::new(store.clone()).drive(claim, ports.clone(), cancel), | |
| ) | |
| .await??; | |
| assert!(matches!(exit, DriverExit::Retired { .. })); | |
| let dispatched = ports.dispatched(); | |
| assert_eq!(dispatched.len(), 2); | |
| assert_eq!( | |
| dispatched[0].0, "fast", | |
| "fast sibling must dispatch immediately without waiting on slow sibling" | |
| ); | |
| assert_eq!(dispatched[1].0, "slow"); | |
| let history = store.history(run, 0, 100).await?; | |
| let admit_batches: BTreeSet<i64> = history | |
| .iter() | |
| .filter(|f| matches!(f.fact, Fact::ToolAdmitted { .. })) | |
| .map(|f| f.at.0) | |
| .collect(); | |
| assert_eq!( | |
| admit_batches.len(), | |
| 2, | |
| "fast and slow siblings must commit in separate publishes with no waiting" | |
| ); | |
| Ok::<_, Box<dyn std::error::Error + Send + Sync>>(()) | |
| }) | |
| .catch_unwind() | |
| .await; | |
| drop((store, witness)); | |
| root.close().await?; | |
| match res { | |
| Ok(r) => r?, | |
| Err(p) => std::panic::resume_unwind(p), | |
| } | |
| } | |
| Ok(()) | |
| } | |
| #[tokio::test] | |
| async fn mixed_approval_and_exclusive_step_stay_on_original_paths() -> TestResult<()> { | |
| let (_temp, root, store, claim, attempt, witness) = setup_attempt_with_tools( | |
| &["par-1", "needs-approval", "exclusive", "par-2"], | |
| true, | |
| Some(OperationCleanup::Confirmed), | |
| ) | |
| .await?; | |
| let run = claim.run(); | |
| let cancel = CancellationToken::new(); | |
| let approval_id = ApprovalId::new(); | |
| let mut behaviors = BTreeMap::new(); | |
| behaviors.insert( | |
| "needs-approval".into(), | |
| ToolBehavior { | |
| approval: Some(approval_id), | |
| ..Default::default() | |
| }, | |
| ); | |
| behaviors.insert( | |
| "exclusive".into(), | |
| ToolBehavior { | |
| semantics: Some(ToolSemantics::ExclusiveStep), | |
| ..Default::default() | |
| }, | |
| ); | |
| // Do not cancel on dispatch count: let the driver run until it naturally yields | |
| // DriverExit::Waiting on the approval wait while par-1, par-2, and exclusive finish. | |
| let ports = Arc::new(MockDirectPorts::new(behaviors, 0, cancel.clone())); | |
| let res = AssertUnwindSafe(async { | |
| let exit = tokio::time::timeout( | |
| Duration::from_secs(10), | |
| Engine::new(store.clone()).drive(claim, ports.clone(), cancel), | |
| ) | |
| .await??; | |
| assert!( | |
| matches!(exit, DriverExit::Waiting { .. }), | |
| "run must park waiting for approval, got {exit:?}" | |
| ); | |
| let dispatched_names: BTreeSet<String> = ports | |
| .dispatched() | |
| .into_iter() | |
| .map(|(name, _)| name) | |
| .collect(); | |
| assert_eq!( | |
| dispatched_names, | |
| BTreeSet::from([ | |
| "par-1".to_string(), | |
| "par-2".to_string(), | |
| "exclusive".to_string() | |
| ]) | |
| ); | |
| let view = store.frontier(run).await?; | |
| let approval_key = ToolKey { | |
| attempt, | |
| call: "needs-approval".into(), | |
| }; | |
| assert!(!view.tools[&tool_key(&approval_key)].admitted); | |
| assert!(view.waits.values().any(|w| { | |
| w.satisfied.is_none() | |
| && w.cancelled.is_none() | |
| && w.reason | |
| == WaitReason::Approval { | |
| approval: approval_id, | |
| } | |
| })); | |
| let history = store.history(run, 0, 200).await?; | |
| let admit_times: BTreeMap<String, i64> = history | |
| .iter() | |
| .filter_map(|f| match &f.fact { | |
| Fact::ToolAdmitted { tool } => Some((tool.call.clone(), f.at.0)), | |
| _ => None, | |
| }) | |
| .collect(); | |
| assert_eq!( | |
| admit_times["par-1"], admit_times["par-2"], | |
| "independent parallel siblings must batch into one publish" | |
| ); | |
| assert_ne!( | |
| admit_times["exclusive"], admit_times["par-1"], | |
| "ExclusiveStep tool must stay on its own publish, not merged with parallel batch" | |
| ); | |
| assert!(!admit_times.contains_key("needs-approval")); | |
| Ok::<_, Box<dyn std::error::Error + Send + Sync>>(()) | |
| }) | |
| .catch_unwind() | |
| .await; | |
| drop((store, witness)); | |
| root.close().await?; | |
| match res { | |
| Ok(r) => r?, | |
| Err(p) => std::panic::resume_unwind(p), | |
| } | |
| Ok(()) | |
| } | |
| #[tokio::test] | |
| async fn stop_during_prevalidation_fences_entire_batch() -> TestResult<()> { | |
| let call_names = ["stop-0", "stop-1", "stop-2", "stop-3"]; | |
| let (_temp, root, store, claim, _attempt, witness) = | |
| setup_attempt_with_tools(&call_names, true, Some(OperationCleanup::Confirmed)).await?; | |
| let run = claim.run(); | |
| let cancel = CancellationToken::new(); | |
| let gate = Arc::new(Notify::new()); | |
| let started: Vec<Arc<Notify>> = (0..call_names.len()) | |
| .map(|_| Arc::new(Notify::new())) | |
| .collect(); | |
| let mut behaviors = BTreeMap::new(); | |
| for (idx, name) in call_names.iter().enumerate() { | |
| behaviors.insert( | |
| (*name).to_string(), | |
| ToolBehavior { | |
| on_prevalidate_start: Some(started[idx].clone()), | |
| prevalidate_gate: Some(gate.clone()), | |
| ..Default::default() | |
| }, | |
| ); | |
| } | |
| let ports = Arc::new(MockDirectPorts::new(behaviors, 0, cancel.clone())); | |
| let store_for_stop = store.clone(); | |
| let gate_for_stop = gate.clone(); | |
| let stopper = tokio::spawn(async move { | |
| for s in started { | |
| s.notified().await; | |
| } | |
| let current = store_for_stop.frontier(run).await.unwrap(); | |
| store_for_stop | |
| .control( | |
| run, | |
| Head::from(¤t), | |
| vec![Change::new( | |
| Fact::StopRequested { | |
| diagnostic: "user stopped run during prevalidation".into(), | |
| requester: StopRequester::Internal, | |
| }, | |
| UnixMillis(50), | |
| )], | |
| vec![], | |
| ) | |
| .await | |
| .unwrap(); | |
| gate_for_stop.notify_waiters(); | |
| }); | |
| let res = AssertUnwindSafe(async { | |
| let exit = tokio::time::timeout( | |
| Duration::from_secs(10), | |
| Engine::new(store.clone()).drive(claim, ports.clone(), cancel), | |
| ) | |
| .await??; | |
| stopper.await?; | |
| assert!( | |
| matches!( | |
| exit, | |
| DriverExit::Terminal { | |
| terminal: Terminal::Cancelled, | |
| .. | |
| } | |
| ), | |
| "expected cancelled run, got {exit:?}" | |
| ); | |
| assert!( | |
| ports.dispatched().is_empty(), | |
| "no tool may dispatch after StopRequested" | |
| ); | |
| let history = store.history(run, 0, 200).await?; | |
| assert!( | |
| !history | |
| .iter() | |
| .any(|f| matches!(f.fact, Fact::ToolAdmitted { .. })), | |
| "no ToolAdmitted may commit after StopRequested" | |
| ); | |
| Ok::<_, Box<dyn std::error::Error + Send + Sync>>(()) | |
| }) | |
| .catch_unwind() | |
| .await; | |
| drop((store, witness)); | |
| root.close().await?; | |
| match res { | |
| Ok(r) => r?, | |
| Err(p) => std::panic::resume_unwind(p), | |
| } | |
| Ok(()) | |
| } | |
| #[tokio::test] | |
| async fn steering_during_prevalidation_fences_entire_batch_and_supersedes_tools() -> TestResult<()> | |
| { | |
| let call_names = ["steer-0", "steer-1", "steer-2", "steer-3"]; | |
| let temp = tempfile::tempdir()?; | |
| let base = temp.path().to_path_buf(); | |
| let owner = tokio::task::spawn_blocking(move || { | |
| RootOwner::create( | |
| &base.join("root"), | |
| &RootNamespaces { | |
| ownership: base.join("owners"), | |
| control: base.join("control"), | |
| }, | |
| ) | |
| }) | |
| .await??; | |
| let mut migrations = maka_event_log::ROOT_MIGRATIONS.to_vec(); | |
| migrations.extend_from_slice(maka_agent_state::MIGRATIONS); | |
| let root = RootStore::open(Arc::new(owner), &migrations).await?; | |
| let data = root.data_writer()?; | |
| let store = Store::new(data.clone(), DriverDomain::new(data)?)?; | |
| let mut policy = policy_view(None); | |
| let empty = ContentBlob::new(vec![]); | |
| let tool_selection = ContentBlob::json(&serde_json::json!({ | |
| "definitions": [], "directOnly": [], "services": [], "internalBindings": {} | |
| }))?; | |
| let input = ContentBlob::json(&RunInput::Message { | |
| content: "direct steering batch fixture".to_string().into(), | |
| request_fingerprint: None, | |
| source_messages: vec![], | |
| })?; | |
| policy.spec.tool_selection = tool_selection.reference().clone(); | |
| policy.spec.input = input.reference().clone(); | |
| let spec = ContentBlob::json(&policy.spec)?; | |
| apply_policy_fact( | |
| &mut policy, | |
| Fact::RunAdmitted { | |
| spec: spec.reference().clone(), | |
| }, | |
| ); | |
| let (_, mut request, _unused_attempt) = model_closure( | |
| policy.clone(), | |
| ModelPurpose::Main, | |
| ModelFinishReason::ToolCalls, | |
| Outcome::Success, | |
| false, | |
| ); | |
| let admission = Admission::new( | |
| policy.spec, | |
| UnixMillis(1), | |
| vec![empty, tool_selection, input], | |
| ); | |
| let run = admission.run(); | |
| store.admit(admission).await?; | |
| let claim = store.claim(run).await?; | |
| let provenance = ContentBlob::json(&serde_json::json!({ | |
| "estimatedInputTokens": 0, | |
| "breakdown": maka_agent_facts::context::PreparedContextBreakdown::default(), | |
| "modelContext": null, | |
| "previousCheckpointId": null, | |
| }))?; | |
| let surface = ContentBlob::json(&maka_agent_facts::composition::CompositionSurface { | |
| system_prompt: None, | |
| tools: vec![], | |
| sources: vec![], | |
| })?; | |
| let raw_request = ContentBlob::json(&serde_json::json!({"messages": []}))?; | |
| request.request = raw_request.reference().clone(); | |
| request.composition.surface = surface.reference().clone(); | |
| request.provenance = provenance.reference().clone(); | |
| let encoded = ContentBlob::json(&request)?; | |
| let view = store.frontier(run).await?; | |
| store | |
| .append( | |
| &claim, | |
| (&view).into(), | |
| vec![Change::new( | |
| Fact::StepPrepared { | |
| step: request.step, | |
| request: encoded.reference().clone(), | |
| adjudications: vec![], | |
| }, | |
| UnixMillis(2), | |
| )], | |
| vec![encoded, provenance, surface, raw_request], | |
| ) | |
| .await?; | |
| let cancel = CancellationToken::new(); | |
| let gate = Arc::new(Notify::new()); | |
| let started: Vec<Arc<Notify>> = (0..call_names.len()) | |
| .map(|_| Arc::new(Notify::new())) | |
| .collect(); | |
| let mut behaviors = BTreeMap::new(); | |
| for (idx, name) in call_names.iter().enumerate() { | |
| behaviors.insert( | |
| (*name).to_string(), | |
| ToolBehavior { | |
| on_prevalidate_start: Some(started[idx].clone()), | |
| prevalidate_gate: Some(gate.clone()), | |
| ..Default::default() | |
| }, | |
| ); | |
| } | |
| let mut mock_ports = MockDirectPorts::new(behaviors, 0, cancel.clone()); | |
| mock_ports.cancel_on_prepare_step = true; | |
| *mock_ports.model_stream.lock().unwrap() = Some(MockModelStream { | |
| call_ids: call_names.iter().map(|s| (*s).to_string()).collect(), | |
| started, | |
| gate, | |
| close_with_length: false, | |
| }); | |
| let ports = Arc::new(mock_ports); | |
| let res = AssertUnwindSafe(async { | |
| let _ = tokio::time::timeout( | |
| Duration::from_secs(10), | |
| Engine::new(store.clone()).drive(claim, ports.clone(), cancel), | |
| ) | |
| .await?; | |
| assert!( | |
| ports.dispatched().is_empty(), | |
| "no tool may dispatch after model attempt is steered" | |
| ); | |
| let history = store.history(run, 0, 200).await?; | |
| assert!( | |
| !history | |
| .iter() | |
| .any(|f| matches!(f.fact, Fact::ToolAdmitted { .. })), | |
| "no ToolAdmitted may commit after steering" | |
| ); | |
| let superseded: BTreeSet<String> = history | |
| .iter() | |
| .filter_map(|f| match &f.fact { | |
| Fact::ToolDecided { | |
| tool, | |
| decision: | |
| ToolDecision::Rejected { | |
| rejection: ToolRejection::Superseded, | |
| .. | |
| }, | |
| } => Some(tool.call.clone()), | |
| _ => None, | |
| }) | |
| .collect(); | |
| assert_eq!( | |
| superseded, | |
| call_names.iter().map(|s| (*s).to_string()).collect(), | |
| "all 4 tools must be rejected as Superseded after steering" | |
| ); | |
| Ok::<_, Box<dyn std::error::Error + Send + Sync>>(()) | |
| }) | |
| .catch_unwind() | |
| .await; | |
| drop(store); | |
| root.close().await?; | |
| match res { | |
| Ok(r) => r?, | |
| Err(p) => std::panic::resume_unwind(p), | |
| } | |
| Ok(()) | |
| } | |
| #[tokio::test] | |
| async fn model_cleanup_observed_does_not_conflict_with_batch_tool_admission() -> TestResult<()> { | |
| let (_temp, root, store, claim, attempt, witness) = | |
| setup_attempt_with_tools(&["c-0", "c-1"], true, None).await?; | |
| let run = claim.run(); | |
| let res = AssertUnwindSafe(async { | |
| let before = store.frontier(run).await?; | |
| assert_ne!( | |
| before.attempts[&attempt].cleanup, | |
| OperationCleanup::Confirmed | |
| ); | |
| // Confirmed cleanup lands at rev + 1 between frontier read and batch submit. | |
| let proof = witness.prepare_cleanup(OperationCleanup::Confirmed, UnixMillis(10)); | |
| proof.record().await?; | |
| let input = ContentBlob::json(&serde_json::json!({"index": 0}))?; | |
| let t0 = ToolKey { | |
| attempt, | |
| call: "c-0".into(), | |
| }; | |
| let t1 = ToolKey { | |
| attempt, | |
| call: "c-1".into(), | |
| }; | |
| let decision = ToolDecision::Approved { | |
| semantics: ToolSemantics::Parallel, | |
| input: input.reference().clone(), | |
| resources: vec![], | |
| approval: None, | |
| display: Default::default(), | |
| }; | |
| let pub_batch = PendingPublication { | |
| run, | |
| claim: Some(claim.clone()), | |
| head: Head::from(&before), | |
| changes: vec![ | |
| Change::new( | |
| Fact::ToolDecided { | |
| tool: t0.clone(), | |
| decision: decision.clone(), | |
| }, | |
| UnixMillis(11), | |
| ), | |
| Change::new(Fact::ToolAdmitted { tool: t0.clone() }, UnixMillis(11)), | |
| Change::new( | |
| Fact::ToolDecided { | |
| tool: t1.clone(), | |
| decision, | |
| }, | |
| UnixMillis(11), | |
| ), | |
| Change::new(Fact::ToolAdmitted { tool: t1.clone() }, UnixMillis(11)), | |
| ], | |
| contents: vec![input], | |
| steering: None, | |
| }; | |
| pub_batch.submit(&store).await?; | |
| let after = store.frontier(run).await?; | |
| assert!(after.tools[&tool_key(&t0)].admitted); | |
| assert!(after.tools[&tool_key(&t1)].admitted); | |
| Ok::<_, Box<dyn std::error::Error + Send + Sync>>(()) | |
| }) | |
| .catch_unwind() | |
| .await; | |
| drop((store, claim, witness)); | |
| root.close().await?; | |
| match res { | |
| Ok(r) => r?, | |
| Err(p) => std::panic::resume_unwind(p), | |
| } | |
| // Conversely, StopRequested between frontier read and batch submit must conflict. | |
| let (_temp2, root2, store2, claim2, attempt2, witness2) = | |
| setup_attempt_with_tools(&["s-0", "s-1"], true, None).await?; | |
| let run2 = claim2.run(); | |
| let res2 = AssertUnwindSafe(async { | |
| let before = store2.frontier(run2).await?; | |
| store2 | |
| .control( | |
| run2, | |
| Head::from(&before), | |
| vec![Change::new( | |
| Fact::StopRequested { | |
| diagnostic: "stop fences batch".into(), | |
| requester: StopRequester::Internal, | |
| }, | |
| UnixMillis(10), | |
| )], | |
| vec![], | |
| ) | |
| .await?; | |
| let input = ContentBlob::json(&serde_json::json!({"index": 0}))?; | |
| let t0 = ToolKey { | |
| attempt: attempt2, | |
| call: "s-0".into(), | |
| }; | |
| let t1 = ToolKey { | |
| attempt: attempt2, | |
| call: "s-1".into(), | |
| }; | |
| let decision = ToolDecision::Approved { | |
| semantics: ToolSemantics::Parallel, | |
| input: input.reference().clone(), | |
| resources: vec![], | |
| approval: None, | |
| display: Default::default(), | |
| }; | |
| let pub_batch = PendingPublication { | |
| run: run2, | |
| claim: Some(claim2.clone()), | |
| head: Head::from(&before), | |
| changes: vec![ | |
| Change::new( | |
| Fact::ToolDecided { | |
| tool: t0.clone(), | |
| decision: decision.clone(), | |
| }, | |
| UnixMillis(11), | |
| ), | |
| Change::new(Fact::ToolAdmitted { tool: t0.clone() }, UnixMillis(11)), | |
| Change::new( | |
| Fact::ToolDecided { | |
| tool: t1.clone(), | |
| decision, | |
| }, | |
| UnixMillis(11), | |
| ), | |
| Change::new(Fact::ToolAdmitted { tool: t1.clone() }, UnixMillis(11)), | |
| ], | |
| contents: vec![input], | |
| steering: None, | |
| }; | |
| let err = pub_batch | |
| .submit(&store2) | |
| .await | |
| .expect_err("StopRequested must fence batch admission with RevisionConflict"); | |
| assert!(matches!(err, StoreError::RevisionConflict { .. })); | |
| let after = store2.frontier(run2).await?; | |
| assert!(!after.tools[&tool_key(&t0)].admitted); | |
| assert!(!after.tools[&tool_key(&t1)].admitted); | |
| Ok::<_, Box<dyn std::error::Error + Send + Sync>>(()) | |
| }) | |
| .catch_unwind() | |
| .await; | |
| drop((store2, claim2, witness2)); | |
| root2.close().await?; | |
| match res2 { | |
| Ok(r) => r?, | |
| Err(p) => std::panic::resume_unwind(p), | |
| } | |
| Ok(()) | |
| } | |
| #[tokio::test] | |
| async fn code_mode_does_not_batch_multiple_ready_parallel_tools() -> TestResult<()> { | |
| let (_temp, root, store, claim, _attempt, witness) = setup_attempt_with_tools( | |
| &["exec-0", "exec-1"], | |
| true, | |
| Some(OperationCleanup::Confirmed), | |
| ) | |
| .await?; | |
| let run = claim.run(); | |
| let cancel = CancellationToken::new(); | |
| let mut mock_ports = MockDirectPorts::new(BTreeMap::new(), 2, cancel.clone()); | |
| // Explicit execution mode gate: CodeMode disables Direct Mode tool batching. | |
| mock_ports.direct_tool_batching = false; | |
| let ports = Arc::new(mock_ports); | |
| let res = AssertUnwindSafe(async { | |
| let exit = tokio::time::timeout( | |
| Duration::from_secs(10), | |
| Engine::new(store.clone()).drive(claim, ports.clone(), cancel), | |
| ) | |
| .await??; | |
| assert!(matches!(exit, DriverExit::Retired { .. })); | |
| assert_eq!(ports.dispatched().len(), 2); | |
| let history = store.history(run, 0, 128).await?; | |
| let admit_batches: BTreeSet<i64> = history | |
| .iter() | |
| .filter(|f| matches!(f.fact, Fact::ToolAdmitted { .. })) | |
| .map(|f| f.at.0) | |
| .collect(); | |
| assert_eq!( | |
| admit_batches.len(), | |
| 2, | |
| "CodeMode must not merge multiple ready Parallel tools into one batch publish" | |
| ); | |
| Ok::<_, Box<dyn std::error::Error + Send + Sync>>(()) | |
| }) | |
| .catch_unwind() | |
| .await; | |
| drop((store, witness)); | |
| root.close().await?; | |
| match res { | |
| Ok(r) => r?, | |
| Err(p) => std::panic::resume_unwind(p), | |
| } | |
| Ok(()) | |
| } | |
| #[tokio::test] | |
| async fn run_level_blocker_stops_batch_collection_without_admitting_following_sibling() | |
| -> TestResult<()> { | |
| // Part A: Ready order A (Allowed) -> B (Run-level CurrentAuthorityUnavailable) -> C (Allowed). | |
| // Collection must stop at B; C must NOT be batch-admitted alongside A. | |
| { | |
| let (_temp, root, store, claim, attempt, witness) = setup_attempt_with_tools( | |
| &["0-a", "1-b", "2-c"], | |
| true, | |
| Some(OperationCleanup::Confirmed), | |
| ) | |
| .await?; | |
| let run = claim.run(); | |
| let cancel = CancellationToken::new(); | |
| let gate_a = Arc::new(Notify::new()); | |
| let gate_b = Arc::new(Notify::new()); | |
| let gate_c = Arc::new(Notify::new()); | |
| let started_a = Arc::new(Notify::new()); | |
| let started_b = Arc::new(Notify::new()); | |
| let started_c = Arc::new(Notify::new()); | |
| let mut behaviors = BTreeMap::new(); | |
| behaviors.insert( | |
| "0-a".into(), | |
| ToolBehavior { | |
| on_prevalidate_start: Some(started_a.clone()), | |
| prevalidate_gate: Some(gate_a.clone()), | |
| on_prevalidate_finish: Some(gate_b.clone()), | |
| ..Default::default() | |
| }, | |
| ); | |
| behaviors.insert( | |
| "1-b".into(), | |
| ToolBehavior { | |
| on_prevalidate_start: Some(started_b.clone()), | |
| prevalidate_gate: Some(gate_b.clone()), | |
| on_prevalidate_finish: Some(gate_c.clone()), | |
| prevalidate_outcome: Some(MockPrevalidateOutcome::Blocked(Box::new( | |
| BlockerKind::CurrentAuthorityUnavailable { | |
| stage: AuthorityStage::ToolBindings, | |
| diagnostic: "authority unavailable".into(), | |
| }, | |
| ))), | |
| ..Default::default() | |
| }, | |
| ); | |
| behaviors.insert( | |
| "2-c".into(), | |
| ToolBehavior { | |
| on_prevalidate_start: Some(started_c.clone()), | |
| prevalidate_gate: Some(gate_c.clone()), | |
| ..Default::default() | |
| }, | |
| ); | |
| let ports = Arc::new(MockDirectPorts::new(behaviors, 0, cancel.clone())); | |
| let trigger = tokio::spawn(async move { | |
| started_a.notified().await; | |
| started_b.notified().await; | |
| started_c.notified().await; | |
| gate_a.notify_one(); | |
| }); | |
| let res = AssertUnwindSafe(async { | |
| let exit = tokio::time::timeout( | |
| Duration::from_secs(10), | |
| Engine::new(store.clone()).drive(claim, ports.clone(), cancel), | |
| ) | |
| .await??; | |
| trigger.await?; | |
| assert!( | |
| matches!(exit, DriverExit::Blocked { .. }), | |
| "expected Run to park on CurrentAuthorityUnavailable blocker, got {exit:?}" | |
| ); | |
| let dispatched_names: BTreeSet<String> = ports | |
| .dispatched() | |
| .into_iter() | |
| .map(|(name, _)| name) | |
| .collect(); | |
| assert_eq!( | |
| dispatched_names, | |
| BTreeSet::from(["0-a".to_string()]), | |
| "only 0-a before the Run-level blocker may dispatch; 2-c must not bypass 1-b" | |
| ); | |
| let history = store.history(run, 0, 200).await?; | |
| let admitted_calls: BTreeSet<String> = history | |
| .iter() | |
| .filter_map(|f| match &f.fact { | |
| Fact::ToolAdmitted { tool } => Some(tool.call.clone()), | |
| _ => None, | |
| }) | |
| .collect(); | |
| assert_eq!( | |
| admitted_calls, | |
| BTreeSet::from(["0-a".to_string()]), | |
| "2-c must have no durable ToolAdmitted fact" | |
| ); | |
| let view = store.frontier(run).await?; | |
| let c_key = ToolKey { | |
| attempt, | |
| call: "2-c".into(), | |
| }; | |
| assert!(!view.tools[&tool_key(&c_key)].admitted); | |
| assert!( | |
| view.blockers | |
| .values() | |
| .any(|b| matches!(&b.reason, BlockerKind::CurrentAuthorityUnavailable { .. })) | |
| ); | |
| Ok::<_, Box<dyn std::error::Error + Send + Sync>>(()) | |
| }) | |
| .catch_unwind() | |
| .await; | |
| drop((store, witness)); | |
| root.close().await?; | |
| match res { | |
| Ok(r) => r?, | |
| Err(p) => std::panic::resume_unwind(p), | |
| } | |
| } | |
| // Part B: Ordinary per-tool Denied between two Allowed siblings must NOT poison C; | |
| // A and C still batch-admit together while B is rejected. | |
| { | |
| let (_temp, root, store, claim, _attempt, witness) = setup_attempt_with_tools( | |
| &["0-a", "1-b", "2-c"], | |
| true, | |
| Some(OperationCleanup::Confirmed), | |
| ) | |
| .await?; | |
| let run = claim.run(); | |
| let cancel = CancellationToken::new(); | |
| let gate_a = Arc::new(Notify::new()); | |
| let gate_b = Arc::new(Notify::new()); | |
| let gate_c = Arc::new(Notify::new()); | |
| let started_a = Arc::new(Notify::new()); | |
| let started_b = Arc::new(Notify::new()); | |
| let started_c = Arc::new(Notify::new()); | |
| let mut behaviors = BTreeMap::new(); | |
| behaviors.insert( | |
| "0-a".into(), | |
| ToolBehavior { | |
| on_prevalidate_start: Some(started_a.clone()), | |
| prevalidate_gate: Some(gate_a.clone()), | |
| on_prevalidate_finish: Some(gate_b.clone()), | |
| ..Default::default() | |
| }, | |
| ); | |
| behaviors.insert( | |
| "1-b".into(), | |
| ToolBehavior { | |
| on_prevalidate_start: Some(started_b.clone()), | |
| prevalidate_gate: Some(gate_b.clone()), | |
| on_prevalidate_finish: Some(gate_c.clone()), | |
| prevalidate_outcome: Some(MockPrevalidateOutcome::Denied( | |
| ToolRejection::PolicyDenied { | |
| message: "tool denied".into(), | |
| }, | |
| )), | |
| ..Default::default() | |
| }, | |
| ); | |
| behaviors.insert( | |
| "2-c".into(), | |
| ToolBehavior { | |
| on_prevalidate_start: Some(started_c.clone()), | |
| prevalidate_gate: Some(gate_c.clone()), | |
| ..Default::default() | |
| }, | |
| ); | |
| let ports = Arc::new(MockDirectPorts::new(behaviors, 2, cancel.clone())); | |
| let trigger = tokio::spawn(async move { | |
| started_a.notified().await; | |
| started_b.notified().await; | |
| started_c.notified().await; | |
| gate_a.notify_one(); | |
| }); | |
| let res = AssertUnwindSafe(async { | |
| let exit = tokio::time::timeout( | |
| Duration::from_secs(10), | |
| Engine::new(store.clone()).drive(claim, ports.clone(), cancel), | |
| ) | |
| .await??; | |
| trigger.await?; | |
| assert!(matches!(exit, DriverExit::Retired { .. })); | |
| let history = store.history(run, 0, 200).await?; | |
| let admit_times: BTreeMap<String, i64> = history | |
| .iter() | |
| .filter_map(|f| match &f.fact { | |
| Fact::ToolAdmitted { tool } => Some((tool.call.clone(), f.at.0)), | |
| _ => None, | |
| }) | |
| .collect(); | |
| assert_eq!(admit_times.len(), 2); | |
| assert_eq!( | |
| admit_times["0-a"], admit_times["2-c"], | |
| "ordinary per-tool Denied must not split independent siblings A and C" | |
| ); | |
| assert!(!admit_times.contains_key("1-b")); | |
| Ok::<_, Box<dyn std::error::Error + Send + Sync>>(()) | |
| }) | |
| .catch_unwind() | |
| .await; | |
| drop((store, witness)); | |
| root.close().await?; | |
| match res { | |
| Ok(r) => r?, | |
| Err(p) => std::panic::resume_unwind(p), | |
| } | |
| } | |
| Ok(()) | |
| } | |
| #[tokio::test] | |
| async fn physical_cancellation_during_drain_aborts_batch_before_writer_commit() -> TestResult<()> { | |
| let (_temp, root, store, claim, _attempt, witness) = | |
| setup_attempt_with_tools(&["0-a", "1-b"], true, Some(OperationCleanup::Confirmed)).await?; | |
| let run = claim.run(); | |
| let cancel = CancellationToken::new(); | |
| let gate_a = Arc::new(Notify::new()); | |
| let gate_b = Arc::new(Notify::new()); | |
| let started_a = Arc::new(Notify::new()); | |
| let started_b = Arc::new(Notify::new()); | |
| // 0-a returns Allowed while cancel is still false, entering complete_next; | |
| // during complete_next's non-blocking drain, 1-b triggers physical cancellation | |
| // (without writing any durable StopRequested). The live token check must abort | |
| // the entire batch before handing off to the writer. | |
| let mut behaviors = BTreeMap::new(); | |
| behaviors.insert( | |
| "0-a".into(), | |
| ToolBehavior { | |
| on_prevalidate_start: Some(started_a.clone()), | |
| prevalidate_gate: Some(gate_a.clone()), | |
| on_prevalidate_finish: Some(gate_b.clone()), | |
| ..Default::default() | |
| }, | |
| ); | |
| behaviors.insert( | |
| "1-b".into(), | |
| ToolBehavior { | |
| on_prevalidate_start: Some(started_b.clone()), | |
| prevalidate_gate: Some(gate_b.clone()), | |
| cancel_on_prevalidate_finish: Some(cancel.clone()), | |
| ..Default::default() | |
| }, | |
| ); | |
| let ports = Arc::new(MockDirectPorts::new(behaviors, 0, cancel.clone())); | |
| let trigger = tokio::spawn(async move { | |
| started_a.notified().await; | |
| started_b.notified().await; | |
| gate_a.notify_one(); | |
| }); | |
| let res = AssertUnwindSafe(async { | |
| let exit = tokio::time::timeout( | |
| Duration::from_secs(10), | |
| Engine::new(store.clone()).drive(claim, ports.clone(), cancel), | |
| ) | |
| .await??; | |
| trigger.await?; | |
| assert!( | |
| matches!(exit, DriverExit::Retired { .. }), | |
| "expected Retired exit on physical cancellation during drain, got {exit:?}" | |
| ); | |
| assert!( | |
| ports.dispatched().is_empty(), | |
| "no tool may dispatch when physical cancellation fires during drain" | |
| ); | |
| let history = store.history(run, 0, 128).await?; | |
| assert!( | |
| !history | |
| .iter() | |
| .any(|f| matches!(f.fact, Fact::ToolAdmitted { .. })), | |
| "no ToolAdmitted may commit when physical cancellation fires during drain" | |
| ); | |
| Ok::<_, Box<dyn std::error::Error + Send + Sync>>(()) | |
| }) | |
| .catch_unwind() | |
| .await; | |
| drop((store, witness)); | |
| root.close().await?; | |
| match res { | |
| Ok(r) => r?, | |
| Err(p) => std::panic::resume_unwind(p), | |
| } | |
| Ok(()) | |
| } | |
| #[tokio::test(flavor = "multi_thread", worker_threads = 2)] | |
| async fn run_level_blocker_non_control_revision_conflict_still_blocks_following_sibling() | |
| -> TestResult<()> { | |
| use std::sync::atomic::AtomicBool; | |
| enum BlockerShape { | |
| PrevalidateOk, | |
| PrevalidateErr, | |
| DecideErr, | |
| } | |
| for shape in [ | |
| BlockerShape::PrevalidateOk, | |
| BlockerShape::PrevalidateErr, | |
| BlockerShape::DecideErr, | |
| ] { | |
| // Attempt starts with unconfirmed cleanup so we can inject ModelCleanupObserved(Confirmed) | |
| // right between B's frontier read and B's Fact::Blocked write (non-control RevisionConflict). | |
| let (_temp, root, store, claim, attempt, witness) = | |
| setup_attempt_with_tools(&["0-a", "1-b", "2-c"], true, None).await?; | |
| let run = claim.run(); | |
| let cancel = CancellationToken::new(); | |
| let gate_a = Arc::new(Notify::new()); | |
| let gate_b = Arc::new(Notify::new()); | |
| let gate_c = Arc::new(Notify::new()); | |
| let started_a = Arc::new(Notify::new()); | |
| let started_b = Arc::new(Notify::new()); | |
| let started_c = Arc::new(Notify::new()); | |
| let b_finished = Arc::new(Notify::new()); | |
| let b_ready_flag = Arc::new(AtomicBool::new(false)); | |
| let conflict_injected = Arc::new(AtomicBool::new(false)); | |
| let reason = Box::new(BlockerKind::CurrentAuthorityUnavailable { | |
| stage: AuthorityStage::ToolBindings, | |
| diagnostic: "authority unavailable".into(), | |
| }); | |
| let mut b_behavior = ToolBehavior { | |
| on_prevalidate_start: Some(started_b.clone()), | |
| prevalidate_gate: Some(gate_b.clone()), | |
| on_prevalidate_finish: Some(b_finished.clone()), | |
| ..Default::default() | |
| }; | |
| match shape { | |
| BlockerShape::PrevalidateOk => { | |
| b_behavior.prevalidate_outcome = Some(MockPrevalidateOutcome::Blocked(reason)); | |
| } | |
| BlockerShape::PrevalidateErr => { | |
| b_behavior.prevalidate_outcome = Some(MockPrevalidateOutcome::ErrBlocked(reason)); | |
| } | |
| BlockerShape::DecideErr => { | |
| b_behavior.decide_blocked = Some(reason); | |
| } | |
| } | |
| let mut behaviors = BTreeMap::new(); | |
| behaviors.insert( | |
| "0-a".into(), | |
| ToolBehavior { | |
| on_prevalidate_start: Some(started_a.clone()), | |
| prevalidate_gate: Some(gate_a.clone()), | |
| on_prevalidate_finish: Some(gate_b.clone()), | |
| ..Default::default() | |
| }, | |
| ); | |
| behaviors.insert("1-b".into(), b_behavior); | |
| behaviors.insert( | |
| "2-c".into(), | |
| ToolBehavior { | |
| on_prevalidate_start: Some(started_c.clone()), | |
| prevalidate_gate: Some(gate_c.clone()), | |
| ..Default::default() | |
| }, | |
| ); | |
| let mock_ports = MockDirectPorts::new(behaviors, 0, cancel.clone()); | |
| let b_ready_for_hook = b_ready_flag.clone(); | |
| let conflict_for_hook = conflict_injected.clone(); | |
| let witness_for_hook = witness.clone(); | |
| let post_b_now_calls = AtomicUsize::new(0); | |
| *mock_ports.on_now.lock().unwrap() = Some(Box::new(move || { | |
| if !b_ready_for_hook.load(Ordering::SeqCst) { | |
| return; | |
| } | |
| // Call 1 after B finishes is complete_decided_batch([0-a]); | |
| // Call 2 is complete(1-b) right after store.frontier(run) and before try_block. | |
| if post_b_now_calls.fetch_add(1, Ordering::SeqCst) == 1 { | |
| let proof = | |
| witness_for_hook.prepare_cleanup(OperationCleanup::Confirmed, UnixMillis(60)); | |
| tokio::task::block_in_place(|| { | |
| tokio::runtime::Handle::current() | |
| .block_on(proof.record()) | |
| .unwrap(); | |
| }); | |
| conflict_for_hook.store(true, Ordering::SeqCst); | |
| } | |
| })); | |
| let ports = Arc::new(mock_ports); | |
| let b_ready_for_trigger = b_ready_flag.clone(); | |
| let trigger = tokio::spawn(async move { | |
| started_a.notified().await; | |
| started_b.notified().await; | |
| started_c.notified().await; | |
| gate_a.notify_one(); | |
| b_finished.notified().await; | |
| b_ready_for_trigger.store(true, Ordering::SeqCst); | |
| gate_c.notify_one(); | |
| }); | |
| let res = AssertUnwindSafe(async { | |
| let exit = tokio::time::timeout( | |
| Duration::from_secs(10), | |
| Engine::new(store.clone()).drive(claim, ports.clone(), cancel), | |
| ) | |
| .await??; | |
| trigger.await?; | |
| assert!( | |
| conflict_injected.load(Ordering::SeqCst), | |
| "expected non-control RevisionConflict to be injected right before B's blocker write" | |
| ); | |
| assert!( | |
| matches!(exit, DriverExit::Blocked { .. }), | |
| "expected Run to park on CurrentAuthorityUnavailable blocker after retry, got {exit:?}" | |
| ); | |
| let dispatched_names: BTreeSet<String> = ports | |
| .dispatched() | |
| .into_iter() | |
| .map(|(name, _)| name) | |
| .collect(); | |
| assert_eq!( | |
| dispatched_names, | |
| BTreeSet::from(["0-a".to_string()]), | |
| "2-c must not dispatch even when 1-b hits a non-control RevisionConflict" | |
| ); | |
| let history = store.history(run, 0, 200).await?; | |
| let admitted_calls: BTreeSet<String> = history | |
| .iter() | |
| .filter_map(|f| match &f.fact { | |
| Fact::ToolAdmitted { tool } => Some(tool.call.clone()), | |
| _ => None, | |
| }) | |
| .collect(); | |
| assert_eq!( | |
| admitted_calls, | |
| BTreeSet::from(["0-a".to_string()]), | |
| "2-c must have zero ToolAdmitted after 1-b resolves its RevisionConflict" | |
| ); | |
| let view = store.frontier(run).await?; | |
| let c_key = ToolKey { | |
| attempt, | |
| call: "2-c".into(), | |
| }; | |
| assert!(!view.tools[&tool_key(&c_key)].admitted); | |
| assert!( | |
| view.blockers | |
| .values() | |
| .any(|b| matches!(&b.reason, BlockerKind::CurrentAuthorityUnavailable { .. })) | |
| ); | |
| Ok::<_, Box<dyn std::error::Error + Send + Sync>>(()) | |
| }) | |
| .catch_unwind() | |
| .await; | |
| drop((store, witness)); | |
| root.close().await?; | |
| match res { | |
| Ok(r) => r?, | |
| Err(p) => std::panic::resume_unwind(p), | |
| } | |
| } | |
| Ok(()) | |
| } | |
| #[tokio::test] | |
| async fn approved_only_fallback_batch_aborts_on_physical_cancellation_before_commit() | |
| -> TestResult<()> { | |
| use std::sync::atomic::AtomicBool; | |
| let call_names = ["len-0", "len-1"]; | |
| let temp = tempfile::tempdir()?; | |
| let base = temp.path().to_path_buf(); | |
| let owner = tokio::task::spawn_blocking(move || { | |
| RootOwner::create( | |
| &base.join("root"), | |
| &RootNamespaces { | |
| ownership: base.join("owners"), | |
| control: base.join("control"), | |
| }, | |
| ) | |
| }) | |
| .await??; | |
| let mut migrations = maka_event_log::ROOT_MIGRATIONS.to_vec(); | |
| migrations.extend_from_slice(maka_agent_state::MIGRATIONS); | |
| let root = RootStore::open(Arc::new(owner), &migrations).await?; | |
| let data = root.data_writer()?; | |
| let store = Store::new(data.clone(), DriverDomain::new(data)?)?; | |
| let mut policy = policy_view(None); | |
| let empty = ContentBlob::new(vec![]); | |
| let tool_selection = ContentBlob::json(&serde_json::json!({ | |
| "definitions": [], "directOnly": [], "services": [], "internalBindings": {} | |
| }))?; | |
| let input = ContentBlob::json(&RunInput::Message { | |
| content: "approved-only fallback cancellation fixture" | |
| .to_string() | |
| .into(), | |
| request_fingerprint: None, | |
| source_messages: vec![], | |
| })?; | |
| policy.spec.tool_selection = tool_selection.reference().clone(); | |
| policy.spec.input = input.reference().clone(); | |
| let spec = ContentBlob::json(&policy.spec)?; | |
| apply_policy_fact( | |
| &mut policy, | |
| Fact::RunAdmitted { | |
| spec: spec.reference().clone(), | |
| }, | |
| ); | |
| let (_, mut request, _) = model_closure( | |
| policy.clone(), | |
| ModelPurpose::Main, | |
| ModelFinishReason::Length, | |
| Outcome::Success, | |
| false, | |
| ); | |
| let admission = Admission::new( | |
| policy.spec, | |
| UnixMillis(1), | |
| vec![empty, tool_selection, input], | |
| ); | |
| let run = admission.run(); | |
| store.admit(admission).await?; | |
| let claim = store.claim(run).await?; | |
| let provenance = ContentBlob::json(&serde_json::json!({ | |
| "estimatedInputTokens": 0, | |
| "breakdown": maka_agent_facts::context::PreparedContextBreakdown::default(), | |
| "modelContext": null, | |
| "previousCheckpointId": null, | |
| }))?; | |
| let surface = ContentBlob::json(&maka_agent_facts::composition::CompositionSurface { | |
| system_prompt: None, | |
| tools: vec![], | |
| sources: vec![], | |
| })?; | |
| let raw_request = ContentBlob::json(&serde_json::json!({"messages": []}))?; | |
| request.request = raw_request.reference().clone(); | |
| request.composition.surface = surface.reference().clone(); | |
| request.provenance = provenance.reference().clone(); | |
| let encoded = ContentBlob::json(&request)?; | |
| let view = store.frontier(run).await?; | |
| store | |
| .append( | |
| &claim, | |
| (&view).into(), | |
| vec![Change::new( | |
| Fact::StepPrepared { | |
| step: request.step, | |
| request: encoded.reference().clone(), | |
| adjudications: vec![], | |
| }, | |
| UnixMillis(2), | |
| )], | |
| vec![encoded, provenance, surface, raw_request], | |
| ) | |
| .await?; | |
| // Stream 2 tool calls; once both enter prevalidation, close the model with FinishReason::Length | |
| // so complete_decided_batch takes the Approved-only (admit == false) path, and fire physical | |
| // cancellation right after frontier read before the shared pre-submit check. | |
| let cancel = CancellationToken::new(); | |
| let gate = Arc::new(Notify::new()); | |
| let started: Vec<Arc<Notify>> = (0..call_names.len()) | |
| .map(|_| Arc::new(Notify::new())) | |
| .collect(); | |
| let prevalidated_count = Arc::new(AtomicUsize::new(0)); | |
| let cancelled_before_submit = Arc::new(AtomicBool::new(false)); | |
| let finish_notify = Arc::new(Notify::new()); | |
| let mut behaviors = BTreeMap::new(); | |
| for (idx, name) in call_names.iter().enumerate() { | |
| behaviors.insert( | |
| (*name).to_string(), | |
| ToolBehavior { | |
| on_prevalidate_start: Some(started[idx].clone()), | |
| prevalidate_gate: Some(gate.clone()), | |
| on_prevalidate_finish: Some(finish_notify.clone()), | |
| ..Default::default() | |
| }, | |
| ); | |
| } | |
| let mock_ports = MockDirectPorts::new(behaviors, 0, cancel.clone()); | |
| *mock_ports.model_stream.lock().unwrap() = Some(MockModelStream { | |
| call_ids: call_names.iter().map(|s| (*s).to_string()).collect(), | |
| started, | |
| gate, | |
| close_with_length: true, | |
| }); | |
| let cancel_for_hook = cancel.clone(); | |
| let prevalidated_for_hook = prevalidated_count.clone(); | |
| let cancelled_flag_for_hook = cancelled_before_submit.clone(); | |
| *mock_ports.on_now.lock().unwrap() = Some(Box::new(move || { | |
| if prevalidated_for_hook.load(Ordering::SeqCst) > 0 | |
| && !cancelled_flag_for_hook.swap(true, Ordering::SeqCst) | |
| { | |
| cancel_for_hook.cancel(); | |
| } | |
| })); | |
| let prevalidated_for_watcher = prevalidated_count.clone(); | |
| let watcher = tokio::spawn(async move { | |
| finish_notify.notified().await; | |
| prevalidated_for_watcher.fetch_add(1, Ordering::SeqCst); | |
| }); | |
| let ports = Arc::new(mock_ports); | |
| let res = AssertUnwindSafe(async { | |
| let exit = tokio::time::timeout( | |
| Duration::from_secs(10), | |
| Engine::new(store.clone()).drive(claim, ports.clone(), cancel), | |
| ) | |
| .await??; | |
| watcher.await?; | |
| assert!( | |
| matches!(exit, DriverExit::Retired { .. }), | |
| "expected Retired exit on physical cancellation before Approved-only commit, got {exit:?}" | |
| ); | |
| assert!( | |
| cancelled_before_submit.load(Ordering::SeqCst), | |
| "expected cancellation hook to fire before Approved-only batch commit" | |
| ); | |
| assert!(ports.dispatched().is_empty()); | |
| let history = store.history(run, 0, 200).await?; | |
| assert!( | |
| !history | |
| .iter() | |
| .any(|f| matches!(f.fact, Fact::ToolDecided { .. } | Fact::ToolAdmitted { .. })), | |
| "Approved-only fallback batch must not persist ToolDecided or ToolAdmitted after physical cancellation" | |
| ); | |
| Ok::<_, Box<dyn std::error::Error + Send + Sync>>(()) | |
| }) | |
| .catch_unwind() | |
| .await; | |
| drop(store); | |
| root.close().await?; | |
| match res { | |
| Ok(r) => r?, | |
| Err(p) => std::panic::resume_unwind(p), | |
| } | |
| Ok(()) | |
| } | |
| async fn setup_two_completed_local_tools( | |
| tool_discovery: bool, | |
| result_a: ContentBlob, | |
| result_b: ContentBlob, | |
| ) -> TestResult<(tempfile::TempDir, RootStore, Store, DriverClaim)> { | |
| let temp = tempfile::tempdir()?; | |
| let base = temp.path().to_path_buf(); | |
| let owner = tokio::task::spawn_blocking(move || { | |
| RootOwner::create( | |
| &base.join("root"), | |
| &RootNamespaces { | |
| ownership: base.join("owners"), | |
| control: base.join("control"), | |
| }, | |
| ) | |
| }) | |
| .await??; | |
| let mut migrations = maka_event_log::ROOT_MIGRATIONS.to_vec(); | |
| migrations.extend_from_slice(maka_agent_state::MIGRATIONS); | |
| let root = RootStore::open(Arc::new(owner), &migrations).await?; | |
| let data = root.data_writer()?; | |
| let store = Store::new(data.clone(), DriverDomain::new(data)?)?; | |
| let mut policy = policy_view(None); | |
| policy.spec.tool_discovery = tool_discovery; | |
| let empty = ContentBlob::new(vec![]); | |
| let tool_selection = ContentBlob::json(&serde_json::json!({ | |
| "definitions": [], "directOnly": [], "services": [], "internalBindings": {} | |
| }))?; | |
| let input = ContentBlob::json(&RunInput::Message { | |
| content: "batched acceptance fixture".to_string().into(), | |
| request_fingerprint: None, | |
| source_messages: vec![], | |
| })?; | |
| policy.spec.tool_selection = tool_selection.reference().clone(); | |
| policy.spec.input = input.reference().clone(); | |
| let spec = ContentBlob::json(&policy.spec)?; | |
| apply_policy_fact( | |
| &mut policy, | |
| Fact::RunAdmitted { | |
| spec: spec.reference().clone(), | |
| }, | |
| ); | |
| let (_, mut request, attempt) = model_closure( | |
| policy.clone(), | |
| ModelPurpose::Main, | |
| ModelFinishReason::ToolCalls, | |
| Outcome::Success, | |
| false, | |
| ); | |
| let admission = Admission::new( | |
| policy.spec, | |
| UnixMillis(1), | |
| vec![empty, tool_selection, input], | |
| ); | |
| let run = admission.run(); | |
| store.admit(admission).await?; | |
| let claim = store.claim(run).await?; | |
| let provenance = ContentBlob::json(&serde_json::json!({ | |
| "estimatedInputTokens": 0, | |
| "breakdown": maka_agent_facts::context::PreparedContextBreakdown::default(), | |
| "modelContext": null, | |
| "previousCheckpointId": null, | |
| }))?; | |
| let surface = ContentBlob::json(&maka_agent_facts::composition::CompositionSurface { | |
| system_prompt: None, | |
| tools: vec![], | |
| sources: vec![], | |
| })?; | |
| request.composition.surface = surface.reference().clone(); | |
| request.provenance = provenance.reference().clone(); | |
| let encoded = ContentBlob::json(&request)?; | |
| let view = store.frontier(run).await?; | |
| store | |
| .append( | |
| &claim, | |
| (&view).into(), | |
| vec![ | |
| Change::new( | |
| Fact::StepPrepared { | |
| step: request.step, | |
| request: encoded.reference().clone(), | |
| adjudications: vec![], | |
| }, | |
| UnixMillis(2), | |
| ), | |
| Change::new( | |
| Fact::ModelAttemptPrepared { | |
| attempt, | |
| step: request.step, | |
| }, | |
| UnixMillis(2), | |
| ), | |
| Change::new( | |
| Fact::ModelAttemptAdmitted { | |
| attempt, | |
| upstream: serde_json::json!({"typed": "mock-model"}), | |
| }, | |
| UnixMillis(2), | |
| ), | |
| ], | |
| vec![encoded, provenance, surface], | |
| ) | |
| .await?; | |
| let witness = ModelWitness::new(store.clone(), claim.clone(), attempt); | |
| let parts = ["call_a", "call_b"] | |
| .iter() | |
| .enumerate() | |
| .map(|(index, id)| { | |
| ( | |
| index as u64, | |
| ModelPart::ToolCall { | |
| call: ModelToolCall { | |
| id: (*id).to_string(), | |
| name: "read".into(), | |
| input: ToolInput::Json(serde_json::json!({"index": index})), | |
| provider_options: None, | |
| provider_executed: false, | |
| }, | |
| }, | |
| None, | |
| ) | |
| }) | |
| .collect(); | |
| let protocol = serde_json::to_value(ModelClosureProtocol { | |
| model_time_ms: Some(10), | |
| finish_reason: ModelFinishReason::ToolCalls, | |
| provider_options: None, | |
| cache_read_reported: None, | |
| response_id: Some("resp-accept".into()), | |
| model: Some("test".into()), | |
| timestamp: None, | |
| compaction: None, | |
| summary: None, | |
| })?; | |
| witness | |
| .closed_with_all( | |
| Some(UnixMillis(3)), | |
| parts, | |
| Outcome::Success, | |
| None, | |
| ModelUsage { | |
| input_tokens: Some(10), | |
| output_tokens: Some(10), | |
| ..Default::default() | |
| }, | |
| protocol, | |
| Some(OperationCleanup::Confirmed), | |
| UnixMillis(3), | |
| ) | |
| .await?; | |
| let input_a = ContentBlob::json(&serde_json::json!({"index": 0}))?; | |
| let input_b = ContentBlob::json(&serde_json::json!({"index": 1}))?; | |
| let key_a = ToolKey { | |
| attempt, | |
| call: "call_a".into(), | |
| }; | |
| let key_b = ToolKey { | |
| attempt, | |
| call: "call_b".into(), | |
| }; | |
| let view = store.frontier(run).await?; | |
| store | |
| .append( | |
| &claim, | |
| (&view).into(), | |
| vec![ | |
| Change::new( | |
| Fact::ToolDecided { | |
| tool: key_a.clone(), | |
| decision: ToolDecision::Approved { | |
| semantics: ToolSemantics::Parallel, | |
| input: input_a.reference().clone(), | |
| resources: vec![], | |
| approval: None, | |
| display: Default::default(), | |
| }, | |
| }, | |
| UnixMillis(4), | |
| ), | |
| Change::new( | |
| Fact::ToolAdmitted { | |
| tool: key_a.clone(), | |
| }, | |
| UnixMillis(4), | |
| ), | |
| Change::new( | |
| Fact::LocalToolReturned { | |
| tool: key_a, | |
| settlement: maka_agent_facts::tool_call::ToolSettlement::Returned, | |
| result: result_a.reference().clone(), | |
| is_error: false, | |
| cell_observation: None, | |
| }, | |
| UnixMillis(4), | |
| ), | |
| Change::new( | |
| Fact::ToolDecided { | |
| tool: key_b.clone(), | |
| decision: ToolDecision::Approved { | |
| semantics: ToolSemantics::Parallel, | |
| input: input_b.reference().clone(), | |
| resources: vec![], | |
| approval: None, | |
| display: Default::default(), | |
| }, | |
| }, | |
| UnixMillis(4), | |
| ), | |
| Change::new( | |
| Fact::ToolAdmitted { | |
| tool: key_b.clone(), | |
| }, | |
| UnixMillis(4), | |
| ), | |
| Change::new( | |
| Fact::LocalToolReturned { | |
| tool: key_b, | |
| settlement: maka_agent_facts::tool_call::ToolSettlement::Returned, | |
| result: result_b.reference().clone(), | |
| is_error: false, | |
| cell_observation: None, | |
| }, | |
| UnixMillis(4), | |
| ), | |
| ], | |
| vec![input_a, input_b, result_a, result_b], | |
| ) | |
| .await?; | |
| Ok((temp, root, store, claim)) | |
| } | |
| #[tokio::test] | |
| async fn batched_tool_acceptance_preserves_first_when_second_prepare_fails() -> TestResult<()> { | |
| let result_a = ContentBlob::json(&maka_agent_facts::artifact::ToolReturn { | |
| schema_version: maka_agent_facts::durable::SCHEMA_VERSION, | |
| artifacts: vec![], | |
| body: maka_agent_facts::tool_output::StoredToolResult::from_local( | |
| maka_agent_facts::tool_output::ToolOutput::Json(serde_json::json!({"ok": "a"})), | |
| None, | |
| maka_agent_facts::tool_output::DurableToolProjection::Text { | |
| text: "a".to_string(), | |
| }, | |
| false, | |
| BTreeSet::new(), | |
| None, | |
| ), | |
| })?; | |
| let result_b = ContentBlob::json(&maka_agent_facts::artifact::ToolReturn { | |
| schema_version: maka_agent_facts::durable::SCHEMA_VERSION, | |
| artifacts: vec![], | |
| body: serde_json::json!({"is_error": false}), | |
| })?; | |
| let (_temp, root, store, claim) = | |
| setup_two_completed_local_tools(true, result_a, result_b).await?; | |
| let run = claim.run(); | |
| let cancel = CancellationToken::new(); | |
| let ports = Arc::new(MockDirectPorts::new(BTreeMap::new(), 0, cancel.clone())); | |
| let res = AssertUnwindSafe(async { | |
| let err = tokio::time::timeout( | |
| Duration::from_secs(10), | |
| Engine::new(store.clone()).drive(claim, ports, cancel), | |
| ) | |
| .await? | |
| .expect_err("expected prepare failure on malformed call_b return"); | |
| assert!( | |
| matches!(err, RunError::InvalidInput(_)), | |
| "unexpected error: {err:?}" | |
| ); | |
| let history = store.history(run, 0, 200).await?; | |
| let accepted: Vec<String> = history | |
| .iter() | |
| .filter_map(|record| match &record.fact { | |
| Fact::ToolResultAccepted { tool, .. } => Some(tool.call.clone()), | |
| _ => None, | |
| }) | |
| .collect(); | |
| assert_eq!( | |
| accepted, | |
| vec!["call_a".to_string()], | |
| "first independent tool acceptance must persist when second sibling fails to prepare" | |
| ); | |
| Ok::<_, Box<dyn std::error::Error + Send + Sync>>(()) | |
| }) | |
| .catch_unwind() | |
| .await; | |
| drop(store); | |
| root.close().await?; | |
| match res { | |
| Ok(r) => r?, | |
| Err(p) => std::panic::resume_unwind(p), | |
| } | |
| Ok(()) | |
| } |