aegis-runtime-mv
Native Rust agent runtime: Axum WebSocket/SSE/REST gateway, heartbeat scheduler, dependency-aware task workflow, SQLite storage. Attachment of AienOS. Pre-alpha.
Brought by drakestapleton
aegis-runtime-mv / tests / round2_completion_tests.rs
| 1 | //! Round-two completion contract: real loopback transports, deterministic faults, no model service. |
| 2 | use aegis::{ |
| 3 | create_router, AgentEngine, Database, EffectCertainty, FailureClass, GatewayState, |
| 4 | HeartbeatEngine, HttpInferenceBackend, SkillRegistry, ToolDispatcher, ToolFault, |
| 5 | }; |
| 6 | use axum::{ |
| 7 | body::Body, |
| 8 | http::{Request, StatusCode}, |
| 9 | }; |
| 10 | use futures_util::{SinkExt, StreamExt}; |
| 11 | use serde_json::{json, Value}; |
| 12 | use std::sync::{ |
| 13 | atomic::{AtomicUsize, Ordering}, |
| 14 | Arc, |
| 15 | }; |
| 16 | use std::time::{Duration, Instant}; |
| 17 | use tower::ServiceExt; |
| 18 | |
| 19 | const TOKEN: &str = "round-two-operator-0123456789abcdef"; |
| 20 | struct Server(tokio::task::JoinHandle<()>); |
| 21 | impl Drop for Server { |
| 22 | fn drop(&mut self) { |
| 23 | self.0.abort(); |
| 24 | } |
| 25 | } |
| 26 | async fn serve(app: axum::Router) -> (std::net::SocketAddr, Server) { |
| 27 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 28 | let address = listener.local_addr().unwrap(); |
| 29 | let handle = tokio::spawn(async move { |
| 30 | axum::serve(listener, app).await.unwrap(); |
| 31 | }); |
| 32 | (address, Server(handle)) |
| 33 | } |
| 34 | struct Dispatch { |
| 35 | attempts: AtomicUsize, |
| 36 | recover: bool, |
| 37 | } |
| 38 | #[async_trait::async_trait] |
| 39 | impl ToolDispatcher for Dispatch { |
| 40 | async fn dispatch(&self, _: &str, _: &Value) -> Result<String, ToolFault> { |
| 41 | let attempt = self.attempts.fetch_add(1, Ordering::SeqCst); |
| 42 | if self.recover && attempt > 0 { |
| 43 | return Ok("retried read succeeded".into()); |
| 44 | } |
| 45 | Err(ToolFault::new( |
| 46 | if self.recover { |
| 47 | FailureClass::Unavailable |
| 48 | } else { |
| 49 | FailureClass::Failed |
| 50 | }, |
| 51 | EffectCertainty::NoEffect, |
| 52 | "injected read failure", |
| 53 | )) |
| 54 | } |
| 55 | } |
| 56 | async fn transport_case(websocket: bool, case: &'static str) { |
| 57 | let model = axum::Router::new().route("/v1/chat/completions", axum::routing::post( |
| 58 | move |axum::Json(body): axum::Json<Value>| async move { |
| 59 | let tool_done = body["messages"].as_array().unwrap().iter().any(|m| m["role"] == "tool"); |
| 60 | let response = if case == "empty_choices" { json!({"choices":[]}) } |
| 61 | else if matches!(case, "tool_failure" | "retry_success" | "length_tools") && !tool_done { |
| 62 | json!({"choices":[{"message":{"tool_calls":[{"id":"read","type":"function", |
| 63 | "function":{"name":"read_file","arguments":"{\"path\":\"fixture\"}"}}]},"finish_reason":if case == "length_tools" { "length" } else { "tool_calls" }}]}) |
| 64 | } else { |
| 65 | json!({"choices":[{"message":{"content":if case == "empty_text" { " " } else { "final text" }, |
| 66 | "reasoning":"Reasoning is not a terminal answer"},"finish_reason":if case == "length" { "length" } else { "stop" }}]}) |
| 67 | }; |
| 68 | axum::Json(response) |
| 69 | } |
| 70 | )); |
| 71 | let (model_address, _model_server) = serve(model).await; |
| 72 | let db = Arc::new(Database::open_in_memory().unwrap()); |
| 73 | let inference = Arc::new(HttpInferenceBackend::new( |
| 74 | Some(format!("http://{model_address}/v1/chat/completions")), |
| 75 | None, |
| 76 | )); |
| 77 | let skills = Arc::new(SkillRegistry::new()); |
| 78 | let dispatch = Arc::new(Dispatch { |
| 79 | attempts: AtomicUsize::new(0), |
| 80 | recover: case == "retry_success", |
| 81 | }); |
| 82 | let agent = AgentEngine::new(inference.clone(), skills.clone(), Some(db.clone())) |
| 83 | .with_dispatcher(dispatch.clone()) |
| 84 | .with_failure_policy(aegis::agent::FailurePolicy { |
| 85 | retry: aegis::RetryPolicy { max_attempts: 2 }, |
| 86 | tool_timeout: None, |
| 87 | }); |
| 88 | let state = GatewayState { |
| 89 | start_time: Instant::now(), |
| 90 | db: db.clone(), |
| 91 | inference: inference.clone(), |
| 92 | skills, |
| 93 | heartbeat: Arc::new(HeartbeatEngine::with_inference(60, db, inference)), |
| 94 | agent: Arc::new(agent), |
| 95 | operator: aegis::OperatorAuth::with_token(TOKEN).unwrap(), |
| 96 | }; |
| 97 | let app = create_router(state); |
| 98 | let body = if websocket { |
| 99 | use tokio_tungstenite::tungstenite::client::IntoClientRequest; |
| 100 | let (address, _gateway_server) = serve(app).await; |
| 101 | let mut request = format!("ws://{address}/ws").into_client_request().unwrap(); |
| 102 | request |
| 103 | .headers_mut() |
| 104 | .insert("authorization", format!("Bearer {TOKEN}").parse().unwrap()); |
| 105 | let (mut ws, _) = tokio_tungstenite::connect_async(request).await.unwrap(); |
| 106 | ws.send(tokio_tungstenite::tungstenite::Message::Text( |
| 107 | json!({"type":"agent_run","prompt":"read then answer","max_turns":3}).to_string(), |
| 108 | )) |
| 109 | .await |
| 110 | .unwrap(); |
| 111 | let body = tokio::time::timeout(Duration::from_secs(5), async { |
| 112 | loop { |
| 113 | let message = ws.next().await.unwrap().unwrap(); |
| 114 | if let Ok(text) = message.to_text() { |
| 115 | let body: Value = serde_json::from_str(text).unwrap(); |
| 116 | if matches!(body["type"].as_str(), Some("agent_result" | "agent_error")) { |
| 117 | break body; |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | }) |
| 122 | .await |
| 123 | .unwrap(); |
| 124 | ws.close(None).await.unwrap(); |
| 125 | body |
| 126 | } else { |
| 127 | let response = app |
| 128 | .oneshot( |
| 129 | Request::builder() |
| 130 | .method("POST") |
| 131 | .uri("/api/v1/agent/run") |
| 132 | .header("Authorization", format!("Bearer {TOKEN}")) |
| 133 | .header("Content-Type", "application/json") |
| 134 | .body(Body::from(r#"{"prompt":"read then answer","max_turns":3}"#)) |
| 135 | .unwrap(), |
| 136 | ) |
| 137 | .await |
| 138 | .unwrap(); |
| 139 | assert_eq!( |
| 140 | response.status(), |
| 141 | if case == "empty_choices" { |
| 142 | StatusCode::INTERNAL_SERVER_ERROR |
| 143 | } else { |
| 144 | StatusCode::OK |
| 145 | } |
| 146 | ); |
| 147 | let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) |
| 148 | .await |
| 149 | .unwrap(); |
| 150 | if case == "empty_choices" { |
| 151 | json!({"error": String::from_utf8(bytes.to_vec()).unwrap()}) |
| 152 | } else { |
| 153 | serde_json::from_slice(&bytes).unwrap() |
| 154 | } |
| 155 | }; |
| 156 | if case == "empty_choices" { |
| 157 | if websocket { |
| 158 | assert_eq!(body["type"], "agent_error"); |
| 159 | } |
| 160 | assert!(body.to_string().contains("empty choices"), "{body}"); |
| 161 | } else { |
| 162 | let result = if websocket { &body["result"] } else { &body }; |
| 163 | let completed = case == "retry_success"; |
| 164 | assert_eq!(result["completed"], completed, "{body}"); |
| 165 | assert_eq!( |
| 166 | body["status"], |
| 167 | if completed { "completed" } else { "incomplete" } |
| 168 | ); |
| 169 | if case == "tool_failure" { |
| 170 | assert_eq!(result["steps"][0]["tool_calls"][0]["success"], false); |
| 171 | assert_eq!(result["final_response"], "final text"); |
| 172 | } |
| 173 | if case == "length_tools" { |
| 174 | assert_eq!( |
| 175 | dispatch.attempts.load(Ordering::SeqCst), |
| 176 | 0, |
| 177 | "truncated tool call must not dispatch" |
| 178 | ); |
| 179 | } |
| 180 | if completed { |
| 181 | assert_eq!(dispatch.attempts.load(Ordering::SeqCst), 2); |
| 182 | assert_eq!( |
| 183 | result["steps"][0]["tool_calls"][0]["retry_failures"] |
| 184 | .as_array() |
| 185 | .unwrap() |
| 186 | .len(), |
| 187 | 1 |
| 188 | ); |
| 189 | } |
| 190 | } |
| 191 | } |
| 192 | macro_rules! transport_test { |
| 193 | ($name:ident, $ws:expr, $case:expr) => { |
| 194 | #[tokio::test] |
| 195 | async fn $name() { |
| 196 | transport_case($ws, $case).await; |
| 197 | } |
| 198 | }; |
| 199 | } |
| 200 | transport_test!(round2_http_failed_tool_final_text, false, "tool_failure"); |
| 201 | transport_test!(round2_ws_failed_tool_final_text, true, "tool_failure"); |
| 202 | transport_test!(round2_http_retry_success, false, "retry_success"); |
| 203 | transport_test!(round2_ws_retry_success, true, "retry_success"); |
| 204 | transport_test!(round2_http_length, false, "length"); |
| 205 | transport_test!(round2_ws_length, true, "length"); |
| 206 | transport_test!(round2_http_empty_text, false, "empty_text"); |
| 207 | transport_test!(round2_ws_empty_text, true, "empty_text"); |
| 208 | transport_test!(round2_http_empty_choices, false, "empty_choices"); |
| 209 | transport_test!(round2_ws_empty_choices, true, "empty_choices"); |
| 210 | transport_test!(round2_http_length_tools, false, "length_tools"); |
| 211 | transport_test!(round2_ws_length_tools, true, "length_tools"); |