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
aien-sovereign-core-mv / crates / aien-runtime / src / spine.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Canonical AienRuntimeSpine |
| 17 | //! Unifies SequenceArena, AienScheduler, AienKvManager, WorldStore, ContextComposer, |
| 18 | //! and SwarmManager in a single process address space. |
| 19 | |
| 20 | use crate::context::ContextComposer; |
| 21 | use crate::control::{ |
| 22 | ControlCommand, ControlEnvelope, ControlResponse, RuntimeController, RuntimeStatusReport, |
| 23 | }; |
| 24 | use crate::kv_residency::{KvDrainHandle, KvResidency, KvResidencyStatus}; |
| 25 | use crate::sequence::{SequenceArena, SequenceId, SequenceState}; |
| 26 | use crate::swarm::{SwarmConfig, SwarmManager, SwarmState}; |
| 27 | use crate::world::WorldStore; |
| 28 | |
| 29 | use aien_abi_core::{AienInferenceBackend, SamplingParams, StepMetrics}; |
| 30 | use aien_kv_cache::AienKvManager; |
| 31 | use aien_scheduler::{ |
| 32 | AienScheduler, CompletionSink, CompletionSinkId, PromptHandle, SchedulerConfig, |
| 33 | }; |
| 34 | use parking_lot::RwLock; |
| 35 | use std::sync::Arc; |
| 36 | |
| 37 | pub struct AienRuntimeSpine { |
| 38 | pub arena: SequenceArena, |
| 39 | pub kv_manager: Arc<RwLock<AienKvManager>>, |
| 40 | pub scheduler: AienScheduler, |
| 41 | pub world_store: WorldStore, |
| 42 | pub context_composer: ContextComposer, |
| 43 | pub swarm_manager: SwarmManager, |
| 44 | pub controller: RuntimeController, |
| 45 | pub step_counter: u64, |
| 46 | /// Subagent forks whose KV is already forked but whose backend state is |
| 47 | /// not yet: (parent, child) KV ids, applied via the backend's |
| 48 | /// `fork_sequence` at the start of the next `step`, before any decode. |
| 49 | pending_backend_forks: Vec<(u64, u64)>, |
| 50 | /// PREFILL-E2E C5: sequence ids whose KV and arena slots were reclaimed |
| 51 | /// without a backend in reach (swarm cancel). Their backend per-sequence |
| 52 | /// state is released by `release_pending_backend_sequences`, which `step` |
| 53 | /// calls first. |
| 54 | pending_backend_releases: Vec<u64>, |
| 55 | /// Persistent KV (ADR 0003 section 6): park at the finish transaction, |
| 56 | /// restore at submit. `None` (the default) is today's behaviour exactly. |
| 57 | kv_residency: Option<KvResidency>, |
| 58 | /// Why persistence was refused at start (ADR 0003 section 20: store key |
| 59 | /// missing or malformed). `Some` only with the store dir set; then there |
| 60 | /// is no residency and every prompt is prefilled. |
| 61 | kv_persist_refused: Option<&'static str>, |
| 62 | } |
| 63 | |
| 64 | impl AienRuntimeSpine { |
| 65 | pub fn new( |
| 66 | arena_capacity: usize, |
| 67 | scheduler_config: SchedulerConfig, |
| 68 | kv_manager: Arc<RwLock<AienKvManager>>, |
| 69 | ) -> Self { |
| 70 | let scheduler = AienScheduler::new(scheduler_config, kv_manager.clone()); |
| 71 | Self { |
| 72 | arena: SequenceArena::new(arena_capacity), |
| 73 | kv_manager, |
| 74 | scheduler, |
| 75 | world_store: WorldStore::new(), |
| 76 | context_composer: ContextComposer::new(), |
| 77 | swarm_manager: SwarmManager::new(), |
| 78 | controller: RuntimeController::new(), |
| 79 | step_counter: 0, |
| 80 | pending_backend_forks: Vec::new(), |
| 81 | pending_backend_releases: Vec::new(), |
| 82 | kv_residency: None, |
| 83 | kv_persist_refused: None, |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | /// Submits structured InferenceWork with PromptHandle and optional completion sink. |
| 88 | pub fn submit_inference_work( |
| 89 | &mut self, |
| 90 | work: aien_platform::queue::InferenceWork, |
| 91 | prompt: PromptHandle, |
| 92 | sampling_params: Option<SamplingParams>, |
| 93 | sink_id: Option<CompletionSinkId>, |
| 94 | ) -> Result<(), String> { |
| 95 | self.scheduler |
| 96 | .submit_work(work, prompt, sampling_params, sink_id) |
| 97 | .map(|_| ()) |
| 98 | } |
| 99 | |
| 100 | /// Submits a prompt ticket to the scheduler for execution, constructing default InferenceWork. |
| 101 | pub fn submit_work( |
| 102 | &mut self, |
| 103 | prompt: PromptHandle, |
| 104 | sampling_params: SamplingParams, |
| 105 | priority: u8, |
| 106 | sink_id: Option<CompletionSinkId>, |
| 107 | ) -> Result<u64, String> { |
| 108 | self.step_counter += 1; |
| 109 | let seq_id = self.step_counter; |
| 110 | let plat_priority = match priority { |
| 111 | 0 => aien_platform::Priority::Background, |
| 112 | 1 => aien_platform::Priority::Normal, |
| 113 | 2 => aien_platform::Priority::Interactive, |
| 114 | _ => aien_platform::Priority::Realtime, |
| 115 | }; |
| 116 | let work = aien_platform::queue::InferenceWork { |
| 117 | sequence: seq_id, |
| 118 | model: aien_platform::ModelHandle(1), |
| 119 | kv: aien_platform::queue::KvHandle(seq_id), |
| 120 | priority: plat_priority, |
| 121 | deadline: None, |
| 122 | branch_parent: None, |
| 123 | next_token_budget: sampling_params.max_tokens as u32, |
| 124 | }; |
| 125 | let assigned = self |
| 126 | .scheduler |
| 127 | .submit_work(work, prompt, Some(sampling_params), sink_id)?; |
| 128 | self.try_restore(assigned); |
| 129 | Ok(assigned.to_u64()) |
| 130 | } |
| 131 | |
| 132 | /// Submits a plain `SequenceRequest` (the scheduler assigns the id) and, |
| 133 | /// with persistent KV enabled, starts the restore of its stored prefix |
| 134 | /// (ADR 0003 section 6.3). A miss or any refusal leaves a plain prefill; |
| 135 | /// a request is never refused because of the cache. |
| 136 | pub fn submit_request(&mut self, request: aien_abi_core::SequenceRequest) -> u64 { |
| 137 | let seq = self.scheduler.submit_request(request); |
| 138 | self.try_restore(seq); |
| 139 | seq.to_u64() |
| 140 | } |
| 141 | |
| 142 | fn try_restore(&mut self, seq: aien_scheduler::SequenceId) { |
| 143 | if let Some(r) = self.kv_residency.as_mut() { |
| 144 | r.try_restore(&mut self.scheduler, seq); |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | /// Turns persistent KV on: installs the park hook in the scheduler's finish |
| 149 | /// transaction (S1) and hands S2 the scheduler's watermark. |
| 150 | pub fn enable_kv_residency(&mut self, mut residency: KvResidency) { |
| 151 | residency.set_watermark_blocks(self.scheduler.config().watermark_blocks); |
| 152 | self.scheduler |
| 153 | .set_finish_hook(Some(residency.finish_hook())); |
| 154 | self.kv_residency = Some(residency); |
| 155 | } |
| 156 | |
| 157 | /// Records that persistence was refused (fail closed): no residency is |
| 158 | /// installed, and the status reports state `refused` with `reason`. |
| 159 | pub fn refuse_kv_persistence(&mut self, reason: &'static str) { |
| 160 | self.kv_persist_refused = Some(reason); |
| 161 | } |
| 162 | |
| 163 | pub fn kv_residency(&self) -> Option<&KvResidency> { |
| 164 | self.kv_residency.as_ref() |
| 165 | } |
| 166 | |
| 167 | /// Persistent-KV status fields (METRICS_AND_SETTINGS), `None` when off. |
| 168 | pub fn kv_residency_status(&self) -> Option<KvResidencyStatus> { |
| 169 | self.kv_residency.as_ref().map(KvResidency::status) |
| 170 | } |
| 171 | |
| 172 | /// The shutdown drain of the persistent-KV store (ADR 7.5), `None` when off. |
| 173 | pub fn kv_drain_handle(&self) -> Option<KvDrainHandle> { |
| 174 | self.kv_residency.as_ref().map(KvResidency::drain_handle) |
| 175 | } |
| 176 | |
| 177 | /// Registers a completion sink for streaming output events. |
| 178 | pub fn register_completion_sink(&mut self, sink: Arc<dyn CompletionSink>) -> CompletionSinkId { |
| 179 | self.scheduler.register_completion_sink(sink) |
| 180 | } |
| 181 | |
| 182 | /// Zero-copy subagent sequence branching with completion sink routing. |
| 183 | pub fn fork_subagent( |
| 184 | &mut self, |
| 185 | parent_id: u64, |
| 186 | child_id: u64, |
| 187 | sink_id: Option<CompletionSinkId>, |
| 188 | ) -> Result<(), String> { |
| 189 | let ids = self |
| 190 | .scheduler |
| 191 | .fork_subagent_with_sink_ids(parent_id, child_id, sink_id)?; |
| 192 | // The backend is not reachable here; its state is forked at the start |
| 193 | // of the next step, before the child can be decoded. |
| 194 | self.pending_backend_forks.push(ids); |
| 195 | Ok(()) |
| 196 | } |
| 197 | |
| 198 | /// Executes runtime steps in a closed loop until all active requests complete or max_steps is reached. |
| 199 | pub async fn run_until_complete<B: AienInferenceBackend>( |
| 200 | &mut self, |
| 201 | backend: &mut B, |
| 202 | max_steps: usize, |
| 203 | ) -> Result<Vec<StepMetrics>, String> { |
| 204 | let mut all_metrics = Vec::new(); |
| 205 | for _ in 0..max_steps { |
| 206 | if self.scheduler.waiting_count() == 0 |
| 207 | && self.scheduler.running_count() == 0 |
| 208 | && self.scheduler.preempted_count() == 0 |
| 209 | { |
| 210 | break; |
| 211 | } |
| 212 | if let Some(metrics) = self.step(backend).await? { |
| 213 | all_metrics.push(metrics); |
| 214 | } |
| 215 | } |
| 216 | Ok(all_metrics) |
| 217 | } |
| 218 | |
| 219 | /// Advances the engine by one transactional step. |
| 220 | pub async fn step<B: AienInferenceBackend>( |
| 221 | &mut self, |
| 222 | backend: &mut B, |
| 223 | ) -> Result<Option<StepMetrics>, String> { |
| 224 | self.step_counter += 1; |
| 225 | |
| 226 | // PREFILL-E2E C5: backend state of sequences cancelled since the last |
| 227 | // step; their KV is already freed. CancelSwarm also frees them in the |
| 228 | // scheduler arena, so queued copies are stale and never re-admitted. |
| 229 | self.release_pending_backend_sequences(backend)?; |
| 230 | |
| 231 | // PREFILL-E2E C4: backend state for subagent forks made since the |
| 232 | // last step, before the scheduler can decode the children. |
| 233 | for (parent, child) in std::mem::take(&mut self.pending_backend_forks) { |
| 234 | backend.fork_sequence(parent, child)?; |
| 235 | } |
| 236 | |
| 237 | // PREFILL-GATE: run the model prefill over each pending swarm root |
| 238 | // prompt BEFORE any branch can be scheduled, then share the computed |
| 239 | // root blocks with the branches. Branches never see root blocks that |
| 240 | // have not passed the completion fence. |
| 241 | let root_prefill_tokens = self.prefill_pending_swarm_roots(backend).await?; |
| 242 | |
| 243 | // Persistent KV (ADR 0003 sections 5.4 and 8): completions are polled on |
| 244 | // this thread, never waited for; S3 commits finished restores here, |
| 245 | // before the scheduler builds its batch, so a restored request's suffix |
| 246 | // can be scheduled in this very step. |
| 247 | if let Some(r) = self.kv_residency.as_mut() { |
| 248 | r.poll(&mut self.scheduler, backend); |
| 249 | } |
| 250 | |
| 251 | // Execute scheduler step via backend |
| 252 | let step_result = self.scheduler.step(backend).await; |
| 253 | |
| 254 | // Park what this step's finish transactions forked (S1), with no lock |
| 255 | // held; submit never blocks on I/O. |
| 256 | if let Some(r) = self.kv_residency.as_mut() { |
| 257 | r.drain_outbox(); |
| 258 | } |
| 259 | let step_result = step_result?; |
| 260 | |
| 261 | if step_result.is_none() && root_prefill_tokens > 0 { |
| 262 | return Ok(Some(StepMetrics { |
| 263 | prefill_tokens_processed: root_prefill_tokens, |
| 264 | active_kv_blocks: self.kv_manager.read().allocated_block_count(), |
| 265 | ..StepMetrics::default() |
| 266 | })); |
| 267 | } |
| 268 | |
| 269 | if let Some((outputs, mut metrics)) = step_result { |
| 270 | metrics.prefill_tokens_processed += root_prefill_tokens; |
| 271 | // Generational SequenceId validation on step completion |
| 272 | for output in &outputs { |
| 273 | match output { |
| 274 | aien_abi_core::DecodeOutput::Token { |
| 275 | request_id, |
| 276 | token_id: _, |
| 277 | logprob: _, |
| 278 | } => { |
| 279 | let seq_id = SequenceId::from_u64(*request_id); |
| 280 | if let Some(record) = self.arena.get_mut(seq_id) { |
| 281 | record.generated_tokens += 1; |
| 282 | } |
| 283 | } |
| 284 | aien_abi_core::DecodeOutput::Finished { |
| 285 | request_id, |
| 286 | reason: _, |
| 287 | total_tokens: _, |
| 288 | } => { |
| 289 | let seq_id = SequenceId::from_u64(*request_id); |
| 290 | if let Some(record) = self.arena.get_mut(seq_id) { |
| 291 | record.state = SequenceState::Completed; |
| 292 | } |
| 293 | self.arena.free(seq_id); |
| 294 | let reclaimed_root = { |
| 295 | let mut kv = self.kv_manager.write(); |
| 296 | self.swarm_manager.note_sequence_finished( |
| 297 | seq_id, |
| 298 | &mut self.arena, |
| 299 | &mut kv, |
| 300 | &mut self.world_store, |
| 301 | ) |
| 302 | }; |
| 303 | // PREFILL-E2E C5 (bullet 12): drop the backend's |
| 304 | // per-sequence state. Safe order: this runs after |
| 305 | // execute_step returned, so the backend no longer |
| 306 | // reads this sequence's KV (the scheduler already |
| 307 | // freed it), and the KV lock is released first. The |
| 308 | // root goes last, once its final branch finished: |
| 309 | // branches hold their own copy of the root's tokens |
| 310 | // (fork_sequence) and never read the root's state. |
| 311 | backend.release_sequence(*request_id)?; |
| 312 | if let Some(root) = reclaimed_root { |
| 313 | backend.release_sequence(root.as_u64())?; |
| 314 | } |
| 315 | } |
| 316 | } |
| 317 | } |
| 318 | Ok(Some(metrics)) |
| 319 | } else { |
| 320 | Ok(None) |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | /// PREFILL-E2E C5: releases the backend per-sequence state of every |
| 325 | /// sequence reclaimed without a backend in reach (swarm cancel). Runs at |
| 326 | /// the start of each `step`; callers that stop stepping after a cancel |
| 327 | /// call it directly. Returns the number of ids released. |
| 328 | pub fn release_pending_backend_sequences<B: AienInferenceBackend>( |
| 329 | &mut self, |
| 330 | backend: &mut B, |
| 331 | ) -> Result<usize, String> { |
| 332 | let ids = std::mem::take(&mut self.pending_backend_releases); |
| 333 | // A cancelled sequence must not be forked from or into afterwards. |
| 334 | self.pending_backend_forks |
| 335 | .retain(|(parent, child)| !ids.contains(parent) && !ids.contains(child)); |
| 336 | for &id in &ids { |
| 337 | backend.release_sequence(id)?; |
| 338 | } |
| 339 | Ok(ids.len()) |
| 340 | } |
| 341 | |
| 342 | /// Prefills every pending swarm root through the scheduler's completion |
| 343 | /// fence and, once the root is PrefillReady, shares its blocks with the |
| 344 | /// branches. Returns the number of root prompt tokens prefilled. |
| 345 | async fn prefill_pending_swarm_roots<B: AienInferenceBackend>( |
| 346 | &mut self, |
| 347 | backend: &mut B, |
| 348 | ) -> Result<usize, String> { |
| 349 | let mut prefilled = 0usize; |
| 350 | for (swarm_id, root_kv_id, prompt) in self.swarm_manager.pending_root_prefills() { |
| 351 | if let Some(m) = self |
| 352 | .scheduler |
| 353 | .prefill_detached(backend, root_kv_id, &prompt) |
| 354 | .await? |
| 355 | { |
| 356 | prefilled += m.prefill_tokens_processed; |
| 357 | } |
| 358 | { |
| 359 | let mut kv = self.kv_manager.write(); |
| 360 | self.swarm_manager.fork_branches_from_ready_root( |
| 361 | swarm_id, |
| 362 | &mut self.arena, |
| 363 | &mut kv, |
| 364 | )?; |
| 365 | } |
| 366 | // PREFILL-E2E C4 (bullets 6-8): fork the backend's per-sequence |
| 367 | // state (tokens, position, last token) for each branch right after |
| 368 | // the physical KV fork and before any branch can be scheduled for |
| 369 | // decode. The KV lock is released first: the backend reads the |
| 370 | // same shared KV manager to check the parent is PrefillReady. |
| 371 | // PREFILL-E2E C6 (bullet 11): the fork hook also hands each |
| 372 | // branch its own sampling params (the same ones its scheduler |
| 373 | // request carries), so branches decode with temperature and a |
| 374 | // per-branch seed instead of all taking the argmax. |
| 375 | let (branches, sampling): (Vec<u64>, SamplingParams) = self |
| 376 | .swarm_manager |
| 377 | .get_swarm(swarm_id) |
| 378 | .map(|s| { |
| 379 | ( |
| 380 | s.branch_sequences.iter().map(|b| b.as_u64()).collect(), |
| 381 | branch_sampling_params(&s.config), |
| 382 | ) |
| 383 | }) |
| 384 | .unwrap_or_else(|| (Vec::new(), SamplingParams::default())); |
| 385 | for child in branches { |
| 386 | backend.fork_sequence_with_sampling(root_kv_id, child, &sampling)?; |
| 387 | } |
| 388 | } |
| 389 | Ok(prefilled) |
| 390 | } |
| 391 | |
| 392 | /// Launches a swarm of agents sharing an immutable root World and physical KV blocks. |
| 393 | /// Branch KV is shared from the root only after the root prompt prefill |
| 394 | /// completes (next `step`); until then branches cannot be decoded. |
| 395 | pub fn launch_swarm( |
| 396 | &mut self, |
| 397 | config: SwarmConfig, |
| 398 | prompt_tokens: &[u32], |
| 399 | ) -> Result<u64, String> { |
| 400 | let mut kv = self.kv_manager.write(); |
| 401 | let swarm_id = self.swarm_manager.launch_swarm( |
| 402 | config, |
| 403 | &mut self.arena, |
| 404 | &mut kv, |
| 405 | &mut self.world_store, |
| 406 | prompt_tokens, |
| 407 | self.step_counter, |
| 408 | )?; |
| 409 | |
| 410 | // Enqueue branch requests into scheduler |
| 411 | if let Some(swarm) = self.swarm_manager.get_swarm(swarm_id) { |
| 412 | for &child_seq in &swarm.branch_sequences { |
| 413 | let req = aien_abi_core::SequenceRequest { |
| 414 | request_id: child_seq.as_u64(), |
| 415 | prompt_tokens: prompt_tokens.to_vec(), |
| 416 | sampling_params: branch_sampling_params(&swarm.config), |
| 417 | arrival_time_ns: self.step_counter, |
| 418 | priority: swarm.config.priority, |
| 419 | }; |
| 420 | self.scheduler.submit_request(req); |
| 421 | } |
| 422 | } |
| 423 | |
| 424 | Ok(swarm_id) |
| 425 | } |
| 426 | |
| 427 | /// Handles a typed operator command with idempotency verification. |
| 428 | pub fn handle_control_command(&mut self, envelope: ControlEnvelope) -> ControlResponse { |
| 429 | if self |
| 430 | .controller |
| 431 | .is_operation_processed(envelope.operation_id) |
| 432 | { |
| 433 | return ControlResponse::Error(format!( |
| 434 | "Operation {} already processed", |
| 435 | envelope.operation_id |
| 436 | )); |
| 437 | } |
| 438 | |
| 439 | let resp = match envelope.command { |
| 440 | ControlCommand::LaunchSwarm(req) => { |
| 441 | let config = SwarmConfig { |
| 442 | model_handle: req.model_handle, |
| 443 | branch_count: req.branch_count, |
| 444 | max_active_sequences: req.max_active_sequences, |
| 445 | max_tokens_per_branch: req.max_tokens_per_branch, |
| 446 | root_world_id: req.root_world_id, |
| 447 | priority: req.priority, |
| 448 | }; |
| 449 | match self.launch_swarm(config, &req.prompt_tokens) { |
| 450 | Ok(swarm_id) => { |
| 451 | record_processed(&mut self.controller, envelope.operation_id); |
| 452 | ControlResponse::SwarmAccepted { |
| 453 | swarm_id, |
| 454 | operation_id: envelope.operation_id, |
| 455 | } |
| 456 | } |
| 457 | Err(e) => ControlResponse::Error(e), |
| 458 | } |
| 459 | } |
| 460 | ControlCommand::CancelSwarm(swarm_id) => { |
| 461 | let mut kv = self.kv_manager.write(); |
| 462 | match self.swarm_manager.cancel_swarm( |
| 463 | swarm_id, |
| 464 | &mut self.arena, |
| 465 | &mut kv, |
| 466 | &mut self.world_store, |
| 467 | ) { |
| 468 | Ok(released) => { |
| 469 | // KV, arena slots and branch worlds are reclaimed; |
| 470 | // backend state follows on the next step (C5). |
| 471 | // The scheduler keeps its own arena, with the same ids |
| 472 | // (submit_request inserts them explicitly). Free them |
| 473 | // there too, so queued or running copies turn stale |
| 474 | // and are never admitted or decoded again. |
| 475 | for &id in &released { |
| 476 | if let Ok(sid) = aien_scheduler::sequence::SequenceId::from_u64(id) { |
| 477 | self.scheduler.arena_mut().free_sequence(sid); |
| 478 | } |
| 479 | } |
| 480 | self.pending_backend_releases.extend(released); |
| 481 | record_processed(&mut self.controller, envelope.operation_id); |
| 482 | ControlResponse::SwarmCancelled { swarm_id } |
| 483 | } |
| 484 | Err(e) => ControlResponse::Error(e), |
| 485 | } |
| 486 | } |
| 487 | ControlCommand::GetRuntimeStatus => ControlResponse::Status(self.status_report()), |
| 488 | ControlCommand::InspectSwarm(swarm_id) => match self.swarm_status_report(swarm_id) { |
| 489 | Some(report) => ControlResponse::Status(report), |
| 490 | None => ControlResponse::Error(format!("Swarm {} not found", swarm_id)), |
| 491 | }, |
| 492 | ControlCommand::StreamTurn { .. } => ControlResponse::Error( |
| 493 | "StreamTurn is handled on the socket connection, not as a one-shot command".into(), |
| 494 | ), |
| 495 | ControlCommand::RunComposeTask { .. } |
| 496 | | ControlCommand::ComposeNote { .. } |
| 497 | | ControlCommand::ComposeRecall { .. } |
| 498 | | ControlCommand::RecoverComposeHome |
| 499 | | ControlCommand::ComposeEffectIntent { .. } |
| 500 | | ControlCommand::ComposeEffectAck { .. } |
| 501 | | ControlCommand::ComposeReconcile { .. } |
| 502 | | ControlCommand::ComposeControl { .. } |
| 503 | | ControlCommand::ComposeAuthorize { .. } |
| 504 | | ControlCommand::ComposeApprovedProposal { .. } |
| 505 | | ControlCommand::AllenStatus |
| 506 | | ControlCommand::AllenProfileShow |
| 507 | | ControlCommand::AllenProfileSet { .. } |
| 508 | | ControlCommand::AllenProfileHistory |
| 509 | | ControlCommand::AllenProfileRevert { .. } |
| 510 | | ControlCommand::AllenMemoryPut { .. } |
| 511 | | ControlCommand::AllenMemoryRecall { .. } |
| 512 | | ControlCommand::AllenMemoryInspect { .. } |
| 513 | | ControlCommand::AllenMemoryCorrect { .. } |
| 514 | | ControlCommand::AllenMemoryForget { .. } |
| 515 | | ControlCommand::AllenMemoryExport { .. } |
| 516 | | ControlCommand::AllenGoalsList { .. } |
| 517 | | ControlCommand::AllenGoalAdd { .. } |
| 518 | | ControlCommand::AllenGoalClose { .. } |
| 519 | | ControlCommand::AllenProfileReset { .. } => ControlResponse::Error( |
| 520 | "compose commands are handled on the socket connection, not as one-shot commands" |
| 521 | .into(), |
| 522 | ), |
| 523 | ControlCommand::Shutdown => { |
| 524 | record_processed(&mut self.controller, envelope.operation_id); |
| 525 | ControlResponse::ShutdownAck |
| 526 | } |
| 527 | }; |
| 528 | |
| 529 | resp |
| 530 | } |
| 531 | |
| 532 | /// Status scoped to one swarm. Sequence, swarm, and world counts cover only |
| 533 | /// this swarm; KV block and page fields describe the shared runtime pool. |
| 534 | pub fn swarm_status_report(&self, swarm_id: u64) -> Option<RuntimeStatusReport> { |
| 535 | let swarm = self.swarm_manager.get_swarm(swarm_id)?; |
| 536 | let running = swarm.state == SwarmState::Running; |
| 537 | let active_sequences = if running { |
| 538 | swarm |
| 539 | .branch_sequences |
| 540 | .len() |
| 541 | .saturating_sub(swarm.finished_branches.len()) |
| 542 | } else { |
| 543 | 0 |
| 544 | }; |
| 545 | let active_worlds = swarm |
| 546 | .branch_worlds |
| 547 | .iter() |
| 548 | .filter(|&&w| self.world_store.get_world(w).is_some()) |
| 549 | .count(); |
| 550 | Some(RuntimeStatusReport { |
| 551 | active_sequences, |
| 552 | active_swarms: usize::from(running), |
| 553 | active_worlds, |
| 554 | ..self.status_report() |
| 555 | }) |
| 556 | } |
| 557 | |
| 558 | pub fn status_report(&self) -> RuntimeStatusReport { |
| 559 | let mut report = self.pool_status_report(); |
| 560 | // After the pool guard is released: the residency status takes the KV |
| 561 | // read lock itself (a nested read could wait behind a queued writer). |
| 562 | report.kv_persist = match (&self.kv_residency, self.kv_persist_refused) { |
| 563 | (Some(r), _) => Some(Box::new(r.persist_report())), |
| 564 | (None, Some(reason)) => Some(Box::new(crate::control::KvPersistReport { |
| 565 | kv_store_state: "refused".to_string(), |
| 566 | kv_store_refused_reason: reason.to_string(), |
| 567 | kv_store_key_refused_total: aien_kv_store::seal::key_refusals_total(), |
| 568 | ..Default::default() |
| 569 | })), |
| 570 | (None, None) => None, |
| 571 | }; |
| 572 | report |
| 573 | } |
| 574 | |
| 575 | fn pool_status_report(&self) -> RuntimeStatusReport { |
| 576 | let kv = self.kv_manager.read(); |
| 577 | let metrics = kv.metrics(); |
| 578 | let free = kv.free_block_count(); |
| 579 | let allocated = kv.allocated_block_count(); |
| 580 | let total = free + allocated; |
| 581 | // Honest proxy until the GB10 telemetry hook lands: KV memory pressure |
| 582 | // as a percentage. This is memory pressure, not SM activity. |
| 583 | let pressure_pct = if total > 0 { |
| 584 | (allocated as f32 / total as f32) * 100.0 |
| 585 | } else { |
| 586 | 0.0 |
| 587 | }; |
| 588 | |
| 589 | RuntimeStatusReport { |
| 590 | active_sequences: self.arena.active_count(), |
| 591 | active_swarms: self.swarm_manager.active_swarm_count(), |
| 592 | active_worlds: self.world_store.active_world_count(), |
| 593 | free_kv_blocks: free, |
| 594 | total_kv_blocks: total, |
| 595 | shared_kv_pages: metrics.shared_pages, |
| 596 | cow_faults: metrics.cow_faults, |
| 597 | gpu_utilization_pct: pressure_pct, |
| 598 | kv_pool_allocated_bytes: kv.pool().map_or(0, |p| p.layout().total_bytes as u64), |
| 599 | kv_pool_total_blocks: total, |
| 600 | kv_pool_free_blocks: free, |
| 601 | kv_pool_used_blocks: allocated, |
| 602 | kv_pool_holder_blocks: kv.holder_block_count(), |
| 603 | kv_persist: None, |
| 604 | } |
| 605 | } |
| 606 | } |
| 607 | |
| 608 | /// Sampling params of every swarm branch: submitted with the branch's |
| 609 | /// scheduler request (`launch_swarm`) and handed to the backend by the fork |
| 610 | /// hook (`prefill_pending_swarm_roots`), so both sides agree. |
| 611 | fn branch_sampling_params(config: &SwarmConfig) -> SamplingParams { |
| 612 | SamplingParams { |
| 613 | temperature: 0.7, |
| 614 | top_p: 0.95, |
| 615 | max_tokens: config.max_tokens_per_branch, |
| 616 | stop_token_ids: vec![2], |
| 617 | } |
| 618 | } |
| 619 | |
| 620 | /// Records a processed operation id. The operation has already run, so a |
| 621 | /// failed save does not change the reply; it is reported on stderr so the |
| 622 | /// loss of durability is never silent (#299). |
| 623 | fn record_processed(controller: &mut RuntimeController, operation_id: u128) { |
| 624 | if let Err(e) = controller.mark_operation_processed(operation_id) { |
| 625 | eprintln!("aien-runtime: {e}"); |
| 626 | } |
| 627 | } |