diff --git a/Cargo.lock b/Cargo.lock index d9ad4669..e47f9b88 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -30,6 +30,9 @@ name = "aien-cli" version = "0.1.0" dependencies = [ "aien-inference-abi", + "aien-kv-cache", + "aien-runtime", + "aien-scheduler", "async-trait", "chrono", "colored", @@ -41,6 +44,7 @@ dependencies = [ "serde", "serde_json", "spark-hive", + "tempfile", "tokio", ] diff --git a/crates/aien-cli/Cargo.toml b/crates/aien-cli/Cargo.toml index 5ea5f37e..b95a8d03 100644 --- a/crates/aien-cli/Cargo.toml +++ b/crates/aien-cli/Cargo.toml @@ -20,3 +20,10 @@ rustyline = "14" async-trait = "0.1.92" spark-hive = { path = "../spark-hive" } aien-inference-abi = { path = "../aien-inference-abi" } +aien-kv-cache = { path = "../aien-kv-cache" } +aien-scheduler = { path = "../aien-scheduler" } +aien-runtime = { path = "../aien-runtime" } + +[dev-dependencies] +tempfile = "3.10" + diff --git a/crates/aien-cli/src/commands.rs b/crates/aien-cli/src/commands.rs index b8b1fe6f..084ef1f3 100644 --- a/crates/aien-cli/src/commands.rs +++ b/crates/aien-cli/src/commands.rs @@ -888,41 +888,149 @@ fn handle_adapter_command(args: &[&str]) { // SOVEREIGN ORCHESTRATION & DEVELOPER EXPERIENCE // -------------------------------------------------------------------------- +pub async fn run_daemon_server() { + println!( + "{}", + "⚡ Starting AIEN Sovereign Runtime Daemon...".cyan().bold() + ); + let socket_path = aien_runtime::client::AienRuntimeClient::default_socket_path(); + let kv_manager = aien_kv_cache::create_shared_kv_manager(8192, 16); + let sched_cfg = aien_scheduler::SchedulerConfig { + max_batch_size: 256, + max_batch_tokens: 16384, + max_prefill_tokens: 8192, + prefill_chunk_size: 128, + chunk_prefill: true, + watermark_blocks: 64, + }; + let spine = aien_runtime::spine::AienRuntimeSpine::new(4096, sched_cfg, kv_manager); + let server = aien_runtime::server::AienRuntimeServer::new(spine, &socket_path); + + let backend = aien_inference_abi::MockInferenceBackend::new(1); + println!("✓ Binding socket at {}", socket_path.display()); + if let Err(e) = server.run(backend).await { + eprintln!("Runtime daemon error: {}", e); + } +} + pub async fn handle_start_command() { - println!("{}", "⚡ Starting AIEN Sovereign Services...".cyan().bold()); - let supervisor = std::process::Command::new("spark-supervisor") - .arg("start") - .spawn(); - match supervisor { - Ok(_) => println!("{}", "✓ spark-supervisor initialized".green()), - Err(_) => { - println!( - "{}", - "ℹ Launching core background daemons directly...".yellow() - ); - let _ = std::process::Command::new("cortex").spawn(); - let _ = std::process::Command::new("spark-cockpit").spawn(); + let client = aien_runtime::client::AienRuntimeClient::default_client(); + if client.is_alive().await { + println!( + "{}", + "✓ AIEN Sovereign Runtime is already active.".green().bold() + ); + if let Ok(status) = client.get_status().await { + render_runtime_status(&status); } + return; } - println!("\n{}", "✓ Sovereign Services Online:".green().bold()); + println!( - " - Sovereign Cockpit: http://127.0.0.1:18095 (or Tailscale http://100.116.106.93:18095)" + "{}", + "⚡ Starting AIEN Sovereign Runtime Machine..." + .cyan() + .bold() ); - println!(" - Cortex Memory: http://127.0.0.1:18080"); - println!(" - Modular MAX: http://127.0.0.1:18006"); + let exe = std::env::current_exe().unwrap_or_else(|_| std::path::PathBuf::from("aien")); + let mut cmd = std::process::Command::new(exe); + cmd.arg("--daemon"); + + match cmd.spawn() { + Ok(_) => { + let mut ready = false; + for _ in 0..60 { + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + if client.is_alive().await { + ready = true; + break; + } + } + + if ready { + println!("{}", "✓ AIEN Sovereign Runtime Online".green().bold()); + println!( + " Socket: {}", + aien_runtime::client::AienRuntimeClient::default_socket_path().display() + ); + println!( + " Runtime: Unified Sequence Arena, Transactional PagedAttention KV Pool, In-Process Cortex Memory" + ); + if let Ok(status) = client.get_status().await { + render_runtime_status(&status); + } + } else { + eprintln!( + "{}", + "⚠ Runtime daemon spawned but socket did not become ready in 3s.".yellow() + ); + } + } + Err(e) => { + eprintln!("Failed to spawn AIEN runtime daemon: {}", e); + } + } } pub async fn handle_stop_command() { - println!("{}", "Stopping AIEN Sovereign Services...".yellow().bold()); + println!("{}", "Stopping AIEN Sovereign Runtime...".yellow().bold()); + let client = aien_runtime::client::AienRuntimeClient::default_client(); + if client.is_alive().await { + match client.shutdown().await { + Ok(()) => println!("{}", "✓ Runtime daemon stopped cleanly over IPC".green()), + Err(e) => eprintln!("Failed to send shutdown command: {}", e), + } + } else { + println!("{}", "ℹ Runtime daemon is not running".dimmed()); + } + let _ = std::process::Command::new("pkill") .args(["-f", "spark-cockpit"]) .status(); - println!("{}", "✓ Services stopped cleanly".green()); +} + +pub fn render_runtime_status(status: &aien_runtime::control::RuntimeStatusReport) { + let sharing_pct = + if status.total_kv_blocks > status.free_kv_blocks && status.total_kv_blocks > 0 { + let allocated = status.total_kv_blocks - status.free_kv_blocks; + (status.shared_kv_pages as f64 / (allocated + status.shared_kv_pages) as f64) * 100.0 + } else { + 0.0 + }; + + println!(" - Active Sequences: {}", status.active_sequences); + println!(" - Active Swarms: {}", status.active_swarms); + println!(" - Active Worlds: {}", status.active_worlds); + println!( + " - KV Cache Pool: {}/{} blocks free", + status.free_kv_blocks, status.total_kv_blocks + ); + println!( + " - Shared KV Pages: {} ({:.1}% deduplication)", + status.shared_kv_pages, sharing_pct + ); + println!(" - COW Faults: {}", status.cow_faults); + println!(" - Engine Status: ONLINE"); } pub async fn handle_status_command() { - println!("{}", "=== AIEN Sovereign Stack Telemetry ===".cyan().bold()); - let client = reqwest::Client::builder() + println!("{}", "=== AIEN Sovereign Machine Status ===".cyan().bold()); + let client = aien_runtime::client::AienRuntimeClient::default_client(); + + match client.get_status().await { + Ok(status) => { + render_runtime_status(&status); + } + Err(_) => { + println!( + "{}", + " ℹ Native Runtime: OFFLINE (Run 'aien start' to initialize)".yellow() + ); + } + } + + println!("\n{}", "=== Hardware & Ancillary Services ===".cyan()); + let http_client = reqwest::Client::builder() .timeout(std::time::Duration::from_millis(500)) .build() .unwrap_or_default(); @@ -958,7 +1066,7 @@ pub async fn handle_status_command() { for (name, url, port) in checks { let t0 = std::time::Instant::now(); - match client.get(url).send().await { + match http_client.get(url).send().await { Ok(resp) if resp.status().is_success() => { let elapsed = t0.elapsed().as_millis(); println!( @@ -981,6 +1089,116 @@ pub async fn handle_status_command() { } } +pub async fn handle_swarm_command(args: &[String]) { + let client = aien_runtime::client::AienRuntimeClient::default_client(); + if !client.is_alive().await { + eprintln!( + "{}", + "Error: AIEN runtime is not running. Run 'aien start' first.".red() + ); + return; + } + + if args.is_empty() || args[0] == "help" { + println!("{}", "AIEN Swarm Management:".cyan().bold()); + println!(" aien swarm launch [--branches N] [--tokens M] [--prompt \"\"]"); + println!(" aien swarm status"); + println!(" aien swarm inspect "); + println!(" aien swarm cancel "); + return; + } + + match args[0].as_str() { + "launch" => { + let mut branch_count = 16; + let mut max_tokens = 32; + let mut prompt_str = "Explain sovereign systems architecture".to_string(); + + let mut i = 1; + while i < args.len() { + match args[i].as_str() { + "--branches" | "-b" if i + 1 < args.len() => { + branch_count = args[i + 1].parse().unwrap_or(16); + i += 2; + } + "--tokens" | "-t" if i + 1 < args.len() => { + max_tokens = args[i + 1].parse().unwrap_or(32); + i += 2; + } + "--prompt" | "-p" if i + 1 < args.len() => { + prompt_str = args[i + 1].clone(); + i += 2; + } + _ => i += 1, + } + } + + let prompt_tokens: Vec = prompt_str.bytes().map(|b| b as u32).collect(); + let req = aien_runtime::control::LaunchSwarmReq { + model_handle: 1, + branch_count, + max_active_sequences: branch_count * 2, + max_tokens_per_branch: max_tokens, + root_world_id: 0, + priority: 1, + prompt_tokens, + }; + + println!( + "{}", + format!( + "🚀 Launching Swarm with {} branches sharing root World...", + branch_count + ) + .cyan() + ); + match client.launch_swarm(req).await { + Ok(swarm_id) => { + println!( + "{}", + format!("✓ Swarm #{} launched successfully.", swarm_id) + .green() + .bold() + ); + println!( + "Use 'aien swarm inspect {}' or 'aien status' to monitor.", + swarm_id + ); + } + Err(e) => eprintln!("Failed to launch swarm: {}", e), + } + } + "inspect" if args.len() > 1 => { + if let Ok(swarm_id) = args[1].parse::() { + match client.inspect_swarm(swarm_id).await { + Ok(status) => render_runtime_status(&status), + Err(e) => eprintln!("Error inspecting swarm: {}", e), + } + } else { + eprintln!("Invalid swarm ID: {}", args[1]); + } + } + "cancel" if args.len() > 1 => { + if let Ok(swarm_id) = args[1].parse::() { + match client.cancel_swarm(swarm_id).await { + Ok(()) => println!("{}", format!("✓ Swarm #{} cancelled.", swarm_id).green()), + Err(e) => eprintln!("Error cancelling swarm: {}", e), + } + } else { + eprintln!("Invalid swarm ID: {}", args[1]); + } + } + "status" => { + if let Ok(status) = client.get_status().await { + render_runtime_status(&status); + } + } + unknown => { + eprintln!("Unknown swarm subcommand: {}", unknown); + } + } +} + pub async fn handle_cockpit_command() { println!( "{}", diff --git a/crates/aien-cli/src/main.rs b/crates/aien-cli/src/main.rs index 3ac05ffa..52a26abb 100644 --- a/crates/aien-cli/src/main.rs +++ b/crates/aien-cli/src/main.rs @@ -37,6 +37,14 @@ async fn main() { let args: Vec = env::args().collect(); if args.len() > 1 { + if args[1] == "--daemon" || args[1] == "daemon" { + commands::run_daemon_server().await; + return; + } + if args[1] == "--swarm" || args[1] == "swarm" { + commands::handle_swarm_command(&args[2..]).await; + return; + } if args[1] == "--start" || args[1] == "start" { commands::handle_start_command().await; return; diff --git a/crates/aien-cli/tests/test_cli_runtime_ipc.rs b/crates/aien-cli/tests/test_cli_runtime_ipc.rs new file mode 100644 index 00000000..76636cd7 --- /dev/null +++ b/crates/aien-cli/tests/test_cli_runtime_ipc.rs @@ -0,0 +1,87 @@ +//! Integration tests for AIEN CLI and runtime IPC protocol. + +use aien_inference_abi::MockInferenceBackend; +use aien_runtime::client::AienRuntimeClient; +use aien_runtime::control::LaunchSwarmReq; +use aien_runtime::server::AienRuntimeServer; +use aien_runtime::spine::AienRuntimeSpine; +use aien_runtime::{create_shared_kv_manager, SchedulerConfig}; +use std::time::Duration; +use tempfile::TempDir; + +#[tokio::test] +async fn test_cli_runtime_ipc_lifecycle() { + let temp_dir = TempDir::new().expect("Failed to create tempdir"); + let socket_path = temp_dir.path().join("aien-test.sock"); + std::env::set_var("AIEN_RUNTIME_SOCK", socket_path.to_str().unwrap()); + + let kv_manager = create_shared_kv_manager(512, 16); + let sched_cfg = SchedulerConfig { + max_batch_size: 32, + max_batch_tokens: 2048, + max_prefill_tokens: 1024, + prefill_chunk_size: 64, + chunk_prefill: true, + watermark_blocks: 8, + }; + + let spine = AienRuntimeSpine::new(256, sched_cfg, kv_manager); + let server = AienRuntimeServer::new(spine, &socket_path); + + let server_handle = tokio::spawn(async move { + let backend = MockInferenceBackend::new(1); + server.run(backend).await + }); + + let client = AienRuntimeClient::default_client(); + let mut ready = false; + for _ in 0..50 { + if client.is_alive().await { + ready = true; + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert!( + ready, + "Runtime server must become alive on designated socket" + ); + + // 1. Check status + let status = client + .get_status() + .await + .expect("Status query must succeed"); + assert_eq!(status.active_sequences, 0); + + // 2. Launch swarm + let prompt: Vec = (1..=16).collect(); + let req = LaunchSwarmReq { + model_handle: 1, + branch_count: 4, + max_active_sequences: 8, + max_tokens_per_branch: 8, + root_world_id: 0, + priority: 1, + prompt_tokens: prompt, + }; + + let swarm_id = client.launch_swarm(req).await.expect("Launch must succeed"); + assert_eq!(swarm_id, 1); + + // 3. Inspect swarm + let swarm_status = client + .inspect_swarm(swarm_id) + .await + .expect("Inspect must succeed"); + assert!(swarm_status.active_sequences >= 1); + + // 4. Clean shutdown + client.shutdown().await.expect("Shutdown must succeed"); + let server_res = server_handle + .await + .expect("Server task panicked") + .expect("Server exited with error"); + assert_eq!(server_res, ()); + assert!(!socket_path.exists(), "Socket must be removed on shutdown"); +} diff --git a/crates/aien-runtime/src/client.rs b/crates/aien-runtime/src/client.rs new file mode 100644 index 00000000..9c44a1f8 --- /dev/null +++ b/crates/aien-runtime/src/client.rs @@ -0,0 +1,130 @@ +//! Local UNIX domain socket client for AienRuntimeSpine +//! Used by aien-cli to communicate with the in-process runtime daemon. + +use crate::control::{ + ControlCommand, ControlEnvelope, ControlResponse, LaunchSwarmReq, RuntimeStatusReport, +}; +use std::path::{Path, PathBuf}; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; +use tokio::net::UnixStream; + +pub struct AienRuntimeClient { + socket_path: PathBuf, +} + +impl AienRuntimeClient { + pub fn new(socket_path: impl AsRef) -> Self { + Self { + socket_path: socket_path.as_ref().to_path_buf(), + } + } + + pub fn default_socket_path() -> PathBuf { + if let Ok(sock) = std::env::var("AIEN_RUNTIME_SOCK") { + if !sock.trim().is_empty() { + return PathBuf::from(sock.trim()); + } + } + PathBuf::from("/tmp/aien-runtime.sock") + } + + pub fn default_client() -> Self { + Self::new(Self::default_socket_path()) + } + + pub async fn is_alive(&self) -> bool { + self.get_status().await.is_ok() + } + + pub async fn send_command(&self, command: ControlCommand) -> Result { + let stream = UnixStream::connect(&self.socket_path).await.map_err(|e| { + format!( + "Failed to connect to AIEN runtime socket at {}: {}", + self.socket_path.display(), + e + ) + })?; + + let (reader, mut writer) = stream.into_split(); + let mut buf_reader = BufReader::new(reader); + + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default(); + + let envelope = ControlEnvelope { + protocol_version: 1, + request_id: now.as_millis() as u64, + operation_id: now.as_nanos(), + operator_session: 1, + command, + }; + + let mut payload = serde_json::to_string(&envelope) + .map_err(|e| format!("Failed to serialize ControlEnvelope: {}", e))?; + payload.push('\n'); + + writer + .write_all(payload.as_bytes()) + .await + .map_err(|e| format!("Failed to send control command: {}", e))?; + + let mut line = String::new(); + buf_reader + .read_line(&mut line) + .await + .map_err(|e| format!("Failed to read response from runtime socket: {}", e))?; + + serde_json::from_str::(line.trim()) + .map_err(|e| format!("Failed to parse ControlResponse: {}", e)) + } + + pub async fn get_status(&self) -> Result { + match self.send_command(ControlCommand::GetRuntimeStatus).await? { + ControlResponse::Status(report) => Ok(report), + ControlResponse::Error(e) => Err(e), + other => Err(format!( + "Unexpected response for GetRuntimeStatus: {:?}", + other + )), + } + } + + pub async fn launch_swarm(&self, req: LaunchSwarmReq) -> Result { + match self.send_command(ControlCommand::LaunchSwarm(req)).await? { + ControlResponse::SwarmAccepted { swarm_id, .. } => Ok(swarm_id), + ControlResponse::Error(e) => Err(e), + other => Err(format!("Unexpected response for LaunchSwarm: {:?}", other)), + } + } + + pub async fn cancel_swarm(&self, swarm_id: u64) -> Result<(), String> { + match self + .send_command(ControlCommand::CancelSwarm(swarm_id)) + .await? + { + ControlResponse::SwarmCancelled { .. } => Ok(()), + ControlResponse::Error(e) => Err(e), + other => Err(format!("Unexpected response for CancelSwarm: {:?}", other)), + } + } + + pub async fn inspect_swarm(&self, swarm_id: u64) -> Result { + match self + .send_command(ControlCommand::InspectSwarm(swarm_id)) + .await? + { + ControlResponse::Status(report) => Ok(report), + ControlResponse::Error(e) => Err(e), + other => Err(format!("Unexpected response for InspectSwarm: {:?}", other)), + } + } + + pub async fn shutdown(&self) -> Result<(), String> { + match self.send_command(ControlCommand::Shutdown).await? { + ControlResponse::ShutdownAck => Ok(()), + ControlResponse::Error(e) => Err(e), + other => Err(format!("Unexpected response for Shutdown: {:?}", other)), + } + } +} diff --git a/crates/aien-runtime/src/control.rs b/crates/aien-runtime/src/control.rs index c5e4ea52..c3e4e433 100644 --- a/crates/aien-runtime/src/control.rs +++ b/crates/aien-runtime/src/control.rs @@ -21,6 +21,7 @@ pub enum ControlCommand { InspectSwarm(u64), CancelSwarm(u64), GetRuntimeStatus, + Shutdown, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -49,6 +50,7 @@ pub enum ControlResponse { SwarmAccepted { swarm_id: u64, operation_id: u128 }, SwarmCancelled { swarm_id: u64 }, Status(RuntimeStatusReport), + ShutdownAck, Error(String), } diff --git a/crates/aien-runtime/src/lib.rs b/crates/aien-runtime/src/lib.rs index 7319fbc6..2592259e 100644 --- a/crates/aien-runtime/src/lib.rs +++ b/crates/aien-runtime/src/lib.rs @@ -1,17 +1,23 @@ //! AIEN Runtime: Canonical Single-Process Host for Persistent Branching Intelligence +pub mod client; pub mod context; pub mod control; pub mod rsi; pub mod sequence; +pub mod server; pub mod spine; pub mod swarm; pub mod world; +pub use aien_kv_cache::create_shared_kv_manager; +pub use aien_scheduler::SchedulerConfig; +pub use client::*; pub use context::*; pub use control::*; pub use rsi::*; pub use sequence::*; +pub use server::*; pub use spine::*; pub use swarm::*; pub use world::*; diff --git a/crates/aien-runtime/src/server.rs b/crates/aien-runtime/src/server.rs new file mode 100644 index 00000000..a636ab6f --- /dev/null +++ b/crates/aien-runtime/src/server.rs @@ -0,0 +1,177 @@ +//! Local UNIX domain socket server for AienRuntimeSpine +//! Exposes typed control RPC over local IPC to operator CLI tools. + +use crate::control::{ControlCommand, ControlEnvelope, ControlResponse}; +use crate::spine::AienRuntimeSpine; +use aien_inference_abi::AienInferenceBackend; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; +use tokio::net::{UnixListener, UnixStream}; +use tokio::sync::{Mutex, Notify}; + +pub struct AienRuntimeServer { + socket_path: PathBuf, + spine: Arc>, + shutdown_notify: Arc, + is_running: Arc, +} + +impl AienRuntimeServer { + pub fn new(spine: AienRuntimeSpine, socket_path: impl AsRef) -> Self { + Self { + socket_path: socket_path.as_ref().to_path_buf(), + spine: Arc::new(Mutex::new(spine)), + shutdown_notify: Arc::new(Notify::new()), + is_running: Arc::new(AtomicBool::new(false)), + } + } + + pub fn spine(&self) -> Arc> { + self.spine.clone() + } + + pub fn socket_path(&self) -> &Path { + &self.socket_path + } + + /// Runs the runtime server, accepting control connections and advancing the engine step loop. + pub async fn run( + &self, + mut backend: B, + ) -> Result<(), String> { + // Clean up stale socket file if it exists and refuses connection + if self.socket_path.exists() { + if UnixStream::connect(&self.socket_path).await.is_err() { + let _ = std::fs::remove_file(&self.socket_path); + } else { + return Err(format!( + "Runtime socket already active at {}", + self.socket_path.display() + )); + } + } + + if let Some(parent) = self.socket_path.parent() { + if !parent.exists() { + let _ = std::fs::create_dir_all(parent); + } + } + + let listener = UnixListener::bind(&self.socket_path).map_err(|e| { + format!( + "Failed to bind runtime UNIX domain socket at {}: {}", + self.socket_path.display(), + e + ) + })?; + + self.is_running.store(true, Ordering::SeqCst); + + // Background worker advancing engine steps whenever requests are active + let spine_worker = self.spine.clone(); + let is_running_worker = self.is_running.clone(); + let shutdown_notify_worker = self.shutdown_notify.clone(); + + let worker_handle = tokio::spawn(async move { + while is_running_worker.load(Ordering::Relaxed) { + let has_work = { + let s = spine_worker.lock().await; + s.scheduler.running_count() > 0 || s.scheduler.waiting_count() > 0 + }; + + if has_work { + let mut s = spine_worker.lock().await; + let _ = s.step(&mut backend).await; + } else { + tokio::select! { + _ = tokio::time::sleep(tokio::time::Duration::from_millis(5)) => {}, + _ = shutdown_notify_worker.notified() => break, + } + } + } + }); + + // Connection accept loop + loop { + tokio::select! { + accept_res = listener.accept() => { + match accept_res { + Ok((stream, _)) => { + let spine_conn = self.spine.clone(); + let is_running_conn = self.is_running.clone(); + let notify_conn = self.shutdown_notify.clone(); + + tokio::spawn(async move { + handle_connection(stream, spine_conn, is_running_conn, notify_conn).await; + }); + } + Err(e) => { + tracing::warn!("Failed to accept runtime connection: {}", e); + } + } + } + _ = self.shutdown_notify.notified() => { + break; + } + } + } + + self.is_running.store(false, Ordering::SeqCst); + let _ = worker_handle.await; + + // Clean up socket file on clean shutdown + if self.socket_path.exists() { + let _ = std::fs::remove_file(&self.socket_path); + } + + Ok(()) + } +} + +async fn handle_connection( + stream: UnixStream, + spine: Arc>, + is_running: Arc, + shutdown_notify: Arc, +) { + let (reader, mut writer) = stream.into_split(); + let mut buf_reader = BufReader::new(reader); + let mut line = String::new(); + + while let Ok(n) = buf_reader.read_line(&mut line).await { + if n == 0 { + break; + } + let trimmed = line.trim(); + if trimmed.is_empty() { + line.clear(); + continue; + } + + let resp = match serde_json::from_str::(trimmed) { + Ok(envelope) => { + let is_shutdown = matches!(envelope.command, ControlCommand::Shutdown); + let response = { + let mut s = spine.lock().await; + s.handle_control_command(envelope) + }; + if is_shutdown { + is_running.store(false, Ordering::SeqCst); + shutdown_notify.notify_waiters(); + } + response + } + Err(e) => ControlResponse::Error(format!("Invalid control envelope JSON: {}", e)), + }; + + if let Ok(mut serialized) = serde_json::to_string(&resp) { + serialized.push('\n'); + if writer.write_all(serialized.as_bytes()).await.is_err() { + break; + } + } + line.clear(); + } +} diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs index 01585739..e27cdcf5 100644 --- a/crates/aien-runtime/src/spine.rs +++ b/crates/aien-runtime/src/spine.rs @@ -180,6 +180,11 @@ impl AienRuntimeSpine { ControlResponse::Error(format!("Swarm {} not found", swarm_id)) } } + ControlCommand::Shutdown => { + self.controller + .mark_operation_processed(envelope.operation_id); + ControlResponse::ShutdownAck + } }; resp diff --git a/crates/aien-runtime/src/swarm.rs b/crates/aien-runtime/src/swarm.rs index f1aa2bac..f328558a 100644 --- a/crates/aien-runtime/src/swarm.rs +++ b/crates/aien-runtime/src/swarm.rs @@ -69,9 +69,16 @@ impl SwarmManager { let swarm_id = self.next_swarm_id; self.next_swarm_id += 1; + // Ensure a root world exists + let root_world_id = if world_store.get_world(config.root_world_id).is_some() { + config.root_world_id + } else { + world_store.create_root_world(1, 1, 1, timestamp) + }; + // 1. Allocate root sequence in arena let root_seq = arena.allocate( - config.root_world_id, + root_world_id, 1, // Initial root context revision config.priority, timestamp, @@ -89,7 +96,7 @@ impl SwarmManager { // 3. Atomically fork N branches sharing the root World and root KV blocks let mut branch_sequences = Vec::with_capacity(config.branch_count); for _ in 0..config.branch_count { - let child_world = world_store.fork_world(config.root_world_id, timestamp)?; + let child_world = world_store.fork_world(root_world_id, timestamp)?; let child_seq = arena.fork(root_seq, child_world, timestamp)?; let child_u64 = child_seq.as_u64(); diff --git a/crates/aien-runtime/tests/runtime_ipc_test.rs b/crates/aien-runtime/tests/runtime_ipc_test.rs new file mode 100644 index 00000000..b028a4b8 --- /dev/null +++ b/crates/aien-runtime/tests/runtime_ipc_test.rs @@ -0,0 +1,102 @@ +//! Integration test for AienRuntimeServer and AienRuntimeClient over local UNIX domain socket. + +use aien_inference_abi::MockInferenceBackend; +use aien_kv_cache::create_shared_kv_manager; +use aien_runtime::client::AienRuntimeClient; +use aien_runtime::control::LaunchSwarmReq; +use aien_runtime::server::AienRuntimeServer; +use aien_runtime::spine::AienRuntimeSpine; +use aien_scheduler::SchedulerConfig; +use std::time::Duration; +use tempfile::TempDir; + +#[tokio::test] +async fn test_runtime_server_client_ipc_lifecycle() { + let temp_dir = TempDir::new().expect("Failed to create tempdir"); + let socket_path = temp_dir.path().join("runtime.sock"); + + let kv_manager = create_shared_kv_manager(1024, 16); + let scheduler_config = SchedulerConfig { + max_batch_size: 64, + max_batch_tokens: 4096, + prefill_chunk_size: 64, + watermark_blocks: 16, + chunk_prefill: true, + max_prefill_tokens: 4096, + }; + + let spine = AienRuntimeSpine::new(1024, scheduler_config, kv_manager); + let server = AienRuntimeServer::new(spine, &socket_path); + + // Run server in background task + let server_handle = tokio::spawn(async move { + let backend = MockInferenceBackend::new(1); + server.run(backend).await + }); + + // Wait for server to bind socket + let client = AienRuntimeClient::new(&socket_path); + let mut alive = false; + for _ in 0..50 { + if client.is_alive().await { + alive = true; + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert!(alive, "Runtime server failed to bind and become alive"); + + // 1. Initial status query + let initial_status = client.get_status().await.expect("Failed to get status"); + assert_eq!(initial_status.active_sequences, 0); + assert_eq!(initial_status.active_swarms, 0); + + // 2. Launch swarm over socket IPC + let prompt_tokens: Vec = (1..=32).collect(); + let launch_req = LaunchSwarmReq { + model_handle: 1, + branch_count: 8, + max_active_sequences: 8, + max_tokens_per_branch: 8, + root_world_id: 0, + priority: 1, + prompt_tokens, + }; + + let swarm_id = client + .launch_swarm(launch_req) + .await + .expect("Failed to launch swarm over IPC"); + assert_eq!(swarm_id, 1); + + // 3. Allow background engine worker to execute branch steps + let mut completed = false; + for _ in 0..100 { + let status = client.get_status().await.expect("Failed to query status"); + // Root sequence remains as context anchor, child branches finish + if status.active_sequences <= 1 { + completed = true; + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert!(completed, "Swarm branches did not complete within budget"); + + // 4. Shutdown server cleanly over IPC + client + .shutdown() + .await + .expect("Failed to send shutdown command"); + + let server_res = server_handle + .await + .expect("Server task panicked") + .expect("Server exited with error"); + assert_eq!(server_res, ()); + + // Verify socket file was cleaned up on clean exit + assert!( + !socket_path.exists(), + "Socket file should be unlinked after shutdown" + ); +}