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 / src / fake.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 | //! Deterministic in-memory `KvStore` (ADR 0003 section 13): a virtual clock, |
| 17 | //! scripted latencies and faults, no threads, no real time, no I/O. The same |
| 18 | //! script gives the same completions in the same order. |
| 19 | //! |
| 20 | //! The virtual clock is the **only** place I/O and eviction happen: `advance` |
| 21 | //! (and `run_until_idle`, `shutdown`) run the worker's steps. `submit_*` |
| 22 | //! never does, which a test can assert by counting I/O calls (`FakeStats::io_ops`). |
| 23 | |
| 24 | use crate::identity::{ChunkKey, NamespaceId}; |
| 25 | use crate::pin::{HolderGuard, PinnedDest, PinnedSource}; |
| 26 | use crate::record::{ChunkHeader, MAX_SEGMENTS}; |
| 27 | use crate::store::{ |
| 28 | CancelOutcome, Capacity, Completion, DrainReport, Incarnation, JobId, JobStage, KvStore, |
| 29 | PinToken, PublishOutcome, RecoveryProgress, StoreState, Terminal, UnfinishedJob, |
| 30 | }; |
| 31 | use aien_platform::{ObjectId, PlatformError}; |
| 32 | use sha2::{Digest, Sha256}; |
| 33 | use std::collections::{BTreeMap, VecDeque}; |
| 34 | use std::string::String; |
| 35 | use std::sync::{Mutex, MutexGuard, TryLockError}; |
| 36 | use std::vec::Vec; |
| 37 | |
| 38 | /// What `Durable` means (ADR 3.3 table). |
| 39 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 40 | pub enum DurabilityMode { |
| 41 | /// Native-like: a store ends `Published` (not durable); a later flush job |
| 42 | /// makes it so. |
| 43 | OnFlush, |
| 44 | /// Host-like: publication includes the directory sync; the store's |
| 45 | /// terminal completion carries `Durable` (or `Indeterminate`). |
| 46 | WithPublish, |
| 47 | } |
| 48 | |
| 49 | /// One injectable misbehaviour, attached to the next job through `JobScript`. |
| 50 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 51 | pub enum Fault { |
| 52 | /// `submit_*` refuses with `QueueFull` regardless of the real occupancy. |
| 53 | QueueFull, |
| 54 | /// The write fails with `OutOfMemory`: the filesystem refuses despite the quota (P1). |
| 55 | DiskFull, |
| 56 | /// A flush job fails (`HardwareFault`); the store fail-stops (`Failed`) on |
| 57 | /// `OnFlush`, goes `Degraded` on `WithPublish`. |
| 58 | FlushFail, |
| 59 | /// The write is cut short: the job fails and a partial temporary object |
| 60 | /// remains until `recover_step` (P1, crash style). |
| 61 | TornWrite, |
| 62 | /// `fsync(file)` fails (P2): the job fails, nothing is published, the temp |
| 63 | /// is unlinked, and the store enters `Degraded` (`Failed` on `OnFlush`). |
| 64 | FsyncFileFail, |
| 65 | /// Host-only (ignored on `OnFlush`): rename succeeds, `fsync(dir)` fails |
| 66 | /// (P4): the object is published and served, the job ends `Indeterminate`, |
| 67 | /// the store goes `Degraded`. |
| 68 | RenameOkDirsyncFail, |
| 69 | /// `fsync(file)` takes this many extra virtual microseconds and cannot be |
| 70 | /// cancelled while it runs. |
| 71 | StallFsync(u64), |
| 72 | /// Reclamation of this store job takes this many extra microseconds. |
| 73 | StallEviction(u64), |
| 74 | /// The first victim unlink of this store job fails: the victim stays, the |
| 75 | /// job fails with `HardwareFault`. |
| 76 | UnlinkFail, |
| 77 | /// Do not start until `FakeKvStore::release(job)`. |
| 78 | Hold, |
| 79 | /// Deliberate adapter misbehaviour for testing callers: every completion |
| 80 | /// of this job is reported twice (the terminal count becomes 2). |
| 81 | DuplicateCompletion, |
| 82 | /// Deliberate adapter misbehaviour for testing callers: after `cancel` |
| 83 | /// answered `Cancelled` and the terminal `Cancelled` was reported, a stale |
| 84 | /// `Completed` progress completion is still reported. |
| 85 | CompletionAfterCancel, |
| 86 | } |
| 87 | |
| 88 | /// Latency and faults for the next job submitted. Scripts are consumed in FIFO |
| 89 | /// order, one per `submit_*` call, whatever the call's outcome. |
| 90 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 91 | pub struct JobScript { |
| 92 | /// Virtual microseconds from start to `Completed` (write plus file sync). |
| 93 | pub completed_after_us: u64, |
| 94 | /// Virtual microseconds from `Completed` to publication (rename plus dir sync). |
| 95 | pub published_after_us: u64, |
| 96 | pub faults: Vec<Fault>, |
| 97 | } |
| 98 | |
| 99 | impl JobScript { |
| 100 | pub fn latency(completed_after_us: u64, published_after_us: u64) -> Self { |
| 101 | Self { |
| 102 | completed_after_us, |
| 103 | published_after_us, |
| 104 | faults: Vec::new(), |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | pub fn fault(fault: Fault) -> Self { |
| 109 | Self::default().with(fault) |
| 110 | } |
| 111 | |
| 112 | pub fn with(mut self, fault: Fault) -> Self { |
| 113 | self.faults.push(fault); |
| 114 | self |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 119 | pub struct FakeConfig { |
| 120 | pub namespace: NamespaceId, |
| 121 | pub quota_bytes: u64, |
| 122 | pub max_objects: u64, |
| 123 | pub max_restore_ops: u32, |
| 124 | pub max_park_ops: u32, |
| 125 | pub max_inflight_bytes: u64, |
| 126 | pub max_waiters_per_job: u32, |
| 127 | pub max_waiters_total: u32, |
| 128 | pub durability: DurabilityMode, |
| 129 | /// Virtual microseconds one unlink takes. |
| 130 | pub unlink_us: u64, |
| 131 | /// Virtual microseconds a flush barrier takes. |
| 132 | pub flush_us: u64, |
| 133 | /// Default latencies for jobs with no script. |
| 134 | pub default_completed_after_us: u64, |
| 135 | pub default_published_after_us: u64, |
| 136 | /// Start in `Recovering`; the unindexed disk entries are walked by `recover_step`. |
| 137 | pub start_recovering: bool, |
| 138 | /// Disk entries one millisecond of `recover_step` slice accounts for. |
| 139 | pub recovery_entries_per_ms: u64, |
| 140 | } |
| 141 | |
| 142 | impl FakeConfig { |
| 143 | /// Defaults: 64 MiB quota, 1024 objects, 48 restore and 16 park ops |
| 144 | /// (ADR 7.1), 256 MiB in flight, 16 waiters per job and 1024 in total, |
| 145 | /// `WithPublish`, instant unlink and flush, 100 us to complete and 100 us |
| 146 | /// to publish, open at once. |
| 147 | pub fn new(namespace: NamespaceId) -> Self { |
| 148 | Self { |
| 149 | namespace, |
| 150 | quota_bytes: 64 << 20, |
| 151 | max_objects: 1024, |
| 152 | max_restore_ops: 48, |
| 153 | max_park_ops: 16, |
| 154 | max_inflight_bytes: 256 << 20, |
| 155 | max_waiters_per_job: 16, |
| 156 | max_waiters_total: 1024, |
| 157 | durability: DurabilityMode::WithPublish, |
| 158 | unlink_us: 0, |
| 159 | flush_us: 0, |
| 160 | default_completed_after_us: 100, |
| 161 | default_published_after_us: 100, |
| 162 | start_recovering: false, |
| 163 | recovery_entries_per_ms: 1000, |
| 164 | } |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 169 | pub struct FakeStats { |
| 170 | /// Every I/O-like step: payload write, file sync, rename, dir sync, payload |
| 171 | /// read, unlink, flush. `submit_*` never changes it. |
| 172 | pub io_ops: u64, |
| 173 | pub reads: u64, |
| 174 | pub writes: u64, |
| 175 | pub unlinks: u64, |
| 176 | pub queue_full_total: u64, |
| 177 | pub disk_full_total: u64, |
| 178 | pub cancelled_total: u64, |
| 179 | pub evicted_bytes_total: u64, |
| 180 | pub dedup_total: u64, |
| 181 | pub indeterminate_total: u64, |
| 182 | /// Terminal completions generated, by kind. |
| 183 | pub terminal_done: u64, |
| 184 | pub terminal_failed: u64, |
| 185 | pub terminal_cancelled: u64, |
| 186 | /// High-water mark of unpolled completions. |
| 187 | pub peak_completion_queue: u64, |
| 188 | /// Completions queued beyond the reserved capacity: only the two |
| 189 | /// deliberate-misbehaviour faults can raise it. |
| 190 | pub completion_overflow_total: u64, |
| 191 | /// Reads or writes of pool memory whose holder had already been released. |
| 192 | pub poison_violations: u64, |
| 193 | /// Store jobs that reached publication (any durability outcome). |
| 194 | pub published_total: u64, |
| 195 | pub shutdown_unfinished_jobs: u64, |
| 196 | pub shutdown_unfinished_bytes: u64, |
| 197 | } |
| 198 | |
| 199 | /// A file found on the fake disk by `recover_step`. |
| 200 | #[derive(Debug, Clone)] |
| 201 | pub enum DiskEntry { |
| 202 | /// A complete object: indexed when the namespace matches, counted always. |
| 203 | Object { |
| 204 | header: ChunkHeader, |
| 205 | payload: Vec<u8>, |
| 206 | segment_bytes: usize, |
| 207 | }, |
| 208 | /// A leftover `tmp/*.part`: unlinked, not counted. |
| 209 | Tmp, |
| 210 | /// An object whose header region fails validation: unlinked. |
| 211 | CorruptHeader { physical_bytes: u64 }, |
| 212 | } |
| 213 | |
| 214 | type Kb = [u8; 32]; |
| 215 | |
| 216 | fn kb(k: &ChunkKey) -> Kb { |
| 217 | k.0 .0 |
| 218 | } |
| 219 | |
| 220 | const HEADER_REGION: u64 = 4096; |
| 221 | |
| 222 | fn digests_of(payload: &[u8], segment_bytes: usize) -> Vec<[u8; 32]> { |
| 223 | payload |
| 224 | .chunks(segment_bytes.max(1)) |
| 225 | .map(|s| { |
| 226 | let mut h = Sha256::new(); |
| 227 | h.update(s); |
| 228 | h.finalize().into() |
| 229 | }) |
| 230 | .collect() |
| 231 | } |
| 232 | |
| 233 | fn hw(msg: &str) -> PlatformError { |
| 234 | PlatformError::HardwareFault(String::from(msg)) |
| 235 | } |
| 236 | |
| 237 | /// A published object on the fake disk. |
| 238 | struct Object { |
| 239 | header: ChunkHeader, |
| 240 | payload: Vec<u8>, |
| 241 | segment_bytes: usize, |
| 242 | digests: Vec<[u8; 32]>, |
| 243 | /// Insertion order: the oldest object is evicted first. |
| 244 | seq: u64, |
| 245 | publish_seq: u64, |
| 246 | durable: bool, |
| 247 | indeterminate: bool, |
| 248 | evicting: bool, |
| 249 | } |
| 250 | |
| 251 | impl Object { |
| 252 | fn phys(&self) -> u64 { |
| 253 | self.payload.len() as u64 + HEADER_REGION |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | #[derive(Clone, Copy, PartialEq, Eq)] |
| 258 | enum Kind { |
| 259 | Store, |
| 260 | Load, |
| 261 | Flush, |
| 262 | /// A store of a key that is already published: nothing to write. |
| 263 | Noop, |
| 264 | } |
| 265 | |
| 266 | #[derive(Clone, Copy, PartialEq, Eq)] |
| 267 | enum Phase { |
| 268 | Held, |
| 269 | Start { at: u64 }, |
| 270 | Writing { at: u64 }, |
| 271 | Syncing { at: u64 }, |
| 272 | Publishing { at: u64 }, |
| 273 | Reading { at: u64 }, |
| 274 | Flushing { at: u64 }, |
| 275 | NoopDone { at: u64 }, |
| 276 | } |
| 277 | |
| 278 | impl Phase { |
| 279 | fn at(&self) -> Option<u64> { |
| 280 | match *self { |
| 281 | Phase::Held => None, |
| 282 | Phase::Start { at } |
| 283 | | Phase::Writing { at } |
| 284 | | Phase::Syncing { at } |
| 285 | | Phase::Publishing { at } |
| 286 | | Phase::Reading { at } |
| 287 | | Phase::Flushing { at } |
| 288 | | Phase::NoopDone { at } => Some(at), |
| 289 | } |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | struct Staged { |
| 294 | payload: Vec<u8>, |
| 295 | segment_bytes: usize, |
| 296 | } |
| 297 | |
| 298 | struct Job { |
| 299 | id: u64, |
| 300 | kind: Kind, |
| 301 | inc: Incarnation, |
| 302 | key: ChunkKey, |
| 303 | park: bool, |
| 304 | /// Credit bytes (`payload_len + 4096`), 0 for a flush or a no-op store. |
| 305 | bytes: u64, |
| 306 | payload_len: u64, |
| 307 | /// Quota reservation still held (store jobs). |
| 308 | reserved: u64, |
| 309 | submitted_at: u64, |
| 310 | stage: JobStage, |
| 311 | phase: Phase, |
| 312 | cancelling: bool, |
| 313 | script: JobScript, |
| 314 | header: Option<ChunkHeader>, |
| 315 | src: Option<PinnedSource>, |
| 316 | dst: Option<PinnedDest>, |
| 317 | staged: Option<Staged>, |
| 318 | cover_seq: u64, |
| 319 | attached: u32, |
| 320 | noop_stage: JobStage, |
| 321 | /// Objects (key, generation) this store marked to make room; unlinked |
| 322 | /// only after it publishes, returned to service otherwise. |
| 323 | victims: Vec<(Kb, u64)>, |
| 324 | } |
| 325 | |
| 326 | impl Job { |
| 327 | fn has(&self, f: Fault) -> bool { |
| 328 | self.script.faults.contains(&f) |
| 329 | } |
| 330 | |
| 331 | fn stall_fsync(&self) -> u64 { |
| 332 | self.script |
| 333 | .faults |
| 334 | .iter() |
| 335 | .map(|f| if let Fault::StallFsync(x) = f { *x } else { 0 }) |
| 336 | .sum() |
| 337 | } |
| 338 | |
| 339 | fn stall_eviction(&self) -> u64 { |
| 340 | self.script |
| 341 | .faults |
| 342 | .iter() |
| 343 | .map(|f| { |
| 344 | if let Fault::StallEviction(x) = f { |
| 345 | *x |
| 346 | } else { |
| 347 | 0 |
| 348 | } |
| 349 | }) |
| 350 | .sum() |
| 351 | } |
| 352 | } |
| 353 | |
| 354 | struct Unlink { |
| 355 | key: Kb, |
| 356 | /// The object generation being removed. |
| 357 | seq: u64, |
| 358 | at: u64, |
| 359 | fail: bool, |
| 360 | evict: bool, |
| 361 | } |
| 362 | |
| 363 | struct Inner { |
| 364 | cfg: FakeConfig, |
| 365 | now: u64, |
| 366 | state: StoreState, |
| 367 | closed: bool, |
| 368 | next_job: u64, |
| 369 | next_seq: u64, |
| 370 | publish_seq: u64, |
| 371 | next_pin: u64, |
| 372 | scripts: VecDeque<JobScript>, |
| 373 | objects: BTreeMap<Kb, Object>, |
| 374 | foreign_bytes: u64, |
| 375 | unindexed_bytes: u64, |
| 376 | unindexed_objects: u64, |
| 377 | reserved: u64, |
| 378 | jobs: BTreeMap<u64, Job>, |
| 379 | inflight_store: BTreeMap<Kb, u64>, |
| 380 | unlinks: Vec<Unlink>, |
| 381 | pins: BTreeMap<u64, Vec<Kb>>, |
| 382 | pin_counts: BTreeMap<Kb, u32>, |
| 383 | restore_ops: u32, |
| 384 | park_ops: u32, |
| 385 | restore_bytes: u64, |
| 386 | park_bytes: u64, |
| 387 | attached_total: u32, |
| 388 | queue: VecDeque<Completion>, |
| 389 | term_counts: BTreeMap<u64, u32>, |
| 390 | stats: FakeStats, |
| 391 | torn: u64, |
| 392 | disk: VecDeque<DiskEntry>, |
| 393 | recovery: RecoveryProgress, |
| 394 | poison_unacked: u64, |
| 395 | /// Guards of finished jobs; dropped by the caller after the lock is released. |
| 396 | graveyard: Vec<HolderGuard>, |
| 397 | } |
| 398 | |
| 399 | impl Inner { |
| 400 | fn new(cfg: FakeConfig) -> Self { |
| 401 | Self { |
| 402 | now: 0, |
| 403 | state: if cfg.start_recovering { |
| 404 | StoreState::Recovering |
| 405 | } else { |
| 406 | StoreState::Open |
| 407 | }, |
| 408 | closed: false, |
| 409 | next_job: 1, |
| 410 | next_seq: 1, |
| 411 | publish_seq: 0, |
| 412 | next_pin: 1, |
| 413 | scripts: VecDeque::new(), |
| 414 | objects: BTreeMap::new(), |
| 415 | foreign_bytes: 0, |
| 416 | unindexed_bytes: 0, |
| 417 | unindexed_objects: 0, |
| 418 | reserved: 0, |
| 419 | jobs: BTreeMap::new(), |
| 420 | inflight_store: BTreeMap::new(), |
| 421 | unlinks: Vec::new(), |
| 422 | pins: BTreeMap::new(), |
| 423 | pin_counts: BTreeMap::new(), |
| 424 | restore_ops: 0, |
| 425 | park_ops: 0, |
| 426 | restore_bytes: 0, |
| 427 | park_bytes: 0, |
| 428 | attached_total: 0, |
| 429 | queue: VecDeque::new(), |
| 430 | term_counts: BTreeMap::new(), |
| 431 | stats: FakeStats::default(), |
| 432 | torn: 0, |
| 433 | disk: VecDeque::new(), |
| 434 | recovery: RecoveryProgress::default(), |
| 435 | poison_unacked: 0, |
| 436 | graveyard: Vec::new(), |
| 437 | cfg, |
| 438 | } |
| 439 | } |
| 440 | |
| 441 | // ---- accounting ------------------------------------------------------ |
| 442 | |
| 443 | fn indexed_bytes(&self) -> u64 { |
| 444 | self.objects.values().map(Object::phys).sum() |
| 445 | } |
| 446 | |
| 447 | fn used(&self) -> u64 { |
| 448 | self.indexed_bytes() + self.foreign_bytes + self.unindexed_bytes |
| 449 | } |
| 450 | |
| 451 | fn evicting_bytes(&self) -> u64 { |
| 452 | self.objects |
| 453 | .values() |
| 454 | .filter(|o| o.evicting) |
| 455 | .map(Object::phys) |
| 456 | .sum() |
| 457 | } |
| 458 | |
| 459 | fn store_reservations(&self) -> u64 { |
| 460 | self.jobs |
| 461 | .values() |
| 462 | .filter(|j| j.kind == Kind::Store && j.reserved > 0) |
| 463 | .count() as u64 |
| 464 | } |
| 465 | |
| 466 | fn bytes_after(&self) -> u64 { |
| 467 | self.used() - self.evicting_bytes() + self.reserved |
| 468 | } |
| 469 | |
| 470 | fn count_after(&self) -> u64 { |
| 471 | let live = self.objects.values().filter(|o| !o.evicting).count() as u64; |
| 472 | live + self.unindexed_objects + self.store_reservations() |
| 473 | } |
| 474 | |
| 475 | fn is_busy(&self, key: &Kb) -> bool { |
| 476 | self.pin_counts.get(key).copied().unwrap_or(0) > 0 |
| 477 | || self |
| 478 | .jobs |
| 479 | .values() |
| 480 | .any(|j| matches!(j.kind, Kind::Load | Kind::Noop) && kb(&j.key) == *key) |
| 481 | } |
| 482 | |
| 483 | /// (bytes, count) of objects eviction could reclaim now. |
| 484 | fn evictable(&self) -> (u64, u64) { |
| 485 | let mut b = 0; |
| 486 | let mut n = 0; |
| 487 | for (k, o) in &self.objects { |
| 488 | if !o.evicting && !self.is_busy(k) { |
| 489 | b += o.phys(); |
| 490 | n += 1; |
| 491 | } |
| 492 | } |
| 493 | (b, n) |
| 494 | } |
| 495 | |
| 496 | fn pick_victim(&self) -> Option<Kb> { |
| 497 | self.objects |
| 498 | .iter() |
| 499 | .filter(|(k, o)| !o.evicting && !self.is_busy(k)) |
| 500 | .min_by_key(|(_, o)| o.seq) |
| 501 | .map(|(k, _)| *k) |
| 502 | } |
| 503 | |
| 504 | fn completion_capacity(&self) -> usize { |
| 505 | 3 * (self.cfg.max_restore_ops as usize + self.cfg.max_park_ops as usize) |
| 506 | } |
| 507 | |
| 508 | fn park_byte_limit(&self) -> u64 { |
| 509 | self.cfg.max_inflight_bytes / 4 |
| 510 | } |
| 511 | |
| 512 | fn restore_byte_limit(&self) -> u64 { |
| 513 | self.cfg.max_inflight_bytes - self.park_byte_limit() |
| 514 | } |
| 515 | |
| 516 | fn capacity(&self) -> Capacity { |
| 517 | Capacity { |
| 518 | state: self.state, |
| 519 | quota_bytes: self.cfg.quota_bytes, |
| 520 | used_bytes: self.used(), |
| 521 | reserved_bytes: self.reserved, |
| 522 | evicting_bytes: self.evicting_bytes(), |
| 523 | unindexed_bytes: self.unindexed_bytes, |
| 524 | unindexed_objects: self.unindexed_objects, |
| 525 | objects: self.objects.len() as u64, |
| 526 | max_objects: self.cfg.max_objects, |
| 527 | restore_ops: self.restore_ops, |
| 528 | max_restore_ops: self.cfg.max_restore_ops, |
| 529 | park_ops: self.park_ops, |
| 530 | max_park_ops: self.cfg.max_park_ops, |
| 531 | inflight_bytes: self.restore_bytes + self.park_bytes, |
| 532 | max_inflight_bytes: self.cfg.max_inflight_bytes, |
| 533 | max_waiters_per_job: self.cfg.max_waiters_per_job, |
| 534 | } |
| 535 | } |
| 536 | |
| 537 | fn set_degraded(&mut self) { |
| 538 | if self.state == StoreState::Open { |
| 539 | self.state = StoreState::Degraded; |
| 540 | } |
| 541 | } |
| 542 | |
| 543 | // ---- completions ----------------------------------------------------- |
| 544 | |
| 545 | fn push(&mut self, c: Completion) { |
| 546 | self.queue.push_back(c); |
| 547 | let len = self.queue.len(); |
| 548 | if len > self.completion_capacity() { |
| 549 | self.stats.completion_overflow_total += 1; |
| 550 | } |
| 551 | self.stats.peak_completion_queue = self.stats.peak_completion_queue.max(len as u64); |
| 552 | } |
| 553 | |
| 554 | fn progress(&mut self, job: &Job, stage: JobStage) { |
| 555 | let c = Completion { |
| 556 | job: JobId(job.id), |
| 557 | incarnation: job.inc, |
| 558 | key: job.key, |
| 559 | stage, |
| 560 | terminal: None, |
| 561 | publish: PublishOutcome::NotApplicable, |
| 562 | bytes: job.payload_len, |
| 563 | elapsed_us: self.now - job.submitted_at, |
| 564 | holder: None, |
| 565 | }; |
| 566 | self.push(c.clone()); |
| 567 | if job.has(Fault::DuplicateCompletion) { |
| 568 | self.push(c); |
| 569 | } |
| 570 | } |
| 571 | |
| 572 | /// The one place a job ends: releases its credits and reservation, queues |
| 573 | /// its terminal completion and hands its buffers to the graveyard. |
| 574 | fn finish( |
| 575 | &mut self, |
| 576 | mut job: Job, |
| 577 | terminal: Terminal, |
| 578 | stage: JobStage, |
| 579 | publish: PublishOutcome, |
| 580 | ) { |
| 581 | if job.park { |
| 582 | self.park_ops -= 1; |
| 583 | self.park_bytes -= job.bytes; |
| 584 | } else { |
| 585 | self.restore_ops -= 1; |
| 586 | self.restore_bytes -= job.bytes; |
| 587 | } |
| 588 | self.reserved -= job.reserved; |
| 589 | job.reserved = 0; |
| 590 | if job.kind == Kind::Store { |
| 591 | let published = matches!(terminal, Terminal::Done(_)); |
| 592 | self.settle_victims(&mut job, published); |
| 593 | if self.inflight_store.get(&kb(&job.key)) == Some(&job.id) { |
| 594 | self.inflight_store.remove(&kb(&job.key)); |
| 595 | } |
| 596 | } |
| 597 | self.attached_total -= job.attached; |
| 598 | match &terminal { |
| 599 | Terminal::Done(_) => self.stats.terminal_done += 1, |
| 600 | Terminal::Failed(_) => self.stats.terminal_failed += 1, |
| 601 | Terminal::Cancelled => { |
| 602 | self.stats.terminal_cancelled += 1; |
| 603 | self.stats.cancelled_total += 1; |
| 604 | } |
| 605 | } |
| 606 | let copies = if job.has(Fault::DuplicateCompletion) { |
| 607 | 2 |
| 608 | } else { |
| 609 | 1 |
| 610 | }; |
| 611 | *self.term_counts.entry(job.id).or_insert(0) += copies; |
| 612 | let c = Completion { |
| 613 | job: JobId(job.id), |
| 614 | incarnation: job.inc, |
| 615 | key: job.key, |
| 616 | stage, |
| 617 | terminal: Some(terminal.clone()), |
| 618 | publish, |
| 619 | bytes: job.payload_len, |
| 620 | elapsed_us: self.now - job.submitted_at, |
| 621 | holder: None, |
| 622 | }; |
| 623 | for _ in 0..copies { |
| 624 | self.push(c.clone()); |
| 625 | } |
| 626 | if terminal == Terminal::Cancelled && job.has(Fault::CompletionAfterCancel) { |
| 627 | let mut stale = c; |
| 628 | stale.stage = JobStage::Completed; |
| 629 | stale.terminal = None; |
| 630 | stale.publish = PublishOutcome::NotApplicable; |
| 631 | self.push(stale); |
| 632 | } |
| 633 | if let Some(s) = job.src.take() { |
| 634 | self.graveyard.push(s.into_guard()); |
| 635 | } |
| 636 | if let Some(d) = job.dst.take() { |
| 637 | self.graveyard.push(d.into_guard()); |
| 638 | } |
| 639 | } |
| 640 | |
| 641 | /// A store job ended. Its victims were only marked; queue their unlinks |
| 642 | /// when it published (`StallEviction` delays them, `UnlinkFail` fails the |
| 643 | /// first), otherwise return them to service (ADR 3.4, Grok C4 P1-1). |
| 644 | fn settle_victims(&mut self, job: &mut Job, published: bool) { |
| 645 | let victims = std::mem::take(&mut job.victims); |
| 646 | let mut first = true; |
| 647 | for (key, seq) in victims { |
| 648 | if published { |
| 649 | let fail = first && job.has(Fault::UnlinkFail); |
| 650 | first = false; |
| 651 | self.unlinks.push(Unlink { |
| 652 | key, |
| 653 | seq, |
| 654 | at: self.now + self.cfg.unlink_us + job.stall_eviction(), |
| 655 | fail, |
| 656 | evict: true, |
| 657 | }); |
| 658 | } else if let Some(o) = self.objects.get_mut(&key).filter(|o| o.seq == seq) { |
| 659 | o.evicting = false; |
| 660 | } |
| 661 | } |
| 662 | } |
| 663 | |
| 664 | fn fail(&mut self, job: Job, e: PlatformError) { |
| 665 | let stage = job.stage; |
| 666 | self.finish( |
| 667 | job, |
| 668 | Terminal::Failed(e), |
| 669 | stage, |
| 670 | PublishOutcome::NotApplicable, |
| 671 | ); |
| 672 | } |
| 673 | |
| 674 | fn violation(&mut self) { |
| 675 | self.stats.poison_violations += 1; |
| 676 | self.poison_unacked += 1; |
| 677 | } |
| 678 | |
| 679 | // ---- submit ---------------------------------------------------------- |
| 680 | |
| 681 | fn take_script(&mut self) -> JobScript { |
| 682 | self.scripts.pop_front().unwrap_or_else(|| { |
| 683 | JobScript::latency( |
| 684 | self.cfg.default_completed_after_us, |
| 685 | self.cfg.default_published_after_us, |
| 686 | ) |
| 687 | }) |
| 688 | } |
| 689 | |
| 690 | fn queue_full(&mut self) -> PlatformError { |
| 691 | self.stats.queue_full_total += 1; |
| 692 | PlatformError::QueueFull |
| 693 | } |
| 694 | |
| 695 | /// Refusals that depend only on the store's state (and the scripted fault). |
| 696 | fn gate(&mut self, script: &JobScript, needs_open: bool) -> Result<(), PlatformError> { |
| 697 | if script.faults.contains(&Fault::QueueFull) || self.state == StoreState::Recovering { |
| 698 | return Err(self.queue_full()); |
| 699 | } |
| 700 | if self.closed |
| 701 | || self.state == StoreState::Failed |
| 702 | || (needs_open && self.state == StoreState::Degraded) |
| 703 | { |
| 704 | return Err(PlatformError::DeviceUnavailable); |
| 705 | } |
| 706 | Ok(()) |
| 707 | } |
| 708 | |
| 709 | fn credit_check(&mut self, park: bool, bytes: u64) -> Result<(), PlatformError> { |
| 710 | let (ops, max_ops, used_bytes, limit) = if park { |
| 711 | ( |
| 712 | self.park_ops, |
| 713 | self.cfg.max_park_ops, |
| 714 | self.park_bytes, |
| 715 | self.park_byte_limit(), |
| 716 | ) |
| 717 | } else { |
| 718 | ( |
| 719 | self.restore_ops, |
| 720 | self.cfg.max_restore_ops, |
| 721 | self.restore_bytes, |
| 722 | self.restore_byte_limit(), |
| 723 | ) |
| 724 | }; |
| 725 | let slots = self.queue.len() + 3 * self.jobs.len() + 3; |
| 726 | if ops >= max_ops || used_bytes + bytes > limit || slots > self.completion_capacity() { |
| 727 | return Err(self.queue_full()); |
| 728 | } |
| 729 | Ok(()) |
| 730 | } |
| 731 | |
| 732 | #[allow(clippy::too_many_arguments)] |
| 733 | fn new_job( |
| 734 | &mut self, |
| 735 | kind: Kind, |
| 736 | inc: Incarnation, |
| 737 | key: ChunkKey, |
| 738 | bytes: u64, |
| 739 | payload_len: u64, |
| 740 | reserved: u64, |
| 741 | script: JobScript, |
| 742 | phase: Phase, |
| 743 | ) -> Job { |
| 744 | let id = self.next_job; |
| 745 | self.next_job += 1; |
| 746 | let park = kind != Kind::Load; |
| 747 | if park { |
| 748 | self.park_ops += 1; |
| 749 | self.park_bytes += bytes; |
| 750 | } else { |
| 751 | self.restore_ops += 1; |
| 752 | self.restore_bytes += bytes; |
| 753 | } |
| 754 | self.reserved += reserved; |
| 755 | Job { |
| 756 | id, |
| 757 | kind, |
| 758 | inc, |
| 759 | key, |
| 760 | park, |
| 761 | bytes, |
| 762 | payload_len, |
| 763 | reserved, |
| 764 | submitted_at: self.now, |
| 765 | stage: JobStage::Submitted, |
| 766 | phase, |
| 767 | cancelling: false, |
| 768 | script, |
| 769 | header: None, |
| 770 | src: None, |
| 771 | dst: None, |
| 772 | staged: None, |
| 773 | cover_seq: 0, |
| 774 | attached: 0, |
| 775 | noop_stage: JobStage::Submitted, |
| 776 | victims: Vec::new(), |
| 777 | } |
| 778 | } |
| 779 | |
| 780 | fn start_phase(&self, script: &JobScript) -> Phase { |
| 781 | if script.faults.contains(&Fault::Hold) { |
| 782 | Phase::Held |
| 783 | } else { |
| 784 | Phase::Start { at: self.now } |
| 785 | } |
| 786 | } |
| 787 | |
| 788 | fn submit_store( |
| 789 | &mut self, |
| 790 | header: ChunkHeader, |
| 791 | slot: &mut Option<PinnedSource>, |
| 792 | inc: Incarnation, |
| 793 | ) -> Result<JobId, PlatformError> { |
| 794 | let script = self.take_script(); |
| 795 | self.gate(&script, true)?; |
| 796 | let src = slot.as_ref().ok_or(PlatformError::InvalidLayout)?; |
| 797 | // The header and the source must agree (ADR 3.2); nothing is reserved on refusal. |
| 798 | if header.namespace_id != self.cfg.namespace |
| 799 | || header.payload_len == 0 |
| 800 | || src.total_bytes() != Some(header.payload_len) |
| 801 | || header.block_size == 0 |
| 802 | || src.block_count() == 0 |
| 803 | || src.block_count() > MAX_SEGMENTS |
| 804 | { |
| 805 | return Err(PlatformError::InvalidLayout); |
| 806 | } |
| 807 | let full = (src.block_count() as u64 - 1) * header.block_size as u64; |
| 808 | let tail = (header.token_count as u64).checked_sub(full); |
| 809 | match tail { |
| 810 | Some(t) |
| 811 | if t >= 1 |
| 812 | && t <= header.block_size as u64 |
| 813 | && t == src.tail_valid_tokens() as u64 => {} |
| 814 | _ => return Err(PlatformError::InvalidLayout), |
| 815 | } |
| 816 | let key = header.chunk_key; |
| 817 | let k = kb(&key); |
| 818 | // Never dedup into a job that is being cancelled: it will never publish. |
| 819 | if let Some(&jid) = self |
| 820 | .inflight_store |
| 821 | .get(&k) |
| 822 | .filter(|jid| self.jobs.get(jid).is_some_and(|j| !j.cancelling)) |
| 823 | { |
| 824 | self.stats.dedup_total += 1; |
| 825 | return Ok(JobId(jid)); |
| 826 | } |
| 827 | if let Some(o) = self.objects.get(&k).filter(|o| !o.evicting) { |
| 828 | let stage = if o.durable { |
| 829 | JobStage::Durable |
| 830 | } else { |
| 831 | JobStage::Published |
| 832 | }; |
| 833 | self.credit_check(true, 0)?; |
| 834 | let at = self.now; |
| 835 | let mut job = self.new_job( |
| 836 | Kind::Noop, |
| 837 | inc, |
| 838 | key, |
| 839 | 0, |
| 840 | 0, |
| 841 | 0, |
| 842 | script, |
| 843 | Phase::NoopDone { at }, |
| 844 | ); |
| 845 | job.noop_stage = stage; |
| 846 | self.stats.dedup_total += 1; |
| 847 | let id = job.id; |
| 848 | self.jobs.insert(id, job); |
| 849 | return Ok(JobId(id)); |
| 850 | } |
| 851 | let bytes = header.payload_len + HEADER_REGION; |
| 852 | self.credit_check(true, bytes)?; |
| 853 | let (eb, en) = self.evictable(); |
| 854 | if self.bytes_after() + bytes > self.cfg.quota_bytes + eb |
| 855 | || self.count_after() + 1 > self.cfg.max_objects + en |
| 856 | { |
| 857 | self.stats.disk_full_total += 1; |
| 858 | return Err(PlatformError::OutOfMemory); |
| 859 | } |
| 860 | let phase = self.start_phase(&script); |
| 861 | let mut job = self.new_job( |
| 862 | Kind::Store, |
| 863 | inc, |
| 864 | key, |
| 865 | bytes, |
| 866 | header.payload_len, |
| 867 | bytes, |
| 868 | script, |
| 869 | phase, |
| 870 | ); |
| 871 | job.header = Some(header); |
| 872 | job.src = slot.take(); |
| 873 | let id = job.id; |
| 874 | self.inflight_store.insert(k, id); |
| 875 | self.jobs.insert(id, job); |
| 876 | Ok(JobId(id)) |
| 877 | } |
| 878 | |
| 879 | fn submit_load( |
| 880 | &mut self, |
| 881 | key: ChunkKey, |
| 882 | expect: &ChunkHeader, |
| 883 | slot: &mut Option<PinnedDest>, |
| 884 | inc: Incarnation, |
| 885 | ) -> Result<JobId, PlatformError> { |
| 886 | let script = self.take_script(); |
| 887 | self.gate(&script, false)?; |
| 888 | let dst = slot.as_ref().ok_or(PlatformError::InvalidLayout)?; |
| 889 | let o = self |
| 890 | .objects |
| 891 | .get(&kb(&key)) |
| 892 | .filter(|o| !o.evicting) |
| 893 | .ok_or(PlatformError::ObjectNotFound(key.0))?; |
| 894 | let mut a = o.header; |
| 895 | let mut b = *expect; |
| 896 | a.written_unix_ns = 0; |
| 897 | b.written_unix_ns = 0; |
| 898 | if a != b |
| 899 | || dst.total_bytes() != Some(o.payload.len() as u64) |
| 900 | || dst.block_bytes() != o.segment_bytes |
| 901 | { |
| 902 | return Err(PlatformError::InvalidLayout); |
| 903 | } |
| 904 | let (bytes, len) = (o.phys(), o.payload.len() as u64); |
| 905 | self.credit_check(false, bytes)?; |
| 906 | let phase = self.start_phase(&script); |
| 907 | let mut job = self.new_job(Kind::Load, inc, key, bytes, len, 0, script, phase); |
| 908 | job.dst = slot.take(); |
| 909 | let id = job.id; |
| 910 | self.jobs.insert(id, job); |
| 911 | Ok(JobId(id)) |
| 912 | } |
| 913 | |
| 914 | fn submit_flush(&mut self, inc: Incarnation) -> Result<JobId, PlatformError> { |
| 915 | let script = self.take_script(); |
| 916 | // A degraded store may still make what it published durable. |
| 917 | self.gate(&script, false)?; |
| 918 | self.credit_check(true, 0)?; |
| 919 | let at = self.now + self.cfg.flush_us; |
| 920 | let mut job = self.new_job( |
| 921 | Kind::Flush, |
| 922 | inc, |
| 923 | ChunkKey(ObjectId([0; 32])), |
| 924 | 0, |
| 925 | 0, |
| 926 | 0, |
| 927 | script, |
| 928 | Phase::Flushing { at }, |
| 929 | ); |
| 930 | job.cover_seq = self.publish_seq; |
| 931 | let id = job.id; |
| 932 | self.jobs.insert(id, job); |
| 933 | Ok(JobId(id)) |
| 934 | } |
| 935 | |
| 936 | // ---- the worker ------------------------------------------------------ |
| 937 | |
| 938 | fn reap_cancels(&mut self) { |
| 939 | let ids: Vec<u64> = self |
| 940 | .jobs |
| 941 | .iter() |
| 942 | .filter(|(_, j)| j.cancelling) |
| 943 | .map(|(id, _)| *id) |
| 944 | .collect(); |
| 945 | for id in ids { |
| 946 | let job = self.jobs.remove(&id).expect("cancelling job"); |
| 947 | if job.staged.is_some() { |
| 948 | // The temporary object was written and synced: unlink it. |
| 949 | self.stats.unlinks += 1; |
| 950 | self.stats.io_ops += 1; |
| 951 | } |
| 952 | let stage = job.stage; |
| 953 | self.finish( |
| 954 | job, |
| 955 | Terminal::Cancelled, |
| 956 | stage, |
| 957 | PublishOutcome::NotApplicable, |
| 958 | ); |
| 959 | } |
| 960 | } |
| 961 | |
| 962 | /// Run every due step in time order. `target: None` runs until nothing is |
| 963 | /// scheduled. With `jump`, the clock ends at `target`. |
| 964 | fn run(&mut self, target: Option<u64>, jump: bool) { |
| 965 | self.reap_cancels(); |
| 966 | loop { |
| 967 | let mut best: Option<(u64, u8, u64)> = None; |
| 968 | for (i, u) in self.unlinks.iter().enumerate() { |
| 969 | let c = (u.at, 0u8, i as u64); |
| 970 | if best.is_none_or(|b| c < b) { |
| 971 | best = Some(c); |
| 972 | } |
| 973 | } |
| 974 | for (id, j) in &self.jobs { |
| 975 | if j.cancelling { |
| 976 | continue; |
| 977 | } |
| 978 | if let Some(at) = j.phase.at() { |
| 979 | let c = (at, 1u8, *id); |
| 980 | if best.is_none_or(|b| c < b) { |
| 981 | best = Some(c); |
| 982 | } |
| 983 | } |
| 984 | } |
| 985 | let Some((at, kind, id)) = best else { break }; |
| 986 | if target.is_some_and(|t| at > t) { |
| 987 | break; |
| 988 | } |
| 989 | self.now = self.now.max(at); |
| 990 | if kind == 0 { |
| 991 | self.do_unlink(id as usize); |
| 992 | } else { |
| 993 | self.step_job(id); |
| 994 | } |
| 995 | } |
| 996 | if jump { |
| 997 | if let Some(t) = target { |
| 998 | self.now = self.now.max(t); |
| 999 | } |
| 1000 | } |
| 1001 | } |
| 1002 | |
| 1003 | fn do_unlink(&mut self, idx: usize) { |
| 1004 | let u = self.unlinks.remove(idx); |
| 1005 | self.stats.io_ops += 1; |
| 1006 | let present = self.objects.get(&u.key).is_some_and(|o| o.seq == u.seq); |
| 1007 | if u.fail { |
| 1008 | // Still on disk: back in service, still counted. No job waits. |
| 1009 | if let Some(o) = self.objects.get_mut(&u.key).filter(|_| present) { |
| 1010 | o.evicting = false; |
| 1011 | } |
| 1012 | return; |
| 1013 | } |
| 1014 | if present { |
| 1015 | let o = self.objects.remove(&u.key).expect("object present"); |
| 1016 | self.stats.unlinks += 1; |
| 1017 | if u.evict { |
| 1018 | self.stats.evicted_bytes_total += o.phys(); |
| 1019 | } |
| 1020 | } |
| 1021 | } |
| 1022 | |
| 1023 | fn step_job(&mut self, id: u64) { |
| 1024 | let mut job = self.jobs.remove(&id).expect("scheduled job"); |
| 1025 | match (job.kind, job.phase) { |
| 1026 | (Kind::Store, Phase::Start { .. }) => self.start_store(job), |
| 1027 | (Kind::Store, Phase::Writing { .. }) => self.end_write(job), |
| 1028 | (Kind::Store, Phase::Syncing { .. }) => self.end_sync(job), |
| 1029 | (Kind::Store, Phase::Publishing { .. }) => self.publish(job), |
| 1030 | (Kind::Load, Phase::Start { .. }) => { |
| 1031 | job.phase = Phase::Reading { |
| 1032 | at: self.now + job.script.completed_after_us, |
| 1033 | }; |
| 1034 | self.jobs.insert(id, job); |
| 1035 | } |
| 1036 | (Kind::Load, Phase::Reading { .. }) => self.end_read(job), |
| 1037 | (Kind::Flush, Phase::Flushing { .. }) => self.end_flush(job), |
| 1038 | (Kind::Noop, Phase::NoopDone { .. }) => { |
| 1039 | let stage = job.noop_stage; |
| 1040 | self.finish( |
| 1041 | job, |
| 1042 | Terminal::Done(stage), |
| 1043 | stage, |
| 1044 | PublishOutcome::NotApplicable, |
| 1045 | ); |
| 1046 | } |
| 1047 | (kind, _) => { |
| 1048 | let _ = kind; |
| 1049 | unreachable!("job scheduled in a phase it cannot be in") |
| 1050 | } |
| 1051 | } |
| 1052 | } |
| 1053 | |
| 1054 | /// Worker-side reclamation (ADR 7.4): mark victims, then write at once. |
| 1055 | /// The victims' unlinks wait for the publish (`settle_victims`). |
| 1056 | fn start_store(&mut self, mut job: Job) { |
| 1057 | while self.bytes_after() > self.cfg.quota_bytes |
| 1058 | || self.count_after() + 1 > self.cfg.max_objects |
| 1059 | { |
| 1060 | // `job` is not in the map, so `count_after` misses its own reservation |
| 1061 | // (bytes use the scalar `self.reserved`, which already holds it): add 1. |
| 1062 | let Some(victim) = self.pick_victim() else { |
| 1063 | // Nothing evictable (everything pinned or in flight): the need cannot be met. |
| 1064 | self.fail(job, PlatformError::OutOfMemory); |
| 1065 | return; |
| 1066 | }; |
| 1067 | let o = self.objects.get_mut(&victim).expect("victim"); |
| 1068 | o.evicting = true; |
| 1069 | job.victims.push((victim, o.seq)); |
| 1070 | } |
| 1071 | job.phase = Phase::Writing { |
| 1072 | at: self.now + job.script.completed_after_us, |
| 1073 | }; |
| 1074 | self.jobs.insert(job.id, job); |
| 1075 | } |
| 1076 | |
| 1077 | fn end_write(&mut self, mut job: Job) { |
| 1078 | if job.has(Fault::DiskFull) { |
| 1079 | self.stats.disk_full_total += 1; |
| 1080 | self.fail(job, PlatformError::OutOfMemory); |
| 1081 | return; |
| 1082 | } |
| 1083 | if job.has(Fault::TornWrite) { |
| 1084 | self.torn += 1; |
| 1085 | self.fail(job, hw("torn write")); |
| 1086 | return; |
| 1087 | } |
| 1088 | let src = job.src.as_ref().expect("store source"); |
| 1089 | let mut data = Vec::with_capacity(job.payload_len as usize); |
| 1090 | for i in 0..src.block_count() { |
| 1091 | match src.block(i) { |
| 1092 | Ok(b) => data.extend_from_slice(b), |
| 1093 | Err(e) => { |
| 1094 | self.violation(); |
| 1095 | self.fail(job, e); |
| 1096 | return; |
| 1097 | } |
| 1098 | } |
| 1099 | } |
| 1100 | let segment_bytes = src.block_bytes(); |
| 1101 | job.staged = Some(Staged { |
| 1102 | payload: data, |
| 1103 | segment_bytes, |
| 1104 | }); |
| 1105 | let stall = job.stall_fsync(); |
| 1106 | if stall > 0 || job.has(Fault::FsyncFileFail) { |
| 1107 | job.phase = Phase::Syncing { |
| 1108 | at: self.now + stall, |
| 1109 | }; |
| 1110 | self.jobs.insert(job.id, job); |
| 1111 | } else { |
| 1112 | self.complete_write(job); |
| 1113 | } |
| 1114 | } |
| 1115 | |
| 1116 | fn end_sync(&mut self, mut job: Job) { |
| 1117 | if job.has(Fault::FsyncFileFail) { |
| 1118 | // P2: nothing is published, the temporary object is unlinked. |
| 1119 | job.staged = None; |
| 1120 | self.stats.unlinks += 1; |
| 1121 | self.stats.io_ops += 1; |
| 1122 | if self.cfg.durability == DurabilityMode::OnFlush { |
| 1123 | self.state = StoreState::Failed; |
| 1124 | } else { |
| 1125 | self.set_degraded(); |
| 1126 | } |
| 1127 | self.fail(job, hw("fsync(file) failed")); |
| 1128 | } else { |
| 1129 | self.complete_write(job); |
| 1130 | } |
| 1131 | } |
| 1132 | |
| 1133 | fn complete_write(&mut self, mut job: Job) { |
| 1134 | self.stats.writes += 1; |
| 1135 | self.stats.io_ops += 2; // payload write and file sync |
| 1136 | job.stage = JobStage::Completed; |
| 1137 | self.progress(&job, JobStage::Completed); |
| 1138 | job.phase = Phase::Publishing { |
| 1139 | at: self.now + job.script.published_after_us, |
| 1140 | }; |
| 1141 | self.jobs.insert(job.id, job); |
| 1142 | } |
| 1143 | |
| 1144 | fn publish(&mut self, mut job: Job) { |
| 1145 | let staged = job.staged.take().expect("staged payload"); |
| 1146 | let header = job.header.expect("store header"); |
| 1147 | let with_publish = self.cfg.durability == DurabilityMode::WithPublish; |
| 1148 | let dirsync_fail = with_publish && job.has(Fault::RenameOkDirsyncFail); |
| 1149 | self.stats.io_ops += if with_publish { 2 } else { 1 }; |
| 1150 | self.stats.published_total += 1; |
| 1151 | self.publish_seq += 1; |
| 1152 | let seq = self.next_seq; |
| 1153 | self.next_seq += 1; |
| 1154 | let digests = digests_of(&staged.payload, staged.segment_bytes); |
| 1155 | self.objects.insert( |
| 1156 | kb(&job.key), |
| 1157 | Object { |
| 1158 | header, |
| 1159 | payload: staged.payload, |
| 1160 | segment_bytes: staged.segment_bytes, |
| 1161 | digests, |
| 1162 | seq, |
| 1163 | publish_seq: self.publish_seq, |
| 1164 | durable: with_publish && !dirsync_fail, |
| 1165 | indeterminate: dirsync_fail, |
| 1166 | evicting: false, |
| 1167 | }, |
| 1168 | ); |
| 1169 | // The reservation became used bytes. |
| 1170 | self.reserved -= job.reserved; |
| 1171 | job.reserved = 0; |
| 1172 | job.stage = JobStage::Published; |
| 1173 | if dirsync_fail { |
| 1174 | self.stats.indeterminate_total += 1; |
| 1175 | self.set_degraded(); |
| 1176 | self.finish( |
| 1177 | job, |
| 1178 | Terminal::Failed(hw("fsync(dir) failed after rename")), |
| 1179 | JobStage::Published, |
| 1180 | PublishOutcome::Indeterminate, |
| 1181 | ); |
| 1182 | } else if with_publish { |
| 1183 | job.stage = JobStage::Durable; |
| 1184 | self.finish( |
| 1185 | job, |
| 1186 | Terminal::Done(JobStage::Durable), |
| 1187 | JobStage::Durable, |
| 1188 | PublishOutcome::Durable, |
| 1189 | ); |
| 1190 | } else { |
| 1191 | self.finish( |
| 1192 | job, |
| 1193 | Terminal::Done(JobStage::Published), |
| 1194 | JobStage::Published, |
| 1195 | PublishOutcome::NotApplicable, |
| 1196 | ); |
| 1197 | } |
| 1198 | } |
| 1199 | |
| 1200 | fn end_read(&mut self, mut job: Job) { |
| 1201 | let k = kb(&job.key); |
| 1202 | let Some(o) = self.objects.get(&k) else { |
| 1203 | let key = job.key.0; |
| 1204 | self.fail(job, PlatformError::ObjectNotFound(key)); |
| 1205 | return; |
| 1206 | }; |
| 1207 | let good = digests_of(&o.payload, o.segment_bytes) == o.digests; |
| 1208 | if !good { |
| 1209 | // A failed hash removes the object (cache semantics, ADR 1.4). |
| 1210 | self.objects.remove(&k); |
| 1211 | self.stats.unlinks += 1; |
| 1212 | self.stats.io_ops += 2; |
| 1213 | self.fail(job, PlatformError::InvalidLayout); |
| 1214 | return; |
| 1215 | } |
| 1216 | let o = self.objects.get(&k).expect("object"); |
| 1217 | let dst = job.dst.as_mut().expect("load destination"); |
| 1218 | for (i, seg) in o.payload.chunks(o.segment_bytes).enumerate() { |
| 1219 | if let Err(e) = dst.write_block(i, seg) { |
| 1220 | self.violation(); |
| 1221 | self.fail(job, e); |
| 1222 | return; |
| 1223 | } |
| 1224 | } |
| 1225 | self.stats.reads += 1; |
| 1226 | self.stats.io_ops += 1; |
| 1227 | job.stage = JobStage::Completed; |
| 1228 | self.finish( |
| 1229 | job, |
| 1230 | Terminal::Done(JobStage::Completed), |
| 1231 | JobStage::Completed, |
| 1232 | PublishOutcome::NotApplicable, |
| 1233 | ); |
| 1234 | } |
| 1235 | |
| 1236 | fn end_flush(&mut self, mut job: Job) { |
| 1237 | self.stats.io_ops += 1; |
| 1238 | if job.has(Fault::FlushFail) { |
| 1239 | if self.cfg.durability == DurabilityMode::OnFlush { |
| 1240 | self.state = StoreState::Failed; |
| 1241 | } else { |
| 1242 | self.set_degraded(); |
| 1243 | } |
| 1244 | self.fail(job, hw("flush failed")); |
| 1245 | return; |
| 1246 | } |
| 1247 | let cover = job.cover_seq; |
| 1248 | for o in self.objects.values_mut() { |
| 1249 | if o.publish_seq <= cover && !o.indeterminate { |
| 1250 | o.durable = true; |
| 1251 | } |
| 1252 | } |
| 1253 | job.stage = JobStage::Durable; |
| 1254 | self.finish( |
| 1255 | job, |
| 1256 | Terminal::Done(JobStage::Durable), |
| 1257 | JobStage::Durable, |
| 1258 | PublishOutcome::Durable, |
| 1259 | ); |
| 1260 | } |
| 1261 | |
| 1262 | // ---- recovery -------------------------------------------------------- |
| 1263 | |
| 1264 | fn recover_step(&mut self, slice_ms: u64) -> RecoveryProgress { |
| 1265 | for _ in 0..std::mem::take(&mut self.torn) { |
| 1266 | self.disk.push_back(DiskEntry::Tmp); |
| 1267 | } |
| 1268 | let per_ms = self.cfg.recovery_entries_per_ms.max(1); |
| 1269 | let budget = slice_ms.saturating_mul(per_ms); |
| 1270 | let mut n = 0; |
| 1271 | while n < budget { |
| 1272 | let Some(e) = self.disk.pop_front() else { |
| 1273 | break; |
| 1274 | }; |
| 1275 | n += 1; |
| 1276 | self.stats.io_ops += 1; |
| 1277 | match e { |
| 1278 | DiskEntry::Tmp => { |
| 1279 | self.recovery.tmp_deleted += 1; |
| 1280 | self.stats.unlinks += 1; |
| 1281 | } |
| 1282 | DiskEntry::CorruptHeader { .. } => { |
| 1283 | self.recovery.corrupt_deleted += 1; |
| 1284 | self.stats.unlinks += 1; |
| 1285 | } |
| 1286 | DiskEntry::Object { |
| 1287 | header, |
| 1288 | payload, |
| 1289 | segment_bytes, |
| 1290 | } => { |
| 1291 | let phys = payload.len() as u64 + HEADER_REGION; |
| 1292 | self.recovery.bytes += phys; |
| 1293 | if header.namespace_id != self.cfg.namespace { |
| 1294 | self.foreign_bytes += phys; |
| 1295 | self.recovery.foreign_namespace += 1; |
| 1296 | } else if (self.objects.len() as u64) < self.cfg.max_objects { |
| 1297 | let seq = self.next_seq; |
| 1298 | self.next_seq += 1; |
| 1299 | let digests = digests_of(&payload, segment_bytes); |
| 1300 | self.objects.insert( |
| 1301 | kb(&header.chunk_key), |
| 1302 | Object { |
| 1303 | header, |
| 1304 | payload, |
| 1305 | segment_bytes, |
| 1306 | digests, |
| 1307 | seq, |
| 1308 | publish_seq: 0, |
| 1309 | durable: true, |
| 1310 | indeterminate: false, |
| 1311 | evicting: false, |
| 1312 | }, |
| 1313 | ); |
| 1314 | self.recovery.indexed += 1; |
| 1315 | } else { |
| 1316 | self.unindexed_objects += 1; |
| 1317 | self.unindexed_bytes += phys; |
| 1318 | self.recovery.unindexed_objects += 1; |
| 1319 | self.recovery.unindexed_bytes += phys; |
| 1320 | } |
| 1321 | } |
| 1322 | } |
| 1323 | } |
| 1324 | self.recovery.elapsed_us += n.saturating_mul(1000).div_ceil(per_ms); |
| 1325 | self.recovery.done = self.disk.is_empty(); |
| 1326 | if self.recovery.done && self.state == StoreState::Recovering { |
| 1327 | self.state = StoreState::Open; |
| 1328 | } |
| 1329 | self.recovery |
| 1330 | } |
| 1331 | } |
| 1332 | |
| 1333 | /// Deterministic in-memory `KvStore`; see the module docs. |
| 1334 | pub struct FakeKvStore { |
| 1335 | inner: Mutex<Inner>, |
| 1336 | } |
| 1337 | |
| 1338 | impl FakeKvStore { |
| 1339 | pub fn new(config: FakeConfig) -> Self { |
| 1340 | Self { |
| 1341 | inner: Mutex::new(Inner::new(config)), |
| 1342 | } |
| 1343 | } |
| 1344 | |
| 1345 | fn lock(&self) -> MutexGuard<'_, Inner> { |
| 1346 | self.inner.lock().unwrap_or_else(|e| e.into_inner()) |
| 1347 | } |
| 1348 | |
| 1349 | /// Run `f` under the lock, then drop released holder guards outside it (ADR 8). |
| 1350 | fn with<R>(&self, f: impl FnOnce(&mut Inner) -> R) -> R { |
| 1351 | let (r, garbage) = { |
| 1352 | let mut g = self.lock(); |
| 1353 | let r = f(&mut g); |
| 1354 | (r, std::mem::take(&mut g.graveyard)) |
| 1355 | }; |
| 1356 | drop(garbage); |
| 1357 | r |
| 1358 | } |
| 1359 | |
| 1360 | /// Queue a script for the next `submit_*` call. |
| 1361 | pub fn script(&self, script: JobScript) { |
| 1362 | self.with(|i| i.scripts.push_back(script)); |
| 1363 | } |
| 1364 | |
| 1365 | pub fn now_us(&self) -> u64 { |
| 1366 | self.with(|i| i.now) |
| 1367 | } |
| 1368 | |
| 1369 | /// Move the virtual clock forward, running every due step in time order. |
| 1370 | pub fn advance(&self, us: u64) { |
| 1371 | self.with(|i| { |
| 1372 | let t = i.now + us; |
| 1373 | i.run(Some(t), true); |
| 1374 | }); |
| 1375 | } |
| 1376 | |
| 1377 | /// Run every scheduled step, jumping the clock to each; held jobs stay held. |
| 1378 | pub fn run_until_idle(&self) { |
| 1379 | self.with(|i| i.run(None, false)); |
| 1380 | } |
| 1381 | |
| 1382 | /// End a `Hold`: the job starts at the current time. |
| 1383 | pub fn release(&self, job: JobId) -> bool { |
| 1384 | self.with(|i| { |
| 1385 | let now = i.now; |
| 1386 | match i.jobs.get_mut(&job.0) { |
| 1387 | Some(j) if j.phase == Phase::Held => { |
| 1388 | j.phase = Phase::Start { at: now }; |
| 1389 | true |
| 1390 | } |
| 1391 | _ => false, |
| 1392 | } |
| 1393 | }) |
| 1394 | } |
| 1395 | |
| 1396 | pub fn stats(&self) -> FakeStats { |
| 1397 | self.with(|i| i.stats) |
| 1398 | } |
| 1399 | |
| 1400 | pub fn payload_of(&self, key: &ChunkKey) -> Option<Vec<u8>> { |
| 1401 | self.with(|i| i.objects.get(&kb(key)).map(|o| o.payload.clone())) |
| 1402 | } |
| 1403 | |
| 1404 | /// `Some(true)` after publication on `WithPublish` or after a flush that |
| 1405 | /// started later than the publication on `OnFlush`. |
| 1406 | pub fn is_durable(&self, key: &ChunkKey) -> Option<bool> { |
| 1407 | self.with(|i| i.objects.get(&kb(key)).map(|o| o.durable)) |
| 1408 | } |
| 1409 | |
| 1410 | pub fn is_indeterminate(&self, key: &ChunkKey) -> Option<bool> { |
| 1411 | self.with(|i| i.objects.get(&kb(key)).map(|o| o.indeterminate)) |
| 1412 | } |
| 1413 | |
| 1414 | /// Flip one payload byte of a published object (a hash failure on next load). |
| 1415 | pub fn corrupt_payload(&self, key: &ChunkKey) -> bool { |
| 1416 | self.with(|i| match i.objects.get_mut(&kb(key)) { |
| 1417 | Some(o) if !o.payload.is_empty() => { |
| 1418 | o.payload[0] ^= 0xFF; |
| 1419 | true |
| 1420 | } |
| 1421 | _ => false, |
| 1422 | }) |
| 1423 | } |
| 1424 | |
| 1425 | /// Put a published object in place without a job (test setup). It is durable. |
| 1426 | pub fn inject_object(&self, header: ChunkHeader, payload: Vec<u8>, segment_bytes: usize) { |
| 1427 | self.with(|i| { |
| 1428 | let seq = i.next_seq; |
| 1429 | i.next_seq += 1; |
| 1430 | let digests = digests_of(&payload, segment_bytes); |
| 1431 | i.objects.insert( |
| 1432 | kb(&header.chunk_key), |
| 1433 | Object { |
| 1434 | header, |
| 1435 | payload, |
| 1436 | segment_bytes, |
| 1437 | digests, |
| 1438 | seq, |
| 1439 | publish_seq: 0, |
| 1440 | durable: true, |
| 1441 | indeterminate: false, |
| 1442 | evicting: false, |
| 1443 | }, |
| 1444 | ); |
| 1445 | }); |
| 1446 | } |
| 1447 | |
| 1448 | /// Put a file on the fake disk that only `recover_step` will find. |
| 1449 | pub fn inject_disk_entry(&self, entry: DiskEntry) { |
| 1450 | self.with(|i| i.disk.push_back(entry)); |
| 1451 | } |
| 1452 | |
| 1453 | /// Partial temporary objects left by torn writes, until `recover_step`. |
| 1454 | pub fn torn_residue(&self) -> u64 { |
| 1455 | self.with(|i| i.torn) |
| 1456 | } |
| 1457 | |
| 1458 | /// Terminal completions generated for `job` so far (1 once it ended, in |
| 1459 | /// every case but the duplicate-completion fault). |
| 1460 | pub fn terminal_count(&self, job: JobId) -> u32 { |
| 1461 | self.with(|i| i.term_counts.get(&job.0).copied().unwrap_or(0)) |
| 1462 | } |
| 1463 | |
| 1464 | /// Jobs that were accepted and have not reached their terminal completion. |
| 1465 | pub fn live_jobs(&self) -> Vec<JobId> { |
| 1466 | self.with(|i| i.jobs.keys().map(|k| JobId(*k)).collect()) |
| 1467 | } |
| 1468 | |
| 1469 | /// Stage a live job has reached. |
| 1470 | pub fn job_stage(&self, job: JobId) -> Option<JobStage> { |
| 1471 | self.with(|i| i.jobs.get(&job.0).map(|j| j.stage)) |
| 1472 | } |
| 1473 | |
| 1474 | /// Completions generated and not yet polled. |
| 1475 | pub fn pending_completions(&self) -> usize { |
| 1476 | self.with(|i| i.queue.len()) |
| 1477 | } |
| 1478 | |
| 1479 | /// Completion queue capacity: three slots per possible in-flight op. |
| 1480 | pub fn completion_capacity(&self) -> usize { |
| 1481 | self.with(|i| i.completion_capacity()) |
| 1482 | } |
| 1483 | |
| 1484 | /// Acknowledge recorded poison violations (they otherwise fail the test |
| 1485 | /// when the store is dropped); returns how many there were. |
| 1486 | pub fn take_poison_violations(&self) -> u64 { |
| 1487 | self.with(|i| std::mem::take(&mut i.poison_unacked)) |
| 1488 | } |
| 1489 | |
| 1490 | /// True when the internal lock is free right now. A holder-release |
| 1491 | /// callback calls this to prove it runs outside the store's lock (ADR 8). |
| 1492 | pub fn lock_is_free(&self) -> bool { |
| 1493 | match self.inner.try_lock() { |
| 1494 | Ok(_) => true, |
| 1495 | Err(TryLockError::Poisoned(_)) => true, |
| 1496 | Err(TryLockError::WouldBlock) => false, |
| 1497 | } |
| 1498 | } |
| 1499 | } |
| 1500 | |
| 1501 | impl Drop for FakeKvStore { |
| 1502 | fn drop(&mut self) { |
| 1503 | let unacked = self.lock().poison_unacked; |
| 1504 | if unacked > 0 && !std::thread::panicking() { |
| 1505 | panic!( |
| 1506 | "fake adapter: {unacked} access(es) to pool memory whose holder was already released" |
| 1507 | ); |
| 1508 | } |
| 1509 | } |
| 1510 | } |
| 1511 | |
| 1512 | impl KvStore for FakeKvStore { |
| 1513 | fn namespace(&self) -> NamespaceId { |
| 1514 | self.with(|i| i.cfg.namespace) |
| 1515 | } |
| 1516 | |
| 1517 | fn capacity(&self) -> Capacity { |
| 1518 | self.with(|i| i.capacity()) |
| 1519 | } |
| 1520 | |
| 1521 | fn lookup(&self, keys: &[ChunkKey]) -> Vec<Option<u64>> { |
| 1522 | self.with(|i| { |
| 1523 | let serving = !matches!(i.state, StoreState::Recovering | StoreState::Failed); |
| 1524 | keys.iter() |
| 1525 | .map(|k| { |
| 1526 | i.objects |
| 1527 | .get(&kb(k)) |
| 1528 | .filter(|o| serving && !o.evicting) |
| 1529 | .map(|o| o.payload.len() as u64) |
| 1530 | }) |
| 1531 | .collect() |
| 1532 | }) |
| 1533 | } |
| 1534 | |
| 1535 | fn submit_store( |
| 1536 | &self, |
| 1537 | header: ChunkHeader, |
| 1538 | src: PinnedSource, |
| 1539 | inc: Incarnation, |
| 1540 | ) -> Result<JobId, PlatformError> { |
| 1541 | // Whatever stays in `slot` is dropped here, after the lock is released. |
| 1542 | let mut slot = Some(src); |
| 1543 | self.with(|i| i.submit_store(header, &mut slot, inc)) |
| 1544 | } |
| 1545 | |
| 1546 | fn submit_load( |
| 1547 | &self, |
| 1548 | key: ChunkKey, |
| 1549 | expect: &ChunkHeader, |
| 1550 | dst: PinnedDest, |
| 1551 | inc: Incarnation, |
| 1552 | ) -> Result<JobId, PlatformError> { |
| 1553 | let mut slot = Some(dst); |
| 1554 | self.with(|i| i.submit_load(key, expect, &mut slot, inc)) |
| 1555 | } |
| 1556 | |
| 1557 | fn submit_flush(&self, inc: Incarnation) -> Result<JobId, PlatformError> { |
| 1558 | self.with(|i| i.submit_flush(inc)) |
| 1559 | } |
| 1560 | |
| 1561 | fn attach_waiter(&self, job: JobId, _inc: Incarnation) -> Result<(), PlatformError> { |
| 1562 | self.with(|i| { |
| 1563 | let per_job = i.cfg.max_waiters_per_job; |
| 1564 | let total = i.cfg.max_waiters_total; |
| 1565 | let attached_total = i.attached_total; |
| 1566 | let j = match i.jobs.get_mut(&job.0) { |
| 1567 | Some(j) if j.kind == Kind::Load && !j.cancelling => j, |
| 1568 | _ => { |
| 1569 | return Err(PlatformError::TaskRejected(String::from( |
| 1570 | "not an in-flight load", |
| 1571 | ))) |
| 1572 | } |
| 1573 | }; |
| 1574 | // The requester that submitted the load is the first waiter. |
| 1575 | if 1 + j.attached >= per_job || attached_total >= total { |
| 1576 | i.stats.queue_full_total += 1; |
| 1577 | return Err(PlatformError::QueueFull); |
| 1578 | } |
| 1579 | j.attached += 1; |
| 1580 | i.attached_total += 1; |
| 1581 | Ok(()) |
| 1582 | }) |
| 1583 | } |
| 1584 | |
| 1585 | fn poll(&self, max: usize) -> Vec<Completion> { |
| 1586 | self.with(|i| { |
| 1587 | let n = max.min(i.queue.len()); |
| 1588 | i.queue.drain(..n).collect() |
| 1589 | }) |
| 1590 | } |
| 1591 | |
| 1592 | fn cancel(&self, job: JobId) -> CancelOutcome { |
| 1593 | self.with(|i| match i.jobs.get_mut(&job.0) { |
| 1594 | None => CancelOutcome::TooLate, |
| 1595 | Some(j) if j.cancelling => CancelOutcome::Cancelled, |
| 1596 | Some(j) => { |
| 1597 | let cancellable = !matches!( |
| 1598 | (j.kind, j.phase), |
| 1599 | (Kind::Flush | Kind::Noop, _) | (_, Phase::Syncing { .. }) |
| 1600 | ); |
| 1601 | if cancellable { |
| 1602 | j.cancelling = true; |
| 1603 | CancelOutcome::Cancelled |
| 1604 | } else { |
| 1605 | CancelOutcome::TooLate |
| 1606 | } |
| 1607 | } |
| 1608 | }) |
| 1609 | } |
| 1610 | |
| 1611 | fn pin(&self, keys: &[ChunkKey]) -> Result<PinToken, PlatformError> { |
| 1612 | self.with(|i| { |
| 1613 | if i.state == StoreState::Recovering { |
| 1614 | return Err(i.queue_full()); |
| 1615 | } |
| 1616 | if i.state == StoreState::Failed || i.closed { |
| 1617 | return Err(PlatformError::DeviceUnavailable); |
| 1618 | } |
| 1619 | if i.pins.len() as u32 >= i.cfg.max_restore_ops { |
| 1620 | return Err(i.queue_full()); |
| 1621 | } |
| 1622 | for k in keys { |
| 1623 | if !i.objects.get(&kb(k)).is_some_and(|o| !o.evicting) { |
| 1624 | return Err(PlatformError::ObjectNotFound(k.0)); |
| 1625 | } |
| 1626 | } |
| 1627 | let id = i.next_pin; |
| 1628 | i.next_pin += 1; |
| 1629 | let list: Vec<Kb> = keys.iter().map(kb).collect(); |
| 1630 | for k in &list { |
| 1631 | *i.pin_counts.entry(*k).or_insert(0) += 1; |
| 1632 | } |
| 1633 | i.pins.insert(id, list); |
| 1634 | Ok(PinToken(id)) |
| 1635 | }) |
| 1636 | } |
| 1637 | |
| 1638 | fn unpin(&self, token: PinToken) { |
| 1639 | self.with(|i| { |
| 1640 | if let Some(list) = i.pins.remove(&token.0) { |
| 1641 | for k in list { |
| 1642 | if let Some(c) = i.pin_counts.get_mut(&k) { |
| 1643 | *c -= 1; |
| 1644 | if *c == 0 { |
| 1645 | i.pin_counts.remove(&k); |
| 1646 | } |
| 1647 | } |
| 1648 | } |
| 1649 | } |
| 1650 | }) |
| 1651 | } |
| 1652 | |
| 1653 | fn delete(&self, keys: &[ChunkKey]) -> u64 { |
| 1654 | self.with(|i| { |
| 1655 | if matches!(i.state, StoreState::Recovering | StoreState::Failed) { |
| 1656 | return 0; |
| 1657 | } |
| 1658 | let mut marked = 0; |
| 1659 | for k in keys { |
| 1660 | let k = kb(k); |
| 1661 | if i.is_busy(&k) || i.inflight_store.contains_key(&k) { |
| 1662 | continue; |
| 1663 | } |
| 1664 | let Some(o) = i.objects.get_mut(&k).filter(|o| !o.evicting) else { |
| 1665 | continue; |
| 1666 | }; |
| 1667 | o.evicting = true; |
| 1668 | let seq = o.seq; |
| 1669 | i.unlinks.push(Unlink { |
| 1670 | key: k, |
| 1671 | seq, |
| 1672 | at: i.now + i.cfg.unlink_us, |
| 1673 | fail: false, |
| 1674 | evict: false, |
| 1675 | }); |
| 1676 | marked += 1; |
| 1677 | } |
| 1678 | marked |
| 1679 | }) |
| 1680 | } |
| 1681 | |
| 1682 | fn recover_step(&self, slice_ms: u64) -> RecoveryProgress { |
| 1683 | self.with(|i| i.recover_step(slice_ms)) |
| 1684 | } |
| 1685 | |
| 1686 | fn shutdown(&self, intake_deadline_ms: u64) -> DrainReport { |
| 1687 | self.with(|i| { |
| 1688 | i.closed = true; |
| 1689 | let published_before = i.stats.published_total; |
| 1690 | // Cancel what can be cancelled; stores past the file sync finish. |
| 1691 | let mut cancelled = 0; |
| 1692 | for j in i.jobs.values_mut() { |
| 1693 | let cancellable = !matches!( |
| 1694 | (j.kind, j.phase), |
| 1695 | (Kind::Flush | Kind::Noop, _) |
| 1696 | | (Kind::Store, Phase::Publishing { .. }) |
| 1697 | | (_, Phase::Syncing { .. }) |
| 1698 | ); |
| 1699 | if cancellable && !j.cancelling { |
| 1700 | j.cancelling = true; |
| 1701 | } |
| 1702 | if cancellable { |
| 1703 | cancelled += 1; |
| 1704 | } |
| 1705 | } |
| 1706 | let deadline = i.now + intake_deadline_ms.saturating_mul(1000); |
| 1707 | i.run(Some(deadline), false); |
| 1708 | let unfinished: Vec<UnfinishedJob> = i |
| 1709 | .jobs |
| 1710 | .values() |
| 1711 | .map(|j| UnfinishedJob { |
| 1712 | job: JobId(j.id), |
| 1713 | key: j.key, |
| 1714 | bytes: j.bytes, |
| 1715 | stage: j.stage, |
| 1716 | }) |
| 1717 | .collect(); |
| 1718 | if !unfinished.is_empty() { |
| 1719 | i.now = i.now.max(deadline); |
| 1720 | } |
| 1721 | i.stats.shutdown_unfinished_jobs = unfinished.len() as u64; |
| 1722 | i.stats.shutdown_unfinished_bytes = unfinished.iter().map(|u| u.bytes).sum(); |
| 1723 | DrainReport { |
| 1724 | published: i.stats.published_total - published_before, |
| 1725 | cancelled, |
| 1726 | unfinished, |
| 1727 | } |
| 1728 | }) |
| 1729 | } |
| 1730 | } |