From b79431dd0d45c259ece0dc6a53c821eff87a902f Mon Sep 17 00:00:00 2001 From: strebdom Date: Thu, 19 Nov 2026 09:46:07 +0100 Subject: [PATCH 1/7] fix(engine): check that an edit's copy fits beside what the session holds (#2431) --- crates/data/src/memory.rs | 15 ++ crates/engine/src/lib.rs | 47 +++++ crates/engine/src/policy/dispatch.rs | 11 +- crates/engine/src/undo_memory.rs | 275 +++++++++++++++++++++++++-- docs/user-guide/analysis.md | 10 + 5 files changed, 342 insertions(+), 16 deletions(-) diff --git a/crates/data/src/memory.rs b/crates/data/src/memory.rs index f9e10c5a06..6627162b42 100644 --- a/crates/data/src/memory.rs +++ b/crates/data/src/memory.rs @@ -60,6 +60,14 @@ pub fn undo_history() -> usize { scaled(physical(), 256 << 20, usize::try_from(4_u64 << 30).unwrap_or(usize::MAX), 1) } +/// The memory RustGIS plans to hold on a computer with `memory` bytes (`None`: not known), what the +/// session's layers, rasters and Undo history may take together before an edit that copies a +/// layer is refused (#2431 fix 3): all of it but [`SHARE`], which is left for drawing, the window +/// and a job running at the same time. +pub fn usable(memory: Option) -> Option { + memory.map(|m| m.saturating_sub(m / SHARE)) +} + /// 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 { @@ -85,6 +93,13 @@ mod tests { assert_eq!(scaled(Some(16 * GIB), 100, 50, 8), 100, "a ceiling below the floor is the floor"); } + #[test] + fn usable_memory_leaves_a_share() { + assert_eq!(usable(Some(16 * GIB)), Some(12 * GIB)); + assert_eq!(usable(None), None); + assert_eq!(usable(Some(3)), Some(3), "a share below a byte leaves it all"); + } + #[cfg(not(target_arch = "wasm32"))] #[test] fn the_memory_is_read_once_and_stays() { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ef367863a1..56e92ea2d9 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1818,6 +1818,11 @@ impl Session { return Err(e); } let op = self.authorize(id, params)?; + // After authorizing: an edit refused there (an Assistant call not approved) costs no history. + if let Some(e) = self.room_for_edit(id, mutates, label, named.or(active), table) { + self.notify(e.clone(), true); + return Err(e); + } self.merge = merge; let res = self.invoke(op, policy::Txn::Own); if id == "layer.addDownload" @@ -1916,6 +1921,48 @@ impl Session { Some(streamed_refusal(label, &l.name)) } + /// Makes room in memory for an edit of a layer's or table's features or fields (#2431 fix 3): + /// its first write copies the rows the Undo snapshot shares, so the copy has to fit beside what + /// the session holds. Older history is dropped first, said once a project; an edit that + /// wouldn't fit even without history is refused before anything changes. A command run by + /// another (a script's, a task's step) isn't checked: its history belongs to the command + /// running it, which may still roll back. A table edit the desktop runs in the background is + /// checked before its work starts (`capture_read`). An edit of several layers is + /// measured by the one it names, and memory outside the project (results, caches, the + /// clipboard) is left to the quarter [`rustgis_data::memory::usable`] keeps free. + pub(crate) fn room_for_edit(&mut self, id: &str, mutates: bool, label: &str, layer: Option, table: Option) -> Option { + // Paste Special makes a layer of its own: it copies none of the active one's rows. + if !(mutates && edits_features(id)) || id == "edit.pasteSpecial" || self.depth > 0 { + return None; + } + let (name, features) = match table { + Some(t) => self.project.table(t).map(|t| (t.dataset.name.clone(), t.dataset.features.clone()))?, + None => layer + .and_then(|l| self.map().layer(l)) + .filter(|l| !l.is_streamed()) + .map(|l| (l.name.clone(), l.dataset.features.clone()))?, + }; + let copy = self.undo_memory.rows_bytes(&features); + drop(features); + match self.undo_memory.make_room(&self.project, &mut self.undo, &mut self.redo, copy) { + Ok(None) => None, + Ok(Some(dropped)) => { + let template = "Memory is nearly full: older Undo steps are dropped to make room for edits ({count} before editing {layer}). An edit that still doesn't fit is refused."; + self.notify_text( + notice_text::NoticeText::format(template, [("count", dropped.to_string().into()), ("layer", name.into())]), + false, + ); + None + } + Err((held, usable)) => Some(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), + undo_memory::size_said(usable), + )), + } + } + /// Runs `f` as the command `label`: when it `mutates`, the project is snapshotted for undo /// and restored if `f` fails or panics. pub(crate) fn guarded(&mut self, label: &'static str, mutates: bool, f: impl FnOnce(&mut Session) -> CmdResult) -> CmdResult { diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index 41653e5a4e..98977d45dc 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -189,7 +189,7 @@ impl Session { params.insert("layer".into(), json!(id)); } let mut op = self.authorize(command, &Value::Object(params))?; - self.check_read_command(&op)?; + self.check_read_command(&op, true)?; let copy_command = matches!(command, "model.run" | "script.run") && self.policy_user(); if copy_command { // A model's or script's native copy may read through several tools. Bind the original @@ -231,7 +231,7 @@ impl Session { if !owner.native_tool_owner() && *op.node != s.command_node(command, ¶ms)? { return Err("the read command changed since it was authorized".into()); } - s.check_read_command(&op)?; + s.check_read_command(&op, false)?; s.read_ahead = ready; let result = s.invoke(op, Txn::Own); if result.is_ok() @@ -251,7 +251,9 @@ impl Session { } } /// Preserves ordinary command conditions for the admitted read's layer or table selector. - fn check_read_command(&mut self, op: &Authorized) -> Result<(), String> { + /// `before_work`: the read is about to start, and an edit's copy is checked against memory + /// then (#2431), before its worker makes it; landing doesn't check again. + fn check_read_command(&mut self, op: &Authorized, before_work: bool) -> Result<(), String> { let CommandOp::Registered { spec, params } = op.op() else { return Err("not a registered read command".into()) }; let named = self.layer_id(params).ok(); let active = self.active_layer; @@ -266,6 +268,9 @@ impl Session { if let Some(why) = self.streamed_edit(spec.id, spec.mutates, spec.label, if table.is_some() { None } else { named.or(active) }) { return Err(why); } + if before_work && let Some(why) = self.room_for_edit(spec.id, spec.mutates, spec.label, named.or(active), table) { + return Err(why); + } Ok(()) } /// Admits an export before its preparation reads any input or creates off-thread work. diff --git a/crates/engine/src/undo_memory.rs b/crates/engine/src/undo_memory.rs index a414912ca4..872f6403ee 100644 --- a/crates/engine/src/undo_memory.rs +++ b/crates/engine/src/undo_memory.rs @@ -1,6 +1,6 @@ //! Budget for feature allocations retained by undo and redo snapshots. use crate::{Project, Step, notice_text::NoticeText}; -use rustgis_data::{Feature, Features, source::memory::feature_bytes}; +use rustgis_data::{Coord, Feature, Features, Geometry, Value}; use std::{ collections::{HashMap, HashSet}, mem::size_of, @@ -19,6 +19,11 @@ pub(crate) struct Budget { // Dropping steps is said once a project: past the budget every further edit drops one, and // a message each time would only repeat the first. Another project says it again. said: bool, + /// The computer's memory the check before an edit plans with ([`rustgis_data::memory::physical`]; + /// tests pass fixed amounts). `None`: not known, as in the browser, and nothing is checked. + pub(crate) memory: Option, + // Dropping steps to make room for an edit is said once a project, as `said` is. + room_said: bool, // 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, @@ -26,7 +31,14 @@ pub(crate) struct Budget { impl Default for Budget { fn default() -> Self { - Self { limit: rustgis_data::memory::undo_history(), deferred: false, said: false, estimates: HashMap::new() } + Self { + limit: rustgis_data::memory::undo_history(), + deferred: false, + said: false, + memory: rustgis_data::memory::physical(), + room_said: false, + estimates: HashMap::new(), + } } } @@ -34,6 +46,7 @@ impl Budget { pub(crate) fn clear(&mut self) { self.estimates.clear(); self.said = false; + self.room_said = false; } /// Keep a contiguous history around the current state. Count a shared allocation only at its @@ -68,14 +81,62 @@ impl Budget { return None; } let template = "Undo history is limited by memory: older steps are dropped as you edit, keeping Undo and Redo to about {limit}. The newest step is always kept."; - let limit = if self.limit >= 1 << 30 { - format!("{:.1} GiB", self.limit as f64 / (1_u64 << 30) as f64) - } else if self.limit >= 1 << 20 { - format!("{:.1} MiB", self.limit as f64 / (1_u64 << 20) as f64) - } else { - format!("{} B", self.limit) - }; - Some(NoticeText::format(template, [("limit", limit.into())])) + Some(NoticeText::format(template, [("limit", size_said(self.limit as u64).into())])) + } + + /// What the session holds (#2431 fix 3): the rows of the open project and those only Undo and + /// Redo keep, each allocation counted once however many snapshots share it, and the pixels + /// and embedded files of their rasters likewise. Rows are estimated as for the budget, from a + /// cache, so this visits allocations, not rows. + pub(crate) fn held(&mut self, live: &Project, undo: &[Step], redo: &[Step]) -> u64 { + let mut seen = HashSet::new(); + let mut bytes = self.private_bytes(&allocations(live), &mut seen); + for step in undo.iter().chain(redo) { + bytes = bytes.saturating_add(self.private_bytes(&step.8, &mut seen)); + } + let projects = std::iter::once(live).chain(undo.iter().chain(redo).map(|step| &step.0)); + (bytes as u64).saturating_add(raster_bytes(projects)) + } + + /// Makes room for an edit that copies `copy` bytes of rows (#2431 fix 3): when what the session + /// holds and the copy pass the memory it plans to use ([`rustgis_data::memory::usable`]), + /// history goes until they fit: Redo first, farthest first, as the edit clears it anyway, then + /// Undo, oldest first. The history is left as it is, and `Err` gives what is held and the memory + /// planned for, 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) }; + let fits = |held: u64| held.saturating_add(copy) <= usable; + if fits(self.held(live, undo, redo)) { + return Ok(None); + } + let open = self.held(live, &[], &[]); + if !fits(open) { + return Err((open, usable)); + } + let mut dropped = 0; + while !fits(self.held(live, undo, redo)) { + if !redo.is_empty() { + redo.remove(0); + } else if undo.is_empty() { + break; + } else { + undo.remove(0); + } + dropped += 1; + } + Ok((dropped > 0 && !std::mem::replace(&mut self.room_said, true)).then_some(dropped)) + } + + /// The estimated size of `features`' rows: what the first write to them copies while a + /// snapshot shares them. + pub(crate) fn rows_bytes(&mut self, features: &Features) -> u64 { + self.private_bytes(&vec![features.allocation_key()], &mut HashSet::new()) as u64 } /// Measure only history-owned allocations with no cached estimate. The other work visits @@ -95,6 +156,37 @@ impl Budget { } } +/// The pixels and embedded files of the rasters in `projects`, each shared allocation once. +fn raster_bytes<'a>(projects: impl Iterator) -> u64 { + let mut seen = HashSet::new(); + let mut bytes = 0u64; + let rasters = projects + .flat_map(|project| project.maps.iter().chain(project.offline_areas.iter().map(|area| &area.data))) + .flat_map(|map| map.layers.iter()) + .filter_map(|layer| layer.raster.as_ref()); + for raster in rasters { + if let Some(data) = raster.data.as_ref().filter(|data| seen.insert(std::sync::Arc::as_ptr(data) as usize)) { + let pixels = data.bands.iter().fold(0usize, |n, band| n.saturating_add(band.data.capacity().saturating_mul(size_of::()))); + bytes = bytes.saturating_add(pixels as u64); + } + if let Some(file) = raster.embedded.as_ref().filter(|file| seen.insert(std::sync::Arc::as_ptr(file) as usize)) { + bytes = bytes.saturating_add(file.capacity() as u64); + } + } + bytes +} + +/// A size as notices say it: GiB or MiB to one decimal, or bytes. +pub(crate) fn size_said(bytes: u64) -> String { + if bytes >= 1 << 30 { + format!("{:.1} GiB", bytes as f64 / (1_u64 << 30) as f64) + } else if bytes >= 1 << 20 { + format!("{:.1} MiB", bytes as f64 / (1_u64 << 20) as f64) + } else { + format!("{bytes} B") + } +} + /// Records identities once when the snapshot enters history or has a reservation removed. pub(crate) fn allocations(project: &Project) -> Allocations { rows(project).map(Features::allocation_key).collect() @@ -111,12 +203,43 @@ fn rows(project: &Project) -> impl Iterator { } /// Count the row vector's capacity and extrapolate the heap storage of up to 64 evenly spaced -/// rows, using the same attribute, string and geometry accounting as streamed view windows. +/// rows, each heap allocation as a block of the system allocator ([`block`]). fn estimate(features: &Vec) -> usize { let stride = features.len().div_ceil(64).max(1); let (sum, count) = - features.iter().step_by(stride).fold((0usize, 0usize), |(sum, count), row| (sum.saturating_add(feature_bytes(row)), count + 1)); - features.capacity().saturating_mul(size_of::()).saturating_add(sum.div_ceil(count.max(1)).saturating_mul(features.len())) + features.iter().step_by(stride).fold((0usize, 0usize), |(sum, count), row| (sum.saturating_add(row_bytes(row)), count + 1)); + block(features.capacity().saturating_mul(size_of::())) + .saturating_add(sum.div_ceil(count.max(1)).saturating_mul(features.len())) +} + +/// A row's heap storage, block by block: its attribute list, each text, and its geometry's parts. +fn row_bytes(row: &Feature) -> usize { + let attrs = row.attrs.iter().fold(block(row.attrs.capacity().saturating_mul(size_of::())), |n, v| { + n.saturating_add(match v { + Value::Text(s) => block(s.capacity()), + _ => 0, + }) + }); + let ring = |r: &Vec| block(r.capacity().saturating_mul(size_of::())); + let parts = + |p: &Vec>| p.iter().fold(block(p.capacity().saturating_mul(size_of::>())), |n, r| n.saturating_add(ring(r))); + let geometry = match &row.geometry { + None | Some(Geometry::Point(_)) => 0, + Some(Geometry::MultiPoint(p)) => ring(p), + Some(Geometry::Line(p)) => parts(p), + Some(Geometry::Polygon(p)) => { + p.iter().fold(block(p.capacity().saturating_mul(size_of::>>())), |n, r| n.saturating_add(parts(r))) + } + }; + attrs.saturating_add(geometry) +} + +/// What an allocation of `bytes` takes from the system allocator: a header and 16-byte rounding, +/// 32 bytes at the least (glibc's malloc; others are alike). It is most of a short text's cost: +/// a layer of short texts measured about 0.74 GB a copy where its bytes alone came to 0.54 +/// (#2431). Nothing is allocated for none. +fn block(bytes: usize) -> usize { + if bytes == 0 { 0 } else { bytes.saturating_add(8 + 15).max(32) & !15 } } #[cfg(test)] @@ -217,4 +340,130 @@ mod tests { assert_eq!(value(&session), &Value::Text(b)); assert!(!session.can_redo(), "only the nearer redo fits"); } + + /// Memory planned so the open rows and one copy of them fit with `spare` bytes over, + /// without the history. + fn room_for_one_copy(session: &mut Session, spare: u64) -> u64 { + let rows = session.map().layer_by_name("rows").unwrap().dataset.features.clone(); + let copy = session.undo_memory.rows_bytes(&rows); + let open = session.undo_memory.held(&session.project, &[], &[]); + let target = open + copy + spare; + // `usable` leaves a quarter: the smallest memory whose three quarters reach the target. + let memory = (target * 4).div_ceil(3) + 4; + assert!(rustgis_data::memory::usable(Some(memory)).unwrap() >= target); + memory + } + + #[test] + fn an_edit_that_fits_beside_the_history_drops_nothing() { + let mut session = session(4096); + session.undo_memory.limit = 1 << 30; + session.undo_memory.memory = Some(1 << 40); + let mark = session.notice_mark(); + edit(&mut session, "b"); + edit(&mut session, "c"); + assert_eq!(session.undo_depth(), 2); + assert!(session.notices_since(mark).is_empty()); + } + + #[test] + fn older_steps_make_room_for_an_edit_and_that_is_said_once() { + let mut session = session(4096); + session.undo_memory.limit = 1 << 30; + session.undo_memory.memory = None; + let (b, c) = ("b".repeat(4096), "c".repeat(4096)); + edit(&mut session, &b); + edit(&mut session, &c); + assert_eq!(session.undo_depth(), 2); + let memory = room_for_one_copy(&mut session, 64); + session.undo_memory.memory = Some(memory); + let mark = session.notice_mark(); + edit(&mut session, "d"); + let notices = session.notices_since(mark); + assert_eq!(notices.len(), 1, "{notices:?}"); + assert!(notices[0].text.contains("dropped to make room for edits (2 before editing rows)"), "{notices:?}"); + assert_eq!(value(&session), &Value::Text("d".into())); + // The step the edit made undoes it. + session.run("edit.undo", &json!({})).unwrap(); + assert_eq!(value(&session), &Value::Text(c.clone())); + session.run("edit.redo", &json!({})).unwrap(); + + // Dropping again says nothing more in the same project. + edit(&mut session, &b); + let mark = session.notice_mark(); + session.undo_memory.memory = Some(room_for_one_copy(&mut session, 64)); + edit(&mut session, &c); + assert!(session.notices_since(mark).is_empty()); + assert_eq!(session.undo_depth(), 1, "the older steps went"); + assert_eq!(value(&session), &Value::Text(c)); + } + + #[test] + fn an_edit_that_cannot_fit_is_refused_and_changes_nothing() { + let mut session = session(4096); + session.undo_memory.limit = 1 << 30; + session.undo_memory.memory = None; + edit(&mut session, "b"); + let state = session.state; + session.undo_memory.memory = Some(4); + let mark = session.notice_mark(); + let err = session.run("edit.setValue", &json!({"layer": "rows", "row": 0, "field": "text", "value": "c"})).unwrap_err(); + assert!(err.contains("not enough memory to edit rows: the edit copies its rows"), "{err}"); + assert_eq!(value(&session), &Value::Text("b".into())); + assert_eq!(session.undo_depth(), 1, "the history is kept"); + assert_eq!(session.state, state); + let notices = session.notices_since(mark); + assert_eq!(notices.len(), 1, "{notices:?}"); + // Commands that don't edit features still run. + session.run("layer.visibility", &json!({"layer": "rows", "visible": false})).unwrap(); + // Unknown memory (the browser) checks nothing. + session.undo_memory.memory = None; + edit(&mut session, "c"); + assert_eq!(value(&session), &Value::Text("c".into())); + } + + #[test] + fn redo_goes_before_undo_to_make_room() { + let mut session = session(4096); + session.undo_memory.limit = 1 << 30; + session.undo_memory.memory = None; + for text in ["b", "c", "d"] { + edit(&mut session, &text.repeat(4096)); + } + session.run("edit.undo", &json!({})).unwrap(); + assert_eq!((session.undo_depth(), session.can_redo()), (2, true)); + // Room for the open rows, the Undo steps and one copy: only Redo has to go. + let rows = session.map().layer_by_name("rows").unwrap().dataset.features.clone(); + let copy = session.undo_memory.rows_bytes(&rows); + drop(rows); + let held = session.undo_memory.held(&session.project, &session.undo, &[]); + session.undo_memory.memory = Some(((held + copy + 64) * 4).div_ceil(3) + 4); + let mark = session.notice_mark(); + edit(&mut session, "e"); + let notices = session.notices_since(mark); + assert!(notices.iter().any(|n| n.text.contains("(1 before editing rows)")), "{notices:?}"); + assert_eq!(session.undo_depth(), 3, "every Undo step is kept"); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_table_edit_run_in_the_background_is_checked_before_its_work() { + let mut session = Session::new(crate::Project::default()); + session.run("layer.addDataText", &json!({"fileName": "calc.csv", "text": "n\n1\n2\n"})).unwrap(); + session.undo_memory.memory = Some(4); + let p = json!({"table": "calc", "row": 0, "field": "n", "value": 3}); + let err = crate::cmd::reads::read_ahead(&mut session, "edit.setValue", &p).err().unwrap(); + assert!(err.contains("not enough memory to edit calc"), "{err}"); + session.undo_memory.memory = Some(1 << 40); + assert!(crate::cmd::reads::read_ahead(&mut session, "edit.setValue", &p).is_ok()); + } + + #[test] + fn paste_special_is_not_measured_by_the_active_layer() { + let mut session = session(4096); + session.undo_memory.memory = Some(4); + let id = Some(session.map().layer_by_name("rows").unwrap().id); + assert!(session.room_for_edit("edit.pasteSpecial", true, "Paste Special", id, None).is_none()); + assert!(session.room_for_edit("edit.paste", true, "Paste", id, None).is_some()); + } } diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 061333ed6e..7970659295 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1569,6 +1569,16 @@ exceeds `undoBytes`, RustGIS drops the oldest Undo steps first, then the farthes It keeps the newest Undo step even if that step alone exceeds the limit. The first time this happens in a project, a message says so. Edits can still create a temporary full copy of a layer. +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, and what only Undo and Redo +keep, all within three quarters of the computer's memory. When it doesn't fit, Redo steps are +dropped first (the edit clears them anyway), then the oldest Undo steps, and a message says so the +first time in a project. 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. Edits made by a +script, model, task or plugin aren't checked, and the web app doesn't +check, as it can't read the memory. Sizes are estimated, counting each text and part as the block +of memory it takes, so they come out above the bytes themselves. + So a computer with 16 GB reads rasters of up to about 500 million samples. A run that passes on one computer can be refused on a smaller one; the error names the limit there. Project Raster (`raster.project`) puts a raster on a grid of any coordinate system, cell size and extent, and Polygons to Raster From 21d46572bf8d0ccbc0f131e59996c35ade3c6557 Mon Sep 17 00:00:00 2001 From: strebdom Date: Thu, 19 Nov 2026 10:50:06 +0100 Subject: [PATCH 2/7] fix(engine): free history only when an edit copies, and count background copies in flight (#2431) --- crates/data/src/lib.rs | 56 +++++++ crates/engine/src/cmd/reads.rs | 63 ++++++- crates/engine/src/lib.rs | 203 ++++++++++++++++++---- crates/engine/src/policy/dispatch.rs | 28 ++-- crates/engine/src/undo_memory.rs | 241 ++++++++++++++++++++++++--- crates/ui-egui/src/readjob.rs | 4 +- docs/user-guide/analysis.md | 22 ++- 7 files changed, 538 insertions(+), 79 deletions(-) diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 6a7cbd1f7a..d02daf8a5c 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -205,6 +205,50 @@ pub struct Feature { pub attrs: Vec, } +mod rows_copy { + use std::cell::RefCell; + + thread_local! { + static HOOK: RefCell>> = const { RefCell::new(None) }; + } + + /// Takes the hook out before calling it, so it runs once and may itself change rows. + pub(super) fn fire() { + if let Some(hook) = HOOK.try_with(|h| h.borrow_mut().take()).ok().flatten() { + hook(); + } + } + + /// Puts back the hook that was set before, also when `f` unwinds. + struct Restore(Option>>); + + impl Drop for Restore { + fn drop(&mut self) { + if let Some(previous) = self.0.take() { + let _ = HOOK.try_with(|h| *h.borrow_mut() = previous); + } + } + } + + pub(super) fn with(hook: Box, f: impl FnOnce() -> R) -> (R, bool) { + let previous = HOOK.try_with(|h| h.borrow_mut().replace(hook)).unwrap_or(None); + let restore = Restore(Some(previous)); + let result = f(); + let fired = HOOK.try_with(|h| h.borrow().is_none()).unwrap_or(true); + drop(restore); + (result, fired) + } +} + +/// Runs `f`, calling `hook` once on this thread just before the first change in it copies rows +/// that another owner shares (an Undo snapshot), and says whether it was called. The session +/// frees older Undo steps there, only once an edit is about to copy (#2431); an edit that fails +/// before writing keeps them. Any shared rows `f` copies call it, not only those it set out to +/// change. A hook set before is put back afterwards. +pub fn before_rows_copy(hook: Box, f: impl FnOnce() -> R) -> (R, bool) { + rows_copy::with(hook, f) +} + /// A dataset's features, shared until changed: cloning them (an undo snapshot, a copy of the /// project) copies a pointer, and the first change through one of the copies copies the rows /// for it. A large layer is then held once however many undo steps leave it alone. @@ -231,14 +275,24 @@ impl Features { /// The rows, taking them out of the share (copying them only when another copy holds them). pub fn into_vec(self) -> Vec { + self.before_copy(); std::sync::Arc::unwrap_or_clone(self.rows) } + /// Calls the hook [`before_rows_copy`] set, when a change is about to copy rows another + /// owner shares. + fn before_copy(&self) { + if std::sync::Arc::strong_count(&self.rows) > 1 { + rows_copy::fire(); + } + } + /// Appends a row with the id one past the largest. `max_id` stays right only because every /// other change to `rows` goes through `DerefMut`, which clears it. fn push_with_new_id(&mut self, geometry: Option, attrs: Vec) { let max = self.max_id.unwrap_or_else(|| self.rows.iter().map(|f| f.id).max().unwrap_or(0)); let id = max.saturating_add(1); + self.before_copy(); std::sync::Arc::make_mut(&mut self.rows).push(Feature { id, geometry, attrs }); self.max_id = Some(id); } @@ -246,6 +300,7 @@ impl Features { /// Appends a row with the id one past the last row's, keeping the largest id if it is known. fn push_after_last(&mut self, geometry: Option, attrs: Vec) { let id = self.rows.last().map(|f| f.id.saturating_add(1)).unwrap_or(1); + self.before_copy(); std::sync::Arc::make_mut(&mut self.rows).push(Feature { id, geometry, attrs }); self.max_id = self.max_id.map(|m| m.max(id)); } @@ -262,6 +317,7 @@ impl std::ops::DerefMut for Features { fn deref_mut(&mut self) -> &mut Vec { // The caller may change ids, so the largest is searched for again on the next push. self.max_id = None; + self.before_copy(); std::sync::Arc::make_mut(&mut self.rows) } } diff --git a/crates/engine/src/cmd/reads.rs b/crates/engine/src/cmd/reads.rs index 77179a5afc..776cc27b90 100644 --- a/crates/engine/src/cmd/reads.rs +++ b/crates/engine/src/cmd/reads.rs @@ -28,6 +28,10 @@ pub struct Read { pub(crate) source: Option, pub(crate) ready: Option, pub(crate) inputs: Vec, + /// History set aside to make room for an edit's copy, and the copy counted as held until it + /// lands (#2431). + pub(crate) room: Option, + pub(crate) reservation: Option, } /// A reader chosen only after the command and its original input have been admitted. @@ -59,6 +63,9 @@ pub struct ReadAhead { /// A table write retains its admitted project and table identity across queue waits. table: Option<(u64, u32, u64)>, preview: Option, + /// Set when the edit starts ([`Self::refresh_table_input`]), carried to its landing. + room: Option, + reservation: Option, } impl ReadAhead { @@ -83,8 +90,39 @@ impl ReadAhead { /// Refreshes a table write's input immediately before its worker starts, so queued writes /// see earlier writes' output. The admitted operation, owner and table contents identity stay fixed; /// landing still rejects changes made while the worker runs. Other reads keep their input. - pub fn refresh_table_input(mut self, s: &Session) -> Result { + /// + /// An edit's copy is checked against memory here, with the session's history as it is now and + /// the copies of edits still running counted (#2431): refused when it can't fit, or with + /// older history set aside for it, freed on the worker just before it copies. + pub fn refresh_table_input(self, s: &mut Session) -> Result { self.owner.check()?; + let mut ahead = self.refresh_input(s)?; + ahead.make_room(s)?; + Ok(ahead) + } + + fn make_room(&mut self, s: &mut Session) -> Result<(), String> { + let CommandOp::Registered { spec, params } = self.op.op() else { return Ok(()) }; + s.reclaim_rooms(); + let table = s.named_table(spec, params); + let layer = s.layer_id(params).ok().or(s.active_layer); + let pending = s.room_pending(); + let Some(room) = s.room_for_edit(spec.id, spec.mutates, spec.label, layer, table)? else { return Ok(()) }; + if pending && room.count > 0 { + // One edit's history out at a time, so each goes back in its place. + s.put_back(&room, true, true); + return Err(format!( + "{}: not enough memory to start it while another edit is running; run it again once that one has finished", + spec.label + )); + } + self.reservation = Some(s.undo_memory.reserve(room.copy)); + s.remember_room(&room); + self.room = Some(room); + Ok(()) + } + + fn refresh_input(mut self, s: &Session) -> Result { let CommandOp::Registered { spec, params } = self.op.op() else { return Err("not a registered read command".into()) }; if let Some(preview) = &self.preview { let dataset = if let Some(table) = s.named_table(spec, params) { @@ -123,7 +161,7 @@ impl ReadAhead { /// says it as it would have; only a cancelled run (or a bug in a reader) is an error here. pub fn run(self, control: &std::sync::Arc) -> Result { let inputs = self.capture_inputs.then(rustgis_data::provenance::Capture::start); - let ReadAhead { name, op, owner, source, work, .. } = self; + let ReadAhead { name, op, owner, source, work, room, reservation, .. } = self; owner.check()?; let current = owner.clone(); let still = std::sync::Arc::new(move || current.check().is_ok()); @@ -132,14 +170,29 @@ impl ReadAhead { let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { crate::render::rustgis_tiles::cache::with_still(still, || { rustgis_analysis::run_under(name, control, || { - ready = work.map(|ReadWork { key, work, .. }| Ready { key, value: work() }); + ready = work.map(|ReadWork { key, work, .. }| { + // History set aside for this edit is freed just before it copies. + let value = match &room { + Some(room) => rustgis_data::before_rows_copy(room.free_on_copy(), work).0, + None => work(), + }; + Ready { key, value } + }); Ok(()) }) }) })) .unwrap_or_else(|_| Err(format!("{name} failed unexpectedly"))); res?; - Ok(Read { op, owner, source, ready, inputs: inputs.as_ref().map_or_else(Vec::new, rustgis_data::provenance::Capture::inputs) }) + Ok(Read { + op, + owner, + source, + ready, + inputs: inputs.as_ref().map_or_else(Vec::new, rustgis_data::provenance::Capture::inputs), + room, + reservation, + }) } } @@ -231,7 +284,7 @@ pub(crate) fn prepare(s: &mut Session, op: Authorized, owner: Continu let table = super::edit::table_edit_in_background(spec.id) .and_then(|_| s.named_table(spec, params)) .and_then(|id| s.project.table(id).map(|t| (s.opened, id, t.instance_id()))); - Ok(ReadAhead { name, op, owner, source, work, table, preview: None, capture_inputs: s.log.on() }) + Ok(ReadAhead { name, op, owner, source, work, table, preview: None, capture_inputs: s.log.on(), room: None, reservation: None }) } /// Consumes a completed read under its initiating owner, with ordinary command history and undo. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 56e92ea2d9..50a5e3db53 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -619,6 +619,25 @@ struct ProjectFiles { opened_package: Option, } +/// Room made in memory for an edit ([`Session::room_for_edit`]): the history steps set aside for +/// it, and what to say or give back once it has run ([`Session::put_back`]). +pub(crate) struct RoomMade { + slot: undo_memory::AsideSlot, + count: usize, + name: String, + /// The copy, counted as held while a background edit runs ([`undo_memory::Budget::reserve`]). + pub(crate) copy: u64, + /// The history when the steps were set aside ([`Session::history_stamp`]). + pub(crate) stamp: (u64, usize), +} + +impl RoomMade { + /// The hook that frees the steps just before the edit copies, on the thread it runs on. + pub(crate) fn free_on_copy(&self) -> Box { + undo_memory::free_on_copy(&self.slot) + } +} + /// An undo or redo step: the project before it, the layout open then, its label, who made it, /// which state of the project it is ([`Session::dirty`]), and the identities of its feature /// allocations for memory accounting. File origins accompany changes made by the command only: @@ -902,6 +921,9 @@ pub struct Session { undo: Vec, redo: Vec, undo_memory: undo_memory::Budget, + /// History set aside for edits running in the background, and the project's state then + /// ([`Session::remember_room`]). + rooms: Vec<(undo_memory::AsideSlot, (u64, usize), usize, String)>, /// The key the next command's undo step merges by ([`Session::merge_undo`]), and the key the /// last step was made under. merge: Option, @@ -1216,9 +1238,19 @@ fn streamed_refusal(label: &str, layer: &str) -> String { /// Commands that change a layer's features or fields, refused on streamed layers (whose features /// are a window read again from the file as the view moves, so edits would be lost). -fn edits_features(id: &str) -> bool { - const SETTINGS: &[&str] = - &["edit.enable", "edit.settings", "edit.status", "edit.template", "edit.snapping", "edit.snap", "edit.tools", "edit.copy"]; +pub(crate) fn edits_features(id: &str) -> bool { + const SETTINGS: &[&str] = &[ + "edit.enable", + "edit.settings", + "edit.status", + "edit.template", + "edit.snapping", + "edit.snap", + "edit.tools", + "edit.copy", + "edit.elevation", + "edit.groundToGrid", + ]; id.starts_with("edit.") && !SETTINGS.contains(&id) } @@ -1331,6 +1363,7 @@ impl Session { undo: Vec::new(), redo: Vec::new(), undo_memory: undo_memory::Budget::default(), + rooms: Vec::new(), merge: None, merged: None, put_aside: None, @@ -1806,6 +1839,8 @@ impl Session { } } let active = self.active_layer; + // History a cancelled background edit set aside comes back before Undo is judged. + self.reclaim_rooms(); let (blocked, named, table) = self.conditions(&spec, params); if let Some(why) = blocked { return Err(format!("{}: {why}", spec.label)); @@ -1819,12 +1854,22 @@ impl Session { } let op = self.authorize(id, params)?; // After authorizing: an edit refused there (an Assistant call not approved) costs no history. - if let Some(e) = self.room_for_edit(id, mutates, label, named.or(active), table) { - self.notify(e.clone(), true); - return Err(e); - } + let room = match self.room_for_edit(id, mutates, label, named.or(active), table) { + Ok(room) => room, + Err(e) => { + self.notify(e.clone(), true); + return Err(e); + } + }; self.merge = merge; - let res = self.invoke(op, policy::Txn::Own); + let res = match room.as_ref().filter(|room| room.count > 0) { + None => self.invoke(op, policy::Txn::Own), + Some(room) => { + let (res, _) = rustgis_data::before_rows_copy(undo_memory::free_on_copy(&room.slot), || self.invoke(op, policy::Txn::Own)); + self.put_back(room, res.is_err(), true); + res + } + }; if id == "layer.addDownload" && res.is_ok() && let Some(token) = params.get("geolibreLayer").and_then(|v| v.get("token")).and_then(serde_json::Value::as_str) @@ -1923,38 +1968,46 @@ impl Session { /// Makes room in memory for an edit of a layer's or table's features or fields (#2431 fix 3): /// its first write copies the rows the Undo snapshot shares, so the copy has to fit beside what - /// the session holds. Older history is dropped first, said once a project; an edit that - /// wouldn't fit even without history is refused before anything changes. A command run by - /// another (a script's, a task's step) isn't checked: its history belongs to the command - /// running it, which may still roll back. A table edit the desktop runs in the background is - /// checked before its work starts (`capture_read`). An edit of several layers is - /// measured by the one it names, and memory outside the project (results, caches, the - /// clipboard) is left to the quarter [`rustgis_data::memory::usable`] keeps free. - pub(crate) fn room_for_edit(&mut self, id: &str, mutates: bool, label: &str, layer: Option, table: Option) -> Option { + /// the session holds. Older history is set aside ([`undo_memory::Budget::make_room`]): freed + /// just before the edit copies, given back by [`Session::put_back`] if it never does. An edit + /// that wouldn't fit even without history is refused before anything changes (`Err`). + /// + /// A command run by another (a script's, a task's step) isn't checked: its history belongs to + /// the command running it, which may still roll back. A table edit the desktop runs in the + /// background is checked when its work starts ([`cmd::reads::ReadAhead::refresh_table_input`]). + /// An edit of several layers is measured by the one it names, and memory outside the project + /// (results, caches, the clipboard) is left to the quarter [`rustgis_data::memory::usable`] + /// keeps free. + pub(crate) fn room_for_edit( + &mut self, + id: &str, + mutates: bool, + label: &str, + layer: Option, + table: Option, + ) -> Result, String> { // Paste Special makes a layer of its own: it copies none of the active one's rows. - if !(mutates && edits_features(id)) || id == "edit.pasteSpecial" || self.depth > 0 { - return None; + if !(mutates && edits_features(id)) || id == "edit.pasteSpecial" || self.depth > 0 || self.undo_memory.memory.is_none() { + return Ok(None); } - let (name, features) = match table { - Some(t) => self.project.table(t).map(|t| (t.dataset.name.clone(), t.dataset.features.clone()))?, - None => layer - .and_then(|l| self.map().layer(l)) - .filter(|l| !l.is_streamed()) - .map(|l| (l.name.clone(), l.dataset.features.clone()))?, + let target = match table { + Some(t) => self.project.table(t).map(|t| (t.dataset.name.clone(), t.dataset.features.clone())), + None => { + layer.and_then(|l| self.map().layer(l)).filter(|l| !l.is_streamed()).map(|l| (l.name.clone(), l.dataset.features.clone())) + } }; + let Some((name, features)) = target else { return Ok(None) }; let copy = self.undo_memory.rows_bytes(&features); drop(features); match self.undo_memory.make_room(&self.project, &mut self.undo, &mut self.redo, copy) { - Ok(None) => None, - Ok(Some(dropped)) => { - let template = "Memory is nearly full: older Undo steps are dropped to make room for edits ({count} before editing {layer}). An edit that still doesn't fit is refused."; - self.notify_text( - notice_text::NoticeText::format(template, [("count", dropped.to_string().into()), ("layer", name.into())]), - false, - ); - None - } - Err((held, usable)) => Some(format!( + Ok(aside) => Ok(Some(RoomMade { + count: aside.as_ref().map_or(0, undo_memory::Aside::len), + slot: std::sync::Arc::new(std::sync::Mutex::new(aside)), + name, + copy, + stamp: self.history_stamp(), + })), + Err((held, usable)) => 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), @@ -1963,6 +2016,88 @@ impl Session { } } + /// After an edit that had room made for it: steps it never needed freed (it failed, or wrote + /// nothing shared) go back where they were, Redo only when it failed, as success clears it. + /// `in_place` says the history still follows on from them: nothing else changed the project + /// since they were set aside (a background edit's may have); otherwise they are freed. Freed + /// steps are said, once a project. + pub(crate) fn put_back(&mut self, room: &RoomMade, failed: bool, in_place: bool) { + if room.count == 0 { + return; + } + let aside = room.slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take(); + // Redo goes back unless the edit made a step of its own, which cleared it. + let redo = in_place && (failed || room.stamp == self.history_stamp()); + self.return_steps(aside, in_place, redo, room.count, &room.name); + } + + /// What tells whether the history moved on since steps were set aside: the count of states + /// given (each edit makes one; Undo and Redo don't) and the number of steps, which trimming + /// lowers. + pub(crate) fn history_stamp(&self) -> (u64, usize) { + (self.states, self.undo.len() + self.redo.len()) + } + + fn return_steps(&mut self, aside: Option, undo: bool, redo: bool, count: usize, name: &str) { + match aside { + // Redo not put back was cleared by the edit's own step, as it would have been anyway. + Some(aside) if undo => { + self.undo.splice(0..0, aside.undo); + if redo { + self.redo.splice(0..0, aside.redo); + } + // The edit's own step went in while they were out. + let over = self.undo.len().saturating_sub(UNDO_LIMIT); + self.undo.drain(..over); + } + // Freed: by the copy (none left), or because the history moved on. + _ => { + if self.undo_memory.say_room() { + let template = "Memory is nearly full: older Undo steps are dropped to make room for edits ({count} before editing {layer}). An edit that still doesn't fit is refused."; + let args = [("count", count.to_string().into()), ("layer", name.to_string().into())]; + self.notify_text(notice_text::NoticeText::format(template, args), false); + } + } + } + } + + /// Keeps track of history set aside for an edit running in the background, so it can be given + /// back if the edit ends without landing ([`Session::reclaim_rooms`]). + pub(crate) fn remember_room(&mut self, room: &RoomMade) { + if room.count > 0 { + self.rooms.push((std::sync::Arc::clone(&room.slot), room.stamp, room.count, room.name.clone())); + } + } + + /// Whether history is set aside for an edit running in the background. + pub(crate) fn room_pending(&self) -> bool { + !self.rooms.is_empty() + } + + /// Forgets a background edit's set-aside history once it has landed. + pub(crate) fn forget_room(&mut self, room: &RoomMade) { + self.rooms.retain(|(slot, ..)| !std::sync::Arc::ptr_eq(slot, &room.slot)); + } + + /// Gives back the history set aside for background edits that ended without landing (cancelled, + /// failed to start, or their worker failed): only the session still holds it. It goes back + /// while nothing else changed the project since, newest set aside first so the oldest ends + /// in front, and is freed and said otherwise. Run before each command run by itself, and by + /// the desktop as its background jobs end, so Undo sees it. + pub fn reclaim_rooms(&mut self) { + if self.depth > 0 || self.rooms.is_empty() { + return; + } + let (ended, running): (Vec<_>, Vec<_>) = + std::mem::take(&mut self.rooms).into_iter().partition(|(slot, ..)| std::sync::Arc::strong_count(slot) == 1); + self.rooms = running; + for (slot, stamp, count, name) in ended.into_iter().rev() { + let aside = slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take(); + let in_place = stamp == self.history_stamp(); + self.return_steps(aside, in_place, in_place, count, &name); + } + } + /// Runs `f` as the command `label`: when it `mutates`, the project is snapshotted for undo /// and restored if `f` fails or panics. pub(crate) fn guarded(&mut self, label: &'static str, mutates: bool, f: impl FnOnce(&mut Session) -> CmdResult) -> CmdResult { diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index 98977d45dc..a4b0b58ed2 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -189,7 +189,7 @@ impl Session { params.insert("layer".into(), json!(id)); } let mut op = self.authorize(command, &Value::Object(params))?; - self.check_read_command(&op, true)?; + self.check_read_command(&op)?; let copy_command = matches!(command, "model.run" | "script.run") && self.policy_user(); if copy_command { // A model's or script's native copy may read through several tools. Bind the original @@ -211,7 +211,10 @@ impl Session { } /// Lands only the original read invocation; no result can be claimed by another command. pub(crate) fn finish_read(&mut self, read: crate::cmd::reads::Read) -> CmdResult { - let crate::cmd::reads::Read { op, owner, source, ready, inputs } = read; + let crate::cmd::reads::Read { op, owner, source, ready, inputs, room, reservation } = read; + // History set aside for the edit's copy goes back if the edit fails or never copied, while + // nothing else has changed the history since (#2431). + let in_place = room.as_ref().is_some_and(|room| room.stamp == self.history_stamp()); let (command, params) = match op.op() { CommandOp::Registered { spec, params } => (spec.id, params.clone()), _ => return Err("not a registered read command".into()), @@ -231,9 +234,13 @@ impl Session { if !owner.native_tool_owner() && *op.node != s.command_node(command, ¶ms)? { return Err("the read command changed since it was authorized".into()); } - s.check_read_command(&op, false)?; + s.check_read_command(&op)?; s.read_ahead = ready; - let result = s.invoke(op, Txn::Own); + // An edit without a worker copies here, when it lands. + let result = match room.as_ref().filter(|room| room.count > 0) { + Some(room) => rustgis_data::before_rows_copy(room.free_on_copy(), || s.invoke(op, Txn::Own)).0, + None => s.invoke(op, Txn::Own), + }; if result.is_ok() && let Some(source) = crate::sources::added_by(command, ¶ms) { @@ -245,15 +252,19 @@ impl Session { }) })); self.read_ahead = None; + if let Some(room) = &room { + let failed = !matches!(&result, Ok(Ok(_))); + self.put_back(room, failed, in_place); + self.forget_room(room); + } + drop(reservation); match result { Ok(result) => result, Err(panic) => std::panic::resume_unwind(panic), } } /// Preserves ordinary command conditions for the admitted read's layer or table selector. - /// `before_work`: the read is about to start, and an edit's copy is checked against memory - /// then (#2431), before its worker makes it; landing doesn't check again. - fn check_read_command(&mut self, op: &Authorized, before_work: bool) -> Result<(), String> { + fn check_read_command(&mut self, op: &Authorized) -> Result<(), String> { let CommandOp::Registered { spec, params } = op.op() else { return Err("not a registered read command".into()) }; let named = self.layer_id(params).ok(); let active = self.active_layer; @@ -268,9 +279,6 @@ impl Session { if let Some(why) = self.streamed_edit(spec.id, spec.mutates, spec.label, if table.is_some() { None } else { named.or(active) }) { return Err(why); } - if before_work && let Some(why) = self.room_for_edit(spec.id, spec.mutates, spec.label, named.or(active), table) { - return Err(why); - } Ok(()) } /// Admits an export before its preparation reads any input or creates off-thread work. diff --git a/crates/engine/src/undo_memory.rs b/crates/engine/src/undo_memory.rs index 872f6403ee..ffadc48654 100644 --- a/crates/engine/src/undo_memory.rs +++ b/crates/engine/src/undo_memory.rs @@ -4,7 +4,10 @@ use rustgis_data::{Coord, Feature, Features, Geometry, Value}; use std::{ collections::{HashMap, HashSet}, mem::size_of, - sync::Weak, + sync::{ + Arc, Mutex, Weak, + atomic::{AtomicU64, Ordering}, + }, }; type Key = Weak>; @@ -24,6 +27,8 @@ pub(crate) struct Budget { pub(crate) memory: Option, // Dropping steps to make room for an edit is said once a project, as `said` is. room_said: bool, + // The copies of background edits not landed yet ([`Budget::reserve`]). + in_flight: Arc, // 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, @@ -37,6 +42,7 @@ impl Default for Budget { said: false, memory: rustgis_data::memory::physical(), room_said: false, + in_flight: Arc::default(), estimates: HashMap::new(), } } @@ -99,38 +105,52 @@ impl Budget { } /// Makes room for an edit that copies `copy` bytes of rows (#2431 fix 3): when what the session - /// holds and the copy pass the memory it plans to use ([`rustgis_data::memory::usable`]), - /// history goes until they fit: Redo first, farthest first, as the edit clears it anyway, then - /// Undo, oldest first. The history is left as it is, and `Err` gives what is held and the memory - /// planned for, when the copy wouldn't fit even with the history gone. + /// 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)). `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)> { + ) -> Result, (u64, u64)> { let Some(usable) = rustgis_data::memory::usable(self.memory) else { return Ok(None) }; - let fits = |held: u64| held.saturating_add(copy) <= usable; + let running = self.in_flight.load(Ordering::Relaxed); + let fits = |held: u64| held.saturating_add(running).saturating_add(copy) <= usable; if fits(self.held(live, undo, redo)) { return Ok(None); } let open = self.held(live, &[], &[]); if !fits(open) { - return Err((open, usable)); + return Err((open.saturating_add(running), usable)); } - let mut dropped = 0; + let mut aside = Aside::default(); while !fits(self.held(live, undo, redo)) { if !redo.is_empty() { - redo.remove(0); + aside.redo.push(redo.remove(0)); } else if undo.is_empty() { break; } else { - undo.remove(0); + aside.undo.push(undo.remove(0)); } - dropped += 1; } - Ok((dropped > 0 && !std::mem::replace(&mut self.room_said, true)).then_some(dropped)) + Ok(Some(aside).filter(|aside| aside.len() > 0)) + } + + /// Whether dropping steps to make room is to be said: once a project. + pub(crate) fn say_room(&mut self) -> bool { + !std::mem::replace(&mut self.room_said, true) + } + + /// Counts `bytes` as held until the reservation is dropped: the copy an edit running in the + /// 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 } } /// The estimated size of `features`' rows: what the first write to them copies while a @@ -156,6 +176,42 @@ impl Budget { } } +/// Undo and Redo steps set aside to make room for an edit ([`Budget::make_room`]), oldest first. +#[derive(Default)] +pub(crate) struct Aside { + pub(crate) undo: Vec, + pub(crate) redo: Vec, +} + +impl Aside { + pub(crate) fn len(&self) -> usize { + self.undo.len() + self.redo.len() + } +} + +/// Steps set aside, shared with the hook that frees them just before the edit copies rows, on +/// whichever thread it runs. +pub(crate) type AsideSlot = Arc>>; + +/// The hook [`rustgis_data::before_rows_copy`] calls: frees the steps in `slot`. +pub(crate) fn free_on_copy(slot: &AsideSlot) -> Box { + let slot = Arc::clone(slot); + Box::new(move || drop(slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take())) +} + +/// A background edit's copy, counted as held while it runs ([`Budget::reserve`]). +pub struct Reservation { + in_flight: Arc, + bytes: u64, +} + +impl Drop for Reservation { + fn drop(&mut self) { + // Only what `reserve` added is taken away, so this never goes below zero. + self.in_flight.fetch_sub(self.bytes, Ordering::Relaxed); + } +} + /// The pixels and embedded files of the rasters in `projects`, each shared allocation once. fn raster_bytes<'a>(projects: impl Iterator) -> u64 { let mut seen = HashSet::new(); @@ -445,17 +501,156 @@ mod tests { assert_eq!(session.undo_depth(), 3, "every Undo step is kept"); } + /// A session with a table of one long text, added and edited twice: three Undo steps, two of + /// them holding their own rows. #[cfg(not(target_arch = "wasm32"))] - #[test] - fn a_table_edit_run_in_the_background_is_checked_before_its_work() { + fn table_session() -> Session { let mut session = Session::new(crate::Project::default()); - session.run("layer.addDataText", &json!({"fileName": "calc.csv", "text": "n\n1\n2\n"})).unwrap(); - session.undo_memory.memory = Some(4); + let text = format!("n,t\n1,{}\n", "a".repeat(4096)); + session.run("layer.addDataText", &json!({"fileName": "calc.csv", "text": text})).unwrap(); + session.undo_memory.limit = 1 << 30; + session.undo_memory.memory = None; + for t in ["b", "c"] { + session.run("edit.setValue", &json!({"table": "calc", "row": 0, "field": "t", "value": t.repeat(4096)})).unwrap(); + } + session + } + + /// Memory planned so the open rows, the copies in flight and one copy of the table fit with a + /// little over, without the history. + #[cfg(not(target_arch = "wasm32"))] + fn room_for_one_table_copy(session: &mut Session) -> u64 { + let rows = session.project.tables[0].dataset.features.clone(); + let copy = session.undo_memory.rows_bytes(&rows); + drop(rows); + let open = + session.undo_memory.held(&session.project, &[], &[]) + session.undo_memory.in_flight.load(std::sync::atomic::Ordering::Relaxed); + ((open + copy + 64) * 4).div_ceil(3) + 4 + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_table_edit_run_in_the_background_is_checked_when_it_starts() { + use crate::cmd::reads::read_ahead; + let mut session = table_session(); let p = json!({"table": "calc", "row": 0, "field": "n", "value": 3}); - let err = crate::cmd::reads::read_ahead(&mut session, "edit.setValue", &p).err().unwrap(); + session.undo_memory.memory = Some(4); + let ahead = read_ahead(&mut session, "edit.setValue", &p).ok().unwrap(); + let err = ahead.refresh_table_input(&mut session).err().unwrap(); assert!(err.contains("not enough memory to edit calc"), "{err}"); + assert_eq!(session.undo_depth(), 3, "a refused edit keeps the history"); + + // Room for one copy: the history is set aside when the edit starts. + session.undo_memory.memory = Some(room_for_one_table_copy(&mut session)); + let first = read_ahead(&mut session, "edit.setValue", &p).ok().unwrap().refresh_table_input(&mut session).ok().unwrap(); + assert_eq!(session.undo_depth(), 0); + // A second edit starting while the first one's copy is in flight sees that copy. + let second = read_ahead(&mut session, "edit.setValue", &p).ok().unwrap(); + let err = second.refresh_table_input(&mut session).err().unwrap(); + assert!(err.contains("not enough memory to edit calc"), "{err}"); + + // Cancelled before it ran: its history comes back at the next check, as nothing else changed. + drop(first); session.undo_memory.memory = Some(1 << 40); - assert!(crate::cmd::reads::read_ahead(&mut session, "edit.setValue", &p).is_ok()); + let ahead = read_ahead(&mut session, "edit.setValue", &p).ok().unwrap().refresh_table_input(&mut session).ok().unwrap(); + assert_eq!(session.undo_depth(), 3, "the history set aside comes back"); + assert_eq!( + session.undo_memory.in_flight.load(std::sync::atomic::Ordering::Relaxed), + session.undo_memory.rows_bytes(&session.project.tables[0].dataset.features.clone()) + ); + drop(ahead); + assert_eq!(session.undo_memory.in_flight.load(std::sync::atomic::Ordering::Relaxed), 0, "the reservation ends with the edit"); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_background_table_edit_frees_the_history_when_it_copies_and_says_so() { + use crate::cmd::reads::read_ahead; + let mut session = table_session(); + let p = json!({"table": "calc", "row": 0, "field": "t", "value": "d"}); + session.undo_memory.memory = Some(room_for_one_table_copy(&mut session)); + let mark = session.notice_mark(); + let ahead = read_ahead(&mut session, "edit.setValue", &p).ok().unwrap().refresh_table_input(&mut session).ok().unwrap(); + let read = ahead.run(&rustgis_analysis::control::Control::stoppable()).ok().unwrap(); + session.finish_read(read).unwrap(); + assert_eq!(session.project.tables[0].dataset.features[0].attrs[1], Value::Text("d".into())); + let notices = session.notices_since(mark); + assert!(notices.iter().any(|n| n.text.contains("(3 before editing calc)")), "{notices:?}"); + assert_eq!(session.undo_depth(), 1, "the edit's own step"); + assert_eq!(session.undo_memory.in_flight.load(std::sync::atomic::Ordering::Relaxed), 0); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_second_background_edit_needing_history_waits_for_the_first() { + use crate::cmd::reads::read_ahead; + let mut session = table_session(); + let p = json!({"table": "calc", "row": 0, "field": "n", "value": 3}); + // Room for what is held and 64 bytes: the first edit's copy needs the oldest Undo step + // with rows of its own set aside, the second's the next one too. + let held = session.undo_memory.held(&session.project, &session.undo, &session.redo); + session.undo_memory.memory = Some(((held + 64) * 4).div_ceil(3) + 4); + let first = read_ahead(&mut session, "edit.setValue", &p).ok().unwrap().refresh_table_input(&mut session).ok().unwrap(); + assert_eq!(session.undo_depth(), 1, "the table's addition and its first edit are aside"); + let in_flight = session.undo_memory.in_flight.load(std::sync::atomic::Ordering::Relaxed); + let err = read_ahead(&mut session, "edit.setValue", &p).ok().unwrap().refresh_table_input(&mut session).err().unwrap(); + assert!(err.contains("while another edit is running"), "{err}"); + assert_eq!(session.undo_depth(), 1, "what the second set aside is back"); + assert_eq!(session.undo_memory.in_flight.load(std::sync::atomic::Ordering::Relaxed), in_flight); + drop(first); + session.reclaim_rooms(); + assert_eq!(session.undo_depth(), 3); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_cancelled_background_edit_gives_its_history_back_or_says_it_went() { + use crate::cmd::reads::read_ahead; + let p = json!({"table": "calc", "row": 0, "field": "n", "value": 3}); + + // Cancelled before copying, nothing else done: Undo has its steps again at once. + let mut session = table_session(); + session.undo_memory.memory = Some(room_for_one_table_copy(&mut session)); + let ahead = read_ahead(&mut session, "edit.setValue", &p).ok().unwrap().refresh_table_input(&mut session).ok().unwrap(); + assert_eq!(session.undo_depth(), 0); + drop(ahead); + let mark = session.notice_mark(); + session.run("edit.undo", &json!({})).unwrap(); + assert_eq!(session.undo_depth(), 2, "three came back, one was undone"); + assert!(session.notices_since(mark).is_empty()); + + // The project changed meanwhile: the steps can't go back in place, and that is said. + let mut session = table_session(); + session.undo_memory.memory = Some(room_for_one_table_copy(&mut session)); + let ahead = read_ahead(&mut session, "edit.setValue", &p).ok().unwrap().refresh_table_input(&mut session).ok().unwrap(); + session.undo_memory.memory = None; + session.run("layer.addDataText", &json!({"fileName": "other.csv", "text": "a\n1\n"})).unwrap(); + drop(ahead); + let mark = session.notice_mark(); + session.run("layer.addDataText", &json!({"fileName": "third.csv", "text": "a\n1\n"})).unwrap(); + let notices = session.notices_since(mark); + assert!(notices.iter().any(|n| n.text.contains("(3 before editing calc)")), "{notices:?}"); + assert_eq!(session.undo_depth(), 2, "only the two later steps"); + } + + #[test] + fn a_failed_edit_keeps_the_history_set_aside_for_it() { + 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)); + } + session.undo_memory.memory = Some(room_for_one_copy(&mut session, 64)); + let mark = session.notice_mark(); + // An unknown field fails before anything is written. + assert!(session.run("edit.setValue", &json!({"layer": "rows", "row": 0, "field": "nope", "value": "x"})).is_err()); + assert_eq!(session.undo_depth(), 2, "nothing was copied, so nothing was dropped"); + assert!(!session.notices_since(mark).iter().any(|n| n.text.contains("make room"))); + // The same edit with a real field copies, and drops them. + edit(&mut session, "d"); + assert_eq!(session.undo_depth(), 1); + assert!(session.notices_since(mark).iter().any(|n| n.text.contains("(2 before editing rows)"))); } #[test] @@ -463,7 +658,11 @@ mod tests { let mut session = session(4096); session.undo_memory.memory = Some(4); let id = Some(session.map().layer_by_name("rows").unwrap().id); - assert!(session.room_for_edit("edit.pasteSpecial", true, "Paste Special", id, None).is_none()); - assert!(session.room_for_edit("edit.paste", true, "Paste", id, None).is_some()); + assert!(matches!(session.room_for_edit("edit.pasteSpecial", true, "Paste Special", id, None), Ok(None))); + assert!(session.room_for_edit("edit.paste", true, "Paste", id, None).is_err()); + // Editing settings copy no rows. + for command in ["edit.elevation", "edit.groundToGrid"] { + assert!(matches!(session.room_for_edit(command, true, "Settings", id, None), Ok(None)), "{command}"); + } } } diff --git a/crates/ui-egui/src/readjob.rs b/crates/ui-egui/src/readjob.rs index 4209c5dffd..ca98888036 100644 --- a/crates/ui-egui/src/readjob.rs +++ b/crates/ui-egui/src/readjob.rs @@ -446,7 +446,7 @@ fn start(app: &mut RustGisApp, mut asked: Asked, p: Value) -> Result ahead, Err(why) => return complete_here(app, asked, p, Err(why)), }; @@ -565,6 +565,8 @@ fn complete_here(app: &mut RustGisApp, asked: Asked, p: Value, done: Result bool { + // History an ended edit set aside comes back now, not at the next command: Undo must see it. + app.session.reclaim_rooms(); if !busy(app) { return false; } diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 7970659295..831f0d9af5 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1570,14 +1570,20 @@ It keeps the newest Undo step even if that step alone exceeds the limit. The fir happens in a project, a message says so. Edits can still create a temporary full copy of a layer. 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, and what only Undo and Redo -keep, all within three quarters of the computer's memory. When it doesn't fit, Redo steps are -dropped first (the edit clears them anyway), then the oldest Undo steps, and a message says so the -first time in a project. 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. Edits made by a -script, model, task or plugin aren't checked, and the web app doesn't -check, as it can't read the memory. Sizes are estimated, counting each text and part as the block -of memory it takes, so they come out above the bytes themselves. +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 +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. A message says when steps are freed, the +first time in a project. 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 +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 reloading or repairing a layer's data, and the +web app doesn't check, as it can't read the memory. Sizes are estimated, counting each text and part +as the block of memory it takes, so they come out above the bytes themselves. So a computer with 16 GB reads rasters of up to about 500 million samples. A run that passes on one computer can be refused on a smaller one; the error names the limit there. Project Raster (`raster.project`) puts a raster From 36abfd510df911013ea5a3441134a5881a04e81d Mon Sep 17 00:00:00 2001 From: strebdom Date: Thu, 19 Nov 2026 11:37:40 +0100 Subject: [PATCH 3/7] fix(engine): count set-aside history as held, check rows before writing, refuse a changed layer at start (#2431) --- crates/engine/src/cmd/edit.rs | 4 ++ crates/engine/src/cmd/reads.rs | 15 ++++++- crates/engine/src/undo_memory.rs | 74 +++++++++++++++++++++++++++----- 3 files changed, 81 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index e5c6ab6bb1..25e026271c 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -668,6 +668,8 @@ fn set_value(s: &mut Session, p: &Json) -> CmdResult { let (ty, field) = ds.fields.get(fi).map(|f| (f.ty, f.name.clone())).ok_or("no field")?; let v = typed(raw, ty)?; let loss = numeric_loss(&input, &v, ty); + // Looked at before writing: a write copies rows shared with the Undo snapshot (#2431). + ds.features.get(row).and_then(|f| f.attrs.get(fi)).ok_or("no such row")?; let cell = ds.features.get_mut(row).and_then(|f| f.attrs.get_mut(fi)).ok_or("no such row")?; *cell = v; let table = ds.name.clone(); @@ -684,6 +686,8 @@ fn set_value(s: &mut Session, p: &Json) -> CmdResult { let v = typed(raw, ty)?; // Keep the existing finite coercion, but say when it discards information. let loss = numeric_loss(&input, &v, ty); + // Looked at before writing: a write copies rows shared with the Undo snapshot (#2431). + l.dataset.features.get(row).and_then(|f| f.attrs.get(fi)).ok_or("no such row")?; let f = l.dataset.features.get_mut(row).ok_or("no such row")?; let before = f.clone(); let cell = f.attrs.get_mut(fi).ok_or("no such row")?; diff --git a/crates/engine/src/cmd/reads.rs b/crates/engine/src/cmd/reads.rs index 776cc27b90..3548ccb741 100644 --- a/crates/engine/src/cmd/reads.rs +++ b/crates/engine/src/cmd/reads.rs @@ -66,6 +66,8 @@ pub struct ReadAhead { /// Set when the edit starts ([`Self::refresh_table_input`]), carried to its landing. room: Option, reservation: Option, + /// The rows a layer edit's worker copies, as they were when it was prepared. + rows: Option>>, } impl ReadAhead { @@ -134,6 +136,12 @@ impl ReadAhead { return Err("the data changed after its date preview: choose the format again".into()); } } + if let Some(rows) = &self.rows { + let now = s.layer_id(params).ok().and_then(|id| s.map().layer(id)).map(|l| l.dataset.features.allocation_key()); + if !now.is_some_and(|now| now.ptr_eq(rows)) { + return Err("the layer changed while the edit was waiting: run the edit again".into()); + } + } let Some((opened, table, instance)) = self.table else { return Ok(self) }; if s.opened != opened || s.named_table(spec, params) != Some(table) @@ -284,7 +292,12 @@ pub(crate) fn prepare(s: &mut Session, op: Authorized, owner: Continu let table = super::edit::table_edit_in_background(spec.id) .and_then(|_| s.named_table(spec, params)) .and_then(|id| s.project.table(id).map(|t| (s.opened, id, t.instance_id()))); - Ok(ReadAhead { name, op, owner, source, work, table, preview: None, capture_inputs: s.log.on(), room: None, reservation: None }) + // A layer edit's worker copies the rows taken here: they must still be the layer's when it + // starts, so the memory checked then is what it copies (#2431). + let rows = (work.is_some() && table.is_none() && spec.mutates && crate::edits_features(spec.id)) + .then(|| s.layer_id(params).ok().and_then(|id| s.map().layer(id)).map(|l| l.dataset.features.allocation_key())) + .flatten(); + Ok(ReadAhead { name, op, owner, source, work, table, preview: None, capture_inputs: s.log.on(), room: None, reservation: None, rows }) } /// Consumes a completed read under its initiating owner, with ordinary command history and undo. diff --git a/crates/engine/src/undo_memory.rs b/crates/engine/src/undo_memory.rs index ffadc48654..48599341dd 100644 --- a/crates/engine/src/undo_memory.rs +++ b/crates/engine/src/undo_memory.rs @@ -109,7 +109,7 @@ impl Budget { /// 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)). `Err` gives what is held and the memory planned + /// ([`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, @@ -121,7 +121,8 @@ impl Budget { let Some(usable) = rustgis_data::memory::usable(self.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; - if fits(self.held(live, undo, redo)) { + let before = self.held(live, undo, redo); + if fits(before) { return Ok(None); } let open = self.held(live, &[], &[]); @@ -138,6 +139,8 @@ impl Budget { aside.undo.push(undo.remove(0)); } } + let after = self.held(live, undo, redo); + aside.held = Some(self.reserve(before.saturating_sub(after))); Ok(Some(aside).filter(|aside| aside.len() > 0)) } @@ -181,6 +184,9 @@ impl Budget { pub(crate) struct Aside { pub(crate) undo: Vec, pub(crate) redo: Vec, + /// The steps' own memory, still held until they are freed or put back: counted by the checks + /// of other edits meanwhile. + held: Option, } impl Aside { @@ -585,21 +591,50 @@ mod tests { fn a_second_background_edit_needing_history_waits_for_the_first() { use crate::cmd::reads::read_ahead; let mut session = table_session(); - let p = json!({"table": "calc", "row": 0, "field": "n", "value": 3}); - // Room for what is held and 64 bytes: the first edit's copy needs the oldest Undo step - // with rows of its own set aside, the second's the next one too. - let held = session.undo_memory.held(&session.project, &session.undo, &session.redo); - session.undo_memory.memory = Some(((held + 64) * 4).div_ceil(3) + 4); + // A small table to edit: its copy is far smaller than a step of `calc`'s rows. + session.run("layer.addDataText", &json!({"fileName": "tiny.csv", "text": "n\n1\n"})).unwrap(); + let p = json!({"table": "tiny", "row": 0, "field": "n", "value": 3}); + let tiny = session.project.tables.iter().find(|t| t.dataset.name == "tiny").unwrap().dataset.features.clone(); + let small = session.undo_memory.rows_bytes(&tiny); + drop(tiny); + let rows = session.undo_memory.rows_bytes(&session.project.tables[0].dataset.features.clone()); + let open = session.undo_memory.held(&session.project, &[], &[]); + // Room for the open rows, one step of `calc`'s rows (a step takes a little more than the + // rows) and two small copies: the first edit sets aside the oldest step with rows; the + // second, with the first's copy and steps still counted, would need the next one. + session.undo_memory.memory = Some(((open + rows + 2 * small + 1024) * 4).div_ceil(3) + 4); let first = read_ahead(&mut session, "edit.setValue", &p).ok().unwrap().refresh_table_input(&mut session).ok().unwrap(); - assert_eq!(session.undo_depth(), 1, "the table's addition and its first edit are aside"); - let in_flight = session.undo_memory.in_flight.load(std::sync::atomic::Ordering::Relaxed); + let (depth, in_flight) = (session.undo_depth(), session.undo_memory.in_flight.load(std::sync::atomic::Ordering::Relaxed)); + assert_eq!(depth, 2, "calc's addition and first edit are aside"); + assert!(in_flight > small, "the steps aside are counted with the copy: {in_flight}"); let err = read_ahead(&mut session, "edit.setValue", &p).ok().unwrap().refresh_table_input(&mut session).err().unwrap(); assert!(err.contains("while another edit is running"), "{err}"); - assert_eq!(session.undo_depth(), 1, "what the second set aside is back"); + assert_eq!(session.undo_depth(), depth, "what the second set aside is back"); assert_eq!(session.undo_memory.in_flight.load(std::sync::atomic::Ordering::Relaxed), in_flight); drop(first); session.reclaim_rooms(); - assert_eq!(session.undo_depth(), 3); + assert_eq!(session.undo_depth(), 4); + assert_eq!(session.undo_memory.in_flight.load(std::sync::atomic::Ordering::Relaxed), 0); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_layer_edit_waiting_in_the_background_is_refused_once_its_layer_changed() { + use crate::cmd::reads::read_ahead; + let mut session = Session::new(crate::Project::default()); + let text = json!({"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {"day": "01/02/2024"}, + "geometry": {"type": "Point", "coordinates": [10.01, 45.01]}}]}) + .to_string(); + session.run("layer.addDataText", &json!({"fileName": "dated.geojson", "text": text})).unwrap(); + session.run("edit.enable", &json!({"on": true})).unwrap(); + let p = json!({"layer": "dated", "field": "day", "type": "date", "format": "%m/%d/%Y"}); + let ahead = read_ahead(&mut session, "edit.convertField", &p).ok().unwrap(); + session.run("edit.setValue", &json!({"layer": "dated", "row": 0, "field": "day", "value": "02/03/2024"})).unwrap(); + let err = ahead.refresh_table_input(&mut session).err().unwrap(); + assert!(err.contains("the layer changed while the edit was waiting"), "{err}"); + // Unchanged, it starts. + let ahead = read_ahead(&mut session, "edit.convertField", &p).ok().unwrap(); + assert!(ahead.refresh_table_input(&mut session).is_ok()); } #[cfg(not(target_arch = "wasm32"))] @@ -633,6 +668,23 @@ mod tests { assert_eq!(session.undo_depth(), 2, "only the two later steps"); } + #[test] + fn an_edit_of_a_row_past_the_end_keeps_the_history_set_aside_for_it() { + 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)); + } + session.run("edit.undo", &json!({})).unwrap(); + session.undo_memory.memory = Some(room_for_one_copy(&mut session, 64)); + let mark = session.notice_mark(); + let err = session.run("edit.setValue", &json!({"layer": "rows", "row": 5, "field": "text", "value": "x"})).unwrap_err(); + assert!(err.contains("no such row"), "{err}"); + assert_eq!((session.undo_depth(), session.can_redo()), (1, true), "Undo and Redo are kept"); + assert!(!session.notices_since(mark).iter().any(|n| n.text.contains("make room"))); + } + #[test] fn a_failed_edit_keeps_the_history_set_aside_for_it() { let mut session = session(4096); From 1295c031919bdcd5aecd2b8f5b4397f57d8c5c5a Mon Sep 17 00:00:00 2001 From: strebdom Date: Thu, 19 Nov 2026 13:20:51 +0100 Subject: [PATCH 4/7] fix(engine): Set Geometry and Move, Rotate, Scale read rows before writing, so a failed edit keeps its history (#2431) --- crates/engine/src/cmd/design.rs | 10 +++++++++- crates/engine/src/undo_memory.rs | 26 ++++++++++++++++++++++++++ docs/user-guide/analysis.md | 3 ++- 3 files changed, 37 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index f82365cf2c..33c1bc50c3 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -1078,9 +1078,12 @@ fn modify(s: &mut Session, mut change: impl FnMut((u32, usize), &Geometry) -> Re let mut changes = Vec::new(); let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; for r in l.selection.clone() { - let Some(f) = l.dataset.features.get_mut(r) else { continue }; + // Read first, writing only a row that changes: the first write copies the layer's rows + // when Undo shares them, and frees history set aside for that copy (#2431). + let Some(f) = l.dataset.features.get(r) else { continue }; let Some(g) = f.geometry.as_ref().map(|g| change((id, r), g)).transpose()?.flatten() else { continue }; super::edit::validate(&g)?; + let Some(f) = l.dataset.features.get_mut(r) else { continue }; let before = f.clone(); f.geometry = Some(g); changes.push(Change { before: Some(before), row: Some(r) }); @@ -1151,6 +1154,11 @@ pub(crate) fn replace_geometry(s: &mut Session, id: u32, row: usize, g: Geometry if l.geometry_type() != GeometryType::None && l.geometry_type() != g.kind() { return Err(format!("a {} can't replace a {}", g.kind().label(), l.geometry_type().label())); } + // The row checked before writing: the first write copies the layer's rows when Undo shares + // them, and frees history set aside for that copy (#2431). + if l.dataset.features.get(row).is_none() { + return Err("no such row".into()); + } let f = l.dataset.features.get_mut(row).ok_or("no such row")?; let before = f.clone(); f.geometry = Some(g); diff --git a/crates/engine/src/undo_memory.rs b/crates/engine/src/undo_memory.rs index 48599341dd..e7c2d8f838 100644 --- a/crates/engine/src/undo_memory.rs +++ b/crates/engine/src/undo_memory.rs @@ -705,6 +705,32 @@ mod tests { assert!(session.notices_since(mark).iter().any(|n| n.text.contains("(2 before editing rows)"))); } + #[test] + fn shape_edits_that_change_nothing_keep_the_history_set_aside_for_them() { + let mut session = session(4096); + session.undo_memory.limit = 1 << 30; + session.undo_memory.memory = None; + // A selection with no shape, so Move changes nothing. + let id = session.map().layer_by_name("rows").unwrap().id; + let layer = session.map_mut().layer_mut(id).unwrap(); + layer.dataset.features[0].geometry = None; + layer.selection = vec![0]; + session.active_layer = Some(id); + for text in ["b", "c"] { + edit(&mut session, &text.repeat(4096)); + } + session.undo_memory.memory = Some(room_for_one_copy(&mut session, 64)); + let mark = session.notice_mark(); + let point = json!({"type": "Point", "coordinates": [1.0, 1.0]}); + let err = session.run("edit.setGeometry", &json!({"layer": "rows", "row": 5, "geometry": point})).unwrap_err(); + assert!(err.contains("no such row"), "{err}"); + assert_eq!(session.undo_depth(), 2, "Set Geometry of a row past the end keeps the history"); + let err = session.run("edit.move", &json!({"dx": 1.0, "dy": 1.0})).unwrap_err(); + assert!(err.contains("nothing selected"), "{err}"); + assert_eq!(session.undo_depth(), 2, "Move that changes nothing keeps the history"); + assert!(!session.notices_since(mark).iter().any(|n| n.text.contains("make room"))); + } + #[test] fn paste_special_is_not_measured_by_the_active_layer() { let mut session = session(4096); diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 831f0d9af5..942f2aabea 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1575,7 +1575,8 @@ and the copies of edits still running in the background, all within three quarte computer's 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. A message says when steps are freed, the +project was changed while it ran in the background. One that fails after it started copying has +used them, as a finished edit would have. A message says when steps are freed, the first time in a project. 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 From 09a21b791a7ff631367e9591039291631b876f2b Mon Sep 17 00:00:00 2001 From: strebdom Date: Thu, 19 Nov 2026 14:36:06 +0100 Subject: [PATCH 5/7] fix(data): memory limits plan for what is left once much is held (#2431) --- apps/rustgis-cli/tests/memory_override.rs | 19 ++++ crates/analysis/src/density.rs | 3 +- crates/analysis/src/rasterops.rs | 3 +- crates/analysis/src/tools.rs | 3 +- crates/data/src/io.rs | 83 +++++++++++++--- crates/data/src/memory.rs | 111 +++++++++++++++++++++- crates/data/src/ogc.rs | 6 +- crates/data/src/raster/mod.rs | 3 +- crates/engine/src/cmd/workflows.rs | 6 ++ crates/engine/src/lib.rs | 2 + crates/engine/src/undo_memory.rs | 42 +++++++- docs/user-guide/analysis.md | 12 +++ 12 files changed, 268 insertions(+), 25 deletions(-) diff --git a/apps/rustgis-cli/tests/memory_override.rs b/apps/rustgis-cli/tests/memory_override.rs index 62faf5f217..23ce239760 100644 --- a/apps/rustgis-cli/tests/memory_override.rs +++ b/apps/rustgis-cli/tests/memory_override.rs @@ -35,3 +35,22 @@ fn the_memory_override_sets_the_limits_and_says_so() { assert!(!quiet.contains("RUSTGIS_MEMORY_BYTES"), "{quiet}"); assert_eq!(run(Some("8 GiB")).0, 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}"); + // 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..5e89074a13 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -29,19 +29,26 @@ 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 ([`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())) } -/// [`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 @@ -61,13 +68,33 @@ pub fn too_large(len: u64) -> String { /// [`too_large`] against the limit `max` taken when the read started. 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. + let held = if TEST_MAX.with(std::cell::Cell::get).is_some() { 0 } else { crate::memory::held() }; + too_large_held(len, max, memory, held) +} + +/// [`too_large_said`] on a computer with `memory` bytes (`None`: the limit doesn't follow it) +/// while RustGIS holds `held`: what is held is said when it lowered the limit (#2431), with the +/// limit when nothing is held and what to do. +fn too_large_held(len: u64, max: u64, memory: Option, held: u64) -> 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 held == 0 || max >= full { + 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) + ); + } + format!( + "file is too large ({file}; the most read into memory is {} on this computer while RustGIS holds {} of its memory, {} with nothing held): remove layers or tables you no longer need, and save and reopen the project to let go of what Undo keeps of them, 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 +2337,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. @@ -4768,6 +4796,29 @@ 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); + assert_eq!( + lowered, + "file is too large (2048 MiB; the most read into memory is 1024 MiB on this computer while RustGIS holds 40960 MiB of its memory, 2048 MiB with nothing held): remove layers or tables you no longer need, and save and reopen the project to let go of what Undo keeps of them, then try again" + ); + let full = too_large_held(3 * GIB, 2 * GIB, Some(64 * GIB), 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), full); + assert_eq!(too_large_held(GIB, 256 << 20, None, 40 * GIB), "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,6 +4836,12 @@ mod tests { assert_eq!(max_bytes_for(Some(16 * GIB)), BYTES_FLOOR); assert_eq!(max_bytes_for(Some(1024 * GIB)), BYTES_FLOOR); } + // 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)), 512 << 20, "half held: unchanged"); + assert_eq!(max_bytes_within(crate::memory::share(Some(64 * GIB), 40 * GIB)), GIB); + assert_eq!(max_bytes_within(crate::memory::share(Some(16 * GIB), 12 * GIB)), BYTES_FLOOR); + } // The test limit is the calling thread's, and comes back after it, nested too. let real = max_bytes(); with_max_bytes(10, || { diff --git a/crates/data/src/memory.rs b/crates/data/src/memory.rs index 4bdef413a7..eb500bc8c4 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,76 @@ 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`]) taken off, 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()), floor, ceiling, bytes) +} + +/// The memory a job plans for on a computer with `memory` bytes (`None`: not known) while `held` +/// bytes are held: [`SHARE`] of it, or what is left of [`usable`] after what is held when that +/// is less. Up to half the memory held, it is the share. +pub fn share(memory: Option, held: u64) -> Option { + let memory = memory?; + Some((memory / SHARE).min(usable(Some(memory)).unwrap_or(0).saturating_sub(held))) +} + +/// 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 +197,37 @@ 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), Some(4 * GIB), "nothing held: the share"); + assert_eq!(share(Some(16 * GIB), 8 * GIB), Some(4 * GIB), "half held: still the share"); + assert_eq!(share(Some(16 * GIB), 10 * GIB), Some(2 * GIB), "what is left of three quarters"); + assert_eq!(share(Some(16 * GIB), 20 * GIB), Some(0), "more held than planned for: nothing"); + assert_eq!(share(None, 10 * GIB), None, "memory not known"); + // The limits keep their floors and ceilings. + assert_eq!(within(share(Some(16 * GIB), 10 * GIB), 100, 1 << 40, 8), 256 << 20); + assert_eq!(within(share(Some(16 * GIB), 12 * GIB), 100, 1 << 40, 8), 100, "never below the floor"); + assert_eq!(within(share(None, 12 * GIB), 100, 1 << 40, 8), 100); + assert_eq!(within(share(Some(1024 * GIB), 0), 100, 1_000, 8), 1_000); + } + + #[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 4af8c8c139..46308b5b39 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -478,6 +478,9 @@ 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(), "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 +830,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 50a5e3db53..b538d87f80 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 diff --git a/crates/engine/src/undo_memory.rs b/crates/engine/src/undo_memory.rs index e7c2d8f838..ab8f46a9f2 100644 --- a/crates/engine/src/undo_memory.rs +++ b/crates/engine/src/undo_memory.rs @@ -29,6 +29,8 @@ 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, // 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 +45,7 @@ impl Default for Budget { memory: rustgis_data::memory::physical(), room_said: false, in_flight: Arc::default(), + holding: rustgis_data::memory::Holding::default(), estimates: HashMap::new(), } } @@ -104,6 +107,20 @@ 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: @@ -153,7 +170,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 @@ -209,6 +226,8 @@ pub(crate) fn free_on_copy(slot: &AsideSlot) -> Box { 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 { @@ -731,6 +750,27 @@ 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); + } + #[test] fn paste_special_is_not_measured_by_the_active_layer() { let mut session = session(4096); diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 9d9bc468b0..c60df13f71 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1558,6 +1558,18 @@ 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. +Once RustGIS holds more than half the memory, the limits below other than `threadScratchBytes`, +`undoBytes` and `projectBytes` plan for less: for what is +left of three quarters of the memory after what it holds, never below their floors. On a 16 GB +computer holding 10 GiB, they plan for 2 GiB instead of 4 GiB. 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. A file +refused for its size then says what is held, and the limit with nothing held. 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; never below the floors. + | 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 | From e1c559bc9061fa45d5c2ff50033ea57f035181a0 Mon Sep 17 00:00:00 2001 From: strebdom Date: Thu, 19 Nov 2026 15:49:37 +0100 Subject: [PATCH 6/7] fix(data): memory limits and the edit check plan with what the computer has free (#2431) --- apps/rustgis-cli/tests/memory_override.rs | 13 +++- crates/data/src/io.rs | 56 ++++++++------- crates/data/src/memory.rs | 88 ++++++++++++++++++----- crates/engine/src/cmd/workflows.rs | 3 + crates/engine/src/lib.rs | 8 ++- crates/engine/src/undo_memory.rs | 65 +++++++++++++++-- docs/user-guide/analysis.md | 37 ++++++---- 7 files changed, 208 insertions(+), 62 deletions(-) diff --git a/apps/rustgis-cli/tests/memory_override.rs b/apps/rustgis-cli/tests/memory_override.rs index 23ce239760..d330470ce6 100644 --- a/apps/rustgis-cli/tests/memory_override.rs +++ b/apps/rustgis-cli/tests/memory_override.rs @@ -30,10 +30,17 @@ 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 @@ -51,6 +58,8 @@ fn gp_env_says_what_is_held() { 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/data/src/io.rs b/crates/data/src/io.rs index 5e89074a13..0f135b6e6d 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -30,12 +30,13 @@ 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. Less once -/// RustGIS holds more than half the memory ([`crate::memory::share`], #2431), never below the floor. +/// 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_within(crate::memory::share(crate::memory::physical(), crate::memory::held())) + 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) with nothing held. The @@ -69,28 +70,30 @@ pub fn too_large(len: u64) -> String { /// [`too_large`] against the limit `max` taken when the read started. fn too_large_said(len: u64, max: u64) -> String { let memory = crate::memory::physical().filter(|_| bytes_ceiling() > BYTES_FLOOR); - // A test's own limit isn't lowered by what is held. - let held = if TEST_MAX.with(std::cell::Cell::get).is_some() { 0 } else { crate::memory::held() }; - too_large_held(len, max, memory, held) + // 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`: what is held is said when it lowered the limit (#2431), with the -/// limit when nothing is held and what to do. -fn too_large_held(len: u64, max: u64, memory: Option, held: u64) -> String { +/// 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)); }; let full = max_bytes_for(Some(memory)); - if held == 0 || max >= full { + 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 while RustGIS holds {} of its memory, {} with nothing held): remove layers or tables you no longer need, and save and reopen the project to let go of what Undo keeps of them, then try again", + "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) @@ -4805,18 +4808,23 @@ mod tests { 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); + 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 while RustGIS holds 40960 MiB of its memory, 2048 MiB with nothing held): remove layers or tables you no longer need, and save and reopen the project to let go of what Undo keeps of them, then try again" + "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 full = too_large_held(3 * GIB, 2 * GIB, Some(64 * GIB), GIB); + 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), full); - assert_eq!(too_large_held(GIB, 256 << 20, None, 40 * GIB), "file is too large (1024 MiB; the most read into memory is 256 MiB)"); + 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, @@ -4838,21 +4846,21 @@ mod tests { } // 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)), 512 << 20, "half held: unchanged"); - assert_eq!(max_bytes_within(crate::memory::share(Some(64 * GIB), 40 * GIB)), GIB); - assert_eq!(max_bytes_within(crate::memory::share(Some(16 * GIB), 12 * GIB)), 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. - let real = max_bytes(); + // 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 eb500bc8c4..f691c8e632 100644 --- a/crates/data/src/memory.rs +++ b/crates/data/src/memory.rs @@ -112,19 +112,60 @@ pub fn scaled(memory: Option, floor: usize, ceiling: usize, bytes: u64) -> } /// 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`]) taken off, 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. +/// [`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()), floor, ceiling, bytes) + 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: [`SHARE`] of it, or what is left of [`usable`] after what is held when that -/// is less. Up to half the memory held, it is the share. -pub fn share(memory: Option, held: u64) -> Option { +/// 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?; - Some((memory / SHARE).min(usable(Some(memory)).unwrap_or(0).saturating_sub(held))) + 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`. @@ -199,16 +240,29 @@ mod tests { #[test] fn a_job_plans_for_what_is_left_of_the_memory_once_half_is_held() { - assert_eq!(share(Some(16 * GIB), 0), Some(4 * GIB), "nothing held: the share"); - assert_eq!(share(Some(16 * GIB), 8 * GIB), Some(4 * GIB), "half held: still the share"); - assert_eq!(share(Some(16 * GIB), 10 * GIB), Some(2 * GIB), "what is left of three quarters"); - assert_eq!(share(Some(16 * GIB), 20 * GIB), Some(0), "more held than planned for: nothing"); - assert_eq!(share(None, 10 * GIB), None, "memory not known"); + 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), 100, 1 << 40, 8), 256 << 20); - assert_eq!(within(share(Some(16 * GIB), 12 * GIB), 100, 1 << 40, 8), 100, "never below the floor"); - assert_eq!(within(share(None, 12 * GIB), 100, 1 << 40, 8), 100); - assert_eq!(within(share(Some(1024 * GIB), 0), 100, 1_000, 8), 1_000); + 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] diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index b5941438e3..950e27ca62 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -481,6 +481,9 @@ fn environments(s: &mut Session, p: &Value) -> CmdResult { // 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). diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b538d87f80..b012cdfcb5 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -2009,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 ab8f46a9f2..843c3fec1c 100644 --- a/crates/engine/src/undo_memory.rs +++ b/crates/engine/src/undo_memory.rs @@ -31,6 +31,9 @@ pub(crate) struct Budget { 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, @@ -46,6 +49,8 @@ impl Default for Budget { 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(), } } @@ -123,7 +128,11 @@ impl Budget { /// 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: + /// 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: 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. Set aside: /// 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 @@ -134,17 +143,23 @@ impl Budget { 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 room = free.map(|free| free.saturating_sub(rustgis_data::memory::margin(memory))); let before = self.held(live, undo, redo); + let planned = |held: u64| held.saturating_add(running).saturating_add(copy) <= usable; + let fits = |held: u64| planned(held) && room.is_none_or(|room| copy <= room.saturating_add(before.saturating_sub(held))); 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)) { @@ -222,6 +237,16 @@ 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, @@ -335,6 +360,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 } @@ -535,6 +563,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(); } @@ -771,6 +800,32 @@ mod tests { 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"); + } + #[test] fn paste_special_is_not_measured_by_the_active_layer() { let mut session = session(4096); diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index c60df13f71..877ca10e76 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1558,17 +1558,27 @@ 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. -Once RustGIS holds more than half the memory, the limits below other than `threadScratchBytes`, -`undoBytes` and `projectBytes` plan for less: for what is -left of three quarters of the memory after what it holds, never below their floors. On a 16 GB -computer holding 10 GiB, they plan for 2 GiB instead of 4 GiB. 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. A file -refused for its size then says what is held, and the limit with nothing held. 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; never below the floors. +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 | |---|---|---|---| @@ -1590,14 +1600,15 @@ 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 used them, as a finished edit would have. A message says when steps are freed, the first time in a project. 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 +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 reloading or repairing a layer's data, and the From f2c251d35139e23b9abc19f0274a9d66fcbda4f2 Mon Sep 17 00:00:00 2001 From: strebdom Date: Thu, 19 Nov 2026 17:39:20 +0100 Subject: [PATCH 7/7] fix(engine): set-aside history doesn't make up for less free than the margin (#2431) An edit's copy must fit in what is free plus the history set aside, less the margin: set-aside steps no longer let an edit pass when less than the margin is free. The shapefile zip loop reads the file-size limit once. --- crates/data/src/io.rs | 16 ++++++++------ crates/engine/src/undo_memory.rs | 36 ++++++++++++++++++++++++-------- 2 files changed, 37 insertions(+), 15 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 0f135b6e6d..7949750b5c 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -67,7 +67,9 @@ 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 memory = crate::memory::physical().filter(|_| bytes_ceiling() > BYTES_FLOOR); // A test's own limit isn't lowered by what is held or free. @@ -2974,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); @@ -2986,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 { @@ -2999,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}")), } } diff --git a/crates/engine/src/undo_memory.rs b/crates/engine/src/undo_memory.rs index 3c32374a24..235987f611 100644 --- a/crates/engine/src/undo_memory.rs +++ b/crates/engine/src/undo_memory.rs @@ -130,13 +130,14 @@ impl Budget { /// holds, the copies of edits still running in the background and this copy pass the memory /// 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: 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. Set aside: - /// 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. + /// 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, @@ -148,10 +149,14 @@ impl Budget { let Some(usable) = rustgis_data::memory::usable(Some(memory)) else { return Ok(None) }; let running = self.in_flight.load(Ordering::Relaxed); let free = (self.free)(); - let room = free.map(|free| free.saturating_sub(rustgis_data::memory::margin(memory))); + 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; - let fits = |held: u64| planned(held) && room.is_none_or(|room| copy <= room.saturating_add(before.saturating_sub(held))); + // 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); } @@ -825,6 +830,19 @@ mod tests { 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