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/aienux/blob/main/crates/aienos-c1-tree/src/tree.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / crates / aienos-c1-tree / src / tree.rs` 516 lines · 17616 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 //! C1 Copy-On-Write Prefix Tree engine (§10, §28). 17 18 use crate::metrics::C1MemoryMetrics; 19 use crate::page::{PageId, PAGE_CAPACITY_TOKENS}; 20 use crate::pool::PhysicalPagePool; 21 use aienos_agent_state::LogicalBranchId; 22 use core::fmt; 23 use std::collections::HashMap; 24 25 /// Errors occurring during C1 prefix tree operations. 26 #[derive(Debug, Clone, PartialEq, Eq)] 27 pub enum C1Error { 28 BranchNotFound(LogicalBranchId), 29 BranchEvicted(LogicalBranchId), 30 BranchAlreadyExists(LogicalBranchId), 31 CorruptedPage(PageId), 32 ReservationQuotaExceeded { requested: usize, available: usize }, 33 } 34 35 impl fmt::Display for C1Error { 36 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 37 match self { 38 Self::BranchNotFound(b) => write!(f, "C1 branch not found: {}", b), 39 Self::BranchEvicted(b) => { 40 write!(f, "C1 branch physical KV is currently evicted: {}", b) 41 } 42 Self::BranchAlreadyExists(b) => write!(f, "C1 branch already exists: {}", b), 43 Self::CorruptedPage(p) => write!(f, "Physical KV page corrupted: {}", p), 44 Self::ReservationQuotaExceeded { 45 requested, 46 available, 47 } => write!( 48 f, 49 "KV reservation quota exceeded: requested {} pages, available {}", 50 requested, available 51 ), 52 } 53 } 54 } 55 56 /// Transactional KV step reservation receipt (ADR 0005). 57 #[derive(Clone, Debug, PartialEq, Eq)] 58 pub struct ReservationReceipt { 59 pub branch_id: LogicalBranchId, 60 pub tokens_reserved: usize, 61 pub pages_reserved: usize, 62 pub reservation_tick: u64, 63 } 64 65 /// Descriptor tracking physical KV page table bindings for a reasoning branch. 66 #[derive(Clone, Debug)] 67 pub struct BranchDescriptor { 68 pub branch_id: LogicalBranchId, 69 pub page_ids: Vec, 70 pub total_tokens: usize, 71 pub evicted: bool, 72 } 73 74 /// The C1 Prefix Tree: Bare-metal copy-on-write KV engine for agent branching. 75 #[derive(Default)] 76 pub struct C1PrefixTree { 77 pool: PhysicalPagePool, 78 branches: HashMap, 79 } 80 81 impl C1PrefixTree { 82 /// Initialize an empty C1 prefix tree. 83 pub fn new() -> Self { 84 Self::default() 85 } 86 87 /// Access underlying physical page pool. 88 pub fn pool(&self) -> &PhysicalPagePool { 89 &self.pool 90 } 91 92 /// Initialize a new root reasoning branch populated with a prompt token sequence. 93 pub fn create_root_branch( 94 &mut self, 95 branch_id: LogicalBranchId, 96 prompt_tokens: &[u32], 97 ) -> Result<(), C1Error> { 98 if self.branches.contains_key(&branch_id) { 99 return Err(C1Error::BranchAlreadyExists(branch_id)); 100 } 101 102 let mut desc = BranchDescriptor { 103 branch_id, 104 page_ids: Vec::new(), 105 total_tokens: 0, 106 evicted: false, 107 }; 108 109 for &tok in prompt_tokens { 110 Self::append_single_token(&mut self.pool, &mut desc, tok)?; 111 } 112 113 self.branches.insert(branch_id, desc); 114 Ok(()) 115 } 116 117 /// Fork an existing reasoning branch with ZERO memory duplication (§10). 118 /// 119 /// The child branch points directly to the parent's physical KV pages. 120 /// Memory overhead of fork = 0 bytes! 121 pub fn fork_branch( 122 &mut self, 123 parent_id: LogicalBranchId, 124 child_id: LogicalBranchId, 125 ) -> Result<(), C1Error> { 126 let parent = self 127 .branches 128 .get(&parent_id) 129 .ok_or(C1Error::BranchNotFound(parent_id))? 130 .clone(); 131 132 if parent.evicted { 133 return Err(C1Error::BranchEvicted(parent_id)); 134 } 135 136 if self.branches.contains_key(&child_id) { 137 return Err(C1Error::BranchAlreadyExists(child_id)); 138 } 139 140 // Increment reference count on all shared physical pages 141 for &pid in &parent.page_ids { 142 self.pool.retain(pid); 143 } 144 145 let child = BranchDescriptor { 146 branch_id: child_id, 147 page_ids: parent.page_ids.clone(), 148 total_tokens: parent.total_tokens, 149 evicted: false, 150 }; 151 152 self.branches.insert(child_id, child); 153 Ok(()) 154 } 155 156 /// Explicit transactional KV reservation prior to step admission (ADR 0005). 157 pub fn reserve_step_capacity( 158 &self, 159 branch_id: LogicalBranchId, 160 num_tokens: usize, 161 tick: u64, 162 max_pool_pages: usize, 163 ) -> Result { 164 let desc = self 165 .branches 166 .get(&branch_id) 167 .ok_or(C1Error::BranchNotFound(branch_id))?; 168 169 if desc.evicted { 170 return Err(C1Error::BranchEvicted(branch_id)); 171 } 172 173 let needed_pages = num_tokens.div_ceil(PAGE_CAPACITY_TOKENS); 174 let current_allocated = self.pool.allocated_page_count(); 175 if current_allocated + needed_pages > max_pool_pages { 176 return Err(C1Error::ReservationQuotaExceeded { 177 requested: needed_pages, 178 available: max_pool_pages.saturating_sub(current_allocated), 179 }); 180 } 181 182 Ok(ReservationReceipt { 183 branch_id, 184 tokens_reserved: num_tokens, 185 pages_reserved: needed_pages, 186 reservation_tick: tick, 187 }) 188 } 189 190 /// Append tokens to an active reasoning branch, triggering Copy-On-Write only upon divergence. 191 pub fn append_tokens( 192 &mut self, 193 branch_id: LogicalBranchId, 194 tokens: &[u32], 195 ) -> Result<(), C1Error> { 196 let mut desc = self 197 .branches 198 .get(&branch_id) 199 .ok_or(C1Error::BranchNotFound(branch_id))? 200 .clone(); 201 202 if desc.evicted { 203 return Err(C1Error::BranchEvicted(branch_id)); 204 } 205 206 for &tok in tokens { 207 Self::append_single_token(&mut self.pool, &mut desc, tok)?; 208 } 209 210 self.branches.insert(branch_id, desc); 211 Ok(()) 212 } 213 214 fn append_single_token( 215 pool: &mut PhysicalPagePool, 216 desc: &mut BranchDescriptor, 217 token_id: u32, 218 ) -> Result<(), C1Error> { 219 if desc.page_ids.is_empty() { 220 let pid = pool.allocate(); 221 let page = pool.get_mut(pid).unwrap(); 222 page.append(token_id); 223 desc.page_ids.push(pid); 224 desc.total_tokens += 1; 225 return Ok(()); 226 } 227 228 let last_pid = *desc.page_ids.last().unwrap(); 229 let page = pool.get(last_pid).ok_or(C1Error::CorruptedPage(last_pid))?; 230 if !page.verify_checksum() { 231 return Err(C1Error::CorruptedPage(last_pid)); 232 } 233 234 if !page.is_full() { 235 if page.ref_count == 1 { 236 // Exclusive ownership: append directly 237 let page_mut = pool.get_mut(last_pid).unwrap(); 238 page_mut.append(token_id); 239 } else { 240 // Shared page: perform Copy-On-Write! 241 let new_pid = pool.clone_on_write(last_pid); 242 let page_mut = pool.get_mut(new_pid).unwrap(); 243 page_mut.append(token_id); 244 // Replace last page with private page in this branch 245 let last_idx = desc.page_ids.len() - 1; 246 desc.page_ids[last_idx] = new_pid; 247 } 248 } else { 249 // Last page is full: allocate a brand new page 250 let new_pid = pool.allocate(); 251 let page_mut = pool.get_mut(new_pid).unwrap(); 252 page_mut.append(token_id); 253 desc.page_ids.push(new_pid); 254 } 255 256 desc.total_tokens += 1; 257 Ok(()) 258 } 259 260 /// Retrieve complete token sequence for a branch. 261 pub fn get_tokens(&self, branch_id: LogicalBranchId) -> Result, C1Error> { 262 let desc = self 263 .branches 264 .get(&branch_id) 265 .ok_or(C1Error::BranchNotFound(branch_id))?; 266 267 if desc.evicted { 268 return Err(C1Error::BranchEvicted(branch_id)); 269 } 270 271 let mut out = Vec::with_capacity(desc.total_tokens); 272 for &pid in &desc.page_ids { 273 let page = self.pool.get(pid).ok_or(C1Error::CorruptedPage(pid))?; 274 if !page.verify_checksum() { 275 return Err(C1Error::CorruptedPage(pid)); 276 } 277 for i in 0..page.len { 278 out.push(page.tokens[i]); 279 } 280 } 281 Ok(out) 282 } 283 284 /// Evict physical KV pages for a branch to simulate memory reclamation. 285 pub fn evict_branch(&mut self, branch_id: LogicalBranchId) -> Result<(), C1Error> { 286 let desc = self 287 .branches 288 .get_mut(&branch_id) 289 .ok_or(C1Error::BranchNotFound(branch_id))?; 290 291 if desc.evicted { 292 return Ok(()); 293 } 294 295 for &pid in &desc.page_ids { 296 self.pool.release(pid); 297 } 298 desc.page_ids.clear(); 299 desc.evicted = true; 300 Ok(()) 301 } 302 303 /// Remove and deallocate an exploratory or completed reasoning branch, releasing all its pages. 304 pub fn remove_branch(&mut self, branch_id: LogicalBranchId) -> Result<(), C1Error> { 305 let desc = self 306 .branches 307 .remove(&branch_id) 308 .ok_or(C1Error::BranchNotFound(branch_id))?; 309 310 if !desc.evicted { 311 for &pid in &desc.page_ids { 312 self.pool.release(pid); 313 } 314 } 315 Ok(()) 316 } 317 318 /// Reconstruct physical KV pages deterministically from token sequence. 319 /// Re-allocates pages cleanly without leaking existing physical frames. 320 pub fn reconstruct_branch( 321 &mut self, 322 branch_id: LogicalBranchId, 323 tokens: &[u32], 324 ) -> Result<(), C1Error> { 325 let desc = self 326 .branches 327 .get_mut(&branch_id) 328 .ok_or(C1Error::BranchNotFound(branch_id))?; 329 330 if !desc.evicted { 331 for &pid in &desc.page_ids { 332 self.pool.release(pid); 333 } 334 } 335 336 desc.page_ids.clear(); 337 desc.total_tokens = 0; 338 desc.evicted = false; 339 340 for &tok in tokens { 341 Self::append_single_token(&mut self.pool, desc, tok)?; 342 } 343 344 Ok(()) 345 } 346 347 /// Compute memory and sharing metrics across all branches. 348 pub fn memory_metrics(&self) -> C1MemoryMetrics { 349 let physical_pages = self.pool.allocated_page_count(); 350 let physical_bytes = self.pool.physical_memory_bytes(); 351 let total_virtual_tokens: usize = self.branches.values().map(|b| b.total_tokens).sum(); 352 let total_unique_physical_tokens: usize = physical_pages * PAGE_CAPACITY_TOKENS; 353 354 let sharing_ratio = if total_unique_physical_tokens > 0 { 355 total_virtual_tokens as f64 / total_unique_physical_tokens as f64 356 } else { 357 1.0 358 }; 359 360 C1MemoryMetrics { 361 physical_pages_allocated: physical_pages, 362 physical_memory_bytes: physical_bytes, 363 total_virtual_tokens, 364 total_unique_physical_tokens, 365 sharing_ratio, 366 } 367 } 368 } 369 370 #[cfg(test)] 371 mod tests { 372 use super::*; 373 use aienos_agent_state::{LogicalAgentId, LogicalBranchId}; 374 use std::sync::{Arc, Mutex}; 375 use std::thread; 376 377 #[test] 378 fn test_zero_memory_increase_on_10k_tokens_fork() { 379 let mut tree = C1PrefixTree::new(); 380 let agent = LogicalAgentId::from_seed("c1-cow-test"); 381 let root_branch = LogicalBranchId::root_branch(agent); 382 383 // 1. Create a 10,000-token prompt 384 let prompt_tokens: Vec = (0..10_000).map(|i| 1000 + (i % 50000)).collect(); 385 tree.create_root_branch(root_branch, &prompt_tokens) 386 .unwrap(); 387 388 let initial_pages = tree.pool().allocated_page_count(); 389 let initial_bytes = tree.pool().physical_memory_bytes(); 390 assert_eq!(initial_pages, 10_000_usize.div_ceil(PAGE_CAPACITY_TOKENS)); 391 392 // 2. Fork into 10 concurrent exploratory branches 393 let mut child_branches = Vec::new(); 394 for i in 0..10 { 395 let child = LogicalBranchId::derive(root_branch, i); 396 tree.fork_branch(root_branch, child).unwrap(); 397 child_branches.push(child); 398 } 399 400 // ACCEPTANCE CRITERIA VERIFICATION: 401 // Demonstrates ZERO memory increase when branching a 10,000-token prefix across 10 concurrent exploratory branches! 402 let post_fork_pages = tree.pool().allocated_page_count(); 403 let post_fork_bytes = tree.pool().physical_memory_bytes(); 404 assert_eq!( 405 initial_pages, post_fork_pages, 406 "Physical pages allocated must NOT increase upon branching" 407 ); 408 assert_eq!( 409 initial_bytes, post_fork_bytes, 410 "Physical memory bytes must NOT increase upon branching (ZERO overhead)" 411 ); 412 413 // 3. Verify deterministic divergence upon appending tokens 414 for (i, &child) in child_branches.iter().enumerate() { 415 tree.append_tokens(child, &[9999 + i as u32]).unwrap(); 416 let tokens = tree.get_tokens(child).unwrap(); 417 assert_eq!(tokens.len(), 10_001); 418 assert_eq!(tokens[10_000], 9999 + i as u32); 419 } 420 421 // After appending 1 divergent token each, only private pages allocated for divergent step 422 let post_divergence_pages = tree.pool().allocated_page_count(); 423 assert_eq!(post_divergence_pages, initial_pages + 10); 424 } 425 426 #[test] 427 fn test_transactional_kv_reservation() { 428 let mut tree = C1PrefixTree::new(); 429 let agent = LogicalAgentId::from_seed("reservation-test"); 430 let root = LogicalBranchId::root_branch(agent); 431 tree.create_root_branch(root, &[1, 2, 3]).unwrap(); 432 433 // Limit pool to 10 pages total 434 let receipt = tree.reserve_step_capacity(root, 64, 42, 10).unwrap(); 435 assert_eq!(receipt.pages_reserved, 1); 436 assert_eq!(receipt.tokens_reserved, 64); 437 438 // Try reserving more pages than available in quota 439 let overflow = tree.reserve_step_capacity(root, 1000, 43, 10); 440 assert!(matches!( 441 overflow, 442 Err(C1Error::ReservationQuotaExceeded { .. }) 443 )); 444 } 445 446 #[test] 447 fn test_reconstruct_branch_no_page_leak() { 448 let mut tree = C1PrefixTree::new(); 449 let agent = LogicalAgentId::from_seed("reconstruct-leak-test"); 450 let root = LogicalBranchId::root_branch(agent); 451 tree.create_root_branch(root, &[10, 20, 30]).unwrap(); 452 let initial_pages = tree.pool().allocated_page_count(); 453 assert_eq!(initial_pages, 1); 454 455 // Reconstructing an active branch must release previous pages and allocate clean ones without leak 456 tree.reconstruct_branch(root, &[10, 20, 30]).unwrap(); 457 assert_eq!(tree.pool().allocated_page_count(), initial_pages); 458 459 // Remove branch should release all pages back to 0 460 tree.remove_branch(root).unwrap(); 461 assert_eq!(tree.pool().allocated_page_count(), 0); 462 } 463 464 #[test] 465 fn test_concurrent_multithreaded_branching_and_reservations() { 466 let tree = Arc::new(Mutex::new(C1PrefixTree::new())); 467 let agent = LogicalAgentId::from_seed("concurrent-c1-agent"); 468 let root = LogicalBranchId::root_branch(agent); 469 470 { 471 let mut t = tree.lock().unwrap(); 472 let prompt: Vec = (0..128).collect(); 473 t.create_root_branch(root, &prompt).unwrap(); 474 } 475 476 let mut handles = Vec::new(); 477 for worker_id in 0..8 { 478 let tree_clone = Arc::clone(&tree); 479 let handle = thread::spawn(move || { 480 let child = LogicalBranchId::derive(root, worker_id); 481 { 482 let mut t = tree_clone.lock().unwrap(); 483 t.fork_branch(root, child).unwrap(); 484 } 485 486 // Reserve capacity 487 { 488 let t = tree_clone.lock().unwrap(); 489 let res = t 490 .reserve_step_capacity(child, 16, 100 + worker_id, 1000) 491 .unwrap(); 492 assert_eq!(res.tokens_reserved, 16); 493 } 494 495 // Append divergent tokens 496 { 497 let mut t = tree_clone.lock().unwrap(); 498 t.append_tokens(child, &[5000 + worker_id as u32]).unwrap(); 499 let tokens = t.get_tokens(child).unwrap(); 500 assert_eq!(tokens.len(), 129); 501 assert_eq!(tokens[128], 5000 + worker_id as u32); 502 } 503 }); 504 handles.push(handle); 505 } 506 507 for h in handles { 508 h.join().unwrap(); 509 } 510 511 let t = tree.lock().unwrap(); 512 let metrics = t.memory_metrics(); 513 assert_eq!(metrics.total_virtual_tokens, 128 + 8 * 129); 514 assert!(metrics.sharing_ratio > 1.0); 515 } 516 }