From 0d294cdefe23f9c34e11433c1ed3ff004197f39c Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sat, 28 Nov 2026 01:12:59 -0300 Subject: [PATCH 1/4] feat(plugins): a plugin command's cube.reduce on a STAC collection runs off the frame (#3183) A plugin command the app runs that calls cube.reduce or cube.trend over a STAC collection no longer holds the window while the slices are read. The call checks its parameters and searches the collection as before, answers {"pending": true}, and leaves the read as a call request. The command is undone quietly, the read runs on a thread of its own with its progress and Cancel in the status bar, and the command runs again once it has landed, when the same call adds the held layers in the command's own undo step. Cancel or a failed read is that call's error. Several reads in one call run one after another, with one rerun. The command line, scripts, the assistant and Python wait for the read as before. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/cube.rs | 15 + crates/engine/src/cmd/plugin_fetch.rs | 45 ++- crates/engine/src/cmd/plugin_summary.rs | 379 ++++++++++++++++++++ crates/engine/src/cmd/plugins.rs | 11 + crates/engine/src/lib.rs | 4 + crates/engine/src/tests.rs | 3 + crates/engine/src/tests/plugin_summaries.rs | 178 +++++++++ crates/plugins/src/testing.rs | 39 ++ crates/ui-egui/src/chrome.rs | 40 ++- crates/ui-egui/src/pluginstart.rs | 36 +- docs/plugins.md | 12 + 11 files changed, 750 insertions(+), 12 deletions(-) create mode 100644 crates/engine/src/cmd/plugin_summary.rs create mode 100644 crates/engine/src/tests/plugin_summaries.rs diff --git a/crates/engine/src/cmd/cube.rs b/crates/engine/src/cmd/cube.rs index 212fc4ddb7..b234c1c712 100644 --- a/crates/engine/src/cmd/cube.rs +++ b/crates/engine/src/cmd/cube.rs @@ -1094,6 +1094,14 @@ fn trend_cmd(s: &mut Session, p: &Value) -> CmdResult { let (_, rasters, dates) = s.trend_results.remove(at); return add_outputs(s, rasters, dates); } + // A plugin's command the app runs reads a STAC collection off the frame (#3183), with the + // panes' bound, as the Workflows pane's thread does. + if let Some(left) = super::plugins::summary::left(s, "cube.trend", p, |s| { + let run = trend_start(s, p)?; + Ok(super::plugins::summary::Work::new(run.total(), run.dates(), move |cancel, done| run.run(cancel, done))) + }) { + return left; + } // Worked out here, waited for with no Cancel: in the app (a script, the assistant) and Python a // run of seconds, not minutes; where only a shell waits on it (`rustgis-cli run`), the panes' // bound, its progress told. @@ -2205,6 +2213,13 @@ pub fn reduce_start(s: &mut Session, p: &Value) -> Result { /// `cube.reduce`: the summary computed here (blocking), its progress told where only a shell waits /// on it (`rustgis-cli run`), its layers added, each kept in the project as a GeoTIFF. fn reduce_cmd(s: &mut Session, p: &Value) -> CmdResult { + // A plugin's command the app runs reads a STAC collection off the frame (#3183). + if let Some(left) = super::plugins::summary::left(s, "cube.reduce", p, |s| { + let run = reduce_start(s, p)?; + Ok(super::plugins::summary::Work::new(run.total(), run.dates(), move |cancel, done| run.run(cancel, done))) + }) { + return left; + } let run = reduce_start(s, p)?; let rasters = run_here(s.long_runs, "cube.reduce", run.total(), |cancel, done| run.run(cancel, done))?; let added = add_outputs(s, rasters, run.dates()); diff --git a/crates/engine/src/cmd/plugin_fetch.rs b/crates/engine/src/cmd/plugin_fetch.rs index 54582c3364..6fa0d45784 100644 --- a/crates/engine/src/cmd/plugin_fetch.rs +++ b/crates/engine/src/cmd/plugin_fetch.rs @@ -22,7 +22,9 @@ //! //! A plugin command's `service.add` on the desktop waits the same way (#1319): the documents it //! reads are fetched off the frame ([`Session::left_document`]), and its features or coverage are -//! left to the app as `layer.addUrl`'s download is. +//! left to the app as `layer.addUrl`'s download is. So does its `cube.reduce` or `cube.trend` on a +//! STAC collection (#3183): the slices are read on a thread of the session's (see +//! [`super::summary`]). use std::collections::VecDeque; use std::sync::{Arc, Mutex}; @@ -435,7 +437,7 @@ pub(crate) struct UrlWaits { pub(crate) views: std::collections::BTreeMap, owners: std::collections::BTreeMap, in_flight: Vec<(u64, Value, Instant)>, - landed: Vec<(u64, Value, CmdResult, Added)>, + pub(super) landed: Vec<(u64, Value, CmdResult, Added)>, /// Requests given up (past [`REQUEST_WAIT`], or their command replaced or dropped), with their /// addresses (about [`MAX_EXPIRED`] at most, see `remember_given_up`): one that lands after is /// refused, not added with no command left to go on with it. @@ -446,6 +448,8 @@ pub(crate) struct UrlWaits { added: VecDeque<(u64, Value)>, /// A service's documents being read off the frame, by request number. reading: Vec<(u64, String, Arc, String>>>>)>, + /// Data cubes' summaries being read off the frame ([`super::summary`]). + pub(super) summaries: Vec, } /// What adding a landed download added, to tell when its command runs again whether it is still @@ -463,6 +467,8 @@ pub(crate) struct Added { pub(crate) map: u64, /// A service's document read off the frame ([`Session::left_document`]), which adds nothing. pub(crate) document: Option>, + /// A data cube's summary read off the frame ([`super::summary`]), which its command adds. + pub(crate) summary: Option, } impl Added { @@ -482,7 +488,12 @@ impl Added { (None, Some(i)) => usize::try_from(i).ok().and_then(|i| map.tiles.get(i)).cloned().into_iter().collect(), _ => Vec::new(), }; - Added { layers, tiles, map: at, document: None } + Added { layers, tiles, map: at, document: None, summary: None } + } + + /// What a data cube's summary read off the frame made: no layer yet, its command adds them. + pub(super) fn of_summary(summary: super::summary::Summary) -> Added { + Added { summary: Some(summary), ..Added::default() } } /// `answer` as it stands in `map` now: a tile layer's place in the list, which moves as others @@ -551,6 +562,10 @@ const MAX_EXPIRED: usize = 1024; /// the address the front end downloads, with the range marked in it /// ([`crate::cmd::layer::ranged_address`]), and its rows of a box (`"bbox"`) with the box too. fn asked_by(asked: &Value, params: &Value) -> bool { + // A summary read off the frame has no address: no front end's download is it. + if super::summary::is_summary(asked) { + return false; + } let Some(o) = asked.as_object() else { return false }; let range = match asked.get("bytes").and_then(Value::as_array).map(Vec::as_slice) { Some([a, b]) => a.as_u64().zip(b.as_u64()), @@ -633,8 +648,8 @@ impl UrlWaits { pub(crate) fn land(&mut self, n: u64, answer: CmdResult, added: Added) { if let Some(i) = self.in_flight.iter().position(|(m, ..)| *m == n) { let (_, asked, _) = self.in_flight.remove(i); - // (A document adds nothing, and no front end lands it again by its number.) - if answer.is_ok() && added.document.is_none() { + // (A document or a summary adds nothing, and no front end lands it again by its number.) + if answer.is_ok() && added.document.is_none() && added.summary.is_none() { if self.added.len() >= MAX_EXPIRED { self.added.pop_front(); } @@ -650,7 +665,7 @@ impl UrlWaits { } /// Waits for request `n`, which asked for `asked`. - fn wait(&mut self, n: u64, asked: Value) { + pub(super) fn wait(&mut self, n: u64, asked: Value) { if !self.has(n) { self.in_flight.push((n, asked, Instant::now())); } @@ -663,7 +678,8 @@ impl UrlWaits { let late: Vec<(u64, Value)> = self .in_flight .iter() - .filter(|(.., at)| now.saturating_duration_since(*at) >= REQUEST_WAIT) + // A summary still being read has its own end, and its Cancel. + .filter(|(n, _, at)| now.saturating_duration_since(*at) >= REQUEST_WAIT && !self.summarising(*n)) .map(|(n, q, _)| (*n, q.clone())) .collect(); let mut addresses = Vec::new(); @@ -679,6 +695,9 @@ impl UrlWaits { /// so a late landing is refused. /// `taken`: whether the front end took it (it may still land); one it didn't is just forgotten. fn give_up(&mut self, n: u64, taken: bool) { + // A summary being read is stopped, and never lands: there is nothing to refuse later. + let taken = taken && !self.summarising(n); + self.stop_summaries(|m| m != n); if let Some(i) = self.in_flight.iter().position(|(m, ..)| *m == n) { let (_, asked, _) = self.in_flight.remove(i); if taken { @@ -760,6 +779,7 @@ impl UrlWaits { self.in_flight.retain(|(n, ..)| wanted(n)); self.landed.retain(|(n, ..)| wanted(n)); self.views.retain(|n, _| wanted(n)); + self.stop_summaries(|n| wanted(&n)); let retained: Vec = self .in_flight .iter() @@ -970,8 +990,14 @@ impl Session { if !fetching.is_empty() { answer["fetching"] = json!(fetching); } - if !requests.is_empty() { - answer["downloading"] = json!(requests.iter().map(|(_, q)| q["url"].as_str().map(crate::sources::redact)).collect::>()); + let (summaries, downloads): (Vec<&(u64, Value)>, Vec<&(u64, Value)>) = + requests.iter().partition(|(_, q)| super::summary::is_summary(q)); + if !downloads.is_empty() { + answer["downloading"] = json!(downloads.iter().map(|(_, q)| q["url"].as_str().map(crate::sources::redact)).collect::>()); + } + // A summary read off the frame, by its command's name. + if !summaries.is_empty() { + answer["reading"] = json!(summaries.iter().map(|(_, q)| q["summary"].clone()).collect::>()); } let numbers = requests.iter().map(|(n, _)| *n).collect(); for (n, asked) in requests { @@ -1053,6 +1079,7 @@ impl Session { /// by then are given up (a test passes a later time instead of backdating the waits). fn poll_plugin_retries_at(&mut self, now: Instant) -> Vec<(String, CmdResult)> { self.url_waits.documents_in(); + self.url_waits.summaries_in(); if self.plugin_retries.is_empty() { self.url_waits.prune_views(); return Vec::new(); diff --git a/crates/engine/src/cmd/plugin_summary.rs b/crates/engine/src/cmd/plugin_summary.rs new file mode 100644 index 0000000000..ba994c7df1 --- /dev/null +++ b/crates/engine/src/cmd/plugin_summary.rs @@ -0,0 +1,379 @@ +//! A plugin command's `cube.reduce` or `cube.trend` on a STAC collection, run by the app, reads +//! its slices off the frame (#3183), as a download the command leaves to the app does (#1202). +//! +//! The call checks its parameters and searches the collection as before, then answers +//! `{"pending": true}` and leaves the read to the app: whatever the command did is undone +//! quietly, the read runs on a thread of its own (its progress and Cancel in the status bar, +//! naming the plugin's command), and the command runs again from the start once it has landed. +//! That run's call, with the same parameters, adds what was read at once. Several in one call are +//! read one after another, and the command runs again once all have landed. Cancel, or a read that +//! failed, is that call's answer in the run again, and the plugin says it as it says any error. +//! +//! Only a plugin's command the app runs ([`Session::run_leaving_downloads`]) leaves the read: the +//! command line, scripts, the assistant and Python wait for it, as before, and layers, bands and +//! Zarr stores, quick to read, are read where the call is made. + +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +use rustgis_data::raster::Raster; +use serde_json::{Value, json}; + +use crate::render::rustgis_tiles::cache; +use crate::{CmdResult, Session}; + +/// The most summaries plugin commands may have left to read at once: each holds its layers until +/// its command has run again. +pub const MAX_SUMMARIES: usize = 4; + +/// The key a summary's request names its command by (`{"summary": "cube.reduce", "params": …}`), +/// which no download's request has with no address. +const SUMMARY: &str = "summary"; + +/// What a summary's thread does: the slices read and folded, `done` counting them and `cancel` +/// stopping it between them. +type Run = Box Result, String> + Send>; + +/// A summary (or a trend) prepared on the session: it reads nothing more of it, so it runs on any +/// thread. +pub(crate) struct Work { + total: usize, + dates: usize, + run: Run, +} + +impl Work { + /// `run`, `total` steps of work, of `dates` dates. + pub(crate) fn new( + total: usize, + dates: usize, + run: impl FnOnce(&AtomicBool, &AtomicUsize) -> Result, String> + Send + 'static, + ) -> Work { + Work { total, dates, run: Box::new(run) } + } +} + +/// A summary the plugin call running now left, held until the call is kept to run again. +pub(crate) struct Left { + n: u64, + command: &'static str, + work: Work, + /// The call's request context, which the reads on the thread keep: they stop once its plugin + /// or project is gone, and a plugin's are held to the internet as its call's are. + still: Option, + capture: rustgis_data::diagnostics::Capture, +} + +impl Left { + /// Its request's number. + pub(crate) fn number(&self) -> u64 { + self.n + } +} + +/// A summary being read off the frame, shared with its thread. +#[derive(Clone)] +pub(crate) struct Reading { + n: u64, + /// The plugin command it is read for. + owner: String, + total: usize, + cancel: Arc, + done: Arc, + slot: Arc, usize), String>>>>, +} + +/// What a summary read off the frame made (its layers, and how many dates), held for its command's +/// run again, which adds a copy of it: a run waiting again, for another read, adds it again. +#[derive(Clone)] +pub(crate) struct Summary(Arc<(Vec, usize)>); + +impl std::fmt::Debug for Summary { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Summary({} layers of {} dates)", self.0.0.len(), self.0.1) + } +} + +impl PartialEq for Summary { + fn eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) + } +} + +/// A summary under way, as the status bar shows it. +#[derive(Clone, Debug, PartialEq)] +pub struct UnderWay { + pub id: u64, + /// The plugin command it is read for (`plugin:/`). + pub command: String, + /// The slices read, and how many there are. + pub done: usize, + pub total: usize, + pub cancelled: bool, +} + +/// Whether a request asks for a summary read off the frame, rather than for a download or a +/// service's document (which have an address). +pub(crate) fn is_summary(q: &Value) -> bool { + q.get("url").is_none() && matches!(q.get(SUMMARY).and_then(Value::as_str), Some("cube.reduce" | "cube.trend")) +} + +/// The request for `command` with `p`. +fn asked(command: &str, p: &Value) -> Value { + json!({SUMMARY: command, "params": p}) +} + +/// Whether `command` with `p` leaves its read off the frame: a plugin's call the app runs (on the +/// desktop) that reads a STAC collection, by itself or through a catalogue's entry. +fn defers(s: &Session, p: &Value) -> bool { + let given = |p: &Value, k: &str| p.get(k).is_some_and(|v| !v.is_null()); + cfg!(not(target_arch = "wasm32")) + && s.leave_downloads + && s.call_requests.is_some() + && crate::cmd::cube_catalog::with_entry(p).is_ok_and(|p| given(&p, "collection") && !given(&p, "layers")) +} + +/// `command` with `p` (`cube.reduce`, `cube.trend`) when its read is left off the frame +/// ([`defers`]): what was read, added, in the command's run again; else `{"pending": true}`, the +/// read prepared by `start` to begin once the call is kept. `None` when it is read here. +pub(crate) fn left( + s: &mut Session, + command: &'static str, + p: &Value, + start: impl FnOnce(&mut Session) -> Result, +) -> Option { + defers(s, p).then(|| s.left_summary(command, p, start)) +} + +/// The cancelled read's error, which its command's call answers. +fn cancelled(command: &str) -> String { + format!("{command} was cancelled") +} + +/// One summary read at a time: each takes the threads the app reads and computes with. +static TURN: Mutex<()> = Mutex::new(()); + +/// Tests: holds the summaries back, so one is cancelled before it starts. +#[cfg(test)] +pub(crate) fn hold_turn() -> std::sync::MutexGuard<'static, ()> { + TURN.lock().unwrap_or_else(|e| e.into_inner()) +} + +impl Session { + fn left_summary(&mut self, command: &'static str, p: &Value, start: impl FnOnce(&mut Session) -> Result) -> CmdResult { + let asked = asked(command, p); + if let Some((answer, added)) = self.rerun_answer(&asked) { + let held = answer.and_then(|_| added.summary.ok_or_else(|| format!("{command}: nothing was read")))?; + let (rasters, dates) = held.0.as_ref().clone(); + return super::super::cube::add_outputs(self, rasters, dates); + } + // Asked for already in this call, or by a run before it for the same caller: that read, + // not another (as a document's is, `left_document`). + let caller = self.continuation().ok(); + let owns = |n: u64| { + caller.as_ref().is_some_and(|c| { + self.url_waits.owner(n).is_some_and(|owner| self.same_url_caller(owner, c) && self.check_continuation(owner).is_ok()) + }) + }; + let now = self.call_requests.as_deref().unwrap_or_default(); + let known = now + .iter() + .find(|(_, q)| super::fetch::same_request(q, &asked)) + .map(|(n, _)| *n) + .or_else(|| self.url_waits.in_flight(&asked, owns)); + let number = match known { + Some(n) => n, + None => { + let reading = self.url_waits.summaries.len() + now.iter().filter(|(_, q)| is_summary(q)).count(); + if reading >= MAX_SUMMARIES { + return Err(format!( + "{MAX_SUMMARIES} data cube summaries are already being read for plugin commands; try again when they have come" + )); + } + let work = start(self)?; + self.next_request += 1; + let n = self.next_request; + let (still, capture) = (cache::current_still(), rustgis_data::diagnostics::Capture::current()); + self.call_summaries.push(Left { n, command, work, still, capture }); + n + } + }; + if let Some(asked_now) = self.call_requests.as_mut() + && !asked_now.iter().any(|(n, _)| *n == number) + { + asked_now.push((number, asked)); + } + Ok(json!({"pending": true})) + } + + /// The summaries plugin commands left to read off the frame, under way. + pub fn plugin_summaries(&self) -> Vec { + self.url_waits + .summaries + .iter() + .map(|r| UnderWay { + id: r.n, + command: r.owner.clone(), + done: r.done.load(Ordering::Relaxed).min(r.total), + total: r.total, + cancelled: r.cancel.load(Ordering::Relaxed), + }) + .collect() + } + + /// Stops summary `id` between two slices: its command runs again, its call answering that it + /// was cancelled. + pub fn cancel_plugin_summary(&mut self, id: u64) { + if let Some(r) = self.url_waits.summaries.iter().find(|r| r.n == id) { + r.cancel.store(true, Ordering::Relaxed); + } + } + + /// Tests in other crates: a summary under way for plugin command `owner`, read until it is + /// cancelled (one of its 4 slices read), and its number. Only in a test build. + #[cfg(all(feature = "testing", debug_assertions))] + #[doc(hidden)] + pub fn start_test_summary(&mut self, owner: &str) -> u64 { + let work = Work::new(4, 4, |cancel: &AtomicBool, done: &AtomicUsize| { + done.store(1, Ordering::Relaxed); + while !cancel.load(Ordering::Relaxed) { + std::thread::sleep(std::time::Duration::from_millis(5)); // test-wait: a read that lasts until it is cancelled + } + Ok(Vec::new()) + }); + self.next_request += 1; + let n = self.next_request; + self.url_waits.read_summary( + Left { n, command: "cube.reduce", work, still: None, capture: rustgis_data::diagnostics::Capture::current() }, + owner, + ); + n + } +} + +impl super::fetch::UrlWaits { + /// Starts reading `left` off the frame for plugin command `owner`, after the summaries + /// started before it. + pub(crate) fn read_summary(&mut self, left: Left, owner: &str) { + let Left { n, command, work, still, capture } = left; + let Work { total, dates, run } = work; + let reading = Reading { + n, + owner: owner.to_string(), + total: total.max(1), + cancel: Arc::default(), + done: Arc::default(), + slot: Arc::default(), + }; + let (cancel, done, slot) = (reading.cancel.clone(), reading.done.clone(), reading.slot.clone()); + let spawned = std::thread::Builder::new().name("cube summary".into()).spawn(move || { + let _turn = TURN.lock().unwrap_or_else(|e| e.into_inner()); + let out = if cancel.load(Ordering::Relaxed) { + Err(cancelled(command)) + } else { + // A bug in the read, as one in a tool, must not take the app down. + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + cache::with_optional_still(still, || { + let _diagnostics = capture.enter(); + run(&cancel, &done) + }) + })) + .unwrap_or_else(|_| Err(format!("{command} failed unexpectedly"))); + if cancel.load(Ordering::Relaxed) { Err(cancelled(command)) } else { r } + }; + *slot.lock().unwrap_or_else(|e| e.into_inner()) = Some(out.map(|rasters| (rasters, dates))); + }); + if let Err(e) = spawned { + *reading.slot.lock().unwrap_or_else(|e| e.into_inner()) = Some(Err(format!("{command} couldn't start: {e}"))); + } + self.summaries.push(reading); + } + + /// Lands the summaries read by now. One whose command gave up is dropped, and forgotten. + pub(super) fn summaries_in(&mut self) { + for r in std::mem::take(&mut self.summaries) { + let out = r.slot.lock().unwrap_or_else(|e| e.into_inner()).take(); + let Some(out) = out else { + self.summaries.push(r); + continue; + }; + match out { + Ok(held) => { + self.land(r.n, Ok(json!({})), super::fetch::Added::of_summary(Summary(Arc::new(held)))); + } + Err(e) => self.land(r.n, Err(e), super::fetch::Added::default()), + } + self.refused(r.n); + } + } + + /// Whether request `n` is a summary still being read: it isn't given up for taking long. + pub(super) fn summarising(&self, n: u64) -> bool { + self.summaries.iter().any(|r| r.n == n) + } + + /// Stops and forgets the summaries no command waits for any more (`wanted`). + pub(super) fn stop_summaries(&mut self, wanted: impl Fn(u64) -> bool) { + self.summaries.retain(|r| { + let keep = wanted(r.n); + if !keep { + r.cancel.store(true, Ordering::Relaxed); + } + keep + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A summary's request has no address, so no front end's download lands it, and a download's + /// request, whatever it carries, isn't one. + #[test] + fn a_summary_is_no_download() { + let q = asked("cube.reduce", &json!({"collection": "s2"})); + assert!(is_summary(&q) && is_summary(&asked("cube.trend", &json!({})))); + assert!(!is_summary(&json!({"url": "https://x.org/a.csv", "summary": "cube.reduce"}))); + assert!(!is_summary(&json!({"summary": "layer.addUrl"}))); + let mut waits = super::super::fetch::UrlWaits::default(); + waits.wait(7, q); + assert!(!waits.holds(7, &json!({"url": "https://x.org/a.csv", "request": 7}))); + assert!(!waits.holds(7, &json!({"request": 7}))); + } + + /// A summary read off the frame lands for the command waiting for it, a cancelled one as its + /// error; one no command waits for any more is stopped. + #[test] + fn summaries_land_or_are_stopped() { + let mut waits = super::super::fetch::UrlWaits::default(); + let work = |rasters: Vec| { + Work::new(2, 2, move |_: &AtomicBool, done: &AtomicUsize| { + done.fetch_add(2, Ordering::Relaxed); + Ok(rasters) + }) + }; + let left = |n, work| Left { n, command: "cube.reduce", work, still: None, capture: rustgis_data::diagnostics::Capture::current() }; + for n in 1..=3 { + waits.wait(n, asked("cube.reduce", &json!({"n": n}))); + } + // The third waits for the second's turn, which waits for the test's. + let turn = TURN.lock().unwrap_or_else(|e| e.into_inner()); + waits.read_summary(left(1, work(Vec::new())), "plugin:p/f"); + waits.read_summary(left(2, work(Vec::new())), "plugin:p/f"); + waits.read_summary(left(3, work(Vec::new())), "plugin:p/g"); + waits.summaries.iter().find(|r| r.n == 2).unwrap().cancel.store(true, Ordering::Relaxed); + waits.stop_summaries(|n| n != 3); + assert_eq!(waits.summaries.len(), 2); + drop(turn); + let started = web_time::Instant::now(); + while !waits.summaries.is_empty() && started.elapsed() < web_time::Duration::from_secs(30) { + waits.summaries_in(); + std::thread::sleep(std::time::Duration::from_millis(5)); // test-wait: the reads land on their threads, polled as the frame loop polls them + } + let landed = |n: u64| waits.landed.iter().find(|(m, ..)| *m == n).map(|(_, _, answer, added)| (answer.clone(), added.clone())); + assert!(landed(1).is_some_and(|(answer, added)| answer.is_ok() && added.summary.is_some())); + assert_eq!(landed(2).map(|(answer, _)| answer), Some(Err("cube.reduce was cancelled".to_string()))); + assert!(landed(3).is_none(), "stopped, and not landed"); + } +} diff --git a/crates/engine/src/cmd/plugins.rs b/crates/engine/src/cmd/plugins.rs index ad5be9231d..dc9ac4d178 100644 --- a/crates/engine/src/cmd/plugins.rs +++ b/crates/engine/src/cmd/plugins.rs @@ -16,6 +16,8 @@ use crate::{CmdResult, CommandSpec as C, Session}; #[path = "plugin_fetch.rs"] pub mod fetch; +#[path = "plugin_summary.rs"] +pub mod summary; pub fn commands() -> Vec { vec![ @@ -921,6 +923,7 @@ impl Session { let queued_before = self.queued_authority(); // The downloads this call leaves to the app: its own, apart from a calling command's. let outer = self.call_requests.replace(Vec::new()); + let outer_summaries = std::mem::take(&mut self.call_summaries); let mark = self.notice_mark(); let res = self.guarded(label, mutates, |s| { let fetches = fetch::Calls::for_plugin(&plugin.manifest.id); @@ -975,6 +978,8 @@ impl Session { } } self.call_requests = outer; + // The summaries this call left to read off the frame (#3183), read once it is kept. + let summaries = std::mem::replace(&mut self.call_summaries, outer_summaries); // A session's program this command found failed, and started again: the command line // has no poll, so this is where it hears of it. #[cfg(not(target_arch = "wasm32"))] @@ -1000,6 +1005,9 @@ impl Session { // and with no command waiting nothing would take it. let documents: Vec<(u64, Value)> = requested.iter().filter(|(n, asked)| !giving_up && fetch::is_document(asked) && !self.url_waits.has(*n)).cloned().collect(); + // So is a summary this call left (one asked for again is already being read). + let summarised: Vec = + requested.iter().filter(|(_, asked)| !giving_up && summary::is_summary(asked)).map(|(n, _)| *n).collect(); // The errors this run said stay: the next run, doing the same again, doesn't repeat them. let earlier = self.rerun_said.len(); let said: Vec = self.notices_since(mark).iter().filter(|n| n.error).map(|n| n.text.clone()).collect(); @@ -1014,6 +1022,9 @@ impl Session { for (n, asked) in &documents { self.url_waits.read_document(*n, asked); } + for left in summaries.into_iter().filter(|l| summarised.contains(&l.number())) { + self.url_waits.read_summary(left, id); + } } res } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 042518e237..a8b861240c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1150,6 +1150,9 @@ pub struct Session { /// The download requests of the plugin call running now (none outside one): each one's /// number, and what was asked. pub(crate) call_requests: Option>, + /// The data cube summaries the plugin call running now left to read off the frame (#3183), + /// until the call is kept to run again. + pub(crate) call_summaries: Vec, /// While a plugin command runs again for its downloads: what each one asked for, and what /// adding it answered, for its `layer.addUrl` to answer once. pub(crate) rerun_landed: Vec<(serde_json::Value, CmdResult, cmd::plugins::fetch::Added)>, @@ -1612,6 +1615,7 @@ impl Session { url_waits: cmd::plugins::fetch::UrlWaits::default(), next_request: 0, call_requests: None, + call_summaries: Vec::new(), rerun_landed: Vec::new(), rerun_told: Vec::new(), rerun_said: Vec::new(), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 337abec2af..1f2ec26420 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -46,6 +46,9 @@ mod cube_mask; #[cfg(not(target_arch = "wasm32"))] #[path = "tests/cube_rgb.rs"] mod cube_rgb; +#[cfg(not(target_arch = "wasm32"))] +#[path = "tests/plugin_summaries.rs"] +mod plugin_summaries; #[path = "tests/permission_policy.rs"] mod permission_policy; diff --git a/crates/engine/src/tests/plugin_summaries.rs b/crates/engine/src/tests/plugin_summaries.rs new file mode 100644 index 0000000000..295ad3ba9f --- /dev/null +++ b/crates/engine/src/tests/plugin_summaries.rs @@ -0,0 +1,178 @@ +//! A plugin command's `cube.reduce` or `cube.trend` on a STAC collection, run by the app, reads its +//! slices off the frame, and the command runs again once they have landed (#3183). +use super::*; + +/// A collection "s2" of `dates` dates of a 4 × 4 band over [10, 11] × [45, 46], date k's cells all +/// 10 (k + 1): its STAC API's address. +fn collection(dates: usize) -> String { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + let band = |k: usize| { + let t = GeoTransform { origin_x: 10.0, origin_y: 46.0, pixel_width: 0.25, pixel_height: -0.25 }; + let r = Raster::new("r", 4, 4, vec![vec![10.0 * (k + 1) as f32; 16]], t, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + rustgis_data::raster::cogwrite::write(&r, 0).unwrap() + }; + let (files, _) = serve_ranged_files((0..dates).map(|k| (format!("/b{k}.tif"), band(k))).collect()); + let features: Vec = (0..dates) + .map(|k| { + let d = format!("2024-{:02}-01", k + 1); + format!( + r#"{{"type": "Feature", "id": "s{k}", "collection": "s2", "bbox": [10, 45, 11, 46], "geometry": null, + "properties": {{"datetime": "{d}T00:00:00Z", "bdc:tiles": ["t1"]}}, + "assets": {{"B04": {{"href": "{files}/b{k}.tif"}}}}}}"# + ) + }) + .collect(); + let search = format!(r#"{{"type": "FeatureCollection", "features": [{}]}}"#, features.join(",")); + format!("{}/v1", serve_routes(vec![("/v1/search", search)], 64)) +} + +/// `cube.reduce`'s parameters for the collection at `api`, with `stat`. +fn reduce(api: &str, stat: &str) -> Value { + json!({"url": api, "collection": "s2", "asset": "B04", "bbox": [10, 45, 11, 46], "start": "2024-01-01", "end": "2024-12-31", "stat": stat}) +} + +/// The plugin commands run again once their reads have landed, waited for (they read on threads). +fn ran_again(s: &mut Session) -> Vec<(String, crate::CmdResult)> { + let started = web_time::Instant::now(); + loop { + let ran = s.poll_plugin_retries(); + if !ran.is_empty() || started.elapsed() > web_time::Duration::from_secs(60) { + return ran; + } + std::thread::sleep(std::time::Duration::from_millis(10)); // test-wait: the reads land on their threads, polled as the frame loop polls them + } +} + +/// The first cell of layer `id`'s first band. +fn first_cell(s: &Session, id: &Value) -> f32 { + let l = s.map().layer(u32::try_from(id.as_u64().unwrap()).unwrap()).unwrap(); + l.raster.as_ref().unwrap().data.as_ref().unwrap().bands[0].data[0] +} + +/// The call answers pending and adds nothing; the read runs off the frame, named for the plugin's +/// command, and the command runs again once it has landed, adding the layer as one undo step. +/// Clicked again meanwhile, it waits for the same read. Run another way (the command line, a +/// script), the same command waits for the read, and a summary of layers is read in the call. +#[test] +fn a_plugins_summary_of_a_collection_is_read_off_the_frame() { + let mut s = world(); + plugin("eng-summary", &["edit", "files", "network"]); + // Its collection is served from this computer. + fetch_mode(true, true); + let api = collection(3); + let (undo, layers) = (s.undo.len(), s.map().layers.len()); + let p = json!({"op": "cube.reduce", "params": reduce(&api, "mean")}); + assert_eq!(s.run_leaving_downloads("plugin:eng-summary/f", &p).unwrap(), json!({"pending": true, "reading": ["cube.reduce"]})); + assert_eq!((s.undo.len(), s.map().layers.len()), (undo, layers), "nothing added, and no undo step"); + assert!(s.take_url_requests().is_empty(), "nothing for the app to download"); + let under_way = s.plugin_summaries(); + assert_eq!(under_way.len(), 1); + assert_eq!(under_way[0].command, "plugin:eng-summary/f"); + s.run_leaving_downloads("plugin:eng-summary/f", &p).unwrap(); + assert_eq!(s.plugin_summaries().len(), 1, "clicked again, the same read"); + let ran = ran_again(&mut s); + assert_eq!(ran.len(), 1, "{ran:?}"); + assert_eq!(ran[0].0, "plugin:eng-summary/f"); + let answer = ran[0].1.as_ref().unwrap(); + assert_eq!(answer["dates"], 3, "{answer}"); + assert_eq!(first_cell(&s, &answer["layers"][0]), 20.0, "the mean of 10, 20 and 30"); + assert_eq!((s.undo.len(), s.map().layers.len()), (undo + 1, layers + 1), "one layer, one undo step"); + assert!(s.plugin_summaries().is_empty() && !s.plugin_retries_waiting()); + assert!(s.poll_plugin_retries().is_empty(), "run once"); + // Run another way, it waits for the read. + let max = s.run("plugin:eng-summary/f", &json!({"op": "cube.reduce", "params": reduce(&api, "max")})).unwrap(); + assert_eq!(first_cell(&s, &max["layers"][0]), 30.0); + assert!(s.plugin_summaries().is_empty() && !s.plugin_retries_waiting()); + // A summary of layers is read in the call, as before. + let names: Vec = [&answer["layers"][0], &max["layers"][0]] + .iter() + .map(|id| s.map().layer(id.as_u64().unwrap() as u32).unwrap().name.clone()) + .collect(); + let q = json!({"op": "cube.reduce", "params": {"layers": names, "dates": ["2024-01-01", "2024-02-01"], "stat": "min"}}); + let min = s.run_leaving_downloads("plugin:eng-summary/f", &q).unwrap(); + assert_eq!(first_cell(&s, &min["layers"][0]), 20.0, "{min}"); + assert!(s.plugin_summaries().is_empty() && !s.plugin_retries_waiting()); + rustgis_plugins::unload("eng-summary"); +} + +/// Two summaries in one call are both left, read one after the other, and the command runs again +/// once, when both have landed: both layers in one undo step. +#[test] +fn two_summaries_in_one_call_run_the_command_again_once() { + let mut s = world(); + fetch_mode(true, true); + let api = collection(3); + let id = "eng-summary-two"; + let calls = [json!({"op": "cube.reduce", "params": reduce(&api, "min")}), json!({"op": "cube.reduce", "params": reduce(&api, "max")})]; + let wasm = rustgis_plugins::testing::wasm_with_host_calls(&calls); + assert!(!wasm.is_empty()); + let manifest = rustgis_plugins::testing::manifest(id, &["edit", "files", "network"]); + let package = rustgis_plugins::testing::zip_of(&[("plugin.json", manifest.as_bytes()), ("plugin.wasm", &wasm)]); + rustgis_plugins::load(rustgis_plugins::Package::from_zip(&package).unwrap(), "test").unwrap(); + let (undo, layers) = (s.undo.len(), s.map().layers.len()); + let answer = s.run_leaving_downloads(&format!("plugin:{id}/f"), &json!({})).unwrap(); + assert_eq!(answer, json!({"pending": true, "reading": ["cube.reduce", "cube.reduce"]})); + assert_eq!(s.plugin_summaries().len(), 2); + let ran = ran_again(&mut s); + assert_eq!(ran.len(), 1, "{ran:?}"); + // The module answers its last call's reply: the max. + let max = ran[0].1.as_ref().unwrap(); + assert_eq!(first_cell(&s, &max["layers"][0]), 30.0, "{max}"); + assert_eq!((s.undo.len(), s.map().layers.len()), (undo + 1, layers + 2)); + let min = s.map().layers.iter().find(|l| l.name.contains(" min ")).map(|l| json!(l.id)).unwrap(); + assert_eq!(first_cell(&s, &min), 10.0); + assert!(s.plugin_summaries().is_empty() && !s.plugin_retries_waiting()); + rustgis_plugins::unload(id); +} + +/// Cancelled, the read answers the command's call run again with that error, and nothing is added. +#[test] +fn a_cancelled_summary_is_the_calls_error() { + let mut s = world(); + plugin("eng-summary-cancel", &["edit", "files", "network"]); + fetch_mode(true, true); + let api = collection(3); + let (undo, layers) = (s.undo.len(), s.map().layers.len()); + let p = json!({"op": "cube.reduce", "params": reduce(&api, "mean")}); + // Held before it starts, so the Cancel comes first. + let turn = crate::cmd::plugins::summary::hold_turn(); + s.run_leaving_downloads("plugin:eng-summary-cancel/f", &p).unwrap(); + let under_way = s.plugin_summaries(); + s.cancel_plugin_summary(under_way[0].id); + assert!(s.plugin_summaries()[0].cancelled); + drop(turn); + let ran = ran_again(&mut s); + assert_eq!(ran.len(), 1, "{ran:?}"); + assert!(ran[0].1.as_ref().is_err_and(|e| e.contains("cube.reduce was cancelled")), "{ran:?}"); + assert_eq!((s.undo.len(), s.map().layers.len()), (undo, layers), "nothing added"); + assert!(s.plugin_summaries().is_empty() && !s.plugin_retries_waiting()); + rustgis_plugins::unload("eng-summary-cancel"); +} + +/// A trend over a collection is read off the frame the same way; its parameters are checked in the +/// call, so one that can't be worked out is said at once. +#[test] +fn a_plugins_trend_of_a_collection_is_read_off_the_frame() { + let mut s = world(); + plugin("eng-summary-trend", &["edit", "files", "network"]); + fetch_mode(true, true); + let api = collection(6); + let mut p = reduce(&api, "mean"); + if let Some(o) = p.as_object_mut() { + o.remove("stat"); + } + // Two dates: too few for a trend, said in the call, and nothing left to read. + let mut short = p.clone(); + short["end"] = json!("2024-02-28"); + let e = s.run_leaving_downloads("plugin:eng-summary-trend/f", &json!({"op": "cube.trend", "params": short})).unwrap_err(); + assert!(e.contains("a trend needs"), "{e}"); + assert!(s.plugin_summaries().is_empty() && !s.plugin_retries_waiting()); + let layers = s.map().layers.len(); + let answer = s.run_leaving_downloads("plugin:eng-summary-trend/f", &json!({"op": "cube.trend", "params": p})).unwrap(); + assert_eq!(answer, json!({"pending": true, "reading": ["cube.trend"]})); + let ran = ran_again(&mut s); + let answer = ran[0].1.as_ref().unwrap(); + assert_eq!(answer["layers"].as_array().map(Vec::len), Some(4), "{answer}"); + assert_eq!(s.map().layers.len(), layers + 4); + rustgis_plugins::unload("eng-summary-trend"); +} diff --git a/crates/plugins/src/testing.rs b/crates/plugins/src/testing.rs index b78cdae8a4..d64429a4b6 100644 --- a/crates/plugins/src/testing.rs +++ b/crates/plugins/src/testing.rs @@ -198,6 +198,45 @@ pub fn wasm_with_host_call(request: &serde_json::Value) -> Vec { .unwrap_or_default() } +/// A test module that makes fixed host calls one after another, in one call of its own, and +/// answers what the last one replied: a command that asks for several things at once. +pub fn wasm_with_host_calls(requests: &[serde_json::Value]) -> Vec { + // The requests, then the heap the host's answers are put in, then the last reply. + const REPLY: usize = 4 << 16; + let (mut data, mut calls, mut at) = (String::new(), String::new(), 0usize); + for request in requests { + let request = request.to_string(); + let encoded: String = request.bytes().map(|byte| format!("\\{byte:02x}")).collect(); + data.push_str(&format!("(data (i32.const {at}) \"{encoded}\")\n")); + calls.push_str(&format!( + "(local.set $len (call $call (i32.const {at}) (i32.const {len})))\n(call $result (i32.const {REPLY}))\n", + len = request.len(), + )); + at += request.len(); + } + let heap = at.div_ceil(65536).max(1) * 65536; + wat::parse_str(format!( + r#" + (module + (import "rustgis" "call" (func $call (param i32 i32) (result i32))) + (import "rustgis" "result" (func $result (param i32))) + (memory (export "memory") 6) + (global $heap (mut i32) (i32.const {heap})) + {data} + (func (export "rustgis_alloc") (param $n i32) (result i32) + (local $p i32) + (local.set $p (global.get $heap)) + (global.set $heap (i32.add (global.get $heap) (local.get $n))) + (local.get $p)) + (func (export "rustgis_call") (param i32 i32) (result i64) + (local $len i32) + {calls} + (i64.or (i64.shl (i64.const {REPLY}) (i64.const 32)) (i64.extend_i32_u (local.get $len))))) + "# + )) + .unwrap_or_default() +} + /// Calls the host, handles its error as data, and returns a successful plugin result. /// Exercises host-call rollback when the guest does not propagate the host's failure. pub fn wasm_with_handled_host_error(request: &serde_json::Value) -> Vec { diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 70d60652b2..50fa374633 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -544,6 +544,9 @@ pub fn status_bar(app: &mut RustGisApp, ui: &mut Ui) { } #[cfg(not(target_arch = "wasm32"))] source_open_status(app, ui, &t); + // Data cubes' summaries plugin commands left to read off the frame (#3183). + #[cfg(not(target_arch = "wasm32"))] + summaries_status(app, ui, &t); crate::geocodeui::status(app, ui); // Downloads and windows being read off the frame, each with its Cancel. if !app.ui.downloads.is_empty() || window_reads_under_way(app) { @@ -730,11 +733,42 @@ fn source_open_status(app: &RustGisApp, ui: &mut Ui, t: &Tokens) { ui.ctx().request_repaint_after(std::time::Duration::from_millis(50)); } +/// The data cubes' summaries plugin commands left to read off the frame (#3183), each naming its +/// command, with its progress and Cancel: the command runs again once its summary has landed, or +/// says it was cancelled. +#[cfg(not(target_arch = "wasm32"))] +fn summaries_status(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { + let under_way = app.session.plugin_summaries(); + if under_way.is_empty() { + return; + } + let size = StripSize::of(app); + let mut cancel = None; + for summary in &under_way { + sep(ui, t); + ui.spinner(); + if size.cancel_first(ui, !summary.cancelled) { + cancel = Some(summary.id); + } + let reading = crate::i18n::fmt("Reading for {command}…", &[("command", &crate::pluginstart::title(app, &summary.command))]); + ui.label(egui::RichText::new(reading).size(size.text).color(t.text_dim)); + size.progress(ui, summary.done as f32 / summary.total.max(1) as f32); + if size.cancel_last(ui, !summary.cancelled) { + cancel = Some(summary.id); + } + } + if let Some(id) = cancel { + app.session.cancel_plugin_summary(id); + } + // The bar moves while the slices are read on their thread. + ui.ctx().request_repaint_after(std::time::Duration::from_millis(200)); +} + /// Whether work is running that the status bar shows with its progress and Cancel: an export, a -/// file or a layer being read, a download. +/// file or a layer being read, a download, a plugin command's summary. pub(crate) fn background_busy(app: &RustGisApp) -> bool { #[cfg(not(target_arch = "wasm32"))] - if app.export_job.is_some() || crate::readjob::showing(app) || sources_opening(app) { + if app.export_job.is_some() || crate::readjob::showing(app) || sources_opening(app) || !app.session.plugin_summaries().is_empty() { return true; } !app.ui.downloads.is_empty() || window_reads_under_way(app) @@ -753,6 +787,8 @@ pub(crate) fn background_status(app: &mut RustGisApp, ui: &mut Ui) { } #[cfg(not(target_arch = "wasm32"))] source_open_status(app, ui, &t); + #[cfg(not(target_arch = "wasm32"))] + summaries_status(app, ui, &t); if !app.ui.downloads.is_empty() || window_reads_under_way(app) { downloads_status(app, ui, &t); } diff --git a/crates/ui-egui/src/pluginstart.rs b/crates/ui-egui/src/pluginstart.rs index 6d06f236c4..9e7a5368c4 100644 --- a/crates/ui-egui/src/pluginstart.rs +++ b/crates/ui-egui/src/pluginstart.rs @@ -7,6 +7,10 @@ //! //! A command that isn't a plugin's, asked for during the wait, runs first. One that replaces the //! project takes the commands waiting with it, and says so: they name the old project's layers. +//! +//! A plugin command's `cube.reduce` or `cube.trend` on a STAC collection doesn't hold the frame +//! for its slices either (#3183): they are read on a thread, shown in the status bar with their +//! progress and Cancel, and the command runs again once they have landed (`run_again`). use crate::{RustGisApp, i18n}; use serde_json::Value; @@ -141,7 +145,7 @@ pub(crate) fn running(app: &RustGisApp) -> Option { } /// A plugin command as the user knows it: `BrasilData: Solos`. -fn title(app: &RustGisApp, id: &str) -> String { +pub(crate) fn title(app: &RustGisApp, id: &str) -> String { let plugin = rustgis_engine::plugins::split_id(id).and_then(|(plugin, item)| Some((rustgis_engine::plugins::get(plugin)?, item))); plugin.map_or_else( || id.to_string(), @@ -367,6 +371,36 @@ mod tests { plugins::unload("ui-again-asked"); } + /// A summary a plugin command left to read off the frame shows in the status bar, naming the + /// command, with its progress; its Cancel stops it, and the window answers meanwhile (#3183). + #[test] + fn a_summary_read_off_the_frame_shows_with_its_cancel() { + let mut h = launch("ui-summary"); + let id = h.state_mut().session.start_test_summary("plugin:ui-summary/f"); + h.step(); + h.step(); + let _ = h.get_by_label_contains("Reading for Test ui-summary: Forward"); + // Its progress, told from its thread. + let started = web_time::Instant::now(); + while h.state().session.plugin_summaries()[0].done == 0 && started.elapsed() < Duration::from_secs(30) { + std::thread::sleep(Duration::from_millis(5)); // test-wait: the read's thread tells its progress when it starts + } + assert_eq!(h.state().session.plugin_summaries()[0].done, 1); + h.get_by_label("Cancel").click(); + h.step(); + assert!(h.state().session.plugin_summaries().iter().all(|s| s.id == id && s.cancelled)); + // It stops between slices, and is gone from the status bar. + let started = web_time::Instant::now(); + while !h.state().session.plugin_summaries().is_empty() && started.elapsed() < Duration::from_secs(30) { + h.step(); + std::thread::sleep(Duration::from_millis(5)); // test-wait: the cancelled read ends on its thread, polled as the frame loop polls it + } + assert!(h.state().session.plugin_summaries().is_empty()); + h.step(); + assert!(h.query_by_label_contains("Reading for").is_none()); + plugins::unload("ui-summary"); + } + /// Clicks are dropped once, after a long run; what the pointer did otherwise stays. #[test] fn clicks_made_during_a_long_run_are_dropped_once() { diff --git a/docs/plugins.md b/docs/plugins.md index 5b72cdb4c4..86a00761de 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -708,6 +708,18 @@ area's files or none. When they are left to download, a file that fails stops th error that says how many landed before it. Those stay, each its own undo step. It also fetches the catalog on each run, which waits with the window held. +`cube.reduce` and `cube.trend` over a STAC collection (`"collection"`, or a catalogue's `"cube"` +entry of one) do the same on the desktop: the call checks its parameters and searches the +collection, with the window held as before, then answers `{"pending": true}` and leaves the slices +to read on a thread of their own. The status bar names the command, with the read's progress and a +Cancel. Once the read has landed the command runs again, and the same call, with the same +parameters, adds the layers at once and answers them as it would have (`{"layers", "dates"}`): +they are part of the command's own undo step. Cancelled, or failed, the read is that call's error. +Several in one call are read one after another, and the command runs again once all have landed; +up to 4 wait at a time, and asking for more fails. Their layers are held in memory until the +command has run again. A cube of layers, bands or a Zarr store is read in the call, as before, and +`rustgis-cli`, a script or a task waits for the read. + While a command waits the window answers, so the user can work and the project can change. The status bar says the command is running, and asking for it again with the same parameters does nothing. A run again sees the view the command first ran with, and the window's size then, unless From f6d0e29bcfa714dc4ca537cc1745392833bbea8c Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sat, 28 Nov 2026 03:17:48 -0300 Subject: [PATCH 2/4] fix(plugins): share a plugin summary's layers, bound what waits, stop on a new project (#3183) Review round on #3198: - the summary's thread makes the layers and their GeoTIFFs, and the run again adds those same layers, sharing their pixels: no second copy and no GeoTIFF written on the frame; - the cap counts landed summaries still waiting for their commands, and each request once; a new read plans its output against memory::share and is refused past it with a way out; - a project replaced or created stops the old project's reads; - a Cancel after the thread has finished lands the read as cancelled. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/cube.rs | 50 +++++++- crates/engine/src/cmd/plugin_summary.rs | 127 +++++++++++++++++--- crates/engine/src/lib.rs | 8 +- crates/engine/src/tests/plugin_summaries.rs | 114 ++++++++++++++++++ crates/plugins/src/testing.rs | 43 +++++-- docs/plugins.md | 6 +- 6 files changed, 310 insertions(+), 38 deletions(-) diff --git a/crates/engine/src/cmd/cube.rs b/crates/engine/src/cmd/cube.rs index b234c1c712..7de94b6f2c 100644 --- a/crates/engine/src/cmd/cube.rs +++ b/crates/engine/src/cmd/cube.rs @@ -592,6 +592,13 @@ pub struct TrendRun { } impl TrendRun { + /// About the bytes its four outputs hold once made, with their GeoTIFFs: the most a run can + /// make when the cube doesn't know its size. + pub fn output_bytes(&self) -> u64 { + let cells = self.cube.size().map_or(MAX_VALUES, |(w, h)| (w as u64).saturating_mul(h as u64)); + output_bytes(cells.saturating_mul(4).min(MAX_VALUES)) + } + /// The work, for a progress bar: the slices read (every piece's), then the cells worked out, /// in [`CELL_PARTS`] parts. pub fn total(&self) -> usize { @@ -1098,7 +1105,7 @@ fn trend_cmd(s: &mut Session, p: &Value) -> CmdResult { // panes' bound, as the Workflows pane's thread does. if let Some(left) = super::plugins::summary::left(s, "cube.trend", p, |s| { let run = trend_start(s, p)?; - Ok(super::plugins::summary::Work::new(run.total(), run.dates(), move |cancel, done| run.run(cancel, done))) + Ok(super::plugins::summary::Work::new(run.total(), run.dates(), run.output_bytes(), move |cancel, done| run.run(cancel, done))) }) { return left; } @@ -1206,20 +1213,42 @@ fn run_telling( }) } +/// About the bytes `values` output cells hold as a raster (4 bytes each) and as its GeoTIFF. +fn output_bytes(values: u64) -> u64 { + values.saturating_mul(8) +} + /// Adds a trend's (or a summary's) layers, each as a GeoTIFF the project keeps. pub fn add_outputs(s: &mut Session, rasters: Vec, dates: usize) -> CmdResult { let mut layers = Vec::new(); for r in rasters { - let name = r.name.clone(); - let tif = raster::geotiff::write_all(&r).map_err(|e| e.to_string())?; - let file: String = name.chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_' | '.') { c } else { '_' }).collect(); - let layer = rustgis_map::raster::RasterLayer::from_written(r, format!("{file}.tif"), tif); + let (name, layer) = output_layer(r)?; let out = super::raster::add_raster(s, &name, layer)?; layers.push(out["layer"].clone()); } Ok(json!({ "layers": layers, "dates": dates })) } +/// A trend's (or a summary's) output as the layer it adds, with its name: its GeoTIFF written, so +/// it is made on any thread. +pub(crate) fn output_layer(r: Raster) -> Result<(String, rustgis_map::raster::RasterLayer), String> { + let name = r.name.clone(); + let tif = raster::geotiff::write_all(&r).map_err(|e| e.to_string())?; + let file: String = name.chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_' | '.') { c } else { '_' }).collect(); + Ok((name, rustgis_map::raster::RasterLayer::from_written(r, format!("{file}.tif"), tif))) +} + +/// Adds layers [`output_layer`] made (a summary read off the frame, #3183), sharing their pixels +/// and GeoTIFFs with whatever holds them. +pub(crate) fn add_output_layers(s: &mut Session, made: &[(String, rustgis_map::raster::RasterLayer)], dates: usize) -> CmdResult { + let mut layers = Vec::new(); + for (name, layer) in made { + let out = super::raster::add_raster(s, name, layer.clone())?; + layers.push(out["layer"].clone()); + } + Ok(json!({ "layers": layers, "dates": dates })) +} + // --- A summary over time of any cube ------------------------------------------------------------- /// What a summary over time takes from each cell's values (`cube.reduce`, `zarr.reduce`). @@ -1740,6 +1769,15 @@ pub struct ReduceRun { } impl ReduceRun { + /// About the bytes its outputs hold once made, with their GeoTIFFs: the most a run can make + /// ([`MAX_REDUCED`] values) when the cube doesn't know its size, or for frequency, whose + /// classes aren't known before it is read. + pub fn output_bytes(&self) -> u64 { + let slots = (self.groups.len() * self.cube.assets().len().max(1)) as u64; + let cells = self.cube.size().filter(|_| self.stat != Stat::Frequency).map(|(w, h)| (w as u64).saturating_mul(h as u64)); + output_bytes(cells.map_or(MAX_REDUCED, |c| c.saturating_mul(slots).min(MAX_REDUCED))) + } + /// The work, for a progress bar: the slices read, every piece's, and the dates' clear shares /// when first takes them in that order. pub fn total(&self) -> usize { @@ -2216,7 +2254,7 @@ fn reduce_cmd(s: &mut Session, p: &Value) -> CmdResult { // A plugin's command the app runs reads a STAC collection off the frame (#3183). if let Some(left) = super::plugins::summary::left(s, "cube.reduce", p, |s| { let run = reduce_start(s, p)?; - Ok(super::plugins::summary::Work::new(run.total(), run.dates(), move |cancel, done| run.run(cancel, done))) + Ok(super::plugins::summary::Work::new(run.total(), run.dates(), run.output_bytes(), move |cancel, done| run.run(cancel, done))) }) { return left; } diff --git a/crates/engine/src/cmd/plugin_summary.rs b/crates/engine/src/cmd/plugin_summary.rs index ba994c7df1..88dded0350 100644 --- a/crates/engine/src/cmd/plugin_summary.rs +++ b/crates/engine/src/cmd/plugin_summary.rs @@ -9,6 +9,12 @@ //! read one after another, and the command runs again once all have landed. Cancel, or a read that //! failed, is that call's answer in the run again, and the plugin says it as it says any error. //! +//! The read's thread also makes the layers (their GeoTIFFs written), and the run again adds those +//! very layers, sharing their pixels: what was read is held once, counted in what the app holds +//! ([`memory::held`]), until no command waits for it. A new read is refused when the reads waiting +//! would hold more than the memory the app plans for ([`memory::share`]), or more than +//! [`MAX_SUMMARIES`] would wait, landed ones included. +//! //! Only a plugin's command the app runs ([`Session::run_leaving_downloads`]) leaves the read: the //! command line, scripts, the assistant and Python wait for it, as before, and layers, bands and //! Zarr stores, quick to read, are read where the call is made. @@ -16,14 +22,16 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; +use rustgis_data::memory; use rustgis_data::raster::Raster; +use rustgis_map::raster::RasterLayer; use serde_json::{Value, json}; use crate::render::rustgis_tiles::cache; use crate::{CmdResult, Session}; -/// The most summaries plugin commands may have left to read at once: each holds its layers until -/// its command has run again. +/// The most summaries plugin commands may have left to read at once, being read or landed: each +/// holds its layers until its command has run again. pub const MAX_SUMMARIES: usize = 4; /// The key a summary's request names its command by (`{"summary": "cube.reduce", "params": …}`), @@ -39,17 +47,20 @@ type Run = Box Result, Stri pub(crate) struct Work { total: usize, dates: usize, + /// About the bytes its layers will hold, planned before it starts. + bytes: u64, run: Run, } impl Work { - /// `run`, `total` steps of work, of `dates` dates. + /// `run`, `total` steps of work, of `dates` dates, its layers holding about `bytes`. pub(crate) fn new( total: usize, dates: usize, + bytes: u64, run: impl FnOnce(&AtomicBool, &AtomicUsize) -> Result, String> + Send + 'static, ) -> Work { - Work { total, dates, run: Box::new(run) } + Work { total, dates, bytes, run: Box::new(run) } } } @@ -75,25 +86,50 @@ impl Left { #[derive(Clone)] pub(crate) struct Reading { n: u64, + command: &'static str, /// The plugin command it is read for. owner: String, total: usize, + /// About the bytes its layers will hold. + bytes: u64, cancel: Arc, done: Arc, - slot: Arc, usize), String>>>>, + slot: Arc>>>, +} + +/// What a summary's thread made: its layers (with their names) and how many dates, and its part of +/// what the app holds. +pub(crate) struct Held { + layers: Vec<(String, RasterLayer)>, + dates: usize, + _holding: memory::Holding, } -/// What a summary read off the frame made (its layers, and how many dates), held for its command's -/// run again, which adds a copy of it: a run waiting again, for another read, adds it again. +/// What a summary read off the frame made, held for its command's run again, which adds those +/// layers, sharing their pixels: a run waiting again, for another read, adds them again. #[derive(Clone)] -pub(crate) struct Summary(Arc<(Vec, usize)>); +pub(crate) struct Summary(Arc); impl std::fmt::Debug for Summary { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "Summary({} layers of {} dates)", self.0.0.len(), self.0.1) + write!(f, "Summary({} layers of {} dates)", self.0.layers.len(), self.0.dates) } } +/// `rasters`, of `dates` dates, as the layers a summary adds: made on its thread, and counted in +/// what the app holds. +fn held(rasters: Vec, dates: usize) -> Result { + let layers = rasters.into_iter().map(super::super::cube::output_layer).collect::, _>>()?; + let bytes = layers + .iter() + .map(|(_, l)| { + let pixels = l.data.as_ref().map_or(0, |r| r.bands.len() as u64 * u64::from(r.width) * u64::from(r.height) * 4); + pixels + l.embedded.as_ref().map_or(0, |e| e.len() as u64) + }) + .sum(); + Ok(Held { layers, dates, _holding: memory::Holding::of(bytes) }) +} + impl PartialEq for Summary { fn eq(&self, other: &Self) -> bool { Arc::ptr_eq(&self.0, &other.0) @@ -164,8 +200,7 @@ impl Session { let asked = asked(command, p); if let Some((answer, added)) = self.rerun_answer(&asked) { let held = answer.and_then(|_| added.summary.ok_or_else(|| format!("{command}: nothing was read")))?; - let (rasters, dates) = held.0.as_ref().clone(); - return super::super::cube::add_outputs(self, rasters, dates); + return super::super::cube::add_output_layers(self, &held.0.layers, held.0.dates); } // Asked for already in this call, or by a run before it for the same caller: that read, // not another (as a document's is, `left_document`). @@ -184,13 +219,30 @@ impl Session { let number = match known { Some(n) => n, None => { - let reading = self.url_waits.summaries.len() + now.iter().filter(|(_, q)| is_summary(q)).count(); - if reading >= MAX_SUMMARIES { + // Those being read, those landed whose commands haven't run again, and this call's + // new ones: each counted once. + let waiting = self.url_waits.summaries.len() + self.url_waits.held_summaries() + self.call_summaries.len(); + if waiting >= MAX_SUMMARIES { return Err(format!( "{MAX_SUMMARIES} data cube summaries are already being read for plugin commands; try again when they have come" )); } let work = start(self)?; + // What those still to land will hold, with this one: those landed are counted in + // what the app holds already. + let planned = work.bytes + + self.url_waits.summaries.iter().map(|r| r.bytes).sum::() + + self.call_summaries.iter().map(|l| l.work.bytes).sum::(); + if let Some(room) = memory::share(memory::physical(), memory::held(), memory::available()) + && planned > room + { + let mb = |b: u64| b.div_ceil(1 << 20); + return Err(format!( + "{command}: the summaries plugin commands are reading would hold about {} MB until their commands run again, more than the {} MB there is room for: take a smaller area or a coarser cell size, or try again once the reads under way have come", + mb(planned), + mb(room) + )); + } self.next_request += 1; let n = self.next_request; let (still, capture) = (cache::current_still(), rustgis_data::diagnostics::Capture::current()); @@ -231,10 +283,10 @@ impl Session { /// Tests in other crates: a summary under way for plugin command `owner`, read until it is /// cancelled (one of its 4 slices read), and its number. Only in a test build. - #[cfg(all(feature = "testing", debug_assertions))] + #[cfg(any(test, all(feature = "testing", debug_assertions)))] #[doc(hidden)] pub fn start_test_summary(&mut self, owner: &str) -> u64 { - let work = Work::new(4, 4, |cancel: &AtomicBool, done: &AtomicUsize| { + let work = Work::new(4, 4, 0, |cancel: &AtomicBool, done: &AtomicUsize| { done.store(1, Ordering::Relaxed); while !cancel.load(Ordering::Relaxed) { std::thread::sleep(std::time::Duration::from_millis(5)); // test-wait: a read that lasts until it is cancelled @@ -256,11 +308,13 @@ impl super::fetch::UrlWaits { /// started before it. pub(crate) fn read_summary(&mut self, left: Left, owner: &str) { let Left { n, command, work, still, capture } = left; - let Work { total, dates, run } = work; + let Work { total, dates, bytes, run } = work; let reading = Reading { n, + command, owner: owner.to_string(), total: total.max(1), + bytes, cancel: Arc::default(), done: Arc::default(), slot: Arc::default(), @@ -281,7 +335,9 @@ impl super::fetch::UrlWaits { .unwrap_or_else(|_| Err(format!("{command} failed unexpectedly"))); if cancel.load(Ordering::Relaxed) { Err(cancelled(command)) } else { r } }; - *slot.lock().unwrap_or_else(|e| e.into_inner()) = Some(out.map(|rasters| (rasters, dates))); + // Its layers made here too, their GeoTIFFs written: the run again only adds them. + let out = out.and_then(|rasters| held(rasters, dates)); + *slot.lock().unwrap_or_else(|e| e.into_inner()) = Some(out); }); if let Err(e) = spawned { *reading.slot.lock().unwrap_or_else(|e| e.into_inner()) = Some(Err(format!("{command} couldn't start: {e}"))); @@ -297,6 +353,8 @@ impl super::fetch::UrlWaits { self.summaries.push(r); continue; }; + // Cancelled after its thread had finished, it is cancelled all the same. + let out = if r.cancel.load(Ordering::Relaxed) { Err(cancelled(r.command)) } else { out }; match out { Ok(held) => { self.land(r.n, Ok(json!({})), super::fetch::Added::of_summary(Summary(Arc::new(held)))); @@ -307,6 +365,18 @@ impl super::fetch::UrlWaits { } } + /// How many summaries have landed whose commands haven't run again: each holds its layers. + fn held_summaries(&self) -> usize { + self.landed.iter().filter(|(.., added)| added.summary.is_some()).count() + } + + /// Stops every summary being read: their project is gone (replaced, or closed). + pub(crate) fn stop_every_summary(&self) { + for r in &self.summaries { + r.cancel.store(true, Ordering::Relaxed); + } + } + /// Whether request `n` is a summary still being read: it isn't given up for taking long. pub(super) fn summarising(&self, n: u64) -> bool { self.summaries.iter().any(|r| r.n == n) @@ -342,13 +412,34 @@ mod tests { assert!(!waits.holds(7, &json!({"request": 7}))); } + /// Cancelled once its thread had finished, before it landed, a read lands as cancelled: its + /// command adds nothing. + #[test] + fn a_cancel_after_the_read_ended_is_its_answer() { + let mut waits = super::super::fetch::UrlWaits::default(); + waits.wait(1, asked("cube.reduce", &json!({"n": "ended"}))); + let work = Work::new(1, 2, 0, |_: &AtomicBool, _: &AtomicUsize| Ok(Vec::new())); + waits.read_summary( + Left { n: 1, command: "cube.reduce", work, still: None, capture: rustgis_data::diagnostics::Capture::current() }, + "plugin:p/f", + ); + let started = web_time::Instant::now(); + while waits.summaries[0].slot.lock().unwrap().is_none() && started.elapsed() < web_time::Duration::from_secs(30) { + std::thread::sleep(std::time::Duration::from_millis(5)); // test-wait: the read ends on its thread + } + waits.summaries[0].cancel.store(true, Ordering::Relaxed); + waits.summaries_in(); + let landed = waits.landed.iter().find(|(m, ..)| *m == 1).map(|(_, _, answer, _)| answer.clone()); + assert_eq!(landed, Some(Err("cube.reduce was cancelled".to_string()))); + } + /// A summary read off the frame lands for the command waiting for it, a cancelled one as its /// error; one no command waits for any more is stopped. #[test] fn summaries_land_or_are_stopped() { let mut waits = super::super::fetch::UrlWaits::default(); let work = |rasters: Vec| { - Work::new(2, 2, move |_: &AtomicBool, done: &AtomicUsize| { + Work::new(2, 2, 0, move |_: &AtomicBool, done: &AtomicUsize| { done.fetch_add(2, Ordering::Relaxed); Ok(rasters) }) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a8b861240c..c9b6d97664 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -2654,7 +2654,10 @@ impl Session { } // The command, and those it ran, are done: a replaced project stays replaced. if self.depth == 0 { - self.put_aside = None; + // Its summaries being read for plugin commands stop: their project won't come back. + if let Some(aside) = self.put_aside.take() { + aside.url_waits.stop_every_summary(); + } self.published_syncs.clear(); // Frame maintenance and some policy adapters run a guard without command dispatch. // Otherwise the command epilogue trims once, after any maintenance steps. @@ -3785,7 +3788,8 @@ impl Session { /// Forgets undo/redo and extent history and marks the project clean (after new/open, or a /// front end setting up how the project starts): what [`PutAside`] holds, dropped. pub fn clear_history(&mut self) { - drop(self.take_project_state()); + // Its summaries being read for plugin commands stop with it. + self.take_project_state().url_waits.stop_every_summary(); self.undo_memory.clear(); self.project_starts = self.project_starts.wrapping_add(1); // A state of its own: undo back past a replacement made within a command (a task's step) diff --git a/crates/engine/src/tests/plugin_summaries.rs b/crates/engine/src/tests/plugin_summaries.rs index 295ad3ba9f..0b42a204a0 100644 --- a/crates/engine/src/tests/plugin_summaries.rs +++ b/crates/engine/src/tests/plugin_summaries.rs @@ -176,3 +176,117 @@ fn a_plugins_trend_of_a_collection_is_read_off_the_frame() { assert_eq!(s.map().layers.len(), layers + 4); rustgis_plugins::unload("eng-summary-trend"); } + +/// Loads plugin `id`, whose commands make `commands`' calls (each its list, by its one-letter id). +fn calls_plugin(id: &str, commands: &[(char, &[Value])]) { + let wasm = rustgis_plugins::testing::wasm_with_host_calls_by_command(commands); + assert!(!wasm.is_empty()); + let manifest = rustgis_plugins::testing::manifest(id, &["edit", "files", "network"]); + let package = rustgis_plugins::testing::zip_of(&[("plugin.json", manifest.as_bytes()), ("plugin.wasm", &wasm)]); + rustgis_plugins::load(rustgis_plugins::Package::from_zip(&package).unwrap(), "test").unwrap(); +} + +/// `cube.reduce` of the collection at `api` with `stat`, as a plugin's call. +fn reduce_call(api: &str, stat: &str) -> Value { + json!({"op": "cube.reduce", "params": reduce(api, stat)}) +} + +/// Two commands waiting for one read add what it read without copying it: their layers hold the +/// same pixels and GeoTIFF, made on the read's thread. +#[test] +fn commands_sharing_a_summary_share_its_pixels() { + let mut s = world(); + fetch_mode(true, true); + let api = collection(3); + let id = "eng-summary-shared"; + let mean = [reduce_call(&api, "mean")]; + calls_plugin(id, &[('h', &mean), ('f', &mean)]); + // Held back, so both commands ask for it before it lands. + let turn = crate::cmd::plugins::summary::hold_turn(); + for command in ["h", "f"] { + let answer = s.run_leaving_downloads(&format!("plugin:{id}/{command}"), &json!({})).unwrap(); + assert_eq!(answer, json!({"pending": true, "reading": ["cube.reduce"]}), "{command}"); + } + assert_eq!(s.plugin_summaries().len(), 1, "one read for both"); + drop(turn); + let ran = ran_again(&mut s); + assert_eq!(ran.len(), 2, "{ran:?}"); + let raster = |answer: &crate::CmdResult| { + let id = u32::try_from(answer.as_ref().unwrap()["layers"][0].as_u64().unwrap()).unwrap(); + s.map().layer(id).unwrap().raster.clone().unwrap() + }; + let (a, b) = (raster(&ran[0].1), raster(&ran[1].1)); + assert!(std::sync::Arc::ptr_eq(a.data.as_ref().unwrap(), b.data.as_ref().unwrap()), "the same pixels"); + assert!(std::sync::Arc::ptr_eq(a.embedded.as_ref().unwrap(), b.embedded.as_ref().unwrap()), "the same GeoTIFF"); + rustgis_plugins::unload(id); +} + +/// A summary that has landed, its command still waiting for another of its requests, counts among +/// those held: no more than [`MAX_SUMMARIES`] are held at once. +/// +/// [`MAX_SUMMARIES`]: crate::cmd::plugins::summary::MAX_SUMMARIES +#[test] +fn a_summary_landed_and_held_counts_among_those_read() { + let mut s = world(); + fetch_mode(true, true); + let api = collection(3); + let id = "eng-summary-held"; + let first = [reduce_call(&api, "mean"), json!({"op": "layer.addUrl", "params": {"url": "https://x.org/held.csv"}})]; + let more: Vec = ["min", "max", "sum", "std"].iter().map(|stat| reduce_call(&api, stat)).collect(); + calls_plugin(id, &[('f', &first), ('h', &more)]); + let answer = s.run_leaving_downloads(&format!("plugin:{id}/f"), &json!({})).unwrap(); + assert_eq!(answer["reading"], json!(["cube.reduce"]), "{answer}"); + // It lands; the command still waits for its download. + let started = web_time::Instant::now(); + while !s.plugin_summaries().is_empty() && started.elapsed() < web_time::Duration::from_secs(60) { + assert!(s.poll_plugin_retries().is_empty()); + std::thread::sleep(std::time::Duration::from_millis(10)); // test-wait: the read lands on its thread, polled as the frame loop polls it + } + assert!(s.plugin_summaries().is_empty() && s.plugin_retries_waiting()); + // Four more would hold five. + let e = s.run_leaving_downloads(&format!("plugin:{id}/h"), &json!({})).unwrap_err(); + assert!(e.contains("already being read"), "{e}"); + assert!(s.plugin_summaries().is_empty(), "none of them started"); + rustgis_plugins::unload(id); +} + +/// A read asked for again by the next call, beside new ones, is counted once: with two under way, +/// a call asking for one of them and two more holds four, and is let through. +#[test] +fn a_summary_asked_again_is_counted_once() { + let mut s = world(); + fetch_mode(true, true); + let api = collection(3); + let id = "eng-summary-again"; + let (a, b, c, d) = (reduce_call(&api, "mean"), reduce_call(&api, "min"), reduce_call(&api, "max"), reduce_call(&api, "sum")); + calls_plugin(id, &[('h', &[a.clone(), b]), ('f', &[a, c, d])]); + let turn = crate::cmd::plugins::summary::hold_turn(); + s.run_leaving_downloads(&format!("plugin:{id}/h"), &json!({})).unwrap(); + assert_eq!(s.plugin_summaries().len(), 2); + let answer = s.run_leaving_downloads(&format!("plugin:{id}/f"), &json!({})).unwrap(); + assert_eq!(answer["reading"].as_array().map(Vec::len), Some(3), "{answer}"); + assert_eq!(s.plugin_summaries().len(), 4); + drop(turn); + let ran = ran_again(&mut s); + assert!(!ran.is_empty(), "they land"); + rustgis_plugins::unload(id); +} + +/// A project replacing this one stops its summaries: a summary of the new project isn't held +/// behind them. +#[test] +fn a_new_project_stops_the_summaries_of_the_old() { + let mut s = world(); + plugin("eng-summary-new-project", &["edit", "files", "network"]); + fetch_mode(true, true); + let api = collection(3); + // A read of the old project that lasts until it is stopped. + s.start_test_summary("plugin:eng-summary-new-project/f"); + s.run("project.sample", &Value::Null).unwrap(); + assert!(s.plugin_summaries().is_empty(), "not the new project's"); + s.run_leaving_downloads("plugin:eng-summary-new-project/f", &reduce_call(&api, "mean")).unwrap(); + let ran = ran_again(&mut s); + assert_eq!(ran.len(), 1, "the new project's read lands: {ran:?}"); + assert!(ran[0].1.is_ok(), "{ran:?}"); + rustgis_plugins::unload("eng-summary-new-project"); +} diff --git a/crates/plugins/src/testing.rs b/crates/plugins/src/testing.rs index d64429a4b6..b96ea9d64e 100644 --- a/crates/plugins/src/testing.rs +++ b/crates/plugins/src/testing.rs @@ -201,18 +201,41 @@ pub fn wasm_with_host_call(request: &serde_json::Value) -> Vec { /// A test module that makes fixed host calls one after another, in one call of its own, and /// answers what the last one replied: a command that asks for several things at once. pub fn wasm_with_host_calls(requests: &[serde_json::Value]) -> Vec { + calls_module(&[(None, requests)]) +} + +/// [`wasm_with_host_calls`] with the calls of each command, by its one-letter id (`'f'`, `'h'`…): +/// a plugin whose commands ask for different things. A command not listed makes no call. +pub fn wasm_with_host_calls_by_command(commands: &[(char, &[serde_json::Value])]) -> Vec { + let commands: Vec<(Option, &[serde_json::Value])> = commands.iter().map(|(id, requests)| (Some(*id), *requests)).collect(); + calls_module(&commands) +} + +/// A module making `commands`' calls: each list for its command id (the byte at 15 of a command's +/// request, `{"abi":1,"id":"f"…`), or for every command when it has none. +fn calls_module(commands: &[(Option, &[serde_json::Value])]) -> Vec { // The requests, then the heap the host's answers are put in, then the last reply. const REPLY: usize = 4 << 16; let (mut data, mut calls, mut at) = (String::new(), String::new(), 0usize); - for request in requests { - let request = request.to_string(); - let encoded: String = request.bytes().map(|byte| format!("\\{byte:02x}")).collect(); - data.push_str(&format!("(data (i32.const {at}) \"{encoded}\")\n")); - calls.push_str(&format!( - "(local.set $len (call $call (i32.const {at}) (i32.const {len})))\n(call $result (i32.const {REPLY}))\n", - len = request.len(), - )); - at += request.len(); + for (id, requests) in commands { + let mut block = String::new(); + for request in *requests { + let request = request.to_string(); + let encoded: String = request.bytes().map(|byte| format!("\\{byte:02x}")).collect(); + data.push_str(&format!("(data (i32.const {at}) \"{encoded}\")\n")); + block.push_str(&format!( + "(local.set $len (call $call (i32.const {at}) (i32.const {len})))\n(call $result (i32.const {REPLY}))\n", + len = request.len(), + )); + at += request.len(); + } + match id { + Some(id) => calls.push_str(&format!( + "(if (i32.eq (i32.load8_u (i32.add (local.get $request) (i32.const 15))) (i32.const {})) (then {block}))\n", + u32::from(*id) + )), + None => calls.push_str(&block), + } } let heap = at.div_ceil(65536).max(1) * 65536; wat::parse_str(format!( @@ -228,7 +251,7 @@ pub fn wasm_with_host_calls(requests: &[serde_json::Value]) -> Vec { (local.set $p (global.get $heap)) (global.set $heap (i32.add (global.get $heap) (local.get $n))) (local.get $p)) - (func (export "rustgis_call") (param i32 i32) (result i64) + (func (export "rustgis_call") (param $request i32) (param i32) (result i64) (local $len i32) {calls} (i64.or (i64.shl (i64.const {REPLY}) (i64.const 32)) (i64.extend_i32_u (local.get $len))))) diff --git a/docs/plugins.md b/docs/plugins.md index 86a00761de..57471a440c 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -716,8 +716,10 @@ Cancel. Once the read has landed the command runs again, and the same call, with parameters, adds the layers at once and answers them as it would have (`{"layers", "dates"}`): they are part of the command's own undo step. Cancelled, or failed, the read is that call's error. Several in one call are read one after another, and the command runs again once all have landed; -up to 4 wait at a time, and asking for more fails. Their layers are held in memory until the -command has run again. A cube of layers, bands or a Zarr store is read in the call, as before, and +up to 4 wait at a time, read or landed, and asking for more fails. Their layers are made on the +read's thread and held in memory until the command has run again, which adds those same layers; a +read that would hold more than the memory there is room for is refused, saying to take a smaller +area or a coarser cell size. A project opened meanwhile stops the reads of the one before. A cube of layers, bands or a Zarr store is read in the call, as before, and `rustgis-cli`, a script or a task waits for the read. While a command waits the window answers, so the user can work and the project can change. The From fdd3b805b83916dada904e48f0e5ef3433f7f530 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sat, 28 Nov 2026 08:59:27 -0300 Subject: [PATCH 3/4] fix(plugins): plan a trend's whole output, count a made summary once, stop reads a rollback drops (#3183) - TrendRun::output_bytes plans all four outputs of a cube that knows its size: its run caps the area, not the outputs. - A summary's result is counted in memory::held as it goes in its slot, under the slot's lock; a new read's plan reads the slots and memory::held together, so a finished read isn't counted twice. - give_back stops the replacement's summaries before dropping its waits, and a failed command stops the summaries it started before its waits go back to the snapshot. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/cube.rs | 7 +- crates/engine/src/cmd/plugin_summary.rs | 78 +++++++++++++++++---- crates/engine/src/lib.rs | 4 ++ crates/engine/src/tests/plugin_summaries.rs | 68 +++++++++++++++++- 4 files changed, 141 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/cube.rs b/crates/engine/src/cmd/cube.rs index 7de94b6f2c..ab4776d735 100644 --- a/crates/engine/src/cmd/cube.rs +++ b/crates/engine/src/cmd/cube.rs @@ -592,11 +592,12 @@ pub struct TrendRun { } impl TrendRun { - /// About the bytes its four outputs hold once made, with their GeoTIFFs: the most a run can - /// make when the cube doesn't know its size. + /// About the bytes its four outputs hold once made, with their GeoTIFFs: all of them, for a + /// cube that knows its size, as the run doesn't cap its outputs (only its pairs); when it + /// doesn't, those of a block of [`MAX_VALUES`] cells. pub fn output_bytes(&self) -> u64 { let cells = self.cube.size().map_or(MAX_VALUES, |(w, h)| (w as u64).saturating_mul(h as u64)); - output_bytes(cells.saturating_mul(4).min(MAX_VALUES)) + output_bytes(cells.saturating_mul(OUTPUTS as u64)) } /// The work, for a progress bar: the slices read (every piece's), then the cells worked out, diff --git a/crates/engine/src/cmd/plugin_summary.rs b/crates/engine/src/cmd/plugin_summary.rs index 88dded0350..8994bb921e 100644 --- a/crates/engine/src/cmd/plugin_summary.rs +++ b/crates/engine/src/cmd/plugin_summary.rs @@ -116,9 +116,8 @@ impl std::fmt::Debug for Summary { } } -/// `rasters`, of `dates` dates, as the layers a summary adds: made on its thread, and counted in -/// what the app holds. -fn held(rasters: Vec, dates: usize) -> Result { +/// `rasters` as the layers a summary adds, made on its thread, and the bytes they hold. +fn made(rasters: Vec) -> Result<(Vec<(String, RasterLayer)>, u64), String> { let layers = rasters.into_iter().map(super::super::cube::output_layer).collect::, _>>()?; let bytes = layers .iter() @@ -127,7 +126,7 @@ fn held(rasters: Vec, dates: usize) -> Result { pixels + l.embedded.as_ref().map_or(0, |e| e.len() as u64) }) .sum(); - Ok(Held { layers, dates, _holding: memory::Holding::of(bytes) }) + Ok((layers, bytes)) } impl PartialEq for Summary { @@ -228,12 +227,11 @@ impl Session { )); } let work = start(self)?; - // What those still to land will hold, with this one: those landed are counted in - // what the app holds already. - let planned = work.bytes - + self.url_waits.summaries.iter().map(|r| r.bytes).sum::() - + self.call_summaries.iter().map(|l| l.work.bytes).sum::(); - if let Some(room) = memory::share(memory::physical(), memory::held(), memory::available()) + // What those still being read will hold, with this one: those made or landed are + // counted in what the app holds already. + let (reading, held) = self.url_waits.reading_and_held(); + let planned = work.bytes + reading + self.call_summaries.iter().map(|l| l.work.bytes).sum::(); + if let Some(room) = memory::share(memory::physical(), held, memory::available()) && planned > room { let mb = |b: u64| b.div_ceil(1 << 20); @@ -336,8 +334,11 @@ impl super::fetch::UrlWaits { if cancel.load(Ordering::Relaxed) { Err(cancelled(command)) } else { r } }; // Its layers made here too, their GeoTIFFs written: the run again only adds them. - let out = out.and_then(|rasters| held(rasters, dates)); - *slot.lock().unwrap_or_else(|e| e.into_inner()) = Some(out); + let out = out.and_then(made); + // Counted in what the app holds as they are put in the slot, under its lock: a new + // read's plan finds them there or still to come, never both (`reading_and_held`). + let mut slot = slot.lock().unwrap_or_else(|e| e.into_inner()); + *slot = Some(out.map(|(layers, bytes)| Held { layers, dates, _holding: memory::Holding::of(bytes) })); }); if let Err(e) = spawned { *reading.slot.lock().unwrap_or_else(|e| e.into_inner()) = Some(Err(format!("{command} couldn't start: {e}"))); @@ -365,6 +366,15 @@ impl super::fetch::UrlWaits { } } + /// What the summaries still being read will hold, by what each planned, and what the app holds + /// now, read together under their slots' locks: one whose layers are made is counted in what + /// the app holds, and not again among those still being read. + pub(super) fn reading_and_held(&self) -> (u64, u64) { + let slots: Vec<_> = self.summaries.iter().map(|r| (r.bytes, r.slot.lock().unwrap_or_else(|e| e.into_inner()))).collect(); + let reading = slots.iter().filter(|(_, slot)| slot.is_none()).map(|(bytes, _)| bytes).sum(); + (reading, memory::held()) + } + /// How many summaries have landed whose commands haven't run again: each holds its layers. fn held_summaries(&self) -> usize { self.landed.iter().filter(|(.., added)| added.summary.is_some()).count() @@ -377,6 +387,14 @@ impl super::fetch::UrlWaits { } } + /// Stops the summaries being read that `kept` doesn't have: a failed command's, as its waits + /// go back to `kept`, from before it. + pub(crate) fn stop_summaries_beside(&self, kept: &Self) { + for r in self.summaries.iter().filter(|r| !kept.summarising(r.n)) { + r.cancel.store(true, Ordering::Relaxed); + } + } + /// Whether request `n` is a summary still being read: it isn't given up for taking long. pub(super) fn summarising(&self, n: u64) -> bool { self.summaries.iter().any(|r| r.n == n) @@ -433,6 +451,42 @@ mod tests { assert_eq!(landed, Some(Err("cube.reduce was cancelled".to_string()))); } + /// A read whose layers are made is counted in what the app holds, and no more among those still + /// to hold theirs: a new read's plan counts it once. + #[test] + fn a_read_made_is_counted_once() { + let mut waits = super::super::fetch::UrlWaits::default(); + let raster = || { + let t = rustgis_data::raster::GeoTransform { origin_x: 10.0, origin_y: 46.0, pixel_width: 0.25, pixel_height: -0.25 }; + Raster::new( + "r", + 4, + 4, + vec![vec![1.0; 16]], + t, + rustgis_data::raster::Crs::LonLat, + None, + rustgis_data::raster::ColorHint::Gray, + "Float32", + ) + .unwrap() + }; + let left = |n, work| Left { n, command: "cube.reduce", work, still: None, capture: rustgis_data::diagnostics::Capture::current() }; + waits.wait(1, asked("cube.reduce", &json!({"n": "made"}))); + waits.read_summary(left(1, Work::new(1, 2, 1000, move |_: &AtomicBool, _: &AtomicUsize| Ok(vec![raster()]))), "plugin:p/f"); + let started = web_time::Instant::now(); + while waits.summaries[0].slot.lock().unwrap().is_none() && started.elapsed() < web_time::Duration::from_secs(30) { + std::thread::sleep(std::time::Duration::from_millis(5)); // test-wait: the read ends on its thread + } + assert_eq!(waits.reading_and_held().0, 0, "made: in what the app holds"); + // One that hasn't started is counted by what it planned. + let turn = hold_turn(); + waits.wait(2, asked("cube.reduce", &json!({"n": "waits"}))); + waits.read_summary(left(2, Work::new(1, 2, 700, |_: &AtomicBool, _: &AtomicUsize| Ok(Vec::new()))), "plugin:p/f"); + assert_eq!(waits.reading_and_held().0, 700); + drop(turn); + } + /// A summary read off the frame lands for the command waiting for it, a cancelled one as its /// error; one no command waits for any more is stopped. #[test] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a4f5d2be2a..5298fa3d6d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -2726,6 +2726,8 @@ impl Session { self.request_only = outer_request_only; if res.is_err() { self.restore_url_request_checkpoint(requests); + // The summaries it started stop: those before it are kept, and nothing waits for the others. + self.url_waits.stop_summaries_beside(&retry_state.1); (self.plugin_retries, self.url_waits) = retry_state; // Keep only still-present old identities: drained bytes and terminal refusals stay consumed. let (kept, mut dropped): (Vec<_>, Vec<_>) = @@ -2907,6 +2909,8 @@ impl Session { (self.path, self.model_run, self.style_view) = (path, model_run, style_view); self.opened_package = opened_package; self.file_identity = file_identity; + // The replacement's summaries being read for plugin commands stop: its project is gone. + self.url_waits.stop_every_summary(); (self.pending, self.plugin_runs, self.plugin_retries, self.url_waits) = (pending, plugin_runs, plugin_retries, url_waits); let replaced = std::mem::replace(&mut self.file_outputs, file_outputs); (self.downloading, self.downloaded, self.url_requests) = (downloading, downloaded, url_requests); diff --git a/crates/engine/src/tests/plugin_summaries.rs b/crates/engine/src/tests/plugin_summaries.rs index 0b42a204a0..233ce6a7bd 100644 --- a/crates/engine/src/tests/plugin_summaries.rs +++ b/crates/engine/src/tests/plugin_summaries.rs @@ -5,9 +5,15 @@ use super::*; /// A collection "s2" of `dates` dates of a 4 × 4 band over [10, 11] × [45, 46], date k's cells all /// 10 (k + 1): its STAC API's address. fn collection(dates: usize) -> String { + collection_of(dates, 0.25) +} + +/// A collection "s2" of `dates` dates of a 4 × 4 band of `pixel`° cells from (10, 46), date k's +/// cells all 10 (k + 1), its items over [10, 11] × [45, 46]: its STAC API's address. +fn collection_of(dates: usize, pixel: f64) -> String { use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; let band = |k: usize| { - let t = GeoTransform { origin_x: 10.0, origin_y: 46.0, pixel_width: 0.25, pixel_height: -0.25 }; + let t = GeoTransform { origin_x: 10.0, origin_y: 46.0, pixel_width: pixel, pixel_height: -pixel }; let r = Raster::new("r", 4, 4, vec![vec![10.0 * (k + 1) as f32; 16]], t, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); rustgis_data::raster::cogwrite::write(&r, 0).unwrap() }; @@ -290,3 +296,63 @@ fn a_new_project_stops_the_summaries_of_the_old() { assert!(ran[0].1.is_ok(), "{ran:?}"); rustgis_plugins::unload("eng-summary-new-project"); } + +/// A command that replaced the project and then failed gives the old one back: the summaries the +/// replacement started stop with it, so the old project's next one isn't held behind them. +#[test] +fn a_project_given_back_stops_the_summaries_of_its_replacement() { + let mut s = world(); + plugin("eng-summary-given-back", &["edit", "files", "network"]); + fetch_mode(true, true); + let api = collection(3); + let e = s.guarded("test", true, |s| { + s.run("project.sample", &Value::Null)?; + // A read of the replacement that lasts until it is stopped. + s.start_test_summary("plugin:eng-summary-given-back/f"); + Err("failed once the project was replaced".to_string()) + }); + assert!(e.is_err()); + assert!(s.plugin_summaries().is_empty(), "not the replacement's"); + s.run_leaving_downloads("plugin:eng-summary-given-back/f", &reduce_call(&api, "mean")).unwrap(); + let ran = ran_again(&mut s); + assert_eq!(ran.len(), 1, "the old project's read lands: {ran:?}"); + assert!(ran[0].1.is_ok(), "{ran:?}"); + rustgis_plugins::unload("eng-summary-given-back"); +} + +/// A trend over a large grid plans all four of its outputs, with their GeoTIFFs: its run doesn't +/// cap them, only its area (`MAX_TREND_CELLS`). +#[test] +fn a_large_trend_plans_its_whole_output() { + let mut s = world(); + fetch_mode(true, true); + // 1° in cells of 0.000201°: about 4,976 × 4,976 cells, within a trend's area. + let api = collection_of(4, 0.000201); + let mut p = reduce(&api, "mean"); + p.as_object_mut().unwrap().remove("stat"); + let run = crate::cmd::cube::trend_start(&mut s, &p).unwrap(); + let whole = 4_975u64 * 4_975 * 4 * 8; + assert!(run.output_bytes() >= whole, "{} bytes planned, not the {whole} its outputs hold", run.output_bytes()); +} + +/// A command that failed leaves the summaries as they were before it: one it started stops, so the +/// next isn't held behind it. +#[test] +fn a_failed_command_stops_the_summaries_it_started() { + let mut s = world(); + plugin("eng-summary-failed", &["edit", "files", "network"]); + fetch_mode(true, true); + let api = collection(3); + let e = s.guarded("test", true, |s| { + // A read that lasts until it is stopped. + s.start_test_summary("plugin:eng-summary-failed/f"); + Err("failed once the read had started".to_string()) + }); + assert!(e.is_err()); + assert!(s.plugin_summaries().is_empty(), "not the failed command's"); + s.run_leaving_downloads("plugin:eng-summary-failed/f", &reduce_call(&api, "mean")).unwrap(); + let ran = ran_again(&mut s); + assert_eq!(ran.len(), 1, "the next read lands: {ran:?}"); + assert!(ran[0].1.is_ok(), "{ran:?}"); + rustgis_plugins::unload("eng-summary-failed"); +} From fbd82e47a88b7ee27b7b70018cc64489d7424661 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sat, 28 Nov 2026 10:05:35 -0300 Subject: [PATCH 4/4] fix(plugins): plan one output band for firstDate over several assets (#3183) ReduceRun::output_bytes now takes the slots as ReduceRun::run does: firstDate makes one date a cell for all the assets, so a band a group, and the other stats a band for each group and asset. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/cube.rs | 10 +++++---- crates/engine/src/tests/plugin_summaries.rs | 25 +++++++++++++++++++-- 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/cube.rs b/crates/engine/src/cmd/cube.rs index 4691ec5ea3..8f6982c18a 100644 --- a/crates/engine/src/cmd/cube.rs +++ b/crates/engine/src/cmd/cube.rs @@ -1842,11 +1842,13 @@ pub struct ReduceRun { } impl ReduceRun { - /// About the bytes its outputs hold once made, with their GeoTIFFs: the most a run can make - /// ([`MAX_REDUCED`] values) when the cube doesn't know its size, or for frequency, whose - /// classes aren't known before it is read. + /// About the bytes its outputs hold once made, with their GeoTIFFs: a band for each group and + /// asset (firstDate's one date for all the assets, as [`ReduceRun::run`] makes them); the most + /// a run can make ([`MAX_REDUCED`] values) when the cube doesn't know its size, or for + /// frequency, whose classes aren't known before it is read. pub fn output_bytes(&self) -> u64 { - let slots = (self.groups.len() * self.cube.assets().len().max(1)) as u64; + let per = if self.stat == Stat::FirstDate { 1 } else { self.cube.assets().len().max(1) }; + let slots = (self.groups.len() * per) as u64; let cells = self.cube.size().filter(|_| self.stat != Stat::Frequency).map(|(w, h)| (w as u64).saturating_mul(h as u64)); output_bytes(cells.map_or(MAX_REDUCED, |c| c.saturating_mul(slots).min(MAX_REDUCED))) } diff --git a/crates/engine/src/tests/plugin_summaries.rs b/crates/engine/src/tests/plugin_summaries.rs index 233ce6a7bd..f7a9a65c24 100644 --- a/crates/engine/src/tests/plugin_summaries.rs +++ b/crates/engine/src/tests/plugin_summaries.rs @@ -9,7 +9,8 @@ fn collection(dates: usize) -> String { } /// A collection "s2" of `dates` dates of a 4 × 4 band of `pixel`° cells from (10, 46), date k's -/// cells all 10 (k + 1), its items over [10, 11] × [45, 46]: its STAC API's address. +/// cells all 10 (k + 1), its items over [10, 11] × [45, 46]: its STAC API's address. The band is +/// each item's B04, and its B08 and B11 too. fn collection_of(dates: usize, pixel: f64) -> String { use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; let band = |k: usize| { @@ -24,7 +25,8 @@ fn collection_of(dates: usize, pixel: f64) -> String { format!( r#"{{"type": "Feature", "id": "s{k}", "collection": "s2", "bbox": [10, 45, 11, 46], "geometry": null, "properties": {{"datetime": "{d}T00:00:00Z", "bdc:tiles": ["t1"]}}, - "assets": {{"B04": {{"href": "{files}/b{k}.tif"}}}}}}"# + "assets": {{"B04": {{"href": "{files}/b{k}.tif"}}, "B08": {{"href": "{files}/b{k}.tif"}}, + "B11": {{"href": "{files}/b{k}.tif"}}}}}}"# ) }) .collect(); @@ -356,3 +358,22 @@ fn a_failed_command_stops_the_summaries_it_started() { assert!(ran[0].1.is_ok(), "{ran:?}"); rustgis_plugins::unload("eng-summary-failed"); } + +/// A summary of several bands plans an output band for each, but firstDate one for all of them: +/// one date a cell, the same for its bands. +#[test] +fn a_first_date_of_several_bands_plans_one_output() { + let mut s = world(); + fetch_mode(true, true); + let api = collection(3); + let planned = |s: &mut Session, stat: &str| { + let mut p = reduce(&api, stat); + let o = p.as_object_mut().unwrap(); + o.remove("asset"); + o.insert("assets".into(), json!(["B04", "B08", "B11"])); + crate::cmd::cube::reduce_start(s, &p).unwrap().output_bytes() + }; + // 4 × 4 cells, 8 bytes each for the raster and its GeoTIFF. + assert_eq!(planned(&mut s, "mean"), 16 * 3 * 8, "a band each"); + assert_eq!(planned(&mut s, "firstDate"), 16 * 8, "one for all three"); +}