//! Settings › Preview options › Local cache budget: the memory TextureCraft's rebuildable caches hold //! //! Every rebuildable cache (whole-map fields, curvature sizes, micro details and anchor heights, //! the layers below an edited one per texture set, projector depth views, painted path tiles and //! layer thumbnails) counts its entries in one [`CacheLedger`]. The caches have no size of their //! own: on Auto they keep entries while the system has memory to spare, and when memory gets tight //! the ledger evicts the least recently used entries across all caches. Memory is tight when the //! caches hold more than Max RAM for file work's share of the system's memory, or more than the //! system still has available. A cap set in Local cache budget (in MB) also evicts at the cap. use std::collections::{BTreeMap, HashMap}; use std::sync::{Arc, LazyLock, Mutex, MutexGuard, PoisonError, Weak}; /// The system's memory, in bytes (0 when the system does not say) #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Memory { pub total: u64, pub available: u64, } /// Reads the system's memory when the ledger checks for pressure pub type MemoryProbe = Box Memory + Send + Sync>; /// A cache whose entries the ledger can evict pub trait Evict: Send + Sync { /// Drop the entry holding the ticket numbered `entry`, if it is still there fn evict(&self, entry: u64); } /// A cache entry that carries its ledger ticket pub trait Ticketed { fn ticket(&self) -> &CacheTicket; } /// A cache kept as one list of ticketed entries: eviction drops the entry with the ticket impl Evict for Mutex> { fn evict(&self, entry: u64) { let evicted: Vec = { let mut entries = self.lock().unwrap_or_else(PoisonError::into_inner); let (evicted, kept) = std::mem::take(&mut *entries).into_iter().partition(|cached| cached.ticket().id == entry); *entries = kept; evicted }; // Dropped outside the lock: dropping an entry releases its ticket drop(evicted); } } /// One cache entry counted in a [`CacheLedger`]: using it marks it recently used, dropping it /// takes its bytes off the count pub struct CacheTicket { id: u64, ledger: Arc, } impl CacheTicket { /// Mark the entry as the most recently used of all caches pub fn touch(&self) { self.ledger.touch(self.id); } } impl Drop for CacheTicket { fn drop(&mut self) { self.ledger.release(self.id); } } impl std::fmt::Debug for CacheTicket { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.debug_struct("CacheTicket").field("id", &self.id).finish() } } /// An entry the ledger counts: its bytes and the cache holding it struct Slot { id: u64, bytes: usize, owner: Weak, } #[derive(Default)] struct LedgerState { held: usize, next_id: u64, clock: u64, /// Entries by when they were last used, oldest first by_age: BTreeMap, /// When each entry was last used, by ticket ages: HashMap, /// Local cache budget (in MB) in bytes; None is Auto cap: Option, /// Max RAM for file work, percent of the system's memory ram_percent: u8, } impl LedgerState { fn tick(&mut self) -> u64 { self.clock += 1; self.clock } } /// The bytes all rebuildable caches hold, and their entries from least to most recently used pub struct CacheLedger { state: Mutex, memory: MemoryProbe, } impl CacheLedger { /// A ledger on Auto reading the system's memory through `memory`, with Max RAM for file work's default share pub fn new(memory: MemoryProbe) -> Arc { let state = LedgerState { ram_percent: DEFAULT_RAM_PERCENT, ..LedgerState::default() }; Arc::new(CacheLedger { state: Mutex::new(state), memory }) } /// Evict at `cap_mib` MiB as well as under memory pressure (None: Auto), and /// count more than `ram_percent` percent of the system's memory as pressure; 0 MiB is Auto too. /// Returns whether they changed. pub fn set_limits(&self, cap_mib: Option, ram_percent: u8) -> bool { let mut state = self.lock(); let cap = cap_mib.filter(|&mib| mib > 0).map(|mib| (mib as usize).saturating_mul(BYTES_PER_MIB)); let ram_percent = ram_percent.clamp(1, 100); let changed = (cap, ram_percent) != (state.cap, state.ram_percent); state.cap = cap; state.ram_percent = ram_percent; changed } /// Evict at `cap` bytes as well as under memory pressure (None: Auto) #[cfg(test)] pub(crate) fn set_cap_bytes(&self, cap: Option) { self.lock().cap = cap; } /// The bytes the caches hold together pub fn held_bytes(&self) -> usize { self.lock().held } /// Count a new entry of `bytes` held by `owner` as the most recently used, then evict the /// least recently used entries of every cache while memory is tight. Call it with the /// owner's lock released: eviction locks the caches it evicts from. pub fn admit(self: &Arc, owner: Weak, bytes: usize) -> CacheTicket { let ticket = self.register(owner, bytes); self.trim(); ticket } /// Count a new entry of `bytes` held by `owner` as the most recently used without evicting: /// call it while holding the owner's lock and push the entry before the lock goes, then /// [`CacheLedger::trim`] with the lock released, so no eviction can miss the entry pub fn register(self: &Arc, owner: Weak, bytes: usize) -> CacheTicket { let id = { let mut state = self.lock(); let id = state.next_id; state.next_id += 1; let age = state.tick(); state.by_age.insert(age, Slot { id, bytes, owner }); state.ages.insert(id, age); state.held = state.held.saturating_add(bytes); id }; CacheTicket { id, ledger: self.clone() } } /// Evict least recently used entries across all caches while the caches hold more than the /// cap or memory is tight. The most recently used entry stays: the evaluation in progress reads it. pub fn trim(&self) { let victims = { let mut state = self.lock(); if state.by_age.len() <= 1 { return; } let memory = (self.memory)(); let share = usize::try_from(memory.total.saturating_mul(u64::from(state.ram_percent)) / 100).unwrap_or(usize::MAX); let available = usize::try_from(memory.available).unwrap_or(usize::MAX); let mut freed = 0usize; let mut victims = Vec::new(); while state.by_age.len() > 1 { // Evicted bytes go back to what the system has available let over_cap = state.cap.is_some_and(|cap| state.held > cap); let over_share = memory.total != 0 && state.held > share; let over_available = memory.total != 0 && state.held > available.saturating_add(freed); if !(over_cap || over_share || over_available) { break; } let Some((_, slot)) = state.by_age.pop_first() else { break }; state.ages.remove(&slot.id); state.held = state.held.saturating_sub(slot.bytes); freed = freed.saturating_add(slot.bytes); victims.push(slot); } victims }; // Evict with the ledger unlocked: dropping an entry releases its ticket for slot in victims { if let Some(owner) = slot.owner.upgrade() { owner.evict(slot.id); } } } /// The bytes the caches can still take before memory gets tight (`usize::MAX` when nothing says) pub fn headroom(&self) -> usize { let (held, cap, ram_percent) = { let state = self.lock(); (state.held, state.cap, state.ram_percent) }; let mut room = cap.map_or(usize::MAX, |cap| cap.saturating_sub(held)); let memory = (self.memory)(); if memory.total != 0 { let share = usize::try_from(memory.total.saturating_mul(u64::from(ram_percent)) / 100).unwrap_or(usize::MAX); let available = usize::try_from(memory.available).unwrap_or(usize::MAX); room = room.min(share.saturating_sub(held)).min(available); } room } /// Change the bytes of entry `id` and mark it the most recently used, then evict while memory is tight fn resize(&self, id: u64, bytes: usize) { { let mut state = self.lock(); let Some(age) = state.ages.get(&id).copied() else { return }; let Some(mut slot) = state.by_age.remove(&age) else { return }; state.held = state.held.saturating_sub(slot.bytes).saturating_add(bytes); slot.bytes = bytes; let newest = state.tick(); state.by_age.insert(newest, slot); state.ages.insert(id, newest); } self.trim(); } fn touch(&self, id: u64) { let mut state = self.lock(); let Some(age) = state.ages.get(&id).copied() else { return }; let Some(slot) = state.by_age.remove(&age) else { return }; let newest = state.tick(); state.by_age.insert(newest, slot); state.ages.insert(id, newest); } fn release(&self, id: u64) { let mut state = self.lock(); let Some(age) = state.ages.remove(&id) else { return }; if let Some(slot) = state.by_age.remove(&age) { state.held = state.held.saturating_sub(slot.bytes); } } fn lock(&self) -> MutexGuard<'_, LedgerState> { self.state.lock().unwrap_or_else(PoisonError::into_inner) } } /// Max RAM for file work's default share, until the settings apply theirs const DEFAULT_RAM_PERCENT: u8 = 50; const BYTES_PER_MIB: usize = 1 << 20; #[path = "cache_budget/ledger_share.rs"] mod ledger_share; pub use ledger_share::{EvictFlag, LedgerShare}; /// The ledger of the app's caches, reading the system's memory static LEDGER: LazyLock> = LazyLock::new(|| CacheLedger::new(Box::new(system_memory))); /// The ledger every cache of the app counts its entries in pub fn ledger() -> &'static Arc { &LEDGER } /// Apply the settings: Local cache budget (in MB) as a cap (None: Auto) and Max RAM for file work's share pub fn set_cache_limits(cap_mib: Option, ram_percent: u8) { if LEDGER.set_limits(cap_mib, ram_percent) { LEDGER.trim(); } } /// Count a new cache entry of `bytes` held by `owner` in the app's ledger without evicting ([`CacheLedger::register`]) pub fn register(owner: Weak, bytes: usize) -> CacheTicket { LEDGER.register(owner, bytes) } /// Evict the least recently used entries of the app's caches while memory is tight pub fn trim() { LEDGER.trim(); } /// The bytes the app's caches can still take before memory gets tight pub fn headroom() -> usize { LEDGER.headroom() } /// How long a reading of the system's memory stands: caches check it per tile, and a reading /// costs several file reads #[cfg(not(target_arch = "wasm32"))] const MEMORY_READING_LIFETIME: std::time::Duration = std::time::Duration::from_millis(100); /// The system's memory and what it can still give out, within the process's memory limit #[cfg(not(target_arch = "wasm32"))] fn system_memory() -> Memory { static READING: Mutex> = Mutex::new(None); let mut reading = READING.lock().unwrap_or_else(PoisonError::into_inner); if let Some((taken, memory)) = *reading && taken.elapsed() < MEMORY_READING_LIFETIME { return memory; } let memory = read_system_memory(); *reading = Some((std::time::Instant::now(), memory)); memory } #[cfg(not(target_arch = "wasm32"))] fn read_system_memory() -> Memory { let Ok(mut system) = sysinfo::System::new() else { return Memory { total: 0, available: 0 } }; system.refresh_memory(); let (mut total, mut available) = (system.total_memory(), system.available_memory()); if let Some(limits) = system.cgroup_limits() { total = total.min(limits.total_memory); available = available.min(limits.free_memory); } Memory { total, available } } /// Bytes of one WebAssembly memory page #[cfg(target_arch = "wasm32")] const WASM_PAGE_BYTES: u64 = 64 * 1024; /// A wasm32 module addresses at most 4 GiB; what it has not grown into yet is what it can still take #[cfg(target_arch = "wasm32")] fn system_memory() -> Memory { let total = 1u64 << 32; let grown = core::arch::wasm32::memory_size::<0>() as u64 * WASM_PAGE_BYTES; Memory { total, available: total.saturating_sub(grown) } } #[cfg(test)] mod tests { use std::sync::atomic::{AtomicU64, Ordering}; use super::*; const GIB: u64 = 1 << 30; /// An entry of a declared size in a cache list struct Entry(CacheTicket); impl Ticketed for Entry { fn ticket(&self) -> &CacheTicket { &self.0 } } type Cache = Arc>>; fn add(ledger: &Arc, cache: &Cache, bytes: u64) { let owner: Weak = Arc::downgrade(cache) as Weak; let ticket = ledger.admit(owner, bytes as usize); cache.lock().unwrap().push(Entry(ticket)); } /// A ledger whose system reports `total` bytes and the available bytes `available` holds fn ledger_with(total: u64, available: &Arc) -> Arc { let available = available.clone(); CacheLedger::new(Box::new(move || Memory { total, available: available.load(Ordering::Relaxed) })) } #[test] fn auto_keeps_every_entry_while_memory_is_free() { let available = Arc::new(AtomicU64::new(48 * GIB)); let ledger = ledger_with(64 * GIB, &available); let cache: Cache = Arc::default(); (0..8).for_each(|_| add(&ledger, &cache, 2 * GIB)); assert_eq!(cache.lock().unwrap().len(), 8, "Auto has no size of its own"); assert_eq!(ledger.held_bytes() as u64, 16 * GIB); } #[test] fn memory_pressure_evicts_the_least_recently_used_entries_of_every_cache() { let available = Arc::new(AtomicU64::new(48 * GIB)); let ledger = ledger_with(64 * GIB, &available); let (fields, thumbnails): (Cache, Cache) = (Arc::default(), Arc::default()); add(&ledger, &fields, GIB); add(&ledger, &thumbnails, GIB); add(&ledger, &fields, GIB); fields.lock().unwrap()[0].0.touch(); // Other programs leave 1.5 GiB: evicting gives memory back until the caches fit beside it available.store(GIB + GIB / 2, Ordering::Relaxed); add(&ledger, &fields, GIB); assert!(thumbnails.lock().unwrap().is_empty(), "the least recently used entry was another cache's"); assert_eq!(fields.lock().unwrap().len(), 2, "the touched field and the newest stay"); assert_eq!(ledger.held_bytes() as u64, 2 * GIB); } #[test] fn more_than_the_ram_share_of_the_system_is_pressure() { let available = Arc::new(AtomicU64::new(60 * GIB)); let ledger = ledger_with(64 * GIB, &available); ledger.set_limits(None, 25); let cache: Cache = Arc::default(); (0..20).for_each(|_| add(&ledger, &cache, GIB)); assert_eq!(ledger.held_bytes() as u64, 16 * GIB, "a quarter of 64 GiB"); } #[test] fn a_set_cap_evicts_at_the_cap_across_caches() { let available = Arc::new(AtomicU64::new(48 * GIB)); let ledger = ledger_with(64 * GIB, &available); ledger.set_limits(Some(3 * 1024), 50); let (first, second): (Cache, Cache) = (Arc::default(), Arc::default()); (0..4).for_each(|_| { add(&ledger, &first, GIB); add(&ledger, &second, GIB); }); assert_eq!(ledger.held_bytes() as u64, 3 * GIB); assert_eq!(first.lock().unwrap().len() + second.lock().unwrap().len(), 3); let second_bytes = second.lock().unwrap().len() as u64 * GIB; drop(first); assert_eq!(ledger.held_bytes() as u64, second_bytes, "a dropped cache takes its bytes off"); } }