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-kv-store / tests / worker_tests.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 | //! The storage worker (cut C5, ADR 0003 sections 7 and 8) against the |
| 17 | //! deterministic fake store. |
| 18 | //! |
| 19 | //! The fake does all its I/O when its virtual clock is advanced. The worker |
| 20 | //! thread advances it through the `drive` closure given to `spawn`; the test |
| 21 | //! controls how fast (`W::step`). A `Probe` wraps the fake to make a store |
| 22 | //! slow or stalled in real time (a gate that blocks the calling thread) and to |
| 23 | //! record which thread made which call. |
| 24 | |
| 25 | mod common; |
| 26 | |
| 27 | use aien_kv_store::coalesce::{AttachRefused, CoalesceLimits, CoalesceTable, Detach, Share}; |
| 28 | use aien_kv_store::fake::{FakeConfig, FakeKvStore, Fault, JobScript}; |
| 29 | use aien_kv_store::worker::{Class, LoadTicket, StorageWorker, WorkerConfig}; |
| 30 | use aien_kv_store::{ |
| 31 | CancelOutcome, Capacity, ChunkHeader, ChunkKey, Completion, DrainReport, HolderGuard, |
| 32 | HolderHandle, Incarnation, JobId, JobStage, KvStore, NamespaceFields, NamespaceId, PinToken, |
| 33 | PinnedDest, PinnedSource, PublishOutcome, RecoveryProgress, Terminal, |
| 34 | }; |
| 35 | use aien_platform::PlatformError; |
| 36 | use common::rig::{pattern, tiny, Mem, BLOCK, OBJ, PAYLOAD}; |
| 37 | use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; |
| 38 | use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; |
| 39 | use std::sync::{mpsc, Arc, Condvar, Mutex}; |
| 40 | use std::thread::{self, ThreadId}; |
| 41 | use std::time::{Duration, Instant}; |
| 42 | |
| 43 | // ---------------------------------------------------------------- the probe |
| 44 | |
| 45 | /// Blocks every thread that passes through it while closed. |
| 46 | struct Gate { |
| 47 | open: Mutex<bool>, |
| 48 | cv: Condvar, |
| 49 | waiting: AtomicU64, |
| 50 | } |
| 51 | |
| 52 | impl Gate { |
| 53 | fn new() -> Gate { |
| 54 | Gate { |
| 55 | open: Mutex::new(true), |
| 56 | cv: Condvar::new(), |
| 57 | waiting: AtomicU64::new(0), |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | fn set(&self, open: bool) { |
| 62 | *self.open.lock().unwrap() = open; |
| 63 | self.cv.notify_all(); |
| 64 | } |
| 65 | |
| 66 | fn pass(&self) { |
| 67 | let mut g = self.open.lock().unwrap(); |
| 68 | if !*g { |
| 69 | self.waiting.fetch_add(1, Ordering::SeqCst); |
| 70 | while !*g { |
| 71 | g = self.cv.wait(g).unwrap(); |
| 72 | } |
| 73 | self.waiting.fetch_sub(1, Ordering::SeqCst); |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | fn waiting(&self) -> u64 { |
| 78 | self.waiting.load(Ordering::SeqCst) |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | /// The fake behind a gate, recording who calls what. |
| 83 | struct Probe { |
| 84 | fake: Arc<FakeKvStore>, |
| 85 | gate: Arc<Gate>, |
| 86 | /// Passed only inside `submit_*`: holds a job in `Dispatching`. |
| 87 | submit_gate: Arc<Gate>, |
| 88 | threads: Mutex<BTreeMap<&'static str, HashSet<ThreadId>>>, |
| 89 | seq: Mutex<Vec<char>>, |
| 90 | forged: Mutex<Vec<Completion>>, |
| 91 | slow_us: AtomicU64, |
| 92 | } |
| 93 | |
| 94 | impl Probe { |
| 95 | fn note(&self, what: &'static str) { |
| 96 | self.threads |
| 97 | .lock() |
| 98 | .unwrap() |
| 99 | .entry(what) |
| 100 | .or_default() |
| 101 | .insert(thread::current().id()); |
| 102 | } |
| 103 | |
| 104 | fn enter(&self, what: &'static str) { |
| 105 | self.note(what); |
| 106 | self.gate.pass(); |
| 107 | let us = self.slow_us.load(Ordering::SeqCst); |
| 108 | if us > 0 { |
| 109 | thread::sleep(Duration::from_micros(us)); |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | fn threads_of(&self, what: &'static str) -> HashSet<ThreadId> { |
| 114 | self.threads |
| 115 | .lock() |
| 116 | .unwrap() |
| 117 | .get(what) |
| 118 | .cloned() |
| 119 | .unwrap_or_default() |
| 120 | } |
| 121 | |
| 122 | fn submitted(&self) -> Vec<char> { |
| 123 | self.seq.lock().unwrap().clone() |
| 124 | } |
| 125 | |
| 126 | fn forge(&self, c: Completion) { |
| 127 | self.forged.lock().unwrap().push(c); |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | impl KvStore for Probe { |
| 132 | fn namespace(&self) -> NamespaceId { |
| 133 | self.fake.namespace() |
| 134 | } |
| 135 | fn capacity(&self) -> Capacity { |
| 136 | self.note("capacity"); |
| 137 | self.fake.capacity() |
| 138 | } |
| 139 | fn lookup(&self, keys: &[ChunkKey]) -> Vec<Option<u64>> { |
| 140 | self.note("lookup"); |
| 141 | self.fake.lookup(keys) |
| 142 | } |
| 143 | fn submit_store( |
| 144 | &self, |
| 145 | header: ChunkHeader, |
| 146 | src: PinnedSource, |
| 147 | inc: Incarnation, |
| 148 | ) -> Result<JobId, PlatformError> { |
| 149 | self.enter("submit"); |
| 150 | self.submit_gate.pass(); |
| 151 | self.seq.lock().unwrap().push('S'); |
| 152 | self.fake.submit_store(header, src, inc) |
| 153 | } |
| 154 | fn submit_load( |
| 155 | &self, |
| 156 | key: ChunkKey, |
| 157 | expect: &ChunkHeader, |
| 158 | dst: PinnedDest, |
| 159 | inc: Incarnation, |
| 160 | ) -> Result<JobId, PlatformError> { |
| 161 | self.enter("submit"); |
| 162 | self.submit_gate.pass(); |
| 163 | self.seq.lock().unwrap().push('L'); |
| 164 | self.fake.submit_load(key, expect, dst, inc) |
| 165 | } |
| 166 | fn submit_flush(&self, inc: Incarnation) -> Result<JobId, PlatformError> { |
| 167 | self.enter("submit"); |
| 168 | self.submit_gate.pass(); |
| 169 | self.seq.lock().unwrap().push('F'); |
| 170 | self.fake.submit_flush(inc) |
| 171 | } |
| 172 | fn attach_waiter(&self, job: JobId, inc: Incarnation) -> Result<(), PlatformError> { |
| 173 | self.fake.attach_waiter(job, inc) |
| 174 | } |
| 175 | fn poll(&self, max: usize) -> Vec<Completion> { |
| 176 | self.enter("poll"); |
| 177 | let mut v = self.fake.poll(max); |
| 178 | v.extend(self.forged.lock().unwrap().drain(..)); |
| 179 | v |
| 180 | } |
| 181 | fn cancel(&self, job: JobId) -> CancelOutcome { |
| 182 | self.note("cancel"); |
| 183 | self.fake.cancel(job) |
| 184 | } |
| 185 | fn pin(&self, keys: &[ChunkKey]) -> Result<PinToken, PlatformError> { |
| 186 | self.note("pin"); |
| 187 | self.fake.pin(keys) |
| 188 | } |
| 189 | fn unpin(&self, token: PinToken) { |
| 190 | self.note("unpin"); |
| 191 | self.fake.unpin(token) |
| 192 | } |
| 193 | fn delete(&self, keys: &[ChunkKey]) -> u64 { |
| 194 | self.note("delete"); |
| 195 | self.fake.delete(keys) |
| 196 | } |
| 197 | fn recover_step(&self, slice_ms: u64) -> RecoveryProgress { |
| 198 | self.fake.recover_step(slice_ms) |
| 199 | } |
| 200 | fn shutdown(&self, intake_deadline_ms: u64) -> DrainReport { |
| 201 | self.enter("shutdown"); |
| 202 | self.fake.shutdown(intake_deadline_ms) |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | // ------------------------------------------------------------------ the rig |
| 207 | |
| 208 | struct W { |
| 209 | fake: Arc<FakeKvStore>, |
| 210 | probe: Arc<Probe>, |
| 211 | worker: StorageWorker, |
| 212 | /// Virtual microseconds the drive closure advances the fake per pass; 0 freezes it. |
| 213 | step: Arc<AtomicU64>, |
| 214 | fields: NamespaceFields<'static>, |
| 215 | ns: NamespaceId, |
| 216 | } |
| 217 | |
| 218 | fn rig() -> W { |
| 219 | w_with(|_| {}, |_| {}) |
| 220 | } |
| 221 | |
| 222 | /// Paused at start, spinning (not sleeping) between passes, depth 4. |
| 223 | fn w_with(fake_cfg: impl FnOnce(&mut FakeConfig), worker_cfg: impl FnOnce(&mut WorkerConfig)) -> W { |
| 224 | let fields = tiny(); |
| 225 | let ns = fields.namespace_id().unwrap(); |
| 226 | let mut fc = FakeConfig::new(ns); |
| 227 | fake_cfg(&mut fc); |
| 228 | let fake = Arc::new(FakeKvStore::new(fc)); |
| 229 | let gate = Arc::new(Gate::new()); |
| 230 | let probe = Arc::new(Probe { |
| 231 | fake: fake.clone(), |
| 232 | gate: gate.clone(), |
| 233 | submit_gate: Arc::new(Gate::new()), |
| 234 | threads: Mutex::new(BTreeMap::new()), |
| 235 | seq: Mutex::new(Vec::new()), |
| 236 | forged: Mutex::new(Vec::new()), |
| 237 | slow_us: AtomicU64::new(0), |
| 238 | }); |
| 239 | let mut wc = WorkerConfig { |
| 240 | idle_poll: Duration::ZERO, |
| 241 | start_paused: true, |
| 242 | dispatch_depth: 4, |
| 243 | ..WorkerConfig::default() |
| 244 | }; |
| 245 | worker_cfg(&mut wc); |
| 246 | let step = Arc::new(AtomicU64::new(100)); |
| 247 | let drive = { |
| 248 | let (fake, gate, step, probe) = (fake.clone(), gate, step.clone(), probe.clone()); |
| 249 | move || { |
| 250 | probe.note("drive"); |
| 251 | gate.pass(); |
| 252 | let s = step.load(Ordering::SeqCst); |
| 253 | if s > 0 { |
| 254 | fake.advance(s); |
| 255 | } |
| 256 | } |
| 257 | }; |
| 258 | let worker = StorageWorker::spawn(probe.clone(), wc, drive).expect("spawn"); |
| 259 | W { |
| 260 | fake, |
| 261 | probe, |
| 262 | worker, |
| 263 | step, |
| 264 | fields, |
| 265 | ns, |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | fn released_guard(n: &Arc<AtomicU64>) -> HolderGuard { |
| 270 | let n = n.clone(); |
| 271 | HolderGuard::new(move || { |
| 272 | n.fetch_add(1, Ordering::SeqCst); |
| 273 | }) |
| 274 | } |
| 275 | |
| 276 | fn wait_for(what: &str, mut f: impl FnMut() -> bool) { |
| 277 | let t0 = Instant::now(); |
| 278 | while !f() { |
| 279 | if t0.elapsed() > Duration::from_secs(30) { |
| 280 | panic!("timed out waiting for {what}"); |
| 281 | } |
| 282 | thread::sleep(Duration::from_micros(200)); |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | fn terminals(v: &[Completion]) -> Vec<&Completion> { |
| 287 | v.iter().filter(|c| c.terminal.is_some()).collect() |
| 288 | } |
| 289 | |
| 290 | impl W { |
| 291 | fn chunk(&self, n: u32) -> (ChunkKey, ChunkHeader) { |
| 292 | let tokens: Vec<u32> = (0..8).map(|i| n * 1000 + i).collect(); |
| 293 | let key = aien_kv_store::chunk_chain(&self.ns, 8, &tokens).unwrap()[0]; |
| 294 | let h = self |
| 295 | .fields |
| 296 | .chunk_header(&self.ns, key, None, 0, 8, 1) |
| 297 | .unwrap(); |
| 298 | (key, h) |
| 299 | } |
| 300 | |
| 301 | fn key(&self, n: u32) -> ChunkKey { |
| 302 | self.chunk(n).0 |
| 303 | } |
| 304 | |
| 305 | fn inject(&self, n: u32) -> ChunkKey { |
| 306 | let (k, h) = self.chunk(n); |
| 307 | self.fake |
| 308 | .inject_object(h, pattern(n as u8, PAYLOAD as usize), BLOCK); |
| 309 | k |
| 310 | } |
| 311 | |
| 312 | fn store_with( |
| 313 | &self, |
| 314 | n: u32, |
| 315 | guard: HolderGuard, |
| 316 | ) -> (Result<JobId, PlatformError>, HolderHandle, Mem) { |
| 317 | let (_, h) = self.chunk(n); |
| 318 | let mem = Mem::new(2, 0); |
| 319 | let p = pattern(n as u8, PAYLOAD as usize); |
| 320 | mem.fill_with(|i| p[i]); |
| 321 | let (src, handle) = mem.source_with(2, 4, guard); |
| 322 | ( |
| 323 | self.worker.submit_store(h, src, Incarnation::seq(n as u64)), |
| 324 | handle, |
| 325 | mem, |
| 326 | ) |
| 327 | } |
| 328 | |
| 329 | fn store_h(&self, n: u32) -> (Result<JobId, PlatformError>, HolderHandle, Mem) { |
| 330 | self.store_with(n, HolderGuard::detached()) |
| 331 | } |
| 332 | |
| 333 | fn store(&self, n: u32) -> Result<JobId, PlatformError> { |
| 334 | self.store_h(n).0 |
| 335 | } |
| 336 | |
| 337 | fn load_with( |
| 338 | &self, |
| 339 | n: u32, |
| 340 | guard: HolderGuard, |
| 341 | ) -> (Result<JobId, PlatformError>, Mem, HolderHandle) { |
| 342 | let (k, h) = self.chunk(n); |
| 343 | let mem = Mem::new(2, 0xEE); |
| 344 | let (dst, handle) = mem.dest_with(2, guard); |
| 345 | ( |
| 346 | self.worker |
| 347 | .submit_load(k, &h, dst, Incarnation::seq(1000 + n as u64)), |
| 348 | mem, |
| 349 | handle, |
| 350 | ) |
| 351 | } |
| 352 | |
| 353 | fn load_h(&self, n: u32) -> (Result<JobId, PlatformError>, Mem, HolderHandle) { |
| 354 | self.load_with(n, HolderGuard::detached()) |
| 355 | } |
| 356 | |
| 357 | fn load(&self, n: u32) -> Result<JobId, PlatformError> { |
| 358 | self.load_h(n).0 |
| 359 | } |
| 360 | |
| 361 | fn resume(&self) { |
| 362 | self.worker.resume_dispatch(); |
| 363 | } |
| 364 | |
| 365 | fn poll_all(&self) -> Vec<Completion> { |
| 366 | let mut out = Vec::new(); |
| 367 | loop { |
| 368 | let v = self.worker.poll(64); |
| 369 | if v.is_empty() { |
| 370 | return out; |
| 371 | } |
| 372 | out.extend(v); |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | /// Poll until `n` terminal completions have been seen; returns everything polled. |
| 377 | fn collect(&self, n: usize) -> Vec<Completion> { |
| 378 | let mut out = Vec::new(); |
| 379 | let mut seen = 0; |
| 380 | let t0 = Instant::now(); |
| 381 | while seen < n { |
| 382 | let v = self.worker.poll(64); |
| 383 | seen += terminals(&v).len(); |
| 384 | out.extend(v); |
| 385 | if t0.elapsed() > Duration::from_secs(30) { |
| 386 | panic!("timed out: {seen} of {n} terminals, got {out:?}"); |
| 387 | } |
| 388 | thread::yield_now(); |
| 389 | } |
| 390 | out |
| 391 | } |
| 392 | |
| 393 | /// Wait until nothing is in flight in the worker (all terminals produced), then poll all. |
| 394 | fn settle(&self) -> Vec<Completion> { |
| 395 | wait_for("all jobs terminal", || { |
| 396 | let c = self.worker.capacity(); |
| 397 | c.restore_ops == 0 && c.park_ops == 0 |
| 398 | }); |
| 399 | self.poll_all() |
| 400 | } |
| 401 | |
| 402 | fn dispatched(&self, job: JobId) -> bool { |
| 403 | self.worker.inner_job(job).is_some() |
| 404 | } |
| 405 | |
| 406 | /// Stop the worker thread inside a gated call of the store. |
| 407 | fn stall_store(&self) { |
| 408 | self.probe.gate.set(false); |
| 409 | let g = self.probe.gate.clone(); |
| 410 | wait_for("worker blocked in the store", move || g.waiting() >= 1); |
| 411 | } |
| 412 | |
| 413 | fn unstall_store(&self) { |
| 414 | self.probe.gate.set(true); |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | // ---------------------------------------------------------- the red tests |
| 419 | |
| 420 | #[test] |
| 421 | fn worker_bounds_ops_and_bytes_in_flight() { |
| 422 | // Ops: 2 parks, 3 restores. Bytes: 8 objects' worth, split 3:1. |
| 423 | let w = w_with( |
| 424 | |_| {}, |
| 425 | |c| { |
| 426 | c.max_restore_ops = 3; |
| 427 | c.max_park_ops = 2; |
| 428 | c.max_inflight_bytes = 8 * OBJ; |
| 429 | }, |
| 430 | ); |
| 431 | assert!(w.store(1).is_ok()); |
| 432 | assert!(w.store(2).is_ok()); |
| 433 | assert_eq!(w.store(3), Err(PlatformError::QueueFull), "park ops bound"); |
| 434 | let cap = w.worker.capacity(); |
| 435 | assert_eq!((cap.park_ops, cap.max_park_ops), (2, 2)); |
| 436 | assert_eq!(cap.restore_ops, 0); |
| 437 | assert_eq!( |
| 438 | cap.reserved_bytes, |
| 439 | 2 * OBJ, |
| 440 | "queued stores hold a reservation" |
| 441 | ); |
| 442 | assert_eq!(cap.inflight_bytes, 2 * OBJ); |
| 443 | assert_eq!(cap.max_inflight_bytes, 8 * OBJ); |
| 444 | for n in 50..54 { |
| 445 | w.inject(n); |
| 446 | } |
| 447 | for n in 50..53 { |
| 448 | assert!( |
| 449 | w.load(n).is_ok(), |
| 450 | "a full park class must not refuse a restore" |
| 451 | ); |
| 452 | } |
| 453 | assert_eq!( |
| 454 | w.load(53), |
| 455 | Err(PlatformError::QueueFull), |
| 456 | "restore ops bound" |
| 457 | ); |
| 458 | assert_eq!(w.worker.capacity().inflight_bytes, 5 * OBJ); |
| 459 | let s = w.worker.stats(); |
| 460 | assert!(s.peak_restore_queue <= 3 && s.peak_park_queue <= 2, "{s:?}"); |
| 461 | assert_eq!(s.queue_full_total, 2); |
| 462 | assert_eq!( |
| 463 | w.fake.stats().io_ops, |
| 464 | 0, |
| 465 | "nothing reaches storage while paused" |
| 466 | ); |
| 467 | assert!(w.probe.submitted().is_empty()); |
| 468 | |
| 469 | w.resume(); |
| 470 | let v = w.settle(); |
| 471 | assert_eq!(terminals(&v).len(), 5); |
| 472 | let cap = w.worker.capacity(); |
| 473 | assert_eq!( |
| 474 | (cap.restore_ops, cap.park_ops, cap.inflight_bytes), |
| 475 | (0, 0, 0) |
| 476 | ); |
| 477 | assert!( |
| 478 | w.store(3).is_ok(), |
| 479 | "credits come back at the terminal completion" |
| 480 | ); |
| 481 | |
| 482 | // Bytes: plenty of ops, 4 objects' worth in flight: one for parks, three for restores. |
| 483 | let w = w_with( |
| 484 | |_| {}, |
| 485 | |c| { |
| 486 | c.max_restore_ops = 8; |
| 487 | c.max_park_ops = 8; |
| 488 | c.max_inflight_bytes = 4 * OBJ; |
| 489 | }, |
| 490 | ); |
| 491 | assert!(w.store(1).is_ok()); |
| 492 | assert_eq!(w.store(2), Err(PlatformError::QueueFull), "park bytes full"); |
| 493 | for n in 60..64 { |
| 494 | w.inject(n); |
| 495 | } |
| 496 | assert!(w.load(60).is_ok() && w.load(61).is_ok() && w.load(62).is_ok()); |
| 497 | assert_eq!( |
| 498 | w.load(63), |
| 499 | Err(PlatformError::QueueFull), |
| 500 | "restore bytes full" |
| 501 | ); |
| 502 | assert_eq!(w.worker.capacity().inflight_bytes, 4 * OBJ); |
| 503 | } |
| 504 | |
| 505 | #[test] |
| 506 | fn worker_three_restores_then_one_park_when_both_waiting() { |
| 507 | let w = w_with(|_| {}, |c| c.dispatch_depth = 1); |
| 508 | for n in 1..=8 { |
| 509 | w.inject(n); |
| 510 | } |
| 511 | let mut jobs = Vec::new(); |
| 512 | // Park submissions are interleaved with restores on purpose: arrival order must not matter. |
| 513 | for n in 1..=8 { |
| 514 | jobs.push((w.load(n).unwrap(), Class::Restore)); |
| 515 | if n % 3 == 0 { |
| 516 | jobs.push((w.store(100 + n).unwrap(), Class::Park)); |
| 517 | } |
| 518 | } |
| 519 | jobs.push((w.store(200).unwrap(), Class::Park)); |
| 520 | assert_eq!(jobs.iter().filter(|(_, c)| *c == Class::Park).count(), 3); |
| 521 | w.resume(); |
| 522 | let v = w.collect(11); |
| 523 | assert!(terminals(&v) |
| 524 | .iter() |
| 525 | .all(|c| matches!(c.terminal, Some(Terminal::Done(_))))); |
| 526 | use Class::{Park as P, Restore as R}; |
| 527 | let classes: Vec<Class> = w.worker.dispatch_order().iter().map(|(_, c)| *c).collect(); |
| 528 | assert_eq!(classes, vec![R, R, R, P, R, R, R, P, R, R, P]); |
| 529 | // The store saw the same order (independent of the worker's own log). |
| 530 | assert_eq!( |
| 531 | w.probe.submitted().iter().collect::<String>(), |
| 532 | "LLLSLLLSLLS" |
| 533 | ); |
| 534 | // FIFO within a class. |
| 535 | let restores: Vec<JobId> = w |
| 536 | .worker |
| 537 | .dispatch_order() |
| 538 | .iter() |
| 539 | .filter(|(_, c)| *c == R) |
| 540 | .map(|(j, _)| *j) |
| 541 | .collect(); |
| 542 | let expect: Vec<JobId> = jobs |
| 543 | .iter() |
| 544 | .filter(|(_, c)| *c == R) |
| 545 | .map(|(j, _)| *j) |
| 546 | .collect(); |
| 547 | assert_eq!(restores, expect); |
| 548 | assert!(w.worker.stats().max_restore_run_with_park_waiting <= 3); |
| 549 | } |
| 550 | |
| 551 | #[test] |
| 552 | fn worker_coalesces_same_key_loads_into_one_io() { |
| 553 | let w = rig(); |
| 554 | let k = w.inject(7); |
| 555 | let (_, h) = w.chunk(7); |
| 556 | let made = Arc::new(AtomicU64::new(0)); |
| 557 | let mut tickets = Vec::new(); |
| 558 | let mut mems = Vec::new(); |
| 559 | for i in 0..5u64 { |
| 560 | let made = made.clone(); |
| 561 | let mem = Mem::new(2, 0xEE); |
| 562 | mems.push(mem); |
| 563 | let t = w |
| 564 | .worker |
| 565 | .submit_load_coalesced( |
| 566 | k, |
| 567 | &h, |
| 568 | move || { |
| 569 | made.fetch_add(1, Ordering::SeqCst); |
| 570 | mem.dest(2).0 |
| 571 | }, |
| 572 | Incarnation::seq(500 + i), |
| 573 | ) |
| 574 | .unwrap(); |
| 575 | tickets.push(t); |
| 576 | } |
| 577 | let LoadTicket::Started(job) = tickets[0] else { |
| 578 | panic!("first request starts the load: {:?}", tickets[0]); |
| 579 | }; |
| 580 | assert!(tickets[1..].iter().all(|t| *t == LoadTicket::Attached(job))); |
| 581 | assert_eq!( |
| 582 | made.load(Ordering::SeqCst), |
| 583 | 1, |
| 584 | "followers allocate no landing buffer" |
| 585 | ); |
| 586 | assert_eq!(w.worker.load_in_flight(&k), Some(job)); |
| 587 | assert_eq!( |
| 588 | w.worker.capacity().restore_ops, |
| 589 | 1, |
| 590 | "one job for five requests" |
| 591 | ); |
| 592 | assert_eq!(w.worker.stats().coalesced_total, 4); |
| 593 | // The trait-level attach joins the same job. |
| 594 | assert_eq!(w.worker.attach_waiter(job, Incarnation::seq(77)), Ok(())); |
| 595 | |
| 596 | w.resume(); |
| 597 | let v = w.collect(6); |
| 598 | let t = terminals(&v); |
| 599 | assert_eq!( |
| 600 | t.len(), |
| 601 | 6, |
| 602 | "one terminal per waiter (5 requests + 1 attach): {v:?}" |
| 603 | ); |
| 604 | assert!(t.iter().all(|c| c.job == job)); |
| 605 | assert_eq!(t[0].terminal, Some(Terminal::Done(JobStage::Completed))); |
| 606 | assert_eq!(w.fake.stats().reads, 1, "one read of the object"); |
| 607 | assert_eq!(w.probe.submitted(), vec!['L'], "one submit to the store"); |
| 608 | assert_eq!( |
| 609 | mems[0].bytes(), |
| 610 | pattern(7, PAYLOAD as usize), |
| 611 | "the leader's landing buffer holds the object" |
| 612 | ); |
| 613 | assert_eq!( |
| 614 | w.worker.load_in_flight(&k), |
| 615 | None, |
| 616 | "the entry ends with the job" |
| 617 | ); |
| 618 | // A request after completion starts a fresh load. |
| 619 | let mem = Mem::new(2, 0xEE); |
| 620 | let t = w |
| 621 | .worker |
| 622 | .submit_load_coalesced(k, &h, || mem.dest(2).0, Incarnation::seq(9)) |
| 623 | .unwrap(); |
| 624 | assert!(matches!(t, LoadTicket::Started(_))); |
| 625 | } |
| 626 | |
| 627 | /// A waiter that attaches late, after the load is already dispatched to the |
| 628 | /// store (held there), rides the same job: it gets its own terminal with the |
| 629 | /// landing holder, it is counted against `max_waiters_total` while the job is |
| 630 | /// in flight, and the count is released when the job closes. |
| 631 | #[test] |
| 632 | fn worker_late_attach_after_dispatch_is_counted_and_released() { |
| 633 | let (a, b, c, d) = ( |
| 634 | Incarnation::seq(10), |
| 635 | Incarnation::seq(11), |
| 636 | Incarnation::seq(12), |
| 637 | Incarnation::seq(13), |
| 638 | ); |
| 639 | let w = w_with(|_| {}, |wc| wc.max_waiters_total = 1); |
| 640 | let k = w.inject(10); |
| 641 | let (_, h) = w.chunk(10); |
| 642 | let mem = Mem::new(2, 0xEE); |
| 643 | w.fake.script(JobScript::fault(Fault::Hold)); |
| 644 | let job = w |
| 645 | .worker |
| 646 | .submit_load_coalesced(k, &h, || mem.dest(2).0, a) |
| 647 | .unwrap() |
| 648 | .job(); |
| 649 | w.resume(); |
| 650 | wait_for("dispatch", || w.dispatched(job)); |
| 651 | assert_eq!(w.probe.submitted(), vec!['L'], "the store holds the load"); |
| 652 | assert_eq!(w.worker.capacity().restore_ops, 1); |
| 653 | |
| 654 | // Late attach: the job is at the store, not in the worker queue. |
| 655 | assert_eq!(w.worker.attach_waiter(job, b), Ok(())); |
| 656 | assert_eq!( |
| 657 | w.worker.attach_waiter(job, c), |
| 658 | Err(PlatformError::QueueFull), |
| 659 | "the late waiter is counted: the total bound of one is reached" |
| 660 | ); |
| 661 | assert_eq!(w.worker.stats().attach_refused_total, 1); |
| 662 | assert_eq!(w.worker.capacity().restore_ops, 1, "still one job"); |
| 663 | |
| 664 | assert!(w.fake.release(job), "the held load starts"); |
| 665 | let v = w.collect(2); |
| 666 | let t = terminals(&v); |
| 667 | assert_eq!(t.len(), 2, "one terminal per waiter: {v:?}"); |
| 668 | let mut incs: Vec<Incarnation> = t.iter().map(|x| x.incarnation).collect(); |
| 669 | incs.sort(); |
| 670 | assert_eq!( |
| 671 | incs, |
| 672 | vec![a, b], |
| 673 | "the opener and the late waiter, once each" |
| 674 | ); |
| 675 | assert!(t.iter().all(|x| x.job == job)); |
| 676 | assert!(t |
| 677 | .iter() |
| 678 | .all(|x| x.terminal == Some(Terminal::Done(JobStage::Completed)))); |
| 679 | assert!( |
| 680 | t.iter().all(|x| x.holder.is_some()), |
| 681 | "every waiter of a completed load gets the landing holder" |
| 682 | ); |
| 683 | assert_eq!(w.fake.stats().reads, 1, "one read of the object"); |
| 684 | assert_eq!(mem.bytes(), pattern(10, PAYLOAD as usize)); |
| 685 | assert_eq!(w.worker.load_in_flight(&k), None); |
| 686 | |
| 687 | // The count is released with the job: a fresh load takes one waiter again. |
| 688 | // Hold the second load at the store so the worker thread cannot finish and |
| 689 | // reap `job2` before `attach_waiter` runs on a loaded runner. |
| 690 | let mem2 = Mem::new(2, 0xEE); |
| 691 | w.fake.script(JobScript::fault(Fault::Hold)); |
| 692 | let job2 = w |
| 693 | .worker |
| 694 | .submit_load_coalesced(k, &h, || mem2.dest(2).0, c) |
| 695 | .unwrap(); |
| 696 | let LoadTicket::Started(job2) = job2 else { |
| 697 | panic!("a fresh load after the first closed: {job2:?}"); |
| 698 | }; |
| 699 | wait_for("dispatch", || w.dispatched(job2)); |
| 700 | assert_eq!( |
| 701 | w.worker.attach_waiter(job2, d), |
| 702 | Ok(()), |
| 703 | "the late waiter's count was released when its job closed" |
| 704 | ); |
| 705 | assert!(w.fake.release(job2), "the second held load starts"); |
| 706 | let v = w.collect(2); |
| 707 | assert_eq!(terminals(&v).len(), 2); |
| 708 | assert_eq!(w.worker.stats().attach_refused_total, 1); |
| 709 | } |
| 710 | |
| 711 | #[test] |
| 712 | fn worker_cancel_removes_only_own_waiter() { |
| 713 | // Queued, three requests: the opener and one follower withdraw, the third |
| 714 | // still gets its data. Every request still gets exactly one terminal, and |
| 715 | // only once the shared read ended. |
| 716 | let w = rig(); |
| 717 | let k = w.inject(7); |
| 718 | let (_, h) = w.chunk(7); |
| 719 | let mem = Mem::new(2, 0xEE); |
| 720 | let (a, b, c) = ( |
| 721 | Incarnation::seq(1), |
| 722 | Incarnation::seq(77), |
| 723 | Incarnation::seq(78), |
| 724 | ); |
| 725 | let job = w |
| 726 | .worker |
| 727 | .submit_load_coalesced(k, &h, || mem.dest(2).0, a) |
| 728 | .unwrap() |
| 729 | .job(); |
| 730 | w.worker.attach_waiter(job, b).unwrap(); |
| 731 | w.worker.attach_waiter(job, c).unwrap(); |
| 732 | assert_eq!( |
| 733 | w.worker.cancel(job), |
| 734 | CancelOutcome::TooLate, |
| 735 | "others still wait" |
| 736 | ); |
| 737 | assert_eq!( |
| 738 | w.worker.cancel_waiter(job, b), |
| 739 | CancelOutcome::TooLate, |
| 740 | "c still waits" |
| 741 | ); |
| 742 | assert_eq!( |
| 743 | w.worker.capacity().restore_ops, |
| 744 | 1, |
| 745 | "the shared job is alive" |
| 746 | ); |
| 747 | assert!(w.poll_all().is_empty(), "no terminal before the job ends"); |
| 748 | w.resume(); |
| 749 | let v = w.collect(3); |
| 750 | let t = terminals(&v); |
| 751 | assert_eq!(t.len(), 3, "one terminal per request: {v:?}"); |
| 752 | assert!( |
| 753 | t.iter() |
| 754 | .all(|x| x.terminal == Some(Terminal::Done(JobStage::Completed))), |
| 755 | "the read ran for the request that stayed: {v:?}" |
| 756 | ); |
| 757 | assert_eq!(mem.bytes(), pattern(7, PAYLOAD as usize)); |
| 758 | |
| 759 | // Queued, everybody leaves: the real cancel, every terminal is Cancelled, no I/O. |
| 760 | let w = w_with(|_| {}, |_| {}); |
| 761 | let k = w.inject(8); |
| 762 | let (_, h) = w.chunk(8); |
| 763 | let mem = Mem::new(2, 0xEE); |
| 764 | let job = w |
| 765 | .worker |
| 766 | .submit_load_coalesced(k, &h, || mem.dest(2).0, a) |
| 767 | .unwrap() |
| 768 | .job(); |
| 769 | w.worker.attach_waiter(job, b).unwrap(); |
| 770 | assert_eq!(w.worker.cancel(job), CancelOutcome::TooLate); |
| 771 | assert_eq!(w.worker.cancel_waiter(job, b), CancelOutcome::Cancelled); |
| 772 | let v = w.collect(2); |
| 773 | assert!(terminals(&v) |
| 774 | .iter() |
| 775 | .all(|x| x.terminal == Some(Terminal::Cancelled))); |
| 776 | assert_eq!(w.worker.load_in_flight(&k), None); |
| 777 | assert!(w.probe.submitted().is_empty(), "never reached the store"); |
| 778 | assert_eq!(mem.bytes(), vec![0xEE; 2 * BLOCK], "destination untouched"); |
| 779 | |
| 780 | // Dispatched (held in the device), two requests: same rule, through the store. |
| 781 | let w = w_with(|_| {}, |_| {}); |
| 782 | let k = w.inject(9); |
| 783 | let (_, h) = w.chunk(9); |
| 784 | let mem = Mem::new(2, 0xEE); |
| 785 | w.fake.script(JobScript::fault(Fault::Hold)); |
| 786 | let job = w |
| 787 | .worker |
| 788 | .submit_load_coalesced(k, &h, || mem.dest(2).0, a) |
| 789 | .unwrap() |
| 790 | .job(); |
| 791 | w.worker.attach_waiter(job, b).unwrap(); |
| 792 | w.resume(); |
| 793 | wait_for("dispatch", || w.dispatched(job)); |
| 794 | assert_eq!( |
| 795 | w.worker.cancel(job), |
| 796 | CancelOutcome::TooLate, |
| 797 | "the other waiter stays" |
| 798 | ); |
| 799 | assert_eq!(w.fake.live_jobs().len(), 1); |
| 800 | assert_eq!(w.worker.cancel_waiter(job, b), CancelOutcome::Cancelled); |
| 801 | let v = w.collect(2); |
| 802 | assert!(terminals(&v) |
| 803 | .iter() |
| 804 | .all(|x| x.terminal == Some(Terminal::Cancelled))); |
| 805 | assert_eq!(w.fake.stats().reads, 0); |
| 806 | assert_eq!(mem.bytes(), vec![0xEE; 2 * BLOCK]); |
| 807 | } |
| 808 | |
| 809 | #[test] |
| 810 | fn worker_stale_completion_is_dropped_by_incarnation() { |
| 811 | // (a) a store that reports every completion twice still yields one terminal. |
| 812 | let w = rig(); |
| 813 | w.fake.script(JobScript::fault(Fault::DuplicateCompletion)); |
| 814 | let job = w.store(1).unwrap(); |
| 815 | w.resume(); |
| 816 | let v = w.collect(1); |
| 817 | wait_for("duplicates dropped", || { |
| 818 | w.worker.stats().stale_completions_total >= 2 |
| 819 | }); |
| 820 | let mut v = v; |
| 821 | v.extend(w.poll_all()); |
| 822 | let mine: Vec<_> = v.iter().filter(|c| c.job == job).collect(); |
| 823 | assert_eq!(terminals(&v).len(), 1, "{v:?}"); |
| 824 | assert_eq!( |
| 825 | mine.iter().filter(|c| c.terminal.is_none()).count(), |
| 826 | 1, |
| 827 | "one progress report" |
| 828 | ); |
| 829 | assert_eq!( |
| 830 | w.fake |
| 831 | .terminal_count(w.worker.inner_job(job).unwrap_or(JobId(1))), |
| 832 | 2 |
| 833 | ); |
| 834 | |
| 835 | // (b) a progress report that arrives after the cancelled terminal is dropped. |
| 836 | let w = rig(); |
| 837 | w.fake |
| 838 | .script(JobScript::fault(Fault::Hold).with(Fault::CompletionAfterCancel)); |
| 839 | let job = w.store(2).unwrap(); |
| 840 | w.resume(); |
| 841 | wait_for("dispatch", || w.dispatched(job)); |
| 842 | assert_eq!(w.worker.cancel(job), CancelOutcome::Cancelled); |
| 843 | let mut v = w.collect(1); |
| 844 | wait_for("stale progress seen", || { |
| 845 | w.worker.stats().stale_completions_total >= 1 |
| 846 | }); |
| 847 | v.extend(w.poll_all()); |
| 848 | assert_eq!( |
| 849 | v.len(), |
| 850 | 1, |
| 851 | "only the cancelled terminal reaches the caller: {v:?}" |
| 852 | ); |
| 853 | assert_eq!(v[0].terminal, Some(Terminal::Cancelled)); |
| 854 | |
| 855 | // (c) a completion with the wrong incarnation is dropped; the real one still lands. |
| 856 | let w = rig(); |
| 857 | w.fake.script(JobScript::fault(Fault::Hold)); |
| 858 | let (k, _) = w.chunk(3); |
| 859 | let job = w.store(3).unwrap(); |
| 860 | w.resume(); |
| 861 | wait_for("dispatch", || w.dispatched(job)); |
| 862 | let inner = w.worker.inner_job(job).unwrap(); |
| 863 | w.probe.forge(Completion { |
| 864 | job: inner, |
| 865 | incarnation: Incarnation::seq(9999), |
| 866 | key: k, |
| 867 | stage: JobStage::Durable, |
| 868 | terminal: Some(Terminal::Done(JobStage::Durable)), |
| 869 | publish: PublishOutcome::Durable, |
| 870 | bytes: PAYLOAD, |
| 871 | elapsed_us: 1, |
| 872 | holder: None, |
| 873 | }); |
| 874 | wait_for("forged completion dropped", || { |
| 875 | w.worker.stats().stale_completions_total >= 1 |
| 876 | }); |
| 877 | assert!( |
| 878 | w.poll_all().is_empty(), |
| 879 | "the forgery never reaches the caller" |
| 880 | ); |
| 881 | assert_eq!(w.worker.capacity().park_ops, 1, "the job is still live"); |
| 882 | assert!(w.fake.release(inner)); |
| 883 | let v = w.collect(1); |
| 884 | let t = terminals(&v); |
| 885 | assert_eq!(t[0].job, job); |
| 886 | assert_eq!( |
| 887 | t[0].incarnation, |
| 888 | Incarnation::seq(3), |
| 889 | "the caller's own token is echoed" |
| 890 | ); |
| 891 | assert_eq!(t[0].terminal, Some(Terminal::Done(JobStage::Durable))); |
| 892 | } |
| 893 | |
| 894 | #[test] |
| 895 | fn worker_never_touches_dest_after_cancel_ack() { |
| 896 | // Dispatched (held in the device) load: cancel, then the terminal, then nothing more. |
| 897 | let w = rig(); |
| 898 | w.inject(5); |
| 899 | w.fake.script(JobScript::fault(Fault::Hold)); |
| 900 | let released = Arc::new(AtomicU64::new(0)); |
| 901 | let (job, mem, handle) = w.load_with(5, released_guard(&released)); |
| 902 | let job = job.unwrap(); |
| 903 | w.resume(); |
| 904 | wait_for("dispatch", || w.dispatched(job)); |
| 905 | let inner = w.worker.inner_job(job).unwrap(); |
| 906 | assert_eq!(w.worker.cancel(job), CancelOutcome::Cancelled); |
| 907 | let v = w.collect(1); |
| 908 | assert_eq!(terminals(&v)[0].terminal, Some(Terminal::Cancelled)); |
| 909 | wait_for("destination released after the terminal", || { |
| 910 | released.load(Ordering::SeqCst) == 1 |
| 911 | }); |
| 912 | assert!(!handle.is_held()); |
| 913 | // Time moves on, the store is poked again: the destination is never written. |
| 914 | assert!(!w.fake.release(inner)); |
| 915 | w.fake.advance(10_000_000); |
| 916 | thread::sleep(Duration::from_millis(20)); |
| 917 | assert_eq!(mem.bytes(), vec![0xEE; 2 * BLOCK], "never written"); |
| 918 | assert_eq!(w.fake.take_poison_violations(), 0); |
| 919 | assert_eq!(w.fake.stats().reads, 0); |
| 920 | assert_eq!(released.load(Ordering::SeqCst), 1, "released exactly once"); |
| 921 | |
| 922 | // Queued (never dispatched) load: cancelled before the store ever sees it. |
| 923 | let w = rig(); |
| 924 | w.inject(6); |
| 925 | let released = Arc::new(AtomicU64::new(0)); |
| 926 | let (job, mem, _h) = w.load_with(6, released_guard(&released)); |
| 927 | let job = job.unwrap(); |
| 928 | assert_eq!(w.worker.cancel(job), CancelOutcome::Cancelled); |
| 929 | let v = w.collect(1); |
| 930 | assert_eq!(terminals(&v)[0].terminal, Some(Terminal::Cancelled)); |
| 931 | w.resume(); |
| 932 | thread::sleep(Duration::from_millis(20)); |
| 933 | wait_for("queued destination released", || { |
| 934 | released.load(Ordering::SeqCst) == 1 |
| 935 | }); |
| 936 | assert!(w.probe.submitted().is_empty()); |
| 937 | assert_eq!(w.fake.stats().io_ops, 0); |
| 938 | assert_eq!(mem.bytes(), vec![0xEE; 2 * BLOCK]); |
| 939 | assert_eq!(w.fake.take_poison_violations(), 0); |
| 940 | } |
| 941 | |
| 942 | #[test] |
| 943 | fn worker_backpressure_refuses_not_grows() { |
| 944 | let w = rig(); |
| 945 | for n in 0..64 { |
| 946 | w.inject(n); |
| 947 | } |
| 948 | let mut ok = 0; |
| 949 | let mut full = 0; |
| 950 | for i in 0..1000u32 { |
| 951 | match w.load(i % 64) { |
| 952 | Ok(_) => ok += 1, |
| 953 | Err(PlatformError::QueueFull) => full += 1, |
| 954 | Err(e) => panic!("{e:?}"), |
| 955 | } |
| 956 | } |
| 957 | assert_eq!( |
| 958 | (ok, full), |
| 959 | (48, 952), |
| 960 | "exactly the restore bound is accepted" |
| 961 | ); |
| 962 | let s = w.worker.stats(); |
| 963 | assert_eq!( |
| 964 | s.peak_restore_queue, 48, |
| 965 | "the intake queue never exceeds the bound" |
| 966 | ); |
| 967 | assert_eq!(s.queue_full_total, 952); |
| 968 | assert_eq!(w.worker.capacity().restore_ops, 48); |
| 969 | assert!(w.poll_all().is_empty()); |
| 970 | let mut okp = 0; |
| 971 | for n in 0..100u32 { |
| 972 | if w.store(n).is_ok() { |
| 973 | okp += 1; |
| 974 | } |
| 975 | } |
| 976 | let park_bound = WorkerConfig::default().max_park_ops; |
| 977 | assert_eq!(okp, park_bound, "the park class is bounded on its own"); |
| 978 | assert_eq!(w.worker.stats().peak_park_queue, park_bound as u64); |
| 979 | // Once everything ends the bound is available again. |
| 980 | w.resume(); |
| 981 | w.settle(); |
| 982 | assert!(w.load(0).is_ok()); |
| 983 | } |
| 984 | |
| 985 | #[test] |
| 986 | fn sustained_restores_cannot_starve_parks() { |
| 987 | // Finding 9 / B4: offer restores at the maximum rate for 10 000 operations; |
| 988 | // parks are still admitted whenever their class has room and are |
| 989 | // dispatched at no less than their reserved share. |
| 990 | let w = w_with( |
| 991 | |c| { |
| 992 | c.quota_bytes = 1 << 40; |
| 993 | c.max_objects = 1 << 20; |
| 994 | }, |
| 995 | |c| c.dispatch_depth = 2, |
| 996 | ); |
| 997 | for n in 1..=32 { |
| 998 | w.inject(n); |
| 999 | } |
| 1000 | let mut restores = 0u64; |
| 1001 | let mut restore_refusals = 0u64; |
| 1002 | let mut parks = 0u64; |
| 1003 | let mut next_park = 1000u32; |
| 1004 | let mut terminal_count = 0u64; |
| 1005 | let mut seen: HashMap<JobId, u32> = HashMap::new(); |
| 1006 | let mut last_park_at = u64::MAX; |
| 1007 | while restores < 10_000 { |
| 1008 | for c in w.worker.poll(256) { |
| 1009 | if c.terminal.is_some() { |
| 1010 | *seen.entry(c.job).or_default() += 1; |
| 1011 | terminal_count += 1; |
| 1012 | } |
| 1013 | } |
| 1014 | match w.load(1 + (restores % 32) as u32) { |
| 1015 | Ok(_) => restores += 1, |
| 1016 | Err(PlatformError::QueueFull) => { |
| 1017 | restore_refusals += 1; |
| 1018 | if restore_refusals == 1 { |
| 1019 | w.resume(); |
| 1020 | } |
| 1021 | thread::yield_now(); |
| 1022 | } |
| 1023 | Err(e) => panic!("{e:?}"), |
| 1024 | } |
| 1025 | if restores.is_multiple_of(4) && last_park_at != restores { |
| 1026 | last_park_at = restores; |
| 1027 | // Only this thread adds park ops, so a park class below its bound |
| 1028 | // must admit, however saturated the restore class is. |
| 1029 | let before = w.worker.capacity(); |
| 1030 | if before.park_ops < before.max_park_ops { |
| 1031 | for c in w.worker.poll(256) { |
| 1032 | if c.terminal.is_some() { |
| 1033 | *seen.entry(c.job).or_default() += 1; |
| 1034 | terminal_count += 1; |
| 1035 | } |
| 1036 | } |
| 1037 | let r = w.store(next_park); |
| 1038 | assert!(r.is_ok(), "park refused with room in its class: {r:?}"); |
| 1039 | next_park += 1; |
| 1040 | parks += 1; |
| 1041 | } |
| 1042 | } |
| 1043 | } |
| 1044 | assert!( |
| 1045 | restore_refusals > 0, |
| 1046 | "the restore class really was saturated" |
| 1047 | ); |
| 1048 | assert!(parks >= 100, "parks were offered throughout ({parks})"); |
| 1049 | let t0 = Instant::now(); |
| 1050 | while terminal_count < restores + parks { |
| 1051 | for c in w.worker.poll(256) { |
| 1052 | if c.terminal.is_some() { |
| 1053 | *seen.entry(c.job).or_default() += 1; |
| 1054 | terminal_count += 1; |
| 1055 | } |
| 1056 | } |
| 1057 | assert!(t0.elapsed() < Duration::from_secs(60), "drain stalled"); |
| 1058 | thread::yield_now(); |
| 1059 | } |
| 1060 | let s = w.worker.stats(); |
| 1061 | assert_eq!(s.dispatched_restore, restores); |
| 1062 | assert_eq!( |
| 1063 | s.dispatched_park, parks, |
| 1064 | "every admitted park was dispatched" |
| 1065 | ); |
| 1066 | assert!( |
| 1067 | s.max_restore_run_with_park_waiting <= 3, |
| 1068 | "a waiting park was passed over {} times in a row", |
| 1069 | s.max_restore_run_with_park_waiting |
| 1070 | ); |
| 1071 | assert!(seen.values().all(|n| *n == 1), "one terminal per job"); |
| 1072 | assert_eq!(seen.len() as u64, restores + parks); |
| 1073 | } |
| 1074 | |
| 1075 | #[test] |
| 1076 | fn completion_queue_never_overflows_at_max_inflight() { |
| 1077 | // 4 restores + 2 parks: 18 completion slots. The caller never polls. |
| 1078 | let cfg = |c: &mut WorkerConfig| { |
| 1079 | c.max_restore_ops = 4; |
| 1080 | c.max_park_ops = 2; |
| 1081 | c.start_paused = false; |
| 1082 | }; |
| 1083 | let w = w_with( |
| 1084 | |c| { |
| 1085 | c.max_restore_ops = 4; |
| 1086 | c.max_park_ops = 2; |
| 1087 | }, |
| 1088 | cfg, |
| 1089 | ); |
| 1090 | for n in 1..=4 { |
| 1091 | w.inject(n); |
| 1092 | } |
| 1093 | let mut accepted = 0; |
| 1094 | let mut refused_when_quiet = false; |
| 1095 | for i in 0..60u32 { |
| 1096 | // Wait for the worker to finish what it has, still without polling. |
| 1097 | wait_for("quiet", || { |
| 1098 | let c = w.worker.capacity(); |
| 1099 | c.restore_ops == 0 && c.park_ops == 0 |
| 1100 | }); |
| 1101 | let r = if i % 2 == 0 { |
| 1102 | w.load(1 + i % 4) |
| 1103 | } else { |
| 1104 | w.store(100 + i) |
| 1105 | }; |
| 1106 | match r { |
| 1107 | Ok(_) => accepted += 1, |
| 1108 | Err(PlatformError::QueueFull) => { |
| 1109 | refused_when_quiet = true; |
| 1110 | break; |
| 1111 | } |
| 1112 | Err(e) => panic!("{e:?}"), |
| 1113 | } |
| 1114 | } |
| 1115 | assert!( |
| 1116 | refused_when_quiet, |
| 1117 | "unpolled completions must close admission ({accepted} accepted)" |
| 1118 | ); |
| 1119 | wait_for("quiet", || w.worker.capacity().restore_ops == 0); |
| 1120 | let s = w.worker.stats(); |
| 1121 | assert!(s.peak_completion_queue <= 18, "{s:?}"); |
| 1122 | assert_eq!(s.completion_overflow_total, 0); |
| 1123 | assert_eq!(w.fake.stats().completion_overflow_total, 0); |
| 1124 | // Polling gives the slots back. |
| 1125 | let v = w.poll_all(); |
| 1126 | assert!(!v.is_empty()); |
| 1127 | assert!(w.store(500).is_ok()); |
| 1128 | } |
| 1129 | |
| 1130 | #[test] |
| 1131 | fn coalesced_waiters_are_bounded() { |
| 1132 | let w = w_with( |
| 1133 | |_| {}, |
| 1134 | |c| { |
| 1135 | c.max_waiters_per_job = 3; |
| 1136 | c.max_waiters_total = 4; |
| 1137 | }, |
| 1138 | ); |
| 1139 | let mut jobs = Vec::new(); |
| 1140 | let made = Arc::new(AtomicU64::new(0)); |
| 1141 | for n in 1..=3 { |
| 1142 | let k = w.inject(n); |
| 1143 | let (_, h) = w.chunk(n); |
| 1144 | let mem = Mem::new(2, 0xEE); |
| 1145 | let t = w |
| 1146 | .worker |
| 1147 | .submit_load_coalesced(k, &h, || mem.dest(2).0, Incarnation::seq(n as u64)) |
| 1148 | .unwrap(); |
| 1149 | jobs.push((k, h, t.job())); |
| 1150 | } |
| 1151 | let (a, b, c) = (jobs[0].2, jobs[1].2, jobs[2].2); |
| 1152 | // Per job: the opener counts as waiter 1, so 3 means two attaches. |
| 1153 | assert_eq!(w.worker.attach_waiter(a, Incarnation::seq(76)), Ok(())); |
| 1154 | assert_eq!(w.worker.attach_waiter(a, Incarnation::seq(77)), Ok(())); |
| 1155 | assert_eq!( |
| 1156 | w.worker.attach_waiter(a, Incarnation::seq(78)), |
| 1157 | Err(PlatformError::QueueFull) |
| 1158 | ); |
| 1159 | // Coalesced submit is refused the same way, and allocates nothing. |
| 1160 | { |
| 1161 | let made2 = made.clone(); |
| 1162 | let r = w.worker.submit_load_coalesced( |
| 1163 | jobs[0].0, |
| 1164 | &jobs[0].1, |
| 1165 | move || { |
| 1166 | made2.fetch_add(1, Ordering::SeqCst); |
| 1167 | Mem::new(2, 0).dest(2).0 |
| 1168 | }, |
| 1169 | Incarnation::seq(79), |
| 1170 | ); |
| 1171 | assert_eq!(r, Err(PlatformError::QueueFull)); |
| 1172 | assert_eq!( |
| 1173 | made.load(Ordering::SeqCst), |
| 1174 | 0, |
| 1175 | "no landing buffer for a refused waiter" |
| 1176 | ); |
| 1177 | } |
| 1178 | // Total: 4 attached waiters over all jobs. |
| 1179 | assert_eq!(w.worker.attach_waiter(b, Incarnation::seq(76)), Ok(())); |
| 1180 | assert_eq!(w.worker.attach_waiter(b, Incarnation::seq(77)), Ok(())); |
| 1181 | assert_eq!( |
| 1182 | w.worker.attach_waiter(c, Incarnation::seq(77)), |
| 1183 | Err(PlatformError::QueueFull), |
| 1184 | "total bound" |
| 1185 | ); |
| 1186 | assert!(w.worker.stats().attach_refused_total >= 3); |
| 1187 | // Only loads accept waiters. |
| 1188 | let st = w.store(40).unwrap(); |
| 1189 | assert!(matches!( |
| 1190 | w.worker.attach_waiter(st, Incarnation::seq(77)), |
| 1191 | Err(PlatformError::TaskRejected(_)) |
| 1192 | )); |
| 1193 | assert!(matches!( |
| 1194 | w.worker.attach_waiter(JobId(9999), Incarnation::seq(77)), |
| 1195 | Err(PlatformError::TaskRejected(_)) |
| 1196 | )); |
| 1197 | // When a job ends its waiters leave the total. |
| 1198 | w.resume(); |
| 1199 | w.settle(); |
| 1200 | w.worker.pause_dispatch(); |
| 1201 | let k = w.inject(60); |
| 1202 | let (_, h) = w.chunk(60); |
| 1203 | let mem = Mem::new(2, 0xEE); |
| 1204 | let job = w |
| 1205 | .worker |
| 1206 | .submit_load_coalesced(k, &h, || mem.dest(2).0, Incarnation::seq(1)) |
| 1207 | .unwrap() |
| 1208 | .job(); |
| 1209 | assert_eq!(w.worker.attach_waiter(job, Incarnation::seq(77)), Ok(())); |
| 1210 | w.resume(); |
| 1211 | w.settle(); |
| 1212 | } |
| 1213 | |
| 1214 | #[test] |
| 1215 | fn coalesce_table_bounds_counts_and_detach() { |
| 1216 | let key = |b: u8| ChunkKey(aien_platform::ObjectId([b; 32])); |
| 1217 | let mut t = CoalesceTable::new(CoalesceLimits { |
| 1218 | max_waiters_per_job: 3, |
| 1219 | max_waiters_total: 3, |
| 1220 | }); |
| 1221 | assert_eq!(t.limits().max_waiters_per_job, 3); |
| 1222 | t.open(Share::Load, &key(1), JobId(1)); |
| 1223 | t.open(Share::Load, &key(2), JobId(2)); |
| 1224 | assert_eq!(t.waiters(JobId(1)), 1); |
| 1225 | assert_eq!(t.find(Share::Load, &key(1)), Some(JobId(1))); |
| 1226 | assert_eq!( |
| 1227 | t.find(Share::Store, &key(1)), |
| 1228 | None, |
| 1229 | "loads and stores never share" |
| 1230 | ); |
| 1231 | assert_eq!(t.attach(JobId(1)), Ok(2)); |
| 1232 | assert_eq!(t.attach(JobId(1)), Ok(3)); |
| 1233 | assert_eq!(t.attach(JobId(1)), Err(AttachRefused::JobFull)); |
| 1234 | assert_eq!(t.attach(JobId(2)), Ok(2)); |
| 1235 | assert_eq!(t.attached_total(), 3); |
| 1236 | assert_eq!(t.attach(JobId(2)), Err(AttachRefused::TotalFull)); |
| 1237 | assert_eq!(t.attach(JobId(9)), Err(AttachRefused::NoSuchJob)); |
| 1238 | // Detach frees one slot at a time and reports the last waiter. |
| 1239 | assert_eq!(t.detach(JobId(1)), Detach::Remaining(2)); |
| 1240 | assert_eq!(t.attached_total(), 2); |
| 1241 | assert_eq!(t.attach(JobId(2)), Ok(3)); |
| 1242 | assert_eq!(t.detach(JobId(2)), Detach::Remaining(2)); |
| 1243 | assert_eq!(t.detach(JobId(2)), Detach::Remaining(1)); |
| 1244 | assert_eq!(t.detach(JobId(2)), Detach::Last); |
| 1245 | assert_eq!(t.waiters(JobId(2)), 0); |
| 1246 | assert_eq!(t.find(Share::Load, &key(2)), None, "nobody left to join"); |
| 1247 | assert!( |
| 1248 | t.has(Share::Load, &key(2)), |
| 1249 | "but the job still exists until it ends" |
| 1250 | ); |
| 1251 | assert_eq!(t.attach(JobId(2)), Err(AttachRefused::NoSuchJob)); |
| 1252 | assert_eq!(t.detach(JobId(77)), Detach::Unknown); |
| 1253 | // Close releases the job's attached waiters. |
| 1254 | assert_eq!(t.attached_total(), 1); |
| 1255 | t.close(JobId(1)); |
| 1256 | assert_eq!(t.attached_total(), 0); |
| 1257 | t.close(JobId(2)); |
| 1258 | assert_eq!(t.jobs(), 0); |
| 1259 | assert!(!t.has(Share::Load, &key(1))); |
| 1260 | // A second job for a key that has waiters does not take over the key. |
| 1261 | t.open(Share::Store, &key(5), JobId(10)); |
| 1262 | t.open(Share::Store, &key(5), JobId(11)); |
| 1263 | assert_eq!(t.find(Share::Store, &key(5)), Some(JobId(10))); |
| 1264 | t.close(JobId(11)); |
| 1265 | assert_eq!(t.find(Share::Store, &key(5)), Some(JobId(10))); |
| 1266 | t.close(JobId(10)); |
| 1267 | assert_eq!(t.find(Share::Store, &key(5)), None); |
| 1268 | } |
| 1269 | |
| 1270 | #[test] |
| 1271 | fn shutdown_with_stalled_fsync_returns_by_deadline_and_reports_unfinished() { |
| 1272 | // Finding 11: fsync has no bounded completion time; shutdown still returns |
| 1273 | // at its deadline and names the job, keeping its buffer. |
| 1274 | let w = w_with(|_| {}, |c| c.dispatch_depth = 2); |
| 1275 | w.fake |
| 1276 | .script(JobScript::latency(100, 100).with(Fault::StallFsync(10_000_000))); |
| 1277 | w.fake.script(JobScript::fault(Fault::Hold)); |
| 1278 | let rel1 = Arc::new(AtomicU64::new(0)); |
| 1279 | let (j1, h1, _m1) = w.store_with(1, released_guard(&rel1)); |
| 1280 | let j1 = j1.unwrap(); |
| 1281 | let j2 = w.store(2).unwrap(); |
| 1282 | let j3 = w.store(3).unwrap(); // behind the depth: never dispatched |
| 1283 | let (k1, _) = w.chunk(1); |
| 1284 | w.resume(); |
| 1285 | wait_for("dispatch", || w.dispatched(j1) && w.dispatched(j2)); |
| 1286 | wait_for("fsync under way", || w.fake.now_us() >= 400); |
| 1287 | w.step.store(0, Ordering::SeqCst); // the stall is real: time stops for the store |
| 1288 | |
| 1289 | let t0 = Instant::now(); |
| 1290 | let rep = w.worker.shutdown(60); |
| 1291 | let el = t0.elapsed(); |
| 1292 | assert!( |
| 1293 | el >= Duration::from_millis(50), |
| 1294 | "waited for the deadline: {el:?}" |
| 1295 | ); |
| 1296 | assert!(el < Duration::from_secs(5), "and returned by it: {el:?}"); |
| 1297 | assert_eq!(rep.unfinished.len(), 1, "{rep:?}"); |
| 1298 | assert_eq!(rep.unfinished[0].job, j1); |
| 1299 | assert_eq!(rep.unfinished[0].key, k1); |
| 1300 | assert_eq!(rep.unfinished[0].bytes, OBJ); |
| 1301 | assert_eq!(rep.cancelled, 2, "the held job and the queued job: {rep:?}"); |
| 1302 | assert_eq!(rep.published, 0); |
| 1303 | let s = w.worker.stats(); |
| 1304 | assert_eq!( |
| 1305 | (s.shutdown_unfinished_jobs, s.shutdown_unfinished_bytes), |
| 1306 | (1, OBJ) |
| 1307 | ); |
| 1308 | assert!( |
| 1309 | h1.is_held() && rel1.load(Ordering::SeqCst) == 0, |
| 1310 | "buffer kept" |
| 1311 | ); |
| 1312 | assert_eq!( |
| 1313 | w.store(9), |
| 1314 | Err(PlatformError::DeviceUnavailable), |
| 1315 | "intake closed" |
| 1316 | ); |
| 1317 | |
| 1318 | // The job keeps running after the deadline and ends normally. |
| 1319 | w.step.store(1_000_000_000, Ordering::SeqCst); |
| 1320 | let mut v = w.poll_all(); |
| 1321 | let t0 = Instant::now(); |
| 1322 | while terminals(&v).len() < 3 { |
| 1323 | v.extend(w.worker.poll(16)); |
| 1324 | assert!(t0.elapsed() < Duration::from_secs(20)); |
| 1325 | thread::yield_now(); |
| 1326 | } |
| 1327 | let by_job: HashMap<JobId, &Completion> = |
| 1328 | terminals(&v).into_iter().map(|c| (c.job, c)).collect(); |
| 1329 | assert_eq!(by_job.len(), 3, "exactly one terminal per job: {v:?}"); |
| 1330 | assert_eq!( |
| 1331 | by_job[&j1].terminal, |
| 1332 | Some(Terminal::Done(JobStage::Durable)) |
| 1333 | ); |
| 1334 | assert_eq!(by_job[&j2].terminal, Some(Terminal::Cancelled)); |
| 1335 | assert_eq!(by_job[&j3].terminal, Some(Terminal::Cancelled)); |
| 1336 | wait_for("buffer released with the job", || { |
| 1337 | rel1.load(Ordering::SeqCst) == 1 |
| 1338 | }); |
| 1339 | assert!(!h1.is_held()); |
| 1340 | } |
| 1341 | |
| 1342 | #[test] |
| 1343 | fn worker_shutdown_lets_jobs_past_fsync_publish() { |
| 1344 | let w = rig(); |
| 1345 | w.fake.script(JobScript::latency(100, 50_000_000)); |
| 1346 | let j = w.store(1).unwrap(); |
| 1347 | w.resume(); |
| 1348 | wait_for("file synced", || w.fake.now_us() >= 300); |
| 1349 | w.step.store(10_000_000, Ordering::SeqCst); |
| 1350 | let rep = w.worker.shutdown(2000); |
| 1351 | assert_eq!(rep.published, 1, "{rep:?}"); |
| 1352 | assert!(rep.unfinished.is_empty()); |
| 1353 | let v = w.collect(1); |
| 1354 | assert_eq!(terminals(&v)[0].job, j); |
| 1355 | assert_eq!( |
| 1356 | terminals(&v)[0].terminal, |
| 1357 | Some(Terminal::Done(JobStage::Durable)) |
| 1358 | ); |
| 1359 | } |
| 1360 | |
| 1361 | #[test] |
| 1362 | fn worker_shutdown_keeps_buffers_until_each_job_terminal() { |
| 1363 | // The store is stalled in real time (the worker thread is stuck inside a |
| 1364 | // call). Shutdown returns at its deadline; the buffers of the jobs that |
| 1365 | // are still in the device are released only when each reaches its terminal. |
| 1366 | let w = rig(); |
| 1367 | w.inject(2); |
| 1368 | w.fake.script(JobScript::fault(Fault::Hold)); |
| 1369 | w.fake.script(JobScript::fault(Fault::Hold)); |
| 1370 | let rel_s = Arc::new(AtomicU64::new(0)); |
| 1371 | let rel_l = Arc::new(AtomicU64::new(0)); |
| 1372 | let (js, hs, _ms) = w.store_with(1, released_guard(&rel_s)); |
| 1373 | let (jl, _ml, hl) = w.load_with(2, released_guard(&rel_l)); |
| 1374 | let (js, jl) = (js.unwrap(), jl.unwrap()); |
| 1375 | w.resume(); |
| 1376 | wait_for("both in the device", || { |
| 1377 | w.dispatched(js) && w.dispatched(jl) |
| 1378 | }); |
| 1379 | w.stall_store(); |
| 1380 | |
| 1381 | let t0 = Instant::now(); |
| 1382 | let rep = w.worker.shutdown(80); |
| 1383 | let el = t0.elapsed(); |
| 1384 | assert!( |
| 1385 | el >= Duration::from_millis(70) && el < Duration::from_secs(5), |
| 1386 | "{el:?}" |
| 1387 | ); |
| 1388 | let mut un: Vec<JobId> = rep.unfinished.iter().map(|u| u.job).collect(); |
| 1389 | un.sort(); |
| 1390 | assert_eq!(un, vec![js, jl], "{rep:?}"); |
| 1391 | assert!( |
| 1392 | hs.is_held() && hl.is_held(), |
| 1393 | "buffers kept past the deadline" |
| 1394 | ); |
| 1395 | assert_eq!( |
| 1396 | rel_s.load(Ordering::SeqCst) + rel_l.load(Ordering::SeqCst), |
| 1397 | 0 |
| 1398 | ); |
| 1399 | assert!( |
| 1400 | w.worker.state_lock_is_free(), |
| 1401 | "no lock is held while the store stalls" |
| 1402 | ); |
| 1403 | |
| 1404 | w.unstall_store(); |
| 1405 | let v = w.collect(2); |
| 1406 | assert!(terminals(&v) |
| 1407 | .iter() |
| 1408 | .all(|c| c.terminal == Some(Terminal::Cancelled))); |
| 1409 | wait_for("released with the terminals", || { |
| 1410 | rel_s.load(Ordering::SeqCst) == 1 && rel_l.load(Ordering::SeqCst) == 1 |
| 1411 | }); |
| 1412 | assert!(!hs.is_held() && !hl.is_held()); |
| 1413 | } |
| 1414 | |
| 1415 | #[test] |
| 1416 | fn worker_shutdown_cancels_queued_and_closes_intake() { |
| 1417 | let w = rig(); |
| 1418 | for n in 1..=3 { |
| 1419 | w.inject(n); |
| 1420 | } |
| 1421 | let rels: Vec<Arc<AtomicU64>> = (0..5).map(|_| Arc::new(AtomicU64::new(0))).collect(); |
| 1422 | let mut jobs = Vec::new(); |
| 1423 | for n in 1..=3u32 { |
| 1424 | jobs.push( |
| 1425 | w.load_with(n, released_guard(&rels[n as usize - 1])) |
| 1426 | .0 |
| 1427 | .unwrap(), |
| 1428 | ); |
| 1429 | } |
| 1430 | for n in 10..=11u32 { |
| 1431 | jobs.push( |
| 1432 | w.store_with(n, released_guard(&rels[(n - 10) as usize + 3])) |
| 1433 | .0 |
| 1434 | .unwrap(), |
| 1435 | ); |
| 1436 | } |
| 1437 | let t0 = Instant::now(); |
| 1438 | let rep = w.worker.shutdown(500); |
| 1439 | assert!( |
| 1440 | t0.elapsed() < Duration::from_millis(400), |
| 1441 | "nothing in flight: no waiting" |
| 1442 | ); |
| 1443 | assert_eq!(rep.cancelled, 5); |
| 1444 | assert!(rep.unfinished.is_empty()); |
| 1445 | assert_eq!(rep.published, 0); |
| 1446 | for r in &rels { |
| 1447 | assert_eq!(r.load(Ordering::SeqCst), 1, "queued buffers released once"); |
| 1448 | } |
| 1449 | let v = w.poll_all(); |
| 1450 | assert_eq!(terminals(&v).len(), 5); |
| 1451 | assert!(terminals(&v) |
| 1452 | .iter() |
| 1453 | .all(|c| c.terminal == Some(Terminal::Cancelled))); |
| 1454 | assert_eq!(w.load(1), Err(PlatformError::DeviceUnavailable)); |
| 1455 | assert_eq!( |
| 1456 | w.worker.submit_flush(Incarnation::seq(1)), |
| 1457 | Err(PlatformError::DeviceUnavailable) |
| 1458 | ); |
| 1459 | // A second call reports the same facts. |
| 1460 | let rep2 = w.worker.shutdown(10); |
| 1461 | assert_eq!(rep2.cancelled, 5); |
| 1462 | assert!(w.probe.submitted().is_empty(), "the store never saw them"); |
| 1463 | } |
| 1464 | |
| 1465 | #[test] |
| 1466 | fn restore_txn_holder_survives_sibling_failure_until_all_jobs_terminal() { |
| 1467 | // Findings 5 and B3: chunk A fails while B and C are mid-transfer. The |
| 1468 | // destinations of B and C stay held until each has produced its terminal. |
| 1469 | let w = rig(); |
| 1470 | let ka = w.inject(1); |
| 1471 | w.inject(2); |
| 1472 | w.inject(3); |
| 1473 | assert!(w.fake.corrupt_payload(&ka)); |
| 1474 | w.fake.script(JobScript::default()); // A: runs |
| 1475 | w.fake.script(JobScript::fault(Fault::Hold)); // B: mid-transfer |
| 1476 | w.fake.script(JobScript::fault(Fault::Hold)); // C: mid-transfer |
| 1477 | let rel: Vec<Arc<AtomicU64>> = (0..3).map(|_| Arc::new(AtomicU64::new(0))).collect(); |
| 1478 | let (ja, ma, _ha) = w.load_with(1, released_guard(&rel[0])); |
| 1479 | let (jb, mb, hb) = w.load_with(2, released_guard(&rel[1])); |
| 1480 | let (jc, mc, hc) = w.load_with(3, released_guard(&rel[2])); |
| 1481 | let (ja, jb, jc) = (ja.unwrap(), jb.unwrap(), jc.unwrap()); |
| 1482 | w.resume(); |
| 1483 | let v = w.collect(1); |
| 1484 | assert_eq!(terminals(&v)[0].job, ja); |
| 1485 | assert!(matches!( |
| 1486 | terminals(&v)[0].terminal, |
| 1487 | Some(Terminal::Failed(PlatformError::InvalidLayout)) |
| 1488 | )); |
| 1489 | wait_for("A's buffer released", || rel[0].load(Ordering::SeqCst) == 1); |
| 1490 | assert_eq!( |
| 1491 | ma.bytes(), |
| 1492 | vec![0xEE; 2 * BLOCK], |
| 1493 | "a failed chunk wrote nothing" |
| 1494 | ); |
| 1495 | |
| 1496 | // The txn is Draining. Freeze the device so nothing is reaped, then cancel the siblings. |
| 1497 | wait_for("B and C in the device", || { |
| 1498 | w.dispatched(jb) && w.dispatched(jc) |
| 1499 | }); |
| 1500 | w.stall_store(); |
| 1501 | assert_eq!(w.worker.cancel(jb), CancelOutcome::Cancelled); |
| 1502 | assert_eq!(w.worker.cancel(jc), CancelOutcome::Cancelled); |
| 1503 | assert!( |
| 1504 | hb.is_held() && hc.is_held(), |
| 1505 | "cancel acknowledged, the device is not done" |
| 1506 | ); |
| 1507 | assert_eq!( |
| 1508 | rel[1].load(Ordering::SeqCst) + rel[2].load(Ordering::SeqCst), |
| 1509 | 0 |
| 1510 | ); |
| 1511 | assert!(w.poll_all().is_empty(), "no terminal yet for B or C"); |
| 1512 | |
| 1513 | w.unstall_store(); |
| 1514 | let v = w.collect(2); |
| 1515 | let mut got: Vec<JobId> = terminals(&v).iter().map(|c| c.job).collect(); |
| 1516 | got.sort(); |
| 1517 | assert_eq!(got, vec![jb, jc]); |
| 1518 | assert!(terminals(&v) |
| 1519 | .iter() |
| 1520 | .all(|c| c.terminal == Some(Terminal::Cancelled))); |
| 1521 | wait_for("B and C released after their terminals", || { |
| 1522 | rel[1].load(Ordering::SeqCst) == 1 && rel[2].load(Ordering::SeqCst) == 1 |
| 1523 | }); |
| 1524 | assert_eq!(mb.bytes(), vec![0xEE; 2 * BLOCK]); |
| 1525 | assert_eq!(mc.bytes(), vec![0xEE; 2 * BLOCK]); |
| 1526 | assert_eq!(w.fake.take_poison_violations(), 0); |
| 1527 | } |
| 1528 | |
| 1529 | // ----------------------------------------------- the hard requirements |
| 1530 | |
| 1531 | /// Run `f` on its own thread; panic if it does not finish within `secs`. |
| 1532 | fn within<R: Send + 'static>(secs: u64, what: &str, f: impl FnOnce() -> R + Send + 'static) -> R { |
| 1533 | let (tx, rx) = mpsc::channel(); |
| 1534 | thread::spawn(move || { |
| 1535 | let _ = tx.send(f()); |
| 1536 | }); |
| 1537 | rx.recv_timeout(Duration::from_secs(secs)) |
| 1538 | .unwrap_or_else(|_| panic!("{what} blocked on the stalled store")) |
| 1539 | } |
| 1540 | |
| 1541 | #[test] |
| 1542 | fn worker_submit_and_poll_never_block_on_a_stalled_store() { |
| 1543 | let w = rig(); |
| 1544 | for n in 1..=4 { |
| 1545 | w.inject(n); |
| 1546 | } |
| 1547 | let first = w.load(1).unwrap(); |
| 1548 | // The worker thread gets stuck inside the store's submit of the first job. |
| 1549 | w.stall_store(); |
| 1550 | w.resume(); |
| 1551 | wait_for("worker stuck mid-submit", || w.probe.gate.waiting() >= 1); |
| 1552 | // wait until the job was actually handed over (it is `Dispatching` now) |
| 1553 | wait_for("job taken from the queue", || { |
| 1554 | w.worker.dispatch_order().len() == 1 |
| 1555 | }); |
| 1556 | |
| 1557 | let worker = Arc::new(w.worker); |
| 1558 | let probe = w.probe.clone(); |
| 1559 | let t0 = Instant::now(); |
| 1560 | let outcome = { |
| 1561 | let worker = worker.clone(); |
| 1562 | let fields = w.fields; |
| 1563 | let ns = w.ns; |
| 1564 | within(20, "submit/poll/cancel/capacity/lookup", move || { |
| 1565 | let mut accepted = Vec::new(); |
| 1566 | for i in 0..200u32 { |
| 1567 | let tokens: Vec<u32> = (0..8).map(|j| (2000 + i) * 1000 + j).collect(); |
| 1568 | let key = aien_kv_store::chunk_chain(&ns, 8, &tokens).unwrap()[0]; |
| 1569 | let h = fields.chunk_header(&ns, key, None, 0, 8, 1).unwrap(); |
| 1570 | let mem = Mem::new(2, 1); |
| 1571 | let (src, _) = mem.source(2, 4); |
| 1572 | if let Ok(j) = worker.submit_store(h, src, Incarnation::seq(i as u64)) { |
| 1573 | accepted.push(j); |
| 1574 | } |
| 1575 | let _ = worker.poll(8); |
| 1576 | let _ = worker.capacity(); |
| 1577 | let _ = worker.lookup(&[key]); |
| 1578 | let _ = worker.stats(); |
| 1579 | if i % 3 == 0 { |
| 1580 | if let Some(j) = accepted.pop() { |
| 1581 | let _ = worker.cancel(j); |
| 1582 | } |
| 1583 | } |
| 1584 | } |
| 1585 | // The job the worker is stuck on can be cancelled and polled too. |
| 1586 | let c = worker.cancel(first); |
| 1587 | assert_eq!( |
| 1588 | c, |
| 1589 | CancelOutcome::TooLate, |
| 1590 | "mid-dispatch: the answer is the safe one" |
| 1591 | ); |
| 1592 | (accepted.len(), worker.state_lock_is_free()) |
| 1593 | }) |
| 1594 | }; |
| 1595 | assert!(t0.elapsed() < Duration::from_secs(5), "{:?}", t0.elapsed()); |
| 1596 | assert!( |
| 1597 | outcome.0 > 0 && outcome.1, |
| 1598 | "no lock held while the store stalls" |
| 1599 | ); |
| 1600 | assert!(probe.gate.waiting() >= 1, "the worker was stuck all along"); |
| 1601 | |
| 1602 | // Let the store go: every accepted job ends exactly once. |
| 1603 | probe.gate.set(true); |
| 1604 | let t0 = Instant::now(); |
| 1605 | let mut all = Vec::new(); |
| 1606 | loop { |
| 1607 | all.extend(worker.poll(64)); |
| 1608 | let c = worker.capacity(); |
| 1609 | if c.restore_ops == 0 && c.park_ops == 0 { |
| 1610 | all.extend(worker.poll(64)); |
| 1611 | break; |
| 1612 | } |
| 1613 | assert!(t0.elapsed() < Duration::from_secs(30)); |
| 1614 | thread::yield_now(); |
| 1615 | } |
| 1616 | let mut per_job: HashMap<JobId, u32> = HashMap::new(); |
| 1617 | for c in terminals(&all) { |
| 1618 | *per_job.entry(c.job).or_default() += 1; |
| 1619 | } |
| 1620 | assert!(per_job.values().all(|n| *n == 1)); |
| 1621 | assert!(per_job.contains_key(&first)); |
| 1622 | assert_eq!(w.fake.take_poison_violations(), 0); |
| 1623 | } |
| 1624 | |
| 1625 | #[test] |
| 1626 | fn worker_submit_latency_is_independent_of_store_latency() { |
| 1627 | let w = rig(); |
| 1628 | for n in 1..=8 { |
| 1629 | w.inject(n); |
| 1630 | } |
| 1631 | // Deterministic (Grok C5 P2-5): the store is stuck for the whole run, so |
| 1632 | // a caller that touched it would hang here instead of being merely slow. |
| 1633 | w.resume(); |
| 1634 | w.stall_store(); |
| 1635 | let (tx, rx) = mpsc::channel(); |
| 1636 | thread::scope(|sc| { |
| 1637 | sc.spawn(|| { |
| 1638 | for i in 0..300u32 { |
| 1639 | let _ = w.load(1 + i % 8); |
| 1640 | let _ = w.store(100 + i); |
| 1641 | let _ = w.worker.poll(8); |
| 1642 | let _ = w.worker.capacity(); |
| 1643 | } |
| 1644 | let _ = tx.send(()); |
| 1645 | }); |
| 1646 | let finished = rx.recv_timeout(Duration::from_secs(30)).is_ok(); |
| 1647 | let stuck_calls = w.probe.submitted().len(); |
| 1648 | w.unstall_store(); |
| 1649 | assert!(finished, "a caller blocked on the stalled store"); |
| 1650 | assert!( |
| 1651 | stuck_calls <= 1, |
| 1652 | "the store really was stuck: {stuck_calls} submits" |
| 1653 | ); |
| 1654 | }); |
| 1655 | w.settle(); |
| 1656 | } |
| 1657 | |
| 1658 | #[test] |
| 1659 | fn worker_inner_io_runs_only_on_the_worker_thread() { |
| 1660 | let w = rig(); |
| 1661 | w.inject(1); |
| 1662 | let main = thread::current().id(); |
| 1663 | let _ = w.load(1).unwrap(); |
| 1664 | let _ = w.store(2).unwrap(); |
| 1665 | let _ = w.worker.submit_flush(Incarnation::seq(3)).unwrap(); |
| 1666 | w.resume(); |
| 1667 | w.collect(3); |
| 1668 | let _ = w.worker.shutdown(50); |
| 1669 | for what in ["submit", "poll", "drive", "shutdown"] { |
| 1670 | let t = w.probe.threads_of(what); |
| 1671 | assert_eq!(t.len(), 1, "{what}: {t:?}"); |
| 1672 | assert!(!t.contains(&main), "{what} ran on the caller's thread"); |
| 1673 | } |
| 1674 | let worker_thread = *w.probe.threads_of("submit").iter().next().unwrap(); |
| 1675 | assert_eq!(w.probe.threads_of("drive"), HashSet::from([worker_thread])); |
| 1676 | } |
| 1677 | |
| 1678 | #[test] |
| 1679 | fn worker_eviction_happens_on_worker_thread_not_in_submit() { |
| 1680 | // Finding 7: the quota holds exactly three objects and they are all there. |
| 1681 | let w = w_with(|c| c.quota_bytes = 3 * OBJ, |_| {}); |
| 1682 | for n in 1..=3 { |
| 1683 | w.inject(n); |
| 1684 | } |
| 1685 | let before = w.fake.capacity(); |
| 1686 | assert_eq!(before.used_bytes, 3 * OBJ); |
| 1687 | let job = w.store(10).unwrap(); |
| 1688 | let io = w.fake.stats(); |
| 1689 | assert_eq!( |
| 1690 | (io.unlinks, io.io_ops, io.evicted_bytes_total), |
| 1691 | (0, 0, 0), |
| 1692 | "submit evicts nothing" |
| 1693 | ); |
| 1694 | assert_eq!(w.fake.capacity().used_bytes, 3 * OBJ); |
| 1695 | assert_eq!(w.worker.capacity().reserved_bytes, OBJ); |
| 1696 | w.resume(); |
| 1697 | let v = w.collect(1); |
| 1698 | assert_eq!(terminals(&v)[0].job, job); |
| 1699 | assert_eq!( |
| 1700 | terminals(&v)[0].terminal, |
| 1701 | Some(Terminal::Done(JobStage::Durable)) |
| 1702 | ); |
| 1703 | let io = w.fake.stats(); |
| 1704 | assert!(io.unlinks >= 1 && io.evicted_bytes_total >= OBJ, "{io:?}"); |
| 1705 | let main = thread::current().id(); |
| 1706 | assert!(!w.probe.threads_of("drive").contains(&main)); |
| 1707 | assert_eq!(w.worker.capacity().inflight_bytes, 0); |
| 1708 | } |
| 1709 | |
| 1710 | #[test] |
| 1711 | fn worker_delete_skips_keys_with_jobs_and_unlinks_on_the_worker() { |
| 1712 | let w = rig(); |
| 1713 | let k1 = w.inject(1); |
| 1714 | let k2 = w.inject(2); |
| 1715 | let job = w.load(1).unwrap(); // queued: k1 has a job |
| 1716 | assert_eq!( |
| 1717 | w.worker.delete(&[k1]), |
| 1718 | 0, |
| 1719 | "a key with a queued load is not deleted" |
| 1720 | ); |
| 1721 | assert_eq!(w.worker.delete(&[k2]), 1); |
| 1722 | assert_eq!(w.worker.lookup(&[k2]), vec![None], "marked at once"); |
| 1723 | assert_eq!( |
| 1724 | w.fake.stats().unlinks, |
| 1725 | 0, |
| 1726 | "the unlink is not done by the caller" |
| 1727 | ); |
| 1728 | w.resume(); |
| 1729 | w.collect(1); |
| 1730 | let _ = job; |
| 1731 | wait_for("unlink done by the worker", || w.fake.stats().unlinks == 1); |
| 1732 | assert_eq!(w.worker.lookup(&[k1]), vec![Some(PAYLOAD)]); |
| 1733 | } |
| 1734 | |
| 1735 | #[test] |
| 1736 | fn worker_every_job_yields_exactly_one_terminal_completion() { |
| 1737 | let w = w_with( |
| 1738 | |c| { |
| 1739 | c.quota_bytes = 1 << 40; |
| 1740 | c.max_objects = 1 << 20; |
| 1741 | }, |
| 1742 | |c| { |
| 1743 | c.start_paused = false; |
| 1744 | c.dispatch_depth = 3; |
| 1745 | }, |
| 1746 | ); |
| 1747 | for n in 1..=16 { |
| 1748 | w.inject(n); |
| 1749 | } |
| 1750 | // A mixed bag of misbehaviours, consumed in dispatch order. |
| 1751 | for i in 0..400 { |
| 1752 | let s = match i % 9 { |
| 1753 | 0 => JobScript::fault(Fault::DiskFull), |
| 1754 | 1 => JobScript::fault(Fault::TornWrite), |
| 1755 | 2 => JobScript::fault(Fault::DuplicateCompletion), |
| 1756 | 3 => JobScript::fault(Fault::CompletionAfterCancel), |
| 1757 | 4 => JobScript::latency(300, 300).with(Fault::StallFsync(500)), |
| 1758 | 5 => JobScript::fault(Fault::QueueFull), |
| 1759 | _ => JobScript::default(), |
| 1760 | }; |
| 1761 | w.fake.script(s); |
| 1762 | } |
| 1763 | let worker = Arc::new(w.worker); |
| 1764 | let accepted: Arc<Mutex<BTreeSet<(JobId, Incarnation)>>> = |
| 1765 | Arc::new(Mutex::new(BTreeSet::new())); |
| 1766 | let done = Arc::new(AtomicBool::new(false)); |
| 1767 | let mut handles = Vec::new(); |
| 1768 | // Each submitter keeps going until it has ACCEPT_PER_THREAD accepted jobs, |
| 1769 | // so the size of the workload does not depend on how fast the dispatcher |
| 1770 | // drains on this host (sc#575). Bounded by attempts and wall time. |
| 1771 | const ACCEPT_PER_THREAD: usize = 60; |
| 1772 | const MAX_ATTEMPTS: u32 = 999; |
| 1773 | let deadline = Instant::now() + Duration::from_secs(30); |
| 1774 | for t in 0..4u32 { |
| 1775 | let worker = worker.clone(); |
| 1776 | let accepted = accepted.clone(); |
| 1777 | let fields = w.fields; |
| 1778 | let ns = w.ns; |
| 1779 | handles.push(thread::spawn(move || { |
| 1780 | let mut mine = 0usize; |
| 1781 | for i in 0..MAX_ATTEMPTS { |
| 1782 | if mine >= ACCEPT_PER_THREAD || Instant::now() >= deadline { |
| 1783 | break; |
| 1784 | } |
| 1785 | let n = t * 1000 + i; |
| 1786 | let tokens: Vec<u32> = (0..8).map(|j| (5000 + n % 40) * 1000 + j).collect(); |
| 1787 | let key = aien_kv_store::chunk_chain(&ns, 8, &tokens).unwrap()[0]; |
| 1788 | let h = fields.chunk_header(&ns, key, None, 0, 8, 1).unwrap(); |
| 1789 | let r = match i % 5 { |
| 1790 | 0 | 1 => { |
| 1791 | let mem = Mem::new(2, 3); |
| 1792 | let (src, _) = mem.source(2, 4); |
| 1793 | worker.submit_store(h, src, Incarnation::seq(n as u64)) |
| 1794 | } |
| 1795 | 2 | 3 => { |
| 1796 | let k = 1 + (n % 16); |
| 1797 | let tokens: Vec<u32> = (0..8).map(|j| k * 1000 + j).collect(); |
| 1798 | let key = aien_kv_store::chunk_chain(&ns, 8, &tokens).unwrap()[0]; |
| 1799 | let h = fields.chunk_header(&ns, key, None, 0, 8, 1).unwrap(); |
| 1800 | let mem = Mem::new(2, 0xEE); |
| 1801 | let dst = mem.dest(2).0; |
| 1802 | worker.submit_load(key, &h, dst, Incarnation::seq(n as u64)) |
| 1803 | } |
| 1804 | _ => worker.submit_flush(Incarnation::seq(n as u64)), |
| 1805 | }; |
| 1806 | match r { |
| 1807 | Ok(j) => { |
| 1808 | mine += 1; |
| 1809 | accepted |
| 1810 | .lock() |
| 1811 | .unwrap() |
| 1812 | .insert((j, Incarnation::seq(n as u64))); |
| 1813 | if i % 7 == 0 { |
| 1814 | let _ = worker.cancel(j); |
| 1815 | } |
| 1816 | } |
| 1817 | Err(PlatformError::QueueFull) |
| 1818 | | Err(PlatformError::DeviceUnavailable) |
| 1819 | | Err(PlatformError::OutOfMemory) => thread::sleep(Duration::from_micros(200)), |
| 1820 | Err(e) => panic!("{e:?}"), |
| 1821 | } |
| 1822 | } |
| 1823 | })); |
| 1824 | } |
| 1825 | let collector = { |
| 1826 | let worker = worker.clone(); |
| 1827 | let done = done.clone(); |
| 1828 | thread::spawn(move || { |
| 1829 | let mut per_job: HashMap<(JobId, Incarnation), u32> = HashMap::new(); |
| 1830 | let mut last = Instant::now(); |
| 1831 | loop { |
| 1832 | let v = worker.poll(64); |
| 1833 | if v.is_empty() { |
| 1834 | if done.load(Ordering::SeqCst) { |
| 1835 | let c = worker.capacity(); |
| 1836 | if c.restore_ops == 0 && c.park_ops == 0 { |
| 1837 | for c in worker.poll(1024) { |
| 1838 | if c.terminal.is_some() { |
| 1839 | *per_job.entry((c.job, c.incarnation)).or_default() += 1; |
| 1840 | } |
| 1841 | } |
| 1842 | return per_job; |
| 1843 | } |
| 1844 | } |
| 1845 | assert!(last.elapsed() < Duration::from_secs(60), "stalled"); |
| 1846 | thread::yield_now(); |
| 1847 | continue; |
| 1848 | } |
| 1849 | last = Instant::now(); |
| 1850 | for c in v { |
| 1851 | if c.terminal.is_some() { |
| 1852 | *per_job.entry((c.job, c.incarnation)).or_default() += 1; |
| 1853 | } |
| 1854 | } |
| 1855 | } |
| 1856 | }) |
| 1857 | }; |
| 1858 | for h in handles { |
| 1859 | h.join().unwrap(); |
| 1860 | } |
| 1861 | done.store(true, Ordering::SeqCst); |
| 1862 | let per_job = collector.join().unwrap(); |
| 1863 | let accepted = accepted.lock().unwrap(); |
| 1864 | assert!( |
| 1865 | accepted.len() >= 4 * ACCEPT_PER_THREAD, |
| 1866 | "a real workload ran ({} accepted, want {})", |
| 1867 | accepted.len(), |
| 1868 | 4 * ACCEPT_PER_THREAD |
| 1869 | ); |
| 1870 | let got: BTreeSet<(JobId, Incarnation)> = per_job.keys().copied().collect(); |
| 1871 | assert_eq!( |
| 1872 | &got, &*accepted, |
| 1873 | "a terminal for every accepted request (job, incarnation) and for nothing else" |
| 1874 | ); |
| 1875 | assert!( |
| 1876 | per_job.values().all(|n| *n == 1), |
| 1877 | "exactly one each: {per_job:?}" |
| 1878 | ); |
| 1879 | let s = worker.stats(); |
| 1880 | assert_eq!(s.completion_overflow_total, 0); |
| 1881 | assert_eq!( |
| 1882 | s.terminal_done + s.terminal_failed + s.terminal_cancelled, |
| 1883 | accepted |
| 1884 | .iter() |
| 1885 | .map(|(j, _)| *j) |
| 1886 | .collect::<BTreeSet<_>>() |
| 1887 | .len() as u64 |
| 1888 | ); |
| 1889 | let c = worker.capacity(); |
| 1890 | assert_eq!((c.restore_ops, c.park_ops, c.inflight_bytes), (0, 0, 0)); |
| 1891 | assert!(w.fake.live_jobs().is_empty()); |
| 1892 | assert_eq!(w.fake.take_poison_violations(), 0); |
| 1893 | } |
| 1894 | |
| 1895 | #[test] |
| 1896 | fn worker_refusal_by_the_store_becomes_one_failed_terminal() { |
| 1897 | let w = rig(); |
| 1898 | w.fake.script(JobScript::fault(Fault::QueueFull)); |
| 1899 | let rel = Arc::new(AtomicU64::new(0)); |
| 1900 | let (job, _h, _m) = w.store_with(1, released_guard(&rel)); |
| 1901 | let job = job.unwrap(); |
| 1902 | assert_eq!(w.worker.capacity().park_ops, 1); |
| 1903 | w.resume(); |
| 1904 | let v = w.collect(1); |
| 1905 | let t = terminals(&v); |
| 1906 | assert_eq!((t.len(), t[0].job), (1, job)); |
| 1907 | assert_eq!( |
| 1908 | t[0].terminal, |
| 1909 | Some(Terminal::Failed(PlatformError::QueueFull)) |
| 1910 | ); |
| 1911 | assert_eq!(w.worker.stats().inner_refusals_total, 1); |
| 1912 | let c = w.worker.capacity(); |
| 1913 | assert_eq!((c.park_ops, c.inflight_bytes, c.reserved_bytes), (0, 0, 0)); |
| 1914 | wait_for("source released", || rel.load(Ordering::SeqCst) == 1); |
| 1915 | } |
| 1916 | |
| 1917 | #[test] |
| 1918 | fn worker_quota_refusal_is_a_failed_terminal_not_a_submit_error() { |
| 1919 | // DOCS SILENT on where the quota check lives when a worker fronts a store: |
| 1920 | // the worker cannot know what is evictable, so the store decides at dispatch. |
| 1921 | let w = w_with(|c| c.quota_bytes = OBJ / 2, |_| {}); |
| 1922 | let job = w.store(1).expect("accepted by the worker"); |
| 1923 | w.resume(); |
| 1924 | let v = w.collect(1); |
| 1925 | assert_eq!(terminals(&v)[0].job, job); |
| 1926 | assert_eq!( |
| 1927 | terminals(&v)[0].terminal, |
| 1928 | Some(Terminal::Failed(PlatformError::OutOfMemory)) |
| 1929 | ); |
| 1930 | assert_eq!(w.worker.capacity().reserved_bytes, 0); |
| 1931 | } |
| 1932 | |
| 1933 | #[test] |
| 1934 | fn worker_store_dedup_makes_every_owner_cancel_safe() { |
| 1935 | let w = rig(); |
| 1936 | let a = w.store(1).unwrap(); |
| 1937 | // A second owner (another incarnation) storing the same key joins the job. |
| 1938 | let (_, h) = w.chunk(1); |
| 1939 | let mem = Mem::new(2, 0); |
| 1940 | let (src, _hold) = mem.source(2, 4); |
| 1941 | let second = Incarnation::seq(901); |
| 1942 | let b = w.worker.submit_store(h, src, second).unwrap(); |
| 1943 | assert_eq!( |
| 1944 | a, b, |
| 1945 | "a store of a key already in flight returns the existing job" |
| 1946 | ); |
| 1947 | // The same incarnation resubmitting is idempotent: same job, no new waiter. |
| 1948 | assert_eq!(w.store(1).unwrap(), a); |
| 1949 | assert_eq!(w.worker.capacity().park_ops, 1); |
| 1950 | assert_eq!(w.worker.stats().store_dedup_total, 2); |
| 1951 | assert_eq!( |
| 1952 | w.worker.cancel(a), |
| 1953 | CancelOutcome::TooLate, |
| 1954 | "the other owner still wants it" |
| 1955 | ); |
| 1956 | w.resume(); |
| 1957 | let v = w.collect(2); |
| 1958 | let t = terminals(&v); |
| 1959 | assert_eq!(t.len(), 2, "one terminal per owner: {v:?}"); |
| 1960 | assert!(t |
| 1961 | .iter() |
| 1962 | .all(|x| x.terminal == Some(Terminal::Done(JobStage::Durable)))); |
| 1963 | assert!(t.iter().any(|x| x.incarnation == second)); |
| 1964 | assert!(w.fake.payload_of(&w.key(1)).is_some()); |
| 1965 | } |
| 1966 | |
| 1967 | #[test] |
| 1968 | fn worker_flush_is_a_zero_byte_park_job() { |
| 1969 | let w = rig(); |
| 1970 | let f = w.worker.submit_flush(Incarnation::seq(5)).unwrap(); |
| 1971 | let cap = w.worker.capacity(); |
| 1972 | assert_eq!((cap.park_ops, cap.inflight_bytes), (1, 0)); |
| 1973 | w.resume(); |
| 1974 | let v = w.collect(1); |
| 1975 | assert_eq!(terminals(&v)[0].job, f); |
| 1976 | assert_eq!( |
| 1977 | terminals(&v)[0].terminal, |
| 1978 | Some(Terminal::Done(JobStage::Durable)) |
| 1979 | ); |
| 1980 | assert_eq!(w.worker.stats().dispatched_park, 1); |
| 1981 | } |
| 1982 | |
| 1983 | #[test] |
| 1984 | fn worker_submit_refused_while_the_store_is_recovering() { |
| 1985 | let w = w_with(|c| c.start_recovering = true, |_| {}); |
| 1986 | w.inject(1); |
| 1987 | assert_eq!(w.store(2), Err(PlatformError::QueueFull)); |
| 1988 | assert_eq!(w.load(1), Err(PlatformError::QueueFull)); |
| 1989 | let p = w.worker.recover_step(10); |
| 1990 | assert!(p.done); |
| 1991 | assert!(w.store(2).is_ok(), "open again once the walk is complete"); |
| 1992 | } |
| 1993 | |
| 1994 | #[test] |
| 1995 | fn worker_load_of_unknown_key_is_object_not_found() { |
| 1996 | let w = rig(); |
| 1997 | let (k, _) = w.chunk(77); |
| 1998 | assert_eq!(w.load(77), Err(PlatformError::ObjectNotFound(k.0))); |
| 1999 | assert_eq!(w.worker.capacity().restore_ops, 0); |
| 2000 | } |
| 2001 | |
| 2002 | #[test] |
| 2003 | fn worker_rejects_header_and_source_that_disagree() { |
| 2004 | let w = rig(); |
| 2005 | let (_, mut h) = w.chunk(1); |
| 2006 | h.payload_len += 1; |
| 2007 | let mem = Mem::new(2, 0); |
| 2008 | let (src, _) = mem.source(2, 4); |
| 2009 | assert_eq!( |
| 2010 | w.worker.submit_store(h, src, Incarnation::seq(1)), |
| 2011 | Err(PlatformError::InvalidLayout) |
| 2012 | ); |
| 2013 | assert_eq!(w.worker.capacity().park_ops, 0); |
| 2014 | } |
| 2015 | |
| 2016 | #[test] |
| 2017 | fn dropping_the_worker_does_not_wait_for_a_stalled_store() { |
| 2018 | let w = rig(); |
| 2019 | let rel = Arc::new(AtomicU64::new(0)); |
| 2020 | w.fake.script(JobScript::fault(Fault::Hold)); |
| 2021 | let (j, _h, _m) = w.store_with(1, released_guard(&rel)); |
| 2022 | let j = j.unwrap(); |
| 2023 | w.resume(); |
| 2024 | wait_for("dispatch", || w.dispatched(j)); |
| 2025 | w.stall_store(); |
| 2026 | let probe = w.probe.clone(); |
| 2027 | let W { |
| 2028 | worker, |
| 2029 | probe: rig_probe, |
| 2030 | .. |
| 2031 | } = w; |
| 2032 | drop(rig_probe); |
| 2033 | within(10, "drop of the worker", move || drop(worker)); |
| 2034 | assert_eq!( |
| 2035 | rel.load(Ordering::SeqCst), |
| 2036 | 0, |
| 2037 | "the buffer is still the store's" |
| 2038 | ); |
| 2039 | // The detached thread finishes when the store lets go, then lets go of the store. |
| 2040 | probe.gate.set(true); |
| 2041 | wait_for("buffer released once the job ended", || { |
| 2042 | rel.load(Ordering::SeqCst) == 1 |
| 2043 | }); |
| 2044 | wait_for("worker thread gone", || Arc::strong_count(&probe) == 1); |
| 2045 | } |
| 2046 | |
| 2047 | #[test] |
| 2048 | fn worker_panic_in_the_store_fails_live_jobs_once() { |
| 2049 | let boom = Arc::new(AtomicBool::new(false)); |
| 2050 | let fields = tiny(); |
| 2051 | let ns = fields.namespace_id().unwrap(); |
| 2052 | let fake = Arc::new(FakeKvStore::new(FakeConfig::new(ns))); |
| 2053 | let b = boom.clone(); |
| 2054 | let f2 = fake.clone(); |
| 2055 | let worker = StorageWorker::spawn( |
| 2056 | fake.clone(), |
| 2057 | WorkerConfig { |
| 2058 | idle_poll: Duration::ZERO, |
| 2059 | ..WorkerConfig::default() |
| 2060 | }, |
| 2061 | move || { |
| 2062 | if b.load(Ordering::SeqCst) { |
| 2063 | panic!("injected store failure"); |
| 2064 | } |
| 2065 | f2.advance(0); |
| 2066 | }, |
| 2067 | ) |
| 2068 | .unwrap(); |
| 2069 | fake.script(JobScript::fault(Fault::Hold)); |
| 2070 | let mem = Mem::new(2, 1); |
| 2071 | let (src, _) = mem.source(2, 4); |
| 2072 | let tokens: Vec<u32> = (0..8).collect(); |
| 2073 | let key = aien_kv_store::chunk_chain(&ns, 8, &tokens).unwrap()[0]; |
| 2074 | let h = fields.chunk_header(&ns, key, None, 0, 8, 1).unwrap(); |
| 2075 | let job = worker.submit_store(h, src, Incarnation::seq(1)).unwrap(); |
| 2076 | wait_for("dispatch", || worker.inner_job(job).is_some()); |
| 2077 | let inner = worker.inner_job(job).unwrap(); |
| 2078 | boom.store(true, Ordering::SeqCst); |
| 2079 | wait_for("the worker failed", || { |
| 2080 | worker.capacity().state == aien_kv_store::StoreState::Failed |
| 2081 | }); |
| 2082 | // The store still holds the source (Hold): the job may fail only once |
| 2083 | // the store lets go (Grok C5 P1-3). |
| 2084 | assert_eq!(fake.cancel(inner), CancelOutcome::Cancelled); |
| 2085 | fake.advance(0); |
| 2086 | let mut v = Vec::new(); |
| 2087 | wait_for("terminal after the panic", || { |
| 2088 | v.extend(worker.poll(8)); |
| 2089 | !terminals(&v).is_empty() |
| 2090 | }); |
| 2091 | assert_eq!(terminals(&v).len(), 1); |
| 2092 | assert!(matches!( |
| 2093 | terminals(&v)[0].terminal, |
| 2094 | Some(Terminal::Failed(PlatformError::HardwareFault(_))) |
| 2095 | )); |
| 2096 | assert_eq!(worker.capacity().park_ops, 0); |
| 2097 | let mem = Mem::new(2, 1); |
| 2098 | let (src, _) = mem.source(2, 4); |
| 2099 | let h = fields.chunk_header(&ns, key, None, 0, 8, 1).unwrap(); |
| 2100 | assert_eq!( |
| 2101 | worker.submit_store(h, src, Incarnation::seq(2)), |
| 2102 | Err(PlatformError::DeviceUnavailable) |
| 2103 | ); |
| 2104 | } |
| 2105 | |
| 2106 | #[test] |
| 2107 | fn worker_config_reads_the_documented_settings() { |
| 2108 | use std::collections::HashMap; |
| 2109 | let env: HashMap<&str, &str> = HashMap::from([ |
| 2110 | ("AIEN_KV_STORE_MAX_RESTORE_OPS", "12"), |
| 2111 | ("AIEN_KV_STORE_MAX_PARK_OPS", "5"), |
| 2112 | ("AIEN_KV_STORE_MAX_WAITERS_PER_JOB", "8"), |
| 2113 | ("AIEN_KV_STORE_MAX_INFLIGHT_BYTES", "1048576"), |
| 2114 | ("AIEN_KV_STORE_DRAIN_MS", "250"), |
| 2115 | ]); |
| 2116 | let c = WorkerConfig::from_lookup(|n| env.get(n).map(|s| s.to_string())).unwrap(); |
| 2117 | assert_eq!( |
| 2118 | (c.max_restore_ops, c.max_park_ops, c.max_waiters_per_job), |
| 2119 | (12, 5, 8) |
| 2120 | ); |
| 2121 | assert_eq!((c.max_inflight_bytes, c.drain_ms), (1 << 20, 250)); |
| 2122 | // Unset: the documented defaults. |
| 2123 | let d = WorkerConfig::from_lookup(|_| None).unwrap(); |
| 2124 | assert_eq!( |
| 2125 | ( |
| 2126 | d.max_restore_ops, |
| 2127 | d.max_park_ops, |
| 2128 | d.max_inflight_bytes, |
| 2129 | d.drain_ms |
| 2130 | ), |
| 2131 | (48, 64, 256 << 20, 2000) |
| 2132 | ); |
| 2133 | // Garbage is refused, naming the setting; it is not silently replaced. |
| 2134 | for bad in ["abc", "-1", "0", "", "1.5"] { |
| 2135 | let e = WorkerConfig::from_lookup(|n| { |
| 2136 | (n == "AIEN_KV_STORE_MAX_PARK_OPS").then(|| bad.to_string()) |
| 2137 | }) |
| 2138 | .unwrap_err(); |
| 2139 | assert_eq!(e.name, "AIEN_KV_STORE_MAX_PARK_OPS", "{bad:?}"); |
| 2140 | } |
| 2141 | assert!( |
| 2142 | WorkerConfig::from_lookup(|n| { (n == "AIEN_KV_STORE_DRAIN_MS").then(|| "0".to_string()) }) |
| 2143 | .is_ok(), |
| 2144 | "a zero drain deadline is allowed" |
| 2145 | ); |
| 2146 | } |
| 2147 | |
| 2148 | // ------------------------------------------------- incarnation (ADR 5.3, P1) |
| 2149 | |
| 2150 | #[test] |
| 2151 | fn incarnation_keeps_the_full_64_bit_sequence_id_and_the_epoch() { |
| 2152 | // The scheduler's sequence id is slot << 32 | generation: all 64 bits are used. |
| 2153 | let id = (7u64 << 32) | 9; |
| 2154 | let a = Incarnation::new(id, 1); |
| 2155 | assert_eq!(a.seq_id, id); |
| 2156 | assert_eq!(a.epoch, 1); |
| 2157 | assert_ne!(a, Incarnation::new(id, 2), "same sequence, later epoch"); |
| 2158 | assert_ne!(a, Incarnation::new(id & 0xFFFF_FFFF, 1), "high bits matter"); |
| 2159 | assert_ne!(a, Incarnation::new(id ^ (1 << 63), 1)); |
| 2160 | } |
| 2161 | |
| 2162 | #[test] |
| 2163 | fn stale_completion_with_reused_seq_id_but_new_epoch_is_rejected() { |
| 2164 | // The job belongs to (seq 3, epoch 1). A completion for (seq 3, epoch 2) is a |
| 2165 | // different residency of the same sequence id: it must never be committed. |
| 2166 | let w = rig(); |
| 2167 | w.fake.script(JobScript::fault(Fault::Hold)); |
| 2168 | let (k, h) = w.chunk(3); |
| 2169 | let (src_mem, inc) = (Mem::new(2, 0), Incarnation::new(3, 1)); |
| 2170 | let p = pattern(3, PAYLOAD as usize); |
| 2171 | src_mem.fill_with(|i| p[i]); |
| 2172 | let (src, _handle) = src_mem.source(2, 4); |
| 2173 | let job = w.worker.submit_store(h, src, inc).unwrap(); |
| 2174 | w.resume(); |
| 2175 | wait_for("dispatch", || w.dispatched(job)); |
| 2176 | let inner = w.worker.inner_job(job).unwrap(); |
| 2177 | w.probe.forge(Completion { |
| 2178 | job: inner, |
| 2179 | incarnation: Incarnation::new(3, 2), |
| 2180 | key: k, |
| 2181 | stage: JobStage::Durable, |
| 2182 | terminal: Some(Terminal::Done(JobStage::Durable)), |
| 2183 | publish: PublishOutcome::Durable, |
| 2184 | bytes: PAYLOAD, |
| 2185 | elapsed_us: 1, |
| 2186 | holder: None, |
| 2187 | }); |
| 2188 | wait_for("forged completion dropped", || { |
| 2189 | w.worker.stats().stale_completions_total >= 1 |
| 2190 | }); |
| 2191 | assert!( |
| 2192 | w.poll_all().is_empty(), |
| 2193 | "the other epoch's completion is dropped" |
| 2194 | ); |
| 2195 | assert_eq!(w.worker.capacity().park_ops, 1, "the job is still live"); |
| 2196 | assert!(w.fake.release(inner)); |
| 2197 | let v = w.collect(1); |
| 2198 | assert_eq!( |
| 2199 | terminals(&v)[0].incarnation, |
| 2200 | inc, |
| 2201 | "the caller's own token comes back" |
| 2202 | ); |
| 2203 | } |
| 2204 | |
| 2205 | #[test] |
| 2206 | fn coalesced_waiters_each_get_a_terminal_with_their_own_incarnation() { |
| 2207 | // Three requests, two of them from the same sequence id in different epochs, |
| 2208 | // plus one trait-level attach. One I/O, four terminals, each carrying its |
| 2209 | // own waiter's token: the completion never exposes one token for all. |
| 2210 | let w = rig(); |
| 2211 | let k = w.inject(7); |
| 2212 | let (_, h) = w.chunk(7); |
| 2213 | let mem = Mem::new(2, 0xEE); |
| 2214 | let leader = Incarnation::new(10, 1); |
| 2215 | let job = w |
| 2216 | .worker |
| 2217 | .submit_load_coalesced(k, &h, || mem.dest(2).0, leader) |
| 2218 | .unwrap() |
| 2219 | .job(); |
| 2220 | let followers = [Incarnation::new(10, 2), Incarnation::new(11, 1)]; |
| 2221 | for inc in followers { |
| 2222 | let t = w |
| 2223 | .worker |
| 2224 | .submit_load_coalesced(k, &h, || panic!("a follower needs no buffer"), inc) |
| 2225 | .unwrap(); |
| 2226 | assert_eq!(t, LoadTicket::Attached(job)); |
| 2227 | } |
| 2228 | let extra = Incarnation::new(12, 5); |
| 2229 | assert_eq!(w.worker.attach_waiter(job, extra), Ok(())); |
| 2230 | w.resume(); |
| 2231 | let v = w.collect(4); |
| 2232 | let t = terminals(&v); |
| 2233 | assert_eq!(t.len(), 4, "one terminal per waiter: {v:?}"); |
| 2234 | assert!(t.iter().all(|c| c.job == job)); |
| 2235 | assert!(t |
| 2236 | .iter() |
| 2237 | .all(|c| c.terminal == Some(Terminal::Done(JobStage::Completed)))); |
| 2238 | let mut got: Vec<Incarnation> = t.iter().map(|c| c.incarnation).collect(); |
| 2239 | got.sort(); |
| 2240 | let mut want = vec![leader, followers[0], followers[1], extra]; |
| 2241 | want.sort(); |
| 2242 | assert_eq!(got, want, "each waiter gets exactly its own token back"); |
| 2243 | assert_eq!(w.fake.stats().reads, 1, "still one read"); |
| 2244 | } |
| 2245 | |
| 2246 | #[test] |
| 2247 | fn cancel_waiter_removes_exactly_that_incarnation() { |
| 2248 | let w = rig(); |
| 2249 | let k = w.inject(7); |
| 2250 | let (_, h) = w.chunk(7); |
| 2251 | let mem = Mem::new(2, 0xEE); |
| 2252 | let (a, b, c) = ( |
| 2253 | Incarnation::new(1, 1), |
| 2254 | Incarnation::new(1, 2), |
| 2255 | Incarnation::new(2, 1), |
| 2256 | ); |
| 2257 | let job = w |
| 2258 | .worker |
| 2259 | .submit_load_coalesced(k, &h, || mem.dest(2).0, a) |
| 2260 | .unwrap() |
| 2261 | .job(); |
| 2262 | w.worker.attach_waiter(job, b).unwrap(); |
| 2263 | w.worker.attach_waiter(job, c).unwrap(); |
| 2264 | assert_eq!( |
| 2265 | w.worker.cancel_waiter(job, b), |
| 2266 | CancelOutcome::TooLate, |
| 2267 | "others remain" |
| 2268 | ); |
| 2269 | assert_eq!( |
| 2270 | w.worker.cancel_waiter(job, b), |
| 2271 | CancelOutcome::TooLate, |
| 2272 | "a token that is not waiting changes nothing" |
| 2273 | ); |
| 2274 | assert_eq!(w.worker.capacity().restore_ops, 1); |
| 2275 | assert!(w.poll_all().is_empty(), "no terminal before the read ends"); |
| 2276 | w.resume(); |
| 2277 | let v = w.collect(3); |
| 2278 | let mut got: Vec<Incarnation> = terminals(&v).iter().map(|x| x.incarnation).collect(); |
| 2279 | got.sort(); |
| 2280 | let mut want = vec![a, b, c]; |
| 2281 | want.sort(); |
| 2282 | assert_eq!( |
| 2283 | got, want, |
| 2284 | "every waiter, detached or not, gets exactly one terminal after the I/O ended" |
| 2285 | ); |
| 2286 | assert!(w.poll_all().is_empty(), "and no second one"); |
| 2287 | |
| 2288 | // Detaching every waiter in turn cancels the job only on the last one. |
| 2289 | let w = w_with(|_| {}, |_| {}); |
| 2290 | let k = w.inject(8); |
| 2291 | let (_, h) = w.chunk(8); |
| 2292 | let mem = Mem::new(2, 0xEE); |
| 2293 | let job = w |
| 2294 | .worker |
| 2295 | .submit_load_coalesced(k, &h, || mem.dest(2).0, a) |
| 2296 | .unwrap() |
| 2297 | .job(); |
| 2298 | w.worker.attach_waiter(job, b).unwrap(); |
| 2299 | w.worker.attach_waiter(job, c).unwrap(); |
| 2300 | assert_eq!(w.worker.cancel_waiter(job, a), CancelOutcome::TooLate); |
| 2301 | assert_eq!(w.worker.cancel_waiter(job, c), CancelOutcome::TooLate); |
| 2302 | assert_eq!(w.worker.cancel_waiter(job, b), CancelOutcome::Cancelled); |
| 2303 | let v = w.collect(3); |
| 2304 | assert!(terminals(&v) |
| 2305 | .iter() |
| 2306 | .all(|x| x.terminal == Some(Terminal::Cancelled))); |
| 2307 | } |
| 2308 | |
| 2309 | #[test] |
| 2310 | fn the_same_incarnation_cannot_wait_twice_on_one_job() { |
| 2311 | let w = rig(); |
| 2312 | let k = w.inject(7); |
| 2313 | let (_, h) = w.chunk(7); |
| 2314 | let mem = Mem::new(2, 0xEE); |
| 2315 | let a = Incarnation::new(5, 1); |
| 2316 | let job = w |
| 2317 | .worker |
| 2318 | .submit_load_coalesced(k, &h, || mem.dest(2).0, a) |
| 2319 | .unwrap() |
| 2320 | .job(); |
| 2321 | assert!(w.worker.attach_waiter(job, a).is_err(), "duplicate refused"); |
| 2322 | assert_eq!( |
| 2323 | w.worker.attach_waiter(job, Incarnation::new(5, 2)), |
| 2324 | Ok(()), |
| 2325 | "a new epoch of the same slot is a different waiter" |
| 2326 | ); |
| 2327 | w.resume(); |
| 2328 | assert_eq!(terminals(&w.collect(2)).len(), 2); |
| 2329 | } |
| 2330 | |
| 2331 | #[test] |
| 2332 | fn attach_is_refused_when_completion_slots_are_exhausted() { |
| 2333 | // ADR 7.1 item 9: every waiter will need a terminal completion slot, held |
| 2334 | // until the caller polls it. With room for 6 completions, one job holds 3 |
| 2335 | // and three waiters take the rest; the next waiter is refused, not queued. |
| 2336 | let w = w_with( |
| 2337 | |_| {}, |
| 2338 | |c| { |
| 2339 | c.max_restore_ops = 1; |
| 2340 | c.max_park_ops = 1; |
| 2341 | c.max_waiters_per_job = 16; |
| 2342 | c.max_waiters_total = 1024; |
| 2343 | }, |
| 2344 | ); |
| 2345 | let k = w.inject(7); |
| 2346 | let (_, h) = w.chunk(7); |
| 2347 | let mem = Mem::new(2, 0xEE); |
| 2348 | let job = w |
| 2349 | .worker |
| 2350 | .submit_load_coalesced(k, &h, || mem.dest(2).0, Incarnation::seq(1)) |
| 2351 | .unwrap() |
| 2352 | .job(); |
| 2353 | for n in 0..3 { |
| 2354 | assert_eq!( |
| 2355 | w.worker.attach_waiter(job, Incarnation::seq(100 + n)), |
| 2356 | Ok(()), |
| 2357 | "waiter {n} fits" |
| 2358 | ); |
| 2359 | } |
| 2360 | assert_eq!( |
| 2361 | w.worker.attach_waiter(job, Incarnation::seq(200)), |
| 2362 | Err(PlatformError::QueueFull) |
| 2363 | ); |
| 2364 | w.resume(); |
| 2365 | let v = w.collect(4); |
| 2366 | assert_eq!( |
| 2367 | terminals(&v).len(), |
| 2368 | 4, |
| 2369 | "every admitted waiter gets its terminal" |
| 2370 | ); |
| 2371 | } |
| 2372 | |
| 2373 | // ---- Grok C5 review fixes ------------------------------------------------- |
| 2374 | |
| 2375 | #[test] |
| 2376 | fn a_second_store_of_a_live_key_never_takes_over_the_first_jobs_completions() { |
| 2377 | // P1-1: the 17th owner (here the 2nd, with one waiter per job) must not |
| 2378 | // open a second worker job the inner store would merge into the first. |
| 2379 | let w = w_with(|_| {}, |c| c.max_waiters_per_job = 1); |
| 2380 | w.fake.script(JobScript::fault(Fault::Hold)); |
| 2381 | let a = w.store(1).unwrap(); |
| 2382 | w.resume(); |
| 2383 | wait_for("dispatch", || w.dispatched(a)); |
| 2384 | let (_, h) = w.chunk(1); |
| 2385 | let mem = Mem::new(2, 0); |
| 2386 | let (src, _keep) = mem.source(2, 4); |
| 2387 | let second = w.worker.submit_store(h, src, Incarnation::seq(901)); |
| 2388 | match second { |
| 2389 | Ok(j) => assert_eq!(j, a, "it may only join the live job"), |
| 2390 | Err(e) => assert_eq!(e, PlatformError::QueueFull), |
| 2391 | } |
| 2392 | assert_eq!(w.worker.cancel(a), CancelOutcome::Cancelled); |
| 2393 | let v = w.settle(); |
| 2394 | let t = terminals(&v); |
| 2395 | assert!(t.iter().any(|c| c.job == a), "the first job ends: {v:?}"); |
| 2396 | assert_eq!(w.worker.capacity().park_ops, 0, "no park slot leaks"); |
| 2397 | } |
| 2398 | |
| 2399 | #[test] |
| 2400 | fn a_dedup_merge_by_the_store_never_strands_a_job() { |
| 2401 | // P1-1 through the other door: the live job's only waiter cancels too late |
| 2402 | // (the store already holds it), then a new store of the key arrives. |
| 2403 | let w = rig(); |
| 2404 | // The worker never moves the clock (step 0); the test moves the fake into |
| 2405 | // its file sync, which it stalls and where cancel is too late. |
| 2406 | w.fake |
| 2407 | .script(JobScript::latency(5_000, 0).with(Fault::StallFsync(1_000_000))); |
| 2408 | w.step.store(0, Ordering::SeqCst); |
| 2409 | let a = w.store(1).unwrap(); |
| 2410 | w.resume(); |
| 2411 | wait_for("dispatch", || w.dispatched(a)); |
| 2412 | w.fake.advance(10_000); |
| 2413 | assert!(w.dispatched(a), "still in the store"); |
| 2414 | assert_eq!(w.worker.cancel(a), CancelOutcome::TooLate); |
| 2415 | let (_, h) = w.chunk(1); |
| 2416 | let mem = Mem::new(2, 0); |
| 2417 | let (src, _keep) = mem.source(2, 4); |
| 2418 | let b = w.worker.submit_store(h, src, Incarnation::seq(902)); |
| 2419 | w.step.store(1_000_000, Ordering::SeqCst); |
| 2420 | let v = w.settle(); |
| 2421 | let jobs: BTreeSet<JobId> = terminals(&v).iter().map(|c| c.job).collect(); |
| 2422 | assert!(jobs.contains(&a), "the first job ends: {v:?}"); |
| 2423 | if let Ok(b) = b { |
| 2424 | assert!(jobs.contains(&b), "the second job ends: {v:?}"); |
| 2425 | } |
| 2426 | assert_eq!(w.worker.capacity().park_ops, 0); |
| 2427 | } |
| 2428 | |
| 2429 | #[test] |
| 2430 | fn a_restored_landing_holder_outlives_the_terminal_the_caller_sees() { |
| 2431 | // P1-2: the caller adopts the landing blocks after it sees Completed, so |
| 2432 | // the holder must still be alive then; it goes when the caller drops the |
| 2433 | // completion (and every copy of it). |
| 2434 | let w = rig(); |
| 2435 | w.inject(7); |
| 2436 | let released = Arc::new(AtomicU64::new(0)); |
| 2437 | let (job, _mem, handle) = w.load_with(7, released_guard(&released)); |
| 2438 | let job = job.unwrap(); |
| 2439 | w.resume(); |
| 2440 | let v = w.collect(1); |
| 2441 | let t = terminals(&v)[0].clone(); |
| 2442 | assert_eq!(t.job, job); |
| 2443 | assert_eq!(t.terminal, Some(Terminal::Done(JobStage::Completed))); |
| 2444 | assert!(handle.is_held(), "alive when the caller sees Completed"); |
| 2445 | assert_eq!(released.load(Ordering::SeqCst), 0); |
| 2446 | assert!(t.holder.is_some(), "handed back with the terminal"); |
| 2447 | drop(v); |
| 2448 | assert!(handle.is_held(), "a copy still holds it"); |
| 2449 | drop(t); |
| 2450 | assert!(!handle.is_held()); |
| 2451 | assert_eq!(released.load(Ordering::SeqCst), 1); |
| 2452 | } |
| 2453 | |
| 2454 | #[test] |
| 2455 | fn coalesced_waiters_share_one_landing_holder_until_the_last_drops_it() { |
| 2456 | let w = rig(); |
| 2457 | let k = w.inject(7); |
| 2458 | let (_, h) = w.chunk(7); |
| 2459 | let mem = Mem::new(2, 0xEE); |
| 2460 | let released = Arc::new(AtomicU64::new(0)); |
| 2461 | let (dst, handle) = mem.dest_with(2, released_guard(&released)); |
| 2462 | let mut dst = Some(dst); |
| 2463 | let job = w |
| 2464 | .worker |
| 2465 | .submit_load_coalesced(k, &h, || dst.take().unwrap(), Incarnation::seq(1)) |
| 2466 | .unwrap() |
| 2467 | .job(); |
| 2468 | w.worker.attach_waiter(job, Incarnation::seq(2)).unwrap(); |
| 2469 | w.resume(); |
| 2470 | let v = w.collect(2); |
| 2471 | let mut t: Vec<Completion> = terminals(&v).into_iter().cloned().collect(); |
| 2472 | drop(v); |
| 2473 | assert!(t.iter().all(|c| c.holder.is_some())); |
| 2474 | t.pop(); |
| 2475 | assert!(handle.is_held(), "one waiter still holds it"); |
| 2476 | t.clear(); |
| 2477 | assert!(!handle.is_held()); |
| 2478 | assert_eq!(released.load(Ordering::SeqCst), 1); |
| 2479 | } |
| 2480 | |
| 2481 | #[test] |
| 2482 | fn a_panic_never_reports_a_job_whose_buffer_the_store_still_owns() { |
| 2483 | // P1-3: after the worker thread panics, a job the store still holds stays |
| 2484 | // unfinished (its source held) until the store lets go; then it fails once. |
| 2485 | let boom = Arc::new(AtomicBool::new(false)); |
| 2486 | let fields = tiny(); |
| 2487 | let ns = fields.namespace_id().unwrap(); |
| 2488 | let fake = Arc::new(FakeKvStore::new(FakeConfig::new(ns))); |
| 2489 | let b = boom.clone(); |
| 2490 | let f2 = fake.clone(); |
| 2491 | let worker = StorageWorker::spawn( |
| 2492 | fake.clone(), |
| 2493 | WorkerConfig { |
| 2494 | idle_poll: Duration::ZERO, |
| 2495 | ..WorkerConfig::default() |
| 2496 | }, |
| 2497 | move || { |
| 2498 | if b.load(Ordering::SeqCst) { |
| 2499 | panic!("injected store failure"); |
| 2500 | } |
| 2501 | f2.advance(0); |
| 2502 | }, |
| 2503 | ) |
| 2504 | .unwrap(); |
| 2505 | fake.script(JobScript::fault(Fault::Hold)); |
| 2506 | let mem = Mem::new(2, 1); |
| 2507 | let released = Arc::new(AtomicU64::new(0)); |
| 2508 | let (src, handle) = mem.source_with(2, 4, released_guard(&released)); |
| 2509 | let tokens: Vec<u32> = (0..8).collect(); |
| 2510 | let key = aien_kv_store::chunk_chain(&ns, 8, &tokens).unwrap()[0]; |
| 2511 | let h = fields.chunk_header(&ns, key, None, 0, 8, 1).unwrap(); |
| 2512 | let job = worker.submit_store(h, src, Incarnation::seq(1)).unwrap(); |
| 2513 | wait_for("dispatch", || worker.inner_job(job).is_some()); |
| 2514 | let inner = worker.inner_job(job).unwrap(); |
| 2515 | boom.store(true, Ordering::SeqCst); |
| 2516 | wait_for("the worker failed", || { |
| 2517 | worker.capacity().state == aien_kv_store::StoreState::Failed |
| 2518 | }); |
| 2519 | assert!( |
| 2520 | worker.poll(8).is_empty(), |
| 2521 | "no terminal while the store owns the buffer" |
| 2522 | ); |
| 2523 | assert!(handle.is_held()); |
| 2524 | // The store lets go (its own cancel); only now the job fails, once. |
| 2525 | assert_eq!(fake.cancel(inner), CancelOutcome::Cancelled); |
| 2526 | fake.advance(0); |
| 2527 | let mut v = Vec::new(); |
| 2528 | wait_for("terminal after the store let go", || { |
| 2529 | v.extend(worker.poll(8)); |
| 2530 | !terminals(&v).is_empty() |
| 2531 | }); |
| 2532 | assert_eq!(terminals(&v).len(), 1); |
| 2533 | assert!(matches!( |
| 2534 | terminals(&v)[0].terminal, |
| 2535 | Some(Terminal::Failed(PlatformError::HardwareFault(_))) |
| 2536 | )); |
| 2537 | wait_for("source released", || !handle.is_held()); |
| 2538 | assert_eq!(released.load(Ordering::SeqCst), 1); |
| 2539 | } |
| 2540 | |
| 2541 | #[test] |
| 2542 | fn shutdown_cancels_a_job_that_is_still_being_handed_to_the_store() { |
| 2543 | // P2-4: a load in Dispatching when shutdown starts must not go on to write |
| 2544 | // its destination. |
| 2545 | let w = rig(); |
| 2546 | w.inject(7); |
| 2547 | w.probe.submit_gate.set(false); |
| 2548 | let (job, mem, _h) = w.load_h(7); |
| 2549 | let job = job.unwrap(); |
| 2550 | w.resume(); |
| 2551 | let g = w.probe.submit_gate.clone(); |
| 2552 | wait_for("blocked inside submit_load", move || g.waiting() >= 1); |
| 2553 | assert!(w.worker.inner_job(job).is_none(), "still Dispatching"); |
| 2554 | let _ = w.worker.shutdown(0); |
| 2555 | w.probe.submit_gate.set(true); |
| 2556 | let v = w.settle(); |
| 2557 | assert_eq!( |
| 2558 | terminals(&v)[0].terminal, |
| 2559 | Some(Terminal::Cancelled), |
| 2560 | "{v:?}" |
| 2561 | ); |
| 2562 | assert_eq!(w.fake.stats().reads, 0, "no read after shutdown"); |
| 2563 | assert!( |
| 2564 | !w.probe.threads_of("cancel").is_empty(), |
| 2565 | "the worker forwards the cancel itself, not relying on the store's shutdown" |
| 2566 | ); |
| 2567 | assert_eq!(mem.bytes(), vec![0xEE; 2 * BLOCK]); |
| 2568 | } |
| 2569 | |
| 2570 | // ---- default park bound (C9 bench finding) --------------------------------- |
| 2571 | |
| 2572 | #[test] |
| 2573 | fn default_park_bound_admits_eight_conversations_finishing_together() { |
| 2574 | // The C9 bench: 8 conversations finishing in one step park 3 chunks each |
| 2575 | // (24) and the old default of 16 refused 8 of them. The default must |
| 2576 | // admit 8 conversations of up to 8 parks each with no QueueFull. |
| 2577 | let defaults = WorkerConfig::default(); |
| 2578 | let w = w_with(|_| {}, |_| {}); |
| 2579 | assert_eq!(w.worker.capacity().max_park_ops, defaults.max_park_ops); |
| 2580 | let mut refused = 0; |
| 2581 | for n in 0..64u32 { |
| 2582 | if w.store(1000 + n).is_err() { |
| 2583 | refused += 1; |
| 2584 | } |
| 2585 | } |
| 2586 | assert_eq!(refused, 0, "parks refused at 8 conversations x 8 chunks"); |
| 2587 | w.resume(); |
| 2588 | w.settle(); |
| 2589 | } |