diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 44dfa796b6..7a07cbe127 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/data/src/memory.rs b/crates/data/src/memory.rs index 21b0688cf6..4bdef413a7 100644 --- a/crates/data/src/memory.rs +++ b/crates/data/src/memory.rs @@ -94,6 +94,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 { @@ -119,6 +127,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"); + } + #[test] fn the_override_is_a_positive_number_of_bytes() { assert_eq!(overridden(Some("8589934592")), Some(8 * GIB)); 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/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 77179a5afc..3548ccb741 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,11 @@ 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, + /// The rows a layer edit's worker copies, as they were when it was prepared. + rows: Option>>, } impl ReadAhead { @@ -83,8 +92,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) { @@ -96,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) @@ -123,7 +169,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 +178,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 +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() }) + // 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/lib.rs b/crates/engine/src/lib.rs index ef367863a1..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)); @@ -1818,8 +1853,23 @@ 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. + 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) @@ -1916,6 +1966,138 @@ 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 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 || self.undo_memory.memory.is_none() { + return Ok(None); + } + 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(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), + undo_memory::size_said(usable), + )), + } + } + + /// 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 41653e5a4e..a4b0b58ed2 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -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()), @@ -233,7 +236,11 @@ impl Session { } 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,6 +252,12 @@ 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), diff --git a/crates/engine/src/undo_memory.rs b/crates/engine/src/undo_memory.rs index a414912ca4..e7c2d8f838 100644 --- a/crates/engine/src/undo_memory.rs +++ b/crates/engine/src/undo_memory.rs @@ -1,10 +1,13 @@ //! 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, - sync::Weak, + sync::{ + Arc, Mutex, Weak, + atomic::{AtomicU64, Ordering}, + }, }; type Key = Weak>; @@ -19,6 +22,13 @@ 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, + // 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, @@ -26,7 +36,15 @@ 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, + in_flight: Arc::default(), + estimates: HashMap::new(), + } } } @@ -34,6 +52,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 +87,79 @@ 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, the copies of edits still running in the background and this copy pass the memory + /// it plans to use ([`rustgis_data::memory::usable`]), history is set aside until they fit: + /// Redo first, farthest first, as the edit clears it anyway, then Undo, oldest first. What is + /// set aside is freed just before the edit copies, or given back if it never does + /// ([`Session::put_back`](crate::Session)), and counted as held until then. `Err` gives what is held and the memory planned + /// for, with the history left as it is, when the copy wouldn't fit even with the history gone. + 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 running = self.in_flight.load(Ordering::Relaxed); + let fits = |held: u64| held.saturating_add(running).saturating_add(copy) <= usable; + let before = self.held(live, undo, redo); + if fits(before) { + return Ok(None); + } + let open = self.held(live, &[], &[]); + if !fits(open) { + return Err((open.saturating_add(running), usable)); + } + let mut aside = Aside::default(); + while !fits(self.held(live, undo, redo)) { + if !redo.is_empty() { + aside.redo.push(redo.remove(0)); + } else if undo.is_empty() { + break; + } else { + 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)) + } + + /// 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 + /// 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 +179,76 @@ 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, + /// 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 { + 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(); + 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 +265,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 +402,345 @@ 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"); + } + + /// 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"))] + fn table_session() -> Session { + let mut session = Session::new(crate::Project::default()); + 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}); + 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); + 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(); + // 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(); + 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(), 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(), 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"))] + #[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 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); + 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] + 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); + session.undo_memory.memory = Some(4); + let id = Some(session.map().layer_by_name("rows").unwrap().id); + 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 f154a422f2..9d9bc468b0 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1575,6 +1575,23 @@ 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, 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. 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 +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 on a grid of any coordinate system, cell size and extent, and Polygons to Raster