Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/patches/54fd88f00e5a9da6 # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-sovereign-core-mv#122 (code only) closed derived `54fd88f00e5a9da6` #122 Imported from GitHub aien-dev/aien-sovereign-core-mv#122 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `4cd50c40684d37969c08f3de9d2336194c218be7` · Head `94c282182bdd7f119c2a13fbf79330c811886ea2` ### Fetch it A git bundle of the pull request's head, 10576 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/54fd88f00e5a9da6.bundle -o 54fd88f00e5a9da6.bundle git fetch 54fd88f00e5a9da6.bundle refs/pull/122/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 122 94c282182bdd7f119c2a13fbf79330c811886ea2 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":122,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/122","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:02Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/Cargo.lock b/Cargo.lock index adb56e78..257e0237 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -217,6 +217,7 @@ dependencies = [ "aien-security", "async-trait", "cortex-rs", + "libc", "parking_lot", "serde", "serde_json", diff --git a/crates/aien-cli/tests/test_cli_runtime_ipc.rs b/crates/aien-cli/tests/test_cli_runtime_ipc.rs index 616659af..4fce0fe2 100644 --- a/crates/aien-cli/tests/test_cli_runtime_ipc.rs +++ b/crates/aien-cli/tests/test_cli_runtime_ipc.rs @@ -14,6 +14,8 @@ 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()); + // Keep the idempotency log out of the shared /tmp default used by a live runtime. + std::env::set_var("AIEN_RUNTIME_STATE_DIR", temp_dir.path()); let kv_manager = create_shared_kv_manager(512, 16); let sched_cfg = SchedulerConfig { @@ -74,7 +76,17 @@ async fn test_cli_runtime_ipc_lifecycle() { .inspect_swarm(swarm_id) .await .expect("Inspect must succeed"); - assert!(swarm_status.active_sequences >= 1); + // The mock backend may finish all branches before this request lands, so + // assert the swarm-scoped invariant rather than a still-running count. + assert!( + swarm_status.active_sequences <= 4, + "at most the 4 launched branches" + ); + assert_eq!( + swarm_status.active_swarms == 1, + swarm_status.active_sequences > 0, + "swarm is active exactly while it has running branches" + ); // 4. Clean shutdown client.shutdown().await.expect("Shutdown must succeed"); diff --git a/crates/aien-runtime/Cargo.toml b/crates/aien-runtime/Cargo.toml index 2ce0dc74..2a8c4687 100644 --- a/crates/aien-runtime/Cargo.toml +++ b/crates/aien-runtime/Cargo.toml @@ -23,6 +23,7 @@ sha2 = "0.10" tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } async-trait = "0.1" +libc = "0.2" thiserror = "1.0" [dev-dependencies] diff --git a/crates/aien-runtime/src/client.rs b/crates/aien-runtime/src/client.rs index 83c10b0b..3edf9c96 100644 --- a/crates/aien-runtime/src/client.rs +++ b/crates/aien-runtime/src/client.rs @@ -45,6 +45,13 @@ impl AienRuntimeClient { ) })?; + if !crate::server::peer_is_current_user(&stream) { + return Err(format!( + "Refusing runtime socket at {}: server runs as a different user", + self.socket_path.display() + )); + } + let (reader, mut writer) = stream.into_split(); let mut buf_reader = BufReader::new(reader); @@ -134,6 +141,12 @@ impl AienRuntimeClient { e ) })?; + if !crate::server::peer_is_current_user(&stream) { + return Err(format!( + "Refusing runtime socket at {}: server runs as a different user", + self.socket_path.display() + )); + } let (reader, mut writer) = stream.into_split(); let mut buf_reader = BufReader::new(reader); let now = std::time::SystemTime::now() diff --git a/crates/aien-runtime/src/control.rs b/crates/aien-runtime/src/control.rs index f8a8ada3..d92ebe27 100644 --- a/crates/aien-runtime/src/control.rs +++ b/crates/aien-runtime/src/control.rs @@ -135,7 +135,13 @@ impl RuntimeController { self.processed_operations.insert(op_id); let ids: Vec = self.processed_operations.iter().copied().collect(); if let Ok(bytes) = serde_json::to_vec(&ids) { - let _ = std::fs::write(operations_state_path(), bytes); + // Write then rename: a crash mid-write must not leave a truncated + // file, which new() would silently discard, losing idempotency. + let path = operations_state_path(); + let tmp = path.with_extension(format!("json.tmp.{}", std::process::id())); + if std::fs::write(&tmp, bytes).is_ok() && std::fs::rename(&tmp, &path).is_err() { + let _ = std::fs::remove_file(&tmp); + } } } } diff --git a/crates/aien-runtime/src/server.rs b/crates/aien-runtime/src/server.rs index 9bb7b5d2..d3e9a4d8 100644 --- a/crates/aien-runtime/src/server.rs +++ b/crates/aien-runtime/src/server.rs @@ -12,6 +12,15 @@ use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; use tokio::net::{UnixListener, UnixStream}; use tokio::sync::{Mutex, Notify}; +/// True when the process on the other end of `stream` runs as this process's +/// effective user. The default socket lives in shared /tmp, so both ends check +/// peer credentials instead of trusting whoever created the path. +pub(crate) fn peer_is_current_user(stream: &UnixStream) -> bool { + // SAFETY: geteuid has no preconditions and cannot fail. + let euid = unsafe { libc::geteuid() }; + stream.peer_cred().map(|c| c.uid() == euid).unwrap_or(false) +} + pub struct AienRuntimeServer { socket_path: PathBuf, spine: Arc>, @@ -74,6 +83,17 @@ impl AienRuntimeServer { e ) })?; + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&self.socket_path, std::fs::Permissions::from_mode(0o600)) + .map_err(|e| { + format!( + "Failed to restrict runtime socket {} to owner: {}", + self.socket_path.display(), + e + ) + })?; + } self.is_running.store(true, Ordering::SeqCst); @@ -111,6 +131,10 @@ impl AienRuntimeServer { accept_res = listener.accept() => { match accept_res { Ok((stream, _)) => { + if !peer_is_current_user(&stream) { + tracing::warn!("rejected runtime connection from another user"); + continue; + } let spine_conn = self.spine.clone(); let is_running_conn = self.is_running.clone(); let notify_conn = self.shutdown_notify.clone(); diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs index 6b0ff41f..77293c17 100644 --- a/crates/aien-runtime/src/spine.rs +++ b/crates/aien-runtime/src/spine.rs @@ -7,7 +7,7 @@ use crate::control::{ ControlCommand, ControlEnvelope, ControlResponse, RuntimeController, RuntimeStatusReport, }; use crate::sequence::{SequenceArena, SequenceId, SequenceState}; -use crate::swarm::{SwarmConfig, SwarmManager}; +use crate::swarm::{SwarmConfig, SwarmManager, SwarmState}; use crate::world::WorldStore; use aien_inference_abi::{AienInferenceBackend, SamplingParams, StepMetrics}; @@ -268,14 +268,10 @@ impl AienRuntimeSpine { } } ControlCommand::GetRuntimeStatus => ControlResponse::Status(self.status_report()), - ControlCommand::InspectSwarm(swarm_id) => { - if let Some(swarm) = self.swarm_manager.get_swarm(swarm_id) { - let _ = swarm; - ControlResponse::Status(self.status_report()) - } else { - ControlResponse::Error(format!("Swarm {} not found", swarm_id)) - } - } + ControlCommand::InspectSwarm(swarm_id) => match self.swarm_status_report(swarm_id) { + Some(report) => ControlResponse::Status(report), + None => ControlResponse::Error(format!("Swarm {} not found", swarm_id)), + }, ControlCommand::StreamTurn { .. } => ControlResponse::Error( "StreamTurn is handled on the socket connection, not as a one-shot command".into(), ), @@ -289,6 +285,32 @@ impl AienRuntimeSpine { resp } + /// Status scoped to one swarm. Sequence, swarm, and world counts cover only + /// this swarm; KV block and page fields describe the shared runtime pool. + pub fn swarm_status_report(&self, swarm_id: u64) -> Option { + let swarm = self.swarm_manager.get_swarm(swarm_id)?; + let running = swarm.state == SwarmState::Running; + let active_sequences = if running { + swarm + .branch_sequences + .len() + .saturating_sub(swarm.finished_branches.len()) + } else { + 0 + }; + let active_worlds = swarm + .branch_worlds + .iter() + .filter(|&&w| self.world_store.get_world(w).is_some()) + .count(); + Some(RuntimeStatusReport { + active_sequences, + active_swarms: usize::from(running), + active_worlds, + ..self.status_report() + }) + } + pub fn status_report(&self) -> RuntimeStatusReport { let kv = self.kv_manager.read(); let metrics = kv.metrics(); diff --git a/crates/aien-runtime/tests/runtime_socket_permissions_test.rs b/crates/aien-runtime/tests/runtime_socket_permissions_test.rs new file mode 100644 index 00000000..944816c1 --- /dev/null +++ b/crates/aien-runtime/tests/runtime_socket_permissions_test.rs @@ -0,0 +1,52 @@ +//! The runtime socket accepts operator commands (launch, cancel, shutdown), so +//! it must be reachable only by its owner. + +use aien_inference_abi::MockInferenceBackend; +use aien_kv_cache::create_shared_kv_manager; +use aien_runtime::client::AienRuntimeClient; +use aien_runtime::server::AienRuntimeServer; +use aien_runtime::spine::AienRuntimeSpine; +use aien_scheduler::SchedulerConfig; +use std::os::unix::fs::PermissionsExt; +use std::time::Duration; + +#[tokio::test] +async fn runtime_socket_is_owner_only() { + let dir = std::env::temp_dir().join(format!("aien-sock-perm-{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + std::env::set_var("AIEN_RUNTIME_STATE_DIR", &dir); + let socket_path = dir.join("runtime.sock"); + + let scheduler_config = SchedulerConfig { + max_batch_size: 8, + max_batch_tokens: 512, + prefill_chunk_size: 64, + watermark_blocks: 4, + chunk_prefill: true, + max_prefill_tokens: 512, + }; + let spine = AienRuntimeSpine::new(64, scheduler_config, create_shared_kv_manager(128, 16)); + let server = AienRuntimeServer::new(spine, &socket_path); + let handle = tokio::spawn(async move { server.run(MockInferenceBackend::new(1)).await }); + + // Wait until the server answers: the file exists from bind(), but the + // mode is only final once the server is serving. + let client = AienRuntimeClient::new(&socket_path); + for _ in 0..250 { + if client.is_alive().await { + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + let mode = std::fs::metadata(&socket_path) + .ok() + .map(|meta| meta.permissions().mode() & 0o777); + handle.abort(); + let _ = std::fs::remove_file(&socket_path); + + assert_eq!( + mode, + Some(0o600), + "runtime socket must be owner read/write only" + ); +} diff --git a/crates/aien-runtime/tests/swarm_inspect_scoping_test.rs b/crates/aien-runtime/tests/swarm_inspect_scoping_test.rs new file mode 100644 index 00000000..11a11e94 --- /dev/null +++ b/crates/aien-runtime/tests/swarm_inspect_scoping_test.rs @@ -0,0 +1,109 @@ +//! Integration test: InspectSwarm reports the requested swarm, not runtime-wide totals. + +use aien_inference_abi::MockInferenceBackend; +use aien_kv_cache::create_shared_kv_manager; +use aien_runtime::control::{ + ControlCommand, ControlEnvelope, ControlResponse, LaunchSwarmReq, RuntimeStatusReport, +}; +use aien_runtime::spine::AienRuntimeSpine; +use aien_scheduler::SchedulerConfig; + +fn envelope(operation_id: u64, command: ControlCommand) -> ControlEnvelope { + ControlEnvelope { + protocol_version: 1, + request_id: operation_id, + operation_id: operation_id.into(), + operator_session: 1, + command, + } +} + +fn launch(spine: &mut AienRuntimeSpine, operation_id: u64, branch_count: usize) -> u64 { + let req = LaunchSwarmReq { + model_handle: 1, + branch_count, + max_active_sequences: 8, + max_tokens_per_branch: 4, + root_world_id: 0, + priority: 1, + prompt_tokens: vec![1, 2, 3], + }; + match spine.handle_control_command(envelope(operation_id, ControlCommand::LaunchSwarm(req))) { + ControlResponse::SwarmAccepted { swarm_id, .. } => swarm_id, + other => panic!("launch failed: {:?}", other), + } +} + +fn inspect(spine: &mut AienRuntimeSpine, operation_id: u64, swarm_id: u64) -> ControlResponse { + spine.handle_control_command(envelope( + operation_id, + ControlCommand::InspectSwarm(swarm_id), + )) +} + +fn status(resp: ControlResponse) -> RuntimeStatusReport { + match resp { + ControlResponse::Status(report) => report, + other => panic!("expected Status, got {:?}", other), + } +} + +#[tokio::test] +async fn inspect_swarm_is_scoped_to_the_requested_swarm() { + let state_dir = std::env::temp_dir().join(format!("aien-swarm-inspect-{}", std::process::id())); + let _ = std::fs::create_dir_all(&state_dir); + std::env::set_var("AIEN_RUNTIME_STATE_DIR", &state_dir); + + 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 mut spine = + AienRuntimeSpine::new(1024, scheduler_config, create_shared_kv_manager(1024, 16)); + + let small = launch(&mut spine, 1, 2); + let large = launch(&mut spine, 2, 5); + + let small_status = status(inspect(&mut spine, 3, small)); + let large_status = status(inspect(&mut spine, 4, large)); + assert_eq!( + small_status.active_sequences, 2, + "only this swarm's branches" + ); + assert_eq!( + large_status.active_sequences, 5, + "only this swarm's branches" + ); + assert_eq!(small_status.active_swarms, 1); + assert_eq!(small_status.active_worlds, 2, "one live world per branch"); + assert!( + spine.status_report().active_sequences > small_status.active_sequences, + "runtime-wide count must exceed a single swarm's count" + ); + + let mut backend = MockInferenceBackend::new(1); + spine + .run_until_complete(&mut backend, 200) + .await + .expect("run_until_complete"); + + let done = status(inspect(&mut spine, 5, small)); + assert_eq!( + done.active_sequences, 0, + "completed swarm has no active branches" + ); + assert_eq!(done.active_swarms, 0); + assert_eq!( + done.active_worlds, 0, + "branch worlds are dropped on completion" + ); + + assert!(matches!( + inspect(&mut spine, 6, 999), + ControlResponse::Error(_) + )); +} diff --git a/scripts/agent-preflight.sh b/scripts/agent-preflight.sh index f617e035..4b0093ee 100755 --- a/scripts/agent-preflight.sh +++ b/scripts/agent-preflight.sh @@ -30,9 +30,12 @@ else echo "PASSED (Zero disk secrets detected)" fi -# Step 3: Unslop and Sovereign Voice Audit on Staged / Working Changes +# Step 3: Unslop and Sovereign Voice Audit on the branch (committed + working changes) echo -n "[3/5] Verifying Unslop & Anti-Slop Discipline... " -DASH_VIOLATIONS=$(git diff HEAD -- ':(exclude)*.lock' ':(exclude)*.svg' ':(exclude)*.bin' 2>/dev/null | grep -E '^\+[^+]' | grep -E '(—|–)' | grep -v "replace" | grep -v "contains" | grep -v "ZERO EM DASHES" | grep -v "forbidden" | grep -v "assert\!" || true) +# Diff against the merge base with main so committed branch work is audited, +# not only uncommitted edits. Falls back to HEAD when no main ref exists. +DIFF_BASE=$(git merge-base HEAD origin/main 2>/dev/null || git merge-base HEAD main 2>/dev/null || echo HEAD) +DASH_VIOLATIONS=$(git diff "$DIFF_BASE" --':(exclude)*.lock' ':(exclude)*.svg' ':(exclude)*.bin' 2>/dev/null | grep -E '^\+[^+]' | grep -E '(—|–)' | grep -v "replace" | grep -v "contains" | grep -v "ZERO EM DASHES" | grep -v "forbidden" | grep -v "assert\!" || true) if [ -n "$DASH_VIOLATIONS" ]; then echo "FAILED" echo "Error: Prohibited em dash or en dash characters introduced in git diff:" @@ -53,10 +56,13 @@ fi # Step 5: Vulnerability & Advisory Audit echo -n "[5/5] Checking RustSec Vulnerability Advisories... " -if cargo audit 2>/dev/null; then - echo "PASSED (0 advisories)" +if ! cargo audit --version >/dev/null 2>&1; then + echo "SKIPPED (cargo-audit not installed)" +elif cargo audit; then + echo "PASSED (No vulnerabilities; review any warnings above)" else - echo "PASSED WITH WARNINGS (Check cargo audit logs)" + echo "FAILED (Vulnerabilities reported above)" + FAILED=1 fi echo "============================================================" ```