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 / tests / kv_concurrency_test.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 | //! C8 (sc#485 B1 to B5; ADR 0003 sections 5.2, 5.5, 7 and 8): concurrency |
| 17 | //! proof of persistent KV through the real runtime spine, the real scheduler |
| 18 | //! and the host CPU backend (`NativeTransformerBackend` over |
| 19 | //! `ReferenceCpuBackend` with the reference test weights), the real C5 storage |
| 20 | //! worker and the deterministic C2 fake store. |
| 21 | //! |
| 22 | //! Host only: no GPU, no CUDA, no files. Every K/V byte is computed by the CPU |
| 23 | //! model, so restored bytes and greedy continuations are compared with cold |
| 24 | //! runs of the same prompt. |
| 25 | //! |
| 26 | //! Stalls are gates, never wall-clock bounds: [`Gate`] sits between the |
| 27 | //! storage worker and the fake and can hold every load or store it is handed |
| 28 | //! (the fake's `Hold` fault) until the test releases or cancels it, and can |
| 29 | //! make stores fail as if the disk were full. Progress is counted in steps, |
| 30 | //! and a step counts only once the storage worker has run every job it can |
| 31 | //! ([`settle`]), so a busy machine cannot spend a step bound. |
| 32 | //! The only wall clock in this file is a hang guard on loops that wait for the |
| 33 | //! worker thread; it never decides a pass. |
| 34 | //! |
| 35 | //! Geometry: block size 4 tokens, chunk of 2 blocks (8 tokens). A 15-token |
| 36 | //! prompt with `max_tokens = 2` finishes with a computed prefix of 16 tokens |
| 37 | //! (the prompt and the first generated token; the newest token has no K/V), |
| 38 | //! which is exactly two full chunks. |
| 39 | |
| 40 | use aien_abi_core::{ModelConfig, SamplingParams}; |
| 41 | use aien_inference_abi::backend::TensorBackend; |
| 42 | use aien_inference_abi::{NativeTransformerBackend, ReferenceCpuBackend, TransformerWeights}; |
| 43 | use aien_kv_cache::SharedKvManager; |
| 44 | use aien_kv_store::fake::{FakeConfig, FakeKvStore, Fault, JobScript}; |
| 45 | use aien_kv_store::worker::{StorageWorker, WorkerConfig}; |
| 46 | use aien_kv_store::{ |
| 47 | chunk_chain, BackendFormat, CancelOutcome, Capacity, ChunkHeader, ChunkKey, Completion, |
| 48 | DrainReport, Incarnation, JobId, KvDtype, KvStore, NamespaceId, PinToken, PinnedDest, |
| 49 | PinnedSource, RecoveryProgress, |
| 50 | }; |
| 51 | use aien_platform::PlatformError; |
| 52 | use aien_runtime::compute_config::{HostEngineIdentity, ModelBinding, StoreInputs}; |
| 53 | use aien_runtime::kv_residency::{ |
| 54 | layout_strides, KvIdentity, KvResidency, KvResidencyConfig, KvResidencyStatus, ResidencyState, |
| 55 | }; |
| 56 | use aien_runtime::shared_kv::{build_shared_kv_runtime, SharedKvSizing}; |
| 57 | use aien_runtime::spine::AienRuntimeSpine; |
| 58 | use aien_scheduler::{ |
| 59 | ChannelCompletionSink, CompletionEvent, CompletionSinkId, SchedulerConfig, SequenceId, |
| 60 | SequencePhase, |
| 61 | }; |
| 62 | use parking_lot::Mutex; |
| 63 | use std::collections::{BTreeMap, HashMap}; |
| 64 | use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; |
| 65 | use std::sync::Arc; |
| 66 | use std::time::{Duration, Instant}; |
| 67 | use tokio::sync::mpsc::UnboundedReceiver; |
| 68 | |
| 69 | const BLOCK: usize = 4; |
| 70 | const CHUNK_BLOCKS: u32 = 2; |
| 71 | const CHUNK: usize = BLOCK * CHUNK_BLOCKS as usize; |
| 72 | |
| 73 | /// Hang guard for loops that wait on the storage worker thread. Never a pass |
| 74 | /// criterion: every assertion counts steps or reads state. |
| 75 | const HANG_GUARD: Duration = Duration::from_secs(30); |
| 76 | |
| 77 | // --------------------------------------------------------------------------- |
| 78 | // The gate: a KvStore between the storage worker and the fake |
| 79 | // --------------------------------------------------------------------------- |
| 80 | |
| 81 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 82 | enum Kind { |
| 83 | Load, |
| 84 | Store, |
| 85 | } |
| 86 | |
| 87 | /// Delegates to the fake. While `hold_loads` / `hold_stores` is set, each job |
| 88 | /// of that kind is submitted with the fake's `Hold` fault and recorded, so the |
| 89 | /// test can release or cancel it. While `disk_full` is set, every store fails |
| 90 | /// at its write with `OutOfMemory` (the fake's `DiskFull`). Only the storage |
| 91 | /// worker thread submits to the inner store, so a script placed right before |
| 92 | /// the inner `submit_*` is the one that call consumes. |
| 93 | struct Gate { |
| 94 | inner: Arc<FakeKvStore>, |
| 95 | hold_loads: AtomicBool, |
| 96 | hold_stores: AtomicBool, |
| 97 | disk_full: AtomicBool, |
| 98 | held: Mutex<Vec<(Kind, ChunkKey, JobId)>>, |
| 99 | /// Every load and store that reached the store, in order. |
| 100 | seen: Mutex<Vec<(Kind, ChunkKey)>>, |
| 101 | /// Passes of the storage worker loop. The worker calls `poll` on the store |
| 102 | /// exactly once per pass, after it has dispatched and driven, so every |
| 103 | /// `poll` closes one pass. |
| 104 | passes: AtomicU64, |
| 105 | /// The latest pass that handed the store nothing (no submit, cancel or |
| 106 | /// waiter) and reaped nothing from it: the worker had no work it could |
| 107 | /// move without the spine or the test. 0 before the first such pass. |
| 108 | quiet: AtomicU64, |
| 109 | /// The store was touched since the last `poll`. |
| 110 | touched: AtomicBool, |
| 111 | } |
| 112 | |
| 113 | impl Gate { |
| 114 | fn new(inner: Arc<FakeKvStore>) -> Self { |
| 115 | Self { |
| 116 | inner, |
| 117 | hold_loads: AtomicBool::new(false), |
| 118 | hold_stores: AtomicBool::new(false), |
| 119 | disk_full: AtomicBool::new(false), |
| 120 | held: Mutex::new(Vec::new()), |
| 121 | seen: Mutex::new(Vec::new()), |
| 122 | passes: AtomicU64::new(0), |
| 123 | quiet: AtomicU64::new(0), |
| 124 | touched: AtomicBool::new(false), |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | fn script(&self, kind: Kind) -> bool { |
| 129 | let hold = match kind { |
| 130 | Kind::Load => self.hold_loads.load(Ordering::SeqCst), |
| 131 | Kind::Store => self.hold_stores.load(Ordering::SeqCst), |
| 132 | }; |
| 133 | let mut s = JobScript::default(); |
| 134 | if hold { |
| 135 | s = s.with(Fault::Hold); |
| 136 | } |
| 137 | if kind == Kind::Store && self.disk_full.load(Ordering::SeqCst) { |
| 138 | s = s.with(Fault::DiskFull); |
| 139 | } |
| 140 | if s != JobScript::default() { |
| 141 | self.inner.script(s); |
| 142 | } |
| 143 | hold |
| 144 | } |
| 145 | |
| 146 | fn after(&self, kind: Kind, key: ChunkKey, hold: bool, r: &Result<JobId, PlatformError>) { |
| 147 | self.touched.store(true, Ordering::SeqCst); |
| 148 | self.seen.lock().push((kind, key)); |
| 149 | if let (true, Ok(job)) = (hold, r) { |
| 150 | self.held.lock().push((kind, key, *job)); |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | fn held_count(&self, kind: Kind) -> usize { |
| 155 | self.held.lock().iter().filter(|h| h.0 == kind).count() |
| 156 | } |
| 157 | |
| 158 | fn seen_count(&self, kind: Kind) -> usize { |
| 159 | self.seen.lock().iter().filter(|h| h.0 == kind).count() |
| 160 | } |
| 161 | |
| 162 | /// Lets every held job of `kind` start; returns how many. |
| 163 | fn release(&self, kind: Kind) -> usize { |
| 164 | let mut held = self.held.lock(); |
| 165 | let mut n = 0; |
| 166 | held.retain(|&(k, _, job)| { |
| 167 | if k == kind { |
| 168 | assert!(self.inner.release(job), "held job {job:?} not held"); |
| 169 | n += 1; |
| 170 | false |
| 171 | } else { |
| 172 | true |
| 173 | } |
| 174 | }); |
| 175 | n |
| 176 | } |
| 177 | |
| 178 | /// Cancels every held job of `kind` at the store (a mid-transfer cancel, |
| 179 | /// ADR 5.5); returns how many were cancelled. |
| 180 | fn cancel(&self, kind: Kind) -> usize { |
| 181 | let mut held = self.held.lock(); |
| 182 | let mut n = 0; |
| 183 | held.retain(|&(k, _, job)| { |
| 184 | if k == kind { |
| 185 | assert_eq!(self.inner.cancel(job), CancelOutcome::Cancelled); |
| 186 | n += 1; |
| 187 | false |
| 188 | } else { |
| 189 | true |
| 190 | } |
| 191 | }); |
| 192 | n |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | impl KvStore for Gate { |
| 197 | fn namespace(&self) -> NamespaceId { |
| 198 | self.inner.namespace() |
| 199 | } |
| 200 | fn capacity(&self) -> Capacity { |
| 201 | self.inner.capacity() |
| 202 | } |
| 203 | fn lookup(&self, keys: &[ChunkKey]) -> Vec<Option<u64>> { |
| 204 | self.inner.lookup(keys) |
| 205 | } |
| 206 | fn submit_store( |
| 207 | &self, |
| 208 | header: ChunkHeader, |
| 209 | src: PinnedSource, |
| 210 | inc: Incarnation, |
| 211 | ) -> Result<JobId, PlatformError> { |
| 212 | let key = header.chunk_key; |
| 213 | let hold = self.script(Kind::Store); |
| 214 | let r = self.inner.submit_store(header, src, inc); |
| 215 | self.after(Kind::Store, key, hold, &r); |
| 216 | r |
| 217 | } |
| 218 | fn submit_load( |
| 219 | &self, |
| 220 | key: ChunkKey, |
| 221 | expect: &ChunkHeader, |
| 222 | dst: PinnedDest, |
| 223 | inc: Incarnation, |
| 224 | ) -> Result<JobId, PlatformError> { |
| 225 | let hold = self.script(Kind::Load); |
| 226 | let r = self.inner.submit_load(key, expect, dst, inc); |
| 227 | self.after(Kind::Load, key, hold, &r); |
| 228 | r |
| 229 | } |
| 230 | fn submit_flush(&self, inc: Incarnation) -> Result<JobId, PlatformError> { |
| 231 | self.touched.store(true, Ordering::SeqCst); |
| 232 | self.inner.submit_flush(inc) |
| 233 | } |
| 234 | fn attach_waiter(&self, job: JobId, inc: Incarnation) -> Result<(), PlatformError> { |
| 235 | self.touched.store(true, Ordering::SeqCst); |
| 236 | self.inner.attach_waiter(job, inc) |
| 237 | } |
| 238 | fn poll(&self, max: usize) -> Vec<Completion> { |
| 239 | let c = self.inner.poll(max); |
| 240 | let pass = self.passes.fetch_add(1, Ordering::SeqCst) + 1; |
| 241 | if !self.touched.swap(false, Ordering::SeqCst) && c.is_empty() { |
| 242 | self.quiet.store(pass, Ordering::SeqCst); |
| 243 | } |
| 244 | c |
| 245 | } |
| 246 | fn cancel(&self, job: JobId) -> CancelOutcome { |
| 247 | self.touched.store(true, Ordering::SeqCst); |
| 248 | self.inner.cancel(job) |
| 249 | } |
| 250 | fn pin(&self, keys: &[ChunkKey]) -> Result<PinToken, PlatformError> { |
| 251 | self.inner.pin(keys) |
| 252 | } |
| 253 | fn unpin(&self, token: PinToken) { |
| 254 | self.inner.unpin(token) |
| 255 | } |
| 256 | fn delete(&self, keys: &[ChunkKey]) -> u64 { |
| 257 | self.inner.delete(keys) |
| 258 | } |
| 259 | fn recover_step(&self, slice_ms: u64) -> RecoveryProgress { |
| 260 | self.inner.recover_step(slice_ms) |
| 261 | } |
| 262 | fn shutdown(&self, intake_deadline_ms: u64) -> DrainReport { |
| 263 | self.inner.shutdown(intake_deadline_ms) |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | // --------------------------------------------------------------------------- |
| 268 | // Rig: the real runtime over the CPU backend |
| 269 | // --------------------------------------------------------------------------- |
| 270 | |
| 271 | /// The CPU reference model of the C7 greedy test (shared_kv_runtime_test.rs). |
| 272 | fn model() -> ModelConfig { |
| 273 | ModelConfig { |
| 274 | model_id: "c8-concurrency-reference".to_string(), |
| 275 | max_sequence_length: 256, |
| 276 | block_size: BLOCK, |
| 277 | num_layers: 3, |
| 278 | num_heads: 4, |
| 279 | head_dim: 8, |
| 280 | num_kv_heads: 2, |
| 281 | hidden_dim: 32, |
| 282 | intermediate_dim: 64, |
| 283 | vocab_size: 97, |
| 284 | rms_norm_eps: 1e-5, |
| 285 | rope_theta: 10000.0, |
| 286 | rope_scaling: None, |
| 287 | tie_word_embeddings: false, |
| 288 | // Outside the 97-token vocabulary: no sampled token ends a turn early |
| 289 | // (an empty list means the legacy stop set 0, 1, 2). |
| 290 | eos_token_ids: vec![1000], |
| 291 | qk_norm: false, |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | #[derive(Clone)] |
| 296 | struct Opts { |
| 297 | total_blocks: usize, |
| 298 | watermark_blocks: usize, |
| 299 | /// `None`: persistence off (the cold baselines). |
| 300 | persist: bool, |
| 301 | restore_max_blocks: usize, |
| 302 | max_restore_ops: u32, |
| 303 | max_park_ops: u32, |
| 304 | max_batch_size: usize, |
| 305 | } |
| 306 | |
| 307 | impl Default for Opts { |
| 308 | fn default() -> Self { |
| 309 | Self { |
| 310 | total_blocks: 64, |
| 311 | watermark_blocks: 0, |
| 312 | persist: true, |
| 313 | restore_max_blocks: 64, |
| 314 | max_restore_ops: 48, |
| 315 | max_park_ops: 16, |
| 316 | max_batch_size: 16, |
| 317 | } |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | struct Store { |
| 322 | fake: Arc<FakeKvStore>, |
| 323 | gate: Arc<Gate>, |
| 324 | worker: Arc<StorageWorker>, |
| 325 | ns: NamespaceId, |
| 326 | } |
| 327 | |
| 328 | struct Rig { |
| 329 | spine: AienRuntimeSpine, |
| 330 | backend: NativeTransformerBackend, |
| 331 | kv: SharedKvManager, |
| 332 | store: Option<Store>, |
| 333 | sink: CompletionSinkId, |
| 334 | rx: UnboundedReceiver<CompletionEvent>, |
| 335 | /// Tokens streamed to the completion sink, per sequence id. |
| 336 | tokens: HashMap<u64, Vec<u32>>, |
| 337 | steps: u64, |
| 338 | } |
| 339 | |
| 340 | fn rig_with(opts: Opts) -> Rig { |
| 341 | let config = model(); |
| 342 | let weights = TransformerWeights::reference_test_weights(&config); |
| 343 | let (mut spine, backend) = build_shared_kv_runtime( |
| 344 | weights, |
| 345 | Arc::new(ReferenceCpuBackend::new()), |
| 346 | SchedulerConfig { |
| 347 | max_batch_size: opts.max_batch_size, |
| 348 | max_batch_tokens: 4096, |
| 349 | max_prefill_tokens: 4096, |
| 350 | prefill_chunk_size: 4096, |
| 351 | chunk_prefill: true, |
| 352 | watermark_blocks: opts.watermark_blocks, |
| 353 | }, |
| 354 | SharedKvSizing { |
| 355 | arena_capacity: 64, |
| 356 | total_blocks: opts.total_blocks, |
| 357 | }, |
| 358 | ) |
| 359 | .expect("runtime"); |
| 360 | let kv = spine.kv_manager.clone(); |
| 361 | let store = opts.persist.then(|| install_store(&mut spine, &kv, &opts)); |
| 362 | let (sink, rx) = ChannelCompletionSink::channel(); |
| 363 | let sink = spine.register_completion_sink(Arc::new(sink)); |
| 364 | Rig { |
| 365 | spine, |
| 366 | backend, |
| 367 | kv, |
| 368 | store, |
| 369 | sink, |
| 370 | rx, |
| 371 | tokens: HashMap::new(), |
| 372 | steps: 0, |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | /// Binds the namespace exactly as the daemon wiring does |
| 377 | /// (`shared_kv::enable_persistent_kv`), but over the gated fake store. |
| 378 | fn install_store(spine: &mut AienRuntimeSpine, kv: &SharedKvManager, opts: &Opts) -> Store { |
| 379 | let config = model(); |
| 380 | let layout = layout_strides(kv.read().pool().expect("pool").layout()); |
| 381 | let arith = ReferenceCpuBackend::new().name(); |
| 382 | let binding = ModelBinding::from_model(&config, arith).expect("binding"); |
| 383 | let engine = HostEngineIdentity::reference(arith).expect("engine identity"); |
| 384 | let fields = binding |
| 385 | .namespace_fields( |
| 386 | &StoreInputs { |
| 387 | model_sha256: [8u8; 32], |
| 388 | model_digest_kind: "sha256", |
| 389 | dtype: KvDtype::Bf16, |
| 390 | layout, |
| 391 | backend_format: BackendFormat::HostPagedPoolV1, |
| 392 | chunk_tokens: CHUNK as u32, |
| 393 | sharing_namespace: "default", |
| 394 | }, |
| 395 | &engine.identity(), |
| 396 | ) |
| 397 | .expect("fields"); |
| 398 | let identity = KvIdentity::new(&fields).expect("identity"); |
| 399 | let ns = identity.namespace(); |
| 400 | let mut fc = FakeConfig::new(ns); |
| 401 | fc.max_restore_ops = opts.max_restore_ops; |
| 402 | fc.max_park_ops = opts.max_park_ops; |
| 403 | let fake = Arc::new(FakeKvStore::new(fc)); |
| 404 | let gate = Arc::new(Gate::new(fake.clone())); |
| 405 | let drive = { |
| 406 | let fake = fake.clone(); |
| 407 | move || fake.advance(1000) |
| 408 | }; |
| 409 | let worker = Arc::new( |
| 410 | StorageWorker::spawn( |
| 411 | gate.clone(), |
| 412 | WorkerConfig { |
| 413 | max_restore_ops: opts.max_restore_ops, |
| 414 | max_park_ops: opts.max_park_ops, |
| 415 | idle_poll: Duration::from_micros(200), |
| 416 | ..WorkerConfig::default() |
| 417 | }, |
| 418 | drive, |
| 419 | ) |
| 420 | .expect("spawn worker"), |
| 421 | ); |
| 422 | let residency = KvResidency::new( |
| 423 | KvResidencyConfig { |
| 424 | chunk_blocks: CHUNK_BLOCKS, |
| 425 | context_cap: None, |
| 426 | restore_max_blocks: opts.restore_max_blocks, |
| 427 | park: true, |
| 428 | restore: true, |
| 429 | restore_retry_window_ms: 60_000, |
| 430 | drain_ms: 2000, |
| 431 | }, |
| 432 | identity, |
| 433 | worker.clone(), |
| 434 | kv.clone(), |
| 435 | ) |
| 436 | .expect("residency"); |
| 437 | spine.enable_kv_residency(residency); |
| 438 | Store { |
| 439 | fake, |
| 440 | gate, |
| 441 | worker, |
| 442 | ns, |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | fn rig() -> Rig { |
| 447 | rig_with(Opts::default()) |
| 448 | } |
| 449 | |
| 450 | fn st(r: &Rig) -> &Store { |
| 451 | r.store.as_ref().expect("persistence on") |
| 452 | } |
| 453 | |
| 454 | fn status(r: &Rig) -> KvResidencyStatus { |
| 455 | r.spine.kv_residency_status().expect("residency installed") |
| 456 | } |
| 457 | |
| 458 | fn state_of(r: &Rig, seq: u64) -> ResidencyState { |
| 459 | r.spine.kv_residency().expect("residency").residency_of(seq) |
| 460 | } |
| 461 | |
| 462 | fn phase_of(r: &Rig, seq: u64) -> Option<SequencePhase> { |
| 463 | let id = SequenceId::from_u64(seq).ok()?; |
| 464 | r.spine.scheduler.arena().get(id).map(|rec| rec.phase) |
| 465 | } |
| 466 | |
| 467 | fn finished(r: &Rig, seq: u64) -> bool { |
| 468 | phase_of(r, seq).is_none() |
| 469 | } |
| 470 | |
| 471 | fn emitted(r: &Rig, seq: u64) -> usize { |
| 472 | r.tokens.get(&seq).map_or(0, Vec::len) |
| 473 | } |
| 474 | |
| 475 | fn toks(r: &Rig, seq: u64) -> Vec<u32> { |
| 476 | r.tokens.get(&seq).cloned().unwrap_or_default() |
| 477 | } |
| 478 | |
| 479 | fn free_blocks(r: &Rig) -> usize { |
| 480 | r.kv.read().free_block_count() |
| 481 | } |
| 482 | |
| 483 | fn holder_blocks(r: &Rig) -> usize { |
| 484 | r.kv.read().holder_block_count() |
| 485 | } |
| 486 | |
| 487 | fn table(r: &Rig, seq: u64) -> Vec<usize> { |
| 488 | r.kv.read() |
| 489 | .get_block_table(seq) |
| 490 | .map(|t| t.block_ids.clone()) |
| 491 | .unwrap_or_default() |
| 492 | } |
| 493 | |
| 494 | /// Reference count of every block with at least one reference. |
| 495 | fn refcounts(r: &Rig) -> BTreeMap<usize, usize> { |
| 496 | r.kv.read() |
| 497 | .debug_active_blocks() |
| 498 | .into_iter() |
| 499 | .map(|(b, n, _)| (b, n)) |
| 500 | .collect() |
| 501 | } |
| 502 | |
| 503 | /// With no storage holder alive, every block's reference count equals the |
| 504 | /// number of `live` tables that list it, and the free list holds the rest. |
| 505 | fn assert_refcounts_match_tables(r: &Rig, live: &[u64], what: &str) { |
| 506 | assert_eq!(holder_blocks(r), 0, "{what}: holders alive"); |
| 507 | let mut want: BTreeMap<usize, usize> = BTreeMap::new(); |
| 508 | for &s in live { |
| 509 | for b in table(r, s) { |
| 510 | *want.entry(b).or_default() += 1; |
| 511 | } |
| 512 | } |
| 513 | assert_eq!(refcounts(r), want, "{what}: refcounts vs live tables"); |
| 514 | let total = r.kv.read().total_block_count(); |
| 515 | assert_eq!(free_blocks(r), total - want.len(), "{what}: free list"); |
| 516 | } |
| 517 | |
| 518 | fn read_block(r: &Rig, b: usize) -> Vec<u8> { |
| 519 | let kv = r.kv.read(); |
| 520 | let pool = kv.pool().expect("pool"); |
| 521 | let len = pool.block_bytes(); |
| 522 | // SAFETY: test-only read of one in-range pool block while the KV read lock |
| 523 | // is held; the spine does not run on another thread. |
| 524 | unsafe { std::slice::from_raw_parts(pool.base_ptr().add(b * len), len) }.to_vec() |
| 525 | } |
| 526 | |
| 527 | fn read_blocks(r: &Rig, blocks: &[usize]) -> Vec<u8> { |
| 528 | blocks.iter().flat_map(|&b| read_block(r, b)).collect() |
| 529 | } |
| 530 | |
| 531 | /// Byte equality that reports the length and the first differing offset |
| 532 | /// instead of dumping kilobytes. |
| 533 | fn same_bytes(got: &[u8], want: &[u8], what: &str) { |
| 534 | let first = got.iter().zip(want).position(|(a, b)| a != b); |
| 535 | assert!( |
| 536 | got.len() == want.len() && first.is_none(), |
| 537 | "{what}: {} vs {} bytes, first difference at {first:?}", |
| 538 | got.len(), |
| 539 | want.len() |
| 540 | ); |
| 541 | } |
| 542 | |
| 543 | fn keys(r: &Rig, tokens: &[u32]) -> Vec<ChunkKey> { |
| 544 | chunk_chain(&st(r).ns, CHUNK as u32, tokens).expect("chain") |
| 545 | } |
| 546 | |
| 547 | fn payload(r: &Rig, key: &ChunkKey) -> Option<Vec<u8>> { |
| 548 | st(r).fake.payload_of(key) |
| 549 | } |
| 550 | |
| 551 | fn greedy(max_tokens: usize) -> SamplingParams { |
| 552 | SamplingParams { |
| 553 | temperature: 0.0, |
| 554 | top_p: 1.0, |
| 555 | max_tokens, |
| 556 | stop_token_ids: vec![], |
| 557 | } |
| 558 | } |
| 559 | |
| 560 | fn submit(r: &mut Rig, prompt: &[u32], max_tokens: usize) -> u64 { |
| 561 | r.spine |
| 562 | .submit_work( |
| 563 | Arc::from(prompt.to_vec()), |
| 564 | greedy(max_tokens), |
| 565 | 1, |
| 566 | Some(r.sink), |
| 567 | ) |
| 568 | .expect("submit") |
| 569 | } |
| 570 | |
| 571 | fn collect(r: &mut Rig) { |
| 572 | while let Ok(ev) = r.rx.try_recv() { |
| 573 | if let CompletionEvent::Token { seq_id, token } = ev { |
| 574 | r.tokens.entry(seq_id.to_u64()).or_default().push(token); |
| 575 | } |
| 576 | } |
| 577 | } |
| 578 | |
| 579 | /// One spine step, then [`settle`]: a step is counted only once the storage |
| 580 | /// worker has had its turn, so step bounds measure the spine's progress and |
| 581 | /// not how much CPU the OS gave the worker thread. |
| 582 | async fn step(r: &mut Rig) { |
| 583 | r.spine.step(&mut r.backend).await.expect("step"); |
| 584 | r.steps += 1; |
| 585 | settle(r); |
| 586 | collect(r); |
| 587 | } |
| 588 | |
| 589 | /// Waits until a whole pass of the storage worker loop that began after this |
| 590 | /// call handed the store nothing and reaped nothing. The pass sees every job |
| 591 | /// the spine has submitted so far; the fake is driven 1 ms per pass and runs |
| 592 | /// a job in 200 us, so a quiet pass means every job the worker was handed is |
| 593 | /// finished and its completion is waiting for the spine, or is held by the |
| 594 | /// gate, or waits behind a dispatch depth full of held jobs. No-op with |
| 595 | /// persistence off. |
| 596 | fn settle(r: &Rig) { |
| 597 | let Some(s) = r.store.as_ref() else { |
| 598 | return; |
| 599 | }; |
| 600 | // Pass `seen + 1` may have begun before this call; pass `seen + 2` began |
| 601 | // after its poll, so it is the first that surely saw every submission. |
| 602 | let want = s.gate.passes.load(Ordering::SeqCst) + 2; |
| 603 | let t0 = Instant::now(); |
| 604 | while s.gate.quiet.load(Ordering::SeqCst) < want { |
| 605 | assert!( |
| 606 | t0.elapsed() < HANG_GUARD, |
| 607 | "hang guard: storage worker never settled" |
| 608 | ); |
| 609 | std::thread::sleep(Duration::from_micros(50)); |
| 610 | } |
| 611 | } |
| 612 | |
| 613 | /// Steps until `cond` holds, at most `max_steps` steps (the progress bound). |
| 614 | async fn step_until(r: &mut Rig, what: &str, max_steps: u64, cond: impl Fn(&Rig) -> bool) { |
| 615 | let t0 = Instant::now(); |
| 616 | let start = r.steps; |
| 617 | loop { |
| 618 | if cond(r) { |
| 619 | return; |
| 620 | } |
| 621 | assert!( |
| 622 | r.steps - start < max_steps, |
| 623 | "no progress within {max_steps} steps: {what}" |
| 624 | ); |
| 625 | assert!(t0.elapsed() < HANG_GUARD, "hang guard: {what}"); |
| 626 | step(r).await; |
| 627 | } |
| 628 | } |
| 629 | |
| 630 | /// Waits (without stepping) until the worker handed the store `n` held jobs |
| 631 | /// of `kind`. |
| 632 | fn wait_held(r: &Rig, kind: Kind, n: usize) { |
| 633 | let t0 = Instant::now(); |
| 634 | while st(r).gate.held_count(kind) < n { |
| 635 | assert!(t0.elapsed() < HANG_GUARD, "hang guard: {n} held {kind:?}"); |
| 636 | std::thread::sleep(Duration::from_millis(1)); |
| 637 | } |
| 638 | } |
| 639 | |
| 640 | /// Runs `prompt` to its end and waits until every park it caused is terminal. |
| 641 | async fn run_and_park(r: &mut Rig, prompt: &[u32], max_tokens: usize) -> u64 { |
| 642 | let seq = submit(r, prompt, max_tokens); |
| 643 | step_until(r, "turn finished and parks terminal", 500, |r| { |
| 644 | finished(r, seq) && status(r).parking_jobs == 0 |
| 645 | }) |
| 646 | .await; |
| 647 | seq |
| 648 | } |
| 649 | |
| 650 | /// The greedy tokens of `prompt` on a fresh runtime with persistence off. |
| 651 | async fn cold(prompt: &[u32], max_tokens: usize) -> Vec<u32> { |
| 652 | let mut r = rig_with(Opts { |
| 653 | persist: false, |
| 654 | ..Opts::default() |
| 655 | }); |
| 656 | let seq = submit(&mut r, prompt, max_tokens); |
| 657 | step_until(&mut r, "cold run", 500, |r| finished(r, seq)).await; |
| 658 | let t = toks(&r, seq); |
| 659 | assert_eq!(t.len(), max_tokens, "cold run emitted every token"); |
| 660 | t |
| 661 | } |
| 662 | |
| 663 | fn prompt_a() -> Vec<u32> { |
| 664 | vec![5, 17, 42, 3, 88, 61, 9, 23, 70, 11, 36, 2, 44, 19, 80] |
| 665 | } |
| 666 | |
| 667 | fn prompt_b() -> Vec<u32> { |
| 668 | vec![31, 7, 64, 12, 90, 27, 55, 4, 73, 18, 39, 66, 21, 85, 50] |
| 669 | } |
| 670 | |
| 671 | /// Parks `prompt` (15 tokens, `max_tokens = 2`) and returns its 16-token |
| 672 | /// computed prefix: the prompt and its first generated token. |
| 673 | async fn park_prefix(r: &mut Rig, prompt: &[u32]) -> Vec<u32> { |
| 674 | assert_eq!(prompt.len(), 15); |
| 675 | let seq = run_and_park(r, prompt, 2).await; |
| 676 | let mut c = prompt.to_vec(); |
| 677 | c.push(toks(r, seq)[0]); |
| 678 | for k in keys(r, &c) { |
| 679 | assert!(payload(r, &k).is_some(), "prefix chunk published"); |
| 680 | } |
| 681 | c |
| 682 | } |
| 683 | |
| 684 | fn with_suffix(prefix: &[u32], suffix: &[u32]) -> Vec<u32> { |
| 685 | let mut v = prefix.to_vec(); |
| 686 | v.extend_from_slice(suffix); |
| 687 | v |
| 688 | } |
| 689 | |
| 690 | fn unrelated() -> Vec<u32> { |
| 691 | vec![60, 1, 47, 33, 8, 92, 14, 26, 58, 77] |
| 692 | } |
| 693 | |
| 694 | // --------------------------------------------------------------------------- |
| 695 | // B1: slow-I/O progress |
| 696 | // --------------------------------------------------------------------------- |
| 697 | |
| 698 | /// #485 B1 (ADR 6.3 step 2, 8 rule 1): while a restore is stalled at the store |
| 699 | /// (its loads held by the gate), a resident sequence emits one token on every |
| 700 | /// step, and the restoring request is never scheduled. After the gate opens, |
| 701 | /// both outputs equal their cold greedy baselines. |
| 702 | #[tokio::test] |
| 703 | async fn resident_sequence_emits_tokens_before_unrelated_restore_completes() { |
| 704 | let mut r = rig(); |
| 705 | let prefix = park_prefix(&mut r, &prompt_a()).await; |
| 706 | let q_prompt = with_suffix(&prefix, &[13, 29, 51]); |
| 707 | |
| 708 | let resident = submit(&mut r, &unrelated(), 16); |
| 709 | step_until(&mut r, "resident decoding", 50, |r| { |
| 710 | emitted(r, resident) >= 1 |
| 711 | }) |
| 712 | .await; |
| 713 | |
| 714 | st(&r).gate.hold_loads.store(true, Ordering::SeqCst); |
| 715 | let q = submit(&mut r, &q_prompt, 4); |
| 716 | assert_eq!(state_of(&r, q), ResidencyState::Restoring); |
| 717 | wait_held(&r, Kind::Load, 2); |
| 718 | |
| 719 | for i in 0..8 { |
| 720 | let before = emitted(&r, resident); |
| 721 | step(&mut r).await; |
| 722 | assert_eq!( |
| 723 | emitted(&r, resident), |
| 724 | before + 1, |
| 725 | "step {i}: resident emitted while the restore is stalled" |
| 726 | ); |
| 727 | assert_eq!(phase_of(&r, q), Some(SequencePhase::AwaitingRestore)); |
| 728 | assert_eq!(emitted(&r, q), 0, "restoring request scheduled"); |
| 729 | assert_eq!(st(&r).gate.held_count(Kind::Load), 2, "loads still held"); |
| 730 | } |
| 731 | assert!( |
| 732 | emitted(&r, resident) >= 9, |
| 733 | "resident made progress before the restore completed" |
| 734 | ); |
| 735 | |
| 736 | assert_eq!(st(&r).gate.release(Kind::Load), 2); |
| 737 | st(&r).gate.hold_loads.store(false, Ordering::SeqCst); |
| 738 | step_until(&mut r, "both finished, parks terminal", 500, |r| { |
| 739 | finished(r, q) && finished(r, resident) && status(r).parking_jobs == 0 |
| 740 | }) |
| 741 | .await; |
| 742 | |
| 743 | assert_eq!(toks(&r, q), cold(&q_prompt, 4).await, "restored greedy"); |
| 744 | assert_eq!( |
| 745 | toks(&r, resident), |
| 746 | cold(&unrelated(), 16).await, |
| 747 | "resident greedy" |
| 748 | ); |
| 749 | let s = status(&r).stats; |
| 750 | assert_eq!(s.restore_committed_total, 1); |
| 751 | assert_eq!(s.restore_tokens_total, 16); |
| 752 | assert_refcounts_match_tables(&r, &[], "end"); |
| 753 | } |
| 754 | |
| 755 | // --------------------------------------------------------------------------- |
| 756 | // B2: concurrent park and restore of a shared prefix; fork and cancel |
| 757 | // --------------------------------------------------------------------------- |
| 758 | |
| 759 | /// #485 B2 (ADR 5.2, 7.3): a park of a sequence that extends a stored prefix |
| 760 | /// and two restores of that prefix are all in flight at once. The stored |
| 761 | /// prefix bytes are never rewritten (same-key publication dedup), each |
| 762 | /// restored table holds exactly the parked bytes, the coalesced restores share |
| 763 | /// the prefix blocks by reference count, and every count returns to the live |
| 764 | /// tables once the holders are gone. |
| 765 | #[tokio::test] |
| 766 | async fn concurrent_park_and_restore_of_shared_prefix_preserve_bytes_and_refcounts() { |
| 767 | let mut r = rig(); |
| 768 | let prefix = park_prefix(&mut r, &prompt_a()).await; |
| 769 | let pk = keys(&r, &prefix); |
| 770 | let p0 = payload(&r, &pk[0]).expect("chunk 0"); |
| 771 | let p1 = payload(&r, &pk[1]).expect("chunk 1"); |
| 772 | |
| 773 | // S extends the prefix: its own restore runs ungated, then its finish |
| 774 | // parks the new chunks; those stores are held. |
| 775 | let s_prompt = with_suffix(&prefix, &[3, 14, 15, 92, 65, 35, 89, 79]); |
| 776 | st(&r).gate.hold_stores.store(true, Ordering::SeqCst); |
| 777 | let s = submit(&mut r, &s_prompt, 2); |
| 778 | step_until(&mut r, "S finished", 200, |r| finished(r, s)).await; |
| 779 | let s_stats = status(&r).stats; |
| 780 | assert_eq!(s_stats.restore_tokens_total, 16, "S restored the prefix"); |
| 781 | assert_eq!(s_stats.park_dedup_total, 2, "prefix chunks not re-stored"); |
| 782 | // S's computed prefix: 24 prompt tokens + 1 = 25: chunk 2 full, 1-token tail. |
| 783 | wait_held(&r, Kind::Store, 2); |
| 784 | assert_eq!(status(&r).parking_jobs, 2); |
| 785 | |
| 786 | // Two restores of the prefix while S's park is in flight; the second |
| 787 | // attaches to the first's loads. |
| 788 | st(&r).gate.hold_loads.store(true, Ordering::SeqCst); |
| 789 | let q1_prompt = with_suffix(&prefix, &[10, 20, 30]); |
| 790 | let q2_prompt = with_suffix(&prefix, &[40, 50, 60, 70, 80]); |
| 791 | let q1 = submit(&mut r, &q1_prompt, 6); |
| 792 | let q2 = submit(&mut r, &q2_prompt, 6); |
| 793 | wait_held(&r, Kind::Load, 2); |
| 794 | assert_eq!(status(&r).stats.restore_coalesced_total, 2); |
| 795 | for _ in 0..3 { |
| 796 | step(&mut r).await; |
| 797 | assert_eq!(phase_of(&r, q1), Some(SequencePhase::AwaitingRestore)); |
| 798 | assert_eq!(phase_of(&r, q2), Some(SequencePhase::AwaitingRestore)); |
| 799 | } |
| 800 | // Park holders (chunk 2: 2 blocks, tail: 1) and one set of landing |
| 801 | // holders (4 blocks): nothing else is referenced. |
| 802 | assert_eq!(holder_blocks(&r), 7); |
| 803 | assert!(refcounts(&r).values().all(|&n| n == 1)); |
| 804 | assert_eq!(free_blocks(&r), r.kv.read().total_block_count() - 7); |
| 805 | |
| 806 | // Publish S's chunks first, then let the loads land. |
| 807 | assert_eq!(st(&r).gate.release(Kind::Store), 2); |
| 808 | st(&r).gate.hold_stores.store(false, Ordering::SeqCst); |
| 809 | step_until(&mut r, "S parks terminal", 200, |r| { |
| 810 | status(r).parking_jobs == 0 |
| 811 | }) |
| 812 | .await; |
| 813 | assert_eq!(status(&r).stats.park_published_total, 2 + 2); |
| 814 | assert_eq!(st(&r).gate.release(Kind::Load), 2); |
| 815 | st(&r).gate.hold_loads.store(false, Ordering::SeqCst); |
| 816 | step_until(&mut r, "both restores committed", 200, |r| { |
| 817 | status(r).stats.restore_committed_total == 3 |
| 818 | }) |
| 819 | .await; |
| 820 | |
| 821 | let t1 = table(&r, q1); |
| 822 | let t2 = table(&r, q2); |
| 823 | assert_eq!(t1[..4], t2[..4], "coalesced prefix blocks are shared"); |
| 824 | let mut want = p0.clone(); |
| 825 | want.extend_from_slice(&p1); |
| 826 | same_bytes( |
| 827 | &read_blocks(&r, &t1[..4]), |
| 828 | &want, |
| 829 | "q1 holds the parked bytes", |
| 830 | ); |
| 831 | let rc = refcounts(&r); |
| 832 | for b in &t1[..4] { |
| 833 | assert_eq!(rc[b], 2, "prefix block {b} shared by exactly q1 and q2"); |
| 834 | } |
| 835 | for b in t1[4..].iter().chain(&t2[4..]) { |
| 836 | assert_eq!(rc[b], 1, "suffix block {b} owned by one request"); |
| 837 | } |
| 838 | assert_refcounts_match_tables(&r, &[q1, q2], "after commit"); |
| 839 | |
| 840 | step_until(&mut r, "q1 q2 finished, parks terminal", 500, |r| { |
| 841 | finished(r, q1) && finished(r, q2) && status(r).parking_jobs == 0 |
| 842 | }) |
| 843 | .await; |
| 844 | assert_eq!(toks(&r, q1), cold(&q1_prompt, 6).await, "q1 greedy"); |
| 845 | assert_eq!(toks(&r, q2), cold(&q2_prompt, 6).await, "q2 greedy"); |
| 846 | same_bytes( |
| 847 | &payload(&r, &pk[0]).expect("published"), |
| 848 | &p0, |
| 849 | "chunk 0 never rewritten", |
| 850 | ); |
| 851 | same_bytes( |
| 852 | &payload(&r, &pk[1]).expect("published"), |
| 853 | &p1, |
| 854 | "chunk 1 never rewritten", |
| 855 | ); |
| 856 | |
| 857 | // S's own chunk 2 (published while the loads were in flight) restores to |
| 858 | // the same greedy continuation as a cold run. |
| 859 | let t_prompt = with_suffix(&s_prompt, &[11, 22, 33]); |
| 860 | let t = submit(&mut r, &t_prompt, 3); |
| 861 | step_until(&mut r, "t finished", 200, |r| finished(r, t)).await; |
| 862 | assert_eq!(status(&r).stats.restore_tokens_total, 16 * 3 + 24); |
| 863 | assert_eq!(toks(&r, t), cold(&t_prompt, 3).await, "t greedy"); |
| 864 | step_until(&mut r, "parks terminal", 200, |r| { |
| 865 | status(r).parking_jobs == 0 |
| 866 | }) |
| 867 | .await; |
| 868 | assert_refcounts_match_tables(&r, &[], "end"); |
| 869 | } |
| 870 | |
| 871 | /// #485 B2 (ADR 5.2, 5.5): a child is forked from a running parent; the |
| 872 | /// parent finishes and its park forks storage holders over blocks the child |
| 873 | /// shares; the park is cancelled at the store while the child decodes. The |
| 874 | /// child keeps its blocks and their bytes, decodes every step, and its output |
| 875 | /// equals the same fork run with persistence off; nothing is published. |
| 876 | #[tokio::test] |
| 877 | async fn fork_then_cancel_parent_during_park_keeps_child_valid() { |
| 878 | async fn fork_run(r: &mut Rig) -> (u64, u64) { |
| 879 | let parent = submit(r, &prompt_b(), 3); |
| 880 | step_until(r, "parent prefilled", 50, |r| emitted(r, parent) >= 1).await; |
| 881 | r.spine |
| 882 | .fork_subagent(parent, 0, Some(r.sink)) |
| 883 | .expect("fork"); |
| 884 | let child = r |
| 885 | .spine |
| 886 | .scheduler |
| 887 | .arena() |
| 888 | .active_ids() |
| 889 | .into_iter() |
| 890 | .find(|&id| { |
| 891 | r.spine |
| 892 | .scheduler |
| 893 | .arena() |
| 894 | .get(id) |
| 895 | .is_some_and(|rec| rec.branch_parent.map(|p| p.to_u64()) == Some(parent)) |
| 896 | }) |
| 897 | .expect("child") |
| 898 | .to_u64(); |
| 899 | r.spine |
| 900 | .scheduler |
| 901 | .arena_mut() |
| 902 | .get_mut(SequenceId::from_u64(child).unwrap()) |
| 903 | .expect("child record") |
| 904 | .sampling_params |
| 905 | .max_tokens = 10; |
| 906 | (parent, child) |
| 907 | } |
| 908 | |
| 909 | // Baseline: the same fork with persistence off. |
| 910 | let mut base = rig_with(Opts { |
| 911 | persist: false, |
| 912 | ..Opts::default() |
| 913 | }); |
| 914 | let (bp, bc) = fork_run(&mut base).await; |
| 915 | step_until(&mut base, "baseline finished", 200, |r| { |
| 916 | finished(r, bp) && finished(r, bc) |
| 917 | }) |
| 918 | .await; |
| 919 | let want_child = toks(&base, bc); |
| 920 | assert!(want_child.len() >= 8, "baseline child decoded"); |
| 921 | |
| 922 | let mut r = rig(); |
| 923 | st(&r).gate.hold_stores.store(true, Ordering::SeqCst); |
| 924 | let (parent, child) = fork_run(&mut r).await; |
| 925 | step_until(&mut r, "parent finished", 50, |r| finished(r, parent)).await; |
| 926 | assert!(!finished(&r, child)); |
| 927 | // Parent computed prefix: 15 + 2 = 17: two full chunks and a 1-token tail. |
| 928 | wait_held(&r, Kind::Store, 3); |
| 929 | assert_eq!(status(&r).parking_jobs, 3); |
| 930 | |
| 931 | // The 15-token prompt fills blocks 0 to 2 and 3 tokens of block 3. The |
| 932 | // first decode after the fork wrote into the shared partial block 3, which |
| 933 | // copied on write (ADR 5.2), so the child shares the full blocks 0 to 2 |
| 934 | // with the parent's park holders and owns its block 3 alone. |
| 935 | let child_table = table(&r, child); |
| 936 | let shared = &child_table[..3]; |
| 937 | let rc = refcounts(&r); |
| 938 | for b in shared { |
| 939 | assert_eq!(rc[b], 2, "block {b}: child and one park holder"); |
| 940 | } |
| 941 | assert_eq!(rc[&child_table[3]], 1, "child's own copy of block 3"); |
| 942 | let before = read_blocks(&r, shared); |
| 943 | |
| 944 | // The child decodes while the park is held. |
| 945 | for _ in 0..2 { |
| 946 | let n = emitted(&r, child); |
| 947 | step(&mut r).await; |
| 948 | assert_eq!(emitted(&r, child), n + 1, "child progress during park"); |
| 949 | } |
| 950 | |
| 951 | // Cancel the parent's park mid-transfer. |
| 952 | assert_eq!(st(&r).gate.cancel(Kind::Store), 3); |
| 953 | st(&r).gate.hold_stores.store(false, Ordering::SeqCst); |
| 954 | step_until(&mut r, "park cancelled", 50, |r| { |
| 955 | status(r).parking_jobs == 0 |
| 956 | }) |
| 957 | .await; |
| 958 | let s = status(&r).stats; |
| 959 | assert_eq!(s.park_failed_total, 3, "cancelled parks count as failed"); |
| 960 | assert_eq!(s.park_published_total, 0); |
| 961 | let ck = keys(&r, &prompt_b()); |
| 962 | assert!(payload(&r, &ck[0]).is_none(), "nothing published"); |
| 963 | assert!(!finished(&r, child), "child still running"); |
| 964 | assert_eq!(table(&r, child)[..3], *shared, "child kept its blocks"); |
| 965 | same_bytes(&read_blocks(&r, shared), &before, "child bytes unchanged"); |
| 966 | assert_refcounts_match_tables(&r, &[child], "after cancel"); |
| 967 | |
| 968 | step_until(&mut r, "child finished, parks terminal", 200, |r| { |
| 969 | finished(r, child) && status(r).parking_jobs == 0 |
| 970 | }) |
| 971 | .await; |
| 972 | assert_eq!(toks(&r, child), want_child, "child greedy unaffected"); |
| 973 | assert_refcounts_match_tables(&r, &[], "end"); |
| 974 | } |
| 975 | |
| 976 | // --------------------------------------------------------------------------- |
| 977 | // B3: duplicate loads; finding 6: coalesced waiters |
| 978 | // --------------------------------------------------------------------------- |
| 979 | |
| 980 | /// #485 B3 (ADR 7.3): two identical requests restoring the same stored prefix |
| 981 | /// at the same time cause one load per chunk, not two; both get the restored |
| 982 | /// prefix and the cold greedy continuation. |
| 983 | #[tokio::test] |
| 984 | async fn duplicate_restore_requests_share_one_load() { |
| 985 | let mut r = rig(); |
| 986 | let prefix = park_prefix(&mut r, &prompt_a()).await; |
| 987 | let q_prompt = with_suffix(&prefix, &[13, 29, 51]); |
| 988 | let reads_before = st(&r).fake.stats().reads; |
| 989 | let loads_before = st(&r).gate.seen_count(Kind::Load); |
| 990 | |
| 991 | st(&r).gate.hold_loads.store(true, Ordering::SeqCst); |
| 992 | let a = submit(&mut r, &q_prompt, 4); |
| 993 | let b = submit(&mut r, &q_prompt, 4); |
| 994 | assert_eq!(state_of(&r, a), ResidencyState::Restoring); |
| 995 | assert_eq!(state_of(&r, b), ResidencyState::Restoring); |
| 996 | wait_held(&r, Kind::Load, 2); |
| 997 | let s = status(&r).stats; |
| 998 | assert_eq!(s.restore_coalesced_total, 2, "b attached to a's loads"); |
| 999 | assert_eq!(st(&r).worker.stats().coalesced_total, 2); |
| 1000 | |
| 1001 | st(&r).gate.release(Kind::Load); |
| 1002 | st(&r).gate.hold_loads.store(false, Ordering::SeqCst); |
| 1003 | step_until(&mut r, "both finished, parks terminal", 300, |r| { |
| 1004 | finished(r, a) && finished(r, b) && status(r).parking_jobs == 0 |
| 1005 | }) |
| 1006 | .await; |
| 1007 | |
| 1008 | assert_eq!( |
| 1009 | st(&r).gate.seen_count(Kind::Load) - loads_before, |
| 1010 | 2, |
| 1011 | "one load per chunk" |
| 1012 | ); |
| 1013 | assert_eq!( |
| 1014 | st(&r).fake.stats().reads - reads_before, |
| 1015 | 2, |
| 1016 | "one read per chunk" |
| 1017 | ); |
| 1018 | let want = cold(&q_prompt, 4).await; |
| 1019 | assert_eq!(toks(&r, a), want); |
| 1020 | assert_eq!(toks(&r, b), want); |
| 1021 | let s = status(&r).stats; |
| 1022 | assert_eq!(s.restore_committed_total, 2); |
| 1023 | assert_eq!(s.restore_tokens_total, 32); |
| 1024 | assert_refcounts_match_tables(&r, &[], "end"); |
| 1025 | } |
| 1026 | |
| 1027 | /// Late attach (C8 surviving mutant): the second request arrives only after |
| 1028 | /// the first request's loads were dispatched to the store and are held there. |
| 1029 | /// It attaches to the in-flight loads (never a third read), both requests get |
| 1030 | /// the cold greedy output, and the attached-waiter count on each landing is |
| 1031 | /// released with the terminals: no landing is left behind. |
| 1032 | #[tokio::test] |
| 1033 | async fn late_attach_after_dispatch_shares_the_load_and_releases_its_landing() { |
| 1034 | let mut r = rig(); |
| 1035 | let prefix = park_prefix(&mut r, &prompt_a()).await; |
| 1036 | let q_prompt = with_suffix(&prefix, &[13, 29, 51]); |
| 1037 | let reads_before = st(&r).fake.stats().reads; |
| 1038 | let loads_before = st(&r).gate.seen_count(Kind::Load); |
| 1039 | // The park run itself was a plain prefill (counted as a fallback). |
| 1040 | let fallback_before = status(&r).stats.restore_fallback_prefill_total; |
| 1041 | |
| 1042 | st(&r).gate.hold_loads.store(true, Ordering::SeqCst); |
| 1043 | let a = submit(&mut r, &q_prompt, 4); |
| 1044 | assert_eq!(state_of(&r, a), ResidencyState::Restoring); |
| 1045 | // Both loads are at the store (held) before b exists. |
| 1046 | wait_held(&r, Kind::Load, 2); |
| 1047 | assert_eq!(status(&r).stats.restore_coalesced_total, 0); |
| 1048 | assert_eq!( |
| 1049 | status(&r).landing_waiters, |
| 1050 | 2, |
| 1051 | "one waiter (the opener) per in-flight load" |
| 1052 | ); |
| 1053 | |
| 1054 | let b = submit(&mut r, &q_prompt, 4); |
| 1055 | assert_eq!(state_of(&r, b), ResidencyState::Restoring); |
| 1056 | let s = status(&r).stats; |
| 1057 | assert_eq!(s.restore_coalesced_total, 2, "b attached late to a's loads"); |
| 1058 | assert_eq!(st(&r).worker.stats().coalesced_total, 2); |
| 1059 | assert_eq!( |
| 1060 | st(&r).gate.seen_count(Kind::Load) - loads_before, |
| 1061 | 2, |
| 1062 | "no new load for b" |
| 1063 | ); |
| 1064 | assert_eq!( |
| 1065 | status(&r).landing_waiters, |
| 1066 | 4, |
| 1067 | "the late attach adds one waiter to each of the two loads" |
| 1068 | ); |
| 1069 | |
| 1070 | st(&r).gate.release(Kind::Load); |
| 1071 | st(&r).gate.hold_loads.store(false, Ordering::SeqCst); |
| 1072 | step_until(&mut r, "both finished, parks terminal", 300, |r| { |
| 1073 | finished(r, a) && finished(r, b) && status(r).parking_jobs == 0 |
| 1074 | }) |
| 1075 | .await; |
| 1076 | |
| 1077 | assert_eq!( |
| 1078 | st(&r).fake.stats().reads - reads_before, |
| 1079 | 2, |
| 1080 | "one read per chunk" |
| 1081 | ); |
| 1082 | let want = cold(&q_prompt, 4).await; |
| 1083 | assert_eq!(toks(&r, a), want); |
| 1084 | assert_eq!(toks(&r, b), want); |
| 1085 | let s = status(&r).stats; |
| 1086 | assert_eq!(s.restore_committed_total, 2); |
| 1087 | assert_eq!( |
| 1088 | s.restore_fallback_prefill_total, fallback_before, |
| 1089 | "neither fell back" |
| 1090 | ); |
| 1091 | assert_eq!( |
| 1092 | status(&r).landing_waiters, |
| 1093 | 0, |
| 1094 | "every landing released once its opener and its late waiter saw a terminal" |
| 1095 | ); |
| 1096 | assert_eq!(st(&r).worker.stats().stale_completions_total, 0); |
| 1097 | assert_refcounts_match_tables(&r, &[], "end"); |
| 1098 | } |
| 1099 | |
| 1100 | /// Review finding 6 (ADR 7.3): coalescing happens at the landing buffer, never |
| 1101 | /// at the request table. Two requests with the same stored prefix and |
| 1102 | /// different suffixes share the prefix blocks by reference count, each owns |
| 1103 | /// its suffix blocks, and finishing one leaves the other's table, bytes and |
| 1104 | /// greedy output intact. |
| 1105 | #[tokio::test] |
| 1106 | async fn coalesced_waiters_with_different_suffixes_get_independent_tables() { |
| 1107 | let mut r = rig(); |
| 1108 | let prefix = park_prefix(&mut r, &prompt_a()).await; |
| 1109 | let pk = keys(&r, &prefix); |
| 1110 | let mut parked = payload(&r, &pk[0]).expect("chunk 0"); |
| 1111 | parked.extend(payload(&r, &pk[1]).expect("chunk 1")); |
| 1112 | let short_prompt = with_suffix(&prefix, &[10, 20, 30]); |
| 1113 | let long_prompt = with_suffix(&prefix, &[40, 50, 60, 70, 80, 90, 7]); |
| 1114 | |
| 1115 | st(&r).gate.hold_loads.store(true, Ordering::SeqCst); |
| 1116 | let short = submit(&mut r, &short_prompt, 2); |
| 1117 | let long = submit(&mut r, &long_prompt, 8); |
| 1118 | wait_held(&r, Kind::Load, 2); |
| 1119 | assert_eq!(status(&r).stats.restore_coalesced_total, 2); |
| 1120 | st(&r).gate.release(Kind::Load); |
| 1121 | st(&r).gate.hold_loads.store(false, Ordering::SeqCst); |
| 1122 | step_until(&mut r, "both committed", 200, |r| { |
| 1123 | status(r).stats.restore_committed_total == 2 |
| 1124 | }) |
| 1125 | .await; |
| 1126 | |
| 1127 | let ts = table(&r, short); |
| 1128 | let tl = table(&r, long); |
| 1129 | assert_eq!(ts[..4], tl[..4], "prefix blocks shared"); |
| 1130 | same_bytes(&read_blocks(&r, &ts[..4]), &parked, "parked bytes restored"); |
| 1131 | for b in &ts[4..] { |
| 1132 | assert!(!tl.contains(b), "suffix block {b} shared between requests"); |
| 1133 | } |
| 1134 | let rc = refcounts(&r); |
| 1135 | for b in &ts[..4] { |
| 1136 | assert_eq!(rc[b], 2, "prefix block {b}: one reference per request"); |
| 1137 | } |
| 1138 | assert_refcounts_match_tables(&r, &[short, long], "after commit"); |
| 1139 | |
| 1140 | step_until(&mut r, "short finished", 100, |r| finished(r, short)).await; |
| 1141 | assert!(!finished(&r, long), "long still decoding"); |
| 1142 | let tl_now = table(&r, long); |
| 1143 | assert_eq!(tl_now[..4], tl[..4], "long kept the shared prefix blocks"); |
| 1144 | same_bytes( |
| 1145 | &read_blocks(&r, &tl_now[..4]), |
| 1146 | &parked, |
| 1147 | "long's prefix bytes", |
| 1148 | ); |
| 1149 | step_until(&mut r, "parks of short terminal", 200, |r| { |
| 1150 | status(r).parking_jobs == 0 |
| 1151 | }) |
| 1152 | .await; |
| 1153 | assert_refcounts_match_tables(&r, &[long], "after short finished"); |
| 1154 | |
| 1155 | step_until(&mut r, "long finished, parks terminal", 300, |r| { |
| 1156 | finished(r, long) && status(r).parking_jobs == 0 |
| 1157 | }) |
| 1158 | .await; |
| 1159 | assert_eq!( |
| 1160 | toks(&r, short), |
| 1161 | cold(&short_prompt, 2).await, |
| 1162 | "short greedy" |
| 1163 | ); |
| 1164 | assert_eq!(toks(&r, long), cold(&long_prompt, 8).await, "long greedy"); |
| 1165 | assert_ne!( |
| 1166 | toks(&r, short)[..2], |
| 1167 | toks(&r, long)[..2], |
| 1168 | "suffixes diverge" |
| 1169 | ); |
| 1170 | assert_refcounts_match_tables(&r, &[], "end"); |
| 1171 | } |
| 1172 | |
| 1173 | // --------------------------------------------------------------------------- |
| 1174 | // B4: memory pressure; B3 + B4: queue-full and disk-full under load |
| 1175 | // --------------------------------------------------------------------------- |
| 1176 | |
| 1177 | /// #485 B4 (ADR 7.1): a 20-block pool against about 39 blocks of offered work, |
| 1178 | /// a restore block budget of two restores, four restore and two park store |
| 1179 | /// operations, and restore loads held at first. Resident requests and |
| 1180 | /// restoring requests all finish within a bounded number of steps, each with |
| 1181 | /// its cold greedy output; the restore budget is never exceeded; every block |
| 1182 | /// and holder comes back. |
| 1183 | /// |
| 1184 | /// Two running sequences at a time (`max_batch_size = 2`) keep the scheduler |
| 1185 | /// from preempting, so every greedy comparison here is about restores, not |
| 1186 | /// resumes. The test asserts that no preemption happened. Resume after |
| 1187 | /// preemption has its own test below |
| 1188 | /// (`preempted_sequence_resumes_without_re_emitting_tokens`). |
| 1189 | #[tokio::test] |
| 1190 | async fn memory_pressure_restore_and_admission_make_progress_without_deadlock() { |
| 1191 | let opts = Opts { |
| 1192 | total_blocks: 20, |
| 1193 | watermark_blocks: 2, |
| 1194 | restore_max_blocks: 8, |
| 1195 | max_restore_ops: 4, |
| 1196 | max_park_ops: 2, |
| 1197 | max_batch_size: 2, |
| 1198 | ..Opts::default() |
| 1199 | }; |
| 1200 | let mut r = rig_with(opts.clone()); |
| 1201 | let pa = park_prefix(&mut r, &prompt_a()).await; |
| 1202 | let pb = park_prefix(&mut r, &prompt_b()).await; |
| 1203 | |
| 1204 | let mut work: Vec<(Vec<u32>, usize)> = Vec::new(); |
| 1205 | for i in 0..3u32 { |
| 1206 | let p: Vec<u32> = (0..12).map(|t| (t * 7 + i * 13 + 1) % 97).collect(); |
| 1207 | work.push((p, 8)); |
| 1208 | } |
| 1209 | for (i, base) in [&pa, &pb, &pa, &pb].iter().enumerate() { |
| 1210 | let i = i as u32; |
| 1211 | work.push((with_suffix(base, &[i + 1, i + 40, i + 70]), 4)); |
| 1212 | } |
| 1213 | |
| 1214 | st(&r).gate.hold_loads.store(true, Ordering::SeqCst); |
| 1215 | let mut seqs = Vec::new(); |
| 1216 | for (p, n) in &work { |
| 1217 | seqs.push(submit(&mut r, p, *n)); |
| 1218 | } |
| 1219 | let restoring = status(&r).restoring; |
| 1220 | assert!(restoring >= 1, "some restore started"); |
| 1221 | let mut peak_restore_blocks = status(&r).restore_inflight_blocks; |
| 1222 | let mut min_free = free_blocks(&r); |
| 1223 | // While the loads are held, the plain requests still make progress. |
| 1224 | let emitted_plain = |r: &Rig| seqs[..3].iter().map(|&s| emitted(r, s)).sum::<usize>(); |
| 1225 | let before = emitted_plain(&r); |
| 1226 | for _ in 0..5 { |
| 1227 | step(&mut r).await; |
| 1228 | peak_restore_blocks = peak_restore_blocks.max(status(&r).restore_inflight_blocks); |
| 1229 | min_free = min_free.min(free_blocks(&r)); |
| 1230 | } |
| 1231 | assert!( |
| 1232 | emitted_plain(&r) >= before + 5, |
| 1233 | "plain requests progressed while restores were stalled" |
| 1234 | ); |
| 1235 | st(&r).gate.hold_loads.store(false, Ordering::SeqCst); |
| 1236 | st(&r).gate.release(Kind::Load); |
| 1237 | |
| 1238 | let t0 = Instant::now(); |
| 1239 | let start = r.steps; |
| 1240 | while !(seqs.iter().all(|&s| finished(&r, s)) && status(&r).parking_jobs == 0) { |
| 1241 | assert!( |
| 1242 | r.steps - start < 2000, |
| 1243 | "no progress within 2000 steps (deadlock): {:?}", |
| 1244 | status(&r) |
| 1245 | ); |
| 1246 | assert!(t0.elapsed() < HANG_GUARD, "hang guard"); |
| 1247 | step(&mut r).await; |
| 1248 | peak_restore_blocks = peak_restore_blocks.max(status(&r).restore_inflight_blocks); |
| 1249 | min_free = min_free.min(free_blocks(&r)); |
| 1250 | } |
| 1251 | |
| 1252 | assert_eq!( |
| 1253 | r.spine.scheduler.metrics().preempted_requests, |
| 1254 | 0, |
| 1255 | "no preemption (see the doc comment)" |
| 1256 | ); |
| 1257 | assert!( |
| 1258 | min_free <= opts.watermark_blocks + 4, |
| 1259 | "the pool was under pressure: lowest free count {min_free}" |
| 1260 | ); |
| 1261 | assert!( |
| 1262 | peak_restore_blocks <= opts.restore_max_blocks, |
| 1263 | "restore budget exceeded: {peak_restore_blocks}" |
| 1264 | ); |
| 1265 | for (i, (p, n)) in work.iter().enumerate() { |
| 1266 | assert_eq!(toks(&r, seqs[i]), cold(p, *n).await, "request {i} greedy"); |
| 1267 | } |
| 1268 | let s = status(&r).stats; |
| 1269 | assert!( |
| 1270 | s.restore_committed_total >= 1, |
| 1271 | "some restore committed: {s:?}" |
| 1272 | ); |
| 1273 | assert_eq!( |
| 1274 | s.restore_committed_total + s.restore_fallback_prefill_total, |
| 1275 | 4 + 3 + 2, |
| 1276 | "every request either restored or prefilled: {s:?}" |
| 1277 | ); |
| 1278 | assert_eq!(st(&r).worker.stats().completion_overflow_total, 0); |
| 1279 | assert_refcounts_match_tables(&r, &[], "end"); |
| 1280 | } |
| 1281 | |
| 1282 | fn prompt_c() -> Vec<u32> { |
| 1283 | (0..15).map(|t| (t * 11 + 3) % 97).collect() |
| 1284 | } |
| 1285 | |
| 1286 | fn prompt_d() -> Vec<u32> { |
| 1287 | (0..15).map(|t| (t * 13 + 6) % 97).collect() |
| 1288 | } |
| 1289 | |
| 1290 | fn prompt_e() -> Vec<u32> { |
| 1291 | (0..15).map(|t| (t * 17 + 9) % 97).collect() |
| 1292 | } |
| 1293 | |
| 1294 | /// #485 B3 + B4 (ADR 7.1, 7.4; #484 A4): two park operations allowed and both |
| 1295 | /// held, so the next turn's parks are refused with `QueueFull`; two restore |
| 1296 | /// operations allowed and both held, so a second restore is a plain prefill; |
| 1297 | /// then the disk is full and every park write fails. Throughout, a resident |
| 1298 | /// sequence emits one token per step, and objects published before stay |
| 1299 | /// served. Every output equals its cold greedy baseline and no holder or block |
| 1300 | /// leaks. |
| 1301 | #[tokio::test] |
| 1302 | async fn queue_full_and_disk_full_under_load_never_lose_resident_progress() { |
| 1303 | let mut r = rig_with(Opts { |
| 1304 | max_restore_ops: 2, |
| 1305 | max_park_ops: 2, |
| 1306 | ..Opts::default() |
| 1307 | }); |
| 1308 | let pa = park_prefix(&mut r, &prompt_a()).await; |
| 1309 | let pb = park_prefix(&mut r, &prompt_b()).await; |
| 1310 | let pk = keys(&r, &pa); |
| 1311 | let p0 = payload(&r, &pk[0]).expect("chunk 0"); |
| 1312 | |
| 1313 | let resident = submit(&mut r, &unrelated(), 40); |
| 1314 | step_until(&mut r, "resident decoding", 50, |r| { |
| 1315 | emitted(r, resident) >= 1 |
| 1316 | }) |
| 1317 | .await; |
| 1318 | let mut n; |
| 1319 | |
| 1320 | // Park queue full: p1's two parks are held and take both park slots; |
| 1321 | // p2's two parks are refused at submit and their holders released. |
| 1322 | st(&r).gate.hold_stores.store(true, Ordering::SeqCst); |
| 1323 | let p1 = submit(&mut r, &prompt_c(), 2); |
| 1324 | step_until(&mut r, "p1 finished", 50, |r| finished(r, p1)).await; |
| 1325 | wait_held(&r, Kind::Store, 2); |
| 1326 | let before = status(&r).stats; |
| 1327 | let p2 = submit(&mut r, &prompt_d(), 2); |
| 1328 | n = emitted(&r, resident); |
| 1329 | step_until(&mut r, "p2 finished", 50, |r| finished(r, p2)).await; |
| 1330 | assert!(emitted(&r, resident) > n, "resident progressed"); |
| 1331 | let s = status(&r).stats; |
| 1332 | assert_eq!(s.store_queue_full_total, before.store_queue_full_total + 2); |
| 1333 | assert_eq!(s.park_failed_total, before.park_failed_total + 2); |
| 1334 | assert_eq!(status(&r).parking_jobs, 2, "only p1's held parks in flight"); |
| 1335 | assert_eq!(holder_blocks(&r), 4, "p2's refused holders released"); |
| 1336 | for _ in 0..3 { |
| 1337 | n = emitted(&r, resident); |
| 1338 | step(&mut r).await; |
| 1339 | assert_eq!( |
| 1340 | emitted(&r, resident), |
| 1341 | n + 1, |
| 1342 | "resident while park queue full" |
| 1343 | ); |
| 1344 | } |
| 1345 | |
| 1346 | // Restore queue full: qa's two loads are held and take both restore |
| 1347 | // slots; qb (another stored prefix) is refused and prefills plainly. |
| 1348 | st(&r).gate.hold_loads.store(true, Ordering::SeqCst); |
| 1349 | let qa_prompt = with_suffix(&pa, &[13, 29, 51]); |
| 1350 | let qa = submit(&mut r, &qa_prompt, 3); |
| 1351 | assert_eq!(state_of(&r, qa), ResidencyState::Restoring); |
| 1352 | wait_held(&r, Kind::Load, 2); |
| 1353 | let before = status(&r).stats; |
| 1354 | let qb_prompt = with_suffix(&pb, &[4, 8, 15]); |
| 1355 | let qb = submit(&mut r, &qb_prompt, 3); |
| 1356 | assert_eq!( |
| 1357 | state_of(&r, qb), |
| 1358 | ResidencyState::Resident, |
| 1359 | "qb not restoring" |
| 1360 | ); |
| 1361 | let s = status(&r).stats; |
| 1362 | assert_eq!( |
| 1363 | s.restore_fallback_prefill_total, |
| 1364 | before.restore_fallback_prefill_total + 1 |
| 1365 | ); |
| 1366 | assert!(s.store_queue_full_total > before.store_queue_full_total); |
| 1367 | n = emitted(&r, resident); |
| 1368 | step_until(&mut r, "qb finished", 100, |r| finished(r, qb)).await; |
| 1369 | assert!(emitted(&r, resident) > n, "resident progressed"); |
| 1370 | assert_eq!(phase_of(&r, qa), Some(SequencePhase::AwaitingRestore)); |
| 1371 | |
| 1372 | // Disk full: every park submitted from now on fails at its write. p1's |
| 1373 | // held parks were accepted before and publish when released. |
| 1374 | st(&r).gate.disk_full.store(true, Ordering::SeqCst); |
| 1375 | st(&r).gate.hold_stores.store(false, Ordering::SeqCst); |
| 1376 | assert_eq!(st(&r).gate.release(Kind::Store), 2); |
| 1377 | st(&r).gate.hold_loads.store(false, Ordering::SeqCst); |
| 1378 | assert_eq!(st(&r).gate.release(Kind::Load), 2); |
| 1379 | step_until(&mut r, "p1's parks published", 100, |r| { |
| 1380 | status(r).parking_jobs == 0 |
| 1381 | }) |
| 1382 | .await; |
| 1383 | let failed = status(&r).stats.park_failed_total; |
| 1384 | let disk_full = st(&r).fake.stats().disk_full_total; |
| 1385 | let p3 = submit(&mut r, &prompt_e(), 2); |
| 1386 | step_until(&mut r, "p3 and qa finished, parks terminal", 300, |r| { |
| 1387 | finished(r, p3) && finished(r, qa) && finished(r, qb) && status(r).parking_jobs == 0 |
| 1388 | }) |
| 1389 | .await; |
| 1390 | let s = status(&r).stats; |
| 1391 | assert!( |
| 1392 | s.park_failed_total >= failed + 2, |
| 1393 | "disk-full parks failed: {s:?}" |
| 1394 | ); |
| 1395 | assert!(st(&r).fake.stats().disk_full_total >= disk_full + 2); |
| 1396 | let mut p3_computed = prompt_e(); |
| 1397 | p3_computed.push(toks(&r, p3)[0]); |
| 1398 | for k in keys(&r, &p3_computed) { |
| 1399 | assert!( |
| 1400 | payload(&r, &k).is_none(), |
| 1401 | "nothing published on a full disk" |
| 1402 | ); |
| 1403 | } |
| 1404 | same_bytes( |
| 1405 | &payload(&r, &pk[0]).expect("published"), |
| 1406 | &p0, |
| 1407 | "earlier object intact", |
| 1408 | ); |
| 1409 | assert_eq!(s.restore_committed_total, 1, "qa restored: {s:?}"); |
| 1410 | |
| 1411 | // The last usable KV is still served after the full disk. |
| 1412 | st(&r).gate.disk_full.store(false, Ordering::SeqCst); |
| 1413 | let qc_prompt = with_suffix(&pa, &[77, 66, 55]); |
| 1414 | let qc = submit(&mut r, &qc_prompt, 3); |
| 1415 | assert_eq!(state_of(&r, qc), ResidencyState::Restoring); |
| 1416 | step_until(&mut r, "resident, qc finished; parks terminal", 500, |r| { |
| 1417 | finished(r, qc) && finished(r, resident) && status(r).parking_jobs == 0 |
| 1418 | }) |
| 1419 | .await; |
| 1420 | assert_eq!(status(&r).stats.restore_committed_total, 2, "qc restored"); |
| 1421 | |
| 1422 | assert_eq!(toks(&r, resident), cold(&unrelated(), 40).await, "resident"); |
| 1423 | assert_eq!(toks(&r, p1), cold(&prompt_c(), 2).await, "p1"); |
| 1424 | assert_eq!(toks(&r, p2), cold(&prompt_d(), 2).await, "p2"); |
| 1425 | assert_eq!(toks(&r, qa), cold(&qa_prompt, 3).await, "qa"); |
| 1426 | assert_eq!(toks(&r, qb), cold(&qb_prompt, 3).await, "qb"); |
| 1427 | assert_eq!(toks(&r, p3), cold(&prompt_e(), 2).await, "p3"); |
| 1428 | assert_eq!(toks(&r, qc), cold(&qc_prompt, 3).await, "qc"); |
| 1429 | assert_refcounts_match_tables(&r, &[], "end"); |
| 1430 | } |
| 1431 | |
| 1432 | // --------------------------------------------------------------------------- |
| 1433 | // Preemption under KV pressure with persistence off: resume must not re-emit |
| 1434 | // --------------------------------------------------------------------------- |
| 1435 | |
| 1436 | /// A sequence preempted by the watermark check and resumed later must deliver |
| 1437 | /// every token to its sink exactly once, and its output must equal a run that |
| 1438 | /// was never preempted. Persistence is off (no store, no worker): this is pure |
| 1439 | /// scheduler behaviour. |
| 1440 | /// |
| 1441 | /// Geometry: a 10-block pool with a watermark of 3. Request A (15-token |
| 1442 | /// prompt, 4 blocks) decodes alone for a few steps. Request B (another 4 |
| 1443 | /// blocks) is admitted while 3 or more blocks are free, which leaves fewer |
| 1444 | /// than the watermark, so the next step preempts A (the lowest-priority |
| 1445 | /// running sequence, first in running order). A needs 4 blocks plus the |
| 1446 | /// watermark headroom to come back, so it resumes only after B finishes. |
| 1447 | #[tokio::test] |
| 1448 | async fn preempted_sequence_resumes_without_re_emitting_tokens() { |
| 1449 | let max_a = 12; |
| 1450 | let max_b = 4; |
| 1451 | let want_a = cold(&prompt_a(), max_a).await; |
| 1452 | let want_b = cold(&prompt_b(), max_b).await; |
| 1453 | |
| 1454 | let mut r = rig_with(Opts { |
| 1455 | persist: false, |
| 1456 | total_blocks: 10, |
| 1457 | watermark_blocks: 3, |
| 1458 | max_batch_size: 4, |
| 1459 | ..Opts::default() |
| 1460 | }); |
| 1461 | let a = submit(&mut r, &prompt_a(), max_a); |
| 1462 | step_until(&mut r, "A emitted three tokens", 50, |r| emitted(r, a) >= 3).await; |
| 1463 | let emitted_before = emitted(&r, a); |
| 1464 | assert!(!finished(&r, a), "A still running"); |
| 1465 | let b = submit(&mut r, &prompt_b(), max_b); |
| 1466 | step_until(&mut r, "A preempted", 50, |r| { |
| 1467 | r.spine.scheduler.metrics().preempted_requests >= 1 |
| 1468 | }) |
| 1469 | .await; |
| 1470 | assert_eq!( |
| 1471 | phase_of(&r, a), |
| 1472 | Some(SequencePhase::Preempted), |
| 1473 | "A is the preempted sequence" |
| 1474 | ); |
| 1475 | step_until(&mut r, "A and B finished", 500, |r| { |
| 1476 | finished(r, a) && finished(r, b) |
| 1477 | }) |
| 1478 | .await; |
| 1479 | |
| 1480 | assert_eq!(toks(&r, b), want_b, "B greedy"); |
| 1481 | let got_a = toks(&r, a); |
| 1482 | assert!( |
| 1483 | emitted_before < got_a.len(), |
| 1484 | "A emitted more after resuming" |
| 1485 | ); |
| 1486 | assert_eq!( |
| 1487 | got_a.len(), |
| 1488 | max_a, |
| 1489 | "every token of A reached the sink exactly once: {got_a:?}" |
| 1490 | ); |
| 1491 | assert_eq!( |
| 1492 | got_a, want_a, |
| 1493 | "A after preemption equals the uninterrupted run" |
| 1494 | ); |
| 1495 | assert_refcounts_match_tables(&r, &[], "end"); |
| 1496 | } |