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 / context.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 | //! In-Process Context Composition and Revision Management |
| 17 | //! Manages immutable ContextRevisions and computes missing prefill spans for the scheduler. |
| 18 | |
| 19 | use serde::{Deserialize, Serialize}; |
| 20 | use std::collections::HashMap; |
| 21 | use std::sync::Arc; |
| 22 | |
| 23 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 24 | pub struct TokenSegment { |
| 25 | pub id: u64, |
| 26 | pub tokens: Arc<Vec<u32>>, |
| 27 | } |
| 28 | |
| 29 | impl TokenSegment { |
| 30 | pub fn new(id: u64, tokens: Vec<u32>) -> Self { |
| 31 | Self { |
| 32 | id, |
| 33 | tokens: Arc::new(tokens), |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | pub fn len(&self) -> usize { |
| 38 | self.tokens.len() |
| 39 | } |
| 40 | |
| 41 | pub fn is_empty(&self) -> bool { |
| 42 | self.tokens.is_empty() |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | #[derive(Debug, Clone)] |
| 47 | pub enum ContextSegment { |
| 48 | System(TokenSegment), |
| 49 | User(TokenSegment), |
| 50 | Assistant(TokenSegment), |
| 51 | Memory { |
| 52 | memory_id: u64, |
| 53 | tokens: TokenSegment, |
| 54 | }, |
| 55 | ToolResult(TokenSegment), |
| 56 | } |
| 57 | |
| 58 | impl ContextSegment { |
| 59 | pub fn tokens(&self) -> &TokenSegment { |
| 60 | match self { |
| 61 | Self::System(t) => t, |
| 62 | Self::User(t) => t, |
| 63 | Self::Assistant(t) => t, |
| 64 | Self::Memory { tokens, .. } => tokens, |
| 65 | Self::ToolResult(t) => t, |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | #[derive(Debug, Clone)] |
| 71 | pub struct ContextRevision { |
| 72 | pub id: u64, |
| 73 | pub parent: Option<u64>, |
| 74 | pub segments: Arc<Vec<ContextSegment>>, |
| 75 | pub total_tokens: usize, |
| 76 | } |
| 77 | |
| 78 | impl ContextRevision { |
| 79 | pub fn flatten_tokens(&self) -> Vec<u32> { |
| 80 | let mut out = Vec::with_capacity(self.total_tokens); |
| 81 | for seg in self.segments.iter() { |
| 82 | out.extend_from_slice(&seg.tokens().tokens); |
| 83 | } |
| 84 | out |
| 85 | } |
| 86 | |
| 87 | pub fn slice_tokens(&self, start: usize, len: usize) -> Vec<u32> { |
| 88 | let all = self.flatten_tokens(); |
| 89 | if start >= all.len() { |
| 90 | return Vec::new(); |
| 91 | } |
| 92 | let end = (start + len).min(all.len()); |
| 93 | all[start..end].to_vec() |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 98 | pub struct ContextPolicy { |
| 99 | pub max_memory_tokens: usize, |
| 100 | pub max_items: usize, |
| 101 | pub min_relevance: f32, |
| 102 | } |
| 103 | |
| 104 | impl Default for ContextPolicy { |
| 105 | fn default() -> Self { |
| 106 | Self { |
| 107 | max_memory_tokens: 4096, |
| 108 | max_items: 8, |
| 109 | min_relevance: 0.65, |
| 110 | } |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | #[derive(Debug, Clone)] |
| 115 | pub struct PrefillSpan { |
| 116 | pub start: usize, |
| 117 | pub len: usize, |
| 118 | pub tokens: Vec<u32>, |
| 119 | } |
| 120 | |
| 121 | /// Thread-safe ContextComposer caching tokenized segments and revision trees. |
| 122 | pub struct ContextComposer { |
| 123 | revisions: HashMap<u64, ContextRevision>, |
| 124 | #[allow(dead_code)] |
| 125 | segment_cache: HashMap<String, TokenSegment>, |
| 126 | next_revision_id: u64, |
| 127 | next_segment_id: u64, |
| 128 | } |
| 129 | |
| 130 | impl Default for ContextComposer { |
| 131 | fn default() -> Self { |
| 132 | Self::new() |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | impl ContextComposer { |
| 137 | pub fn new() -> Self { |
| 138 | Self { |
| 139 | revisions: HashMap::new(), |
| 140 | segment_cache: HashMap::new(), |
| 141 | next_revision_id: 1, |
| 142 | next_segment_id: 1, |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | pub fn create_root_revision( |
| 147 | &mut self, |
| 148 | system_prompt_tokens: Vec<u32>, |
| 149 | user_prompt_tokens: Vec<u32>, |
| 150 | ) -> u64 { |
| 151 | let seg_id1 = self.next_segment_id; |
| 152 | self.next_segment_id += 1; |
| 153 | let sys_seg = ContextSegment::System(TokenSegment::new(seg_id1, system_prompt_tokens)); |
| 154 | |
| 155 | let seg_id2 = self.next_segment_id; |
| 156 | self.next_segment_id += 1; |
| 157 | let user_seg = ContextSegment::User(TokenSegment::new(seg_id2, user_prompt_tokens)); |
| 158 | |
| 159 | let total_tokens = sys_seg.tokens().len() + user_seg.tokens().len(); |
| 160 | let rev_id = self.next_revision_id; |
| 161 | self.next_revision_id += 1; |
| 162 | |
| 163 | let revision = ContextRevision { |
| 164 | id: rev_id, |
| 165 | parent: None, |
| 166 | segments: Arc::new(vec![sys_seg, user_seg]), |
| 167 | total_tokens, |
| 168 | }; |
| 169 | |
| 170 | self.revisions.insert(rev_id, revision); |
| 171 | rev_id |
| 172 | } |
| 173 | |
| 174 | pub fn append_memory( |
| 175 | &mut self, |
| 176 | parent_rev_id: u64, |
| 177 | memory_id: u64, |
| 178 | memory_tokens: Vec<u32>, |
| 179 | ) -> Result<u64, String> { |
| 180 | let parent = self |
| 181 | .revisions |
| 182 | .get(&parent_rev_id) |
| 183 | .ok_or_else(|| format!("Parent revision {} not found", parent_rev_id))?; |
| 184 | |
| 185 | let seg_id = self.next_segment_id; |
| 186 | self.next_segment_id += 1; |
| 187 | let mem_seg = ContextSegment::Memory { |
| 188 | memory_id, |
| 189 | tokens: TokenSegment::new(seg_id, memory_tokens), |
| 190 | }; |
| 191 | |
| 192 | let mut new_segments = (*parent.segments).clone(); |
| 193 | let added_tokens = mem_seg.tokens().len(); |
| 194 | new_segments.push(mem_seg); |
| 195 | |
| 196 | let rev_id = self.next_revision_id; |
| 197 | self.next_revision_id += 1; |
| 198 | |
| 199 | let revision = ContextRevision { |
| 200 | id: rev_id, |
| 201 | parent: Some(parent_rev_id), |
| 202 | segments: Arc::new(new_segments), |
| 203 | total_tokens: parent.total_tokens + added_tokens, |
| 204 | }; |
| 205 | |
| 206 | self.revisions.insert(rev_id, revision); |
| 207 | Ok(rev_id) |
| 208 | } |
| 209 | |
| 210 | pub fn get_revision(&self, rev_id: u64) -> Option<&ContextRevision> { |
| 211 | self.revisions.get(&rev_id) |
| 212 | } |
| 213 | |
| 214 | /// Computes missing prefill tokens for a sequence whose current prefill cursor lags the revision. |
| 215 | pub fn compute_missing_prefill( |
| 216 | &self, |
| 217 | rev_id: u64, |
| 218 | prefill_cursor: usize, |
| 219 | ) -> Option<PrefillSpan> { |
| 220 | let rev = self.get_revision(rev_id)?; |
| 221 | if prefill_cursor >= rev.total_tokens { |
| 222 | return None; |
| 223 | } |
| 224 | |
| 225 | let missing_len = rev.total_tokens - prefill_cursor; |
| 226 | let tokens = rev.slice_tokens(prefill_cursor, missing_len); |
| 227 | |
| 228 | Some(PrefillSpan { |
| 229 | start: prefill_cursor, |
| 230 | len: missing_len, |
| 231 | tokens, |
| 232 | }) |
| 233 | } |
| 234 | } |