spark-rsi-mv
Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger
Brought by drakestapleton
spark-rsi-mv / src / supervisor / daemon.rs
| 1 | use crate::canary::{ObservationLogWriter, CANARY_PROTOCOL_VERSION}; |
| 2 | use crate::supervisor::ipc::{ |
| 3 | ConnectionAuthState, IpcConnection, IpcServer, SessionAuth, SupervisorMessage, WorkerMessage, |
| 4 | }; |
| 5 | use crate::supervisor::{GenerationInfo, GenerationState, HostSupervisor}; |
| 6 | use std::path::{Path, PathBuf}; |
| 7 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 8 | use std::sync::Arc; |
| 9 | use std::time::Duration; |
| 10 | use tokio::sync::Mutex; |
| 11 | |
| 12 | /// How long a worker has to become ready on the legacy message loop: a versioned `Ready`, the |
| 13 | /// HMAC challenge and the supervisor's `Ping`, all of it. The canary executor takes its own |
| 14 | /// readiness deadline from its configuration. |
| 15 | pub const READINESS_DEADLINE: Duration = Duration::from_secs(10); |
| 16 | |
| 17 | /// Why a connection did not become ready. None of these is ready, and none is a rollback by |
| 18 | /// itself: a worker that never becomes ready fails the canary through the deadline. |
| 19 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 20 | pub enum ReadinessFailureKind { |
| 21 | /// Nothing, or not everything, arrived before the readiness deadline. |
| 22 | Timeout, |
| 23 | /// The peer closed the connection first. |
| 24 | Closed, |
| 25 | /// `Ready` without the current protocol version (an older worker reads as version 0). |
| 26 | OldProtocol, |
| 27 | /// `Ready` for a generation other than the expected one. |
| 28 | WrongGeneration, |
| 29 | /// The HMAC answer did not verify. |
| 30 | BadHmac, |
| 31 | /// Any other frame where `Ready` or `AuthResponse` belonged. |
| 32 | Unexpected, |
| 33 | } |
| 34 | |
| 35 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 36 | pub struct ReadinessFailure { |
| 37 | pub kind: ReadinessFailureKind, |
| 38 | pub detail: String, |
| 39 | } |
| 40 | |
| 41 | impl std::fmt::Display for ReadinessFailure { |
| 42 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 43 | write!(f, "worker not ready ({:?}): {}", self.kind, self.detail) |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | fn recv_failure(err: String) -> ReadinessFailure { |
| 48 | let kind = if err.contains("closed by peer") { |
| 49 | ReadinessFailureKind::Closed |
| 50 | } else { |
| 51 | ReadinessFailureKind::Unexpected |
| 52 | }; |
| 53 | ReadinessFailure { kind, detail: err } |
| 54 | } |
| 55 | |
| 56 | /// Accepts a `Ready` only if it is versioned and names the expected generation. Returns the |
| 57 | /// worker's pid and protocol version. |
| 58 | pub fn check_ready( |
| 59 | expected_generation: &str, |
| 60 | msg: WorkerMessage, |
| 61 | ) -> Result<(u32, u16), ReadinessFailure> { |
| 62 | match msg { |
| 63 | WorkerMessage::Ready { |
| 64 | generation_id, |
| 65 | pid, |
| 66 | protocol_version, |
| 67 | .. |
| 68 | } => { |
| 69 | if protocol_version != CANARY_PROTOCOL_VERSION { |
| 70 | return Err(ReadinessFailure { |
| 71 | kind: ReadinessFailureKind::OldProtocol, |
| 72 | detail: format!( |
| 73 | "Ready states protocol version {}, expected {}", |
| 74 | protocol_version, CANARY_PROTOCOL_VERSION |
| 75 | ), |
| 76 | }); |
| 77 | } |
| 78 | if generation_id != expected_generation { |
| 79 | return Err(ReadinessFailure { |
| 80 | kind: ReadinessFailureKind::WrongGeneration, |
| 81 | detail: format!( |
| 82 | "Ready names generation {}, expected {}", |
| 83 | generation_id, expected_generation |
| 84 | ), |
| 85 | }); |
| 86 | } |
| 87 | Ok((pid, protocol_version)) |
| 88 | } |
| 89 | other => Err(ReadinessFailure { |
| 90 | kind: ReadinessFailureKind::Unexpected, |
| 91 | detail: format!("expected a versioned Ready first, got {:?}", other), |
| 92 | }), |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | /// Sends the HMAC challenge for `generation_id` and verifies the worker's answer. |
| 97 | pub async fn challenge_worker( |
| 98 | conn: &mut IpcConnection, |
| 99 | generation_id: &str, |
| 100 | shared_secret: &str, |
| 101 | ) -> Result<(), ReadinessFailure> { |
| 102 | let nonce = format!("challenge-{}", uuid::Uuid::new_v4().simple()); |
| 103 | conn.send(&SupervisorMessage::AuthChallenge { |
| 104 | nonce: nonce.clone(), |
| 105 | }) |
| 106 | .await |
| 107 | .map_err(recv_failure)?; |
| 108 | |
| 109 | let auth_msg: WorkerMessage = conn.recv().await.map_err(recv_failure)?; |
| 110 | let candidate_hmac = match auth_msg { |
| 111 | WorkerMessage::AuthResponse { response } => response, |
| 112 | other => { |
| 113 | return Err(ReadinessFailure { |
| 114 | kind: ReadinessFailureKind::Unexpected, |
| 115 | detail: format!("expected AuthResponse, got {:?}", other), |
| 116 | }) |
| 117 | } |
| 118 | }; |
| 119 | let message_to_sign = format!("{}:{}", generation_id, nonce); |
| 120 | if !SessionAuth::verify_hmac(shared_secret, &message_to_sign, &candidate_hmac) { |
| 121 | return Err(ReadinessFailure { |
| 122 | kind: ReadinessFailureKind::BadHmac, |
| 123 | detail: format!("HMAC for generation {} did not verify", generation_id), |
| 124 | }); |
| 125 | } |
| 126 | Ok(()) |
| 127 | } |
| 128 | |
| 129 | /// Readiness, as defined in docs/CANARY-CONTRACT.md: the worker sends a versioned `Ready` for |
| 130 | /// the expected generation, completes the HMAC challenge, and the supervisor replies `Ping`, |
| 131 | /// all within `deadline`. Anything else (a bare connection, silence, an older `Ready`, another |
| 132 | /// generation, a failed HMAC, an unknown frame) is not ready. Only success yields |
| 133 | /// `Authenticated`. |
| 134 | pub async fn authenticate_worker_connection( |
| 135 | conn: &mut IpcConnection, |
| 136 | expected_generation: &str, |
| 137 | shared_secret: &str, |
| 138 | deadline: Duration, |
| 139 | ) -> Result<ConnectionAuthState, ReadinessFailure> { |
| 140 | let handshake = async { |
| 141 | let first: WorkerMessage = conn.recv().await.map_err(recv_failure)?; |
| 142 | let (pid, protocol_version) = check_ready(expected_generation, first)?; |
| 143 | challenge_worker(conn, expected_generation, shared_secret).await?; |
| 144 | conn.send(&SupervisorMessage::Ping) |
| 145 | .await |
| 146 | .map_err(recv_failure)?; |
| 147 | Ok(ConnectionAuthState::Authenticated { |
| 148 | generation_id: expected_generation.to_string(), |
| 149 | pid, |
| 150 | protocol_version, |
| 151 | }) |
| 152 | }; |
| 153 | match tokio::time::timeout(deadline, handshake).await { |
| 154 | Ok(result) => result, |
| 155 | Err(_) => Err(ReadinessFailure { |
| 156 | kind: ReadinessFailureKind::Timeout, |
| 157 | detail: format!("no completed handshake within {:?}", deadline), |
| 158 | }), |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | #[derive(Debug, Clone)] |
| 163 | pub struct SupervisorConfig { |
| 164 | pub rsi_root: PathBuf, |
| 165 | pub socket_path: PathBuf, |
| 166 | pub memory_limit_mb: u64, |
| 167 | pub canary_target: u64, |
| 168 | pub max_latency_us: u64, |
| 169 | pub max_error_rate: f64, |
| 170 | pub shared_secret: String, |
| 171 | } |
| 172 | |
| 173 | pub fn resolve_supervisor_secret() -> String { |
| 174 | if let Ok(sec) = std::env::var("SUPERVISOR_SECRET") { |
| 175 | let trimmed = sec.trim().to_string(); |
| 176 | if !trimmed.is_empty() { |
| 177 | return trimmed; |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | if let Ok(out) = std::process::Command::new("atlas-vault") |
| 182 | .args(["get", "SUPERVISOR_SECRET"]) |
| 183 | .output() |
| 184 | { |
| 185 | if out.status.success() { |
| 186 | let val = String::from_utf8_lossy(&out.stdout).trim().to_string(); |
| 187 | if !val.is_empty() { |
| 188 | return val; |
| 189 | } |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | // Ephemeral in-memory dynamic secret: strictly hardware TPM or ephemeral memory, zero disk secrets |
| 194 | format!("tpm-ephemeral-{}", uuid::Uuid::new_v4().simple()) |
| 195 | } |
| 196 | |
| 197 | impl Default for SupervisorConfig { |
| 198 | fn default() -> Self { |
| 199 | Self { |
| 200 | rsi_root: PathBuf::from(".rsi"), |
| 201 | socket_path: PathBuf::from(".rsi/supervisor.sock"), |
| 202 | memory_limit_mb: 49152, |
| 203 | canary_target: 5000, |
| 204 | max_latency_us: 1_000_000, |
| 205 | max_error_rate: 0.0, |
| 206 | shared_secret: resolve_supervisor_secret(), |
| 207 | } |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | pub struct SupervisorDaemon { |
| 212 | pub config: SupervisorConfig, |
| 213 | pub supervisor: HostSupervisor, |
| 214 | pub active_generation: Arc<Mutex<Option<GenerationInfo>>>, |
| 215 | pub canary_generation: Arc<Mutex<Option<GenerationInfo>>>, |
| 216 | pub running: Arc<AtomicBool>, |
| 217 | /// The open observation log of the canary generation, when one is attached. Rejections are |
| 218 | /// appended to it. |
| 219 | pub observation_log: Arc<Mutex<Option<ObservationLogWriter>>>, |
| 220 | } |
| 221 | |
| 222 | impl SupervisorDaemon { |
| 223 | pub fn new(config: SupervisorConfig) -> Self { |
| 224 | let supervisor = HostSupervisor::new(&config.rsi_root, config.memory_limit_mb); |
| 225 | Self { |
| 226 | config, |
| 227 | supervisor, |
| 228 | active_generation: Arc::new(Mutex::new(None)), |
| 229 | canary_generation: Arc::new(Mutex::new(None)), |
| 230 | running: Arc::new(AtomicBool::new(true)), |
| 231 | observation_log: Arc::new(Mutex::new(None)), |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | pub async fn stage_canary( |
| 236 | &self, |
| 237 | generation_id: &str, |
| 238 | artifacts_dir: &Path, |
| 239 | manifest_digest: &str, |
| 240 | ) -> Result<GenerationInfo, String> { |
| 241 | let gen = |
| 242 | self.supervisor |
| 243 | .stage_generation(generation_id, artifacts_dir, manifest_digest)?; |
| 244 | |
| 245 | let mut canary_lock = self.canary_generation.lock().await; |
| 246 | *canary_lock = Some(gen.clone()); |
| 247 | Ok(gen) |
| 248 | } |
| 249 | |
| 250 | /// Opens a generation's observation log to the legacy message loop so rejections are |
| 251 | /// recorded in it as well as traced. |
| 252 | pub async fn attach_observation_log(&self, writer: ObservationLogWriter) { |
| 253 | *self.observation_log.lock().await = Some(writer); |
| 254 | } |
| 255 | |
| 256 | /// Takes the log back, for sealing. |
| 257 | pub async fn detach_observation_log(&self) -> Option<ObservationLogWriter> { |
| 258 | self.observation_log.lock().await.take() |
| 259 | } |
| 260 | |
| 261 | /// Records a refused message (tracing, plus the observation log when one is open) and |
| 262 | /// returns the reason as the error that closes the connection. A rejection never triggers |
| 263 | /// a rollback; a worker that stays silent still fails the canary through its deadline. |
| 264 | async fn reject(&self, reason: String) -> String { |
| 265 | tracing::warn!(target: "supervisor", "rejected worker message: {}", reason); |
| 266 | if let Some(log) = self.observation_log.lock().await.as_mut() { |
| 267 | let now_ms = chrono::Utc::now().timestamp_millis().max(0) as u64; |
| 268 | if let Err(e) = log.append_rejection(&reason, now_ms) { |
| 269 | tracing::error!(target: "supervisor", "cannot record rejection: {}", e); |
| 270 | } |
| 271 | } |
| 272 | reason |
| 273 | } |
| 274 | |
| 275 | /// Handles one frame on a connection whose state is `auth`. `Err` means the connection must |
| 276 | /// be closed. A connection starts `Unauthenticated`; only a versioned `Ready` for the |
| 277 | /// canary generation plus a verified HMAC makes it `Authenticated`. Every other frame is |
| 278 | /// checked against that state first. |
| 279 | /// |
| 280 | /// Nothing here grants `Durable`, and nothing here switches `active.sock` on `Ready`. |
| 281 | /// `CanaryReport` is a diagnostic that can only make the supervisor more cautious. |
| 282 | pub async fn process_worker_message( |
| 283 | &self, |
| 284 | conn: &mut IpcConnection, |
| 285 | auth: &mut ConnectionAuthState, |
| 286 | msg: WorkerMessage, |
| 287 | active_socket_link: &Path, |
| 288 | ) -> Result<Option<SupervisorMessage>, String> { |
| 289 | if let WorkerMessage::Ready { .. } = msg { |
| 290 | if *auth != ConnectionAuthState::Unauthenticated { |
| 291 | return Err(self |
| 292 | .reject("repeated Ready on an authenticated connection".to_string()) |
| 293 | .await); |
| 294 | } |
| 295 | let expected = { |
| 296 | let canary_lock = self.canary_generation.lock().await; |
| 297 | canary_lock.as_ref().map(|c| c.generation_id.clone()) |
| 298 | }; |
| 299 | let expected = match expected { |
| 300 | Some(id) => id, |
| 301 | None => { |
| 302 | return Err(self |
| 303 | .reject("Ready while no canary generation is staged".to_string()) |
| 304 | .await) |
| 305 | } |
| 306 | }; |
| 307 | let (pid, protocol_version) = match check_ready(&expected, msg) { |
| 308 | Ok(v) => v, |
| 309 | Err(failure) => return Err(self.reject(failure.to_string()).await), |
| 310 | }; |
| 311 | let challenged = tokio::time::timeout( |
| 312 | READINESS_DEADLINE, |
| 313 | challenge_worker(conn, &expected, &self.config.shared_secret), |
| 314 | ) |
| 315 | .await; |
| 316 | match challenged { |
| 317 | Ok(Ok(())) => {} |
| 318 | Ok(Err(failure)) => return Err(self.reject(failure.to_string()).await), |
| 319 | Err(_) => { |
| 320 | return Err(self |
| 321 | .reject("HMAC challenge not answered before the readiness deadline".into()) |
| 322 | .await) |
| 323 | } |
| 324 | } |
| 325 | |
| 326 | let mut canary_lock = self.canary_generation.lock().await; |
| 327 | if let Some(ref mut canary) = *canary_lock { |
| 328 | if canary.generation_id == expected { |
| 329 | canary.state = GenerationState::Ready; |
| 330 | canary.pid = Some(pid); |
| 331 | } |
| 332 | } |
| 333 | *auth = ConnectionAuthState::Authenticated { |
| 334 | generation_id: expected, |
| 335 | pid, |
| 336 | protocol_version, |
| 337 | }; |
| 338 | return Ok(Some(SupervisorMessage::Ping)); |
| 339 | } |
| 340 | |
| 341 | let claimed: Option<&str> = match &msg { |
| 342 | WorkerMessage::Heartbeat { generation_id, .. } |
| 343 | | WorkerMessage::DrainComplete { generation_id } |
| 344 | | WorkerMessage::CanaryReport { generation_id, .. } |
| 345 | | WorkerMessage::ExecuteResult { generation_id, .. } => Some(generation_id), |
| 346 | _ => None, |
| 347 | }; |
| 348 | let generation_id = match auth { |
| 349 | ConnectionAuthState::Unauthenticated => { |
| 350 | return Err(self |
| 351 | .reject(format!( |
| 352 | "message on an unauthenticated connection: {:?}", |
| 353 | msg |
| 354 | )) |
| 355 | .await) |
| 356 | } |
| 357 | ConnectionAuthState::Authenticated { generation_id, .. } => generation_id.clone(), |
| 358 | }; |
| 359 | if let Some(named) = claimed { |
| 360 | if named != generation_id { |
| 361 | return Err(self |
| 362 | .reject(format!( |
| 363 | "connection authenticated for generation {} sent a message naming generation {}", |
| 364 | generation_id, named |
| 365 | )) |
| 366 | .await); |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | match msg { |
| 371 | WorkerMessage::Ready { .. } => unreachable!("Ready is handled above"), |
| 372 | |
| 373 | WorkerMessage::Heartbeat { |
| 374 | memory_mb, |
| 375 | active_requests: _, |
| 376 | timestamp_secs: _, |
| 377 | .. |
| 378 | } => { |
| 379 | let memory_exceeded; |
| 380 | { |
| 381 | let mut canary_lock = self.canary_generation.lock().await; |
| 382 | if let Some(ref mut canary) = *canary_lock { |
| 383 | if canary.generation_id == generation_id |
| 384 | && memory_mb > self.config.memory_limit_mb |
| 385 | { |
| 386 | canary.state = GenerationState::Reverting; |
| 387 | memory_exceeded = true; |
| 388 | } else { |
| 389 | memory_exceeded = false; |
| 390 | } |
| 391 | } else { |
| 392 | memory_exceeded = false; |
| 393 | } |
| 394 | } |
| 395 | |
| 396 | if memory_exceeded { |
| 397 | self.trigger_instant_rollback(active_socket_link).await?; |
| 398 | return Ok(Some(SupervisorMessage::RevertOrder { |
| 399 | reason: format!( |
| 400 | "Memory budget exceeded: {} MB > {} MB limit", |
| 401 | memory_mb, self.config.memory_limit_mb |
| 402 | ), |
| 403 | })); |
| 404 | } |
| 405 | Ok(Some(SupervisorMessage::Ping)) |
| 406 | } |
| 407 | |
| 408 | WorkerMessage::CanaryReport { |
| 409 | transaction_id, |
| 410 | success, |
| 411 | latency_us, |
| 412 | error, |
| 413 | .. |
| 414 | } => { |
| 415 | // A self-report is a diagnostic. It is logged and may trigger an early safety |
| 416 | // revert, but it never counts toward admission and never promotes. |
| 417 | tracing::info!( |
| 418 | target: "supervisor", |
| 419 | "diagnostic CanaryReport {} from {}: success={} latency_us={}", |
| 420 | transaction_id, generation_id, success, latency_us |
| 421 | ); |
| 422 | let mut revert_reason = error.clone(); |
| 423 | let should_revert; |
| 424 | { |
| 425 | let mut canary_lock = self.canary_generation.lock().await; |
| 426 | match *canary_lock { |
| 427 | Some(ref mut canary) if canary.generation_id == generation_id => { |
| 428 | match self.supervisor.record_canary_transaction( |
| 429 | canary, |
| 430 | success, |
| 431 | latency_us, |
| 432 | self.config.max_latency_us, |
| 433 | self.config.max_error_rate, |
| 434 | ) { |
| 435 | Ok(_) => should_revert = false, |
| 436 | Err(budget_err) => { |
| 437 | should_revert = true; |
| 438 | revert_reason = Some(match error { |
| 439 | Some(ref orig) => format!("{}: {}", orig, budget_err), |
| 440 | None => budget_err, |
| 441 | }); |
| 442 | } |
| 443 | } |
| 444 | } |
| 445 | _ => should_revert = false, |
| 446 | } |
| 447 | } |
| 448 | |
| 449 | if should_revert { |
| 450 | self.trigger_instant_rollback(active_socket_link).await?; |
| 451 | return Ok(Some(SupervisorMessage::RevertOrder { |
| 452 | reason: revert_reason |
| 453 | .unwrap_or_else(|| "Canary transaction failure".to_string()), |
| 454 | })); |
| 455 | } |
| 456 | Ok(None) |
| 457 | } |
| 458 | |
| 459 | // The worker saying it has drained changes nothing: a generation becomes Durable |
| 460 | // only after quota admission, the safety envelope and the promotion gate. |
| 461 | WorkerMessage::DrainComplete { .. } => Ok(None), |
| 462 | WorkerMessage::Pong => Ok(None), |
| 463 | WorkerMessage::AuthResponse { .. } => Err(self |
| 464 | .reject("AuthResponse outside a handshake".to_string()) |
| 465 | .await), |
| 466 | // Execute results are consumed by the supervisor-driven request loop that issued |
| 467 | // the request (`canary_exec`). This loop issued none, so a result here is |
| 468 | // unsolicited and creates nothing. |
| 469 | WorkerMessage::ExecuteResult { request_id, .. } => { |
| 470 | let _ = self |
| 471 | .reject(format!( |
| 472 | "unsolicited ExecuteResult for request {}", |
| 473 | request_id |
| 474 | )) |
| 475 | .await; |
| 476 | Ok(None) |
| 477 | } |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | pub async fn trigger_instant_rollback(&self, active_socket_link: &Path) -> Result<(), String> { |
| 482 | let active_lock = self.active_generation.lock().await; |
| 483 | if let Some(ref parent) = *active_lock { |
| 484 | let parent_sock = self |
| 485 | .config |
| 486 | .rsi_root |
| 487 | .join(format!("workers/{}.sock", parent.generation_id)); |
| 488 | self.supervisor.rollback_to_parent( |
| 489 | &parent.generation_id, |
| 490 | Some(active_socket_link), |
| 491 | Some(&parent_sock), |
| 492 | )?; |
| 493 | } |
| 494 | let mut canary_lock = self.canary_generation.lock().await; |
| 495 | if let Some(ref mut canary) = *canary_lock { |
| 496 | canary.state = GenerationState::Reverted; |
| 497 | } |
| 498 | Ok(()) |
| 499 | } |
| 500 | |
| 501 | pub async fn run_server(&self, active_socket_link: PathBuf) -> Result<(), String> { |
| 502 | let server = IpcServer::bind(&self.config.socket_path)?; |
| 503 | while self.running.load(Ordering::Relaxed) { |
| 504 | match tokio::time::timeout(Duration::from_millis(500), server.accept()).await { |
| 505 | Ok(Ok(mut conn)) => { |
| 506 | let active_link = active_socket_link.clone(); |
| 507 | let mut auth = ConnectionAuthState::Unauthenticated; |
| 508 | loop { |
| 509 | // An unauthenticated connection has the readiness deadline to speak; |
| 510 | // silence must not hold the server. |
| 511 | let received = if auth == ConnectionAuthState::Unauthenticated { |
| 512 | match tokio::time::timeout( |
| 513 | READINESS_DEADLINE, |
| 514 | conn.recv::<WorkerMessage>(), |
| 515 | ) |
| 516 | .await |
| 517 | { |
| 518 | Ok(r) => r, |
| 519 | Err(_) => { |
| 520 | let _ = self |
| 521 | .reject( |
| 522 | "connection silent past the readiness deadline".into(), |
| 523 | ) |
| 524 | .await; |
| 525 | break; |
| 526 | } |
| 527 | } |
| 528 | } else { |
| 529 | conn.recv::<WorkerMessage>().await |
| 530 | }; |
| 531 | let msg = match received { |
| 532 | Ok(msg) => msg, |
| 533 | Err(_) => break, |
| 534 | }; |
| 535 | match self |
| 536 | .process_worker_message(&mut conn, &mut auth, msg, &active_link) |
| 537 | .await |
| 538 | { |
| 539 | Ok(Some(reply)) => { |
| 540 | let _ = conn.send(&reply).await; |
| 541 | } |
| 542 | Ok(None) => {} |
| 543 | Err(_) => { |
| 544 | break; |
| 545 | } |
| 546 | } |
| 547 | } |
| 548 | } |
| 549 | Ok(Err(_)) => continue, |
| 550 | Err(_) => continue, |
| 551 | } |
| 552 | } |
| 553 | Ok(()) |
| 554 | } |
| 555 | } |
| 556 | |
| 557 | #[cfg(test)] |
| 558 | mod tests { |
| 559 | use super::*; |
| 560 | use crate::canary::LogHeader; |
| 561 | use crate::supervisor::ipc::ConnectionAuthState as Auth; |
| 562 | |
| 563 | const SECRET: &str = "secret-key"; |
| 564 | |
| 565 | fn config(tmp: &Path, max_latency_us: u64) -> SupervisorConfig { |
| 566 | let rsi_root = tmp.join(".rsi"); |
| 567 | SupervisorConfig { |
| 568 | rsi_root: rsi_root.clone(), |
| 569 | socket_path: rsi_root.join("supervisor.sock"), |
| 570 | memory_limit_mb: 49152, |
| 571 | canary_target: 3, |
| 572 | max_latency_us, |
| 573 | max_error_rate: 0.0, |
| 574 | shared_secret: SECRET.to_string(), |
| 575 | } |
| 576 | } |
| 577 | |
| 578 | async fn daemon_with_canary(tmp: &Path, gen: &str, max_latency_us: u64) -> SupervisorDaemon { |
| 579 | let daemon = SupervisorDaemon::new(config(tmp, max_latency_us)); |
| 580 | let src = tmp.join("art_cand"); |
| 581 | std::fs::create_dir_all(&src).unwrap(); |
| 582 | daemon.stage_canary(gen, &src, "sha-cand").await.unwrap(); |
| 583 | daemon |
| 584 | } |
| 585 | |
| 586 | /// Runs a real worker handshake against the daemon over a socket pair and returns the |
| 587 | /// supervisor side, its authentication state and the worker side (kept open). |
| 588 | async fn authenticated( |
| 589 | daemon: &SupervisorDaemon, |
| 590 | gen: &str, |
| 591 | active_link: &Path, |
| 592 | ) -> (IpcConnection, Auth, IpcConnection) { |
| 593 | let (stream_worker, stream_sup) = tokio::net::UnixStream::pair().unwrap(); |
| 594 | let mut conn_worker = IpcConnection::new(stream_worker); |
| 595 | let mut conn_sup = IpcConnection::new(stream_sup); |
| 596 | let gen_owned = gen.to_string(); |
| 597 | let worker = tokio::spawn(async move { |
| 598 | let reply = conn_worker |
| 599 | .perform_worker_handshake(&gen_owned, std::process::id(), SECRET) |
| 600 | .await; |
| 601 | (conn_worker, reply) |
| 602 | }); |
| 603 | let ready: WorkerMessage = conn_sup.recv().await.unwrap(); |
| 604 | let mut auth = Auth::Unauthenticated; |
| 605 | let reply = daemon |
| 606 | .process_worker_message(&mut conn_sup, &mut auth, ready, active_link) |
| 607 | .await |
| 608 | .unwrap(); |
| 609 | assert_eq!(reply, Some(SupervisorMessage::Ping)); |
| 610 | conn_sup.send(&reply.unwrap()).await.unwrap(); |
| 611 | let (conn_worker, worker_reply) = worker.await.unwrap(); |
| 612 | assert_eq!(worker_reply.unwrap(), SupervisorMessage::Ping); |
| 613 | (conn_sup, auth, conn_worker) |
| 614 | } |
| 615 | |
| 616 | fn report(gen: &str, id: u64, success: bool, latency_us: u64) -> WorkerMessage { |
| 617 | WorkerMessage::CanaryReport { |
| 618 | generation_id: gen.to_string(), |
| 619 | transaction_id: id, |
| 620 | success, |
| 621 | latency_us, |
| 622 | error: if success { |
| 623 | None |
| 624 | } else { |
| 625 | Some("Inference assertion panicked".to_string()) |
| 626 | }, |
| 627 | } |
| 628 | } |
| 629 | |
| 630 | #[tokio::test] |
| 631 | async fn ready_needs_versioned_hmac_and_never_switches_active_sock() { |
| 632 | let tmp = tempfile::tempdir().unwrap(); |
| 633 | let active_link = tmp.path().join(".rsi").join("active.sock"); |
| 634 | let daemon = daemon_with_canary(tmp.path(), "gen-002", 1_000_000).await; |
| 635 | |
| 636 | let (_conn, auth, _worker) = authenticated(&daemon, "gen-002", &active_link).await; |
| 637 | assert_eq!( |
| 638 | auth, |
| 639 | Auth::Authenticated { |
| 640 | generation_id: "gen-002".to_string(), |
| 641 | pid: std::process::id(), |
| 642 | protocol_version: CANARY_PROTOCOL_VERSION, |
| 643 | } |
| 644 | ); |
| 645 | let state = daemon |
| 646 | .canary_generation |
| 647 | .lock() |
| 648 | .await |
| 649 | .as_ref() |
| 650 | .unwrap() |
| 651 | .state; |
| 652 | assert_eq!(state, GenerationState::Ready); |
| 653 | assert!( |
| 654 | std::fs::symlink_metadata(&active_link).is_err(), |
| 655 | "Ready must not switch active.sock to the candidate" |
| 656 | ); |
| 657 | } |
| 658 | |
| 659 | #[tokio::test] |
| 660 | async fn old_protocol_other_generation_and_forged_hmac_are_never_ready() { |
| 661 | let tmp = tempfile::tempdir().unwrap(); |
| 662 | let active_link = tmp.path().join(".rsi").join("active.sock"); |
| 663 | let daemon = daemon_with_canary(tmp.path(), "gen-002", 1_000_000).await; |
| 664 | |
| 665 | for (ready_gen, version) in [("gen-002", 0u16), ("gen-other", CANARY_PROTOCOL_VERSION)] { |
| 666 | let (a, b) = tokio::net::UnixStream::pair().unwrap(); |
| 667 | let mut conn_sup = IpcConnection::new(b); |
| 668 | let _keep = a; |
| 669 | let mut auth = Auth::Unauthenticated; |
| 670 | let err = daemon |
| 671 | .process_worker_message( |
| 672 | &mut conn_sup, |
| 673 | &mut auth, |
| 674 | WorkerMessage::Ready { |
| 675 | generation_id: ready_gen.to_string(), |
| 676 | pid: 1, |
| 677 | auth_token: String::new(), |
| 678 | protocol_version: version, |
| 679 | }, |
| 680 | &active_link, |
| 681 | ) |
| 682 | .await |
| 683 | .unwrap_err(); |
| 684 | assert!(err.contains("not ready"), "{}", err); |
| 685 | assert_eq!(auth, Auth::Unauthenticated); |
| 686 | } |
| 687 | |
| 688 | // Forged HMAC: the worker answers the challenge with garbage. |
| 689 | let (a, b) = tokio::net::UnixStream::pair().unwrap(); |
| 690 | let mut worker = IpcConnection::new(a); |
| 691 | let mut conn_sup = IpcConnection::new(b); |
| 692 | let forged = tokio::spawn(async move { |
| 693 | worker |
| 694 | .send(&WorkerMessage::AuthResponse { |
| 695 | response: "forged".to_string(), |
| 696 | }) |
| 697 | .await |
| 698 | .unwrap(); |
| 699 | worker |
| 700 | }); |
| 701 | let mut auth = Auth::Unauthenticated; |
| 702 | let err = daemon |
| 703 | .process_worker_message( |
| 704 | &mut conn_sup, |
| 705 | &mut auth, |
| 706 | WorkerMessage::Ready { |
| 707 | generation_id: "gen-002".to_string(), |
| 708 | pid: 1, |
| 709 | auth_token: String::new(), |
| 710 | protocol_version: CANARY_PROTOCOL_VERSION, |
| 711 | }, |
| 712 | &active_link, |
| 713 | ) |
| 714 | .await |
| 715 | .unwrap_err(); |
| 716 | assert!(err.contains("BadHmac"), "{}", err); |
| 717 | assert_eq!(auth, Auth::Unauthenticated); |
| 718 | let _ = forged.await; |
| 719 | let state = daemon |
| 720 | .canary_generation |
| 721 | .lock() |
| 722 | .await |
| 723 | .as_ref() |
| 724 | .unwrap() |
| 725 | .state; |
| 726 | assert_eq!( |
| 727 | state, |
| 728 | GenerationState::Staged, |
| 729 | "a failed handshake changes nothing" |
| 730 | ); |
| 731 | } |
| 732 | |
| 733 | #[tokio::test] |
| 734 | async fn authenticate_worker_connection_fails_closed_on_silence_close_and_bad_frames() { |
| 735 | let deadline = Duration::from_millis(200); |
| 736 | |
| 737 | // Silence: connected, never speaks. |
| 738 | let (a, b) = tokio::net::UnixStream::pair().unwrap(); |
| 739 | let mut sup = IpcConnection::new(b); |
| 740 | let silent = authenticate_worker_connection(&mut sup, "gen-1", SECRET, deadline) |
| 741 | .await |
| 742 | .unwrap_err(); |
| 743 | assert_eq!(silent.kind, ReadinessFailureKind::Timeout); |
| 744 | drop(a); |
| 745 | |
| 746 | // Bare connection that closes. |
| 747 | let (a, b) = tokio::net::UnixStream::pair().unwrap(); |
| 748 | drop(a); |
| 749 | let mut sup = IpcConnection::new(b); |
| 750 | let closed = authenticate_worker_connection(&mut sup, "gen-1", SECRET, deadline) |
| 751 | .await |
| 752 | .unwrap_err(); |
| 753 | assert_eq!(closed.kind, ReadinessFailureKind::Closed); |
| 754 | |
| 755 | // A frame that is not Ready. |
| 756 | let (a, b) = tokio::net::UnixStream::pair().unwrap(); |
| 757 | let mut worker = IpcConnection::new(a); |
| 758 | let mut sup = IpcConnection::new(b); |
| 759 | worker.send(&WorkerMessage::Pong).await.unwrap(); |
| 760 | let unexpected = authenticate_worker_connection(&mut sup, "gen-1", SECRET, deadline) |
| 761 | .await |
| 762 | .unwrap_err(); |
| 763 | assert_eq!(unexpected.kind, ReadinessFailureKind::Unexpected); |
| 764 | |
| 765 | // Older Ready (protocol version 0). |
| 766 | let (a, b) = tokio::net::UnixStream::pair().unwrap(); |
| 767 | let mut worker = IpcConnection::new(a); |
| 768 | let mut sup = IpcConnection::new(b); |
| 769 | worker |
| 770 | .send(&WorkerMessage::Ready { |
| 771 | generation_id: "gen-1".to_string(), |
| 772 | pid: 1, |
| 773 | auth_token: String::new(), |
| 774 | protocol_version: 0, |
| 775 | }) |
| 776 | .await |
| 777 | .unwrap(); |
| 778 | let old = authenticate_worker_connection(&mut sup, "gen-1", SECRET, deadline) |
| 779 | .await |
| 780 | .unwrap_err(); |
| 781 | assert_eq!(old.kind, ReadinessFailureKind::OldProtocol); |
| 782 | |
| 783 | // The full handshake succeeds and ends with Ping. |
| 784 | let (a, b) = tokio::net::UnixStream::pair().unwrap(); |
| 785 | let mut worker = IpcConnection::new(a); |
| 786 | let mut sup = IpcConnection::new(b); |
| 787 | let w = tokio::spawn(async move { |
| 788 | let reply = worker.perform_worker_handshake("gen-1", 7, SECRET).await; |
| 789 | (worker, reply) |
| 790 | }); |
| 791 | let state = |
| 792 | authenticate_worker_connection(&mut sup, "gen-1", SECRET, Duration::from_secs(5)) |
| 793 | .await |
| 794 | .unwrap(); |
| 795 | assert!(state.can_execute_for("gen-1")); |
| 796 | let (_worker, reply) = w.await.unwrap(); |
| 797 | assert_eq!(reply.unwrap(), SupervisorMessage::Ping); |
| 798 | } |
| 799 | |
| 800 | #[tokio::test] |
| 801 | async fn unauthenticated_and_wrong_generation_messages_are_rejected_without_rollback() { |
| 802 | let tmp = tempfile::tempdir().unwrap(); |
| 803 | let rsi_root = tmp.path().join(".rsi"); |
| 804 | let active_link = rsi_root.join("active.sock"); |
| 805 | let daemon = daemon_with_canary(tmp.path(), "gen-002", 1_000_000).await; |
| 806 | |
| 807 | // Open a real observation log so the rejection is recorded in it. |
| 808 | let log_path = rsi_root.join("canary/observations/gen-002.jsonl"); |
| 809 | let header = LogHeader::new( |
| 810 | "gen-002", |
| 811 | &crate::canary::sha256_hex(b"workload"), |
| 812 | &crate::canary::sha256_hex(b"exe"), |
| 813 | 1, |
| 814 | ); |
| 815 | daemon |
| 816 | .attach_observation_log(ObservationLogWriter::create(&log_path, header).unwrap()) |
| 817 | .await; |
| 818 | |
| 819 | // 1. A CanaryReport on a connection that never authenticated. |
| 820 | let (_a, b) = tokio::net::UnixStream::pair().unwrap(); |
| 821 | let mut conn = IpcConnection::new(b); |
| 822 | let mut unauth = Auth::Unauthenticated; |
| 823 | let err = daemon |
| 824 | .process_worker_message( |
| 825 | &mut conn, |
| 826 | &mut unauth, |
| 827 | report("gen-002", 1, true, 10), |
| 828 | &active_link, |
| 829 | ) |
| 830 | .await |
| 831 | .unwrap_err(); |
| 832 | assert!(err.contains("unauthenticated"), "{}", err); |
| 833 | |
| 834 | // 2. An authenticated connection naming another generation. |
| 835 | let (mut conn_sup, mut auth, _worker) = |
| 836 | authenticated(&daemon, "gen-002", &active_link).await; |
| 837 | let err = daemon |
| 838 | .process_worker_message( |
| 839 | &mut conn_sup, |
| 840 | &mut auth, |
| 841 | report("gen-parent", 2, true, 10), |
| 842 | &active_link, |
| 843 | ) |
| 844 | .await |
| 845 | .unwrap_err(); |
| 846 | assert!(err.contains("naming generation gen-parent"), "{}", err); |
| 847 | |
| 848 | // 3. A repeated Ready. |
| 849 | let err = daemon |
| 850 | .process_worker_message( |
| 851 | &mut conn_sup, |
| 852 | &mut auth, |
| 853 | WorkerMessage::Ready { |
| 854 | generation_id: "gen-002".to_string(), |
| 855 | pid: 1, |
| 856 | auth_token: String::new(), |
| 857 | protocol_version: CANARY_PROTOCOL_VERSION, |
| 858 | }, |
| 859 | &active_link, |
| 860 | ) |
| 861 | .await |
| 862 | .unwrap_err(); |
| 863 | assert!(err.contains("repeated Ready"), "{}", err); |
| 864 | |
| 865 | // No rollback: the canary is still Ready, not Reverted, and active.sock untouched. |
| 866 | let state = daemon |
| 867 | .canary_generation |
| 868 | .lock() |
| 869 | .await |
| 870 | .as_ref() |
| 871 | .unwrap() |
| 872 | .state; |
| 873 | assert_eq!(state, GenerationState::Ready); |
| 874 | assert!(std::fs::symlink_metadata(&active_link).is_err()); |
| 875 | |
| 876 | // The rejections are in the log; no observation exists. |
| 877 | let writer = daemon.detach_observation_log().await.unwrap(); |
| 878 | assert_eq!(writer.stored_count(), 0); |
| 879 | let sealed = writer.seal(2).unwrap(); |
| 880 | assert_eq!(sealed.rejections.len(), 3); |
| 881 | assert!(sealed.observations.is_empty()); |
| 882 | } |
| 883 | |
| 884 | #[tokio::test] |
| 885 | async fn self_reports_never_reach_durable_however_many_arrive() { |
| 886 | let tmp = tempfile::tempdir().unwrap(); |
| 887 | let rsi_root = tmp.path().join(".rsi"); |
| 888 | let active_link = rsi_root.join("active.sock"); |
| 889 | let daemon = daemon_with_canary(tmp.path(), "gen-002", 1_000_000).await; |
| 890 | |
| 891 | let src_parent = tmp.path().join("art_parent"); |
| 892 | std::fs::create_dir_all(&src_parent).unwrap(); |
| 893 | let parent = daemon |
| 894 | .supervisor |
| 895 | .stage_generation("gen-001", &src_parent, "sha-parent") |
| 896 | .unwrap(); |
| 897 | *daemon.active_generation.lock().await = Some(parent); |
| 898 | |
| 899 | let (mut conn, mut auth, _worker) = authenticated(&daemon, "gen-002", &active_link).await; |
| 900 | for i in 1..=25 { |
| 901 | let reply = daemon |
| 902 | .process_worker_message( |
| 903 | &mut conn, |
| 904 | &mut auth, |
| 905 | report("gen-002", i, true, 10), |
| 906 | &active_link, |
| 907 | ) |
| 908 | .await |
| 909 | .unwrap(); |
| 910 | assert_eq!(reply, None, "a self-report earns no reply and no drain"); |
| 911 | } |
| 912 | // A replayed transaction id changes nothing either. |
| 913 | let reply = daemon |
| 914 | .process_worker_message( |
| 915 | &mut conn, |
| 916 | &mut auth, |
| 917 | report("gen-002", 1, true, 10), |
| 918 | &active_link, |
| 919 | ) |
| 920 | .await |
| 921 | .unwrap(); |
| 922 | assert_eq!(reply, None); |
| 923 | // DrainComplete is not a promotion request. |
| 924 | let reply = daemon |
| 925 | .process_worker_message( |
| 926 | &mut conn, |
| 927 | &mut auth, |
| 928 | WorkerMessage::DrainComplete { |
| 929 | generation_id: "gen-002".to_string(), |
| 930 | }, |
| 931 | &active_link, |
| 932 | ) |
| 933 | .await |
| 934 | .unwrap(); |
| 935 | assert_eq!(reply, None); |
| 936 | |
| 937 | let canary_state = daemon |
| 938 | .canary_generation |
| 939 | .lock() |
| 940 | .await |
| 941 | .as_ref() |
| 942 | .unwrap() |
| 943 | .state; |
| 944 | assert_eq!(canary_state, GenerationState::CanaryActive); |
| 945 | let active = daemon.active_generation.lock().await; |
| 946 | assert_eq!(active.as_ref().unwrap().generation_id, "gen-001"); |
| 947 | assert!(std::fs::symlink_metadata(&active_link).is_err()); |
| 948 | } |
| 949 | |
| 950 | #[tokio::test] |
| 951 | async fn reported_latency_violation_still_triggers_the_early_revert() { |
| 952 | let tmp = tempfile::tempdir().unwrap(); |
| 953 | let active_link = tmp.path().join(".rsi").join("active.sock"); |
| 954 | let daemon = daemon_with_canary(tmp.path(), "gen-slow", 50_000).await; |
| 955 | let (mut conn, mut auth, _worker) = authenticated(&daemon, "gen-slow", &active_link).await; |
| 956 | |
| 957 | let reply = daemon |
| 958 | .process_worker_message( |
| 959 | &mut conn, |
| 960 | &mut auth, |
| 961 | report("gen-slow", 1, true, 75_000), |
| 962 | &active_link, |
| 963 | ) |
| 964 | .await |
| 965 | .unwrap(); |
| 966 | match reply { |
| 967 | Some(SupervisorMessage::RevertOrder { reason }) => { |
| 968 | assert!(reason.contains("Latency budget exceeded"), "{}", reason); |
| 969 | } |
| 970 | other => panic!("Expected RevertOrder for latency budget, got {:?}", other), |
| 971 | } |
| 972 | } |
| 973 | |
| 974 | #[tokio::test] |
| 975 | async fn reported_failure_triggers_instant_rollback_to_the_parent() { |
| 976 | let tmp = tempfile::tempdir().unwrap(); |
| 977 | let rsi_root = tmp.path().join(".rsi"); |
| 978 | let active_link = rsi_root.join("active.sock"); |
| 979 | let daemon = daemon_with_canary(tmp.path(), "gen-canary", 1_000_000).await; |
| 980 | |
| 981 | let src_parent = tmp.path().join("art_parent"); |
| 982 | std::fs::create_dir_all(&src_parent).unwrap(); |
| 983 | let parent = daemon |
| 984 | .supervisor |
| 985 | .stage_generation("gen-parent", &src_parent, "sha-parent") |
| 986 | .unwrap(); |
| 987 | daemon.supervisor.atomic_symlink_swap("gen-parent").unwrap(); |
| 988 | *daemon.active_generation.lock().await = Some(parent); |
| 989 | |
| 990 | let (mut conn, mut auth, _worker) = |
| 991 | authenticated(&daemon, "gen-canary", &active_link).await; |
| 992 | let reply = daemon |
| 993 | .process_worker_message( |
| 994 | &mut conn, |
| 995 | &mut auth, |
| 996 | report("gen-canary", 1, false, 9999), |
| 997 | &active_link, |
| 998 | ) |
| 999 | .await |
| 1000 | .unwrap(); |
| 1001 | match reply { |
| 1002 | Some(SupervisorMessage::RevertOrder { reason }) => { |
| 1003 | assert!( |
| 1004 | reason.contains("Inference assertion panicked"), |
| 1005 | "{}", |
| 1006 | reason |
| 1007 | ); |
| 1008 | } |
| 1009 | _ => panic!("Expected RevertOrder"), |
| 1010 | } |
| 1011 | let state = daemon |
| 1012 | .canary_generation |
| 1013 | .lock() |
| 1014 | .await |
| 1015 | .as_ref() |
| 1016 | .unwrap() |
| 1017 | .state; |
| 1018 | assert_eq!(state, GenerationState::Reverted); |
| 1019 | } |
| 1020 | |
| 1021 | #[tokio::test] |
| 1022 | async fn unreadable_memory_budget_reverts_the_canary() { |
| 1023 | let tmp = tempfile::tempdir().unwrap(); |
| 1024 | let active_link = tmp.path().join(".rsi").join("active.sock"); |
| 1025 | let daemon = daemon_with_canary(tmp.path(), "gen-mem", 1_000_000).await; |
| 1026 | let (mut conn, mut auth, _worker) = authenticated(&daemon, "gen-mem", &active_link).await; |
| 1027 | // Point the generation at a pid that has no /proc entry, so the |
| 1028 | // memory read fails. A failed read must revert, never pass. |
| 1029 | let pid = 4_000_000_000u32; |
| 1030 | daemon.canary_generation.lock().await.as_mut().unwrap().pid = Some(pid); |
| 1031 | |
| 1032 | let reply = daemon |
| 1033 | .process_worker_message( |
| 1034 | &mut conn, |
| 1035 | &mut auth, |
| 1036 | report("gen-mem", 1, true, 10), |
| 1037 | &active_link, |
| 1038 | ) |
| 1039 | .await |
| 1040 | .unwrap(); |
| 1041 | match reply { |
| 1042 | Some(SupervisorMessage::RevertOrder { reason }) => { |
| 1043 | assert!(reason.contains("unreadable"), "{}", reason); |
| 1044 | } |
| 1045 | other => panic!("Expected RevertOrder, got {:?}", other), |
| 1046 | } |
| 1047 | } |
| 1048 | } |