interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-runtime / src / swarm.rs

579 lines · 21291 bytes Raw Blame History
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//! SwarmManager and Branch-Native Swarm Coordination
17//! Manages first-class SwarmRecord entities and atomic branch operations.
18
19use crate::sequence::{SequenceArena, SequenceId, SequenceState};
20use crate::world::WorldStore;
21use aien_kv_cache::{AienKvManager, PrefillGateError};
22use aien_trace::{
23 CorrelationIds, EventKind, EventStatus, EvidenceRefs, NullSink, TraceEvent, TraceId, TraceSink,
24};
25use serde::{Deserialize, Serialize};
26use std::collections::HashMap;
27use std::sync::Arc;
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
30pub enum SwarmState {
31 Created,
32 Running,
33 Paused,
34 Cancelling,
35 Completed,
36 Failed,
37}
38
39#[derive(Debug, Clone, Serialize, Deserialize)]
40pub struct SwarmConfig {
41 pub model_handle: u64,
42 pub branch_count: usize,
43 pub max_active_sequences: usize,
44 pub max_tokens_per_branch: usize,
45 pub root_world_id: u64,
46 pub priority: u8,
47}
48
49#[derive(Debug, Clone, Serialize, Deserialize)]
50pub struct SwarmRecord {
51 pub id: u64,
52 pub config: SwarmConfig,
53 pub root_sequence_id: SequenceId,
54 pub branch_sequences: Vec<SequenceId>,
55 /// World IDs recorded at fork time. Cancel must drop these even when the
56 /// arena records were already freed by natural completion.
57 pub branch_worlds: Vec<u64>,
58 /// Branches that finished naturally. Completion of all branches triggers
59 /// swarm-wide reclamation: root arena slot, root KV, and branch worlds.
60 pub finished_branches: Vec<SequenceId>,
61 pub state: SwarmState,
62 pub created_at: u64,
63 /// Id of the `swarm_launched` trace event (the parent of this swarm's
64 /// other trace events). Correlation only; `None` in old records.
65 #[serde(default)]
66 pub trace_root_event: Option<u64>,
67}
68
69pub struct SwarmManager {
70 swarms: HashMap<u64, SwarmRecord>,
71 /// Correlation trace sink. `NullSink` by default (tracing off).
72 trace: Arc<dyn TraceSink>,
73 /// swarm id -> trace id, derived at launch from (root world, swarm id).
74 trace_ids: HashMap<u64, TraceId>,
75 next_swarm_id: u64,
76 /// PREFILL-GATE: swarms whose root prompt has not been prefilled yet
77 /// (swarm id -> root prompt). Branch KV is forked from the root only after
78 /// the root's prefill completion fence; see `fork_branches_from_ready_root`.
79 pending_root_prefill: HashMap<u64, Vec<u32>>,
80}
81
82impl Default for SwarmManager {
83 fn default() -> Self {
84 Self::new()
85 }
86}
87
88impl SwarmManager {
89 pub fn new() -> Self {
90 Self {
91 swarms: HashMap::new(),
92 trace: Arc::new(NullSink),
93 trace_ids: HashMap::new(),
94 next_swarm_id: 1,
95 pending_root_prefill: HashMap::new(),
96 }
97 }
98
99 /// Installs the correlation trace sink. The default is `NullSink`.
100 pub fn set_trace_sink(&mut self, sink: Arc<dyn TraceSink>) {
101 self.trace = sink;
102 }
103
104 /// Trace id of a launched swarm: `TraceId::derive(root_world_id, swarm_id, 0)`.
105 pub fn trace_id(&self, swarm_id: u64) -> Option<TraceId> {
106 self.trace_ids.get(&swarm_id).copied()
107 }
108
109 fn trace_event(
110 &self,
111 trace_id: TraceId,
112 parent: Option<u64>,
113 kind: EventKind,
114 status: EventStatus,
115 ids: CorrelationIds,
116 ) -> u64 {
117 if !self.trace.enabled() {
118 return 0;
119 }
120 let event_id = self.trace.next_event_id();
121 self.trace.emit(TraceEvent {
122 trace_id,
123 event_id,
124 parent_event_id: parent,
125 at_unix_ms: aien_trace::now_unix_ms(),
126 kind,
127 status,
128 effect_certainty: None,
129 ids,
130 refs: EvidenceRefs::default(),
131 note: None,
132 });
133 event_id
134 }
135
136 /// Launches a swarm: creates root sequence, preallocates root KV blocks, and forks N branches.
137 pub fn launch_swarm(
138 &mut self,
139 config: SwarmConfig,
140 arena: &mut SequenceArena,
141 kv: &mut AienKvManager,
142 world_store: &mut WorldStore,
143 prompt_tokens: &[u32],
144 timestamp: u64,
145 ) -> Result<u64, String> {
146 let swarm_id = self.next_swarm_id;
147 self.next_swarm_id += 1;
148
149 // Ensure a root world exists
150 let root_world_id = if world_store.get_world(config.root_world_id).is_some() {
151 config.root_world_id
152 } else {
153 world_store.create_root_world(1, 1, 1, timestamp)
154 };
155
156 // 1. Allocate root sequence in arena
157 let root_seq = arena.allocate(
158 root_world_id,
159 1, // Initial root context revision
160 config.priority,
161 timestamp,
162 )?;
163
164 // 2. Allocate root prompt blocks in physical KV manager. This reserves
165 // and zeroes blocks only (PrefillState::Allocated); no K/V is computed.
166 let trace_id = TraceId::derive(root_world_id, swarm_id, 0);
167 let root_event = self.trace_event(
168 trace_id,
169 None,
170 EventKind::SwarmLaunched,
171 EventStatus::Ok,
172 CorrelationIds {
173 swarm_id: Some(swarm_id),
174 world_id: Some(root_world_id),
175 root_sequence_id: Some(root_seq.as_u64()),
176 ..Default::default()
177 },
178 );
179 let root_u64 = root_seq.as_u64();
180 kv.allocate_sequence(root_u64, prompt_tokens)?;
181
182 if let Some(record) = arena.get_mut(root_seq) {
183 // Nothing is prefilled yet: the cursor advances at the completion fence.
184 record.prefill_cursor = 0;
185 record.state = SequenceState::Prefill;
186 }
187
188 // 3. Fork N branch records and worlds. Branch KV is NOT forked here:
189 // the root blocks are not computed, and sharing them would let branches
190 // decode over zeroed K/V. `fork_branches_from_ready_root` shares the
191 // root blocks after the root prefill completion fence.
192 let mut branch_sequences = Vec::with_capacity(config.branch_count);
193 let mut branch_worlds = Vec::with_capacity(config.branch_count);
194 for _ in 0..config.branch_count {
195 let child_world = world_store.fork_world(root_world_id, timestamp)?;
196 let child_seq = arena.fork(root_seq, child_world, timestamp)?;
197 if let Some(child) = arena.get_mut(child_seq) {
198 // Waiting on the root prefill, not decoding.
199 child.state = SequenceState::Prefill;
200 }
201 self.trace_event(
202 trace_id,
203 Some(root_event),
204 EventKind::BranchForked,
205 EventStatus::Ok,
206 CorrelationIds {
207 swarm_id: Some(swarm_id),
208 world_id: Some(child_world),
209 root_sequence_id: Some(root_seq.as_u64()),
210 sequence_id: Some(child_seq.as_u64()),
211 ..Default::default()
212 },
213 );
214 branch_sequences.push(child_seq);
215 branch_worlds.push(child_world);
216 }
217 self.pending_root_prefill
218 .insert(swarm_id, prompt_tokens.to_vec());
219
220 let record = SwarmRecord {
221 id: swarm_id,
222 config,
223 root_sequence_id: root_seq,
224 branch_sequences,
225 branch_worlds,
226 finished_branches: Vec::new(),
227 state: SwarmState::Running,
228 created_at: timestamp,
229 trace_root_event: Some(root_event),
230 };
231 self.trace_ids.insert(swarm_id, trace_id);
232
233 self.swarms.insert(swarm_id, record);
234 Ok(swarm_id)
235 }
236
237 pub fn get_swarm(&self, swarm_id: u64) -> Option<&SwarmRecord> {
238 self.swarms.get(&swarm_id)
239 }
240
241 /// Swarms whose root prompt still needs a model prefill:
242 /// (swarm id, root KV sequence id, root prompt).
243 pub fn pending_root_prefills(&self) -> Vec<(u64, u64, Vec<u32>)> {
244 let mut pending: Vec<(u64, u64, Vec<u32>)> = self
245 .pending_root_prefill
246 .iter()
247 .filter_map(|(&swarm_id, prompt)| {
248 self.swarms
249 .get(&swarm_id)
250 .filter(|s| s.state == SwarmState::Running)
251 .map(|s| (swarm_id, s.root_sequence_id.as_u64(), prompt.clone()))
252 })
253 .collect();
254 pending.sort_by_key(|p| p.0);
255 pending
256 }
257
258 /// True while the swarm's root prompt has not passed its prefill fence.
259 pub fn is_root_prefill_pending(&self, swarm_id: u64) -> bool {
260 self.pending_root_prefill.contains_key(&swarm_id)
261 }
262
263 /// Shares the root KV blocks with every branch once the root prefill
264 /// completion fence has fired. Refuses (typed `PrefillGateError`, as a
265 /// String) while the root is not PrefillReady; nothing is forked then.
266 pub fn fork_branches_from_ready_root(
267 &mut self,
268 swarm_id: u64,
269 arena: &mut SequenceArena,
270 kv: &mut AienKvManager,
271 ) -> Result<(), String> {
272 let swarm = self
273 .swarms
274 .get(&swarm_id)
275 .ok_or_else(|| format!("Swarm {} not found", swarm_id))?;
276 let root_u64 = swarm.root_sequence_id.as_u64();
277
278 // Check readiness once up front so a refusal forks nothing.
279 match kv.prefill_state(root_u64) {
280 Some(state) if state.is_ready() => {}
281 Some(state) => {
282 return Err(PrefillGateError::NotReady {
283 seq_id: root_u64,
284 state,
285 }
286 .to_string())
287 }
288 None => return Err(PrefillGateError::UnknownSequence { seq_id: root_u64 }.to_string()),
289 }
290
291 let prompt_len = kv
292 .get_block_table(root_u64)
293 .map(|t| t.total_tokens)
294 .unwrap_or(0);
295 for &child in &swarm.branch_sequences {
296 kv.fork_prefilled(root_u64, child.as_u64())
297 .map_err(|e| e.to_string())?;
298 if let Some(rec) = arena.get_mut(child) {
299 rec.prefill_cursor = prompt_len;
300 rec.state = SequenceState::Decode;
301 }
302 }
303 if let Some(root) = arena.get_mut(swarm.root_sequence_id) {
304 root.prefill_cursor = prompt_len;
305 }
306 self.pending_root_prefill.remove(&swarm_id);
307 Ok(())
308 }
309
310 /// Cancels a swarm and reclaims its resources: KV sequences, arena slots,
311 /// and branch worlds. The root world is retained; branch worlds are dropped.
312 /// Returns the sequence ids (root first, then every branch) whose backend
313 /// per-sequence state the caller must release (PREFILL-E2E C5); the
314 /// swarm manager has no backend handle.
315 pub fn cancel_swarm(
316 &mut self,
317 swarm_id: u64,
318 arena: &mut SequenceArena,
319 kv: &mut AienKvManager,
320 worlds: &mut WorldStore,
321 ) -> Result<Vec<u64>, String> {
322 let swarm = self
323 .swarms
324 .get_mut(&swarm_id)
325 .ok_or_else(|| format!("Swarm {} not found", swarm_id))?;
326 self.pending_root_prefill.remove(&swarm_id);
327
328 swarm.state = SwarmState::Cancelling;
329
330 if let Some(root_rec) = arena.get_mut(swarm.root_sequence_id) {
331 root_rec.state = SequenceState::Cancelled;
332 }
333 let _ = kv.free_sequence(swarm.root_sequence_id.as_u64());
334
335 for &child_id in &swarm.branch_sequences {
336 if let Some(child_rec) = arena.get_mut(child_id) {
337 child_rec.state = SequenceState::Cancelled;
338 }
339 let _ = kv.free_sequence(child_id.as_u64());
340 }
341
342 for &child_id in &swarm.branch_sequences {
343 arena.free(child_id);
344 }
345 arena.free(swarm.root_sequence_id);
346
347 // Drop from the launch-time ledger, not from arena lookups: branch
348 // sequences may have completed naturally and already left the arena.
349 let branch_worlds = swarm.branch_worlds.clone();
350 for world_id in branch_worlds {
351 worlds.drop_world(world_id);
352 }
353 worlds.collect_garbage();
354
355 swarm.state = SwarmState::Completed;
356 let mut released = Vec::with_capacity(swarm.branch_sequences.len() + 1);
357 released.push(swarm.root_sequence_id.as_u64());
358 released.extend(swarm.branch_sequences.iter().map(|b| b.as_u64()));
359 let root_event = swarm.trace_root_event;
360 if let Some(trace_id) = self.trace_ids.get(&swarm_id).copied() {
361 self.trace_event(
362 trace_id,
363 root_event,
364 EventKind::SwarmCancelled,
365 EventStatus::Cancelled,
366 CorrelationIds {
367 swarm_id: Some(swarm_id),
368 ..Default::default()
369 },
370 );
371 }
372 Ok(released)
373 }
374
375 /// Records a branch that finished naturally. Once every branch of a
376 /// running swarm has finished, reclaims the whole swarm: root arena slot,
377 /// root KV blocks, and all branch worlds. Without this, the root sequence
378 /// pins the arena forever and finished branch worlds leak.
379 /// Returns the root sequence id when this call reclaimed the swarm, so the
380 /// caller can release the root's backend state (PREFILL-E2E C5).
381 pub fn note_sequence_finished(
382 &mut self,
383 seq_id: SequenceId,
384 arena: &mut SequenceArena,
385 kv: &mut AienKvManager,
386 worlds: &mut WorldStore,
387 ) -> Option<SequenceId> {
388 let swarm_id = self.swarms.iter().find_map(|(id, swarm)| {
389 (swarm.state == SwarmState::Running
390 && swarm.branch_sequences.contains(&seq_id)
391 && !swarm.finished_branches.contains(&seq_id))
392 .then_some(*id)
393 });
394 let swarm_id = swarm_id?;
395 if let Some(trace_id) = self.trace_ids.get(&swarm_id).copied() {
396 let root_event = self.swarms.get(&swarm_id).and_then(|s| s.trace_root_event);
397 self.trace_event(
398 trace_id,
399 root_event,
400 EventKind::SequenceFinished,
401 EventStatus::Ok,
402 CorrelationIds {
403 swarm_id: Some(swarm_id),
404 sequence_id: Some(seq_id.as_u64()),
405 ..Default::default()
406 },
407 );
408 }
409
410 let swarm = self
411 .swarms
412 .get_mut(&swarm_id)
413 .expect("swarm id from live iterator must exist");
414 swarm.finished_branches.push(seq_id);
415 if swarm.finished_branches.len() < swarm.branch_sequences.len() {
416 return None;
417 }
418
419 if let Some(root_rec) = arena.get_mut(swarm.root_sequence_id) {
420 root_rec.state = SequenceState::Completed;
421 }
422 let _ = kv.free_sequence(swarm.root_sequence_id.as_u64());
423 arena.free(swarm.root_sequence_id);
424 self.pending_root_prefill.remove(&swarm_id);
425
426 for world_id in swarm.branch_worlds.clone() {
427 worlds.drop_world(world_id);
428 }
429 worlds.collect_garbage();
430 swarm.state = SwarmState::Completed;
431 Some(swarm.root_sequence_id)
432 }
433
434 pub fn active_swarm_count(&self) -> usize {
435 self.swarms
436 .values()
437 .filter(|s| s.state == SwarmState::Running)
438 .count()
439 }
440}
441
442#[cfg(test)]
443mod tests {
444 use super::*;
445 use crate::world::WorldStore;
446
447 fn test_config(branch_count: usize) -> SwarmConfig {
448 SwarmConfig {
449 model_handle: 1,
450 branch_count,
451 max_active_sequences: branch_count,
452 max_tokens_per_branch: 8,
453 root_world_id: 0,
454 priority: 1,
455 }
456 }
457
458 #[test]
459 fn cancel_drops_branch_worlds_after_natural_completion() {
460 let mut arena = SequenceArena::new(256);
461 let kv_shared = aien_kv_cache::create_shared_kv_manager(256, 16);
462 let mut kv = kv_shared.write();
463 let mut worlds = WorldStore::new();
464 let mut manager = SwarmManager::new();
465
466 let prompt = vec![1u32, 2, 3];
467 let swarm_id = manager
468 .launch_swarm(test_config(4), &mut arena, &mut kv, &mut worlds, &prompt, 1)
469 .expect("swarm launch must succeed");
470 assert_eq!(worlds.active_world_count(), 5, "root plus 4 branch worlds");
471
472 // Branches finish naturally: arena records leave the arena, worlds stay.
473 let record = manager.get_swarm(swarm_id).expect("record").clone();
474 for &child in &record.branch_sequences {
475 arena.free(child);
476 }
477 arena.free(record.root_sequence_id);
478
479 manager
480 .cancel_swarm(swarm_id, &mut arena, &mut kv, &mut worlds)
481 .expect("cancel must succeed");
482
483 assert_eq!(
484 worlds.active_world_count(),
485 1,
486 "branch worlds must drop even after arena records were freed"
487 );
488 }
489
490 #[test]
491 fn natural_completion_reclaims_root_and_branch_worlds() {
492 let mut arena = SequenceArena::new(256);
493 let kv_shared = aien_kv_cache::create_shared_kv_manager(256, 16);
494 let mut kv = kv_shared.write();
495 let mut worlds = WorldStore::new();
496 let mut manager = SwarmManager::new();
497
498 let prompt = vec![7u32, 8, 9];
499 let swarm_id = manager
500 .launch_swarm(test_config(3), &mut arena, &mut kv, &mut worlds, &prompt, 1)
501 .expect("swarm launch must succeed");
502 assert_eq!(worlds.active_world_count(), 4, "root plus 3 branch worlds");
503
504 // Every branch finishes through the scheduler; the spine reports each
505 // finish to the swarm manager.
506 let record = manager.get_swarm(swarm_id).expect("record").clone();
507 for &child in &record.branch_sequences {
508 manager.note_sequence_finished(child, &mut arena, &mut kv, &mut worlds);
509 }
510
511 assert_eq!(manager.active_swarm_count(), 0, "swarm must complete");
512 assert_eq!(
513 worlds.active_world_count(),
514 1,
515 "only the root world remains"
516 );
517 assert!(
518 arena.get(record.root_sequence_id).is_none(),
519 "root arena slot must be reclaimed on natural completion"
520 );
521 }
522
523 #[test]
524 fn prefill_gate_branches_do_not_share_uncomputed_root_blocks() {
525 let mut arena = SequenceArena::new(256);
526 let kv_shared = aien_kv_cache::create_shared_kv_manager(256, 16);
527 let mut kv = kv_shared.write();
528 let mut worlds = WorldStore::new();
529 let mut manager = SwarmManager::new();
530
531 let prompt = vec![4u32, 5, 6, 7];
532 let swarm_id = manager
533 .launch_swarm(test_config(3), &mut arena, &mut kv, &mut worlds, &prompt, 1)
534 .expect("swarm launch must succeed");
535 let record = manager.get_swarm(swarm_id).expect("record").clone();
536 let root = record.root_sequence_id.as_u64();
537
538 assert!(manager.is_root_prefill_pending(swarm_id));
539 assert_eq!(
540 kv.prefill_state(root),
541 Some(aien_kv_cache::PrefillState::Allocated),
542 "launch allocates root blocks; it computes nothing"
543 );
544 for child in &record.branch_sequences {
545 assert!(
546 kv.get_block_table(child.as_u64()).is_none(),
547 "no branch may hold root blocks before the root prefill fence"
548 );
549 }
550
551 // Typed refusal while the root is not PrefillReady; nothing is forked.
552 let err = manager
553 .fork_branches_from_ready_root(swarm_id, &mut arena, &mut kv)
554 .unwrap_err();
555 assert!(
556 err.contains("not PrefillReady"),
557 "unexpected error: {}",
558 err
559 );
560 for child in &record.branch_sequences {
561 assert!(kv.get_block_table(child.as_u64()).is_none());
562 }
563 assert!(manager.is_root_prefill_pending(swarm_id));
564
565 // After the completion fence, branches share the frozen root blocks.
566 kv.mark_prefill_pending(root).unwrap();
567 kv.complete_prefill(root).unwrap();
568 manager
569 .fork_branches_from_ready_root(swarm_id, &mut arena, &mut kv)
570 .expect("fork after fence");
571 assert!(!manager.is_root_prefill_pending(swarm_id));
572 let root_blocks = kv.get_block_table(root).unwrap().block_ids.clone();
573 for child in &record.branch_sequences {
574 let table = kv.get_block_table(child.as_u64()).expect("branch table");
575 assert_eq!(table.block_ids, root_blocks);
576 assert!(table.is_prefill_ready());
577 }
578 }
579}