diff --git a/apps/rustgis-cli/tests/memory_override.rs b/apps/rustgis-cli/tests/memory_override.rs index 62faf5f217..d330470ce6 100644 --- a/apps/rustgis-cli/tests/memory_override.rs +++ b/apps/rustgis-cli/tests/memory_override.rs @@ -30,8 +30,36 @@ fn the_memory_override_sets_the_limits_and_says_so() { // 1 GiB: a quarter is the undo history's 256 MiB floor. assert_eq!(run(Some("1073741824")).0["undoBytes"], json!(256_u64 << 20)); // Without it, or with a value that isn't a positive number of bytes, nothing changes or is said. - let (plain, quiet) = run(None); + let (mut plain, quiet) = run(None); assert_ne!(plain["memorySource"], json!("override")); assert!(!quiet.contains("RUSTGIS_MEMORY_BYTES"), "{quiet}"); - assert_eq!(run(Some("8 GiB")).0, plain); + // What the computer has free is read live (#2431), so it can differ between the two runs, and + // the limits it bounds too: they are compared only where much is free. + let mut junk = run(Some("8 GiB")).0; + let (a, b) = (plain["freeBytes"].take(), junk["freeBytes"].take()); + let roomy = |free: &Value| free.as_u64().is_none_or(|f| f > plain["memory"].as_u64().unwrap_or(0) / 2); + if roomy(&a) && roomy(&b) { + assert_eq!(junk, plain); + } +} + +/// What the process holds reaches `gp.env` (#2431): with the sample project open it is more than +/// nothing, and on a computer that size it is far below half the memory, so the limits are the +/// ones with nothing held. +#[test] +fn gp_env_says_what_is_held() { + let out = Command::new(env!("CARGO_BIN_EXE_rustgis-cli")) + .args(["run", "--no-plugins", "--worldview", "default", "--sample", "--cmd", "gp.env"]) + .env("RUSTGIS_MEMORY_BYTES", "17179869184") + .env_remove("RUSTGIS_WORLDVIEW") + .output() + .unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let limits = serde_json::from_slice::(&out.stdout).unwrap()["limits"].clone(); + let held = limits["heldBytes"].as_u64().unwrap(); + assert!(held > 0 && held < 8 << 30, "{held}"); + // With the override, what else runs on the computer doesn't change the limits. + assert_eq!(limits["freeBytes"], Value::Null); + // 16 GiB plans for 4 GiB: 512 MiB of file. + assert_eq!(limits["fileBytes"], json!(512_u64 << 20)); } diff --git a/crates/analysis/src/density.rs b/crates/analysis/src/density.rs index e957175e90..32bc049017 100644 --- a/crates/analysis/src/density.rs +++ b/crates/analysis/src/density.rs @@ -42,8 +42,9 @@ pub const DENSITY_CELLS_FLOOR: usize = 16_000_000; /// a quarter of the computer's memory holds at 16 bytes a cell (the sums, the output and the /// GeoTIFF written from it), from [`DENSITY_CELLS_FLOOR`] up to the most any tool's output raster /// takes ([`crate::rasterops::PIXELS_CEILING`]) (#1291 step 2). +/// Less once RustGIS holds more than half the memory, never below the floor ([`rustgis_data::memory::planned`], #2431). pub fn max_density_cells() -> usize { - rustgis_data::memory::scaled(rustgis_data::memory::physical(), DENSITY_CELLS_FLOOR, crate::rasterops::PIXELS_CEILING, 16) + rustgis_data::memory::planned(DENSITY_CELLS_FLOOR, crate::rasterops::PIXELS_CEILING, 16) } /// Upper limit on aggregate cell visits across all points on one thread, to prevent CPU diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index c78c97a02f..8774045604 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -17,8 +17,9 @@ pub const PIXELS_CEILING: usize = 512_000_000; /// Largest output raster built (pixels): on the desktop, as many as a quarter of the computer's /// memory holds at 16 bytes each (a tool holds its input, its output and a working grid or two), /// from [`PIXELS_FLOOR`] up to [`PIXELS_CEILING`] (#1291 step 2). +/// Less once RustGIS holds more than half the memory, never below the floor ([`rustgis_data::memory::planned`], #2431). pub fn max_pixels() -> usize { - rustgis_data::memory::scaled(rustgis_data::memory::physical(), PIXELS_FLOOR, PIXELS_CEILING, 16) + rustgis_data::memory::planned(PIXELS_FLOOR, PIXELS_CEILING, 16) } /// Room for a grid of `w × h` cells of `T` (an output band, or a working grid of one), empty: a diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index bd5e1e9ca3..56d363941b 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1590,8 +1590,9 @@ const BUFFER_STORAGE_ERROR: &str = "Buffer output or distance selectors exceed t /// Buffer's retained-storage budget on this computer: on the desktop a quarter of its memory, from /// [`MAX_BUFFER_BYTES`] up to [`BUFFER_BYTES_CEILING`] (#1291 step 2); fixed in the browser. +/// Less once RustGIS holds more than half the memory, never below the floor ([`rustgis_data::memory::planned`], #2431). pub fn max_buffer_bytes() -> usize { - rustgis_data::memory::scaled(rustgis_data::memory::physical(), MAX_BUFFER_BYTES, BUFFER_BYTES_CEILING, 1) + rustgis_data::memory::planned(MAX_BUFFER_BYTES, BUFFER_BYTES_CEILING, 1) } /// [`BUFFER_STORAGE_ERROR`] with the budget it ran out of, so a run refused here but not on a diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index eec7473286..7949750b5c 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -29,19 +29,27 @@ const MEMORY_PER_BYTE: u64 = 8; /// Largest file read into memory on this computer (#2408): on the desktop as much as a quarter of /// its memory holds at [`MEMORY_PER_BYTE`] a byte, from [`BYTES_FLOOR`] up to [`BYTES_CEILING`], -/// as the other memory limits follow it (#1291 step 2); [`BYTES_FLOOR`] in the browser. +/// as the other memory limits follow it (#1291 step 2); [`BYTES_FLOOR`] in the browser. Less once +/// RustGIS holds more than half the memory, or the computer has less free ([`crate::memory::share`], +/// #2431), never below the floor. pub fn max_bytes() -> u64 { if let Some(max) = TEST_MAX.with(std::cell::Cell::get) { return max; } - max_bytes_for(crate::memory::physical()) + max_bytes_within(crate::memory::share(crate::memory::physical(), crate::memory::held(), crate::memory::available())) } -/// [`max_bytes`] on a computer with `memory` bytes (`None`: not known). The formula is -/// [`crate::memory::scaled`]'s, worked out here in `u64`, as that one counts in `usize`, which -/// doesn't hold 4 GiB on a 32-bit build. +/// [`max_bytes`] on a computer with `memory` bytes (`None`: not known) with nothing held. The +/// formula is [`crate::memory::scaled`]'s, worked out here in `u64`, as that one counts in `usize`, +/// which doesn't hold 4 GiB on a 32-bit build. fn max_bytes_for(memory: Option) -> u64 { - memory.map_or(BYTES_FLOOR, |m| (m / crate::memory::SHARE / MEMORY_PER_BYTE).clamp(BYTES_FLOOR, bytes_ceiling())) + max_bytes_within(memory.map(|m| m / crate::memory::SHARE)) +} + +/// [`max_bytes`] when a job plans for `share` bytes ([`crate::memory::share`]; `None`: not known): +/// less once RustGIS holds more than half the memory (#2431), never below [`BYTES_FLOOR`]. +fn max_bytes_within(share: Option) -> u64 { + share.map_or(BYTES_FLOOR, |share| (share / MEMORY_PER_BYTE).clamp(BYTES_FLOOR, bytes_ceiling())) } /// The most [`max_bytes`] grows to in this build: [`BYTES_CEILING`] on a 64-bit desktop build. A @@ -59,15 +67,39 @@ pub fn too_large(len: u64) -> String { too_large_said(len, max_bytes()) } -/// [`too_large`] against the limit `max` taken when the read started. +/// [`too_large`] against the limit `max` taken when the read started. What is held and free is +/// read again here: it may have moved since `max` was taken, so the figures said are the ones now, +/// beside the limit the read was held to. fn too_large_said(len: u64, max: u64) -> String { - let follows = crate::memory::physical().is_some() && bytes_ceiling() > BYTES_FLOOR; - let limit = if follows { - format!("{} on this computer, a limit that follows its memory", size_said(max, false)) - } else { - size_said(max, false) + let memory = crate::memory::physical().filter(|_| bytes_ceiling() > BYTES_FLOOR); + // A test's own limit isn't lowered by what is held or free. + let (held, free) = + if TEST_MAX.with(std::cell::Cell::get).is_some() { (0, None) } else { (crate::memory::held(), crate::memory::available()) }; + too_large_held(len, max, memory, held, free) +} + +/// [`too_large_said`] on a computer with `memory` bytes (`None`: the limit doesn't follow it) +/// while RustGIS holds `held` and `free` is free (`None`: not known): when the limit is below the +/// one with nothing else in use, it says what is held and free, that limit, and what to do (#2431). +fn too_large_held(len: u64, max: u64, memory: Option, held: u64, free: Option) -> String { + let file = size_said(len, true); + let Some(memory) = memory else { + return format!("file is too large ({file}; the most read into memory is {})", size_said(max, false)); }; - format!("file is too large ({}; the most read into memory is {limit})", size_said(len, true)) + let full = max_bytes_for(Some(memory)); + if max >= full || (held == 0 && free.is_none()) { + return format!( + "file is too large ({file}; the most read into memory is {} on this computer, a limit that follows its memory)", + size_said(max, false) + ); + } + let free = free.map(|free| format!(" and {} free", size_said(free, false))).unwrap_or_default(); + format!( + "file is too large ({file}; the most read into memory is {} on this computer now, with RustGIS holding {}{free}, {} otherwise): free memory by removing layers or tables you no longer need (save and reopen the project to let go of what Undo keeps of them) or closing other programs, then try again", + size_said(max, false), + size_said(held, true), + size_said(full, false) + ) } /// A size in MiB, rounded `up` (a file's, so it never looks within the limit) or down (the @@ -2310,9 +2342,10 @@ fn read_gzip_text_budget( /// Estimated memory for retained CSV rows and the dataset built alongside them: a quarter /// of physical memory, between 256 MiB (also the browser limit) and 4 GiB. +/// Less once RustGIS holds more than half the memory, never below the floor ([`crate::memory::planned`], #2431). fn csv_memory_budget() -> usize { let ceiling = usize::try_from(4u64 << 30).unwrap_or(usize::MAX); - crate::memory::scaled(crate::memory::physical(), 256 << 20, ceiling, 1) + crate::memory::planned(256 << 20, ceiling, 1) } /// Collects records for type inference, charging text and row/cell objects before copying. @@ -2943,7 +2976,9 @@ pub fn gather_shapefiles(files: Vec<(String, Vec)>) -> (Vec<(String, Vec } } // The zip must open again: within the read size and the zip reader's inflated total. - let limit = crate::zip::MAX_TOTAL.min(usize::try_from(max_bytes()).unwrap_or(usize::MAX)); + // Read once for the whole run: it reads what the computer has free (#2431). + let max = max_bytes(); + let limit = crate::zip::MAX_TOTAL.min(usize::try_from(max).unwrap_or(usize::MAX)); let (mut out, mut problems) = (Vec::new(), Vec::new()); for (file, parts) in files.into_iter().zip(zips) { out.extend(file); @@ -2955,8 +2990,8 @@ pub fn gather_shapefiles(files: Vec<(String, Vec)>) -> (Vec<(String, Vec let total = parts.iter().fold(0usize, |sum, (_, b)| sum.saturating_add(b.len())); // Said by the limit it passed: the size read into memory (which follows the computer's // memory), or the most a zip expands to. - if total as u64 > max_bytes() { - problems.push(format!("{shp}: its data files together: {}", too_large(total as u64))); + if total as u64 > max { + problems.push(format!("{shp}: its data files together: {}", too_large_said(total as u64, max))); continue; } if total > limit { @@ -2968,8 +3003,8 @@ pub fn gather_shapefiles(files: Vec<(String, Vec)>) -> (Vec<(String, Vec continue; } match crate::zip::write(&parts) { - Ok(zip) if zip.len() as u64 <= max_bytes() => out.push((zip_name, zip)), - Ok(zip) => problems.push(format!("{shp}: zipped together: {}", too_large(zip.len() as u64))), + Ok(zip) if zip.len() as u64 <= max => out.push((zip_name, zip)), + Ok(zip) => problems.push(format!("{shp}: zipped together: {}", too_large_said(zip.len() as u64, max))), Err(e) => problems.push(format!("{shp}: its data files couldn't be zipped together: {e}")), } } @@ -4768,6 +4803,34 @@ mod tests { use super::*; use std::io::Write; + /// A file refused because RustGIS holds much of the memory says so, with the limit when nothing + /// is held and what to do; refused at the full limit, or where the limit doesn't follow the + /// memory, it says what it said before (#2431). + #[test] + fn a_file_refused_while_memory_is_held_says_so() { + const GIB: u64 = 1 << 30; + if bytes_ceiling() == BYTES_FLOOR { + return; // A phone or a 32-bit build: the limit doesn't follow the memory. + } + let lowered = too_large_held(2 * GIB, GIB, Some(64 * GIB), 40 * GIB, None); + assert_eq!( + lowered, + "file is too large (2048 MiB; the most read into memory is 1024 MiB on this computer now, with RustGIS holding 40960 MiB, 2048 MiB otherwise): free memory by removing layers or tables you no longer need (save and reopen the project to let go of what Undo keeps of them) or closing other programs, then try again" + ); + let busy = too_large_held(GIB, 512 << 20, Some(64 * GIB), GIB, Some(5 * GIB)); + assert!(busy.contains("with RustGIS holding 1024 MiB and 5120 MiB free, 2048 MiB otherwise"), "{busy}"); + let full = too_large_held(3 * GIB, 2 * GIB, Some(64 * GIB), GIB, Some(60 * GIB)); + assert_eq!( + full, + "file is too large (3072 MiB; the most read into memory is 2048 MiB on this computer, a limit that follows its memory)" + ); + assert_eq!(too_large_held(3 * GIB, 2 * GIB, Some(64 * GIB), 0, None), full); + assert_eq!( + too_large_held(GIB, 256 << 20, None, 40 * GIB, None), + "file is too large (1024 MiB; the most read into memory is 256 MiB)" + ); + } + /// The size read into memory follows the computer's memory between its floor and ceiling, /// and stays at the floor where the memory isn't known (the browser) (#2408). #[test] @@ -4785,17 +4848,23 @@ mod tests { assert_eq!(max_bytes_for(Some(16 * GIB)), BYTES_FLOOR); assert_eq!(max_bytes_for(Some(1024 * GIB)), BYTES_FLOOR); } - // The test limit is the calling thread's, and comes back after it, nested too. - let real = max_bytes(); + // Holding more than half the memory lowers it, never below the floor (#2431). + if bytes_ceiling() > BYTES_FLOOR { + assert_eq!(max_bytes_within(crate::memory::share(Some(16 * GIB), 8 * GIB, None)), 512 << 20, "half held: unchanged"); + assert_eq!(max_bytes_within(crate::memory::share(Some(64 * GIB), 40 * GIB, None)), GIB); + assert_eq!(max_bytes_within(crate::memory::share(Some(16 * GIB), 12 * GIB, None)), BYTES_FLOOR); + } + // The test limit is the calling thread's, and comes back after it, nested too. The real one + // follows what is free now (#2431), so it is only compared with its floor. with_max_bytes(10, || { assert_eq!(max_bytes(), 10); with_max_bytes(20, || assert_eq!(max_bytes(), 20)); assert_eq!(max_bytes(), 10); - assert_eq!(std::thread::spawn(max_bytes).join().unwrap(), real); + assert!(std::thread::spawn(max_bytes).join().unwrap() >= BYTES_FLOOR); }); - assert_eq!(max_bytes(), real); - let said = too_large(3 << 20); - assert!(said.starts_with("file is too large (3 MiB;") && said.contains(&format!("{} MiB", real >> 20)), "{said}"); + assert!(max_bytes() >= BYTES_FLOOR); + let said = with_max_bytes(1 << 20, || too_large(3 << 20)); + assert!(said.starts_with("file is too large (3 MiB;") && said.contains("is 1 MiB"), "{said}"); } /// A file past the limit is refused before it is parsed, by each reader that takes it whole, diff --git a/crates/data/src/memory.rs b/crates/data/src/memory.rs index 4bdef413a7..f691c8e632 100644 --- a/crates/data/src/memory.rs +++ b/crates/data/src/memory.rs @@ -3,8 +3,11 @@ //! On the desktop a memory limit plans for a share of the physical memory ([`SHARE`]): never below //! the fixed value it had before (its floor, still the browser's limit), never above a ceiling. A //! container's memory limit counts, when it is lower. The memory is read once, at the first limit -//! asked for, so a session keeps the same limits; [`scaled`] takes it as an argument, so tests pass -//! fixed amounts. +//! asked for; [`scaled`] takes it as an argument, so tests pass fixed amounts. Most limits plan for +//! what is left once the process holds more than half the memory ([`planned`], #2431 fix 3), so +//! they can be lower later in a session, never below their floors. + +use std::sync::atomic::{AtomicU64, Ordering}; /// A limit plans for a quarter of the physical memory: room for the layers already held, the /// drawing, and a second job running at the same time. @@ -105,9 +108,117 @@ pub fn usable(memory: Option) -> Option { /// A limit of units costing `bytes` each: as many as [`SHARE`] of `memory` holds, within `floor` /// and `ceiling`; `floor` when the memory isn't known. pub fn scaled(memory: Option, floor: usize, ceiling: usize, bytes: u64) -> usize { - let Some(memory) = memory else { return floor }; - let n = memory / SHARE / bytes.max(1); - usize::try_from(n).unwrap_or(usize::MAX).clamp(floor, ceiling.max(floor)) + within(memory.map(|m| m / SHARE), floor, ceiling, bytes) +} + +/// A limit of units costing `bytes` each that plans for what is left (#2431 fix 3): as many as +/// [`share`] holds with what the process holds now ([`held`]) and what the computer has free now +/// ([`available`]), within `floor` and `ceiling`; `floor` when the memory isn't known. So a limit +/// asked for again later can be lower, never below its floor. +pub fn planned(floor: usize, ceiling: usize, bytes: u64) -> usize { + within(share(physical(), held(), available()), floor, ceiling, bytes) +} + +/// The memory a job plans for on a computer with `memory` bytes (`None`: not known) while `held` +/// bytes are held and `free` bytes are free (`None`: not known): the smallest of [`SHARE`] of it, +/// what is left of [`usable`] after what is held, and what is free less [`margin`]. With half the +/// memory or less held and enough free, it is the share. +pub fn share(memory: Option, held: u64, free: Option) -> Option { + let memory = memory?; + let left = usable(Some(memory)).unwrap_or(0).saturating_sub(held); + let free = free.map_or(u64::MAX, |free| free.saturating_sub(margin(memory))); + Some((memory / SHARE).min(left).min(free)) +} + +/// What is kept free beside a job or an edit's copy on a computer with `memory` bytes, for what +/// RustGIS's estimates don't count (drawing, the window, the allocator's slack): a twentieth of +/// the memory, from 256 MiB up to 2 GiB, as drawing doesn't grow with the memory. +pub fn margin(memory: u64) -> u64 { + (memory / 20).clamp(256 << 20, 2 << 30) +} + +/// The memory the computer has free now, read each time (#2431): what the system can give without +/// swapping, the cache it can drop counted as free, with RustGIS's own use already taken off. +/// It reads files or asks the system, so it is read once a job or an edit, never in a loop. +/// +/// `None`: +/// - in the browser, in a fuzzing build, or when it can't be read; +/// - when [`OVERRIDE`] is set, so a test or a reproduction gives the same limits whatever else +/// runs; +/// - in a container whose limit the limits follow: its usage counts the file cache the kernel only +/// drops near the limit, so it would read as nearly full after any large read; the limit itself +/// bounds RustGIS there. +/// +/// Memory RustGIS freed that its allocator keeps for reuse still counts as used here. On macOS +/// the system counts pages programs are using as available too, so this rarely bounds anything +/// there. +pub fn available() -> Option { + #[cfg(all(not(fuzzing), not(target_arch = "wasm32")))] + { + if source() != "computer" { + return None; + } + let mut s = sysinfo::System::new().ok()?; + s.refresh_memory_specifics(sysinfo::MemoryRefreshKind::nothing().with_ram()); + Some(s.available_memory()).filter(|m| *m > 0) + } + #[cfg(any(fuzzing, target_arch = "wasm32"))] + { + None + } +} + +/// As many units of `bytes` as `share` holds, within `floor` and `ceiling`. +fn within(share: Option, floor: usize, ceiling: usize, bytes: u64) -> usize { + let Some(share) = share else { return floor }; + usize::try_from(share / bytes.max(1)).unwrap_or(usize::MAX).clamp(floor, ceiling.max(floor)) +} + +/// What the process holds (#2431 fix 3): the sum of every [`Holding`]'s bytes, set by each +/// session for its layers, tables, rasters and Undo history, and for copies still being made. +static HELD: AtomicU64 = AtomicU64::new(0); + +/// The memory the process holds now: what every live [`Holding`] says. +pub fn held() -> u64 { + HELD.load(Ordering::Relaxed) +} + +/// One holder's part of [`held`]: what it sets is counted until it sets another amount or is +/// dropped. +#[derive(Debug, Default)] +pub struct Holding { + bytes: u64, +} + +impl Holding { + /// A part of [`held`] counting `bytes` until dropped. + pub fn of(bytes: u64) -> Self { + let mut holding = Self::default(); + holding.set(bytes); + holding + } + + /// Counts `bytes` in place of what this holding counted before. + pub fn set(&mut self, bytes: u64) { + let was = std::mem::replace(&mut self.bytes, bytes); + if bytes >= was { + HELD.fetch_add(bytes - was, Ordering::Relaxed); + } else { + HELD.fetch_sub(was - bytes, Ordering::Relaxed); + } + } + + /// What this holding counts. + pub fn bytes(&self) -> u64 { + self.bytes + } +} + +impl Drop for Holding { + fn drop(&mut self) { + // Only what `set` added is taken away, so the sum never goes below zero. + HELD.fetch_sub(self.bytes, Ordering::Relaxed); + } } #[cfg(test)] @@ -127,6 +238,50 @@ mod tests { assert_eq!(scaled(Some(16 * GIB), 100, 50, 8), 100, "a ceiling below the floor is the floor"); } + #[test] + fn a_job_plans_for_what_is_left_of_the_memory_once_half_is_held() { + assert_eq!(share(Some(16 * GIB), 0, None), Some(4 * GIB), "nothing held: the share"); + assert_eq!(share(Some(16 * GIB), 8 * GIB, None), Some(4 * GIB), "half held: still the share"); + assert_eq!(share(Some(16 * GIB), 10 * GIB, None), Some(2 * GIB), "what is left of three quarters"); + assert_eq!(share(Some(16 * GIB), 20 * GIB, None), Some(0), "more held than planned for: nothing"); + assert_eq!(share(None, 10 * GIB, Some(GIB)), None, "memory not known"); + // The limits keep their floors and ceilings. + assert_eq!(within(share(Some(16 * GIB), 10 * GIB, None), 100, 1 << 40, 8), 256 << 20); + assert_eq!(within(share(Some(16 * GIB), 12 * GIB, None), 100, 1 << 40, 8), 100, "never below the floor"); + assert_eq!(within(share(None, 12 * GIB, None), 100, 1 << 40, 8), 100); + assert_eq!(within(share(Some(1024 * GIB), 0, None), 100, 1_000, 8), 1_000); + } + + #[test] + fn a_job_plans_for_no_more_than_the_computer_has_free() { + // 8 GiB with little held, but other programs use most of it: what is free, less the margin + // (a twentieth of 8 GiB, above 256 MiB). + assert_eq!(share(Some(8 * GIB), GIB, Some(GIB)), Some(GIB - 8 * GIB / 20)); + assert_eq!(margin(GIB), 256 << 20, "at least 256 MiB"); + assert_eq!(share(Some(8 * GIB), GIB, Some(6 * GIB)), Some(2 * GIB), "plenty free: the share"); + assert_eq!(share(Some(8 * GIB), GIB, Some(100 << 20)), Some(0), "less free than the margin: nothing"); + assert_eq!(margin(16 * GIB), 16 * GIB / 20, "a twentieth"); + assert_eq!(margin(1024 * GIB), 2 * GIB, "at most 2 GiB"); + assert_eq!(within(share(Some(8 * GIB), 0, Some(0)), 100, 1 << 40, 8), 100, "never below the floor"); + } + + #[test] + fn holdings_add_up_and_take_their_part_back() { + // Only sessions (in the engine) hold, so nothing else here changes the sum; small amounts, + // so the limits other tests read at the same time don't move. + let base = held(); + let first = Holding::of(3); + let mut second = Holding::of(5); + assert_eq!(held(), base + 8); + second.set(1); + assert_eq!(held(), base + 4); + drop(first); + assert_eq!(held(), base + 1); + assert_eq!(second.bytes(), 1); + drop(second); + assert_eq!(held(), base); + } + #[test] fn usable_memory_leaves_a_share() { assert_eq!(usable(Some(16 * GIB)), Some(12 * GIB)); diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index 9ca23bb96c..87db826f40 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -3098,8 +3098,9 @@ pub const PAGED_FEATURES_CEILING: usize = 1_000_000; /// Most features read from a collection that comes in pages: on the desktop, as many as a quarter /// of the computer's memory holds at 20 KB each (about 100,000 for every 8 GB, the pages read /// included), from [`PAGED_FEATURES_FLOOR`] up to [`PAGED_FEATURES_CEILING`] (#1318). +/// Less once RustGIS holds more than half the memory, never below the floor ([`crate::memory::planned`], #2431). pub fn max_paged_features() -> usize { - crate::memory::scaled(crate::memory::physical(), PAGED_FEATURES_FLOOR, PAGED_FEATURES_CEILING, 20 << 10) + crate::memory::planned(PAGED_FEATURES_FLOOR, PAGED_FEATURES_CEILING, 20 << 10) } /// The most bytes of why a layer's protocol buffer pages couldn't be read that its note says. @@ -3123,8 +3124,9 @@ pub const DECODED_CEILING: usize = 3 << 30; /// Most memory, in bytes, an ArcGIS layer's protocol buffer pages may take once read: on the /// desktop a quarter of the computer's memory, from [`DECODED_FLOOR`] up to [`DECODED_CEILING`]. /// The download budget doesn't bound it: a vertex takes 1 to 3 bytes in a page and 16 read. +/// Less once RustGIS holds more than half the memory, never below the floor ([`crate::memory::planned`], #2431). pub fn max_decoded_bytes() -> usize { - crate::memory::scaled(crate::memory::physical(), DECODED_FLOOR, DECODED_CEILING, 1) + crate::memory::planned(DECODED_FLOOR, DECODED_CEILING, 1) } /// A feature collection page's JSON `next` link, resolved against the page's address. diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 2da1780de7..df23bc334a 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -91,8 +91,9 @@ pub const SAMPLES_CEILING: usize = 1_000_000_000; /// Most samples (pixels × bands) held in memory: on the desktop, as many as a quarter of the /// computer's memory holds at 8 bytes each (a sample takes 4, and reading briefly needs about /// twice that), from [`SAMPLES_FLOOR`] up to [`SAMPLES_CEILING`] (#1291 step 2, #1318). +/// Less once RustGIS holds more than half the memory, never below the floor ([`crate::memory::planned`], #2431). pub fn max_samples() -> usize { - crate::memory::scaled(crate::memory::physical(), SAMPLES_FLOOR, SAMPLES_CEILING, 8) + crate::memory::planned(SAMPLES_FLOOR, SAMPLES_CEILING, 8) } /// Largest ASCII grid file read (1 GiB). pub const MAX_ASCII_BYTES: u64 = 1 << 30; diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index e4942accd9..856ea85976 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -478,6 +478,12 @@ fn environments(s: &mut Session, p: &Value) -> CmdResult { "undoBytes": s.undo_memory.limit, // What the limits follow: the computer, a container's limit, or RUSTGIS_MEMORY_BYTES. "memorySource": rustgis_data::memory::source(), + // What the process holds (layers, tables, rasters, Undo history, copies being made), as of + // the last command: past half the memory, the limits that follow it plan for less (#2431). + "heldBytes": rustgis_data::memory::held(), + // What the computer has free now (null: not known, or RUSTGIS_MEMORY_BYTES is set): the + // limits plan for no more than this, less what is kept for drawing (#2431). + "freeBytes": rustgis_data::memory::available(), "projectBytes": crate::project::max_bytes(), "fileBytes": rustgis_data::io::max_bytes(), // The threads one piece of work uses now, and the cores they come from (#1562). @@ -827,6 +833,9 @@ pub(crate) fn ahead_on_copy(s: &Session, command: &'static str, p: &Value) -> su copy.view_size = view_size; copy.active_layer = active_layer; copy.opened = opened; + // The copy shares this session's rows, which this session already counts in what the + // process holds (#2431): it neither measures nor adds them again. + copy.undo_memory.memory = None; copy.sync_policy_generation(); copy.tools_ahead = Some(super::gp::Ahead::Recording(Vec::new())); copy.files_ahead = Some(super::gp::FilesAhead::Recording(Vec::new())); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 9893de7459..aaa23609eb 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1747,6 +1747,8 @@ impl Session { if res.is_ok() && !history_deferred && self.history_position() != history_before { self.trim_undo_memory(); } + // What the session holds now, for the limits that plan for what is left (#2431). + self.undo_memory.publish(&self.project, &self.undo, &self.redo); // And the coordinate systems that needed a missing datum grid, after every command. self.say_grid_notes(); // A plugin's command waiting for its fetches answers `pending` and runs again when they @@ -2007,7 +2009,13 @@ impl Session { copy, stamp: self.history_stamp(), })), - Err((held, usable)) => Err(format!( + Err(undo_memory::NoRoom { free: Some(free), .. }) => Err(format!( + "{label}: not enough memory to edit {name}: the edit copies its rows (about {}), and the computer has only about {} free now, with about {} kept for drawing and the window, as other programs (and memory RustGIS freed but keeps for reuse) use the rest. Close other programs, or remove layers or tables you no longer need, then try again.", + undo_memory::size_said(copy), + undo_memory::size_said(free), + undo_memory::size_said(self.undo_memory.memory.map_or(0, rustgis_data::memory::margin)), + )), + Err(undo_memory::NoRoom { held, usable, free: None }) => Err(format!( "{label}: not enough memory to edit {name}: the edit copies its rows (about {}), and the open layers and tables already hold about {} of the {} RustGIS plans to use on this computer. Remove layers or tables you no longer need, then try again.", undo_memory::size_said(copy), undo_memory::size_said(held), diff --git a/crates/engine/src/undo_memory.rs b/crates/engine/src/undo_memory.rs index f4be7e365c..235987f611 100644 --- a/crates/engine/src/undo_memory.rs +++ b/crates/engine/src/undo_memory.rs @@ -29,6 +29,11 @@ pub(crate) struct Budget { room_said: bool, // The copies of background edits not landed yet ([`Budget::reserve`]). in_flight: Arc, + // This session's part of what the process holds ([`Budget::publish`]). + holding: rustgis_data::memory::Holding, + /// What the computer has free now ([`rustgis_data::memory::available`]; tests pass fixed + /// amounts). `None`: not known, and only [`Self::memory`] bounds an edit's copy. + pub(crate) free: fn() -> Option, // Keeping the weak key prevents address reuse while its estimate is cached, without keeping // the rows themselves alive. Copy-on-write gives changed rows a different key. estimates: HashMap, @@ -43,6 +48,9 @@ impl Default for Budget { memory: rustgis_data::memory::physical(), room_said: false, in_flight: Arc::default(), + holding: rustgis_data::memory::Holding::default(), + // Unit tests here don't depend on what else runs; they set it where they test it. + free: if cfg!(test) { || None } else { rustgis_data::memory::available }, estimates: HashMap::new(), } } @@ -104,30 +112,59 @@ impl Budget { (bytes as u64).saturating_add(raster_bytes(projects)) } + /// Says what the session holds ([`Self::held`]) to the process-wide figure the memory limits + /// plan with ([`rustgis_data::memory::planned`], #2431 fix 3), after each command. Copies still + /// being made count through their [`Reservation`]s. Nothing is measured where the memory isn't + /// known (the browser), as no limit follows it there. + pub(crate) fn publish(&mut self, live: &Project, undo: &[Step], redo: &[Step]) { + if self.memory.is_some() { + let held = self.held(live, undo, redo); + self.holding.set(held); + // Estimates of rows nothing holds any more go, as `trim` does, which runs only when the + // history moves: a command that replaces rows without a step would otherwise leave them. + self.estimates.retain(|_, (key, _)| key.strong_count() > 0); + } + } + /// Makes room for an edit that copies `copy` bytes of rows (#2431 fix 3): when what the session /// holds, the copies of edits still running in the background and this copy pass the memory - /// it plans to use ([`rustgis_data::memory::usable`]), history is set aside until they fit: - /// Redo first, farthest first, as the edit clears it anyway, then Undo, oldest first. What is - /// set aside is freed just before the edit copies, or given back if it never does - /// ([`Session::put_back`](crate::Session)), and counted as held until then. `Err` gives what is held and the memory planned - /// for, with the history left as it is, when the copy wouldn't fit even with the history gone. + /// it plans to use ([`rustgis_data::memory::usable`]), or the copy passes what the computer has + /// free now less [`rustgis_data::memory::margin`] (other programs use the rest), history is set + /// aside until they fit. What is set aside counts as free for the copy, before the margin is + /// taken off: its memory goes back to RustGIS's allocator, which the copy then reuses, not to + /// the system. Copies of other edits still running count against what is free only once they + /// have allocated it. Redo is set aside first, farthest first, as the edit clears it anyway, + /// then Undo, oldest first. What is set aside is freed just before the edit copies, or given + /// back if it never does ([`Session::put_back`](crate::Session)), and counted as held until + /// then. `Err` gives what is held and the memory planned for, with the history left as it is, + /// when the copy wouldn't fit even with the history gone. pub(crate) fn make_room( &mut self, live: &Project, undo: &mut Vec, redo: &mut Vec, copy: u64, - ) -> Result, (u64, u64)> { - let Some(usable) = rustgis_data::memory::usable(self.memory) else { return Ok(None) }; + ) -> Result, NoRoom> { + let Some(memory) = self.memory else { return Ok(None) }; + let Some(usable) = rustgis_data::memory::usable(Some(memory)) else { return Ok(None) }; let running = self.in_flight.load(Ordering::Relaxed); - let fits = |held: u64| held.saturating_add(running).saturating_add(copy) <= usable; + let free = (self.free)(); + let margin = rustgis_data::memory::margin(memory); let before = self.held(live, undo, redo); + let planned = |held: u64| held.saturating_add(running).saturating_add(copy) <= usable; + // What is set aside is added to what is free before the margin is taken off, so it + // doesn't make up for less free than the margin. + let fits = |held: u64| { + planned(held) && free.is_none_or(|free| copy <= free.saturating_add(before.saturating_sub(held)).saturating_sub(margin)) + }; if fits(before) { return Ok(None); } let open = self.held(live, &[], &[]); if !fits(open) { - return Err((open.saturating_add(running), usable)); + // Said by what refuses it: the memory RustGIS plans to use, or what is free now. + let free = if planned(open) { free } else { None }; + return Err(NoRoom { held: open.saturating_add(running), usable, free }); } let mut aside = Aside::default(); while !fits(self.held(live, undo, redo)) { @@ -153,7 +190,7 @@ impl Budget { /// background makes, until it lands (and the project holds it) or is abandoned. pub(crate) fn reserve(&self, bytes: u64) -> Reservation { self.in_flight.fetch_add(bytes, Ordering::Relaxed); - Reservation { in_flight: Arc::clone(&self.in_flight), bytes } + Reservation { in_flight: Arc::clone(&self.in_flight), bytes, _held: rustgis_data::memory::Holding::of(bytes) } } /// The estimated size of `features`' rows: what the first write to them copies while a @@ -205,10 +242,22 @@ pub(crate) fn free_on_copy(slot: &AsideSlot) -> Box { Box::new(move || drop(slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take())) } +/// Why an edit's copy can't fit even with no history ([`Budget::make_room`]): what RustGIS holds +/// (the copies still being made included) and the memory it plans to use, and what the computer +/// has free when that is what refuses it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct NoRoom { + pub(crate) held: u64, + pub(crate) usable: u64, + pub(crate) free: Option, +} + /// A background edit's copy, counted as held while it runs ([`Budget::reserve`]). pub struct Reservation { in_flight: Arc, bytes: u64, + // Counted in what the process holds too, for the limits (#2431), until dropped. + _held: rustgis_data::memory::Holding, } impl Drop for Reservation { @@ -316,6 +365,9 @@ mod tests { data.push(Some(rustgis_data::Geometry::Point(rustgis_geom::Coord::new(0.0, 0.0))), vec![Value::Text("a".repeat(text_len))]); session.map_mut().add_layer(rustgis_map::Layer::new(0, data)); session.undo_memory.limit = 2 << 10; + // What the computer has free is left out unless a test sets it, so tests don't depend on + // what else runs. + session.undo_memory.free = || None; session } @@ -516,6 +568,7 @@ mod tests { session.run("layer.addDataText", &json!({"fileName": "calc.csv", "text": text})).unwrap(); session.undo_memory.limit = 1 << 30; session.undo_memory.memory = None; + session.undo_memory.free = || None; for t in ["b", "c"] { session.run("edit.setValue", &json!({"table": "calc", "row": 0, "field": "t", "value": t.repeat(4096)})).unwrap(); } @@ -732,6 +785,66 @@ mod tests { assert!(!session.notices_since(mark).iter().any(|n| n.text.contains("make room"))); } + /// After each command a session says what it holds to the process-wide figure the memory + /// limits plan with, and takes it back when dropped; a background copy counts until it is + /// dropped; where the memory isn't known nothing is measured (#2431). + #[test] + fn a_session_says_what_it_holds_for_the_limits() { + let mut session = session(4096); + session.undo_memory.memory = Some(1 << 40); + edit(&mut session, "b"); + let held = session.undo_memory.held(&session.project, &session.undo, &session.redo); + assert!(held > 4096, "{held}"); + assert_eq!(session.undo_memory.holding.bytes(), held); + let copy = session.undo_memory.reserve(1 << 20); + assert_eq!(copy._held.bytes(), 1 << 20, "a copy being made is counted"); + drop(copy); + // Unknown memory: what was said stays as it was, and nothing is measured. + let mut unknown = self::session(4096); + unknown.undo_memory.memory = None; + edit(&mut unknown, "c"); + assert_eq!(unknown.undo_memory.holding.bytes(), 0); + } + + /// The computer's free memory bounds an edit's copy too, when other programs use most of it + /// (#2431): history set aside counts as free for the copy, as the copy reuses its memory; an + /// edit whose copy doesn't fit in what is free even then is refused, saying so. + #[test] + fn an_edit_fits_in_what_the_computer_has_free() { + let mut session = session(4096); + session.undo_memory.limit = 1 << 30; + session.undo_memory.memory = None; + for text in ["b", "c"] { + edit(&mut session, &text.repeat(4096)); + } + // Plenty planned for (1 TiB), but only the margin and a little free. + session.undo_memory.memory = Some(1 << 40); + session.undo_memory.free = || Some(rustgis_data::memory::margin(1 << 40) + 64); + let mark = session.notice_mark(); + edit(&mut session, "d"); + assert!(session.undo_depth() < 3, "older steps were dropped for the copy"); + assert!(session.notices_since(mark).iter().any(|n| n.text.contains("make room"))); + // Nothing free beyond the margin and no history to set aside: refused, saying why. + session.clear_history(); + session.undo_memory.free = || Some(rustgis_data::memory::margin(1 << 40)); + let err = session.run("edit.setValue", &json!({"layer": "rows", "row": 0, "field": "text", "value": "e"})).unwrap_err(); + assert!(err.contains("the computer has only about") && err.contains("as other programs"), "{err}"); + assert_eq!(value(&session), &Value::Text("d".into()), "nothing changed"); + // Less free than the margin: steps set aside make room only beyond it, so an edit that + // fits in them alone is refused, with the history left as it is. + for text in ["f", "g"] { + session.undo_memory.memory = None; + edit(&mut session, &text.repeat(4096)); + } + session.undo_memory.memory = Some(1 << 40); + session.undo_memory.free = || Some(rustgis_data::memory::margin(1 << 40) - (1 << 20)); + let depth = session.undo_depth(); + let err = session.run("edit.setValue", &json!({"layer": "rows", "row": 0, "field": "text", "value": "h"})).unwrap_err(); + assert!(err.contains("the computer has only about"), "{err}"); + assert_eq!(session.undo_depth(), depth, "the history is left as it is"); + assert_eq!(value(&session), &Value::Text("g".repeat(4096)), "nothing changed"); + } + /// Undo and Redo copy no rows and aren't checked (they are registered as `.view()`, so they /// don't count as edits): they run when even one copy of the active layer doesn't fit, as the /// way back from an edit (#2431). diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 4a9f4b5812..b998ad5342 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1558,6 +1558,28 @@ starting RustGIS: it replaces the memory read from the computer and any containe command line says so on every run. It isn't a way to go faster: a value above the computer's memory raises every limit past what it has, and a large job can then run out of memory. +The limits below other than `threadScratchBytes`, `undoBytes` and `projectBytes` plan for less +when memory is short, never below their floors. They plan for the smallest of three figures: +- a quarter of the memory; +- what is left of three quarters of it after what RustGIS holds, which matters once it holds more + than half: on a 16 GiB computer holding 10 GiB, 2 GiB instead of 4 GiB; +- what the computer has free now, less what is kept for drawing and the window (a twentieth of the + memory, from 256 MiB up to 2 GiB), which matters when other programs use most of it. + +What is held counts the open layers, tables and rasters, what only Undo and Redo keep and the +copies of edits running in the background, in every project open in the process, as of the last +command; `limits.heldBytes` gives it, and `limits.freeBytes` what is free. What is free is read each +time, so the same job can pass now and be refused a minute later when another program has taken +memory meanwhile. It isn't read when `RUSTGIS_MEMORY_BYTES` is set (`freeBytes` is then `null`), so +tests give the same limits whatever else runs, nor in a container whose memory limit RustGIS +follows (the container's own count includes file cache, so the limit bounds it instead). On macOS +the system counts memory other programs are using as available too, so this figure rarely lowers +anything there. A file refused for its size says what is held and +free, and the limit otherwise. Removing layers or tables you no longer need raises the limits once +Undo no longer keeps them: saving and reopening the project lets go of the Undo history. Reading a +file again, or opening another project while a large one is open, plans against the lowered limits +too, so a file that opened earlier in the session can be refused later. + | Limit | Floor (web app value in brackets) | Desktop: a quarter of memory at | Ceiling | |---|---|---|---| | `rasterSamples`: samples a raster read holds (cells times bands) | 120 million (32 million in the web app) | 8 bytes a sample | 1 billion | @@ -1578,7 +1600,8 @@ happens in a project, a message says so. Edits can still create a temporary full Before an edit of a layer's or table's features or fields, RustGIS checks that this copy fits beside what it already holds: the open layers, tables and rasters, what only Undo and Redo keep, and the copies of edits still running in the background, all within three quarters of the -computer's memory. When it doesn't fit, Redo steps are set aside first (the edit clears them +computer's memory, and that the copy fits in what the computer has free now, less what is kept for +drawing (Undo steps set aside count as free for it, as the copy reuses their memory). When it doesn't fit, Redo steps are set aside first (the edit clears them anyway), then the oldest Undo steps. They are freed only once the edit starts copying; an edit that fails before that, or is cancelled before it starts copying, gives them back, unless the project was changed while it ran in the background. One that fails after it started copying has @@ -1586,7 +1609,7 @@ used them, as a finished edit would have. A message says when steps are freed to first time in a project, and each time steps set aside for a background edit are freed because the Undo history changed while it ran. Undo and Redo copy nothing and aren't checked. An edit that wouldn't fit even with no Undo history is refused before anything changes, and the message gives -the size of the copy and what is held. An edit the desktop runs in the background is checked when it starts; one that needs Undo +the size of the copy and what is held, or what is free when other programs use the memory. An edit the desktop runs in the background is checked when it starts; one that needs Undo steps set aside while another such edit is still running is refused, to run again once that one has finished. Edits made by a script, model, task or plugin aren't checked, nor is Paste Special (it makes a layer of its own) or