1 //! inf3r-cache — host-global opaque KV state.2 //!3 //! One cache manager owns every tier on a host. A plugin owns the engine's KV4 //! codec and its VRAM slot table; it never owns a disk quota, a TTL, a tier, or5 //! an eviction policy. The wire moves opaque descriptors, never paths.6 //!7 //! The on-disk payload is deliberately uninterpreted. The index records only8 //! what the resource governor needs: identity, size, tier, time, lineage, pin9 //! state, and a CRC32C. Prompt text and tokens never enter this crate.10 11 mod authority;12 mod index;13 14 use std::collections::{BTreeMap, BTreeSet};15 use std::fmt;16 use std::fs::{self, File, OpenOptions};17 use std::io::{self, Read, Seek, SeekFrom};18 use std::os::fd::{AsFd, BorrowedFd};19 use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt};20 use std::path::{Path, PathBuf};21 use std::sync::{Arc, Mutex, MutexGuard, Weak};22 use std::time::{Duration, SystemTime, UNIX_EPOCH};23 24 use inf3r_sha256::{Sha256, sha256};25 use rustix::fs::{Advice, FlockOperation, OFlags, fadvise, fstat, statfs};26 use rustix::io::Errno;27 28 use authority::{29 TierGuard, create_temp, free_bytes, open_read, open_tier, prepare_dir, shard_path,30 };31 pub use authority::{TierProbe, probe_tier};32 use index::{Record, Recovered};33 pub use inf3r_crc32c::{Crc32c, crc32c};34 35 /// A prefix key. Its meaning is private to one engine's codec.36 pub type Key = [u8; 32];37 /// The address of one committed entry.38 pub type EntryId = [u8; 32];39 /// The composite identity of a model's runtime and weights.40 pub type Fingerprint = [u8; 32];41 42 /// The physical kind of a tier, probed from the filesystem.43 #[derive(Clone, Copy, PartialEq, Eq, Debug)]44 pub enum TierKind {45 /// A memory-backed filesystem such as tmpfs.46 Ram,47 /// A persistent filesystem.48 Disk,49 }50 51 impl TierKind {52 pub fn as_str(self) -> &'static str {53 match self {54 TierKind::Ram => "ram",55 TierKind::Disk => "disk",56 }57 }58 }59 60 /// How a codec may be rolled back.61 #[derive(Clone, Copy, PartialEq, Eq, Debug)]62 pub enum StateKind {63 /// Pure Transformer KV: a longer prefix can be truncated safely.64 PrefixTruncatable,65 /// Hybrid/SSM/SWA: a checkpoint is valid only at its exact prefix.66 CheckpointExact,67 }68 69 /// The static cache declaration of one plugin.70 #[derive(Clone, PartialEq, Eq, Debug)]71 pub struct CacheSpec {72 pub codec_version: u64,73 pub slots: u32,74 pub state_kind: StateKind,75 pub max_entry_bytes: u64,76 pub local_ram_bytes: u64,77 pub supports_save: bool,78 pub supports_restore: bool,79 pub supports_erase: bool,80 }81 82 impl CacheSpec {83 /// A declaration must name at least one direction an engine can honour.84 ///85 /// Restore-only is valid: a host may attach a read-only bind to an engine86 /// that can restore a slot but must not write one. The host policy, not87 /// this declaration, decides whether a save is permitted.88 pub fn valid(&self) -> bool {89 self.slots > 090 && self.max_entry_bytes > 091 && self.supports_erase92 && (self.supports_save || self.supports_restore)93 }94 }95 96 /// Whether the cache survives a process restart.97 #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]98 pub enum Persist {99 /// Cache entries survive until the host reboots.100 #[default]101 Reboot,102 /// Cache entries are wiped when this process opens the store.103 Session,104 }105 106 /// One storage tier.107 #[derive(Clone, PartialEq, Eq, Debug)]108 pub struct TierConfig {109 pub name: String,110 pub dir: PathBuf,111 /// Bytes this tier may hold. `None` means free space minus `headroom`.112 pub bound: Option<u64>,113 pub headroom: u64,114 /// Overrides the global TTL for this tier.115 pub ttl: Option<Duration>,116 }117 118 /// Host-global cache intent.119 #[derive(Clone, PartialEq, Eq, Debug)]120 pub struct CacheConfig {121 pub enabled: bool,122 pub persist: Persist,123 /// Bytes that may be pinned. Zero is a zero budget, not unlimited: a pin124 /// request is refused unless the operator grants a positive ceiling.125 pub pin_bound: u64,126 pub flush_budget: Duration,127 pub default_ttl: Duration,128 pub classes: BTreeMap<String, Duration>,129 pub tiers: Vec<TierConfig>,130 pub blob_dir: PathBuf,131 }132 133 impl Default for CacheConfig {134 fn default() -> CacheConfig {135 CacheConfig {136 enabled: false,137 persist: Persist::Reboot,138 // No pin budget by default. A zero value must never mean139 // "unlimited": pins are an operator grant.140 pin_bound: 0,141 flush_budget: Duration::from_secs(5),142 default_ttl: Duration::from_secs(7 * 24 * 60 * 60),143 classes: BTreeMap::new(),144 tiers: Vec::new(),145 blob_dir: PathBuf::new(),146 }147 }148 }149 150 /// A named retention class is a host policy, never a bundle property.151 pub fn class_ttl(config: &CacheConfig, class: &str) -> Duration {152 config153 .classes154 .get(class)155 .copied()156 .unwrap_or(config.default_ttl)157 }158 159 /// The kind of a committed checkpoint.160 #[derive(Clone, Copy, PartialEq, Eq, Debug)]161 pub enum EntryKind {162 Tip,163 Anchor,164 }165 166 /// One committed cache entry. The payload bytes are not here.167 #[derive(Clone, PartialEq, Eq, Debug)]168 pub struct EntryMeta {169 pub id: EntryId,170 pub key: Key,171 pub fingerprint: Fingerprint,172 pub bundle: String,173 pub kind: EntryKind,174 pub lineage: Option<Key>,175 pub supersedes: Option<Key>,176 pub bytes: u64,177 pub allocated: u64,178 pub crc32c: u32,179 pub created: u64,180 pub touched: u64,181 pub expires: u64,182 pub token_count: u64,183 pub prefill_ms: u64,184 pub pinned: bool,185 pub hits: u32,186 pub anchor: bool,187 pub tier: u16,188 }189 190 /// Why a cache operation was refused.191 #[derive(Clone, PartialEq, Eq, Debug)]192 pub enum CacheError {193 /// The host configuration is contradictory.194 Layout(String),195 /// The cache is disabled by the operator.196 Disabled,197 /// Another manager owns the filesystem or directory.198 Busy(String),199 /// A tier or the whole cache is full.200 Full,201 /// The pinned budget would be exceeded.202 PinBound,203 /// The entry is not present or is no longer visible.204 Missing,205 /// A lease does not belong to this session or is already closed.206 Lease(String),207 /// The entry bytes do not match the declared length or checksum.208 Corrupt(String),209 /// The caller's session has no cache declaration.210 Session,211 /// Saving this entry would cost more than recomputing it.212 Admission,213 /// The request is outside the declared shape.214 Invalid(String),215 /// The filesystem failed.216 Io { path: PathBuf, why: String },217 }218 219 impl CacheError {220 pub fn io(path: impl Into<PathBuf>, why: io::Error) -> CacheError {221 CacheError::Io {222 path: path.into(),223 why: why.to_string(),224 }225 }226 227 pub(crate) fn errno(path: impl Into<PathBuf>, why: Errno) -> CacheError {228 CacheError::Io {229 path: path.into(),230 why: why.to_string(),231 }232 }233 }234 235 impl fmt::Display for CacheError {236 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {237 match self {238 CacheError::Layout(why) => f.write_str(why),239 CacheError::Disabled => f.write_str("the cache is disabled"),240 CacheError::Busy(why) => f.write_str(why),241 CacheError::Full => f.write_str("the cache is full"),242 CacheError::PinBound => f.write_str("the pinned cache bound is full"),243 CacheError::Missing => f.write_str("the cache entry is not present"),244 CacheError::Lease(why) => write!(f, "cache lease: {why}"),245 CacheError::Corrupt(why) => write!(f, "cache entry is corrupt: {why}"),246 CacheError::Session => f.write_str("the peer has no cache declaration"),247 CacheError::Admission => f.write_str("the cache entry would cost more than prefill"),248 CacheError::Invalid(why) => f.write_str(why),249 CacheError::Io { path, why } => write!(f, "{}: {why}", path.display()),250 }251 }252 }253 254 impl std::error::Error for CacheError {}255 256 /// One degradation reason.257 #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]258 pub struct EvictionCounts {259 pub quota: u64,260 pub ttl: u64,261 pub disk_pressure: u64,262 pub invalidated: u64,263 pub superseded: u64,264 pub corrupt: u64,265 }266 267 /// Counters and gauges for one tier.268 #[derive(Clone, PartialEq, Eq, Debug, Default)]269 pub struct TierStats {270 pub name: String,271 pub kind: String,272 pub fs_dev: u64,273 pub bytes_used: u64,274 pub bytes_reserved: u64,275 pub bytes_pinned: u64,276 pub bound: Option<u64>,277 pub fs_free: u64,278 pub headroom: u64,279 pub entries: u64,280 pub hits: u64,281 pub evictions: u64,282 pub demotions_in: u64,283 pub demotions_out: u64,284 pub read_mb_s: u64,285 pub write_mb_s: u64,286 }287 288 /// Counters and gauges for one bundle.289 #[derive(Clone, PartialEq, Eq, Debug, Default)]290 pub struct ModelStats {291 pub bundle: String,292 pub fingerprint: String,293 pub hits: u64,294 pub misses: u64,295 pub bytes_by_tier: BTreeMap<String, u64>,296 pub entries: u64,297 pub pinned_bytes: u64,298 pub evictions: u64,299 pub demotions: u64,300 pub saved_prefill_ms: u64,301 pub save_ms_avg: u64,302 pub restore_ms_avg: u64,303 }304 305 /// Everything `/stats` needs about the cache.306 #[derive(Clone, PartialEq, Eq, Debug, Default)]307 pub struct CacheStats {308 pub enabled: bool,309 pub hits: u64,310 pub misses: u64,311 pub saved_prefill_ms_total: u64,312 pub evictions: EvictionCounts,313 pub demotions: u64,314 pub promotions: u64,315 pub corrupt_entries: u64,316 pub active_writes: u64,317 pub active_reads: u64,318 pub pinned_bytes: u64,319 pub pin_bound: u64,320 pub save_count: u64,321 pub save_ms_total: u64,322 pub save_ms_p50: u64,323 pub save_ms_p95: u64,324 pub restore_count: u64,325 pub restore_ms_total: u64,326 pub restore_ms_p50: u64,327 pub restore_ms_p95: u64,328 pub tiers: Vec<TierStats>,329 pub models: Vec<ModelStats>,330 }331 332 /// What one maintenance pass did.333 #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]334 pub struct CacheMaintenance {335 pub expired: u64,336 pub demoted: u64,337 pub promoted: u64,338 }339 340 impl CacheStats {341 pub fn hit_rate_bp(&self) -> u32 {342 let total = self.hits.saturating_add(self.misses);343 if total == 0 {344 return 0;345 }346 u32::try_from(self.hits.saturating_mul(10_000) / total).unwrap_or(u32::MAX)347 }348 }349 350 /// A read lease. The file is open; dropping the lease releases the active351 /// reader, so an eviction that raced this restore waits instead of unlinking352 /// bytes underneath it.353 pub struct ReadLease {354 cache: Weak<Mutex<Inner>>,355 id: u64,356 pub key: Key,357 pub bytes: u64,358 pub crc32c: u32,359 pub token_count: u64,360 pub tier: String,361 file: Option<File>,362 }363 364 impl ReadLease {365 pub fn lease_id(&self) -> u64 {366 self.id367 }368 369 pub fn file(&self) -> &File {370 self.file.as_ref().expect("a live lease has a file")371 }372 373 pub fn as_fd(&self) -> BorrowedFd<'_> {374 self.file().as_fd()375 }376 377 /// Reports whether the engine restored the bytes successfully.378 pub fn release(mut self, ok: bool) {379 self.finish(ok, 0);380 }381 382 /// Reports a restore result and the time the engine spent restoring.383 pub fn release_metered(mut self, ok: bool, restore_ms: u32) {384 self.finish(ok, u64::from(restore_ms));385 }386 387 fn finish(&mut self, ok: bool, restore_ms: u64) {388 let Some(cache) = self.cache.upgrade() else {389 return;390 };391 let mut inner = lock(&cache);392 inner.release_read(self.id, ok, restore_ms);393 self.file.take();394 }395 }396 397 impl fmt::Debug for ReadLease {398 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {399 f.debug_struct("ReadLease")400 .field("id", &self.id)401 .field("bytes", &self.bytes)402 .finish_non_exhaustive()403 }404 }405 406 impl Drop for ReadLease {407 fn drop(&mut self) {408 if self.file.is_some() {409 // Dropping a lease is not proof that the bytes are bad. Only an410 // explicit `release(false)` says the restore failed.411 self.finish(true, 0);412 }413 }414 }415 416 /// A write lease. The engine writes into the temp file; commit renames it only417 /// after length and CRC32C agree. Dropping without commit aborts the write.418 pub struct WriteLease {419 cache: Weak<Mutex<Inner>>,420 id: u64,421 pub key: Key,422 pub entry_id: EntryId,423 pub max_bytes: u64,424 pub tier: String,425 file: Option<File>,426 }427 428 impl WriteLease {429 pub fn lease_id(&self) -> u64 {430 self.id431 }432 433 pub fn file(&self) -> &File {434 self.file.as_ref().expect("a live lease has a file")435 }436 437 pub fn as_fd(&self) -> BorrowedFd<'_> {438 self.file().as_fd()439 }440 441 pub fn max_bytes(&self) -> u64 {442 self.max_bytes443 }444 }445 446 impl fmt::Debug for WriteLease {447 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {448 f.debug_struct("WriteLease")449 .field("id", &self.id)450 .field("max_bytes", &self.max_bytes)451 .finish_non_exhaustive()452 }453 }454 455 impl Drop for WriteLease {456 fn drop(&mut self) {457 if self.file.is_none() {458 return;459 }460 let Some(cache) = self.cache.upgrade() else {461 return;462 };463 let mut inner = lock(&cache);464 inner.abort_write(self.id);465 self.file.take();466 }467 }468 469 /// One open cache manager.470 pub struct Cache {471 inner: Arc<Mutex<Inner>>,472 }473 474 impl Clone for Cache {475 fn clone(&self) -> Cache {476 Cache {477 inner: Arc::clone(&self.inner),478 }479 }480 }481 482 impl fmt::Debug for Cache {483 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {484 f.debug_struct("Cache")485 .field("entries", &lock(&self.inner).entries.len())486 .finish()487 }488 }489 490 impl Cache {491 /// Opens every tier, claims every filesystem, and recovers the indexes.492 pub fn open(config: CacheConfig) -> Result<Cache, CacheError> {493 Cache::open_inner(config, true)494 }495 496 /// Opens a throw-away store for a conformance runner.497 ///498 /// The runner may judge several bindings at once, and it is not the host's499 /// one cache authority. It still exercises the real ledger, index, CRC, and500 /// lease code; only the filesystem claim is skipped.501 #[cfg(feature = "verify")]502 #[doc(hidden)]503 pub fn open_for_verify(config: CacheConfig) -> Result<Cache, CacheError> {504 Cache::open_inner(config, false)505 }506 507 fn open_inner(config: CacheConfig, authority: bool) -> Result<Cache, CacheError> {508 validate(&config)?;509 // Catch the duplicate before a claim is opened, for every tier that510 // already exists. A missing tier is created by `open_tier`; its511 // duplicate is caught by the post-open check below.512 let mut existing_dev = BTreeMap::new();513 for (index, tier) in config.tiers.iter().enumerate() {514 prepare_dir(&tier.dir)?;515 let meta = fs::metadata(&tier.dir).map_err(|why| CacheError::io(&tier.dir, why))?;516 if let Some(previous) = existing_dev.insert(meta.dev(), index) {517 return Err(CacheError::Layout(format!(518 "{} and {} are the same filesystem (st_dev {}); one tier per filesystem",519 config.tiers[previous].dir.display(),520 tier.dir.display(),521 meta.dev()522 )));523 }524 }525 let mut tiers = Vec::with_capacity(config.tiers.len());526 let mut seen_dev = BTreeMap::new();527 let mut seen_disk = false;528 let blob_dir = canonical_or(&config.blob_dir);529 for (index, tc) in config.tiers.iter().enumerate() {530 let guard = open_tier(&tc.dir, authority)?;531 if tc.bound.is_none() && guard.free <= tc.headroom {532 return Err(CacheError::Layout(format!(533 "cache tier {} has {} bytes free, not above its headroom {}",534 tc.name, guard.free, tc.headroom535 )));536 }537 if let Some(previous) = seen_dev.insert(guard.dev, index) {538 return Err(CacheError::Layout(format!(539 "{} and {} are the same filesystem (st_dev {}); one tier per filesystem",540 config.tiers[previous].dir.display(),541 tc.dir.display(),542 guard.dev543 )));544 }545 if !blob_dir.as_os_str().is_empty() && overlaps(&blob_dir, &canonical_or(&tc.dir)) {546 return Err(CacheError::Layout(format!(547 "cache tier {} overlaps the blob directory {}",548 tc.dir.display(),549 config.blob_dir.display()550 )));551 }552 let mut tier = Tier::open(index as u16, tc.clone(), guard)?;553 if tier.kind == TierKind::Disk {554 seen_disk = true;555 } else if seen_disk {556 return Err(CacheError::Layout(format!(557 "cache tier {} is RAM after a disk tier; order tiers hot to cold",558 tc.name559 )));560 }561 if config.persist == Persist::Session {562 tier.wipe()?;563 }564 tier.recover()?;565 tiers.push(tier);566 }567 let total_bound: u64 = tiers.iter().filter_map(|tier| tier.config.bound).sum();568 if config.pin_bound != 0 && config.pin_bound >= total_bound && total_bound != 0 {569 return Err(CacheError::Layout(format!(570 "pin_bound {} must be below the total tier bound {}",571 config.pin_bound, total_bound572 )));573 }574 let inner = Inner {575 config,576 tiers,577 entries: BTreeMap::new(),578 by_key: BTreeMap::new(),579 sessions: BTreeMap::new(),580 inflight: BTreeSet::new(),581 read_leases: BTreeMap::new(),582 write_leases: BTreeMap::new(),583 next_lease: 1,584 stats: Counters::default(),585 pending_unlink: BTreeSet::new(),586 promote_ready: BTreeSet::new(),587 };588 let cache = Cache {589 inner: Arc::new(Mutex::new(inner)),590 };591 {592 let mut inner = lock(&cache.inner);593 let recovered: Vec<_> = inner594 .tiers595 .iter_mut()596 .map(|tier| (tier.index, tier.take_recovered()))597 .collect();598 for (tier_index, entries) in recovered {599 for mut meta in entries {600 if usize::from(tier_index) < inner.tiers.len() {601 // The tier that holds the payload is the truth. A602 // deploy that reordered tiers must not point an old603 // row at a directory that does not contain its bytes.604 meta.tier = tier_index;605 inner.insert_meta(meta, false);606 }607 }608 }609 inner.reconcile_files()?;610 }611 Ok(cache)612 }613 614 pub fn enabled(&self) -> bool {615 lock(&self.inner).config.enabled616 }617 618 pub fn config(&self) -> CacheConfig {619 lock(&self.inner).config.clone()620 }621 622 /// Creates the authenticated session that owns every lease of one peer.623 pub fn open_session(624 &self,625 id: u64,626 bundle: impl Into<String>,627 fingerprint: Fingerprint,628 spec: CacheSpec,629 ttl: Duration,630 ) -> Result<(), CacheError> {631 if !spec.valid() {632 return Err(CacheError::Invalid(633 "the cache declaration is inconsistent".into(),634 ));635 }636 let bundle = bundle.into();637 let mut inner = lock(&self.inner);638 if inner.sessions.contains_key(&id) {639 return Err(CacheError::Invalid(format!(640 "cache session {id} is already open"641 )));642 }643 inner.sessions.insert(644 id,645 SessionState {646 bundle,647 fingerprint,648 spec,649 ttl_ms: ttl.as_millis().min(u128::from(u64::MAX)) as u64,650 leases: BTreeSet::new(),651 },652 );653 Ok(())654 }655 656 pub fn close_session(&self, id: u64) {657 let mut inner = lock(&self.inner);658 inner.abort_peer(id);659 inner.sessions.remove(&id);660 }661 662 /// Finds the deepest valid prefix in the caller's chain.663 ///664 /// The caller sends longest-first. A hit is a read lease whose descriptor665 /// the engine can restore. A miss is not an error: it means cold prefill.666 pub fn lookup(667 &self,668 session: u64,669 keys: &[Key],670 lineage: Option<Key>,671 ) -> Result<Option<ReadLease>, CacheError> {672 let mut inner = lock(&self.inner);673 if !inner.config.enabled {674 return Err(CacheError::Disabled);675 }676 if keys.is_empty() || keys.len() > 64 {677 return Err(CacheError::Invalid("lookup needs 1..=64 keys".into()));678 }679 let Some(state) = inner.sessions.get(&session) else {680 return Err(CacheError::Session);681 };682 if !state.spec.supports_restore {683 return Ok(None);684 }685 let fingerprint = state.fingerprint;686 let now = now_ms();687 let mut expired = Vec::new();688 for key in keys {689 let id = entry_id(fingerprint, key);690 let Some(meta) = inner.entries.get(&id).cloned() else {691 continue;692 };693 if meta.expires != 0 && meta.expires <= now && !meta.pinned {694 expired.push(id);695 continue;696 }697 if inner.inflight.contains(&id) || inner.pending_unlink.contains(&id) {698 continue;699 }700 let path = inner.tiers[usize::from(meta.tier)].entry_path(&id);701 let file = match open_read(&path) {702 Ok(file) => {703 let _ = fadvise(&file, 0, None, Advice::WillNeed);704 file705 }706 Err(_) => {707 inner.stats.corrupt_entries += 1;708 inner.retire(&id, EvictionReason::Corrupt);709 continue;710 }711 };712 let lease = inner.next_lease;713 inner.next_lease = inner.next_lease.wrapping_add(1).max(1);714 let tier_name = inner.tiers[usize::from(meta.tier)].config.name.clone();715 inner.read_leases.insert(716 lease,717 ReadState {718 session,719 entry_id: id,720 bundle: meta.bundle.clone(),721 prefill_ms: meta.prefill_ms,722 bytes: meta.bytes,723 tier: meta.tier,724 },725 );726 inner727 .sessions728 .get_mut(&session)729 .unwrap()730 .leases731 .insert(lease);732 let mut promoted = false;733 let mut promote_tier = false;734 if let Some(meta) = inner.entries.get_mut(&id) {735 meta.hits = meta.hits.saturating_add(1);736 meta.touched = now;737 if meta.lineage.is_some()738 && lineage.is_some()739 && meta.lineage != lineage740 && meta.hits >= 2741 {742 meta.anchor = true;743 promoted = true;744 }745 let touched = Record::Touch {746 id,747 touched: meta.touched,748 hits: meta.hits,749 anchor: meta.anchor,750 };751 if meta.tier > 0 && meta.hits >= 2 {752 promote_tier = true;753 }754 let tier = usize::from(meta.tier);755 let _ = inner.tiers[tier].append(&touched);756 }757 if promote_tier {758 inner.promote_ready.insert(id);759 }760 if promoted {761 inner.stats.promotions = inner.stats.promotions.saturating_add(1);762 }763 return Ok(Some(ReadLease {764 cache: Arc::downgrade(&self.inner),765 id: lease,766 key: *key,767 bytes: meta.bytes,768 crc32c: meta.crc32c,769 token_count: meta.token_count,770 tier: tier_name,771 file: Some(file),772 }));773 }774 for id in expired {775 inner.expire(&id);776 }777 inner.stats.misses = inner.stats.misses.saturating_add(1);778 let bundle = inner779 .sessions780 .get(&session)781 .map(|state| state.bundle.clone());782 if let Some(bundle) = bundle {783 *inner.stats.bundle_misses.entry(bundle).or_default() += 1;784 }785 Ok(None)786 }787 788 /// Reserves space and opens a temp descriptor for one slot dump.789 #[allow(clippy::too_many_arguments)]790 pub fn reserve(791 &self,792 session: u64,793 key: Key,794 lineage: Option<Key>,795 supersedes: Option<Key>,796 kind: EntryKind,797 est_bytes: u64,798 prefill_ms: u64,799 _token_count: u64,800 pin: bool,801 ) -> Result<WriteLease, CacheError> {802 let mut inner = lock(&self.inner);803 if !inner.config.enabled {804 return Err(CacheError::Disabled);805 }806 let Some(state) = inner.sessions.get(&session) else {807 return Err(CacheError::Session);808 };809 if !state.spec.supports_save {810 return Err(CacheError::Invalid(811 "this plugin does not support cache save".into(),812 ));813 }814 if est_bytes == 0 || est_bytes > state.spec.max_entry_bytes {815 return Err(CacheError::Invalid(format!(816 "est_bytes {est_bytes} is above max_entry_bytes {}",817 state.spec.max_entry_bytes818 )));819 }820 let spec_max = state.spec.max_entry_bytes;821 if pin {822 let pinned: u64 = inner823 .entries824 .values()825 .filter(|meta| meta.pinned)826 .map(|meta| meta.bytes)827 .sum();828 if inner.config.pin_bound == 0829 || pinned.saturating_add(est_bytes) > inner.config.pin_bound830 {831 return Err(CacheError::PinBound);832 }833 }834 let fingerprint = state.fingerprint;835 let bundle = state.bundle.clone();836 let ttl_ms = state.ttl_ms;837 let id = entry_id(fingerprint, &key);838 if inner.entries.contains_key(&id) || inner.pending_unlink.contains(&id) {839 return Err(CacheError::Busy(840 "the entry is still retiring; retry after its readers release".into(),841 ));842 }843 if !inner.inflight.insert(id) {844 return Err(CacheError::Invalid("already_writing".into()));845 }846 let Some(tier_index) = inner.choose_tier(est_bytes, pin, &bundle)? else {847 inner.inflight.remove(&id);848 return Err(CacheError::Full);849 };850 if !pin851 && prefill_ms != 0852 && inner853 .estimate_restore_ms(tier_index, est_bytes)854 .is_some_and(|restore| prefill_ms <= restore)855 {856 inner.inflight.remove(&id);857 return Err(CacheError::Admission);858 }859 let lease = inner.next_lease;860 inner.next_lease = inner.next_lease.wrapping_add(1).max(1);861 let tier = &mut inner.tiers[usize::from(tier_index)];862 tier.reserved = tier.reserved.saturating_add(est_bytes);863 let path = tier.temp_path(lease);864 let file = match create_temp(&path) {865 Ok(file) => file,866 Err(why) => {867 tier.reserved = tier.reserved.saturating_sub(est_bytes);868 inner.inflight.remove(&id);869 return Err(why);870 }871 };872 let tier_name = tier.config.name.clone();873 let ttl_ms = tier874 .config875 .ttl876 .map(|ttl| ttl.as_millis().min(u128::from(u64::MAX)) as u64)877 .unwrap_or(ttl_ms);878 inner.write_leases.insert(879 lease,880 WriteState {881 session,882 entry_id: id,883 key,884 fingerprint,885 bundle,886 kind,887 lineage,888 supersedes,889 est_bytes,890 spec_max,891 path,892 tier: tier_index,893 pin,894 prefill_ms,895 ttl_ms,896 },897 );898 inner899 .sessions900 .get_mut(&session)901 .unwrap()902 .leases903 .insert(lease);904 Ok(WriteLease {905 cache: Arc::downgrade(&self.inner),906 id: lease,907 key,908 entry_id: id,909 max_bytes: spec_max,910 tier: tier_name,911 file: Some(file),912 })913 }914 915 /// Commits one write lease after checking its actual bytes and CRC32C.916 pub fn commit(917 &self,918 session: u64,919 lease_id: u64,920 bytes: u64,921 crc32c: u32,922 token_count: u64,923 save_ms: u64,924 ) -> Result<EntryMeta, CacheError> {925 let mut inner = lock(&self.inner);926 let state = inner927 .write_leases928 .get(&lease_id)929 .cloned()930 .ok_or_else(|| CacheError::Lease(format!("write lease {lease_id} is not open")))?;931 if state.session != session {932 return Err(CacheError::Lease(933 "the lease belongs to another session".into(),934 ));935 }936 if bytes == 0 || bytes > state.spec_max {937 return Err(CacheError::Corrupt(format!(938 "committed {bytes} bytes, declared maximum {}",939 state.spec_max940 )));941 }942 if bytes > state.est_bytes {943 // The engine can report the exact dump only after writing it. A944 // larger payload is allowed, but only after re-running the same945 // capacity, headroom and pin checks as a reservation.946 let extra = bytes.saturating_sub(state.est_bytes);947 let tier = &inner.tiers[usize::from(state.tier)];948 if tier.available() < extra949 || tier.guard.free < tier.config.headroom.saturating_add(bytes)950 {951 let _ = fs::remove_file(&state.path);952 inner.abort_write(lease_id);953 return Err(CacheError::Full);954 }955 }956 if state.pin {957 let pinned: u64 = inner958 .entries959 .values()960 .filter(|meta| meta.pinned)961 .map(|meta| meta.bytes)962 .sum();963 if inner.config.pin_bound == 0 || pinned.saturating_add(bytes) > inner.config.pin_bound964 {965 let _ = fs::remove_file(&state.path);966 inner.abort_write(lease_id);967 return Err(CacheError::PinBound);968 }969 }970 let file = OpenOptions::new()971 .read(true)972 .custom_flags(OFlags::NOFOLLOW.bits() as i32)973 .open(&state.path)974 .map_err(|why| CacheError::io(&state.path, why))?;975 let meta = fstat(file.as_fd()).map_err(|why| CacheError::errno(&state.path, why))?;976 if meta.st_size.max(0) as u64 != bytes {977 return Err(CacheError::Corrupt(format!(978 "payload is {} bytes, commit declared {bytes}",979 meta.st_size980 )));981 }982 if file_crc(&state.path)? != crc32c {983 inner.stats.corrupt_entries = inner.stats.corrupt_entries.saturating_add(1);984 let _ = fs::remove_file(&state.path);985 inner.abort_write(lease_id);986 return Err(CacheError::Corrupt("CRC32C mismatch".into()));987 }988 file.sync_all()989 .map_err(|why| CacheError::io(&state.path, why))?;990 let _ = fadvise(&file, 0, None, Advice::DontNeed);991 let tier = &mut inner.tiers[usize::from(state.tier)];992 let target = tier.entry_path(&state.entry_id);993 if let Some(parent) = target.parent() {994 fs::create_dir_all(parent).map_err(|why| CacheError::io(parent, why))?;995 fs::set_permissions(parent, fs::Permissions::from_mode(0o700))996 .map_err(|why| CacheError::io(parent, why))?;997 }998 fs::rename(&state.path, &target).map_err(|why| CacheError::io(&target, why))?;999 if let Ok(dir) = File::open(&tier.config.dir) {1000 let _ = dir.sync_all();1001 }1002 let now = now_ms();1003 let expires = if state.ttl_ms == 0 {1004 01005 } else {1006 now.saturating_add(state.ttl_ms)1007 };1008 let allocated = u64::try_from(meta.st_blocks.saturating_mul(512)).unwrap_or(u64::MAX);1009 let committed = EntryMeta {1010 id: state.entry_id,1011 key: state.key,1012 fingerprint: state.fingerprint,1013 bundle: state.bundle,1014 kind: state.kind,1015 lineage: state.lineage,1016 supersedes: state.supersedes,1017 bytes,1018 allocated,1019 crc32c,1020 created: now,1021 touched: now,1022 expires,1023 token_count,1024 prefill_ms: state.prefill_ms,1025 pinned: state.pin,1026 hits: 0,1027 anchor: state.kind == EntryKind::Anchor,1028 tier: state.tier,1029 };1030 tier.used = tier.used.saturating_add(bytes);1031 tier.reserved = tier.reserved.saturating_sub(state.est_bytes);1032 tier.write_bytes = tier.write_bytes.saturating_add(bytes);1033 tier.write_ms = tier.write_ms.saturating_add(save_ms);1034 if committed.pinned {1035 tier.pinned = tier.pinned.saturating_add(bytes);1036 }1037 let record = Record::Commit(committed.clone());1038 tier.append(&record)?;1039 if committed.pinned {1040 inner.stats.pinned_bytes = inner.stats.pinned_bytes.saturating_add(bytes);1041 }1042 let supersedes = committed.supersedes;1043 inner.insert_meta(committed.clone(), false);1044 inner.inflight.remove(&state.entry_id);1045 inner.write_leases.remove(&lease_id);1046 if let Some(other) = supersedes {1047 let old = entry_id(state.fingerprint, &other);1048 if inner.entries.contains_key(&old)1049 && !inner.entries[&old].pinned1050 && !inner.entries[&old].anchor1051 {1052 inner.retire(&old, EvictionReason::Superseded);1053 }1054 }1055 inner.stats.save_count = inner.stats.save_count.saturating_add(1);1056 inner.stats.save_ms_total = inner.stats.save_ms_total.saturating_add(save_ms);1057 inner1058 .stats1059 .save_samples1060 .push(save_ms.min(u64::from(u32::MAX)) as u32);1061 if inner.stats.save_samples.len() > 1024 {1062 inner.stats.save_samples.remove(0);1063 }1064 let save = inner1065 .stats1066 .bundle_save_ms1067 .entry(committed.bundle.clone())1068 .or_default();1069 save.0 = save.0.saturating_add(save_ms);1070 save.1 = save.1.saturating_add(1);1071 inner.compact_if_needed();1072 let _ = committed.token_count;1073 Ok(committed)1074 }1075 1076 /// Aborts a write lease without publishing anything.1077 pub fn abort(&self, session: u64, lease_id: u64) {1078 let mut inner = lock(&self.inner);1079 if inner1080 .write_leases1081 .get(&lease_id)1082 .is_some_and(|state| state.session == session)1083 {1084 inner.abort_write(lease_id);1085 }1086 }1087 1088 /// Reports the result of one restore, and releases its read lease.1089 pub fn release_read(&self, session: u64, lease_id: u64, ok: bool) {1090 self.release_read_metered(session, lease_id, ok, 0);1091 }1092 1093 /// Reports a restore result and the time it took, for rate accounting.1094 pub fn release_read_metered(&self, session: u64, lease_id: u64, ok: bool, restore_ms: u32) {1095 let mut inner = lock(&self.inner);1096 if inner1097 .read_leases1098 .get(&lease_id)1099 .is_some_and(|state| state.session == session)1100 {1101 inner.release_read(lease_id, ok, u64::from(restore_ms));1102 }1103 }1104 1105 /// Releases a read lease whose caller timed out. It is not a hit and not1106 /// a corrupt entry; the bytes were never restored.1107 pub fn abandon_read(&self, session: u64, lease_id: u64) {1108 let mut inner = lock(&self.inner);1109 if inner1110 .read_leases1111 .get(&lease_id)1112 .is_some_and(|state| state.session == session)1113 {1114 inner.abandon_read(lease_id);1115 }1116 }1117 1118 /// Drops every lease of a dead peer. The core calls this on EOF, fatal,1119 /// timeout, or a child crash.1120 pub fn abort_peer(&self, session: u64) {1121 lock(&self.inner).abort_peer(session);1122 }1123 1124 /// Removes entries of one bundle whose fingerprint is no longer current.1125 pub fn invalidate_bundle(&self, bundle: &str, current: Fingerprint) -> usize {1126 let mut inner = lock(&self.inner);1127 let stale: Vec<EntryId> = inner1128 .entries1129 .values()1130 .filter(|meta| meta.bundle == bundle && meta.fingerprint != current)1131 .map(|meta| meta.id)1132 .collect();1133 for id in &stale {1134 inner.retire(id, EvictionReason::Invalidated);1135 }1136 stale.len()1137 }1138 1139 /// Removes every entry of a bundle. Used when a bundle leaves the deploy.1140 pub fn evict_bundle(&self, bundle: &str) -> usize {1141 let mut inner = lock(&self.inner);1142 let ids: Vec<EntryId> = inner1143 .entries1144 .values()1145 .filter(|meta| meta.bundle == bundle)1146 .map(|meta| meta.id)1147 .collect();1148 for id in &ids {1149 inner.retire(id, EvictionReason::Invalidated);1150 }1151 ids.len()1152 }1153 1154 /// Pins or unpins one entry by its address.1155 pub fn set_pinned(&self, id: &EntryId, pinned: bool) -> Result<(), CacheError> {1156 let mut inner = lock(&self.inner);1157 let meta = inner.entries.get(id).cloned().ok_or(CacheError::Missing)?;1158 let tier = usize::from(meta.tier);1159 if pinned {1160 let current: u64 = inner1161 .entries1162 .values()1163 .filter(|m| m.pinned)1164 .map(|m| m.bytes)1165 .sum();1166 if inner.config.pin_bound == 01167 || current.saturating_add(meta.bytes) > inner.config.pin_bound1168 {1169 return Err(CacheError::PinBound);1170 }1171 }1172 if let Some(meta) = inner.entries.get_mut(id) {1173 if meta.pinned == pinned {1174 return Ok(());1175 }1176 meta.pinned = pinned;1177 let bytes = meta.bytes;1178 let touched = Record::Pin { id: *id, pinned };1179 let _ = inner.tiers[tier].append(&touched);1180 if pinned {1181 inner.stats.pinned_bytes = inner.stats.pinned_bytes.saturating_add(bytes);1182 inner.tiers[tier].pinned = inner.tiers[tier].pinned.saturating_add(bytes);1183 } else {1184 inner.stats.pinned_bytes = inner.stats.pinned_bytes.saturating_sub(bytes);1185 inner.tiers[tier].pinned = inner.tiers[tier].pinned.saturating_sub(bytes);1186 }1187 }1188 Ok(())1189 }1190 1191 /// Metadata for every visible entry. Never the payload.1192 pub fn entries(&self) -> Vec<EntryMeta> {1193 lock(&self.inner).entries.values().cloned().collect()1194 }1195 1196 /// Removes one entry by address.1197 pub fn evict_id(&self, id: &EntryId) -> bool {1198 let mut inner = lock(&self.inner);1199 if inner.entries.contains_key(id) {1200 inner.retire(id, EvictionReason::Invalidated);1201 true1202 } else {1203 false1204 }1205 }1206 1207 /// Runs expiration, economic demotion, and promotion once.1208 ///1209 /// The server calls this on a slow clock. Every move is bounded; a cache1210 /// that needs a second pass is not allowed to hold the caller for one.1211 pub fn maintain(&self) -> CacheMaintenance {1212 let mut inner = lock(&self.inner);1213 inner.maintain()1214 }1215 1216 /// Evicts entries on one filesystem until `need` more bytes are free.1217 ///1218 /// This is the disk-pressure hook for `blobs` and model loads. It never1219 /// touches a tier on another device, and it never evicts a pinned entry.1220 pub fn pressure(&self, dev: u64, need: u64) -> usize {1221 lock(&self.inner).pressure(dev, need)1222 }1223 1224 /// Demotes or evicts memory-backed entries to release host RAM.1225 pub fn pressure_ram(&self, need: u64) -> usize {1226 lock(&self.inner).pressure_ram(need)1227 }1228 1229 /// Releases at least `bytes` of RAM-backed cache, demoting first.1230 pub fn relieve_ram(&self, bytes: u64) -> usize {1231 lock(&self.inner).relieve_ram(bytes)1232 }1233 1234 /// The filesystems and headroom that the pressure hooks must consult.1235 pub fn filesystems(&self) -> Vec<(u64, u64)> {1236 let inner = lock(&self.inner);1237 inner1238 .tiers1239 .iter()1240 .map(|tier| (tier.guard.dev, tier.config.headroom))1241 .collect()1242 }1243 1244 /// Compacts each tier's WAL into a snapshot.1245 pub fn compact(&self) -> Result<(), CacheError> {1246 lock(&self.inner).compact_all()1247 }1248 1249 /// Removes every entry. Used by `inf3r cache evict --all`.1250 pub fn evict_all(&self) {1251 let mut inner = lock(&self.inner);1252 let ids: Vec<EntryId> = inner.entries.keys().copied().collect();1253 for id in ids {1254 inner.retire(&id, EvictionReason::Quota);1255 }1256 }1257 1258 pub fn stats(&self) -> CacheStats {1259 lock(&self.inner).stats()1260 }1261 1262 /// The number of currently visible entries. Cheap enough for a test.1263 pub fn len(&self) -> usize {1264 lock(&self.inner).entries.len()1265 }1266 1267 pub fn is_empty(&self) -> bool {1268 self.len() == 01269 }1270 1271 /// The number of temp files the tiers still hold. A crashed writer must1272 /// leave zero.1273 pub fn temp_files(&self) -> usize {1274 let inner = lock(&self.inner);1275 inner1276 .tiers1277 .iter()1278 .filter_map(|tier| fs::read_dir(tier.config.dir.join(".tmp")).ok())1279 .map(|entries| entries.flatten().count())1280 .sum()1281 }1282 1283 /// The path of a committed entry, for a test or an admin diagnostic.1284 pub fn entry_path(&self, id: &EntryId) -> Option<PathBuf> {1285 let inner = lock(&self.inner);1286 let meta = inner.entries.get(id)?;1287 Some(inner.tiers[usize::from(meta.tier)].entry_path(id))1288 }1289 }1290 1291 /// The domain-separated address of a prefix key.1292 pub fn entry_id(fingerprint: Fingerprint, key: &Key) -> EntryId {1293 let mut digest = Sha256::new();1294 digest.update(b"inf3r-kv-v1");1295 digest.update(&fingerprint);1296 digest.update(key);1297 digest.finish()1298 }1299 1300 fn file_crc(path: &Path) -> Result<u32, CacheError> {1301 let mut file = open_read(path)?;1302 let mut crc = Crc32c::new();1303 let mut buffer = [0u8; 1024 * 1024];1304 loop {1305 let read = file1306 .read(&mut buffer)1307 .map_err(|why| CacheError::io(path, why))?;1308 if read == 0 {1309 break;1310 }1311 crc.update(&buffer[..read]);1312 }1313 Ok(crc.finish())1314 }1315 1316 fn validate(config: &CacheConfig) -> Result<(), CacheError> {1317 if !config.enabled && config.tiers.is_empty() {1318 return Ok(());1319 }1320 if config.enabled && config.tiers.is_empty() {1321 return Err(CacheError::Layout(1322 "cache is enabled but has no tiers".into(),1323 ));1324 }1325 let mut names = BTreeSet::new();1326 let mut dirs = BTreeSet::new();1327 for tier in &config.tiers {1328 if tier.name.is_empty() || !names.insert(tier.name.clone()) {1329 return Err(CacheError::Layout(format!(1330 "cache tier name {} is empty or duplicated",1331 tier.name1332 )));1333 }1334 if !dirs.insert(tier.dir.clone()) {1335 return Err(CacheError::Layout(format!(1336 "cache tier {} is listed twice",1337 tier.dir.display()1338 )));1339 }1340 if tier.bound == Some(0) {1341 return Err(CacheError::Layout(format!(1342 "cache tier {} has a zero bound",1343 tier.name1344 )));1345 }1346 if tier.bound.is_none() && tier.headroom == 0 {1347 return Err(CacheError::Layout(format!(1348 "cache tier {} is unbounded and has no headroom",1349 tier.name1350 )));1351 }1352 }1353 Ok(())1354 }1355 1356 fn overlaps(a: &Path, b: &Path) -> bool {1357 a == b || a.starts_with(b) || b.starts_with(a)1358 }1359 1360 fn canonical_or(path: &Path) -> PathBuf {1361 fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())1362 }1363 1364 fn tier_kind(dir: &Path) -> TierKind {1365 // Linux TMPFS_MAGIC. A tier on any other filesystem is disk-backed, which1366 // is the conservative answer for RAM pressure.1367 const TMPFS_MAGIC: u64 = 0x0102_1994;1368 match statfs(dir) {1369 Ok(fs) if u64::try_from(fs.f_type).ok() == Some(TMPFS_MAGIC) => TierKind::Ram,1370 _ => TierKind::Disk,1371 }1372 }1373 1374 fn now_ms() -> u64 {1375 SystemTime::now()1376 .duration_since(UNIX_EPOCH)1377 .map(|d| d.as_millis().min(u128::from(u64::MAX)) as u64)1378 .unwrap_or(0)1379 }1380 1381 fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {1382 mutex1383 .lock()1384 .unwrap_or_else(|poisoned| poisoned.into_inner())1385 }1386 1387 struct Tier {1388 index: u16,1389 config: TierConfig,1390 guard: TierGuard,1391 kind: TierKind,1392 used: u64,1393 reserved: u64,1394 pinned: u64,1395 hits: u64,1396 evictions: u64,1397 demotions_in: u64,1398 demotions_out: u64,1399 read_bytes: u64,1400 read_ms: u64,1401 write_bytes: u64,1402 write_ms: u64,1403 log: File,1404 writes: u64,1405 recovered: Vec<EntryMeta>,1406 }1407 1408 impl Tier {1409 fn open(index: u16, config: TierConfig, guard: TierGuard) -> Result<Tier, CacheError> {1410 let log_path = config.dir.join("index.log");1411 let log = OpenOptions::new()1412 .read(true)1413 .write(true)1414 .create(true)1415 .truncate(false)1416 .mode(0o600)1417 .custom_flags(OFlags::NOFOLLOW.bits() as i32)1418 .open(&log_path)1419 .map_err(|why| CacheError::io(&log_path, why))?;1420 let kind = tier_kind(&config.dir);1421 Ok(Tier {1422 index,1423 config,1424 guard,1425 kind,1426 used: 0,1427 reserved: 0,1428 pinned: 0,1429 hits: 0,1430 evictions: 0,1431 demotions_in: 0,1432 demotions_out: 0,1433 read_bytes: 0,1434 read_ms: 0,1435 write_bytes: 0,1436 write_ms: 0,1437 log,1438 writes: 0,1439 recovered: Vec::new(),1440 })1441 }1442 1443 fn wipe(&mut self) -> Result<(), CacheError> {1444 for path in [1445 self.config.dir.join("index.snap"),1446 self.config.dir.join("index.log"),1447 ] {1448 match fs::remove_file(&path) {1449 Ok(()) => {}1450 Err(why) if why.kind() == io::ErrorKind::NotFound => {}1451 Err(why) => return Err(CacheError::io(&path, why)),1452 }1453 }1454 let entries = self.config.dir.join("entries");1455 match fs::remove_dir_all(&entries) {1456 Ok(()) => {}1457 Err(why) if why.kind() == io::ErrorKind::NotFound => {}1458 Err(why) => return Err(CacheError::io(&entries, why)),1459 }1460 fs::create_dir(&entries).map_err(|why| CacheError::io(&entries, why))?;1461 fs::set_permissions(&entries, fs::Permissions::from_mode(0o700))1462 .map_err(|why| CacheError::io(&entries, why))?;1463 self.log = OpenOptions::new()1464 .read(true)1465 .write(true)1466 .create(true)1467 .truncate(true)1468 .mode(0o600)1469 .custom_flags(OFlags::NOFOLLOW.bits() as i32)1470 .open(self.config.dir.join("index.log"))1471 .map_err(|why| CacheError::io(self.config.dir.join("index.log"), why))?;1472 Ok(())1473 }1474 1475 fn recover(&mut self) -> Result<(), CacheError> {1476 let Recovered { entries, valid_log } =1477 index::recover(&self.config.dir).map_err(CacheError::Layout)?;1478 let len = self1479 .log1480 .metadata()1481 .map_err(|why| CacheError::io(self.config.dir.join("index.log"), why))?1482 .len();1483 if valid_log < len {1484 self.log1485 .set_len(valid_log)1486 .map_err(|why| CacheError::io(self.config.dir.join("index.log"), why))?;1487 }1488 self.log1489 .seek(SeekFrom::Start(valid_log))1490 .map_err(|why| CacheError::io(self.config.dir.join("index.log"), why))?;1491 self.recovered = entries.into_values().collect();1492 Ok(())1493 }1494 1495 fn take_recovered(&mut self) -> Vec<EntryMeta> {1496 std::mem::take(&mut self.recovered)1497 }1498 1499 fn append(&mut self, record: &Record) -> Result<(), CacheError> {1500 self.writes = self.writes.saturating_add(1);1501 index::append(&mut self.log, record).map_err(CacheError::Layout)1502 }1503 1504 fn entry_path(&self, id: &EntryId) -> PathBuf {1505 shard_path(&self.config.dir, id).join(format!("{}.kv", hex(id)))1506 }1507 1508 fn temp_path(&self, lease: u64) -> PathBuf {1509 self.config1510 .dir1511 .join(".tmp")1512 .join(format!("{}-{lease}.part", std::process::id()))1513 }1514 1515 fn capacity(&self) -> u64 {1516 match self.config.bound {1517 Some(bound) => bound,1518 None => {1519 // `free` is the filesystem's free space right now; `used` is1520 // the part of that filesystem this cache already owns. For a1521 // tier with no explicit bound, both are available.1522 self.guard1523 .free1524 .saturating_add(self.used)1525 .saturating_sub(self.config.headroom)1526 }1527 }1528 }1529 1530 fn available(&self) -> u64 {1531 self.capacity()1532 .saturating_sub(self.used)1533 .saturating_sub(self.reserved)1534 }1535 }1536 1537 #[derive(Clone)]1538 struct SessionState {1539 bundle: String,1540 fingerprint: Fingerprint,1541 spec: CacheSpec,1542 ttl_ms: u64,1543 leases: BTreeSet<u64>,1544 }1545 1546 #[derive(Clone)]1547 struct WriteState {1548 session: u64,1549 entry_id: EntryId,1550 key: Key,1551 fingerprint: Fingerprint,1552 bundle: String,1553 kind: EntryKind,1554 lineage: Option<Key>,1555 supersedes: Option<Key>,1556 est_bytes: u64,1557 spec_max: u64,1558 path: PathBuf,1559 tier: u16,1560 pin: bool,1561 prefill_ms: u64,1562 ttl_ms: u64,1563 }1564 1565 struct ReadState {1566 session: u64,1567 entry_id: EntryId,1568 bundle: String,1569 prefill_ms: u64,1570 bytes: u64,1571 tier: u16,1572 }1573 1574 #[derive(Clone, Copy)]1575 enum EvictionReason {1576 Quota,1577 Ttl,1578 DiskPressure,1579 Invalidated,1580 Superseded,1581 Corrupt,1582 }1583 1584 #[derive(Default)]1585 struct Counters {1586 hits: u64,1587 misses: u64,1588 saved_prefill_ms_total: u64,1589 evictions: EvictionCounts,1590 demotions: u64,1591 promotions: u64,1592 corrupt_entries: u64,1593 save_count: u64,1594 save_ms_total: u64,1595 save_samples: Vec<u32>,1596 restore_count: u64,1597 restore_ms_total: u64,1598 restore_samples: Vec<u32>,1599 pinned_bytes: u64,1600 bundle_hits: BTreeMap<String, u64>,1601 bundle_misses: BTreeMap<String, u64>,1602 bundle_evictions: BTreeMap<String, u64>,1603 bundle_demotions: BTreeMap<String, u64>,1604 bundle_saved_prefill: BTreeMap<String, u64>,1605 bundle_save_ms: BTreeMap<String, (u64, u64)>,1606 bundle_restore_ms: BTreeMap<String, (u64, u64)>,1607 }1608 1609 struct Inner {1610 config: CacheConfig,1611 tiers: Vec<Tier>,1612 entries: BTreeMap<EntryId, EntryMeta>,1613 by_key: BTreeMap<(Fingerprint, Key), EntryId>,1614 sessions: BTreeMap<u64, SessionState>,1615 inflight: BTreeSet<EntryId>,1616 read_leases: BTreeMap<u64, ReadState>,1617 write_leases: BTreeMap<u64, WriteState>,1618 next_lease: u64,1619 stats: Counters,1620 pending_unlink: BTreeSet<EntryId>,1621 promote_ready: BTreeSet<EntryId>,1622 }1623 1624 impl Inner {1625 fn insert_meta(&mut self, meta: EntryMeta, count: bool) {1626 if count {1627 self.tiers[usize::from(meta.tier)].used = self.tiers[usize::from(meta.tier)]1628 .used1629 .saturating_add(meta.bytes);1630 }1631 if meta.pinned {1632 self.tiers[usize::from(meta.tier)].pinned = self.tiers[usize::from(meta.tier)]1633 .pinned1634 .saturating_add(meta.bytes);1635 self.stats.pinned_bytes = self.stats.pinned_bytes.saturating_add(meta.bytes);1636 }1637 self.by_key.insert((meta.fingerprint, meta.key), meta.id);1638 self.entries.insert(meta.id, meta);1639 }1640 1641 fn reconcile_files(&mut self) -> Result<(), CacheError> {1642 // Remove entries whose payload is gone or has the wrong length, then1643 // remove payloads that no live index row names.1644 let ids: Vec<EntryId> = self.entries.keys().copied().collect();1645 for id in ids {1646 let meta = self.entries[&id].clone();1647 let path = self.tiers[usize::from(meta.tier)].entry_path(&id);1648 let ok = fs::symlink_metadata(&path)1649 .map(|m| m.file_type().is_file() && m.len() == meta.bytes)1650 .unwrap_or(false);1651 if !ok {1652 self.entries.remove(&id);1653 self.by_key.remove(&(meta.fingerprint, meta.key));1654 if meta.pinned {1655 self.stats.pinned_bytes = self.stats.pinned_bytes.saturating_sub(meta.bytes);1656 self.tiers[usize::from(meta.tier)].pinned = self.tiers[usize::from(meta.tier)]1657 .pinned1658 .saturating_sub(meta.bytes);1659 }1660 self.stats.evictions.corrupt = self.stats.evictions.corrupt.saturating_add(1);1661 let _ = index::unlink(&path);1662 } else {1663 self.tiers[usize::from(meta.tier)].used = self.tiers[usize::from(meta.tier)]1664 .used1665 .saturating_add(meta.bytes);1666 }1667 }1668 for tier in &mut self.tiers {1669 let entries_dir = tier.config.dir.join("entries");1670 if let Ok(shards) = fs::read_dir(&entries_dir) {1671 for shard in shards.flatten() {1672 let Ok(kind) = shard.file_type() else {1673 continue;1674 };1675 if kind.is_symlink() || !kind.is_dir() {1676 continue;1677 }1678 if let Ok(files) = fs::read_dir(shard.path()) {1679 for file in files.flatten() {1680 let Ok(kind) = file.file_type() else {1681 continue;1682 };1683 if kind.is_symlink() || !kind.is_file() {1684 continue;1685 }1686 let name = file.file_name().to_string_lossy().into_owned();1687 let Some(hex) = name.strip_suffix(".kv") else {1688 continue;1689 };1690 let Some(id) = parse_id(hex) else {1691 let _ = fs::remove_file(file.path());1692 continue;1693 };1694 if !self.entries.contains_key(&id) {1695 let _ = fs::remove_file(file.path());1696 }1697 }1698 }1699 }1700 }1701 }1702 Ok(())1703 }1704 1705 fn choose_tier(1706 &mut self,1707 bytes: u64,1708 pin: bool,1709 bundle: &str,1710 ) -> Result<Option<u16>, CacheError> {1711 for _ in 0..4096 {1712 self.refresh_free();1713 for (index, tier) in self.tiers.iter().enumerate() {1714 if tier.available() >= bytes1715 && tier.guard.free >= tier.config.headroom.saturating_add(bytes)1716 {1717 return Ok(Some(index as u16));1718 }1719 }1720 // A hot tier that is full is a reason to move a cold entry down,1721 // not an immediate reason to recompute it. Demotion preserves the1722 // bytes and leaves the eviction decision for the cold tier.1723 if self.demote_one(false) {1724 continue;1725 }1726 if !self.evict_one_fair(bundle) {1727 break;1728 }1729 }1730 let _ = pin;1731 Ok(None)1732 }1733 1734 fn refresh_free(&mut self) {1735 for tier in &mut self.tiers {1736 if let Ok(free) = free_bytes(&tier.guard, &tier.config.dir) {1737 tier.guard.free = free;1738 }1739 }1740 }1741 1742 fn evict_one_fair(&mut self, reserve_bundle: &str) -> bool {1743 let now = now_ms();1744 let total: u64 = self.entries.values().map(|meta| meta.bytes).sum();1745 let mut per_bundle: BTreeMap<&str, u64> = BTreeMap::new();1746 for meta in self.entries.values() {1747 *per_bundle.entry(meta.bundle.as_str()).or_default() += meta.bytes;1748 }1749 let active = per_bundle.len().max(1) as u64;1750 let share = total / active;1751 let largest = per_bundle1752 .iter()1753 .max_by_key(|(_, bytes)| **bytes)1754 .map(|(bundle, _)| *bundle);1755 let own_bytes = per_bundle.get(reserve_bundle).copied().unwrap_or(0);1756 let own_over_share = own_bytes > share;1757 let victim = self1758 .entries1759 .values()1760 .filter(|meta| !meta.pinned)1761 .min_by_key(|meta| {1762 let expired = meta.expires != 0 && meta.expires <= now;1763 let superseded = meta.supersedes.is_some();1764 // The largest over-share bundle yields before a below-share1765 // bundle's last checkpoint. A reserving bundle that is itself1766 // over share yields its own oldest entry first.1767 let largest_over_share = largest == Some(meta.bundle.as_str())1768 && per_bundle.get(meta.bundle.as_str()).copied().unwrap_or(0) > share;1769 let own = meta.bundle == reserve_bundle;1770 let rank = if own && own_over_share {1771 01772 } else if largest_over_share {1773 11774 } else if own {1775 21776 } else {1777 31778 };1779 (1780 expired,1781 superseded,1782 rank,1783 meta.anchor,1784 meta.touched,1785 meta.id,1786 )1787 })1788 .map(|meta| meta.id);1789 let Some(id) = victim else {1790 return false;1791 };1792 let reason = if self.entries[&id].expires != 0 && self.entries[&id].expires <= now {1793 EvictionReason::Ttl1794 } else if self.entries[&id].supersedes.is_some() {1795 EvictionReason::Superseded1796 } else {1797 EvictionReason::Quota1798 };1799 self.retire(&id, reason);1800 true1801 }1802 1803 fn target_fits(&self, target: u16, bytes: u64) -> bool {1804 let tier = &self.tiers[usize::from(target)];1805 tier.available() >= bytes && tier.guard.free >= tier.config.headroom.saturating_add(bytes)1806 }1807 1808 fn estimate_restore_ms(&self, tier: u16, bytes: u64) -> Option<u64> {1809 let tier = &self.tiers[usize::from(tier)];1810 if tier.read_ms == 0 || tier.read_bytes == 0 || bytes == 0 {1811 return None;1812 }1813 let rate = tier.read_bytes as u128 * 1000 / u128::from(tier.read_ms);1814 let ms = u128::from(bytes) * 1000 / rate.max(1);1815 Some(ms.min(u128::from(u64::MAX)) as u64)1816 }1817 1818 fn demote_cost_ok(&self, meta: &EntryMeta, target: u16) -> bool {1819 if meta.prefill_ms == 0 {1820 return false;1821 }1822 self.estimate_restore_ms(target, meta.bytes)1823 .is_some_and(|restore| restore < meta.prefill_ms)1824 }1825 1826 fn movable(&self, id: &EntryId) -> bool {1827 let Some(meta) = self.entries.get(id) else {1828 return false;1829 };1830 !meta.pinned1831 && !self.inflight.contains(id)1832 && !self.read_leases.values().any(|lease| lease.entry_id == *id)1833 }1834 1835 /// Moves one entry to a colder tier without changing its identity.1836 fn move_entry(&mut self, id: &EntryId, target: u16) -> Result<bool, CacheError> {1837 let Some(meta) = self.entries.get(id).cloned() else {1838 return Ok(false);1839 };1840 if meta.tier == target || !self.movable(id) || !self.target_fits(target, meta.bytes) {1841 return Ok(false);1842 }1843 let source = self.tiers[usize::from(meta.tier)].entry_path(id);1844 let destination = self.tiers[usize::from(target)].entry_path(id);1845 if destination.exists() {1846 return Ok(false);1847 }1848 if let Some(parent) = destination.parent() {1849 fs::create_dir_all(parent).map_err(|why| CacheError::io(parent, why))?;1850 fs::set_permissions(parent, fs::Permissions::from_mode(0o700))1851 .map_err(|why| CacheError::io(parent, why))?;1852 }1853 let lease = self.next_lease;1854 self.next_lease = self.next_lease.wrapping_add(1).max(1);1855 let temp = self.tiers[usize::from(target)].temp_path(lease);1856 let result = (|| -> Result<(), CacheError> {1857 let mut input = open_read(&source)?;1858 let mut output = create_temp(&temp)?;1859 io::copy(&mut input, &mut output).map_err(|why| CacheError::io(&temp, why))?;1860 output1861 .sync_all()1862 .map_err(|why| CacheError::io(&temp, why))?;1863 let _ = fadvise(&output, 0, None, Advice::DontNeed);1864 fs::rename(&temp, &destination).map_err(|why| CacheError::io(&destination, why))?;1865 if let Ok(dir) = File::open(&self.tiers[usize::from(target)].config.dir) {1866 let _ = dir.sync_all();1867 }1868 Ok(())1869 })();1870 if let Err(why) = result {1871 let _ = fs::remove_file(&temp);1872 return Err(why);1873 }1874 let old_tier = meta.tier;1875 {1876 let source_tier = &mut self.tiers[usize::from(old_tier)];1877 source_tier.used = source_tier.used.saturating_sub(meta.bytes);1878 source_tier.demotions_out = source_tier.demotions_out.saturating_add(1);1879 let target_tier = &mut self.tiers[usize::from(target)];1880 target_tier.used = target_tier.used.saturating_add(meta.bytes);1881 target_tier.demotions_in = target_tier.demotions_in.saturating_add(1);1882 }1883 let mut moved = meta.clone();1884 moved.tier = target;1885 self.entries.insert(*id, moved.clone());1886 // The target needs the full row, not only a tier pointer: on a restart1887 // the source WAL is replayed too, and a bare `Demote` in the target1888 // cannot recreate an entry that the source snapshot still names.1889 let _ = self.tiers[usize::from(target)].append(&Record::Commit(moved));1890 let _ = self.tiers[usize::from(old_tier)].append(&Record::Evict(*id));1891 let _ = fs::remove_file(&source);1892 Ok(true)1893 }1894 1895 fn demote_one(&mut self, economic_only: bool) -> bool {1896 if self.tiers.len() < 2 {1897 return false;1898 }1899 for source in 0..self.tiers.len().saturating_sub(1) {1900 let target = u16::try_from(source + 1).unwrap_or(u16::MAX);1901 let candidates: Vec<EntryId> = self1902 .entries1903 .values()1904 .filter(|meta| usize::from(meta.tier) == source && !meta.pinned)1905 .filter(|meta| !economic_only || meta.hits < 2)1906 .filter(|meta| !economic_only || self.demote_cost_ok(meta, target))1907 .map(|meta| meta.id)1908 .collect();1909 for id in candidates {1910 if self.move_entry(&id, target).unwrap_or(false) {1911 self.count_demotion(&id);1912 return true;1913 }1914 }1915 }1916 false1917 }1918 1919 fn count_demotion(&mut self, id: &EntryId) {1920 self.stats.demotions = self.stats.demotions.saturating_add(1);1921 if let Some(meta) = self.entries.get(id) {1922 *self1923 .stats1924 .bundle_demotions1925 .entry(meta.bundle.clone())1926 .or_default() += 1;1927 }1928 }1929 1930 fn promote_one(&mut self) -> bool {1931 let ids: Vec<EntryId> = self.promote_ready.iter().copied().collect();1932 for id in ids {1933 self.promote_ready.remove(&id);1934 let Some(meta) = self.entries.get(&id) else {1935 continue;1936 };1937 if meta.tier == 0 || meta.hits < 2 {1938 continue;1939 }1940 if self.move_entry(&id, 0).unwrap_or(false) {1941 self.stats.promotions = self.stats.promotions.saturating_add(1);1942 return true;1943 }1944 }1945 false1946 }1947 1948 fn maintain(&mut self) -> CacheMaintenance {1949 let now = now_ms();1950 let expired: Vec<EntryId> = self1951 .entries1952 .values()1953 .filter(|meta| !meta.pinned && meta.expires != 0 && meta.expires <= now)1954 .map(|meta| meta.id)1955 .collect();1956 let mut out = CacheMaintenance::default();1957 for id in expired {1958 if self.entries.contains_key(&id) {1959 self.expire(&id);1960 out.expired = out.expired.saturating_add(1);1961 }1962 }1963 for _ in 0..64 {1964 if !self.promote_one() {1965 break;1966 }1967 out.promoted = out.promoted.saturating_add(1);1968 }1969 for _ in 0..64 {1970 if !self.demote_one(true) {1971 break;1972 }1973 out.demoted = out.demoted.saturating_add(1);1974 }1975 self.compact_if_needed();1976 out1977 }1978 1979 fn pressure(&mut self, dev: u64, need: u64) -> usize {1980 let mut evicted = 0;1981 self.refresh_free();1982 while let Some((free, headroom)) = self1983 .tiers1984 .iter()1985 .find(|tier| tier.guard.dev == dev)1986 .map(|tier| (tier.guard.free, tier.config.headroom))1987 {1988 if free >= headroom.saturating_add(need) {1989 break;1990 }1991 let now = now_ms();1992 let victim = self1993 .entries1994 .values()1995 .filter(|meta| !meta.pinned && self.tiers[usize::from(meta.tier)].guard.dev == dev)1996 .min_by_key(|meta| {1997 let expired = meta.expires != 0 && meta.expires <= now;1998 (expired, meta.supersedes.is_some(), meta.touched, meta.id)1999 })2000 .map(|meta| meta.id);2001 let Some(id) = victim else {2002 break;2003 };2004 self.retire(&id, EvictionReason::DiskPressure);2005 evicted += 1;2006 self.refresh_free();2007 }2008 evicted2009 }2010 2011 fn relieve_ram(&mut self, bytes: u64) -> usize {2012 let mut released = 0u64;2013 let mut moved = 0;2014 while released < bytes {2015 let victim = self2016 .entries2017 .values()2018 .filter(|meta| {2019 self.tiers[usize::from(meta.tier)].kind == TierKind::Ram && !meta.pinned2020 })2021 .min_by_key(|meta| (meta.supersedes.is_some(), meta.touched, meta.id))2022 .map(|meta| meta.id);2023 let Some(id) = victim else {2024 break;2025 };2026 let size = self.entries[&id].bytes;2027 let target = self2028 .tiers2029 .iter()2030 .position(|tier| tier.kind == TierKind::Disk)2031 .and_then(|index| u16::try_from(index).ok());2032 let demoted =2033 target.is_some_and(|target| self.move_entry(&id, target).unwrap_or(false));2034 if !demoted {2035 self.retire(&id, EvictionReason::DiskPressure);2036 }2037 released = released.saturating_add(size);2038 moved += 1;2039 }2040 moved2041 }2042 2043 fn pressure_ram(&mut self, need: u64) -> usize {2044 let mut moved = 0;2045 self.refresh_free();2046 while let Some((free, headroom)) = self2047 .tiers2048 .iter()2049 .filter(|tier| tier.kind == TierKind::Ram)2050 .map(|tier| (tier.guard.free, tier.config.headroom))2051 .min()2052 {2053 if free >= headroom.saturating_add(need) {2054 break;2055 }2056 let victim = self2057 .entries2058 .values()2059 .filter(|meta| {2060 self.tiers[usize::from(meta.tier)].kind == TierKind::Ram && !meta.pinned2061 })2062 .min_by_key(|meta| (meta.supersedes.is_some(), meta.touched, meta.id))2063 .map(|meta| meta.id);2064 let Some(id) = victim else {2065 break;2066 };2067 let target = self2068 .tiers2069 .iter()2070 .position(|tier| tier.kind == TierKind::Disk)2071 .and_then(|index| u16::try_from(index).ok());2072 let moved_down =2073 target.is_some_and(|target| self.move_entry(&id, target).unwrap_or(false));2074 if moved_down {2075 self.count_demotion(&id);2076 } else {2077 self.retire(&id, EvictionReason::DiskPressure);2078 }2079 moved += 1;2080 self.refresh_free();2081 }2082 moved2083 }2084 2085 fn retire(&mut self, id: &EntryId, reason: EvictionReason) {2086 let Some(meta) = self.entries.remove(id) else {2087 return;2088 };2089 self.by_key.remove(&(meta.fingerprint, meta.key));2090 *self2091 .stats2092 .bundle_evictions2093 .entry(meta.bundle.clone())2094 .or_default() += 1;2095 self.pending_unlink.insert(*id);2096 let tier = &mut self.tiers[usize::from(meta.tier)];2097 tier.used = tier.used.saturating_sub(meta.bytes);2098 tier.evictions = tier.evictions.saturating_add(1);2099 if meta.pinned {2100 tier.pinned = tier.pinned.saturating_sub(meta.bytes);2101 self.stats.pinned_bytes = self.stats.pinned_bytes.saturating_sub(meta.bytes);2102 }2103 match reason {2104 EvictionReason::Quota => self.stats.evictions.quota += 1,2105 EvictionReason::Ttl => self.stats.evictions.ttl += 1,2106 EvictionReason::DiskPressure => self.stats.evictions.disk_pressure += 1,2107 EvictionReason::Invalidated => self.stats.evictions.invalidated += 1,2108 EvictionReason::Superseded => self.stats.evictions.superseded += 1,2109 EvictionReason::Corrupt => self.stats.evictions.corrupt += 1,2110 }2111 let _ = self.tiers[usize::from(meta.tier)].append(&Record::Evict(*id));2112 self.unlink_if_unheld(id);2113 }2114 2115 fn expire(&mut self, id: &EntryId) {2116 self.retire(id, EvictionReason::Ttl);2117 }2118 2119 fn unlink_if_unheld(&mut self, id: &EntryId) {2120 if !self.pending_unlink.contains(id) {2121 return;2122 }2123 if self.read_leases.values().any(|lease| lease.entry_id == *id) {2124 return;2125 }2126 self.pending_unlink.remove(id);2127 for tier in &self.tiers {2128 let _ = index::unlink(&tier.entry_path(id));2129 }2130 }2131 2132 fn abort_write(&mut self, lease_id: u64) {2133 let Some(state) = self.write_leases.remove(&lease_id) else {2134 return;2135 };2136 self.inflight.remove(&state.entry_id);2137 let tier = &mut self.tiers[usize::from(state.tier)];2138 tier.reserved = tier.reserved.saturating_sub(state.est_bytes);2139 let _ = fs::remove_file(&state.path);2140 if let Some(session) = self.sessions.get_mut(&state.session) {2141 session.leases.remove(&lease_id);2142 }2143 }2144 2145 fn abort_peer(&mut self, session: u64) {2146 let writes: Vec<u64> = self2147 .write_leases2148 .iter()2149 .filter(|(_, state)| state.session == session)2150 .map(|(id, _)| *id)2151 .collect();2152 for id in writes {2153 self.abort_write(id);2154 }2155 let reads: Vec<u64> = self2156 .read_leases2157 .iter()2158 .filter(|(_, state)| state.session == session)2159 .map(|(id, _)| *id)2160 .collect();2161 for id in reads {2162 let Some(state) = self.read_leases.remove(&id) else {2163 continue;2164 };2165 if let Some(session) = self.sessions.get_mut(&state.session) {2166 session.leases.remove(&id);2167 }2168 self.unlink_if_unheld(&state.entry_id);2169 }2170 if let Some(state) = self.sessions.get_mut(&session) {2171 state.leases.clear();2172 }2173 }2174 2175 fn abandon_read(&mut self, lease_id: u64) {2176 let Some(state) = self.read_leases.remove(&lease_id) else {2177 return;2178 };2179 if let Some(session) = self.sessions.get_mut(&state.session) {2180 session.leases.remove(&lease_id);2181 }2182 self.unlink_if_unheld(&state.entry_id);2183 }2184 2185 fn release_read(&mut self, lease_id: u64, ok: bool, restore_ms: u64) {2186 let Some(state) = self.read_leases.remove(&lease_id) else {2187 return;2188 };2189 if let Some(session) = self.sessions.get_mut(&state.session) {2190 session.leases.remove(&lease_id);2191 }2192 self.stats.restore_count = self.stats.restore_count.saturating_add(1);2193 self.stats.restore_ms_total = self.stats.restore_ms_total.saturating_add(restore_ms);2194 self.stats2195 .restore_samples2196 .push(restore_ms.min(u64::from(u32::MAX)) as u32);2197 if self.stats.restore_samples.len() > 1024 {2198 self.stats.restore_samples.remove(0);2199 }2200 let tier = &mut self.tiers[usize::from(state.tier)];2201 tier.read_bytes = tier.read_bytes.saturating_add(state.bytes);2202 tier.read_ms = tier.read_ms.saturating_add(restore_ms);2203 let entry = self2204 .stats2205 .bundle_restore_ms2206 .entry(state.bundle.clone())2207 .or_default();2208 entry.0 = entry.0.saturating_add(restore_ms);2209 entry.1 = entry.1.saturating_add(1);2210 if !ok {2211 self.stats.corrupt_entries += 1;2212 self.retire(&state.entry_id, EvictionReason::Corrupt);2213 return;2214 }2215 // A hit is a successful restore, not merely a lookup. A corrupt or2216 // failed restore must not inflate the hit rate or the saved prefill.2217 self.stats.hits = self.stats.hits.saturating_add(1);2218 self.tiers[usize::from(state.tier)].hits =2219 self.tiers[usize::from(state.tier)].hits.saturating_add(1);2220 *self2221 .stats2222 .bundle_hits2223 .entry(state.bundle.clone())2224 .or_default() += 1;2225 self.stats.saved_prefill_ms_total = self2226 .stats2227 .saved_prefill_ms_total2228 .saturating_add(state.prefill_ms);2229 *self2230 .stats2231 .bundle_saved_prefill2232 .entry(state.bundle)2233 .or_default() += state.prefill_ms;2234 self.unlink_if_unheld(&state.entry_id);2235 }2236 2237 fn compact_if_needed(&mut self) {2238 let live = self.entries.len().max(1) as u64;2239 if self2240 .tiers2241 .iter()2242 .all(|tier| tier.writes <= (live.saturating_mul(2)).max(64))2243 {2244 return;2245 }2246 let _ = self.compact_all();2247 }2248 2249 fn compact_all(&mut self) -> Result<(), CacheError> {2250 for index in 0..self.tiers.len() {2251 let entries: BTreeMap<EntryId, EntryMeta> = self2252 .entries2253 .iter()2254 .filter(|(_, meta)| usize::from(meta.tier) == index)2255 .map(|(id, meta)| (*id, meta.clone()))2256 .collect();2257 let tier = &mut self.tiers[index];2258 index::compact(&tier.config.dir, &entries, &mut tier.log)2259 .map_err(CacheError::Layout)?;2260 tier.writes = 0;2261 }2262 Ok(())2263 }2264 2265 fn stats(&self) -> CacheStats {2266 let mut out = CacheStats {2267 enabled: self.config.enabled,2268 hits: self.stats.hits,2269 misses: self.stats.misses,2270 saved_prefill_ms_total: self.stats.saved_prefill_ms_total,2271 evictions: self.stats.evictions,2272 demotions: self.stats.demotions,2273 promotions: self.stats.promotions,2274 corrupt_entries: self.stats.corrupt_entries,2275 active_writes: self.write_leases.len() as u64,2276 active_reads: self.read_leases.len() as u64,2277 pinned_bytes: self.stats.pinned_bytes,2278 pin_bound: self.config.pin_bound,2279 save_count: self.stats.save_count,2280 save_ms_total: self.stats.save_ms_total,2281 save_ms_p50: percentile(&self.stats.save_samples, 50),2282 save_ms_p95: percentile(&self.stats.save_samples, 95),2283 restore_count: self.stats.restore_count,2284 restore_ms_total: self.stats.restore_ms_total,2285 restore_ms_p50: percentile(&self.stats.restore_samples, 50),2286 restore_ms_p95: percentile(&self.stats.restore_samples, 95),2287 ..CacheStats::default()2288 };2289 let mut by_bundle: BTreeMap<String, ModelStats> = BTreeMap::new();2290 for (index, tier) in self.tiers.iter().enumerate() {2291 let bytes_pinned = self2292 .entries2293 .values()2294 .filter(|m| usize::from(m.tier) == index && m.pinned)2295 .map(|m| m.bytes)2296 .sum();2297 out.tiers.push(TierStats {2298 name: tier.config.name.clone(),2299 kind: tier.kind.as_str().to_string(),2300 fs_dev: tier.guard.dev,2301 bytes_used: tier.used,2302 bytes_reserved: tier.reserved,2303 bytes_pinned,2304 bound: tier.config.bound,2305 fs_free: free_bytes(&tier.guard, &tier.config.dir).unwrap_or(tier.guard.free),2306 headroom: tier.config.headroom,2307 entries: self2308 .entries2309 .values()2310 .filter(|m| usize::from(m.tier) == index)2311 .count() as u64,2312 hits: tier.hits,2313 evictions: tier.evictions,2314 demotions_in: tier.demotions_in,2315 demotions_out: tier.demotions_out,2316 read_mb_s: rate_mb_s(tier.read_bytes, tier.read_ms),2317 write_mb_s: rate_mb_s(tier.write_bytes, tier.write_ms),2318 });2319 }2320 for meta in self.entries.values() {2321 let row = by_bundle.entry(meta.bundle.clone()).or_default();2322 row.bundle = meta.bundle.clone();2323 row.fingerprint = hex(&meta.fingerprint)[..12].to_string();2324 row.entries += 1;2325 row.hits = self2326 .stats2327 .bundle_hits2328 .get(&meta.bundle)2329 .copied()2330 .unwrap_or(0);2331 row.misses = self2332 .stats2333 .bundle_misses2334 .get(&meta.bundle)2335 .copied()2336 .unwrap_or(0);2337 row.pinned_bytes =2338 row.pinned_bytes2339 .saturating_add(if meta.pinned { meta.bytes } else { 0 });2340 row.demotions = self2341 .stats2342 .bundle_demotions2343 .get(&meta.bundle)2344 .copied()2345 .unwrap_or(0);2346 row.evictions = self2347 .stats2348 .bundle_evictions2349 .get(&meta.bundle)2350 .copied()2351 .unwrap_or(0);2352 row.saved_prefill_ms = self2353 .stats2354 .bundle_saved_prefill2355 .get(&meta.bundle)2356 .copied()2357 .unwrap_or(0);2358 if let Some((total, count)) = self.stats.bundle_save_ms.get(&meta.bundle)2359 && *count > 02360 {2361 row.save_ms_avg = total / count;2362 }2363 if let Some((total, count)) = self.stats.bundle_restore_ms.get(&meta.bundle)2364 && *count > 02365 {2366 row.restore_ms_avg = total / count;2367 }2368 *row.bytes_by_tier2369 .entry(self.tiers[usize::from(meta.tier)].config.name.clone())2370 .or_default() += meta.bytes;2371 }2372 out.models = by_bundle.into_values().collect();2373 out2374 }2375 }2376 2377 fn percentile(samples: &[u32], percent: usize) -> u64 {2378 if samples.is_empty() {2379 return 0;2380 }2381 let mut sorted = samples.to_vec();2382 sorted.sort_unstable();2383 let index = (sorted.len().saturating_sub(1) * percent / 100).min(sorted.len() - 1);2384 u64::from(sorted[index])2385 }2386 2387 fn rate_mb_s(bytes: u64, ms: u64) -> u64 {2388 if ms == 0 || bytes == 0 {2389 return 0;2390 }2391 bytes.saturating_mul(1000) / ms / 1_000_0002392 }2393 2394 fn hex(bytes: &[u8]) -> String {2395 let mut out = String::with_capacity(bytes.len() * 2);2396 for byte in bytes {2397 use std::fmt::Write as _;2398 let _ = write!(out, "{byte:02x}");2399 }2400 out2401 }2402 2403 fn parse_id(text: &str) -> Option<EntryId> {2404 if text.len() != 64 {2405 return None;2406 }2407 let mut out = [0u8; 32];2408 #[allow(clippy::chunks_exact_to_as_chunks)]2409 for (index, chunk) in text.as_bytes().chunks_exact(2).enumerate() {2410 let high = hex_digit(chunk[0])?;2411 let low = hex_digit(chunk[1])?;2412 out[index] = (high << 4) | low;2413 }2414 Some(out)2415 }2416 2417 fn hex_digit(byte: u8) -> Option<u8> {2418 match byte {2419 b'0'..=b'9' => Some(byte - b'0'),2420 b'a'..=b'f' => Some(byte - b'a' + 10),2421 b'A'..=b'F' => Some(byte - b'A' + 10),2422 _ => None,2423 }2424 }2425 2426 // Keep the public digest helper close to the address it feeds.2427 #[allow(dead_code)]2428 fn digest(bytes: &[u8]) -> [u8; 32] {2429 sha256(bytes)2430 }2431 2432 #[allow(dead_code)]2433 fn nofollow() -> i32 {2434 OFlags::NOFOLLOW.bits() as i322435 }2436 2437 #[allow(dead_code)]2438 fn exclusive() -> FlockOperation {2439 FlockOperation::NonBlockingLockExclusive2440 }2441 2442 #[allow(dead_code)]2443 fn free(path: &Path, guard: &TierGuard) -> Result<u64, CacheError> {2444 free_bytes(guard, path)2445 }2446 2447 #[allow(dead_code)]2448 fn file_blocks(file: &File) -> io::Result<u64> {2449 Ok(u64::try_from(fstat(file.as_fd())?.st_blocks.saturating_mul(512)).unwrap_or(u64::MAX))2450 }2451 2452 #[allow(dead_code)]2453 fn metadata_blocks(meta: &fs::Metadata) -> u64 {2454 meta.blocks().saturating_mul(512)2455 }