Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions crates/data/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,50 @@ pub struct Feature {
pub attrs: Vec<Value>,
}

mod rows_copy {
use std::cell::RefCell;

thread_local! {
static HOOK: RefCell<Option<Box<dyn FnOnce()>>> = 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<Option<Box<dyn FnOnce()>>>);

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<R>(hook: Box<dyn FnOnce()>, 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<R>(hook: Box<dyn FnOnce()>, f: impl FnOnce() -> R) -> (R, bool) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (quality, minor): every caller discards the bool this returns (let (res, _) = … in lib.rs and reads.rs, .0 in dispatch.rs), and the session decides what to say from the slot's state instead. Either return just R, which drops the fired computation in rows_copy::with, or use the flag somewhere. Left for the release quality pass if you prefer.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left for the release quality pass.

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.
Expand All @@ -231,21 +275,32 @@ impl Features {

/// The rows, taking them out of the share (copying them only when another copy holds them).
pub fn into_vec(self) -> Vec<Feature> {
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<Geometry>, attrs: Vec<Value>) {
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);
}

/// 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<Geometry>, attrs: Vec<Value>) {
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));
}
Expand All @@ -262,6 +317,7 @@ impl std::ops::DerefMut for Features {
fn deref_mut(&mut self) -> &mut Vec<Feature> {
// 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)
}
}
Expand Down
15 changes: 15 additions & 0 deletions crates/data/src/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u64>) -> Option<u64> {
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<u64>, floor: usize, ceiling: usize, bytes: u64) -> usize {
Expand All @@ -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));
Expand Down
10 changes: 9 additions & 1 deletion crates/engine/src/cmd/design.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) });
Expand Down Expand Up @@ -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);
Expand Down
4 changes: 4 additions & 0 deletions crates/engine/src/cmd/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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")?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug, same class elsewhere (confidence: high on the mechanism; it only matters under memory pressure): this pre-check is the right fix for setValue, but the rule it follows, "a failed edit gets its history back", is not yet true for the other handlers. get_mut goes through Features::deref_mut, which fires the copy hook before the row is checked. The sites this PR doesn't touch are outside the diff, so I can't anchor there:

  • crates/engine/src/cmd/design.rs:1154 (replace_geometry, reached by edit.setGeometry and the vertex edits): get_mut(row) runs before no such row. A row past the end frees the set-aside history, then fails.
  • crates/engine/src/cmd/design.rs:1081 (modify, reached by edit.move, edit.rotate and edit.scale): get_mut(r) runs for every selected row before the geometry is checked. A selection where nothing changes frees the history, then fails with "nothing selected can be changed this way".

Both should use get for the check and get_mut only once the change is known. A regression test for edit.setGeometry with an out-of-range row would cover the first.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1295c03. replace_geometry (Set Geometry and the vertex edits) checks the row with get before writing, and modify (Move, Rotate, Scale) reads each row with get and calls get_mut only for a row that changes. A new test, shape_edits_that_change_nothing_keep_the_history_set_aside_for_them, covers a Set Geometry of a row past the end and a Move that changes nothing. It fails without either fix.

The other handlers that write before their last check aren't changed one by one. Instead, the user guide now says what holds: an edit that fails before it starts copying gives the steps back, and one that fails after it started copying has used them, as a finished edit would have.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug (confidence about 60%). This pre-check covers the type, row and field checks, but design::apply (line 695) can still refuse the edit after the row is written. Its checks (calculation rules, validation, editing settings) run after get_mut at line 691 has fired the copy hook. guarded then restores the project, but the history set aside for this edit has already been freed. So a refused edit.setValue under memory pressure still spends Undo and Redo, and the notice says the steps were dropped "to make room for edits".

The earlier thread on lib.rs:1873 was answered "a handler-rejected edit gets them back". That holds for the checks before the write, not for this refusal, so I'm raising it again with that new evidence.

Options: run the design checks before get_mut, or word the notice so it doesn't say an edit was made when it was refused.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left as it is, and documented. A rule that refuses the edit after the row was written has already started the copy, so the steps set aside for it are spent, as they would be for an edit that went through. The user guide says so: "One that fails after it started copying has used them, as a finished edit would have." Moving every design::apply check before the first write would mean doing that in each handler; that belongs with the storage change discussed on #2431 (fix 4), where an edit stops copying the whole layer.

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")?;
Expand Down
76 changes: 71 additions & 5 deletions crates/engine/src/cmd/reads.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ pub struct Read {
pub(crate) source: Option<rustgis_map::source::SourceLayer>,
pub(crate) ready: Option<Ready>,
pub(crate) inputs: Vec<rustgis_data::provenance::Fingerprint>,
/// 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<crate::RoomMade>,
pub(crate) reservation: Option<crate::undo_memory::Reservation>,
}

/// A reader chosen only after the command and its original input have been admitted.
Expand Down Expand Up @@ -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<rustgis_data::Dataset>,
/// Set when the edit starts ([`Self::refresh_table_input`]), carried to its landing.
room: Option<crate::RoomMade>,
reservation: Option<crate::undo_memory::Reservation>,
/// The rows a layer edit's worker copies, as they were when it was prepared.
rows: Option<std::sync::Weak<Vec<rustgis_data::Feature>>>,
}

impl ReadAhead {
Expand All @@ -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<Self, String> {
///
/// 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, String> {
self.owner.check()?;
let mut ahead = self.refresh_input(s)?;
ahead.make_room(s)?;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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<Self, String> {
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) {
Expand All @@ -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)
Expand Down Expand Up @@ -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<rustgis_analysis::control::Control>) -> Result<Read, String> {
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());
Expand All @@ -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,
})
}
}

Expand Down Expand Up @@ -231,7 +292,12 @@ pub(crate) fn prepare(s: &mut Session, op: Authorized<CommandOp>, 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.
Expand Down
Loading
Loading