aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / crates / aienos-agent-state / src / manager.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 | //! Concrete thread-safe AgentStateManager implementing AgentStateAbi. |
| 17 | |
| 18 | use crate::abi::{AgentStateAbi, CheckpointHash, StateError}; |
| 19 | use crate::id::{LogicalAgentId, LogicalBranchId}; |
| 20 | use crate::incarnation::{ComputeState, ExecutionIncarnation, LogicalBranch, SequenceId}; |
| 21 | use aienos_kernel::crypto::sha256; |
| 22 | use serde::{Deserialize, Serialize}; |
| 23 | use std::collections::{BTreeMap, HashMap}; |
| 24 | use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; |
| 25 | use std::sync::RwLock; |
| 26 | |
| 27 | /// Persistent snapshot of agent state for cross-boot serialization. |
| 28 | #[derive(Clone, Debug, Serialize, Deserialize)] |
| 29 | pub struct AgentSnapshot { |
| 30 | pub agents: Vec<LogicalAgentId>, |
| 31 | pub branches: Vec<LogicalBranch>, |
| 32 | pub snapshot_incarnation: u64, |
| 33 | } |
| 34 | |
| 35 | /// Durable checkpoint container with cryptographic seal. |
| 36 | #[derive(Clone, Debug, Serialize, Deserialize)] |
| 37 | pub struct CheckpointEnvelope { |
| 38 | pub hash: [u8; 32], |
| 39 | pub payload_json: String, |
| 40 | } |
| 41 | |
| 42 | struct InnerState { |
| 43 | agents: Vec<LogicalAgentId>, |
| 44 | branches: HashMap<LogicalBranchId, LogicalBranch>, |
| 45 | incarnations: HashMap<LogicalBranchId, ExecutionIncarnation>, |
| 46 | branch_child_counters: HashMap<LogicalBranchId, u64>, |
| 47 | } |
| 48 | |
| 49 | /// Thread-safe sovereign manager for logical agent states and execution incarnations. |
| 50 | pub struct AgentStateManager { |
| 51 | inner: RwLock<InnerState>, |
| 52 | current_incarnation_id: AtomicU64, |
| 53 | next_sequence_id: AtomicU32, |
| 54 | } |
| 55 | |
| 56 | impl Default for AgentStateManager { |
| 57 | fn default() -> Self { |
| 58 | Self::new(1) |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | impl AgentStateManager { |
| 63 | /// Initialize a new manager with a specific boot incarnation ID. |
| 64 | pub fn new(incarnation_id: u64) -> Self { |
| 65 | Self { |
| 66 | inner: RwLock::new(InnerState { |
| 67 | agents: Vec::new(), |
| 68 | branches: HashMap::new(), |
| 69 | incarnations: HashMap::new(), |
| 70 | branch_child_counters: HashMap::new(), |
| 71 | }), |
| 72 | current_incarnation_id: AtomicU64::new(incarnation_id), |
| 73 | next_sequence_id: AtomicU32::new(1), |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | /// Register a new agent and instantiate its root branch. |
| 78 | pub fn register_agent(&self, agent_id: LogicalAgentId, timestamp: u64) -> LogicalBranchId { |
| 79 | let mut inner = self.inner.write().unwrap(); |
| 80 | let root_id = LogicalBranchId::root_branch(agent_id); |
| 81 | if inner.agents.contains(&agent_id) { |
| 82 | // Provisioning is not restart. Re-registering a durable identity |
| 83 | // must not replace its root branch and discard committed history. |
| 84 | if inner.branches.contains_key(&root_id) { |
| 85 | return root_id; |
| 86 | } |
| 87 | } else { |
| 88 | inner.agents.push(agent_id); |
| 89 | } |
| 90 | |
| 91 | let root_branch = LogicalBranch::new_root(agent_id, timestamp); |
| 92 | let branch_id = root_branch.branch_id; |
| 93 | inner.branches.insert(branch_id, root_branch); |
| 94 | |
| 95 | let seq = self.next_sequence_id.fetch_add(1, Ordering::SeqCst); |
| 96 | let incarnation_id = self.current_incarnation_id.load(Ordering::SeqCst); |
| 97 | inner |
| 98 | .incarnations |
| 99 | .insert(branch_id, ExecutionIncarnation::new(incarnation_id, seq)); |
| 100 | |
| 101 | branch_id |
| 102 | } |
| 103 | |
| 104 | /// Append tokens to an existing branch's history. |
| 105 | pub fn append_tokens( |
| 106 | &self, |
| 107 | branch_id: LogicalBranchId, |
| 108 | tokens: &[u32], |
| 109 | ) -> Result<(), StateError> { |
| 110 | let mut inner = self.inner.write().unwrap(); |
| 111 | let history_len = { |
| 112 | let branch = inner |
| 113 | .branches |
| 114 | .get_mut(&branch_id) |
| 115 | .ok_or(StateError::BranchNotFound(branch_id))?; |
| 116 | branch.token_history.append_tokens(tokens); |
| 117 | branch.token_history.len() |
| 118 | }; |
| 119 | |
| 120 | if let Some(inc) = inner.incarnations.get_mut(&branch_id) { |
| 121 | if inc.physical_state.compute_state != ComputeState::Suspended |
| 122 | && inc.physical_state.compute_state != ComputeState::Evicted |
| 123 | { |
| 124 | inc.physical_state.allocated_tokens_in_kv = history_len; |
| 125 | inc.physical_state.compute_state = ComputeState::Decoding; |
| 126 | } |
| 127 | } |
| 128 | Ok(()) |
| 129 | } |
| 130 | |
| 131 | /// Attach a Cortex epistemic reference to a branch. |
| 132 | pub fn add_epistemic_ref( |
| 133 | &self, |
| 134 | branch_id: LogicalBranchId, |
| 135 | record_id: [u8; 16], |
| 136 | ) -> Result<(), StateError> { |
| 137 | let mut inner = self.inner.write().unwrap(); |
| 138 | let branch = inner |
| 139 | .branches |
| 140 | .get_mut(&branch_id) |
| 141 | .ok_or(StateError::BranchNotFound(branch_id))?; |
| 142 | branch.epistemic_refs.insert(record_id); |
| 143 | Ok(()) |
| 144 | } |
| 145 | |
| 146 | /// Retrieve branch details. |
| 147 | pub fn get_branch(&self, branch_id: &LogicalBranchId) -> Option<LogicalBranch> { |
| 148 | let inner = self.inner.read().unwrap(); |
| 149 | inner.branches.get(branch_id).cloned() |
| 150 | } |
| 151 | |
| 152 | /// Retrieve ephemeral incarnation details. |
| 153 | pub fn get_incarnation(&self, branch_id: &LogicalBranchId) -> Option<ExecutionIncarnation> { |
| 154 | let inner = self.inner.read().unwrap(); |
| 155 | inner.incarnations.get(branch_id).cloned() |
| 156 | } |
| 157 | |
| 158 | /// Export a durable checkpoint envelope with SHA-256 seal. |
| 159 | pub fn export_checkpoint(&self, agent_id: LogicalAgentId) -> Result<Vec<u8>, StateError> { |
| 160 | let inner = self.inner.read().unwrap(); |
| 161 | if !inner.agents.contains(&agent_id) { |
| 162 | return Err(StateError::AgentNotFound(agent_id)); |
| 163 | } |
| 164 | |
| 165 | let mut agent_branches: Vec<LogicalBranch> = inner |
| 166 | .branches |
| 167 | .values() |
| 168 | .filter(|b| b.agent_id == agent_id) |
| 169 | .cloned() |
| 170 | .collect(); |
| 171 | agent_branches.sort_unstable_by_key(|branch| branch.branch_id); |
| 172 | |
| 173 | let snapshot = AgentSnapshot { |
| 174 | agents: vec![agent_id], |
| 175 | branches: agent_branches, |
| 176 | snapshot_incarnation: self.current_incarnation_id.load(Ordering::SeqCst), |
| 177 | }; |
| 178 | |
| 179 | let json = serde_json::to_string(&snapshot) |
| 180 | .map_err(|e| StateError::SerializationError(e.to_string()))?; |
| 181 | let hash = sha256::hash(json.as_bytes()); |
| 182 | |
| 183 | let envelope = CheckpointEnvelope { |
| 184 | hash, |
| 185 | payload_json: json, |
| 186 | }; |
| 187 | |
| 188 | serde_json::to_vec(&envelope).map_err(|e| StateError::SerializationError(e.to_string())) |
| 189 | } |
| 190 | |
| 191 | /// Restore state from a durable checkpoint envelope across reboot. |
| 192 | /// |
| 193 | /// Verifies cryptographic checksum, restores all logical state, and |
| 194 | /// resets physical state to `Evicted` under a new monotonic boot incarnation. |
| 195 | pub fn restore_from_checkpoint( |
| 196 | checkpoint_data: &[u8], |
| 197 | new_incarnation_id: u64, |
| 198 | ) -> Result<Self, StateError> { |
| 199 | let envelope: CheckpointEnvelope = serde_json::from_slice(checkpoint_data) |
| 200 | .map_err(|e| StateError::DeserializationError(e.to_string()))?; |
| 201 | |
| 202 | let expected_hash = sha256::hash(envelope.payload_json.as_bytes()); |
| 203 | if envelope.hash != expected_hash { |
| 204 | return Err(StateError::ChecksumMismatch); |
| 205 | } |
| 206 | |
| 207 | let snapshot: AgentSnapshot = serde_json::from_str(&envelope.payload_json) |
| 208 | .map_err(|e| StateError::DeserializationError(e.to_string()))?; |
| 209 | |
| 210 | // Ordered maps keep validation (which reason is reported first) and |
| 211 | // the re-instantiated incarnation sequence ids deterministic. |
| 212 | let mut branches = BTreeMap::<LogicalBranchId, LogicalBranch>::new(); |
| 213 | let mut child_counts = BTreeMap::<LogicalBranchId, u64>::new(); |
| 214 | if snapshot.agents.is_empty() { |
| 215 | return Err(StateError::InvalidCheckpoint("no durable agent identity")); |
| 216 | } |
| 217 | for (index, agent_id) in snapshot.agents.iter().enumerate() { |
| 218 | if snapshot.agents[..index].contains(agent_id) { |
| 219 | return Err(StateError::InvalidCheckpoint("duplicate agent identity")); |
| 220 | } |
| 221 | } |
| 222 | for branch in snapshot.branches { |
| 223 | if !snapshot.agents.contains(&branch.agent_id) { |
| 224 | return Err(StateError::InvalidCheckpoint( |
| 225 | "branch refers to an absent agent identity", |
| 226 | )); |
| 227 | } |
| 228 | let branch_id = branch.branch_id; |
| 229 | let parent = branch.parent_branch_id; |
| 230 | if branches.insert(branch_id, branch).is_some() { |
| 231 | return Err(StateError::InvalidCheckpoint("duplicate branch identity")); |
| 232 | } |
| 233 | if let Some(parent) = parent { |
| 234 | // Bounded by the number of decoded branches; cannot overflow. |
| 235 | *child_counts.entry(parent).or_insert(0) += 1; |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | // A valid snapshot has exactly one deterministic root branch per |
| 240 | // agent, and every child points to an existing branch of that agent. |
| 241 | for agent_id in &snapshot.agents { |
| 242 | let root_id = LogicalBranchId::root_branch(*agent_id); |
| 243 | let root = branches |
| 244 | .get(&root_id) |
| 245 | .ok_or(StateError::InvalidCheckpoint("root branch is missing"))?; |
| 246 | if root.agent_id != *agent_id |
| 247 | || root.parent_branch_id.is_some() |
| 248 | || root.lineage.root_agent != *agent_id |
| 249 | || root.lineage.depth != 0 |
| 250 | || !root.lineage.ancestor_branches.is_empty() |
| 251 | { |
| 252 | return Err(StateError::InvalidCheckpoint("root branch is inconsistent")); |
| 253 | } |
| 254 | } |
| 255 | for branch in branches.values() { |
| 256 | let Some(parent_id) = branch.parent_branch_id else { |
| 257 | if branch.branch_id != LogicalBranchId::root_branch(branch.agent_id) { |
| 258 | return Err(StateError::InvalidCheckpoint("unexpected root branch")); |
| 259 | } |
| 260 | continue; |
| 261 | }; |
| 262 | let parent = branches |
| 263 | .get(&parent_id) |
| 264 | .ok_or(StateError::InvalidCheckpoint("parent branch is missing"))?; |
| 265 | let expected_depth = parent.lineage.depth.checked_add(1); |
| 266 | let mut expected_ancestors = parent.lineage.ancestor_branches.clone(); |
| 267 | expected_ancestors.push(branch.branch_id); |
| 268 | if parent.agent_id != branch.agent_id |
| 269 | || branch.lineage.root_agent != parent.lineage.root_agent |
| 270 | || Some(branch.lineage.depth) != expected_depth |
| 271 | || branch.lineage.ancestor_branches != expected_ancestors |
| 272 | { |
| 273 | return Err(StateError::InvalidCheckpoint( |
| 274 | "branch lineage is inconsistent", |
| 275 | )); |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | // Fork indexes are implicit in the current snapshot schema. Existing |
| 280 | // branches are append-only, so each parent's child count is its next |
| 281 | // fork index. Validate the contiguous deterministic IDs before using |
| 282 | // that count; otherwise fail closed instead of risking an overwrite. |
| 283 | for (parent_id, count) in &child_counts { |
| 284 | for child_index in 0..*count { |
| 285 | let child_id = LogicalBranchId::derive(*parent_id, child_index); |
| 286 | if !branches |
| 287 | .get(&child_id) |
| 288 | .is_some_and(|child| child.parent_branch_id == Some(*parent_id)) |
| 289 | { |
| 290 | return Err(StateError::InvalidCheckpoint( |
| 291 | "branch fork indexes are not contiguous", |
| 292 | )); |
| 293 | } |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | let manager = Self::new(new_incarnation_id); |
| 298 | { |
| 299 | let mut inner = manager.inner.write().unwrap(); |
| 300 | inner.agents = snapshot.agents; |
| 301 | inner.branch_child_counters = child_counts.into_iter().collect(); |
| 302 | for branch_id in branches.keys().copied() { |
| 303 | // Re-instantiate ephemeral incarnation with EVICTED physical state |
| 304 | let seq = manager.next_sequence_id.fetch_add(1, Ordering::SeqCst); |
| 305 | let mut inc = ExecutionIncarnation::new(new_incarnation_id, seq); |
| 306 | inc.evict(); |
| 307 | inner.incarnations.insert(branch_id, inc); |
| 308 | } |
| 309 | inner.branches = branches.into_iter().collect(); |
| 310 | } |
| 311 | |
| 312 | Ok(manager) |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | impl AgentStateAbi for AgentStateManager { |
| 317 | fn fork_branch(&self, parent: LogicalBranchId) -> Result<LogicalBranchId, StateError> { |
| 318 | let mut inner = self.inner.write().unwrap(); |
| 319 | let parent_branch = inner |
| 320 | .branches |
| 321 | .get(&parent) |
| 322 | .ok_or(StateError::ParentBranchNotFound(parent))? |
| 323 | .clone(); |
| 324 | |
| 325 | let counter = inner.branch_child_counters.entry(parent).or_insert(0); |
| 326 | let child_idx = *counter; |
| 327 | *counter += 1; |
| 328 | |
| 329 | let child_id = LogicalBranchId::derive(parent, child_idx); |
| 330 | let child_branch = parent_branch.fork(child_id, 1000 + child_idx); |
| 331 | |
| 332 | inner.branches.insert(child_id, child_branch); |
| 333 | |
| 334 | let seq = self.next_sequence_id.fetch_add(1, Ordering::SeqCst); |
| 335 | let incarnation_id = self.current_incarnation_id.load(Ordering::SeqCst); |
| 336 | inner |
| 337 | .incarnations |
| 338 | .insert(child_id, ExecutionIncarnation::new(incarnation_id, seq)); |
| 339 | |
| 340 | Ok(child_id) |
| 341 | } |
| 342 | |
| 343 | fn checkpoint(&self, agent_id: LogicalAgentId) -> Result<CheckpointHash, StateError> { |
| 344 | let bytes = self.export_checkpoint(agent_id)?; |
| 345 | let envelope: CheckpointEnvelope = serde_json::from_slice(&bytes) |
| 346 | .map_err(|e| StateError::SerializationError(e.to_string()))?; |
| 347 | Ok(CheckpointHash(envelope.hash)) |
| 348 | } |
| 349 | |
| 350 | fn suspend(&mut self, branch_id: LogicalBranchId) -> Result<(), StateError> { |
| 351 | let mut inner = self.inner.write().unwrap(); |
| 352 | if !inner.branches.contains_key(&branch_id) { |
| 353 | return Err(StateError::BranchNotFound(branch_id)); |
| 354 | } |
| 355 | let inc = inner |
| 356 | .incarnations |
| 357 | .get_mut(&branch_id) |
| 358 | .ok_or(StateError::BranchNotFound(branch_id))?; |
| 359 | |
| 360 | if inc.physical_state.compute_state == ComputeState::Suspended { |
| 361 | return Err(StateError::AlreadySuspended(branch_id)); |
| 362 | } |
| 363 | |
| 364 | inc.physical_state.compute_state = ComputeState::Suspended; |
| 365 | Ok(()) |
| 366 | } |
| 367 | |
| 368 | fn resume(&mut self, branch_id: LogicalBranchId) -> Result<SequenceId, StateError> { |
| 369 | let mut inner = self.inner.write().unwrap(); |
| 370 | if !inner.branches.contains_key(&branch_id) { |
| 371 | return Err(StateError::BranchNotFound(branch_id)); |
| 372 | } |
| 373 | |
| 374 | let seq = self.next_sequence_id.fetch_add(1, Ordering::SeqCst); |
| 375 | let inc = inner |
| 376 | .incarnations |
| 377 | .get_mut(&branch_id) |
| 378 | .ok_or(StateError::BranchNotFound(branch_id))?; |
| 379 | |
| 380 | inc.sequence_id = seq; |
| 381 | if inc.physical_state.compute_state == ComputeState::Suspended { |
| 382 | inc.physical_state.compute_state = ComputeState::Idle; |
| 383 | } |
| 384 | |
| 385 | Ok(seq) |
| 386 | } |
| 387 | |
| 388 | fn reconstruct_physical(&mut self, branch_id: LogicalBranchId) -> Result<(), StateError> { |
| 389 | let mut inner = self.inner.write().unwrap(); |
| 390 | let branch = inner |
| 391 | .branches |
| 392 | .get(&branch_id) |
| 393 | .ok_or(StateError::BranchNotFound(branch_id))? |
| 394 | .clone(); |
| 395 | |
| 396 | let inc = inner |
| 397 | .incarnations |
| 398 | .get_mut(&branch_id) |
| 399 | .ok_or(StateError::BranchNotFound(branch_id))?; |
| 400 | |
| 401 | // Reconstruct physical inference state deterministically from TokenHistory |
| 402 | inc.physical_state.allocated_tokens_in_kv = branch.token_history.len(); |
| 403 | inc.physical_state.kv_page_table_ref = Some(0xDEAD_0000 + branch.token_history.len()); |
| 404 | inc.physical_state.compute_state = ComputeState::Decoding; |
| 405 | |
| 406 | Ok(()) |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | #[cfg(test)] |
| 411 | mod tests { |
| 412 | use super::*; |
| 413 | |
| 414 | fn sealed_snapshot(snapshot: &AgentSnapshot) -> Vec<u8> { |
| 415 | let payload_json = serde_json::to_string(snapshot).unwrap(); |
| 416 | let hash = sha256::hash(payload_json.as_bytes()); |
| 417 | serde_json::to_vec(&CheckpointEnvelope { hash, payload_json }).unwrap() |
| 418 | } |
| 419 | |
| 420 | #[test] |
| 421 | fn test_checkpoint_reboot_and_reconstruction() { |
| 422 | let manager = AgentStateManager::new(1); |
| 423 | let agent_id = LogicalAgentId::from_seed("aienos-sovereign-agent"); |
| 424 | let root_branch = manager.register_agent(agent_id, 100); |
| 425 | |
| 426 | // Append 50 tokens |
| 427 | let tokens: Vec<u32> = (1..=50).collect(); |
| 428 | manager.append_tokens(root_branch, &tokens).unwrap(); |
| 429 | |
| 430 | // Fork branch |
| 431 | let child_branch = manager.fork_branch(root_branch).unwrap(); |
| 432 | manager.append_tokens(child_branch, &[51, 52]).unwrap(); |
| 433 | |
| 434 | // Add epistemic ref |
| 435 | let ref_id = [7u8; 16]; |
| 436 | manager.add_epistemic_ref(child_branch, ref_id).unwrap(); |
| 437 | |
| 438 | // Checkpoint agent |
| 439 | let checkpoint_bytes = manager.export_checkpoint(agent_id).unwrap(); |
| 440 | let CheckpointHash(hash) = manager.checkpoint(agent_id).unwrap(); |
| 441 | assert_ne!(hash, [0u8; 32]); |
| 442 | |
| 443 | // SIMULATE SOFT REBOOT: Host powers down, new manager boots with incarnation 2 |
| 444 | let mut rebooted_manager = |
| 445 | AgentStateManager::restore_from_checkpoint(&checkpoint_bytes, 2).unwrap(); |
| 446 | |
| 447 | // Verify logical identity intact |
| 448 | let restored_root = rebooted_manager.get_branch(&root_branch).unwrap(); |
| 449 | assert_eq!(restored_root.agent_id, agent_id); |
| 450 | assert_eq!(restored_root.token_history.len(), 50); |
| 451 | |
| 452 | let restored_child = rebooted_manager.get_branch(&child_branch).unwrap(); |
| 453 | assert_eq!(restored_child.parent_branch_id, Some(root_branch)); |
| 454 | assert_eq!(restored_child.token_history.len(), 52); |
| 455 | assert!(restored_child.epistemic_refs.contains(&ref_id)); |
| 456 | |
| 457 | // Physical state is evicted post-reboot |
| 458 | let inc = rebooted_manager.get_incarnation(&child_branch).unwrap(); |
| 459 | assert_eq!(inc.incarnation_id, 2); |
| 460 | assert_eq!(inc.physical_state.compute_state, ComputeState::Evicted); |
| 461 | assert_eq!(inc.physical_state.allocated_tokens_in_kv, 0); |
| 462 | |
| 463 | // Resume and reconstruct physical inference state |
| 464 | let new_seq = rebooted_manager.resume(child_branch).unwrap(); |
| 465 | assert!(new_seq > 0); |
| 466 | |
| 467 | rebooted_manager.reconstruct_physical(child_branch).unwrap(); |
| 468 | let inc_reconstructed = rebooted_manager.get_incarnation(&child_branch).unwrap(); |
| 469 | assert_eq!( |
| 470 | inc_reconstructed.physical_state.compute_state, |
| 471 | ComputeState::Decoding |
| 472 | ); |
| 473 | assert_eq!(inc_reconstructed.physical_state.allocated_tokens_in_kv, 52); |
| 474 | assert!(inc_reconstructed.physical_state.kv_page_table_ref.is_some()); |
| 475 | } |
| 476 | |
| 477 | #[test] |
| 478 | fn restore_rebuilds_fork_counters_without_reusing_branch_ids() { |
| 479 | let manager = AgentStateManager::new(1); |
| 480 | let agent_id = LogicalAgentId::from_seed("fork-counter-reboot-test"); |
| 481 | let root = manager.register_agent(agent_id, 100); |
| 482 | let child0 = manager.fork_branch(root).unwrap(); |
| 483 | manager.append_tokens(child0, &[11, 12]).unwrap(); |
| 484 | let child1 = manager.fork_branch(root).unwrap(); |
| 485 | |
| 486 | let checkpoint = manager.export_checkpoint(agent_id).unwrap(); |
| 487 | let restored = AgentStateManager::restore_from_checkpoint(&checkpoint, 2).unwrap(); |
| 488 | let child2 = restored.fork_branch(root).unwrap(); |
| 489 | assert_ne!(child2, child0); |
| 490 | assert_ne!(child2, child1); |
| 491 | assert_eq!(restored.get_branch(&child0).unwrap().token_history.len(), 2); |
| 492 | |
| 493 | let checkpoint_after_fork = restored.export_checkpoint(agent_id).unwrap(); |
| 494 | let restored_again = |
| 495 | AgentStateManager::restore_from_checkpoint(&checkpoint_after_fork, 3).unwrap(); |
| 496 | let child3 = restored_again.fork_branch(root).unwrap(); |
| 497 | assert_ne!(child3, child0); |
| 498 | assert_ne!(child3, child1); |
| 499 | assert_ne!(child3, child2); |
| 500 | assert_eq!( |
| 501 | restored_again.get_branch(&child2).unwrap().parent_branch_id, |
| 502 | Some(root) |
| 503 | ); |
| 504 | } |
| 505 | |
| 506 | #[test] |
| 507 | fn checkpoint_bytes_are_stable_across_restore() { |
| 508 | let manager = AgentStateManager::new(7); |
| 509 | let agent_id = LogicalAgentId::from_seed("canonical-checkpoint-test"); |
| 510 | let root = manager.register_agent(agent_id, 100); |
| 511 | for token in 0..24 { |
| 512 | let child = manager.fork_branch(root).unwrap(); |
| 513 | manager.append_tokens(child, &[token]).unwrap(); |
| 514 | } |
| 515 | |
| 516 | let first = manager.export_checkpoint(agent_id).unwrap(); |
| 517 | let restored = AgentStateManager::restore_from_checkpoint(&first, 7).unwrap(); |
| 518 | let second = restored.export_checkpoint(agent_id).unwrap(); |
| 519 | assert_eq!(first, second); |
| 520 | } |
| 521 | |
| 522 | #[test] |
| 523 | fn restore_refuses_checkpoint_without_durable_identity() { |
| 524 | let snapshot = AgentSnapshot { |
| 525 | agents: Vec::new(), |
| 526 | branches: Vec::new(), |
| 527 | snapshot_incarnation: 5, |
| 528 | }; |
| 529 | let checkpoint = sealed_snapshot(&snapshot); |
| 530 | assert_eq!( |
| 531 | AgentStateManager::restore_from_checkpoint(&checkpoint, 6).err(), |
| 532 | Some(StateError::InvalidCheckpoint("no durable agent identity")) |
| 533 | ); |
| 534 | } |
| 535 | |
| 536 | #[test] |
| 537 | fn restore_rejects_noncontiguous_persisted_fork_indexes() { |
| 538 | let manager = AgentStateManager::new(1); |
| 539 | let agent_id = LogicalAgentId::from_seed("fork-gap-test"); |
| 540 | let root = manager.register_agent(agent_id, 100); |
| 541 | let child0 = manager.fork_branch(root).unwrap(); |
| 542 | let _child1 = manager.fork_branch(root).unwrap(); |
| 543 | |
| 544 | let checkpoint = manager.export_checkpoint(agent_id).unwrap(); |
| 545 | let envelope: CheckpointEnvelope = serde_json::from_slice(&checkpoint).unwrap(); |
| 546 | let mut snapshot: AgentSnapshot = serde_json::from_str(&envelope.payload_json).unwrap(); |
| 547 | snapshot |
| 548 | .branches |
| 549 | .retain(|branch| branch.branch_id != child0); |
| 550 | let inconsistent_checkpoint = sealed_snapshot(&snapshot); |
| 551 | |
| 552 | assert_eq!( |
| 553 | AgentStateManager::restore_from_checkpoint(&inconsistent_checkpoint, 2).err(), |
| 554 | Some(StateError::InvalidCheckpoint( |
| 555 | "branch fork indexes are not contiguous" |
| 556 | )) |
| 557 | ); |
| 558 | } |
| 559 | |
| 560 | #[test] |
| 561 | fn re_registering_an_existing_identity_does_not_reset_its_root_branch() { |
| 562 | let manager = AgentStateManager::new(1); |
| 563 | let agent_id = LogicalAgentId::from_seed("idempotent-provisioning-test"); |
| 564 | let root = manager.register_agent(agent_id, 100); |
| 565 | manager |
| 566 | .append_tokens(root, &[4, 8, 15, 16, 23, 42]) |
| 567 | .unwrap(); |
| 568 | |
| 569 | assert_eq!(manager.register_agent(agent_id, 999), root); |
| 570 | let branch = manager.get_branch(&root).unwrap(); |
| 571 | assert_eq!(branch.created_at_utc, 100); |
| 572 | assert_eq!(branch.token_history.tokens(), [4, 8, 15, 16, 23, 42]); |
| 573 | } |
| 574 | |
| 575 | /// Branch tree used by the round-trip and fail-closed tests: |
| 576 | /// root -> {child0 -> {grandchild}, child1}. |
| 577 | struct Tree { |
| 578 | agent_id: LogicalAgentId, |
| 579 | root: LogicalBranchId, |
| 580 | child0: LogicalBranchId, |
| 581 | child1: LogicalBranchId, |
| 582 | grandchild: LogicalBranchId, |
| 583 | } |
| 584 | |
| 585 | fn build_tree(manager: &AgentStateManager, seed: &str) -> Tree { |
| 586 | let agent_id = LogicalAgentId::from_seed(seed); |
| 587 | let root = manager.register_agent(agent_id, 100); |
| 588 | manager.append_tokens(root, &[1, 2, 3]).unwrap(); |
| 589 | let child0 = manager.fork_branch(root).unwrap(); |
| 590 | manager.append_tokens(child0, &[4]).unwrap(); |
| 591 | manager.add_epistemic_ref(child0, [9u8; 16]).unwrap(); |
| 592 | let child1 = manager.fork_branch(root).unwrap(); |
| 593 | let grandchild = manager.fork_branch(child0).unwrap(); |
| 594 | manager.append_tokens(grandchild, &[5, 6]).unwrap(); |
| 595 | Tree { |
| 596 | agent_id, |
| 597 | root, |
| 598 | child0, |
| 599 | child1, |
| 600 | grandchild, |
| 601 | } |
| 602 | } |
| 603 | |
| 604 | fn decode_snapshot(checkpoint: &[u8]) -> AgentSnapshot { |
| 605 | let envelope: CheckpointEnvelope = serde_json::from_slice(checkpoint).unwrap(); |
| 606 | serde_json::from_str(&envelope.payload_json).unwrap() |
| 607 | } |
| 608 | |
| 609 | fn branch_mut(snapshot: &mut AgentSnapshot, id: LogicalBranchId) -> &mut LogicalBranch { |
| 610 | snapshot |
| 611 | .branches |
| 612 | .iter_mut() |
| 613 | .find(|branch| branch.branch_id == id) |
| 614 | .unwrap() |
| 615 | } |
| 616 | |
| 617 | /// Export a valid tree, let `tamper` corrupt the decoded snapshot, reseal |
| 618 | /// it with a correct hash, and return the restore error. |
| 619 | fn restore_tampered(tamper: impl FnOnce(&Tree, &mut AgentSnapshot)) -> StateError { |
| 620 | let manager = AgentStateManager::new(1); |
| 621 | let tree = build_tree(&manager, "fail-closed-restore-test"); |
| 622 | let checkpoint = manager.export_checkpoint(tree.agent_id).unwrap(); |
| 623 | // Sanity: the untampered checkpoint is accepted. |
| 624 | assert!(AgentStateManager::restore_from_checkpoint(&checkpoint, 2).is_ok()); |
| 625 | let mut snapshot = decode_snapshot(&checkpoint); |
| 626 | tamper(&tree, &mut snapshot); |
| 627 | match AgentStateManager::restore_from_checkpoint(&sealed_snapshot(&snapshot), 2) { |
| 628 | Ok(_) => panic!("tampered checkpoint was accepted"), |
| 629 | Err(error) => error, |
| 630 | } |
| 631 | } |
| 632 | |
| 633 | #[test] |
| 634 | fn restore_round_trips_branches_and_next_fork_indexes_exactly() { |
| 635 | let manager = AgentStateManager::new(1); |
| 636 | let tree = build_tree(&manager, "exact-round-trip-test"); |
| 637 | let checkpoint = manager.export_checkpoint(tree.agent_id).unwrap(); |
| 638 | let restored = AgentStateManager::restore_from_checkpoint(&checkpoint, 2).unwrap(); |
| 639 | |
| 640 | let original = decode_snapshot(&checkpoint); |
| 641 | assert_eq!(original.branches.len(), 4); |
| 642 | for branch in &original.branches { |
| 643 | assert_eq!( |
| 644 | restored.get_branch(&branch.branch_id).as_ref(), |
| 645 | Some(branch) |
| 646 | ); |
| 647 | let inc = restored.get_incarnation(&branch.branch_id).unwrap(); |
| 648 | assert_eq!(inc.incarnation_id, 2); |
| 649 | assert_eq!(inc.physical_state.compute_state, ComputeState::Evicted); |
| 650 | } |
| 651 | let grandchild = restored.get_branch(&tree.grandchild).unwrap(); |
| 652 | assert_eq!(grandchild.parent_branch_id, Some(tree.child0)); |
| 653 | assert_eq!( |
| 654 | grandchild.lineage.ancestor_branches, |
| 655 | [tree.child0, tree.grandchild] |
| 656 | ); |
| 657 | assert_eq!(grandchild.lineage.depth, 2); |
| 658 | |
| 659 | // Each parent's next fork continues exactly where the original left off, |
| 660 | // and matches what the never-restarted manager would allocate. |
| 661 | for (parent, next_index) in [(tree.root, 2), (tree.child0, 1), (tree.child1, 0)] { |
| 662 | let expected = LogicalBranchId::derive(parent, next_index); |
| 663 | assert_eq!(restored.fork_branch(parent).unwrap(), expected); |
| 664 | assert_eq!(manager.fork_branch(parent).unwrap(), expected); |
| 665 | } |
| 666 | // Fresh forks did not overwrite any restored branch. |
| 667 | for branch in &original.branches { |
| 668 | assert_eq!( |
| 669 | restored.get_branch(&branch.branch_id).as_ref(), |
| 670 | Some(branch) |
| 671 | ); |
| 672 | } |
| 673 | assert_eq!( |
| 674 | restored.fork_branch(tree.grandchild).unwrap(), |
| 675 | LogicalBranchId::derive(tree.grandchild, 0) |
| 676 | ); |
| 677 | } |
| 678 | |
| 679 | #[test] |
| 680 | fn re_registering_keeps_forked_branches_and_fork_indexes() { |
| 681 | let manager = AgentStateManager::new(1); |
| 682 | let tree = build_tree(&manager, "re-register-keeps-forks-test"); |
| 683 | let before = decode_snapshot(&manager.export_checkpoint(tree.agent_id).unwrap()); |
| 684 | |
| 685 | assert_eq!(manager.register_agent(tree.agent_id, 999), tree.root); |
| 686 | let after = decode_snapshot(&manager.export_checkpoint(tree.agent_id).unwrap()); |
| 687 | assert_eq!(before.branches, after.branches); |
| 688 | assert_eq!( |
| 689 | manager.fork_branch(tree.root).unwrap(), |
| 690 | LogicalBranchId::derive(tree.root, 2) |
| 691 | ); |
| 692 | |
| 693 | // Re-provisioning after a restart is also a no-op on committed history. |
| 694 | let checkpoint = manager.export_checkpoint(tree.agent_id).unwrap(); |
| 695 | let restored = AgentStateManager::restore_from_checkpoint(&checkpoint, 2).unwrap(); |
| 696 | assert_eq!(restored.register_agent(tree.agent_id, 1234), tree.root); |
| 697 | assert_eq!( |
| 698 | decode_snapshot(&restored.export_checkpoint(tree.agent_id).unwrap()).branches, |
| 699 | decode_snapshot(&checkpoint).branches |
| 700 | ); |
| 701 | assert_eq!( |
| 702 | restored.fork_branch(tree.root).unwrap(), |
| 703 | LogicalBranchId::derive(tree.root, 3) |
| 704 | ); |
| 705 | } |
| 706 | |
| 707 | #[test] |
| 708 | fn restore_rejects_duplicate_agent_identity() { |
| 709 | let error = restore_tampered(|tree, snapshot| snapshot.agents.push(tree.agent_id)); |
| 710 | assert_eq!( |
| 711 | error, |
| 712 | StateError::InvalidCheckpoint("duplicate agent identity") |
| 713 | ); |
| 714 | } |
| 715 | |
| 716 | #[test] |
| 717 | fn restore_rejects_branch_of_absent_agent() { |
| 718 | let error = restore_tampered(|_, snapshot| { |
| 719 | let stranger = LogicalAgentId::from_seed("absent-agent"); |
| 720 | snapshot.branches.push(LogicalBranch::new_root(stranger, 1)); |
| 721 | }); |
| 722 | assert_eq!( |
| 723 | error, |
| 724 | StateError::InvalidCheckpoint("branch refers to an absent agent identity") |
| 725 | ); |
| 726 | } |
| 727 | |
| 728 | #[test] |
| 729 | fn restore_rejects_duplicate_branch_identity() { |
| 730 | let error = restore_tampered(|tree, snapshot| { |
| 731 | let copy = branch_mut(snapshot, tree.child1).clone(); |
| 732 | snapshot.branches.push(copy); |
| 733 | }); |
| 734 | assert_eq!( |
| 735 | error, |
| 736 | StateError::InvalidCheckpoint("duplicate branch identity") |
| 737 | ); |
| 738 | } |
| 739 | |
| 740 | #[test] |
| 741 | fn restore_rejects_missing_root_branch() { |
| 742 | let error = restore_tampered(|tree, snapshot| { |
| 743 | snapshot |
| 744 | .branches |
| 745 | .retain(|branch| branch.branch_id != tree.root); |
| 746 | }); |
| 747 | assert_eq!( |
| 748 | error, |
| 749 | StateError::InvalidCheckpoint("root branch is missing") |
| 750 | ); |
| 751 | } |
| 752 | |
| 753 | #[test] |
| 754 | fn restore_rejects_inconsistent_root_branch() { |
| 755 | type Tamper = fn(&mut LogicalBranch); |
| 756 | let tampers: [Tamper; 4] = [ |
| 757 | |root| root.lineage.depth = 1, |
| 758 | |root| root.lineage.ancestor_branches.push(root.branch_id), |
| 759 | |root| root.lineage.root_agent = LogicalAgentId::from_seed("other"), |
| 760 | |root| root.parent_branch_id = Some(root.branch_id), |
| 761 | ]; |
| 762 | for tamper in tampers { |
| 763 | let error = restore_tampered(|tree, snapshot| tamper(branch_mut(snapshot, tree.root))); |
| 764 | assert_eq!( |
| 765 | error, |
| 766 | StateError::InvalidCheckpoint("root branch is inconsistent") |
| 767 | ); |
| 768 | } |
| 769 | |
| 770 | // Root branch id of agent A carrying agent B's identity. |
| 771 | let error = restore_tampered(|tree, snapshot| { |
| 772 | let other = LogicalAgentId::from_seed("other"); |
| 773 | snapshot.agents.push(other); |
| 774 | snapshot.branches.push(LogicalBranch::new_root(other, 1)); |
| 775 | branch_mut(snapshot, tree.root).agent_id = other; |
| 776 | }); |
| 777 | assert_eq!( |
| 778 | error, |
| 779 | StateError::InvalidCheckpoint("root branch is inconsistent") |
| 780 | ); |
| 781 | } |
| 782 | |
| 783 | #[test] |
| 784 | fn restore_rejects_parentless_non_root_branch() { |
| 785 | let error = restore_tampered(|tree, snapshot| { |
| 786 | branch_mut(snapshot, tree.child1).parent_branch_id = None; |
| 787 | }); |
| 788 | assert_eq!( |
| 789 | error, |
| 790 | StateError::InvalidCheckpoint("unexpected root branch") |
| 791 | ); |
| 792 | } |
| 793 | |
| 794 | #[test] |
| 795 | fn restore_rejects_branch_with_missing_parent() { |
| 796 | let error = restore_tampered(|tree, snapshot| { |
| 797 | snapshot |
| 798 | .branches |
| 799 | .retain(|branch| branch.branch_id != tree.child0); |
| 800 | }); |
| 801 | assert_eq!( |
| 802 | error, |
| 803 | StateError::InvalidCheckpoint("parent branch is missing") |
| 804 | ); |
| 805 | } |
| 806 | |
| 807 | #[test] |
| 808 | fn restore_rejects_inconsistent_lineage() { |
| 809 | type Tamper = fn(&Tree, &mut AgentSnapshot); |
| 810 | let tampers: [Tamper; 4] = [ |
| 811 | |tree, snapshot| branch_mut(snapshot, tree.grandchild).lineage.depth = 3, |
| 812 | |tree, snapshot| { |
| 813 | branch_mut(snapshot, tree.grandchild) |
| 814 | .lineage |
| 815 | .ancestor_branches |
| 816 | .remove(0); |
| 817 | }, |
| 818 | |tree, snapshot| { |
| 819 | branch_mut(snapshot, tree.grandchild).lineage.root_agent = |
| 820 | LogicalAgentId::from_seed("other"); |
| 821 | }, |
| 822 | // Parent/child cycle: child0 <-> child1. |
| 823 | |tree, snapshot| { |
| 824 | branch_mut(snapshot, tree.child0).parent_branch_id = Some(tree.child1); |
| 825 | branch_mut(snapshot, tree.child1).parent_branch_id = Some(tree.child0); |
| 826 | }, |
| 827 | ]; |
| 828 | for tamper in tampers { |
| 829 | assert_eq!( |
| 830 | restore_tampered(tamper), |
| 831 | StateError::InvalidCheckpoint("branch lineage is inconsistent") |
| 832 | ); |
| 833 | } |
| 834 | |
| 835 | // Child of another agent's branch. |
| 836 | let error = restore_tampered(|tree, snapshot| { |
| 837 | let other = LogicalAgentId::from_seed("other"); |
| 838 | snapshot.agents.push(other); |
| 839 | snapshot.branches.push(LogicalBranch::new_root(other, 1)); |
| 840 | branch_mut(snapshot, tree.grandchild).agent_id = other; |
| 841 | }); |
| 842 | assert_eq!( |
| 843 | error, |
| 844 | StateError::InvalidCheckpoint("branch lineage is inconsistent") |
| 845 | ); |
| 846 | } |
| 847 | |
| 848 | #[test] |
| 849 | fn restore_rejects_child_id_not_derived_from_fork_index() { |
| 850 | let error = restore_tampered(|tree, snapshot| { |
| 851 | // Consistent lineage, but child1 carries an id for fork index 7. |
| 852 | let bogus = LogicalBranchId::derive(tree.root, 7); |
| 853 | let child1 = branch_mut(snapshot, tree.child1); |
| 854 | child1.branch_id = bogus; |
| 855 | child1.lineage.ancestor_branches = vec![bogus]; |
| 856 | }); |
| 857 | assert_eq!( |
| 858 | error, |
| 859 | StateError::InvalidCheckpoint("branch fork indexes are not contiguous") |
| 860 | ); |
| 861 | } |
| 862 | |
| 863 | #[test] |
| 864 | fn test_suspend_resume_lifecycle_and_tamper_rejection() { |
| 865 | let mut manager = AgentStateManager::new(1); |
| 866 | let agent_id = LogicalAgentId::from_seed("suspend-test-agent"); |
| 867 | let branch = manager.register_agent(agent_id, 100); |
| 868 | |
| 869 | // Suspend branch |
| 870 | manager.suspend(branch).expect("Suspend active branch"); |
| 871 | let inc = manager.get_incarnation(&branch).unwrap(); |
| 872 | assert_eq!(inc.physical_state.compute_state, ComputeState::Suspended); |
| 873 | |
| 874 | // Suspending already suspended branch must fail |
| 875 | assert!(matches!( |
| 876 | manager.suspend(branch), |
| 877 | Err(StateError::AlreadySuspended(_)) |
| 878 | )); |
| 879 | |
| 880 | // Resume branch returns new sequence ID and transitions to Idle |
| 881 | let seq = manager.resume(branch).expect("Resume branch"); |
| 882 | assert!(seq > 0); |
| 883 | let inc_resumed = manager.get_incarnation(&branch).unwrap(); |
| 884 | assert_eq!(inc_resumed.physical_state.compute_state, ComputeState::Idle); |
| 885 | |
| 886 | // Tamper detection on checkpoint restore |
| 887 | let mut valid_checkpoint = manager.export_checkpoint(agent_id).unwrap(); |
| 888 | // Corrupt one byte in payload JSON |
| 889 | let last_idx = valid_checkpoint.len() - 5; |
| 890 | valid_checkpoint[last_idx] ^= 0x55; |
| 891 | |
| 892 | let restore_result = AgentStateManager::restore_from_checkpoint(&valid_checkpoint, 2); |
| 893 | assert!( |
| 894 | matches!( |
| 895 | restore_result, |
| 896 | Err(StateError::ChecksumMismatch) | Err(StateError::DeserializationError(_)) |
| 897 | ), |
| 898 | "Corrupted checkpoint must be detected and rejected" |
| 899 | ); |
| 900 | } |
| 901 | } |