aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-runtime / src / server.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 | //! Local UNIX domain socket server for AienRuntimeSpine |
| 17 | //! Exposes typed control RPC over local IPC to operator CLI tools. |
| 18 | |
| 19 | use crate::compose::{compose_dir_from_env, ComposeBridge, ComposeProposer}; |
| 20 | use crate::control::{ControlCommand, ControlEnvelope, ControlResponse}; |
| 21 | use crate::generation::{DaemonStart, ModelIdentity, TurnEvidence}; |
| 22 | use crate::spine::AienRuntimeSpine; |
| 23 | use aien_inference_abi::{AienInferenceBackend, ChatTokenizer, SamplingParams}; |
| 24 | use aien_scheduler::{ChannelCompletionSink, CompletionEvent}; |
| 25 | use std::path::{Path, PathBuf}; |
| 26 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 27 | use std::sync::{Arc, RwLock}; |
| 28 | use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; |
| 29 | use tokio::net::{UnixListener, UnixStream}; |
| 30 | use tokio::sync::{Mutex, Notify}; |
| 31 | |
| 32 | /// True when the process on the other end of `stream` runs as this process's |
| 33 | /// effective user. The default socket lives in shared /tmp, so both ends check |
| 34 | /// peer credentials instead of trusting whoever created the path. |
| 35 | pub(crate) fn peer_is_current_user(stream: &UnixStream) -> bool { |
| 36 | // SAFETY: geteuid has no preconditions and cannot fail. |
| 37 | let euid = unsafe { libc::geteuid() }; |
| 38 | stream.peer_cred().map(|c| c.uid() == euid).unwrap_or(false) |
| 39 | } |
| 40 | |
| 41 | /// The persistent-KV counters of the `AIEN_STEP_LOG=1` step line, under their |
| 42 | /// METRICS_AND_SETTINGS names (cut C7). |
| 43 | pub fn kv_step_log_fields(s: &crate::kv_residency::KvResidencyStatus) -> String { |
| 44 | let t = &s.stats; |
| 45 | format!( |
| 46 | "kv_park_jobs_total={} kv_park_failed_total={} kv_park_dedup_total={} \ |
| 47 | kv_park_indeterminate_total={} kv_restore_jobs_total={} kv_restore_failed_total={} \ |
| 48 | kv_restore_fallback_prefill_total={} kv_restore_retry_suppressed_total={} \ |
| 49 | kv_store_stale_completions_total={} kv_pool_holder_blocks={} kv_restore_inflight_blocks={}", |
| 50 | t.park_jobs_total, |
| 51 | t.park_failed_total, |
| 52 | t.park_dedup_total, |
| 53 | t.park_indeterminate_total, |
| 54 | t.restore_jobs_total, |
| 55 | t.restore_failed_total, |
| 56 | t.restore_fallback_prefill_total, |
| 57 | t.restore_retry_suppressed_total, |
| 58 | t.store_stale_completions_total, |
| 59 | s.holder_blocks, |
| 60 | s.restore_inflight_blocks, |
| 61 | ) |
| 62 | } |
| 63 | |
| 64 | /// The shutdown log line of the persistent-KV drain (ADR 7.5): the counters |
| 65 | /// `kv_store_shutdown_unfinished_jobs` and `kv_shutdown_unfinished_bytes`, then |
| 66 | /// every unfinished job by key, size and stage. |
| 67 | pub fn kv_shutdown_log_line(r: &aien_kv_store::DrainReport) -> String { |
| 68 | let bytes: u64 = r.unfinished.iter().map(|u| u.bytes).sum(); |
| 69 | let mut line = format!( |
| 70 | "persistent KV drain: published={} cancelled={} kv_store_shutdown_unfinished_jobs={} kv_shutdown_unfinished_bytes={}", |
| 71 | r.published, |
| 72 | r.cancelled, |
| 73 | r.unfinished.len(), |
| 74 | bytes |
| 75 | ); |
| 76 | for u in &r.unfinished { |
| 77 | let key: String = u.key.0 .0.iter().map(|b| format!("{b:02x}")).collect(); |
| 78 | line.push_str(&format!( |
| 79 | "\n unfinished job {} key {key} bytes {} stage {:?}", |
| 80 | u.job.0, u.bytes, u.stage |
| 81 | )); |
| 82 | } |
| 83 | line |
| 84 | } |
| 85 | |
| 86 | pub struct AienRuntimeServer { |
| 87 | socket_path: PathBuf, |
| 88 | spine: Arc<Mutex<AienRuntimeSpine>>, |
| 89 | shutdown_notify: Arc<Notify>, |
| 90 | is_running: Arc<AtomicBool>, |
| 91 | tokenizer: Arc<RwLock<Option<ChatTokenizer>>>, |
| 92 | warm_up: AtomicBool, |
| 93 | /// Optional serving-time probe (GB10 allocation counters), see `set_serving_probe`. |
| 94 | probe: std::sync::Mutex<Option<Arc<dyn aien_inference_abi::gb10_serving::ServingProbe>>>, |
| 95 | /// Test seam: a ready-made compose bridge (see `with_compose_bridge`). |
| 96 | compose_override: std::sync::Mutex<Option<Arc<ComposeBridge>>>, |
| 97 | /// The loaded model files' digests (set by the daemon after load; absent |
| 98 | /// = no generation record, see crate::generation). |
| 99 | identity: std::sync::Mutex<Option<Arc<ModelIdentity>>>, |
| 100 | started: DaemonStart, |
| 101 | /// Headstart M3 (#537): the provisional preparation adapter whose fence |
| 102 | /// bound compose commit requests pass (see `with_prep_adapter`). |
| 103 | #[cfg(feature = "provisional-prep")] |
| 104 | prep: std::sync::Mutex<Option<Arc<crate::provisional::PrepAdapter>>>, |
| 105 | } |
| 106 | |
| 107 | /// NEXT-PHASE-1 v4 declared warm-up prompt (ACCEPTANCE-v4 Section 2(2)): |
| 108 | /// fixed text, more than one 128-token prefill chunk once templated, so |
| 109 | /// both the full-chunk and the remainder prefill paths run before serving. |
| 110 | /// Log line when the warm-up is skipped for a plain model (no chat template). |
| 111 | pub const WARM_UP_SKIPPED_PLAIN: &str = "Warm-up: skipped (plain model, no chat template)"; |
| 112 | |
| 113 | pub const WARM_UP_TEXT: &str = "Warm-up turn before serving requests. This text is fixed and its one generated token is discarded. \ |
| 114 | Warm-up turn before serving requests. This text is fixed and its one generated token is discarded. \ |
| 115 | Warm-up turn before serving requests. This text is fixed and its one generated token is discarded. \ |
| 116 | Warm-up turn before serving requests. This text is fixed and its one generated token is discarded. \ |
| 117 | Warm-up turn before serving requests. This text is fixed and its one generated token is discarded. \ |
| 118 | Warm-up turn before serving requests. This text is fixed and its one generated token is discarded."; |
| 119 | |
| 120 | impl AienRuntimeServer { |
| 121 | pub fn new(spine: AienRuntimeSpine, socket_path: impl AsRef<Path>) -> Self { |
| 122 | Self { |
| 123 | socket_path: socket_path.as_ref().to_path_buf(), |
| 124 | spine: Arc::new(Mutex::new(spine)), |
| 125 | shutdown_notify: Arc::new(Notify::new()), |
| 126 | is_running: Arc::new(AtomicBool::new(false)), |
| 127 | tokenizer: Arc::new(RwLock::new(None)), |
| 128 | warm_up: AtomicBool::new(false), |
| 129 | probe: std::sync::Mutex::new(None), |
| 130 | compose_override: std::sync::Mutex::new(None), |
| 131 | identity: std::sync::Mutex::new(None), |
| 132 | started: DaemonStart::now(), |
| 133 | #[cfg(feature = "provisional-prep")] |
| 134 | prep: std::sync::Mutex::new(None), |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | /// Headstart M3 (#537): send `ComposeApprovedProposal` and |
| 139 | /// `ComposeAuthorize` requests that `adapter` has bound |
| 140 | /// (`PrepAdapter::bind_approval`) through its final commit fence. Unbound |
| 141 | /// requests run the original call unchanged. Without this call (the |
| 142 | /// default) nothing is fenced. |
| 143 | #[cfg(feature = "provisional-prep")] |
| 144 | pub fn with_prep_adapter(self, adapter: Arc<crate::provisional::PrepAdapter>) -> Self { |
| 145 | *self.prep.lock().expect("prep adapter") = Some(adapter); |
| 146 | self |
| 147 | } |
| 148 | |
| 149 | /// Test seam: serve compose commands from `bridge` (for example one with a |
| 150 | /// fixed proposer) instead of the bridge built from the environment and |
| 151 | /// the loaded model. The daemon binary never calls this. |
| 152 | #[doc(hidden)] |
| 153 | #[cfg(feature = "test-support")] |
| 154 | pub fn with_compose_bridge(self, bridge: Arc<ComposeBridge>) -> Self { |
| 155 | *self.compose_override.lock().expect("compose override") = Some(bridge); |
| 156 | self |
| 157 | } |
| 158 | |
| 159 | /// Installs the digests of the model and tokenizer files the daemon loaded. |
| 160 | /// Without them (stub or reference weights) no generation record is written. |
| 161 | pub fn set_model_identity(&self, identity: ModelIdentity) { |
| 162 | *self.identity.lock().expect("identity lock") = Some(Arc::new(identity)); |
| 163 | } |
| 164 | |
| 165 | /// Installs the tokenizer that `StreamTurn` uses to encode prompts and decode tokens. |
| 166 | pub fn set_tokenizer(&self, tokenizer: ChatTokenizer) { |
| 167 | *self.tokenizer.write().expect("tokenizer lock") = Some(tokenizer); |
| 168 | } |
| 169 | |
| 170 | /// Run the declared warm-up turn (1 token, discarded) at the start of |
| 171 | /// `run`, before any request is served (ACCEPTANCE-v4 Section 2(2)). |
| 172 | pub fn enable_warm_up(&self) { |
| 173 | self.warm_up.store(true, Ordering::SeqCst); |
| 174 | } |
| 175 | |
| 176 | /// Log the GB10 allocation counters once after warm-up and the change since warm-up after |
| 177 | /// every served connection (sovereign-core#277). Unset = nothing is logged. |
| 178 | pub fn set_serving_probe( |
| 179 | &self, |
| 180 | probe: Arc<dyn aien_inference_abi::gb10_serving::ServingProbe>, |
| 181 | ) { |
| 182 | *self.probe.lock().expect("probe lock") = Some(probe); |
| 183 | } |
| 184 | |
| 185 | pub fn spine(&self) -> Arc<Mutex<AienRuntimeSpine>> { |
| 186 | self.spine.clone() |
| 187 | } |
| 188 | |
| 189 | pub fn socket_path(&self) -> &Path { |
| 190 | &self.socket_path |
| 191 | } |
| 192 | |
| 193 | /// Runs the runtime server, accepting control connections and advancing the engine step loop. |
| 194 | pub async fn run<B: AienInferenceBackend + Send + 'static>( |
| 195 | &self, |
| 196 | mut backend: B, |
| 197 | ) -> Result<(), String> { |
| 198 | // Clean up stale socket file if it exists and refuses connection |
| 199 | if self.socket_path.exists() { |
| 200 | if UnixStream::connect(&self.socket_path).await.is_err() { |
| 201 | let _ = std::fs::remove_file(&self.socket_path); |
| 202 | } else { |
| 203 | return Err(format!( |
| 204 | "Runtime socket already active at {}", |
| 205 | self.socket_path.display() |
| 206 | )); |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | if let Some(parent) = self.socket_path.parent() { |
| 211 | if !parent.exists() { |
| 212 | let _ = std::fs::create_dir_all(parent); |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | // Bad compose limits stop the daemon here, loudly, before anything is served. |
| 217 | crate::compose::compose_budgets_from_env().map_err(|e| format!("compose limits: {e}"))?; |
| 218 | crate::compose::compose_doc_max_tokens_from_env() |
| 219 | .map_err(|e| format!("compose limits: {e}"))?; |
| 220 | |
| 221 | let authorize_desk = crate::compose::authorize_requires_desk_from_env()?; |
| 222 | // sc#328: a bridge that requires the approval desk refuses to start |
| 223 | // without a loadable desk key, before the socket exists. A bridge with |
| 224 | // the desk off (code that embeds the runtime) is the same dev-only |
| 225 | // opt-out as the env switch: a strict run refuses it. |
| 226 | let desk_home = match self |
| 227 | .compose_override |
| 228 | .lock() |
| 229 | .expect("compose override") |
| 230 | .as_ref() |
| 231 | { |
| 232 | Some(b) if !b.authorize_requires_desk() => { |
| 233 | crate::compose::authorize_desk_setting( |
| 234 | Some("0"), |
| 235 | aien_inference_abi::strict::dev_fallback_active(), |
| 236 | ) |
| 237 | .map_err(|e| format!("compose bridge built with the approval desk off: {e}"))?; |
| 238 | None |
| 239 | } |
| 240 | Some(b) => Some(b.dir().to_path_buf()), |
| 241 | None if authorize_desk => compose_dir_from_env().ok(), |
| 242 | None => None, |
| 243 | }; |
| 244 | if let Some(dir) = desk_home { |
| 245 | crate::compose::check_desk_key_at_start(&dir)?; |
| 246 | } |
| 247 | let listener = UnixListener::bind(&self.socket_path).map_err(|e| { |
| 248 | format!( |
| 249 | "Failed to bind runtime UNIX domain socket at {}: {}", |
| 250 | self.socket_path.display(), |
| 251 | e |
| 252 | ) |
| 253 | })?; |
| 254 | { |
| 255 | use std::os::unix::fs::PermissionsExt; |
| 256 | std::fs::set_permissions(&self.socket_path, std::fs::Permissions::from_mode(0o600)) |
| 257 | .map_err(|e| { |
| 258 | format!( |
| 259 | "Failed to restrict runtime socket {} to owner: {}", |
| 260 | self.socket_path.display(), |
| 261 | e |
| 262 | ) |
| 263 | })?; |
| 264 | } |
| 265 | |
| 266 | self.is_running.store(true, Ordering::SeqCst); |
| 267 | |
| 268 | // Background worker advancing engine steps whenever requests are active |
| 269 | let spine_worker = self.spine.clone(); |
| 270 | let is_running_worker = self.is_running.clone(); |
| 271 | let shutdown_notify_worker = self.shutdown_notify.clone(); |
| 272 | |
| 273 | let step_log = std::env::var("AIEN_STEP_LOG").is_ok_and(|v| v == "1"); |
| 274 | let worker_handle = tokio::spawn(async move { |
| 275 | while is_running_worker.load(Ordering::Relaxed) { |
| 276 | let has_work = { |
| 277 | let s = spine_worker.lock().await; |
| 278 | s.scheduler.running_count() > 0 || s.scheduler.waiting_count() > 0 |
| 279 | }; |
| 280 | |
| 281 | if has_work { |
| 282 | let mut s = spine_worker.lock().await; |
| 283 | let t_step = std::time::Instant::now(); |
| 284 | match s.step(&mut backend).await { |
| 285 | // NEXT-PHASE-1 v3 observation: one line per engine step |
| 286 | // (AIEN_STEP_LOG=1) from the metrics the step already reports. |
| 287 | // Persistent-KV counters are appended when it is on (C7). |
| 288 | Ok(Some(m)) if step_log => eprintln!( |
| 289 | "step: prefill_tokens={} emitted={} backend_us={} spine_us={}{}", |
| 290 | m.prefill_tokens_processed, |
| 291 | m.decode_tokens_emitted, |
| 292 | m.step_latency_us, |
| 293 | t_step.elapsed().as_micros(), |
| 294 | s.kv_residency_status() |
| 295 | .map(|k| format!(" {}", kv_step_log_fields(&k))) |
| 296 | .unwrap_or_default() |
| 297 | ), |
| 298 | Ok(_) => {} |
| 299 | // A swallowed step error makes the daemon look alive |
| 300 | // while its decode loop is dead. Print it. |
| 301 | Err(e) => eprintln!("runtime step error: {}", e), |
| 302 | } |
| 303 | } else { |
| 304 | tokio::select! { |
| 305 | _ = tokio::time::sleep(tokio::time::Duration::from_millis(5)) => {}, |
| 306 | _ = shutdown_notify_worker.notified() => break, |
| 307 | } |
| 308 | } |
| 309 | } |
| 310 | }); |
| 311 | |
| 312 | // NEXT-PHASE-1 v4: the declared warm-up, before the accept loop |
| 313 | // serves anything (clients that connect meanwhile wait in the backlog). |
| 314 | if self.warm_up.load(Ordering::SeqCst) { |
| 315 | println!(" {}", self.run_warm_up().await); |
| 316 | } |
| 317 | let probe = self.probe.lock().expect("probe lock").clone(); |
| 318 | if let Some(line) = probe.as_ref().and_then(|p| p.after_warm_up()) { |
| 319 | println!(" {line}"); |
| 320 | } |
| 321 | |
| 322 | // NEXT-PHASE-1: the compose bridge (opened on the first RunComposeTask). |
| 323 | let preset = self |
| 324 | .compose_override |
| 325 | .lock() |
| 326 | .expect("compose override") |
| 327 | .clone(); |
| 328 | let identity = self.identity.lock().expect("identity lock").clone(); |
| 329 | #[cfg(feature = "provisional-prep")] |
| 330 | let prep = self.prep.lock().expect("prep adapter").clone(); |
| 331 | // Correlation trace exporter (#398): on only when AIEN_TRACE_JSONL names |
| 332 | // a file. Off, the bridge keeps a NullSink and emits nothing. The flusher |
| 333 | // handle lives until the end of `run`, after the compose home closes, |
| 334 | // so the last events are written at shutdown. |
| 335 | let (trace_sink, _trace_flusher) = trace_sink_from_env(); |
| 336 | let compose = match compose_dir_from_env() { |
| 337 | _ if preset.is_some() => preset, |
| 338 | Ok(dir) => Some(Arc::new( |
| 339 | ComposeBridge::new( |
| 340 | dir, |
| 341 | model_proposer( |
| 342 | self.spine.clone(), |
| 343 | self.tokenizer.clone(), |
| 344 | tokio::runtime::Handle::current(), |
| 345 | ), |
| 346 | "model:StreamTurn-path", |
| 347 | ) |
| 348 | .with_doc_proposer(doc_model_proposer( |
| 349 | self.spine.clone(), |
| 350 | self.tokenizer.clone(), |
| 351 | tokio::runtime::Handle::current(), |
| 352 | )?) |
| 353 | .with_authorize_requires_desk(authorize_desk) |
| 354 | .with_trace_sink(trace_sink), |
| 355 | )), |
| 356 | Err(e) => { |
| 357 | tracing::warn!("compose bridge disabled: {e}"); |
| 358 | None |
| 359 | } |
| 360 | }; |
| 361 | // Provenance (arch#162): the compose task writes the generation record of |
| 362 | // the proposal it commits, so the bridge needs the model identity too. |
| 363 | if let (Some(b), Some(id)) = (compose.as_ref(), identity.as_ref()) { |
| 364 | b.set_model_identity((**id).clone(), self.started); |
| 365 | } |
| 366 | // NEXT-PHASE-2 (ACCEPTANCE-v2 2.4): settle effects a previous process |
| 367 | // left open, before serving anything. Reads the world, never re-runs. |
| 368 | // A failed or refused reconcile does not stop the daemon, but every |
| 369 | // effect command refuses until an operator reconcile succeeds |
| 370 | // (ACCEPTANCE-v3 2.5). |
| 371 | if let Some(b) = compose.as_ref() { |
| 372 | let line = crate::compose::authorize_mac_line(b.authorize_requires_desk()); |
| 373 | println!("{line}"); |
| 374 | if !b.authorize_requires_desk() { |
| 375 | tracing::warn!("{line}"); |
| 376 | } |
| 377 | if aien_omega_compose::LINKED { |
| 378 | println!( |
| 379 | "Compose: native (omega {})", |
| 380 | aien_omega_compose::EXPECTED_OMEGA_SHA |
| 381 | ); |
| 382 | } else { |
| 383 | println!("Compose: STUB (every compose call is Unavailable)"); |
| 384 | } |
| 385 | } |
| 386 | if let Some(b) = compose.clone() { |
| 387 | let gate = b.clone(); |
| 388 | let line = |
| 389 | match tokio::task::spawn_blocking(move || crate::effects::reconcile_at_start(&b)) |
| 390 | .await |
| 391 | { |
| 392 | Ok(line) => line, |
| 393 | Err(e) => { |
| 394 | gate.set_reconcile_failed(format!("failed: {e}")); |
| 395 | format!( |
| 396 | "Reconcile: failed: {e}; {}", |
| 397 | crate::effects::RECONCILE_GATE_NOTE |
| 398 | ) |
| 399 | } |
| 400 | }; |
| 401 | println!("{line}"); |
| 402 | // sovereign-core #249: settle approved-proposal claims a previous |
| 403 | // process left open (never re-run). A failure gates effect commands |
| 404 | // and approved proposals like a failed effect reconcile. |
| 405 | let b = compose.clone().expect("compose is Some here"); |
| 406 | let gate = b.clone(); |
| 407 | let line = match tokio::task::spawn_blocking(move || { |
| 408 | crate::approved_replay::reconcile_at_start(&b) |
| 409 | }) |
| 410 | .await |
| 411 | { |
| 412 | Ok(Ok(line)) => line, |
| 413 | Ok(Err(e)) => { |
| 414 | gate.set_reconcile_failed(format!("replay reconcile refused: {e}")); |
| 415 | format!( |
| 416 | "Replay reconcile: refused: {e}; {}", |
| 417 | crate::effects::RECONCILE_GATE_NOTE |
| 418 | ) |
| 419 | } |
| 420 | Err(e) => { |
| 421 | gate.set_reconcile_failed(format!("replay reconcile failed: {e}")); |
| 422 | format!( |
| 423 | "Replay reconcile: failed: {e}; {}", |
| 424 | crate::effects::RECONCILE_GATE_NOTE |
| 425 | ) |
| 426 | } |
| 427 | }; |
| 428 | println!("{line}"); |
| 429 | } |
| 430 | |
| 431 | // Connection accept loop |
| 432 | loop { |
| 433 | tokio::select! { |
| 434 | accept_res = listener.accept() => { |
| 435 | match accept_res { |
| 436 | Ok((stream, _)) => { |
| 437 | if !peer_is_current_user(&stream) { |
| 438 | tracing::warn!("rejected runtime connection from another user"); |
| 439 | continue; |
| 440 | } |
| 441 | let spine_conn = self.spine.clone(); |
| 442 | let is_running_conn = self.is_running.clone(); |
| 443 | let notify_conn = self.shutdown_notify.clone(); |
| 444 | |
| 445 | let tokenizer_conn = self.tokenizer.clone(); |
| 446 | let compose_conn = compose.clone(); |
| 447 | let identity_conn = identity.clone(); |
| 448 | let started = self.started; |
| 449 | let probe_conn = probe.clone(); |
| 450 | #[cfg(feature = "provisional-prep")] |
| 451 | let prep_conn = prep.clone(); |
| 452 | tokio::spawn(async move { |
| 453 | #[cfg(not(feature = "provisional-prep"))] |
| 454 | handle_connection( |
| 455 | stream, |
| 456 | spine_conn, |
| 457 | is_running_conn, |
| 458 | notify_conn, |
| 459 | tokenizer_conn, |
| 460 | compose_conn, |
| 461 | (identity_conn, started), |
| 462 | ) |
| 463 | .await; |
| 464 | #[cfg(feature = "provisional-prep")] |
| 465 | handle_connection( |
| 466 | stream, |
| 467 | spine_conn, |
| 468 | is_running_conn, |
| 469 | notify_conn, |
| 470 | tokenizer_conn, |
| 471 | compose_conn, |
| 472 | (identity_conn, started), |
| 473 | prep_conn, |
| 474 | ) |
| 475 | .await; |
| 476 | if let Some(line) = probe_conn.as_ref().and_then(|p| p.after_request()) { |
| 477 | println!(" {line}"); |
| 478 | } |
| 479 | }); |
| 480 | } |
| 481 | Err(e) => { |
| 482 | tracing::warn!("Failed to accept runtime connection: {}", e); |
| 483 | } |
| 484 | } |
| 485 | } |
| 486 | _ = self.shutdown_notify.notified() => { |
| 487 | break; |
| 488 | } |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | self.is_running.store(false, Ordering::SeqCst); |
| 493 | let _ = worker_handle.await; |
| 494 | |
| 495 | // Persistent KV (ADR 7.5): drain the store with its deadline after the |
| 496 | // step loop stopped. The worker keeps every buffer of an unfinished job |
| 497 | // until its terminal; nothing is freed to meet the deadline. |
| 498 | let drain = self.spine.lock().await.kv_drain_handle(); |
| 499 | if let Some(handle) = drain { |
| 500 | if let Ok(report) = tokio::task::spawn_blocking(move || handle.drain()).await { |
| 501 | eprintln!("{}", kv_shutdown_log_line(&report)); |
| 502 | } |
| 503 | } |
| 504 | |
| 505 | // Close the compose home now, not whenever the last connection task drops |
| 506 | // its Arc (sovereign-core #306). |
| 507 | if let Some(c) = compose.clone() { |
| 508 | let _ = tokio::task::spawn_blocking(move || c.close()).await; |
| 509 | } |
| 510 | |
| 511 | // Clean up socket file on clean shutdown |
| 512 | if self.socket_path.exists() { |
| 513 | let _ = std::fs::remove_file(&self.socket_path); |
| 514 | } |
| 515 | |
| 516 | Ok(()) |
| 517 | } |
| 518 | } |
| 519 | |
| 520 | async fn write_response( |
| 521 | writer: &mut tokio::net::unix::OwnedWriteHalf, |
| 522 | response: &ControlResponse, |
| 523 | ) -> bool { |
| 524 | match serde_json::to_string(response) { |
| 525 | Ok(mut serialized) => { |
| 526 | serialized.push('\n'); |
| 527 | writer.write_all(serialized.as_bytes()).await.is_ok() |
| 528 | } |
| 529 | Err(_) => false, |
| 530 | } |
| 531 | } |
| 532 | |
| 533 | fn text_suffix(previous: &str, decoded: &str) -> String { |
| 534 | decoded.strip_prefix(previous).unwrap_or("").to_string() |
| 535 | } |
| 536 | |
| 537 | impl AienRuntimeServer { |
| 538 | /// One greedy 1-token turn on `WARM_UP_TEXT`; the token is discarded. |
| 539 | /// Returns the log line: `Warm-up: 1 token in <ms> ms over <n> prompt tokens (discarded)`, |
| 540 | /// `Warm-up: FAILED ...` (a failure does not stop the daemon), or [`WARM_UP_SKIPPED_PLAIN`] |
| 541 | /// when the loaded tokenizer has no chat template (a plain model refuses chat turns by |
| 542 | /// design, so the chat warm-up is not attempted). |
| 543 | pub async fn run_warm_up(&self) -> String { |
| 544 | if self |
| 545 | .tokenizer |
| 546 | .read() |
| 547 | .expect("tokenizer lock") |
| 548 | .as_ref() |
| 549 | .is_some_and(|t| matches!(t.template(), aien_inference_abi::ChatTemplate::None)) |
| 550 | { |
| 551 | return WARM_UP_SKIPPED_PLAIN.to_string(); |
| 552 | } |
| 553 | let messages = vec![crate::control::ChatTurn { |
| 554 | role: "user".into(), |
| 555 | content: WARM_UP_TEXT.into(), |
| 556 | }]; |
| 557 | let prompt_tokens = { |
| 558 | let guard = self.tokenizer.read().expect("tokenizer lock"); |
| 559 | guard.as_ref().and_then(|t| { |
| 560 | crate::control::try_format_chat(t.template(), &messages) |
| 561 | .ok() |
| 562 | .and_then(|text| t.encode(&text).ok()) |
| 563 | .map(|ids| ids.len()) |
| 564 | }) |
| 565 | }; |
| 566 | let t0 = std::time::Instant::now(); |
| 567 | let out = generate_text( |
| 568 | self.spine.clone(), |
| 569 | self.tokenizer.clone(), |
| 570 | messages, |
| 571 | 1, |
| 572 | 0.0, |
| 573 | std::time::Duration::from_secs(120), |
| 574 | "", |
| 575 | ) |
| 576 | .await; |
| 577 | let ms = t0.elapsed().as_millis(); |
| 578 | match out { |
| 579 | Ok(g) => format!( |
| 580 | "Warm-up: {} token in {ms} ms over {} prompt tokens (discarded)", |
| 581 | g.tokens, |
| 582 | prompt_tokens.unwrap_or(0) |
| 583 | ), |
| 584 | Err(e) => format!("Warm-up: FAILED after {ms} ms: {e}"), |
| 585 | } |
| 586 | } |
| 587 | } |
| 588 | |
| 589 | /// Encode the chat and submit it to the spine (the `StreamTurn` path). Returns |
| 590 | /// the tokenizer and the completion event stream of the submitted sequence. |
| 591 | async fn submit_turn( |
| 592 | spine: Arc<Mutex<AienRuntimeSpine>>, |
| 593 | tokenizer: Arc<RwLock<Option<ChatTokenizer>>>, |
| 594 | messages: Vec<crate::control::ChatTurn>, |
| 595 | max_tokens: usize, |
| 596 | temperature: f32, |
| 597 | assistant_prefix: &str, |
| 598 | ) -> Result< |
| 599 | ( |
| 600 | ChatTokenizer, |
| 601 | tokio::sync::mpsc::UnboundedReceiver<CompletionEvent>, |
| 602 | Vec<u32>, |
| 603 | ), |
| 604 | String, |
| 605 | > { |
| 606 | let tokenizer = { |
| 607 | let guard = tokenizer.read().expect("tokenizer lock"); |
| 608 | guard.clone() |
| 609 | }; |
| 610 | let Some(tokenizer) = tokenizer else { |
| 611 | return Err("tokenizer is not loaded; native chat cannot encode the prompt".into()); |
| 612 | }; |
| 613 | // The template ends with the assistant marker; an assistant-response |
| 614 | // prefix (compose Skill, ACCEPTANCE-v4 2(1)) follows it directly. The |
| 615 | // tokenizer adds the one BOS token. |
| 616 | let prompt = format!( |
| 617 | "{}{assistant_prefix}", |
| 618 | crate::control::try_format_chat(tokenizer.template(), &messages) |
| 619 | .map_err(|error| format!("{error}"))? |
| 620 | ); |
| 621 | let tokens = tokenizer |
| 622 | .encode(&prompt) |
| 623 | .map_err(|error| format!("tokenizer encode failed: {error}"))?; |
| 624 | let (sink, events) = ChannelCompletionSink::channel(); |
| 625 | let mut spine = spine.lock().await; |
| 626 | let sink_id = spine.register_completion_sink(std::sync::Arc::new(sink)); |
| 627 | let sampling = SamplingParams { |
| 628 | temperature, |
| 629 | top_p: 0.95, |
| 630 | max_tokens: max_tokens.max(1), |
| 631 | stop_token_ids: tokenizer.stop_token_ids().to_vec(), |
| 632 | }; |
| 633 | spine.submit_work( |
| 634 | std::sync::Arc::from(tokens.as_slice()), |
| 635 | sampling, |
| 636 | 2, |
| 637 | Some(sink_id), |
| 638 | )?; |
| 639 | Ok((tokenizer, events, tokens)) |
| 640 | } |
| 641 | |
| 642 | /// Receipt label of a finish reason (ACCEPTANCE-v5 Q3): the stop token |
| 643 | /// (end of sequence) is "eos", the token limit is "max_tokens". |
| 644 | pub fn finish_reason_label(reason: &aien_inference_abi::FinishReason) -> &'static str { |
| 645 | match reason { |
| 646 | aien_inference_abi::FinishReason::StopToken => "eos", |
| 647 | aien_inference_abi::FinishReason::LengthLimit => "max_tokens", |
| 648 | aien_inference_abi::FinishReason::Aborted => "aborted", |
| 649 | aien_inference_abi::FinishReason::Preempted => "preempted", |
| 650 | } |
| 651 | } |
| 652 | |
| 653 | /// A compose command, run on a blocking thread against the bridge. |
| 654 | type ComposeJob = Box<dyn FnOnce(&Arc<ComposeBridge>) -> ControlResponse + Send>; |
| 655 | |
| 656 | /// NEXT-PHASE-1: the whole turn as one string (no streaming) and its token |
| 657 | /// count, for the compose "model" Skill. Same submission path as |
| 658 | /// `StreamTurn`; fails after `limit`. |
| 659 | async fn generate_text( |
| 660 | spine: Arc<Mutex<AienRuntimeSpine>>, |
| 661 | tokenizer: Arc<RwLock<Option<ChatTokenizer>>>, |
| 662 | messages: Vec<crate::control::ChatTurn>, |
| 663 | max_tokens: usize, |
| 664 | temperature: f32, |
| 665 | limit: std::time::Duration, |
| 666 | assistant_prefix: &str, |
| 667 | ) -> Result<crate::compose::Generation, String> { |
| 668 | let (tokenizer, mut events, prompt_ids) = submit_turn( |
| 669 | spine, |
| 670 | tokenizer, |
| 671 | messages, |
| 672 | max_tokens, |
| 673 | temperature, |
| 674 | assistant_prefix, |
| 675 | ) |
| 676 | .await?; |
| 677 | let collect = async { |
| 678 | let mut produced = Vec::new(); |
| 679 | loop { |
| 680 | match events.recv().await { |
| 681 | Some(CompletionEvent::Token { token, .. }) => produced.push(token), |
| 682 | Some(CompletionEvent::Finished { |
| 683 | finish_reason, |
| 684 | decoding, |
| 685 | ops, |
| 686 | .. |
| 687 | }) => { |
| 688 | if let Some(line) = crate::generation::op_report_line(ops.as_ref()) { |
| 689 | eprintln!("{line}"); |
| 690 | } |
| 691 | return tokenizer |
| 692 | .decode_opts(&produced, true) |
| 693 | .map(|text| crate::compose::Generation { |
| 694 | text, |
| 695 | tokens: produced.len(), |
| 696 | finish_reason: Some(finish_reason_label(&finish_reason).to_string()), |
| 697 | token_ids: Some(produced.clone()), |
| 698 | prompt_tokens: Some(prompt_ids.len()), |
| 699 | prompt_ids_sha256: Some(crate::compose::token_ids_sha256(&prompt_ids)), |
| 700 | decoding: decoding.clone(), |
| 701 | ops: ops.clone(), |
| 702 | }) |
| 703 | .map_err(|e| format!("tokenizer decode failed: {e}")); |
| 704 | } |
| 705 | Some(CompletionEvent::Error { message, .. }) => return Err(message), |
| 706 | None => return Err("native runtime stopped before the turn finished".into()), |
| 707 | } |
| 708 | } |
| 709 | }; |
| 710 | tokio::time::timeout(limit, collect) |
| 711 | .await |
| 712 | .map_err(|_| crate::compose::wall_clock_reason(limit.as_millis()))? |
| 713 | } |
| 714 | |
| 715 | /// The compose "model" Skill: real inference through `generate_text`, run |
| 716 | /// from an omega World worker thread (not a tokio thread) via `block_on`. |
| 717 | /// Greedy, at most `AIEN_COMPOSE_MAX_TOKENS` (default 48) tokens per reply; |
| 718 | /// each call gets the limit `propose_task_checked` passes (what is left of |
| 719 | /// the task budget: 29 s for an edit, 120 s for a document; omega waits that |
| 720 | /// plus 1 s), so a slow model fails the Skill (no proposal) instead of failing the run. |
| 721 | pub fn model_proposer( |
| 722 | spine: Arc<Mutex<AienRuntimeSpine>>, |
| 723 | tokenizer: Arc<RwLock<Option<ChatTokenizer>>>, |
| 724 | handle: tokio::runtime::Handle, |
| 725 | ) -> ComposeProposer { |
| 726 | let max_tokens = std::env::var("AIEN_COMPOSE_MAX_TOKENS") |
| 727 | .ok() |
| 728 | .and_then(|v| v.trim().parse::<usize>().ok()) |
| 729 | .unwrap_or(48); |
| 730 | proposer_with_cap(spine, tokenizer, handle, max_tokens) |
| 731 | } |
| 732 | |
| 733 | /// The proposer for full-document tasks: the same inference path with its own |
| 734 | /// token cap, `AIEN_COMPOSE_DOC_MAX_TOKENS` (default 1024). A bad value is refused. |
| 735 | pub fn doc_model_proposer( |
| 736 | spine: Arc<Mutex<AienRuntimeSpine>>, |
| 737 | tokenizer: Arc<RwLock<Option<ChatTokenizer>>>, |
| 738 | handle: tokio::runtime::Handle, |
| 739 | ) -> Result<ComposeProposer, String> { |
| 740 | let cap = crate::compose::compose_doc_max_tokens_from_env()?; |
| 741 | Ok(proposer_with_cap(spine, tokenizer, handle, cap)) |
| 742 | } |
| 743 | |
| 744 | fn proposer_with_cap( |
| 745 | spine: Arc<Mutex<AienRuntimeSpine>>, |
| 746 | tokenizer: Arc<RwLock<Option<ChatTokenizer>>>, |
| 747 | handle: tokio::runtime::Handle, |
| 748 | max_tokens: usize, |
| 749 | ) -> ComposeProposer { |
| 750 | Arc::new(move |prompt: &str, limit: std::time::Duration| { |
| 751 | let messages = vec![crate::control::ChatTurn { |
| 752 | role: "user".into(), |
| 753 | content: prompt.to_string(), |
| 754 | }]; |
| 755 | // The assistant turn starts with the template's fixed prefix; the |
| 756 | // reply the parser reads is prefix + generated text (ACCEPTANCE-v4 2(1)). |
| 757 | let prefix = tokenizer |
| 758 | .read() |
| 759 | .expect("tokenizer lock") |
| 760 | .as_ref() |
| 761 | .map(|t| crate::compose::compose_assistant_prefix(&t.template())) |
| 762 | .unwrap_or(crate::compose::COMPOSE_ASSISTANT_PREFIX); |
| 763 | handle |
| 764 | .block_on(generate_text( |
| 765 | spine.clone(), |
| 766 | tokenizer.clone(), |
| 767 | messages, |
| 768 | max_tokens, |
| 769 | 0.0, |
| 770 | limit, |
| 771 | prefix, |
| 772 | )) |
| 773 | .map(|g| crate::compose::Generation { |
| 774 | text: format!("{prefix}{}", g.text), |
| 775 | ..g |
| 776 | }) |
| 777 | }) |
| 778 | } |
| 779 | |
| 780 | /// What a turn needs to write its generation record. |
| 781 | struct RecordCtx { |
| 782 | compose: Option<Arc<ComposeBridge>>, |
| 783 | identity: Option<Arc<ModelIdentity>>, |
| 784 | started: DaemonStart, |
| 785 | request_id: u64, |
| 786 | operation_id: u128, |
| 787 | } |
| 788 | |
| 789 | /// Owned inputs of one finished turn's generation record. |
| 790 | struct GenerationOwned { |
| 791 | prompt_ids: Vec<u32>, |
| 792 | output_ids: Vec<u32>, |
| 793 | text: String, |
| 794 | total_tokens: usize, |
| 795 | finish_reason: &'static str, |
| 796 | request_id: u64, |
| 797 | operation_id: u128, |
| 798 | decoding: Option<aien_abi_core::DecodeObservation>, |
| 799 | ops: Option<aien_abi_core::OpEvidence>, |
| 800 | } |
| 801 | |
| 802 | /// Write the daemon's generation record for a finished turn and return its |
| 803 | /// ledger id. `None` when there is no compose ledger or no model identity (a |
| 804 | /// stub or reference-weights run), or when the append failed; the failure is |
| 805 | /// logged and the turn still succeeds, but an id is returned only for a record |
| 806 | /// that was written. |
| 807 | async fn record_generation( |
| 808 | compose: Option<Arc<ComposeBridge>>, |
| 809 | identity: Option<Arc<ModelIdentity>>, |
| 810 | started: DaemonStart, |
| 811 | g: GenerationOwned, |
| 812 | ) -> Option<u64> { |
| 813 | let (bridge, identity) = (compose?, identity?); |
| 814 | let written = tokio::task::spawn_blocking(move || { |
| 815 | let record = crate::generation::build_record( |
| 816 | &identity, |
| 817 | &TurnEvidence { |
| 818 | prompt_ids: &g.prompt_ids, |
| 819 | output_ids: &g.output_ids, |
| 820 | text: &g.text, |
| 821 | total_tokens: g.total_tokens, |
| 822 | finish_reason: g.finish_reason, |
| 823 | request_id: g.request_id, |
| 824 | operation_id: g.operation_id, |
| 825 | decoding: g.decoding.as_ref(), |
| 826 | ops: g.ops.as_ref(), |
| 827 | }, |
| 828 | started, |
| 829 | ); |
| 830 | bridge.record_generation(&record) |
| 831 | }) |
| 832 | .await; |
| 833 | match written { |
| 834 | Ok(Ok(id)) => Some(id), |
| 835 | Ok(Err(e)) => { |
| 836 | tracing::warn!("generation record not written: {e}"); |
| 837 | eprintln!("generation record not written: {e}"); |
| 838 | None |
| 839 | } |
| 840 | Err(e) => { |
| 841 | tracing::warn!("generation record task failed: {e}"); |
| 842 | eprintln!("generation record task failed: {e}"); |
| 843 | None |
| 844 | } |
| 845 | } |
| 846 | } |
| 847 | |
| 848 | async fn stream_turn( |
| 849 | writer: &mut tokio::net::unix::OwnedWriteHalf, |
| 850 | spine: Arc<Mutex<AienRuntimeSpine>>, |
| 851 | tokenizer: Arc<RwLock<Option<ChatTokenizer>>>, |
| 852 | messages: Vec<crate::control::ChatTurn>, |
| 853 | max_tokens: usize, |
| 854 | temperature: f32, |
| 855 | rec: RecordCtx, |
| 856 | ) { |
| 857 | let (tokenizer, events, prompt_ids) = |
| 858 | match submit_turn(spine, tokenizer, messages, max_tokens, temperature, "").await { |
| 859 | Ok(x) => x, |
| 860 | Err(error) => { |
| 861 | let _ = write_response(writer, &ControlResponse::Error(error)).await; |
| 862 | return; |
| 863 | } |
| 864 | }; |
| 865 | |
| 866 | forward_turn(writer, tokenizer, events, prompt_ids, rec).await; |
| 867 | } |
| 868 | |
| 869 | // Shared production event-to-wire path. Tests inject scheduler events, never |
| 870 | // fabricated terminal responses, so they exercise the producer and client. |
| 871 | async fn forward_turn( |
| 872 | writer: &mut tokio::net::unix::OwnedWriteHalf, |
| 873 | tokenizer: ChatTokenizer, |
| 874 | mut events: tokio::sync::mpsc::UnboundedReceiver<CompletionEvent>, |
| 875 | prompt_ids: Vec<u32>, |
| 876 | rec: RecordCtx, |
| 877 | ) { |
| 878 | let RecordCtx { |
| 879 | compose, |
| 880 | identity, |
| 881 | started, |
| 882 | request_id, |
| 883 | operation_id, |
| 884 | } = rec; |
| 885 | let mut produced = Vec::new(); |
| 886 | let mut text = String::new(); |
| 887 | loop { |
| 888 | let next = tokio::time::timeout(std::time::Duration::from_secs(120), events.recv()).await; |
| 889 | match next { |
| 890 | Ok(Some(CompletionEvent::Token { token, .. })) => { |
| 891 | produced.push(token); |
| 892 | let decoded = tokenizer |
| 893 | .decode_opts(&produced, true) |
| 894 | .unwrap_or_else(|_| text.clone()); |
| 895 | let delta = text_suffix(&text, &decoded); |
| 896 | if decoded.len() >= text.len() && decoded.starts_with(&text) { |
| 897 | text = decoded; |
| 898 | } |
| 899 | if !delta.is_empty() |
| 900 | && !write_response(writer, &ControlResponse::TurnDelta { text: delta }).await |
| 901 | { |
| 902 | return; |
| 903 | } |
| 904 | } |
| 905 | Ok(Some(CompletionEvent::Finished { |
| 906 | total_tokens, |
| 907 | finish_reason, |
| 908 | decoding, |
| 909 | ops, |
| 910 | .. |
| 911 | })) => { |
| 912 | if let Some(line) = crate::generation::op_report_line(ops.as_ref()) { |
| 913 | eprintln!("{line}"); |
| 914 | } |
| 915 | let generation_record = record_generation( |
| 916 | compose, |
| 917 | identity, |
| 918 | started, |
| 919 | GenerationOwned { |
| 920 | prompt_ids, |
| 921 | output_ids: produced, |
| 922 | text: text.clone(), |
| 923 | total_tokens, |
| 924 | finish_reason: finish_reason_label(&finish_reason), |
| 925 | request_id, |
| 926 | operation_id, |
| 927 | decoding, |
| 928 | ops, |
| 929 | }, |
| 930 | ) |
| 931 | .await; |
| 932 | // Retain the generation evidence even for an incomplete answer. |
| 933 | // Existing clients already fail closed on the Error response. |
| 934 | if !matches!(finish_reason, aien_inference_abi::FinishReason::StopToken) { |
| 935 | let _ = write_response( |
| 936 | writer, |
| 937 | &ControlResponse::Error(format!( |
| 938 | "native turn did not complete: {}", |
| 939 | finish_reason_label(&finish_reason) |
| 940 | )), |
| 941 | ) |
| 942 | .await; |
| 943 | return; |
| 944 | } |
| 945 | let _ = write_response( |
| 946 | writer, |
| 947 | &ControlResponse::TurnFinished { |
| 948 | text, |
| 949 | total_tokens, |
| 950 | generation_record, |
| 951 | }, |
| 952 | ) |
| 953 | .await; |
| 954 | return; |
| 955 | } |
| 956 | Ok(Some(CompletionEvent::Error { message, .. })) => { |
| 957 | let _ = write_response(writer, &ControlResponse::Error(message)).await; |
| 958 | return; |
| 959 | } |
| 960 | Ok(None) | Err(_) => { |
| 961 | let _ = write_response( |
| 962 | writer, |
| 963 | &ControlResponse::Error( |
| 964 | "native runtime stopped streaming before the turn finished".into(), |
| 965 | ), |
| 966 | ) |
| 967 | .await; |
| 968 | return; |
| 969 | } |
| 970 | } |
| 971 | } |
| 972 | } |
| 973 | |
| 974 | #[cfg_attr(feature = "provisional-prep", allow(clippy::too_many_arguments))] |
| 975 | async fn handle_connection( |
| 976 | stream: UnixStream, |
| 977 | spine: Arc<Mutex<AienRuntimeSpine>>, |
| 978 | is_running: Arc<AtomicBool>, |
| 979 | shutdown_notify: Arc<Notify>, |
| 980 | tokenizer: Arc<RwLock<Option<ChatTokenizer>>>, |
| 981 | compose: Option<Arc<ComposeBridge>>, |
| 982 | (identity, started): (Option<Arc<ModelIdentity>>, DaemonStart), |
| 983 | #[cfg(feature = "provisional-prep")] prep: Option<Arc<crate::provisional::PrepAdapter>>, |
| 984 | ) { |
| 985 | let (reader, mut writer) = stream.into_split(); |
| 986 | let mut buf_reader = BufReader::new(reader); |
| 987 | let mut line = String::new(); |
| 988 | |
| 989 | while let Ok(n) = buf_reader.read_line(&mut line).await { |
| 990 | if n == 0 { |
| 991 | break; |
| 992 | } |
| 993 | let trimmed = line.trim(); |
| 994 | if trimmed.is_empty() { |
| 995 | line.clear(); |
| 996 | continue; |
| 997 | } |
| 998 | |
| 999 | let parsed = serde_json::from_str::<ControlEnvelope>(trimmed); |
| 1000 | let envelope = match parsed { |
| 1001 | Ok(envelope) => envelope, |
| 1002 | Err(e) => { |
| 1003 | if !write_response( |
| 1004 | &mut writer, |
| 1005 | &ControlResponse::Error(format!("Invalid control envelope JSON: {}", e)), |
| 1006 | ) |
| 1007 | .await |
| 1008 | { |
| 1009 | break; |
| 1010 | } |
| 1011 | line.clear(); |
| 1012 | continue; |
| 1013 | } |
| 1014 | }; |
| 1015 | |
| 1016 | if let ControlCommand::StreamTurn { |
| 1017 | messages, |
| 1018 | max_tokens, |
| 1019 | temperature, |
| 1020 | } = envelope.command |
| 1021 | { |
| 1022 | stream_turn( |
| 1023 | &mut writer, |
| 1024 | spine.clone(), |
| 1025 | tokenizer.clone(), |
| 1026 | messages, |
| 1027 | max_tokens, |
| 1028 | temperature, |
| 1029 | RecordCtx { |
| 1030 | compose: compose.clone(), |
| 1031 | identity: identity.clone(), |
| 1032 | started, |
| 1033 | request_id: envelope.request_id, |
| 1034 | operation_id: envelope.operation_id, |
| 1035 | }, |
| 1036 | ) |
| 1037 | .await; |
| 1038 | line.clear(); |
| 1039 | continue; |
| 1040 | } |
| 1041 | |
| 1042 | let compose_job: Option<ComposeJob> = match envelope.command { |
| 1043 | ControlCommand::RunComposeTask { |
| 1044 | ref goal, |
| 1045 | ref workspace, |
| 1046 | ref context, |
| 1047 | } => { |
| 1048 | let (g, w, c) = (goal.clone(), workspace.clone(), context.clone()); |
| 1049 | Some(Box::new(move |b: &Arc<ComposeBridge>| { |
| 1050 | b.run_task_in(&g, &w, c.as_deref()) |
| 1051 | })) |
| 1052 | } |
| 1053 | ControlCommand::ComposeNote { |
| 1054 | ref kind, |
| 1055 | ref text, |
| 1056 | ref links, |
| 1057 | } => { |
| 1058 | let (k, t, l) = (kind.clone(), text.clone(), links.clone()); |
| 1059 | // Gated records (every authorization, effect phases, replay and |
| 1060 | // commit records) are refused inside `note` itself (#261). |
| 1061 | Some(Box::new(move |b: &Arc<ComposeBridge>| b.note(&k, &t, &l))) |
| 1062 | } |
| 1063 | ControlCommand::ComposeAuthorize { |
| 1064 | cx_promotion, |
| 1065 | ref proposal_sha256, |
| 1066 | ref workspace, |
| 1067 | ref approver, |
| 1068 | ref constraints, |
| 1069 | ref desk_proof, |
| 1070 | ref objective_id, |
| 1071 | } => { |
| 1072 | let req = crate::effects::MintRequest { |
| 1073 | cx_promotion, |
| 1074 | proposal_sha256: proposal_sha256.clone(), |
| 1075 | workspace: workspace.clone(), |
| 1076 | approver: approver.clone(), |
| 1077 | constraints: constraints.clone(), |
| 1078 | }; |
| 1079 | let proof = desk_proof.clone(); |
| 1080 | let objective = objective_id.clone(); |
| 1081 | #[cfg(feature = "provisional-prep")] |
| 1082 | let fence = prep.clone(); |
| 1083 | Some(Box::new(move |b: &Arc<ComposeBridge>| { |
| 1084 | // Headstart M3: a bound request passes the fence instead. |
| 1085 | #[cfg(feature = "provisional-prep")] |
| 1086 | if let Some(r) = fence.as_ref().and_then(|a| { |
| 1087 | a.route_authorize(b, &req, proof.as_ref(), objective.as_deref()) |
| 1088 | }) { |
| 1089 | return r; |
| 1090 | } |
| 1091 | crate::effects::authorize_with_objective( |
| 1092 | b, |
| 1093 | &req, |
| 1094 | proof.as_ref(), |
| 1095 | objective.as_deref(), |
| 1096 | ) |
| 1097 | })) |
| 1098 | } |
| 1099 | ControlCommand::ComposeRecall { ref ids, prefix } => { |
| 1100 | let i = ids.clone(); |
| 1101 | Some(Box::new(move |b: &Arc<ComposeBridge>| b.recall(&i, prefix))) |
| 1102 | } |
| 1103 | ControlCommand::RecoverComposeHome => { |
| 1104 | Some(Box::new(|b: &Arc<ComposeBridge>| b.recover())) |
| 1105 | } |
| 1106 | // NEXT-PHASE-2: effect intents, acks, reconcile, operator control. |
| 1107 | ControlCommand::ComposeEffectIntent { |
| 1108 | authorization, |
| 1109 | ref proposal_sha256, |
| 1110 | ref path, |
| 1111 | ref target, |
| 1112 | ref content_sha256, |
| 1113 | executor_pid, |
| 1114 | executor_start, |
| 1115 | } => { |
| 1116 | let req = crate::effects::IntentRequest { |
| 1117 | authorization, |
| 1118 | proposal_sha256: proposal_sha256.clone(), |
| 1119 | path: path.clone(), |
| 1120 | target: target.clone(), |
| 1121 | content_sha256: content_sha256.clone(), |
| 1122 | executor_pid, |
| 1123 | executor_start, |
| 1124 | }; |
| 1125 | Some(Box::new(move |b: &Arc<ComposeBridge>| { |
| 1126 | crate::effects::open_intent(b, &req) |
| 1127 | })) |
| 1128 | } |
| 1129 | ControlCommand::ComposeEffectAck { |
| 1130 | intent, |
| 1131 | ref reported, |
| 1132 | } => { |
| 1133 | let r = reported.clone(); |
| 1134 | Some(Box::new(move |b: &Arc<ComposeBridge>| { |
| 1135 | crate::effects::ack(b, intent, &r) |
| 1136 | })) |
| 1137 | } |
| 1138 | ControlCommand::ComposeReconcile { ref declare } => { |
| 1139 | let d = declare.clone(); |
| 1140 | Some(Box::new(move |b: &Arc<ComposeBridge>| { |
| 1141 | crate::effects::reconcile(b, d.as_ref(), "reconcile") |
| 1142 | })) |
| 1143 | } |
| 1144 | ControlCommand::ComposeApprovedProposal { |
| 1145 | ref proposal, |
| 1146 | ref workspace, |
| 1147 | } => { |
| 1148 | let (p, w) = (proposal.clone(), workspace.clone()); |
| 1149 | #[cfg(feature = "provisional-prep")] |
| 1150 | let fence = prep.clone(); |
| 1151 | Some(Box::new(move |b: &Arc<ComposeBridge>| { |
| 1152 | // Headstart M3: a bound request passes the fence instead. |
| 1153 | #[cfg(feature = "provisional-prep")] |
| 1154 | if let Some(r) = fence.as_ref().and_then(|a| a.route_approved(b, &p, &w)) { |
| 1155 | return r; |
| 1156 | } |
| 1157 | match crate::approved::ProposerHook::new(b.clone()).submit(&p, &w) { |
| 1158 | Ok(r) => ControlResponse::ComposeApprovedResult(Box::new(r)), |
| 1159 | Err(r) => ControlResponse::ComposeApprovedRefused(r), |
| 1160 | } |
| 1161 | })) |
| 1162 | } |
| 1163 | ControlCommand::ComposeControl { |
| 1164 | ref action, |
| 1165 | ref approver, |
| 1166 | authorization, |
| 1167 | } => { |
| 1168 | let (a, p) = (action.clone(), approver.clone()); |
| 1169 | Some(Box::new(move |b: &Arc<ComposeBridge>| { |
| 1170 | crate::effects::control(b, &a, &p, authorization) |
| 1171 | })) |
| 1172 | } |
| 1173 | ControlCommand::AllenStatus |
| 1174 | | ControlCommand::AllenProfileShow |
| 1175 | | ControlCommand::AllenProfileSet { .. } |
| 1176 | | ControlCommand::AllenProfileHistory |
| 1177 | | ControlCommand::AllenProfileRevert { .. } |
| 1178 | | ControlCommand::AllenMemoryPut { .. } |
| 1179 | | ControlCommand::AllenMemoryRecall { .. } |
| 1180 | | ControlCommand::AllenMemoryInspect { .. } |
| 1181 | | ControlCommand::AllenMemoryCorrect { .. } |
| 1182 | | ControlCommand::AllenMemoryForget { .. } |
| 1183 | | ControlCommand::AllenMemoryExport { .. } |
| 1184 | | ControlCommand::AllenGoalsList { .. } |
| 1185 | | ControlCommand::AllenGoalAdd { .. } |
| 1186 | | ControlCommand::AllenGoalClose { .. } |
| 1187 | | ControlCommand::AllenProfileReset { .. } => { |
| 1188 | let c = envelope.command.clone(); |
| 1189 | Some(Box::new(move |b: &Arc<ComposeBridge>| b.allen_command(&c))) |
| 1190 | } |
| 1191 | _ => None, |
| 1192 | }; |
| 1193 | if let Some(job) = compose_job { |
| 1194 | let response = match compose.clone() { |
| 1195 | Some(bridge) => tokio::task::spawn_blocking(move || job(&bridge)) |
| 1196 | .await |
| 1197 | .unwrap_or_else(|e| { |
| 1198 | ControlResponse::Error(format!("compose command failed: {e}")) |
| 1199 | }), |
| 1200 | None => ControlResponse::Error( |
| 1201 | "compose: no compose home (set AIEN_COMPOSE_DIR or AIEN_RUNTIME_STATE_DIR)" |
| 1202 | .into(), |
| 1203 | ), |
| 1204 | }; |
| 1205 | if !write_response(&mut writer, &response).await { |
| 1206 | break; |
| 1207 | } |
| 1208 | line.clear(); |
| 1209 | continue; |
| 1210 | } |
| 1211 | |
| 1212 | let is_shutdown = matches!(envelope.command, ControlCommand::Shutdown); |
| 1213 | let response = { |
| 1214 | let mut s = spine.lock().await; |
| 1215 | s.handle_control_command(envelope) |
| 1216 | }; |
| 1217 | if is_shutdown { |
| 1218 | is_running.store(false, Ordering::SeqCst); |
| 1219 | shutdown_notify.notify_waiters(); |
| 1220 | } |
| 1221 | if !write_response(&mut writer, &response).await { |
| 1222 | break; |
| 1223 | } |
| 1224 | line.clear(); |
| 1225 | } |
| 1226 | } |
| 1227 | |
| 1228 | /// The correlation trace sink for this daemon (#398). `AIEN_TRACE_JSONL=<file>` |
| 1229 | /// turns on a bounded append-only JSON-lines exporter (4096 queued events, |
| 1230 | /// drops counted and reported as `trace_dropped`, flushed every 250 ms and |
| 1231 | /// once more when the returned handle drops). Unset or empty: `NullSink`. |
| 1232 | /// Never fails the daemon: an unwritable file only loses trace lines. |
| 1233 | pub fn trace_sink_from_env() -> ( |
| 1234 | Arc<dyn aien_trace::TraceSink>, |
| 1235 | Option<aien_trace::FlusherHandle>, |
| 1236 | ) { |
| 1237 | match std::env::var("AIEN_TRACE_JSONL") { |
| 1238 | Ok(path) if !path.trim().is_empty() => { |
| 1239 | let sink = Arc::new(aien_trace::BoundedJsonlSink::new(path.trim())); |
| 1240 | let flusher = sink.spawn_flusher(std::time::Duration::from_millis(250)); |
| 1241 | tracing::info!(path = %sink.path().display(), "trace exporter on (AIEN_TRACE_JSONL)"); |
| 1242 | (sink, Some(flusher)) |
| 1243 | } |
| 1244 | _ => (Arc::new(aien_trace::NullSink), None), |
| 1245 | } |
| 1246 | } |
| 1247 | #[cfg(test)] |
| 1248 | mod generation_record_tests { |
| 1249 | use super::*; |
| 1250 | |
| 1251 | fn identity() -> Arc<ModelIdentity> { |
| 1252 | Arc::new(ModelIdentity { |
| 1253 | model_sha256: "a".repeat(64), |
| 1254 | model_digest_kind: "file".into(), |
| 1255 | model_path: "/m/model.safetensors".into(), |
| 1256 | tokenizer_sha256: "b".repeat(64), |
| 1257 | tokenizer_path: "/m/tokenizer.json".into(), |
| 1258 | }) |
| 1259 | } |
| 1260 | |
| 1261 | fn turn() -> GenerationOwned { |
| 1262 | GenerationOwned { |
| 1263 | prompt_ids: vec![1, 2], |
| 1264 | output_ids: vec![3], |
| 1265 | text: "t".into(), |
| 1266 | total_tokens: 1, |
| 1267 | finish_reason: "eos", |
| 1268 | request_id: 1, |
| 1269 | operation_id: 1, |
| 1270 | decoding: None, |
| 1271 | ops: None, |
| 1272 | } |
| 1273 | } |
| 1274 | |
| 1275 | fn bridge(dir: std::path::PathBuf) -> Arc<ComposeBridge> { |
| 1276 | let proposer: ComposeProposer = |
| 1277 | Arc::new(|_p: &str, _l: std::time::Duration| Err("not used".to_string())); |
| 1278 | Arc::new(ComposeBridge::new(dir, proposer, "test:generation-record")) |
| 1279 | } |
| 1280 | |
| 1281 | #[tokio::test] |
| 1282 | async fn no_ledger_means_no_record() { |
| 1283 | let got = record_generation(None, Some(identity()), DaemonStart::now(), turn()).await; |
| 1284 | assert_eq!(got, None); |
| 1285 | } |
| 1286 | |
| 1287 | #[tokio::test] |
| 1288 | async fn no_model_identity_means_no_record() { |
| 1289 | let tmp = tempfile::tempdir().unwrap(); |
| 1290 | let b = bridge(tmp.path().join("compose")); |
| 1291 | let got = record_generation(Some(b), None, DaemonStart::now(), turn()).await; |
| 1292 | assert_eq!(got, None); |
| 1293 | // Nothing was opened or written. |
| 1294 | assert!(!tmp.path().join("compose").exists()); |
| 1295 | } |
| 1296 | |
| 1297 | /// A ledger that cannot be written (here: its directory is a regular |
| 1298 | /// file, and in a stub build the engine is absent) yields no id. |
| 1299 | #[tokio::test] |
| 1300 | async fn a_failed_append_returns_no_id() { |
| 1301 | let _home = crate::home_guard::home_slot(); |
| 1302 | let tmp = tempfile::tempdir().unwrap(); |
| 1303 | let blocked = tmp.path().join("compose"); |
| 1304 | std::fs::write(&blocked, b"not a directory").unwrap(); |
| 1305 | let got = record_generation( |
| 1306 | Some(bridge(blocked)), |
| 1307 | Some(identity()), |
| 1308 | DaemonStart::now(), |
| 1309 | turn(), |
| 1310 | ) |
| 1311 | .await; |
| 1312 | assert_eq!(got, None); |
| 1313 | } |
| 1314 | } |
| 1315 | |
| 1316 | #[cfg(test)] |
| 1317 | mod completion_tests { |
| 1318 | use super::*; |
| 1319 | use aien_inference_abi::FinishReason; |
| 1320 | |
| 1321 | async fn event_to_client(reason: FinishReason) -> Result<(String, Option<u64>), String> { |
| 1322 | let scratch = tempfile::tempdir().unwrap(); |
| 1323 | let path = scratch.path().join("finish.sock"); |
| 1324 | let listener = UnixListener::bind(&path).unwrap(); |
| 1325 | let server = tokio::spawn(async move { |
| 1326 | let (socket, _) = listener.accept().await.unwrap(); |
| 1327 | let (reader, mut writer) = socket.into_split(); |
| 1328 | let mut request = String::new(); |
| 1329 | BufReader::new(reader) |
| 1330 | .read_line(&mut request) |
| 1331 | .await |
| 1332 | .unwrap(); |
| 1333 | serde_json::from_str::<ControlEnvelope>(&request).unwrap(); |
| 1334 | let tokenizer = ChatTokenizer::from_bytes(br#"{"version":"1.0","truncation":null,"padding":null,"added_tokens":[],"normalizer":null,"pre_tokenizer":{"type":"Whitespace"},"post_processor":null,"decoder":null,"model":{"type":"WordLevel","unk_token":"<unk>","vocab":{"<unk>":0,"partial":100}}}"#).unwrap(); |
| 1335 | let (sender, events) = tokio::sync::mpsc::unbounded_channel(); |
| 1336 | let seq_id = aien_scheduler::SequenceId { |
| 1337 | slot: 0, |
| 1338 | generation: 1, |
| 1339 | }; |
| 1340 | sender |
| 1341 | .send(CompletionEvent::Token { seq_id, token: 100 }) |
| 1342 | .unwrap(); |
| 1343 | sender |
| 1344 | .send(CompletionEvent::Finished { |
| 1345 | seq_id, |
| 1346 | finish_reason: reason, |
| 1347 | total_tokens: 1, |
| 1348 | decoding: None, |
| 1349 | ops: None, |
| 1350 | }) |
| 1351 | .unwrap(); |
| 1352 | forward_turn( |
| 1353 | &mut writer, |
| 1354 | tokenizer, |
| 1355 | events, |
| 1356 | vec![0], |
| 1357 | RecordCtx { |
| 1358 | compose: None, |
| 1359 | identity: None, |
| 1360 | started: DaemonStart::now(), |
| 1361 | request_id: 1, |
| 1362 | operation_id: 1, |
| 1363 | }, |
| 1364 | ) |
| 1365 | .await; |
| 1366 | }); |
| 1367 | let result = crate::client::AienRuntimeClient::new(&path) |
| 1368 | .stream_turn_recorded(Vec::new(), 10, 0.0) |
| 1369 | .await; |
| 1370 | server.await.unwrap(); |
| 1371 | result |
| 1372 | } |
| 1373 | |
| 1374 | #[tokio::test] |
| 1375 | async fn round3_length_limit_is_not_complete() { |
| 1376 | let error = event_to_client(FinishReason::LengthLimit) |
| 1377 | .await |
| 1378 | .expect_err("limited turn"); |
| 1379 | assert!(error.contains("max_tokens"), "{error}"); |
| 1380 | } |
| 1381 | |
| 1382 | #[tokio::test] |
| 1383 | async fn round3_aborted_is_not_complete() { |
| 1384 | let error = event_to_client(FinishReason::Aborted) |
| 1385 | .await |
| 1386 | .expect_err("aborted turn"); |
| 1387 | assert!(error.contains("aborted"), "{error}"); |
| 1388 | } |
| 1389 | |
| 1390 | #[tokio::test] |
| 1391 | async fn round3_preempted_is_not_complete() { |
| 1392 | let error = event_to_client(FinishReason::Preempted) |
| 1393 | .await |
| 1394 | .expect_err("preempted turn"); |
| 1395 | assert!(error.contains("preempted"), "{error}"); |
| 1396 | } |
| 1397 | |
| 1398 | #[tokio::test] |
| 1399 | async fn round3_stop_token_is_complete() { |
| 1400 | let (text, record) = event_to_client(FinishReason::StopToken).await.unwrap(); |
| 1401 | assert_eq!(text, "partial"); |
| 1402 | assert_eq!(record, None); |
| 1403 | } |
| 1404 | } |