From c06b661a740f82857749c4b0b33e370af5d4c9bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 04:53:06 -0500 Subject: [PATCH 01/19] fix(engine): a saved step that opens a project from its text requires what the project requires (#3462) Each capability's check decided on its own whether to read the text of a project.openText or project.fromTemplate step, and 45 of 51 never did, so a task, model or script could open a project using a setting an older release doesn't know and save the rest without a word. The text is now read once per step, as the project is read without repair, and the project's own capabilities are added to the step's, down to 32 projects deep. The eight checks that did read a project's text for these two commands no longer do: each read the project again, and a project opening a project that opens one cost about three times more at every level (31 s at 680 KB, 357 s at 2.7 MB). It is now 7 ms and 21 ms. Part of #3476 --- crates/engine/src/project_capabilities.rs | 246 +++++++++++------- crates/engine/src/tests.rs | 4 + .../src/tests/capabilities_inline_project.rs | 95 +++++++ 3 files changed, 246 insertions(+), 99 deletions(-) create mode 100644 crates/engine/src/tests/capabilities_inline_project.rs diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index e817be5fff..df1b8b5ec0 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -5,6 +5,7 @@ use rustgis_map::{Layer, Map, raster::RasterRenderer}; use serde::{Deserialize, Serialize}; use serde_json::Value; use std::borrow::Cow; +use std::cell::RefCell; use super::{FORMAT, ModelGraph, ModelNodeKind, ModelStep, Project}; use crate::cmd::exports::Output; @@ -31,6 +32,12 @@ impl<'de> Deserialize<'de> for Project { impl Project { /// Required features of all saved maps, snapshots and replayable commands/scripts. pub(crate) fn required_capabilities(&self) -> Vec<&'static str> { + self.required_capabilities_at(0) + } + + /// [`Project::required_capabilities`] of a project opened `depth` levels down by saved steps + /// ([`collect_opened_project`]). + fn required_capabilities_at(&self, depth: usize) -> Vec<&'static str> { let mut required = map_capabilities(self.maps.iter().chain(self.offline_areas.iter().map(|a| &a.data))); if !self.origin_id.is_empty() || self.field_origin.is_some() || self.offline_areas.iter().any(|area| !area.id.is_empty()) { required.push("field-origin"); @@ -94,8 +101,12 @@ impl Project { required.push("label-duplicates"); } let commands: Vec<&'static str> = - COMMAND_CAPABILITIES.iter().filter_map(|&(name, uses)| self.uses_commands(uses).then_some(name)).collect(); + COMMAND_CAPABILITIES.iter().filter_map(|&(name, uses)| self.uses_commands(&uses).then_some(name)).collect(); required.extend(commands.into_iter().filter(|name| !required.contains(name)).collect::>()); + // And what a project that a saved step opens from its text requires (#3462, #3476). + let opened = RefCell::new(Vec::new()); + self.uses_commands(&|id: &str, params: &Value| collect_opened_project(&opened, depth, id, params)); + merge_opened(&mut required, opened); if self.tasks.iter().any(|task| task.steps.iter().any(|step| command_uses_table_export_order(&step.command, &step.params))) || self.gp_history.iter().any(|record| { command_uses_table_export_order(&record.id, &record.params) @@ -132,12 +143,12 @@ impl Project { } /// Apply the same capability predicate to every replayable project container. - fn uses_commands(&self, uses: CommandCheck) -> bool { + fn uses_commands(&self, uses: &impl Fn(&str, &Value) -> bool) -> bool { self.models.iter().any(|m| model_uses(&m.steps, m.graph.as_ref(), uses)) - || self.tasks.iter().any(|t| t.steps.iter().any(|s| command_uses(&uses, &s.command, &s.params))) + || self.tasks.iter().any(|t| t.steps.iter().any(|s| command_uses(uses, &s.command, &s.params))) || self.gp_history.iter().any(|h| { - command_uses(&uses, if h.id.is_empty() { &h.tool } else { &h.id }, &h.params) - || h.command.as_ref().is_some_and(|(id, params)| command_uses(&uses, id, params)) + command_uses(uses, if h.id.is_empty() { &h.tool } else { &h.id }, &h.params) + || h.command.as_ref().is_some_and(|(id, params)| command_uses(uses, id, params)) }) || self.notebooks.iter().any(|n| { n.language().is_none() @@ -156,9 +167,71 @@ pub(crate) fn task_capabilities(steps: &[super::TaskStep]) -> Vec<&'static str> if steps.iter().any(|s| command_uses_table_export_order(&s.command, &s.params)) { required.push("table-export-order"); } + let opened = RefCell::new(Vec::new()); + for step in steps { + command_uses(&|id: &str, params: &Value| collect_opened_project(&opened, 0, id, params), &step.command, &step.params); + } + merge_opened(&mut required, opened); required } +/// How many projects deep a saved step's opened project is read for what it requires. +const MAX_OPENED_DEPTH: usize = 32; + +/// What a step that opens a project from its text requires: the project's own capabilities, +/// layout ones included (#3462, #3476). A saved step is checked one capability at a time, and +/// most of those checks read nothing of the text, so an older reader opened a project, dropped +/// what it didn't know and saved the rest without a word. The text is read once, as the project +/// is read without repair ([`Project::from_peer_raw`]), so what loading it would cut still +/// counts. The checks of single capabilities no longer read these two commands' text: each read the +/// project again, so the cost of a project that opens a project that opens one grew at every level. +/// A project opened by a step of a project opened by a step, and so on, is read by this down to +/// [`MAX_OPENED_DEPTH`] levels, each once; deeper isn't read. A `text` that holds a project +/// escapes it, so is longer than it and only so much nests; a `data` template (base64, a zip) isn't, +/// hence the depth. It bounds this walk only: the checks that read a style, layer or map given +/// inline still start again from the top when that text is a project. +/// Always `false`, so that whatever walks the commands ([`command_uses`], a script's +/// lines, a model's graph) visits every one of them. Text that isn't a project requires nothing. +fn collect_opened_project(found: &RefCell>, depth: usize, id: &str, params: &Value) -> bool { + // Nothing real holds a project this deep, and a chain of base64 zips (`data`) can be made of + // texts that don't get shorter, so the stack is what bounds it otherwise. + if depth >= MAX_OPENED_DEPTH { + return false; + } + let text = match id { + // It opens its `text` only, whatever else the step holds. + "project.openText" => params.get("text").and_then(Value::as_str).map(Cow::Borrowed), + "project.fromTemplate" => crate::cmd::items::inline_text(params).ok().flatten(), + "script.run" => { + if let Some(script) = params.get("script").and_then(Value::as_str) { + script_uses(script, |id, params| collect_opened_project(found, depth, id, params)); + } + None + } + _ => None, + }; + if let Some(project) = text.and_then(|t| Project::from_peer_raw(&t).ok()) { + // Asked before `found` is borrowed: the project's own walk never touches this cell. + let names = project.required_capabilities_at(depth + 1); + let mut found = found.borrow_mut(); + for name in names { + if !found.contains(&name) { + found.push(name); + } + } + } + false +} + +/// `opened`, a walk's findings ([`collect_opened_project`]), added to `required` after what it has. +fn merge_opened(required: &mut Vec<&'static str>, opened: RefCell>) { + for name in opened.into_inner() { + if !required.contains(&name) { + required.push(name); + } + } +} + type CommandCheck = fn(&str, &Value) -> bool; const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("slope-percent", command_uses_percent_slope), @@ -329,13 +402,11 @@ fn command_sets_generalize(id: &str, params: &Value) -> bool { && crate::cmd::f(params, "generalize") .is_some_and(|v| crate::cmd::raster::relief_generalize(Some(v)).is_ok_and(|g| g > 0.0)) } - // A style, layer, map or project given inline (`text` or `data`) that holds one (#3425 - // review); one read from a `"path"` is a file, whose header requires what it uses. - "style.add" | "style.import" | "layer.addLayerFile" | "map.import" | "project.fromTemplate" => { + // A style, layer or map given inline (`text` or `data`) that holds one (#3425 review); one + // read from a `"path"` is a file, whose header requires what it uses. + "style.add" | "style.import" | "layer.addLayerFile" | "map.import" => { crate::cmd::items::inline_text(params).ok().flatten().is_some_and(|t| text_generalizes(&t)) } - // It opens its `text` only, whatever else the step holds. - "project.openText" => params.get("text").and_then(Value::as_str).is_some_and(text_generalizes), "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_sets_generalize)), _ => false, } @@ -381,18 +452,16 @@ fn command_masks_by_raster(id: &str, params: &Value) -> bool { } } -/// A saved `style.add`, `style.import`, `layer.addLayerFile`, `map.import` or `project.openText` -/// whose inline style, layer, map or project (`text` or `data`) keeps Unique Values classes in +/// A saved `style.add`, `style.import`, `layer.addLayerFile` or `map.import` whose inline style, +/// layer or map (`text` or `data`) keeps Unique Values classes in /// their order (#3319): an older reader would take the renderer with the classes sorted. One read /// from a `"path"` is a file, whose header requires what it uses. Read only when the text names /// `keep_order` (or escapes, which could hide it). fn command_adds_kept_class_order(id: &str, params: &Value) -> bool { match id { - "style.add" | "style.import" | "layer.addLayerFile" | "map.import" | "project.fromTemplate" => { + "style.add" | "style.import" | "layer.addLayerFile" | "map.import" => { crate::cmd::items::inline_text(params).ok().flatten().is_some_and(|t| text_keeps_class_order(&t)) } - // It opens its `text` only, whatever else the step holds. - "project.openText" => params.get("text").and_then(Value::as_str).is_some_and(text_keeps_class_order), "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_adds_kept_class_order)), _ => false, } @@ -569,13 +638,11 @@ fn command_sets_obstacles(id: &str, params: &Value) -> bool { "labels.placement" => { params.get("obstacleWeight").and_then(crate::cmd::labels::number).is_some_and(|w| rustgis_map::symbology::label_weight(w) > 0) } - // A style, layer, map, project or template given inline (`text` or `data`) that holds one; one - // read from a `"path"` is a file, whose header requires what it uses. - "style.add" | "style.import" | "layer.addLayerFile" | "map.import" | "project.fromTemplate" => { + // A style, layer or map given inline (`text` or `data`) that holds one; one read from a + // `"path"` is a file, whose header requires what it uses. + "style.add" | "style.import" | "layer.addLayerFile" | "map.import" => { crate::cmd::items::inline_text(params).ok().flatten().is_some_and(|t| text_sets_obstacles(&t)) } - // It opens its `text` only, whatever else the step holds. - "project.openText" => params.get("text").and_then(Value::as_str).is_some_and(text_sets_obstacles), "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_sets_obstacles)), _ => false, } @@ -759,22 +826,11 @@ fn command_uses_legend_one_row(id: &str, params: &Value) -> bool { match id { "layout.addElement" | "layout.update" => matches!(crate::cmd::layout::legend_one_row_param(params), Ok(Some(true))), "layout.import" | "report.existingTemplate" => imported_layout_uses(id, params, &["\"one_row\""], legend_in_one_row), - // It opens its `text` only, whatever else the step holds. - "project.openText" => params.get("text").and_then(Value::as_str).is_some_and(text_lays_a_legend_in_one_row), - "project.fromTemplate" => crate::cmd::items::inline_text(params).ok().flatten().is_some_and(|t| text_lays_a_legend_in_one_row(&t)), "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_legend_one_row)), _ => false, } } -/// Whether a project's saved text requires `layout-legend-one-row`: for its layouts, its steps -/// or its notebooks. Parsed only when the text names the key, either way it -/// is written, may hide it ([`may_hide_a_key`]), or holds a step's base64 `data` ([`names_data`]). -fn text_lays_a_legend_in_one_row(text: &str) -> bool { - (["one_row", "oneRow"].iter().any(|key| text.contains(key)) || may_hide_a_key(text) || names_data(text)) - && inline_project_requires(text, "layout-legend-one-row") == Some(true) -} - /// Whether a project given as text requires `capability` for what it holds as written; `None` /// for text that isn't a project. Read without repair, so asking reads nothing the text names (#3530), /// and what loading it would cut still counts. @@ -831,24 +887,11 @@ fn command_uses_legend_patch_size(id: &str, params: &Value) -> bool { "layout.import" | "report.existingTemplate" => { imported_layout_uses(id, params, &["\"patch_width\"", "\"patch_height\""], legend_patch_features) } - // It opens its `text` only, whatever else the step holds. - "project.openText" => params.get("text").and_then(Value::as_str).is_some_and(text_gives_legend_patch_size), - "project.fromTemplate" => crate::cmd::items::inline_text(params).ok().flatten().is_some_and(|t| text_gives_legend_patch_size(&t)), "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_legend_patch_size)), _ => false, } } -/// Whether a project's saved text requires `layout-legend-patch-size`: for its layouts, its steps -/// or its notebooks. Parsed only when the text names a key, either way it is written, may hide it -/// ([`may_hide_a_key`]), or holds a step's base64 `data` ([`names_data`]). -fn text_gives_legend_patch_size(text: &str) -> bool { - (["patch_width", "patchWidth", "patch_height", "patchHeight"].iter().any(|key| text.contains(key)) - || may_hide_a_key(text) - || names_data(text)) - && inline_project_requires(text, "layout-legend-patch-size") == Some(true) -} - /// Whether a layout element is a legend whose patches aren't at the default size. fn legend_patch_features(e: &rustgis_map::layout::Element) -> bool { e.kind.legend_patch_features() @@ -882,22 +925,11 @@ fn command_numbers_extents(id: &str, params: &Value) -> bool { match id { "layout.update" => params.get("extentNumbers") == Some(&Value::Bool(true)), "layout.import" | "report.existingTemplate" => imported_layout_uses(id, params, &["\"extent_numbers\""], extent_numbers_features), - // It opens its `text` only, whatever else the step holds. - "project.openText" => params.get("text").and_then(Value::as_str).is_some_and(text_numbers_extents), - "project.fromTemplate" => crate::cmd::items::inline_text(params).ok().flatten().is_some_and(|t| text_numbers_extents(&t)), "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_numbers_extents)), _ => false, } } -/// Whether a project's saved text requires `layout-extent-numbers`: for its frames, its steps -/// or its notebooks. Parsed only when the text names the key, either way it -/// is written, may hide it ([`may_hide_a_key`]), or holds a step's base64 `data` ([`names_data`]). -fn text_numbers_extents(text: &str) -> bool { - (["extent_numbers", "extentNumbers"].iter().any(|key| text.contains(key)) || may_hide_a_key(text) || names_data(text)) - && inline_project_requires(text, "layout-extent-numbers") == Some(true) -} - /// Whether a layout element is a map frame that numbers its extent indicators. fn extent_numbers_features(e: &rustgis_map::layout::Element) -> bool { e.kind.numbers_extents() @@ -1403,23 +1435,11 @@ fn command_uses_north_arrow_font(id: &str, params: &Value) -> bool { match id { "layout.addElement" => adds_with_font(params, "northArrow"), "layout.import" | "report.existingTemplate" => imported_layout_uses(id, params, &["\"font"], north_arrows_with_font), - // It opens its `text` only, whatever else the step holds. - "project.openText" => params.get("text").and_then(Value::as_str).is_some_and(|t| text_gives_font(t, "layout-north-arrow-font")), - "project.fromTemplate" => { - crate::cmd::items::inline_text(params).ok().flatten().is_some_and(|t| text_gives_font(&t, "layout-north-arrow-font")) - } "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_north_arrow_font)), _ => false, } } -/// Whether a project's saved text requires the font `capability`: for its elements, its steps -/// or its notebooks. Parsed only when the text may name a font, may -/// hide the key ([`may_hide_a_key`]) or holds a step's base64 `data` ([`names_data`]). -fn text_gives_font(text: &str, capability: &str) -> bool { - (text.contains("font") || may_hide_a_key(text) || names_data(text)) && inline_project_requires(text, capability) == Some(true) -} - fn scale_bars_with_font(e: &rustgis_map::layout::Element) -> bool { e.kind.scale_bar_uses_font() } @@ -1430,10 +1450,6 @@ fn command_uses_scale_bar_font(id: &str, params: &Value) -> bool { match id { "layout.addElement" => adds_with_font(params, "scaleBar"), "layout.import" | "report.existingTemplate" => imported_layout_uses(id, params, &["\"font"], scale_bars_with_font), - "project.openText" => params.get("text").and_then(Value::as_str).is_some_and(|t| text_gives_font(t, "layout-scale-bar-font")), - "project.fromTemplate" => { - crate::cmd::items::inline_text(params).ok().flatten().is_some_and(|t| text_gives_font(&t, "layout-scale-bar-font")) - } "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_scale_bar_font)), _ => false, } @@ -1483,11 +1499,16 @@ fn imported_layout_text<'a>(id: &str, params: &'a Value) -> Option> /// Require only executable payloads being saved: graph files omit steps, web tools omit graphs. pub(crate) fn model_capabilities(steps: &[ModelStep], graph: Option<&ModelGraph>) -> Vec<&'static str> { - COMMAND_CAPABILITIES.iter().filter_map(|&(name, uses)| model_uses(steps, graph, uses).then_some(name)).collect() + let mut required: Vec<&'static str> = + COMMAND_CAPABILITIES.iter().filter_map(|&(name, uses)| model_uses(steps, graph, &uses).then_some(name)).collect(); + let opened = RefCell::new(Vec::new()); + model_uses(steps, graph, &|id: &str, params: &Value| collect_opened_project(&opened, 0, id, params)); + merge_opened(&mut required, opened); + required } /// Traverse executable model nodes with the same predicate used for project commands. -fn model_uses(steps: &[ModelStep], graph: Option<&ModelGraph>, uses: CommandCheck) -> bool { +fn model_uses(steps: &[ModelStep], graph: Option<&ModelGraph>, uses: &impl Fn(&str, &Value) -> bool) -> bool { steps.iter().any(|s| uses(&s.tool, &s.params)) || graph.is_some_and(|g| g.nodes.iter().any(|n| n.kind == ModelNodeKind::Tool && uses(n.tool.as_deref().unwrap_or(""), &n.params))) } @@ -2147,6 +2168,37 @@ mod tests { use super::*; use serde_json::{Value, json}; + /// Whether a saved step `id` with `params` requires `capability`, as a saved model's step does. + fn requires(capability: &str, id: &str, params: Value) -> bool { + model_capabilities(&[ModelStep { tool: id.into(), params }], None).contains(&capability) + } + + /// A project opened by a project opened by a step, and so on, is read by the walk of these two + /// commands down to [`MAX_OPENED_DEPTH`] levels and no deeper: a chain of base64 zips doesn't get shorter at + /// each level, so the text can't bound it, and a chain of `text` projects can't be built + /// that deep (each level escapes the one inside it). + #[test] + fn opened_projects_are_read_only_so_deep() { + let (text, _) = + Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap().saved_text(None).unwrap(); + let params = json!({"text": text}); + let at = |depth: usize| { + let found = RefCell::new(Vec::new()); + assert!(!collect_opened_project(&found, depth, "project.openText", ¶ms), "it never answers"); + found.into_inner() + }; + assert_eq!(at(0), ["layout-extent-indicators"]); + assert_eq!(at(MAX_OPENED_DEPTH - 1), ["layout-extent-indicators"]); + assert!(at(MAX_OPENED_DEPTH).is_empty()); + } + + /// The text of an empty project holding `tasks`. + fn with_tasks(tasks: Value) -> String { + let mut project = serde_json::to_value(Project::default()).unwrap(); + project["tasks"] = tasks; + project.to_string() + } + /// The one-row check of a step that opens an inline project asks only what that project /// needs: a raster it names, read in place from a server, is never asked for. #[test] @@ -2163,8 +2215,8 @@ mod tests { crate::render::rustgis_tiles::cache::allow_named(&scene); s.wait_in_place_reads(); while listener.accept().is_ok() {} - assert!(command_uses_legend_one_row("project.openText", &json!({"text": text}))); - assert!(command_uses_legend_one_row("project.fromTemplate", &json!({"text": text}))); + assert!(requires("layout-legend-one-row", "project.openText", json!({"text": text}))); + assert!(requires("layout-legend-one-row", "project.fromTemplate", json!({"text": text}))); for _ in 0..20 { let nothing = listener.accept().err().map(|e| e.kind()); assert_eq!(nothing, Some(std::io::ErrorKind::WouldBlock), "the raster was read"); @@ -2179,7 +2231,7 @@ mod tests { let opens = |params: Value| { let mut project = serde_json::to_value(Project::default()).unwrap(); project["tasks"] = json!([{"name": "Size", "steps": [{"title": "Size", "command": "layout.update", "params": params}]}]); - command_uses_legend_patch_size("project.openText", &json!({"text": project.to_string()})) + requires("layout-legend-patch-size", "project.openText", json!({"text": project.to_string()})) }; assert!(opens(json!({"element": 1, "patchWidth": 20}))); assert!(opens(json!({"element": 1, "patchHeight": 12}))); @@ -2226,20 +2278,20 @@ mod tests { s.project } - /// Asking what a step that opens an inline project needs reads nothing that project names, + /// What a step that opens an inline project requires is asked without reading anything that project names, /// as saved, without its header, from a script and from a step of a step (#3530). #[test] - fn the_checks_of_an_inline_project_read_nothing_it_names() { - let checks: [(&str, CommandCheck); 6] = [ - ("label-obstacles", command_sets_obstacles), - ("shaded-relief-generalize", command_sets_generalize), - ("layout-legend-patch-size", command_uses_legend_patch_size), - ("layout-extent-numbers", command_numbers_extents), - ("layout-north-arrow-font", command_uses_north_arrow_font), - ("layout-scale-bar-font", command_uses_scale_bar_font), + fn asking_what_an_inline_project_needs_reads_nothing_it_names() { + let checks = [ + "label-obstacles", + "shaded-relief-generalize", + "layout-legend-patch-size", + "layout-extent-numbers", + "layout-north-arrow-font", + "layout-scale-bar-font", ]; let mut listeners = Vec::new(); - for (capability, check) in checks { + for capability in checks { for wanted in [true, false] { let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); listener.set_nonblocking(true).unwrap(); @@ -2255,12 +2307,12 @@ mod tests { crate::Session::new(project).wait_in_place_reads(); while listener.accept().is_ok() {} for text in [saved.clone(), headerless.to_string(), outer.to_string()] { - assert_eq!(check("project.openText", &json!({"text": text})), wanted, "{capability}"); - assert_eq!(check("project.fromTemplate", &json!({"text": text})), wanted, "{capability} in a template"); + assert_eq!(requires(capability, "project.openText", json!({"text": text})), wanted, "{capability}"); + assert_eq!(requires(capability, "project.fromTemplate", json!({"text": text})), wanted, "{capability} in a template"); let script = format!("project.openText {}", json!({"text": text})); - assert_eq!(check("script.run", &json!({"script": script})), wanted, "{capability} in a script"); + assert_eq!(requires(capability, "script.run", json!({"script": script})), wanted, "{capability} in a script"); } - assert!(!check("project.openText", &json!({"text": "{\"maps\": \"font generalize extent_numbers\""}))); + assert!(!requires(capability, "project.openText", json!({"text": "{\"maps\": \"font generalize extent_numbers\""}))); listeners.push((capability, wanted, listener)); } } @@ -2286,7 +2338,7 @@ mod tests { layouts.push(with_font); text["layouts"] = Value::Array(layouts); assert_eq!(Project::from_json(&text.to_string()).unwrap().layouts.len(), crate::project::MAX_LAYOUTS, "loading cuts it"); - assert!(command_uses_north_arrow_font("project.openText", &json!({"text": text.to_string()}))); + assert!(requires("layout-north-arrow-font", "project.openText", json!({"text": text.to_string()}))); } /// A coordinate system saved with its WKT requires `crs-wkt` only when its PROJ definition, @@ -2629,8 +2681,6 @@ mod tests { (&["dggs-system"], "a5Aggregate", json!({"system": "S2"})), (&["label-weight"], "labels.placement", json!({"weight": 9})), (&["label-obstacles"], "labels.placement", json!({"obstacleWeight": 9})), - // A template opened from text holds a project too. - (&["label-obstacles"], "project.fromTemplate", json!({"text": include_str!("../../../schema/fixtures/label_obstacles.rgis")})), (&["unique-keep-order"], "style.add", json!({"text": kept_order_style()})), (&["label-clearance"], "labels.placement", json!({"clearance": 9})), (&["label-duplicates"], "labels.placement", json!({"removeDuplicates": 20})), @@ -2704,7 +2754,7 @@ mod tests { for (capability, id, params) in samples { let step = [ModelStep { tool: id.into(), params: params.clone() }]; let names: Vec<&str> = - COMMAND_CAPABILITIES.iter().filter_map(|&(name, uses)| model_uses(&step, None, uses).then_some(name)).collect(); + COMMAND_CAPABILITIES.iter().filter_map(|&(name, uses)| model_uses(&step, None, &uses).then_some(name)).collect(); assert_eq!(names, capability, "the sample {id} {params} requires exactly its own capability"); covered.extend(capability.iter().copied()); for (index, saved) in saved_requires_of_inline_graph(&graph_of_one_tool(id, params.clone())).into_iter().enumerate() { @@ -2799,20 +2849,18 @@ mod tests { use base64::Engine; let data = base64::engine::general_purpose::STANDARD.encode(kept_order_style()); let step = json!({"title": "C:\\styles", "command": "style.add", "params": {"data": data}}); - let text = json!({"tasks": [{"name": "Add", "steps": [step]}]}).to_string(); + let text = with_tasks(json!([{"name": "Add", "steps": [step]}])); assert!(!text.contains("keep_order") && !may_hide_a_key(&text), "{text}"); let needs = |text: &str| model_capabilities(&[ModelStep { tool: "project.openText".into(), params: json!({"text": text}) }], None); assert_eq!(needs(&text), ["unique-keep-order"]); // Nested as a string inside another project's step, its `data` key is escaped. let outer = - json!({"tasks": [{"name": "Open", "steps": [{"title": "Open", "command": "project.openText", "params": {"text": text}}]}]}) - .to_string(); + with_tasks(json!([{"name": "Open", "steps": [{"title": "Open", "command": "project.openText", "params": {"text": text}}]}])); assert!(!outer.contains("keep_order"), "{outer}"); assert_eq!(needs(&outer), ["unique-keep-order"]); // Two levels deeper still, its `data` key is escaped seven backslashes deep. let open = |text: &str| { - json!({"tasks": [{"name": "Open", "steps": [{"title": "Open", "command": "project.openText", "params": {"text": text}}]}]}) - .to_string() + with_tasks(json!([{"name": "Open", "steps": [{"title": "Open", "command": "project.openText", "params": {"text": text}}]}])) }; let deepest = open(&open(&outer)); assert!(!deepest.contains("keep_order") && !deepest.contains("data\\\\\\\"") && names_data(&deepest), "{deepest}"); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 40e499f3f5..9c4d0d434f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -220,6 +220,10 @@ mod layout_colorbar; #[path = "tests/layout_open.rs"] mod layout_open; +/// A saved step that opens a project from its text (#3462, #3476). +#[path = "tests/capabilities_inline_project.rs"] +mod capabilities_inline_project; + /// A north arrow's font (#3467). #[path = "tests/layout_north_font.rs"] mod layout_north_font; diff --git a/crates/engine/src/tests/capabilities_inline_project.rs b/crates/engine/src/tests/capabilities_inline_project.rs new file mode 100644 index 0000000000..b781408f1e --- /dev/null +++ b/crates/engine/src/tests/capabilities_inline_project.rs @@ -0,0 +1,95 @@ +//! A saved step that opens a project from its text requires what that project requires (#3462, +//! #3476). + +use super::*; +use crate::project::{ModelStep, TaskStep, model_capabilities, task_capabilities}; +use base64::Engine; + +/// Every project fixture with a `requires` header: its text without the header, and the +/// capabilities the header names. +fn fixtures() -> Vec<(String, String, Vec)> { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../schema/fixtures"); + let mut found = Vec::new(); + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + let name = path.file_name().unwrap().to_string_lossy().into_owned(); + if !name.ends_with(".rgis") { + continue; + } + let mut project: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); + let requires: Vec = project + .as_object_mut() + .and_then(|o| o.remove("requires")) + .map(|r| serde_json::from_value(r).unwrap_or_else(|e| panic!("{name}: {e}"))) + .unwrap_or_default(); + if !requires.is_empty() { + found.push((name, project.to_string(), requires)); + } + } + // Most fixtures carry a header; none found means the folder wasn't read. + assert!(!found.is_empty(), "the fixtures were not found"); + found +} + +/// The four places a saved step is read: a recorded model step, a task's step, a line of a script +/// and a project holding the task. Each answers what the step requires. +fn needs(id: &str, params: Value) -> [Vec; 4] { + let own = |v: Vec<&'static str>| v.into_iter().map(String::from).collect::>(); + let line = format!("{id} {params}"); + let step = + |command: &str, params: Value| TaskStep { title: "Open".into(), instructions: String::new(), command: command.into(), params }; + let mut in_a_task = Project::default(); + in_a_task.tasks = vec![crate::project::Task { name: "Open".into(), description: String::new(), steps: vec![step(id, params.clone())] }]; + [ + own(model_capabilities(&[ModelStep { tool: id.into(), params: params.clone() }], None)), + own(task_capabilities(&[step(id, params)])), + own(model_capabilities(&[ModelStep { tool: "script.run".into(), params: json!({"script": line}) }], None)), + own(in_a_task.required_capabilities()), + ] +} + +/// Opening a project from its text asks for exactly the capabilities the project asks for: the layout +/// ones, and the rest, whichever fixture it is. +#[test] +fn opening_a_project_from_its_text_requires_what_it_requires() { + for (name, text, requires) in fixtures() { + // A template is given by its `text` or by its base64 `data`; opening reads `text` only. + let data = base64::engine::general_purpose::STANDARD.encode(&text); + for (id, params) in [ + ("project.openText", json!({"text": text})), + ("project.fromTemplate", json!({"text": text})), + ("project.fromTemplate", json!({"data": data})), + ] { + for (place, mut found) in ["a model step", "a task", "a script", "a project's task"].iter().zip(needs(id, params.clone())) { + found.sort(); + found.dedup(); + let mut wanted = requires.clone(); + wanted.sort(); + assert_eq!(found, wanted, "{id} {params:.60} of {name} in {place}"); + } + } + } +} + +/// #3462: several extent indicators in a frame, without a header on the opened project. +#[test] +fn an_opened_project_with_several_extent_indicators_requires_them() { + let (_, text, _) = fixtures().into_iter().find(|(n, _, _)| n == "layout_extent_indicators.rgis").unwrap(); + assert!(text.contains("more_extents")); + for found in needs("project.openText", json!({"text": text})) { + assert!(found.contains(&"layout-extent-indicators".to_string()), "{found:?}"); + } +} + +/// A project with nothing new in it, and text that is no project, ask for nothing. +#[test] +fn what_needs_nothing_requires_nothing() { + let plain = Project::default().saved_text(None).unwrap().0; + for text in [plain.as_str(), "not a project", "{\"maps\": 1}", ""] { + for id in ["project.openText", "project.fromTemplate"] { + for found in needs(id, json!({"text": text})) { + assert!(found.is_empty(), "{id} of {text:?}: {found:?}"); + } + } + } +} From 0671cfc55a5661b50d5c591870d710791c713728 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 07:30:01 -0500 Subject: [PATCH 02/19] fix(engine): read a text that several steps open once, not once per step (#3462) Two steps opening the same zip of a template, which deflate stores once, branched at every level of the nest, so a small file made the walk read about k^depth projects. What each text required is now kept for the walk, by its depth, length and hash. --- crates/engine/src/project_capabilities.rs | 80 +++++++++++++++++------ 1 file changed, 61 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index df1b8b5ec0..535b28331d 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -32,12 +32,12 @@ impl<'de> Deserialize<'de> for Project { impl Project { /// Required features of all saved maps, snapshots and replayable commands/scripts. pub(crate) fn required_capabilities(&self) -> Vec<&'static str> { - self.required_capabilities_at(0) + self.required_capabilities_at(0, &Seen::default()) } /// [`Project::required_capabilities`] of a project opened `depth` levels down by saved steps /// ([`collect_opened_project`]). - fn required_capabilities_at(&self, depth: usize) -> Vec<&'static str> { + fn required_capabilities_at(&self, depth: usize, seen: &Seen) -> Vec<&'static str> { let mut required = map_capabilities(self.maps.iter().chain(self.offline_areas.iter().map(|a| &a.data))); if !self.origin_id.is_empty() || self.field_origin.is_some() || self.offline_areas.iter().any(|area| !area.id.is_empty()) { required.push("field-origin"); @@ -105,7 +105,7 @@ impl Project { required.extend(commands.into_iter().filter(|name| !required.contains(name)).collect::>()); // And what a project that a saved step opens from its text requires (#3462, #3476). let opened = RefCell::new(Vec::new()); - self.uses_commands(&|id: &str, params: &Value| collect_opened_project(&opened, depth, id, params)); + self.uses_commands(&|id: &str, params: &Value| collect_opened_project(&opened, seen, depth, id, params)); merge_opened(&mut required, opened); if self.tasks.iter().any(|task| task.steps.iter().any(|step| command_uses_table_export_order(&step.command, &step.params))) || self.gp_history.iter().any(|record| { @@ -167,14 +167,24 @@ pub(crate) fn task_capabilities(steps: &[super::TaskStep]) -> Vec<&'static str> if steps.iter().any(|s| command_uses_table_export_order(&s.command, &s.params)) { required.push("table-export-order"); } - let opened = RefCell::new(Vec::new()); + let (opened, seen) = (RefCell::new(Vec::new()), Seen::default()); for step in steps { - command_uses(&|id: &str, params: &Value| collect_opened_project(&opened, 0, id, params), &step.command, &step.params); + command_uses(&|id: &str, params: &Value| collect_opened_project(&opened, &seen, 0, id, params), &step.command, &step.params); } merge_opened(&mut required, opened); required } +// The projects read by `collect_opened_project` on this thread, for the tests. +#[cfg(test)] +thread_local! { + static PARSED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// What each text a walk has read required, by its depth, length and hash: a text opened by several +/// steps (a zip of the same template stored once and opened many times) is read once. +type Seen = RefCell>>; + /// How many projects deep a saved step's opened project is read for what it requires. const MAX_OPENED_DEPTH: usize = 32; @@ -186,13 +196,13 @@ const MAX_OPENED_DEPTH: usize = 32; /// counts. The checks of single capabilities no longer read these two commands' text: each read the /// project again, so the cost of a project that opens a project that opens one grew at every level. /// A project opened by a step of a project opened by a step, and so on, is read by this down to -/// [`MAX_OPENED_DEPTH`] levels, each once; deeper isn't read. A `text` that holds a project +/// [`MAX_OPENED_DEPTH`] levels, each distinct text once ([`Seen`]); deeper isn't read. A `text` that holds a project /// escapes it, so is longer than it and only so much nests; a `data` template (base64, a zip) isn't, /// hence the depth. It bounds this walk only: the checks that read a style, layer or map given /// inline still start again from the top when that text is a project. /// Always `false`, so that whatever walks the commands ([`command_uses`], a script's /// lines, a model's graph) visits every one of them. Text that isn't a project requires nothing. -fn collect_opened_project(found: &RefCell>, depth: usize, id: &str, params: &Value) -> bool { +fn collect_opened_project(found: &RefCell>, seen: &Seen, depth: usize, id: &str, params: &Value) -> bool { // Nothing real holds a project this deep, and a chain of base64 zips (`data`) can be made of // texts that don't get shorter, so the stack is what bounds it otherwise. if depth >= MAX_OPENED_DEPTH { @@ -204,20 +214,32 @@ fn collect_opened_project(found: &RefCell>, depth: usize, id: "project.fromTemplate" => crate::cmd::items::inline_text(params).ok().flatten(), "script.run" => { if let Some(script) = params.get("script").and_then(Value::as_str) { - script_uses(script, |id, params| collect_opened_project(found, depth, id, params)); + script_uses(script, |id, params| collect_opened_project(found, seen, depth, id, params)); } None } _ => None, }; - if let Some(project) = text.and_then(|t| Project::from_peer_raw(&t).ok()) { - // Asked before `found` is borrowed: the project's own walk never touches this cell. - let names = project.required_capabilities_at(depth + 1); - let mut found = found.borrow_mut(); - for name in names { - if !found.contains(&name) { - found.push(name); - } + let Some(text) = text else { return false }; + let key = { + use std::hash::{Hash, Hasher}; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + text.hash(&mut hasher); + (depth, text.len(), hasher.finish()) + }; + // Asked before `found` is borrowed: the project's own walk never touches this cell. + let cached = seen.borrow().get(&key).cloned(); + let names = cached.unwrap_or_else(|| { + #[cfg(test)] + PARSED.with(|n| n.set(n.get() + 1)); + let names = Project::from_peer_raw(&text).ok().map(|p| p.required_capabilities_at(depth + 1, seen)).unwrap_or_default(); + seen.borrow_mut().insert(key, names.clone()); + names + }); + let mut found = found.borrow_mut(); + for name in names { + if !found.contains(&name) { + found.push(name); } } false @@ -1501,8 +1523,8 @@ fn imported_layout_text<'a>(id: &str, params: &'a Value) -> Option> pub(crate) fn model_capabilities(steps: &[ModelStep], graph: Option<&ModelGraph>) -> Vec<&'static str> { let mut required: Vec<&'static str> = COMMAND_CAPABILITIES.iter().filter_map(|&(name, uses)| model_uses(steps, graph, &uses).then_some(name)).collect(); - let opened = RefCell::new(Vec::new()); - model_uses(steps, graph, &|id: &str, params: &Value| collect_opened_project(&opened, 0, id, params)); + let (opened, seen) = (RefCell::new(Vec::new()), Seen::default()); + model_uses(steps, graph, &|id: &str, params: &Value| collect_opened_project(&opened, &seen, 0, id, params)); merge_opened(&mut required, opened); required } @@ -2173,6 +2195,26 @@ mod tests { model_capabilities(&[ModelStep { tool: id.into(), params }], None).contains(&capability) } + /// The same text opened by several steps is read once, however many steps open it and however + /// deep: a zip of the same template repeated costs next to nothing to store, so a few steps + /// opening it at each level would otherwise be read once per way down. + #[test] + fn a_text_opened_by_several_steps_is_read_once() { + let (text, _) = + Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap().saved_text(None).unwrap(); + let step = |id: &str| json!({"title": "Open", "command": id, "params": {"text": text}}); + let mut inner = serde_json::to_value(Project::default()).unwrap(); + inner["tasks"] = json!([{"name": "Twice", "steps": [step("project.openText"), step("project.fromTemplate")]}]); + let mut outer = serde_json::to_value(Project::default()).unwrap(); + let open = |text: &Value| json!({"title": "Open", "command": "project.openText", "params": {"text": text.to_string()}}); + outer["tasks"] = json!([{"name": "Again", "steps": [open(&inner), open(&inner), open(&inner)]}]); + let outer = Project::from_peer_raw(&outer.to_string()).unwrap(); + PARSED.with(|n| n.set(0)); + assert_eq!(outer.required_capabilities(), ["layout-extent-indicators"]); + // The inner project once, and the template once inside it. + assert_eq!(PARSED.with(std::cell::Cell::get), 2); + } + /// A project opened by a project opened by a step, and so on, is read by the walk of these two /// commands down to [`MAX_OPENED_DEPTH`] levels and no deeper: a chain of base64 zips doesn't get shorter at /// each level, so the text can't bound it, and a chain of `text` projects can't be built @@ -2184,7 +2226,7 @@ mod tests { let params = json!({"text": text}); let at = |depth: usize| { let found = RefCell::new(Vec::new()); - assert!(!collect_opened_project(&found, depth, "project.openText", ¶ms), "it never answers"); + assert!(!collect_opened_project(&found, &Seen::default(), depth, "project.openText", ¶ms), "it never answers"); found.into_inner() }; assert_eq!(at(0), ["layout-extent-indicators"]); From cbc1e15e330f314aef53541173861ff36f4c623e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 07:40:55 -0500 Subject: [PATCH 03/19] fix(engine): key what a walk has read by the text, not by a digest of it (#3462) Two texts of the same length and depth whose 64-bit digests collide shared one entry, so one could inherit the other's capabilities. The cache is now keyed by the depth and the text itself. --- crates/engine/src/project_capabilities.rs | 26 ++++++++++------------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 535b28331d..b3a4cffd34 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -181,9 +181,9 @@ thread_local! { static PARSED: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// What each text a walk has read required, by its depth, length and hash: a text opened by several -/// steps (a zip of the same template stored once and opened many times) is read once. -type Seen = RefCell>>; +/// What each text a walk has read required, by its depth and the text: one opened by several steps +/// (a zip of the same template stored once and opened many times) is read once. +type Seen = RefCell>>; /// How many projects deep a saved step's opened project is read for what it requires. const MAX_OPENED_DEPTH: usize = 32; @@ -221,18 +221,14 @@ fn collect_opened_project(found: &RefCell>, seen: &Seen, depth _ => None, }; let Some(text) = text else { return false }; - let key = { - use std::hash::{Hash, Hasher}; - let mut hasher = std::collections::hash_map::DefaultHasher::new(); - text.hash(&mut hasher); - (depth, text.len(), hasher.finish()) - }; + // Keyed by the text itself, compared whole: a digest of it could collide. + let key = (depth, text.into_owned()); // Asked before `found` is borrowed: the project's own walk never touches this cell. let cached = seen.borrow().get(&key).cloned(); let names = cached.unwrap_or_else(|| { #[cfg(test)] PARSED.with(|n| n.set(n.get() + 1)); - let names = Project::from_peer_raw(&text).ok().map(|p| p.required_capabilities_at(depth + 1, seen)).unwrap_or_default(); + let names = Project::from_peer_raw(&key.1).ok().map(|p| p.required_capabilities_at(depth + 1, seen)).unwrap_or_default(); seen.borrow_mut().insert(key, names.clone()); names }); @@ -2215,12 +2211,12 @@ mod tests { assert_eq!(PARSED.with(std::cell::Cell::get), 2); } - /// A project opened by a project opened by a step, and so on, is read by the walk of these two - /// commands down to [`MAX_OPENED_DEPTH`] levels and no deeper: a chain of base64 zips doesn't get shorter at - /// each level, so the text can't bound it, and a chain of `text` projects can't be built - /// that deep (each level escapes the one inside it). + /// The walk of these two commands reads a project down to [`MAX_OPENED_DEPTH`] levels and + /// nothing at that depth or deeper. Called at a chosen depth: a chain of `text` projects can't + /// be built that deep (each level escapes the one inside it), and one of base64 zips is the + /// case the limit is for. #[test] - fn opened_projects_are_read_only_so_deep() { + fn the_walk_of_opened_projects_stops_at_its_depth() { let (text, _) = Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap().saved_text(None).unwrap(); let params = json!({"text": text}); From e0bf46437abb4627acc0743d5b5413801b98d290 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 07:50:30 -0500 Subject: [PATCH 04/19] fix(engine): look a read text up without copying it, and say the cache is per depth (#3462) A hit in the walk's cache copied the whole opened text first, since the key was built before the lookup. It is now keyed by depth and then the text, looked up borrowed and copied on insert only. The docs say a text is read once at each depth, which is what the cache does. --- crates/engine/src/project_capabilities.rs | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index b3a4cffd34..b8c221b816 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -181,9 +181,10 @@ thread_local! { static PARSED: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// What each text a walk has read required, by its depth and the text: one opened by several steps -/// (a zip of the same template stored once and opened many times) is read once. -type Seen = RefCell>>; +/// What each text a walk has read required, by its depth and then the text: one opened by several +/// steps at the same depth (a zip of the same template stored once and opened many times) is read +/// once. Looked up borrowed, so a hit copies nothing. +type Seen = RefCell>>>; /// How many projects deep a saved step's opened project is read for what it requires. const MAX_OPENED_DEPTH: usize = 32; @@ -196,7 +197,7 @@ const MAX_OPENED_DEPTH: usize = 32; /// counts. The checks of single capabilities no longer read these two commands' text: each read the /// project again, so the cost of a project that opens a project that opens one grew at every level. /// A project opened by a step of a project opened by a step, and so on, is read by this down to -/// [`MAX_OPENED_DEPTH`] levels, each distinct text once ([`Seen`]); deeper isn't read. A `text` that holds a project +/// [`MAX_OPENED_DEPTH`] levels, each text once at each depth ([`Seen`]); deeper isn't read. A `text` that holds a project /// escapes it, so is longer than it and only so much nests; a `data` template (base64, a zip) isn't, /// hence the depth. It bounds this walk only: the checks that read a style, layer or map given /// inline still start again from the top when that text is a project. @@ -222,14 +223,13 @@ fn collect_opened_project(found: &RefCell>, seen: &Seen, depth }; let Some(text) = text else { return false }; // Keyed by the text itself, compared whole: a digest of it could collide. - let key = (depth, text.into_owned()); // Asked before `found` is borrowed: the project's own walk never touches this cell. - let cached = seen.borrow().get(&key).cloned(); + let cached = seen.borrow().get(&depth).and_then(|texts| texts.get(&*text)).cloned(); let names = cached.unwrap_or_else(|| { #[cfg(test)] PARSED.with(|n| n.set(n.get() + 1)); - let names = Project::from_peer_raw(&key.1).ok().map(|p| p.required_capabilities_at(depth + 1, seen)).unwrap_or_default(); - seen.borrow_mut().insert(key, names.clone()); + let names = Project::from_peer_raw(&text).ok().map(|p| p.required_capabilities_at(depth + 1, seen)).unwrap_or_default(); + seen.borrow_mut().entry(depth).or_default().insert(text.into_owned(), names.clone()); names }); let mut found = found.borrow_mut(); @@ -2191,9 +2191,9 @@ mod tests { model_capabilities(&[ModelStep { tool: id.into(), params }], None).contains(&capability) } - /// The same text opened by several steps is read once, however many steps open it and however - /// deep: a zip of the same template repeated costs next to nothing to store, so a few steps - /// opening it at each level would otherwise be read once per way down. + /// The same text opened by several steps at one depth is read once, however many steps open it: + /// a zip of the same template repeated costs next to nothing to store, so a few steps opening + /// it at each level would otherwise be read once per way down. #[test] fn a_text_opened_by_several_steps_is_read_once() { let (text, _) = From afbc88f5d86d51cb0989bbc342ea3300a58201ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 08:06:01 -0500 Subject: [PATCH 05/19] fix(engine): keep a digest of what a walk has read, and require everything past the depth limit (#3462) The walk kept every decoded text until it ended, so steps opening zips that inflate to a gigabyte held that much on every save. It keeps a SHA-256 of the step's text or data now, looked up before anything is decoded. Past 32 levels a step that opens a text requires every capability a release knows, so an older release refuses it instead of dropping what it can't see. --- crates/engine/src/project_capabilities.rs | 118 ++++++++++++++-------- 1 file changed, 78 insertions(+), 40 deletions(-) diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index b8c221b816..69b1e0f9b4 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -181,9 +181,11 @@ thread_local! { static PARSED: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// What each text a walk has read required, by its depth and then the text: one opened by several -/// steps at the same depth (a zip of the same template stored once and opened many times) is read -/// once. Looked up borrowed, so a hit copies nothing. +/// What each text a walk has read required, by its depth and then a digest of where it came from +/// (its `text` or its base64 `data`, as the step gives it): one opened by several steps at the same +/// depth (a zip of the same template stored once and opened many times) is read once, and what is +/// kept is 64 bytes, never the decoded text, which can be a gigabyte. A SHA-256 of the source is +/// looked up before anything is decoded, so a hit decodes nothing either. type Seen = RefCell>>>; /// How many projects deep a saved step's opened project is read for what it requires. @@ -197,41 +199,52 @@ const MAX_OPENED_DEPTH: usize = 32; /// counts. The checks of single capabilities no longer read these two commands' text: each read the /// project again, so the cost of a project that opens a project that opens one grew at every level. /// A project opened by a step of a project opened by a step, and so on, is read by this down to -/// [`MAX_OPENED_DEPTH`] levels, each text once at each depth ([`Seen`]); deeper isn't read. A `text` that holds a project -/// escapes it, so is longer than it and only so much nests; a `data` template (base64, a zip) isn't, -/// hence the depth. It bounds this walk only: the checks that read a style, layer or map given -/// inline still start again from the top when that text is a project. +/// [`MAX_OPENED_DEPTH`] levels, each text once at each depth ([`Seen`]). A `text` that holds a +/// project escapes it, so is longer than it and only so much nests; a `data` template (base64, a +/// zip) isn't, hence the depth. A step that opens a text at that depth requires everything a release +/// knows ([`CAPABILITIES`](super::CAPABILITIES)), so an older one refuses it instead of dropping what +/// it can't see; nothing real nests that deep. It bounds this walk only: the checks that read a +/// style, layer or map given inline still start again from the top when that text is a project. /// Always `false`, so that whatever walks the commands ([`command_uses`], a script's /// lines, a model's graph) visits every one of them. Text that isn't a project requires nothing. fn collect_opened_project(found: &RefCell>, seen: &Seen, depth: usize, id: &str, params: &Value) -> bool { - // Nothing real holds a project this deep, and a chain of base64 zips (`data`) can be made of - // texts that don't get shorter, so the stack is what bounds it otherwise. - if depth >= MAX_OPENED_DEPTH { - return false; - } - let text = match id { - // It opens its `text` only, whatever else the step holds. - "project.openText" => params.get("text").and_then(Value::as_str).map(Cow::Borrowed), - "project.fromTemplate" => crate::cmd::items::inline_text(params).ok().flatten(), + // What the step opens, as the command reads it: `project.openText` its `text` only, whatever + // else the step holds; `project.fromTemplate` its `data` before its `text`. + let (tag, source) = match id { + "project.openText" => ("text", crate::cmd::ps(params, "text")), + "project.fromTemplate" => match crate::cmd::ps(params, "data") { + Some(data) => ("data", Some(data)), + None => ("text", crate::cmd::ps(params, "text")), + }, "script.run" => { if let Some(script) = params.get("script").and_then(Value::as_str) { script_uses(script, |id, params| collect_opened_project(found, seen, depth, id, params)); } - None + return false; } - _ => None, + _ => return false, }; - let Some(text) = text else { return false }; - // Keyed by the text itself, compared whole: a digest of it could collide. - // Asked before `found` is borrowed: the project's own walk never touches this cell. - let cached = seen.borrow().get(&depth).and_then(|texts| texts.get(&*text)).cloned(); - let names = cached.unwrap_or_else(|| { - #[cfg(test)] - PARSED.with(|n| n.set(n.get() + 1)); - let names = Project::from_peer_raw(&text).ok().map(|p| p.required_capabilities_at(depth + 1, seen)).unwrap_or_default(); - seen.borrow_mut().entry(depth).or_default().insert(text.into_owned(), names.clone()); - names - }); + let Some(source) = source else { return false }; + let mut names: Vec<&'static str> = Vec::new(); + if depth >= MAX_OPENED_DEPTH { + // Not read: whatever is in it can't be told, so an older release must not open it. + names.extend_from_slice(super::CAPABILITIES); + } else { + let digest = rustgis_plugins::package::sha256_hex(format!("{tag}:{source}").as_bytes()); + // Asked before `found` is borrowed: the project's own walk never touches this cell. + let cached = seen.borrow().get(&depth).and_then(|digests| digests.get(&digest)).cloned(); + names = cached.unwrap_or_else(|| { + let text = if tag == "data" { crate::cmd::items::inline_text(params).ok().flatten() } else { Some(Cow::Borrowed(source)) }; + #[cfg(test)] + PARSED.with(|n| n.set(n.get() + 1)); + let names = text + .and_then(|text| Project::from_peer_raw(&text).ok()) + .map(|project| project.required_capabilities_at(depth + 1, seen)) + .unwrap_or_default(); + seen.borrow_mut().entry(depth).or_default().insert(digest, names.clone()); + names + }); + } let mut found = found.borrow_mut(); for name in names { if !found.contains(&name) { @@ -2211,23 +2224,48 @@ mod tests { assert_eq!(PARSED.with(std::cell::Cell::get), 2); } - /// The walk of these two commands reads a project down to [`MAX_OPENED_DEPTH`] levels and - /// nothing at that depth or deeper. Called at a chosen depth: a chain of `text` projects can't - /// be built that deep (each level escapes the one inside it), and one of base64 zips is the - /// case the limit is for. + /// The walk of these two commands reads a project down to [`MAX_OPENED_DEPTH`] levels; at that + /// depth a step that opens a text requires everything a release knows, so an older one refuses + /// it rather than drop what it can't see, and a step that opens nothing requires nothing. + /// Called at a chosen depth: a chain of `text` projects can't be built that deep (each level + /// escapes the one inside it), and one of base64 zips is the case the limit is for. #[test] - fn the_walk_of_opened_projects_stops_at_its_depth() { + fn the_walk_of_opened_projects_requires_everything_at_its_depth() { let (text, _) = Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap().saved_text(None).unwrap(); - let params = json!({"text": text}); - let at = |depth: usize| { + let at = |depth: usize, id: &str, params: &Value| { let found = RefCell::new(Vec::new()); - assert!(!collect_opened_project(&found, &Seen::default(), depth, "project.openText", ¶ms), "it never answers"); + assert!(!collect_opened_project(&found, &Seen::default(), depth, id, params), "it never answers"); found.into_inner() }; - assert_eq!(at(0), ["layout-extent-indicators"]); - assert_eq!(at(MAX_OPENED_DEPTH - 1), ["layout-extent-indicators"]); - assert!(at(MAX_OPENED_DEPTH).is_empty()); + let opens = json!({"text": text}); + assert_eq!(at(0, "project.openText", &opens), ["layout-extent-indicators"]); + assert_eq!(at(MAX_OPENED_DEPTH - 1, "project.openText", &opens), ["layout-extent-indicators"]); + for (id, params) in + [("project.openText", &opens), ("project.fromTemplate", &opens), ("project.openText", &json!({"text": "not a project"}))] + { + let mut all = at(MAX_OPENED_DEPTH, id, params); + all.sort_unstable(); + let mut known = crate::project::CAPABILITIES.to_vec(); + known.sort_unstable(); + assert_eq!(all, known, "{id}"); + } + assert!(at(MAX_OPENED_DEPTH, "project.openText", &json!({})).is_empty(), "no text, nothing opened"); + assert!(at(MAX_OPENED_DEPTH, "layer.remove", &opens).is_empty(), "another command"); + } + + /// What a walk keeps of the texts it has read is a digest of where each came from, never the + /// decoded text: a template that inflates to a gigabyte would be held until the walk ends. + #[test] + fn a_walk_keeps_no_text_it_has_read() { + let (text, _) = + Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap().saved_text(None).unwrap(); + let seen = Seen::default(); + let found = RefCell::new(Vec::new()); + collect_opened_project(&found, &seen, 0, "project.openText", &json!({"text": text})); + let kept: Vec<(usize, usize)> = + seen.borrow().iter().flat_map(|(depth, texts)| texts.keys().map(move |k| (*depth, k.len()))).collect(); + assert_eq!(kept, [(0, 64)], "one entry, a SHA-256 in hex"); } /// The text of an empty project holding `tasks`. From ec71b527519340da633dcc548eb8f82ce8d35c56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 08:14:38 -0500 Subject: [PATCH 06/19] fix(engine): hash the text a step opens in place, and say what the depth limit requires (#3462) --- crates/engine/src/project_capabilities.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 69b1e0f9b4..253d61d347 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -206,7 +206,8 @@ const MAX_OPENED_DEPTH: usize = 32; /// it can't see; nothing real nests that deep. It bounds this walk only: the checks that read a /// style, layer or map given inline still start again from the top when that text is a project. /// Always `false`, so that whatever walks the commands ([`command_uses`], a script's -/// lines, a model's graph) visits every one of them. Text that isn't a project requires nothing. +/// lines, a model's graph) visits every one of them. Text that isn't a project requires nothing, +/// except at that depth, where a step that opens any text requires everything. fn collect_opened_project(found: &RefCell>, seen: &Seen, depth: usize, id: &str, params: &Value) -> bool { // What the step opens, as the command reads it: `project.openText` its `text` only, whatever // else the step holds; `project.fromTemplate` its `data` before its `text`. @@ -230,7 +231,7 @@ fn collect_opened_project(found: &RefCell>, seen: &Seen, depth // Not read: whatever is in it can't be told, so an older release must not open it. names.extend_from_slice(super::CAPABILITIES); } else { - let digest = rustgis_plugins::package::sha256_hex(format!("{tag}:{source}").as_bytes()); + let digest = format!("{tag}:{}", rustgis_plugins::package::sha256_hex(source.as_bytes())); // Asked before `found` is borrowed: the project's own walk never touches this cell. let cached = seen.borrow().get(&depth).and_then(|digests| digests.get(&digest)).cloned(); names = cached.unwrap_or_else(|| { @@ -2263,9 +2264,10 @@ mod tests { let seen = Seen::default(); let found = RefCell::new(Vec::new()); collect_opened_project(&found, &seen, 0, "project.openText", &json!({"text": text})); - let kept: Vec<(usize, usize)> = - seen.borrow().iter().flat_map(|(depth, texts)| texts.keys().map(move |k| (*depth, k.len()))).collect(); - assert_eq!(kept, [(0, 64)], "one entry, a SHA-256 in hex"); + let kept: Vec<(usize, String)> = + seen.borrow().iter().flat_map(|(depth, texts)| texts.keys().map(move |k| (*depth, k.clone()))).collect(); + let digest = rustgis_plugins::package::sha256_hex(text.as_bytes()); + assert_eq!(kept, [(0, format!("text:{digest}"))], "one entry: where the text came from and its SHA-256, not the text"); } /// The text of an empty project holding `tasks`. From 06ac65c54bd4c138bbb43fd5525016a683f82c44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 08:27:58 -0500 Subject: [PATCH 07/19] fix(engine): bound the bytes a walk reads by what a project may hold (#3462) The depth limit bounds the length of a chain of templates, not their size: 32 zips that each inflate to a gigabyte are tens of megabytes in the file. A walk counts the bytes of the texts it reads, and past what a project may hold a step that opens a text requires everything, as at the depth limit. --- crates/engine/src/project_capabilities.rs | 60 ++++++++++++++++++----- 1 file changed, 48 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 253d61d347..4bff4e629f 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -185,8 +185,13 @@ thread_local! { /// (its `text` or its base64 `data`, as the step gives it): one opened by several steps at the same /// depth (a zip of the same template stored once and opened many times) is read once, and what is /// kept is 64 bytes, never the decoded text, which can be a gigabyte. A SHA-256 of the source is -/// looked up before anything is decoded, so a hit decodes nothing either. -type Seen = RefCell>>>; +/// looked up before anything is decoded, so a hit decodes nothing either. It also counts the bytes +/// of the texts read, which can't go past what a project may hold ([`crate::project::max_bytes`]). +#[derive(Default)] +struct Seen { + read: RefCell>>>, + bytes: std::cell::Cell, +} /// How many projects deep a saved step's opened project is read for what it requires. const MAX_OPENED_DEPTH: usize = 32; @@ -203,7 +208,7 @@ const MAX_OPENED_DEPTH: usize = 32; /// project escapes it, so is longer than it and only so much nests; a `data` template (base64, a /// zip) isn't, hence the depth. A step that opens a text at that depth requires everything a release /// knows ([`CAPABILITIES`](super::CAPABILITIES)), so an older one refuses it instead of dropping what -/// it can't see; nothing real nests that deep. It bounds this walk only: the checks that read a +/// it can't see; nothing real nests that deep. The same goes past the bytes a project may hold in all the texts a walk reads. It bounds this walk only: the checks that read a /// style, layer or map given inline still start again from the top when that text is a project. /// Always `false`, so that whatever walks the commands ([`command_uses`], a script's /// lines, a model's graph) visits every one of them. Text that isn't a project requires nothing, @@ -233,16 +238,23 @@ fn collect_opened_project(found: &RefCell>, seen: &Seen, depth } else { let digest = format!("{tag}:{}", rustgis_plugins::package::sha256_hex(source.as_bytes())); // Asked before `found` is borrowed: the project's own walk never touches this cell. - let cached = seen.borrow().get(&depth).and_then(|digests| digests.get(&digest)).cloned(); + let cached = seen.read.borrow().get(&depth).and_then(|digests| digests.get(&digest)).cloned(); names = cached.unwrap_or_else(|| { let text = if tag == "data" { crate::cmd::items::inline_text(params).ok().flatten() } else { Some(Cow::Borrowed(source)) }; - #[cfg(test)] - PARSED.with(|n| n.set(n.get() + 1)); - let names = text - .and_then(|text| Project::from_peer_raw(&text).ok()) - .map(|project| project.required_capabilities_at(depth + 1, seen)) - .unwrap_or_default(); - seen.borrow_mut().entry(depth).or_default().insert(digest, names.clone()); + // What a walk reads is no more than a project may hold: past that, as at the depth limit, + // the text is not read and an older release must not open it. + let bytes = seen.bytes.get().saturating_add(text.as_ref().map_or(0, |t| t.len() as u64)); + seen.bytes.set(bytes); + let names = if bytes > crate::project::max_bytes() { + super::CAPABILITIES.to_vec() + } else { + #[cfg(test)] + PARSED.with(|n| n.set(n.get() + 1)); + text.and_then(|text| Project::from_peer_raw(&text).ok()) + .map(|project| project.required_capabilities_at(depth + 1, seen)) + .unwrap_or_default() + }; + seen.read.borrow_mut().entry(depth).or_default().insert(digest, names.clone()); names }); } @@ -2255,6 +2267,30 @@ mod tests { assert!(at(MAX_OPENED_DEPTH, "layer.remove", &opens).is_empty(), "another command"); } + /// A walk reads as many bytes of opened texts as a project may hold ([`crate::project::max_bytes`]) + /// and no more: past that a step that opens a text requires everything, as at the depth + /// limit, so a chain of templates that each inflate to a gigabyte can't make a save read them all. + #[test] + fn a_walk_reads_only_so_many_bytes() { + let project = |name: &str| { + let mut project = Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap(); + project.name = name.into(); + project.saved_text(None).unwrap().0 + }; + let (first, second) = (project("first"), project("second")); + crate::project::with_max_bytes(first.len() as u64 + 10, || { + let (seen, found) = (Seen::default(), RefCell::new(Vec::new())); + collect_opened_project(&found, &seen, 0, "project.openText", &json!({"text": first})); + assert_eq!(found.take(), ["layout-extent-indicators"], "within the budget"); + collect_opened_project(&found, &seen, 0, "project.openText", &json!({"text": second})); + let mut all = found.take(); + all.sort_unstable(); + let mut known = crate::project::CAPABILITIES.to_vec(); + known.sort_unstable(); + assert_eq!(all, known, "past it"); + }); + } + /// What a walk keeps of the texts it has read is a digest of where each came from, never the /// decoded text: a template that inflates to a gigabyte would be held until the walk ends. #[test] @@ -2265,7 +2301,7 @@ mod tests { let found = RefCell::new(Vec::new()); collect_opened_project(&found, &seen, 0, "project.openText", &json!({"text": text})); let kept: Vec<(usize, String)> = - seen.borrow().iter().flat_map(|(depth, texts)| texts.keys().map(move |k| (*depth, k.clone()))).collect(); + seen.read.borrow().iter().flat_map(|(depth, texts)| texts.keys().map(move |k| (*depth, k.clone()))).collect(); let digest = rustgis_plugins::package::sha256_hex(text.as_bytes()); assert_eq!(kept, [(0, format!("text:{digest}"))], "one entry: where the text came from and its SHA-256, not the text"); } From 0ab1fb5a1d4b09333918da06a7ff9e96003672c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 08:35:45 -0500 Subject: [PATCH 08/19] fix(engine): decode nothing once a walk has spent its bytes (#3462) The budget of bytes was checked after a template was inflated, so each later one was still inflated whole and only its parse was skipped. Once the budget is spent a text is not decoded: the step requires everything. --- crates/engine/src/project_capabilities.rs | 41 +++++++++++++++++++---- 1 file changed, 35 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 4bff4e629f..67bff04cad 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -208,8 +208,10 @@ const MAX_OPENED_DEPTH: usize = 32; /// project escapes it, so is longer than it and only so much nests; a `data` template (base64, a /// zip) isn't, hence the depth. A step that opens a text at that depth requires everything a release /// knows ([`CAPABILITIES`](super::CAPABILITIES)), so an older one refuses it instead of dropping what -/// it can't see; nothing real nests that deep. The same goes past the bytes a project may hold in all the texts a walk reads. It bounds this walk only: the checks that read a -/// style, layer or map given inline still start again from the top when that text is a project. +/// it can't see; nothing real nests that deep. The same goes once the texts a walk has read add up +/// to more than a project may hold, and then a text is not even decoded. It bounds this walk only: +/// the checks that read a style, layer or map given inline still start again from the top when that +/// text is a project. /// Always `false`, so that whatever walks the commands ([`command_uses`], a script's /// lines, a model's graph) visits every one of them. Text that isn't a project requires nothing, /// except at that depth, where a step that opens any text requires everything. @@ -240,12 +242,19 @@ fn collect_opened_project(found: &RefCell>, seen: &Seen, depth // Asked before `found` is borrowed: the project's own walk never touches this cell. let cached = seen.read.borrow().get(&depth).and_then(|digests| digests.get(&digest)).cloned(); names = cached.unwrap_or_else(|| { - let text = if tag == "data" { crate::cmd::items::inline_text(params).ok().flatten() } else { Some(Cow::Borrowed(source)) }; - // What a walk reads is no more than a project may hold: past that, as at the depth limit, - // the text is not read and an older release must not open it. + // What a walk reads is no more than a project may hold: once that is spent, as at the + // depth limit, a text is not decoded or read and an older release must not open it. + let text = if seen.bytes.get() >= crate::project::max_bytes() { + None + } else if tag == "data" { + crate::cmd::items::inline_text(params).ok().flatten() + } else { + Some(Cow::Borrowed(source)) + }; + let spent = seen.bytes.get() >= crate::project::max_bytes(); let bytes = seen.bytes.get().saturating_add(text.as_ref().map_or(0, |t| t.len() as u64)); seen.bytes.set(bytes); - let names = if bytes > crate::project::max_bytes() { + let names = if spent || bytes > crate::project::max_bytes() { super::CAPABILITIES.to_vec() } else { #[cfg(test)] @@ -2291,6 +2300,26 @@ mod tests { }); } + /// Once the budget of bytes is spent, a `data` template isn't inflated at all: it requires + /// everything without being decoded, which an undecodable one shows (it requires nothing when + /// it is decoded and fails). + #[test] + fn a_walk_that_has_spent_its_bytes_decodes_no_more() { + let (first, _) = + Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap().saved_text(None).unwrap(); + crate::project::with_max_bytes(first.len() as u64, || { + let (seen, found) = (Seen::default(), RefCell::new(Vec::new())); + collect_opened_project(&found, &seen, 0, "project.openText", &json!({"text": first})); + assert_eq!(found.take(), ["layout-extent-indicators"], "within the budget"); + collect_opened_project(&found, &seen, 0, "project.fromTemplate", &json!({"data": "not base64!"})); + let mut all = found.take(); + all.sort_unstable(); + let mut known = crate::project::CAPABILITIES.to_vec(); + known.sort_unstable(); + assert_eq!(all, known, "the budget is spent before it is decoded"); + }); + } + /// What a walk keeps of the texts it has read is a digest of where each came from, never the /// decoded text: a template that inflates to a gigabyte would be held until the walk ends. #[test] From 30864f190c627c8a9a531f4adb761d3662409691 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 08:52:38 -0500 Subject: [PATCH 09/19] refactor(engine): make the walk of opened projects easier to read, and test a real deep chain (#3462) collect_opened_project returns nothing, the doc says what it does, the bytes budget is read once and the read counter of the walk is named for what it holds. The test counts the texts read from the cache instead of a thread-local, and a chain of 33 real base64 templates is read on a 1 MiB stack. --- crates/engine/src/project_capabilities.rs | 146 +++++++++--------- .../src/tests/capabilities_inline_project.rs | 20 +++ 2 files changed, 94 insertions(+), 72 deletions(-) diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 67bff04cad..4ffa89e501 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -32,12 +32,12 @@ impl<'de> Deserialize<'de> for Project { impl Project { /// Required features of all saved maps, snapshots and replayable commands/scripts. pub(crate) fn required_capabilities(&self) -> Vec<&'static str> { - self.required_capabilities_at(0, &Seen::default()) + self.required_capabilities_at(0, &OpenedReads::default()) } /// [`Project::required_capabilities`] of a project opened `depth` levels down by saved steps /// ([`collect_opened_project`]). - fn required_capabilities_at(&self, depth: usize, seen: &Seen) -> Vec<&'static str> { + fn required_capabilities_at(&self, depth: usize, seen: &OpenedReads) -> Vec<&'static str> { let mut required = map_capabilities(self.maps.iter().chain(self.offline_areas.iter().map(|a| &a.data))); if !self.origin_id.is_empty() || self.field_origin.is_some() || self.offline_areas.iter().any(|area| !area.id.is_empty()) { required.push("field-origin"); @@ -105,7 +105,10 @@ impl Project { required.extend(commands.into_iter().filter(|name| !required.contains(name)).collect::>()); // And what a project that a saved step opens from its text requires (#3462, #3476). let opened = RefCell::new(Vec::new()); - self.uses_commands(&|id: &str, params: &Value| collect_opened_project(&opened, seen, depth, id, params)); + self.uses_commands(&|id: &str, params: &Value| { + collect_opened_project(&opened, seen, depth, id, params); + false + }); merge_opened(&mut required, opened); if self.tasks.iter().any(|task| task.steps.iter().any(|step| command_uses_table_export_order(&step.command, &step.params))) || self.gp_history.iter().any(|record| { @@ -167,28 +170,28 @@ pub(crate) fn task_capabilities(steps: &[super::TaskStep]) -> Vec<&'static str> if steps.iter().any(|s| command_uses_table_export_order(&s.command, &s.params)) { required.push("table-export-order"); } - let (opened, seen) = (RefCell::new(Vec::new()), Seen::default()); + let (opened, seen) = (RefCell::new(Vec::new()), OpenedReads::default()); for step in steps { - command_uses(&|id: &str, params: &Value| collect_opened_project(&opened, &seen, 0, id, params), &step.command, &step.params); + command_uses( + &|id: &str, params: &Value| { + collect_opened_project(&opened, &seen, 0, id, params); + false + }, + &step.command, + &step.params, + ); } merge_opened(&mut required, opened); required } -// The projects read by `collect_opened_project` on this thread, for the tests. -#[cfg(test)] -thread_local! { - static PARSED: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// What each text a walk has read required, by its depth and then a digest of where it came from -/// (its `text` or its base64 `data`, as the step gives it): one opened by several steps at the same -/// depth (a zip of the same template stored once and opened many times) is read once, and what is -/// kept is 64 bytes, never the decoded text, which can be a gigabyte. A SHA-256 of the source is -/// looked up before anything is decoded, so a hit decodes nothing either. It also counts the bytes -/// of the texts read, which can't go past what a project may hold ([`crate::project::max_bytes`]). +/// What a walk has read of the projects that saved steps open: what each text required, by depth and +/// then a digest of where it came from (its `text` or its base64 `data`, as the step gives it), so one +/// opened by several steps at the same depth is read once, and what is kept is 64 bytes, never the +/// decoded text, which can be a gigabyte. The digest is looked up before anything is decoded. It also +/// counts the bytes read. #[derive(Default)] -struct Seen { +struct OpenedReads { read: RefCell>>>, bytes: std::cell::Cell, } @@ -196,26 +199,24 @@ struct Seen { /// How many projects deep a saved step's opened project is read for what it requires. const MAX_OPENED_DEPTH: usize = 32; -/// What a step that opens a project from its text requires: the project's own capabilities, -/// layout ones included (#3462, #3476). A saved step is checked one capability at a time, and -/// most of those checks read nothing of the text, so an older reader opened a project, dropped -/// what it didn't know and saved the rest without a word. The text is read once, as the project -/// is read without repair ([`Project::from_peer_raw`]), so what loading it would cut still -/// counts. The checks of single capabilities no longer read these two commands' text: each read the -/// project again, so the cost of a project that opens a project that opens one grew at every level. -/// A project opened by a step of a project opened by a step, and so on, is read by this down to -/// [`MAX_OPENED_DEPTH`] levels, each text once at each depth ([`Seen`]). A `text` that holds a -/// project escapes it, so is longer than it and only so much nests; a `data` template (base64, a -/// zip) isn't, hence the depth. A step that opens a text at that depth requires everything a release -/// knows ([`CAPABILITIES`](super::CAPABILITIES)), so an older one refuses it instead of dropping what -/// it can't see; nothing real nests that deep. The same goes once the texts a walk has read add up -/// to more than a project may hold, and then a text is not even decoded. It bounds this walk only: -/// the checks that read a style, layer or map given inline still start again from the top when that -/// text is a project. -/// Always `false`, so that whatever walks the commands ([`command_uses`], a script's -/// lines, a model's graph) visits every one of them. Text that isn't a project requires nothing, -/// except at that depth, where a step that opens any text requires everything. -fn collect_opened_project(found: &RefCell>, seen: &Seen, depth: usize, id: &str, params: &Value) -> bool { +/// Adds to `found` what the project that a step opens from its text requires (#3462): the text of +/// `project.openText`, or the `data` else the `text` of `project.fromTemplate`, as those commands +/// read it, without repair ([`Project::from_peer_raw`]) so that what loading it would cut still +/// counts, and so on down the projects its own steps open, `script.run` lines included. Text that +/// isn't a project requires nothing. +/// +/// Two limits keep the walk small: [`MAX_OPENED_DEPTH`] levels, and the bytes a project may hold +/// ([`crate::project::max_bytes`]) in all the texts read. A `text` that holds a project escapes it, +/// so only so much nests; a `data` template (base64, a zip) doesn't get longer. Past either limit a +/// step that opens a text requires every capability a release knows, so an older one refuses it +/// instead of dropping what it can't see, and the text isn't decoded. This bounds this walk only: the +/// checks that read a style, layer or map given inline still start again from the top when that text +/// is a project. +/// +/// Returns nothing: it is called from a walk over saved commands ([`command_uses`], a script's lines, +/// a model's graph) as `|id, params| { collect_opened_project(..); false }`, so that the walk visits +/// every command. +fn collect_opened_project(found: &RefCell>, reads: &OpenedReads, depth: usize, id: &str, params: &Value) { // What the step opens, as the command reads it: `project.openText` its `text` only, whatever // else the step holds; `project.fromTemplate` its `data` before its `text`. let (tag, source) = match id { @@ -226,54 +227,51 @@ fn collect_opened_project(found: &RefCell>, seen: &Seen, depth }, "script.run" => { if let Some(script) = params.get("script").and_then(Value::as_str) { - script_uses(script, |id, params| collect_opened_project(found, seen, depth, id, params)); + script_uses(script, |id, params| { + collect_opened_project(found, reads, depth, id, params); + false + }); } - return false; + return; } - _ => return false, + _ => return, }; - let Some(source) = source else { return false }; - let mut names: Vec<&'static str> = Vec::new(); - if depth >= MAX_OPENED_DEPTH { - // Not read: whatever is in it can't be told, so an older release must not open it. - names.extend_from_slice(super::CAPABILITIES); + let Some(source) = source else { return }; + let names: Vec<&'static str> = if depth >= MAX_OPENED_DEPTH { + super::CAPABILITIES.to_vec() } else { let digest = format!("{tag}:{}", rustgis_plugins::package::sha256_hex(source.as_bytes())); // Asked before `found` is borrowed: the project's own walk never touches this cell. - let cached = seen.read.borrow().get(&depth).and_then(|digests| digests.get(&digest)).cloned(); - names = cached.unwrap_or_else(|| { - // What a walk reads is no more than a project may hold: once that is spent, as at the - // depth limit, a text is not decoded or read and an older release must not open it. - let text = if seen.bytes.get() >= crate::project::max_bytes() { + let cached = reads.read.borrow().get(&depth).and_then(|digests| digests.get(&digest)).cloned(); + cached.unwrap_or_else(|| { + let budget = crate::project::max_bytes(); + let spent = reads.bytes.get() >= budget; + let text = if spent { None } else if tag == "data" { crate::cmd::items::inline_text(params).ok().flatten() } else { Some(Cow::Borrowed(source)) }; - let spent = seen.bytes.get() >= crate::project::max_bytes(); - let bytes = seen.bytes.get().saturating_add(text.as_ref().map_or(0, |t| t.len() as u64)); - seen.bytes.set(bytes); - let names = if spent || bytes > crate::project::max_bytes() { + let bytes = reads.bytes.get().saturating_add(text.as_ref().map_or(0, |t| t.len() as u64)); + reads.bytes.set(bytes); + let names = if spent || bytes > budget { super::CAPABILITIES.to_vec() } else { - #[cfg(test)] - PARSED.with(|n| n.set(n.get() + 1)); text.and_then(|text| Project::from_peer_raw(&text).ok()) - .map(|project| project.required_capabilities_at(depth + 1, seen)) + .map(|project| project.required_capabilities_at(depth + 1, reads)) .unwrap_or_default() }; - seen.read.borrow_mut().entry(depth).or_default().insert(digest, names.clone()); + reads.read.borrow_mut().entry(depth).or_default().insert(digest, names.clone()); names - }); - } + }) + }; let mut found = found.borrow_mut(); for name in names { if !found.contains(&name) { found.push(name); } } - false } /// `opened`, a walk's findings ([`collect_opened_project`]), added to `required` after what it has. @@ -1554,8 +1552,11 @@ fn imported_layout_text<'a>(id: &str, params: &'a Value) -> Option> pub(crate) fn model_capabilities(steps: &[ModelStep], graph: Option<&ModelGraph>) -> Vec<&'static str> { let mut required: Vec<&'static str> = COMMAND_CAPABILITIES.iter().filter_map(|&(name, uses)| model_uses(steps, graph, &uses).then_some(name)).collect(); - let (opened, seen) = (RefCell::new(Vec::new()), Seen::default()); - model_uses(steps, graph, &|id: &str, params: &Value| collect_opened_project(&opened, &seen, 0, id, params)); + let (opened, seen) = (RefCell::new(Vec::new()), OpenedReads::default()); + model_uses(steps, graph, &|id: &str, params: &Value| { + collect_opened_project(&opened, &seen, 0, id, params); + false + }); merge_opened(&mut required, opened); required } @@ -2240,10 +2241,11 @@ mod tests { let open = |text: &Value| json!({"title": "Open", "command": "project.openText", "params": {"text": text.to_string()}}); outer["tasks"] = json!([{"name": "Again", "steps": [open(&inner), open(&inner), open(&inner)]}]); let outer = Project::from_peer_raw(&outer.to_string()).unwrap(); - PARSED.with(|n| n.set(0)); - assert_eq!(outer.required_capabilities(), ["layout-extent-indicators"]); - // The inner project once, and the template once inside it. - assert_eq!(PARSED.with(std::cell::Cell::get), 2); + let reads = OpenedReads::default(); + assert_eq!(outer.required_capabilities_at(0, &reads), ["layout-extent-indicators"]); + // One entry for each text read: the inner project once, and the template once inside it. + let read: usize = reads.read.borrow().values().map(|texts| texts.len()).sum(); + assert_eq!(read, 2); } /// The walk of these two commands reads a project down to [`MAX_OPENED_DEPTH`] levels; at that @@ -2257,7 +2259,7 @@ mod tests { Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap().saved_text(None).unwrap(); let at = |depth: usize, id: &str, params: &Value| { let found = RefCell::new(Vec::new()); - assert!(!collect_opened_project(&found, &Seen::default(), depth, id, params), "it never answers"); + collect_opened_project(&found, &OpenedReads::default(), depth, id, params); found.into_inner() }; let opens = json!({"text": text}); @@ -2288,7 +2290,7 @@ mod tests { }; let (first, second) = (project("first"), project("second")); crate::project::with_max_bytes(first.len() as u64 + 10, || { - let (seen, found) = (Seen::default(), RefCell::new(Vec::new())); + let (seen, found) = (OpenedReads::default(), RefCell::new(Vec::new())); collect_opened_project(&found, &seen, 0, "project.openText", &json!({"text": first})); assert_eq!(found.take(), ["layout-extent-indicators"], "within the budget"); collect_opened_project(&found, &seen, 0, "project.openText", &json!({"text": second})); @@ -2308,7 +2310,7 @@ mod tests { let (first, _) = Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap().saved_text(None).unwrap(); crate::project::with_max_bytes(first.len() as u64, || { - let (seen, found) = (Seen::default(), RefCell::new(Vec::new())); + let (seen, found) = (OpenedReads::default(), RefCell::new(Vec::new())); collect_opened_project(&found, &seen, 0, "project.openText", &json!({"text": first})); assert_eq!(found.take(), ["layout-extent-indicators"], "within the budget"); collect_opened_project(&found, &seen, 0, "project.fromTemplate", &json!({"data": "not base64!"})); @@ -2326,7 +2328,7 @@ mod tests { fn a_walk_keeps_no_text_it_has_read() { let (text, _) = Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap().saved_text(None).unwrap(); - let seen = Seen::default(); + let seen = OpenedReads::default(); let found = RefCell::new(Vec::new()); collect_opened_project(&found, &seen, 0, "project.openText", &json!({"text": text})); let kept: Vec<(usize, String)> = diff --git a/crates/engine/src/tests/capabilities_inline_project.rs b/crates/engine/src/tests/capabilities_inline_project.rs index b781408f1e..d91a546df2 100644 --- a/crates/engine/src/tests/capabilities_inline_project.rs +++ b/crates/engine/src/tests/capabilities_inline_project.rs @@ -93,3 +93,23 @@ fn what_needs_nothing_requires_nothing() { } } } + +/// A chain of projects each opening the next from base64 `data`, as deep as the walk goes and one +/// more, is read on a thread with the stack of Windows' main one (1 MiB): a stack overflow aborts +/// the process, and nothing catches it. +#[test] +fn the_deepest_chain_of_opened_projects_fits_a_small_stack() { + use base64::Engine; + let (_, innermost, _) = fixtures().into_iter().find(|(n, _, _)| n == "layout_extent_indicators.rgis").unwrap(); + let mut text = innermost; + for _ in 0..33 { + let data = base64::engine::general_purpose::STANDARD.encode(&text); + let step = json!({"title": "Open", "command": "project.fromTemplate", "params": {"data": data}}); + let mut project = serde_json::to_value(Project::default()).unwrap(); + project["tasks"] = json!([{"name": "Open", "steps": [step]}]); + text = project.to_string(); + } + let outer = Project::from_peer_raw(&text).unwrap(); + let found = std::thread::Builder::new().stack_size(1 << 20).spawn(move || outer.required_capabilities()).unwrap().join().unwrap(); + assert!(found.len() > 50, "past the depth limit a step requires everything: {}", found.len()); +} From c79f1da6d594d9ea0bd865ec408d8333f449db8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 09:05:57 -0500 Subject: [PATCH 10/19] fix(engine): make what a walk requires the same on every computer (#3462) The bytes a walk may read followed the memory of the computer, so a project past the budget saved a different requires header on a small computer than on a large one. The budget is the least a project may hold anywhere. --- crates/engine/src/project_capabilities.rs | 69 ++++++++++++++++++----- 1 file changed, 55 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 4ffa89e501..b91ab92725 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -6,6 +6,7 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; use std::borrow::Cow; use std::cell::RefCell; +use std::collections::HashMap; use super::{FORMAT, ModelGraph, ModelNodeKind, ModelStep, Project}; use crate::cmd::exports::Output; @@ -189,11 +190,26 @@ pub(crate) fn task_capabilities(steps: &[super::TaskStep]) -> Vec<&'static str> /// then a digest of where it came from (its `text` or its base64 `data`, as the step gives it), so one /// opened by several steps at the same depth is read once, and what is kept is 64 bytes, never the /// decoded text, which can be a gigabyte. The digest is looked up before anything is decoded. It also -/// counts the bytes read. -#[derive(Default)] +/// counts the bytes read, up to a budget. struct OpenedReads { - read: RefCell>>>, + read: RefCell>>>, bytes: std::cell::Cell, + /// The most bytes of texts a walk reads. The same on every computer, since what a project + /// requires is saved in it: [`BYTES_FLOOR`](crate::project::BYTES_FLOOR), the least a project + /// may hold anywhere. + budget: u64, +} + +impl Default for OpenedReads { + fn default() -> Self { + OpenedReads::with_budget(crate::project::BYTES_FLOOR) + } +} + +impl OpenedReads { + fn with_budget(budget: u64) -> Self { + OpenedReads { read: RefCell::default(), bytes: std::cell::Cell::new(0), budget } + } } /// How many projects deep a saved step's opened project is read for what it requires. @@ -205,8 +221,8 @@ const MAX_OPENED_DEPTH: usize = 32; /// counts, and so on down the projects its own steps open, `script.run` lines included. Text that /// isn't a project requires nothing. /// -/// Two limits keep the walk small: [`MAX_OPENED_DEPTH`] levels, and the bytes a project may hold -/// ([`crate::project::max_bytes`]) in all the texts read. A `text` that holds a project escapes it, +/// Two limits keep the walk small: [`MAX_OPENED_DEPTH`] levels, and a budget of bytes +/// ([`OpenedReads::budget`]) in all the texts read. A `text` that holds a project escapes it, /// so only so much nests; a `data` template (base64, a zip) doesn't get longer. Past either limit a /// step that opens a text requires every capability a release knows, so an older one refuses it /// instead of dropping what it can't see, and the text isn't decoded. This bounds this walk only: the @@ -244,7 +260,7 @@ fn collect_opened_project(found: &RefCell>, reads: &OpenedRead // Asked before `found` is borrowed: the project's own walk never touches this cell. let cached = reads.read.borrow().get(&depth).and_then(|digests| digests.get(&digest)).cloned(); cached.unwrap_or_else(|| { - let budget = crate::project::max_bytes(); + let budget = reads.budget; let spent = reads.bytes.get() >= budget; let text = if spent { None @@ -2278,8 +2294,33 @@ mod tests { assert!(at(MAX_OPENED_DEPTH, "layer.remove", &opens).is_empty(), "another command"); } - /// A walk reads as many bytes of opened texts as a project may hold ([`crate::project::max_bytes`]) - /// and no more: past that a step that opens a text requires everything, as at the depth + /// What a saved project requires is a function of the project alone: the same on a computer + /// with a small memory as on one with a large one, so the bytes a walk may read can't follow + /// [`crate::project::max_bytes`]. + #[test] + fn what_a_walk_requires_does_not_follow_the_memory_of_the_computer() { + let project = |name: &str| { + let mut project = Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap(); + project.name = name.into(); + project.saved_text(None).unwrap().0 + }; + let (first, second) = (project("first"), project("second")); + let step = |text: &String| crate::project::TaskStep { + title: "Open".into(), + instructions: String::new(), + command: "project.openText".into(), + params: json!({"text": text}), + }; + let tasks = + vec![crate::project::Task { name: "Open".into(), description: String::new(), steps: vec![step(&first), step(&second)] }]; + let outer = Project { tasks, ..Project::default() }; + // A computer whose projects may hold hardly more than the first text: both are read all the same. + let small = crate::project::with_max_bytes(first.len() as u64 + 10, || outer.required_capabilities()); + assert_eq!(small, outer.required_capabilities()); + assert_eq!(small, ["layout-extent-indicators"]); + } + + /// A walk reads as many bytes of opened texts as its budget and no more: past that a step that opens a text requires everything, as at the depth /// limit, so a chain of templates that each inflate to a gigabyte can't make a save read them all. #[test] fn a_walk_reads_only_so_many_bytes() { @@ -2289,8 +2330,8 @@ mod tests { project.saved_text(None).unwrap().0 }; let (first, second) = (project("first"), project("second")); - crate::project::with_max_bytes(first.len() as u64 + 10, || { - let (seen, found) = (OpenedReads::default(), RefCell::new(Vec::new())); + { + let (seen, found) = (OpenedReads::with_budget(first.len() as u64 + 10), RefCell::new(Vec::new())); collect_opened_project(&found, &seen, 0, "project.openText", &json!({"text": first})); assert_eq!(found.take(), ["layout-extent-indicators"], "within the budget"); collect_opened_project(&found, &seen, 0, "project.openText", &json!({"text": second})); @@ -2299,7 +2340,7 @@ mod tests { let mut known = crate::project::CAPABILITIES.to_vec(); known.sort_unstable(); assert_eq!(all, known, "past it"); - }); + } } /// Once the budget of bytes is spent, a `data` template isn't inflated at all: it requires @@ -2309,8 +2350,8 @@ mod tests { fn a_walk_that_has_spent_its_bytes_decodes_no_more() { let (first, _) = Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap().saved_text(None).unwrap(); - crate::project::with_max_bytes(first.len() as u64, || { - let (seen, found) = (OpenedReads::default(), RefCell::new(Vec::new())); + { + let (seen, found) = (OpenedReads::with_budget(first.len() as u64), RefCell::new(Vec::new())); collect_opened_project(&found, &seen, 0, "project.openText", &json!({"text": first})); assert_eq!(found.take(), ["layout-extent-indicators"], "within the budget"); collect_opened_project(&found, &seen, 0, "project.fromTemplate", &json!({"data": "not base64!"})); @@ -2319,7 +2360,7 @@ mod tests { let mut known = crate::project::CAPABILITIES.to_vec(); known.sort_unstable(); assert_eq!(all, known, "the budget is spent before it is decoded"); - }); + } } /// What a walk keeps of the texts it has read is a digest of where each came from, never the From 6cba04469af59c31a512baf8a987b99c66080dd0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 09:20:55 -0500 Subject: [PATCH 11/19] fix(engine): decode a template within the walk's budget, not this computer's limit (#3462) inline_text refuses base64 past the limit of this computer for a file, so a template over it required nothing there and everything on a computer with more memory. The walk decodes within its own budget and a template that can't be decoded requires everything. --- crates/engine/src/cmd/items.rs | 10 ++++-- crates/engine/src/project_capabilities.rs | 39 +++++++++++++++++++++-- 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index e9ef743a27..dc7a58d7a6 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -2151,9 +2151,15 @@ pub(crate) fn durable_bytes_with( /// Decodes the same data-before-text choice without opening a path. `text` is lent, not copied: /// every save asks each capability check about it. pub(crate) fn inline_text(p: &Value) -> Result>, String> { + inline_text_within(p, max_file()) +} + +/// [`inline_text`] with the largest file it takes given: the limit of this computer for a file, or +/// another that doesn't follow the computer's memory. +pub(crate) fn inline_text_within(p: &Value, limit: u64) -> Result>, String> { if let Some(d) = ps(p, "data") { use base64::Engine; - if d.len() as u64 > max_file() / 3 * 4 { + if d.len() as u64 > limit / 3 * 4 { return Err(too_large()); } let bytes = base64::engine::general_purpose::STANDARD.decode(d.trim()).map_err(|_| "data must be base64".to_string())?; @@ -2163,7 +2169,7 @@ pub(crate) fn inline_text(p: &Value) -> Result>, String> { return String::from_utf8(bytes).map(|t| Some(t.into())).map_err(|_| "not a RustGIS file".to_string()); } match ps(p, "text") { - Some(t) if t.len() as u64 <= max_file() => Ok(Some(t.into())), + Some(t) if t.len() as u64 <= limit => Ok(Some(t.into())), Some(_) => Err(too_large()), None => Ok(None), } diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index b91ab92725..164465d128 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -225,7 +225,7 @@ const MAX_OPENED_DEPTH: usize = 32; /// ([`OpenedReads::budget`]) in all the texts read. A `text` that holds a project escapes it, /// so only so much nests; a `data` template (base64, a zip) doesn't get longer. Past either limit a /// step that opens a text requires every capability a release knows, so an older one refuses it -/// instead of dropping what it can't see, and the text isn't decoded. This bounds this walk only: the +/// instead of dropping what it can't see, and the text isn't decoded; so does a `data` template that can't be decoded, as what a computer's limits say of it can't change what a project requires. This bounds this walk only: the /// checks that read a style, layer or map given inline still start again from the top when that text /// is a project. /// @@ -262,16 +262,20 @@ fn collect_opened_project(found: &RefCell>, reads: &OpenedRead cached.unwrap_or_else(|| { let budget = reads.budget; let spent = reads.bytes.get() >= budget; + // A template that can't be decoded (too large for the budget, not base64, a zip this + // build refuses) is not told apart by what the computer would say: it requires + // everything, as past the budget. What a project requires can't depend on the computer. let text = if spent { None } else if tag == "data" { - crate::cmd::items::inline_text(params).ok().flatten() + crate::cmd::items::inline_text_within(params, budget).ok().flatten() } else { Some(Cow::Borrowed(source)) }; + let undecoded = !spent && tag == "data" && text.is_none(); let bytes = reads.bytes.get().saturating_add(text.as_ref().map_or(0, |t| t.len() as u64)); reads.bytes.set(bytes); - let names = if spent || bytes > budget { + let names = if spent || undecoded || bytes > budget { super::CAPABILITIES.to_vec() } else { text.and_then(|text| Project::from_peer_raw(&text).ok()) @@ -2320,6 +2324,35 @@ mod tests { assert_eq!(small, ["layout-extent-indicators"]); } + /// A template that this computer's limit for a file ([`crate::project::max_bytes`]) refuses is + /// still read: what a project requires can't depend on the computer that saves it, so the limit + /// of a walk is its own budget. + #[test] + fn a_template_over_the_limit_of_this_computer_is_read_all_the_same() { + use base64::Engine; + // A text whose length isn't a multiple of 3, so that its base64 is longer than three + // quarters of a limit the size of the text. + let (text, _) = (0..4) + .map(|pad| { + let mut project = Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap(); + project.name = "p".repeat(pad + 1); + project.saved_text(None).unwrap() + }) + .find(|(text, _)| text.len() % 3 != 0) + .unwrap(); + let data = base64::engine::general_purpose::STANDARD.encode(&text); + let at = |max: Option| { + let read = || { + let found = RefCell::new(Vec::new()); + collect_opened_project(&found, &OpenedReads::default(), 0, "project.fromTemplate", &json!({"data": data})); + found.into_inner() + }; + max.map_or_else(read, |max| crate::project::with_max_bytes(max, read)) + }; + assert_eq!(at(None), ["layout-extent-indicators"]); + assert_eq!(at(Some(text.len() as u64)), ["layout-extent-indicators"]); + } + /// A walk reads as many bytes of opened texts as its budget and no more: past that a step that opens a text requires everything, as at the depth /// limit, so a chain of templates that each inflate to a gigabyte can't make a save read them all. #[test] From b216a9e265e7d2165566311447b27b98efacc0fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 09:31:06 -0500 Subject: [PATCH 12/19] test(engine): drop a redundant import in the stack test (#3462) --- crates/engine/src/tests/capabilities_inline_project.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/engine/src/tests/capabilities_inline_project.rs b/crates/engine/src/tests/capabilities_inline_project.rs index d91a546df2..ec20a7cf7f 100644 --- a/crates/engine/src/tests/capabilities_inline_project.rs +++ b/crates/engine/src/tests/capabilities_inline_project.rs @@ -99,7 +99,6 @@ fn what_needs_nothing_requires_nothing() { /// the process, and nothing catches it. #[test] fn the_deepest_chain_of_opened_projects_fits_a_small_stack() { - use base64::Engine; let (_, innermost, _) = fixtures().into_iter().find(|(n, _, _)| n == "layout_extent_indicators.rgis").unwrap(); let mut text = innermost; for _ in 0..33 { From 779b4735f946e37c9713df107b2fa4dad75446d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 09:42:56 -0500 Subject: [PATCH 13/19] fix(engine): bound the time a walk spends reading opened texts (#3462) A walk could read 512 MiB of opened texts, about two seconds on the calling thread at every save. The budget is a fixed 64 MiB now, a quarter of a second at the limit and the same on every computer. --- crates/engine/src/project_capabilities.rs | 107 +++++++++--------- .../src/tests/capabilities_inline_project.rs | 2 +- 2 files changed, 57 insertions(+), 52 deletions(-) diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 164465d128..a90711f19d 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -5,7 +5,7 @@ use rustgis_map::{Layer, Map, raster::RasterRenderer}; use serde::{Deserialize, Serialize}; use serde_json::Value; use std::borrow::Cow; -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::collections::HashMap; use super::{FORMAT, ModelGraph, ModelNodeKind, ModelStep, Project}; @@ -38,7 +38,7 @@ impl Project { /// [`Project::required_capabilities`] of a project opened `depth` levels down by saved steps /// ([`collect_opened_project`]). - fn required_capabilities_at(&self, depth: usize, seen: &OpenedReads) -> Vec<&'static str> { + fn required_capabilities_at(&self, depth: usize, reads: &OpenedReads) -> Vec<&'static str> { let mut required = map_capabilities(self.maps.iter().chain(self.offline_areas.iter().map(|a| &a.data))); if !self.origin_id.is_empty() || self.field_origin.is_some() || self.offline_areas.iter().any(|area| !area.id.is_empty()) { required.push("field-origin"); @@ -107,7 +107,7 @@ impl Project { // And what a project that a saved step opens from its text requires (#3462, #3476). let opened = RefCell::new(Vec::new()); self.uses_commands(&|id: &str, params: &Value| { - collect_opened_project(&opened, seen, depth, id, params); + collect_opened_project(&opened, reads, depth, id, params); false }); merge_opened(&mut required, opened); @@ -186,32 +186,36 @@ pub(crate) fn task_capabilities(steps: &[super::TaskStep]) -> Vec<&'static str> required } -/// What a walk has read of the projects that saved steps open: what each text required, by depth and -/// then a digest of where it came from (its `text` or its base64 `data`, as the step gives it), so one -/// opened by several steps at the same depth is read once, and what is kept is 64 bytes, never the -/// decoded text, which can be a gigabyte. The digest is looked up before anything is decoded. It also -/// counts the bytes read, up to a budget. +/// What a walk has read of the projects that saved steps open: what each text required, by depth +/// and then a digest of where it came from (its `text` or its base64 `data`, as the step gives it), +/// so one opened by several steps at the same depth is read once, and what is kept is 64 bytes, +/// never the decoded text, which can be a gigabyte. The digest is looked up before anything is +/// decoded. It also counts the bytes read, up to a budget. struct OpenedReads { read: RefCell>>>, - bytes: std::cell::Cell, - /// The most bytes of texts a walk reads. The same on every computer, since what a project - /// requires is saved in it: [`BYTES_FLOOR`](crate::project::BYTES_FLOOR), the least a project - /// may hold anywhere. + bytes: Cell, + /// The most bytes of texts a walk reads: [`OPENED_BYTES`], or less in a test. budget: u64, } impl Default for OpenedReads { fn default() -> Self { - OpenedReads::with_budget(crate::project::BYTES_FLOOR) + OpenedReads::with_budget(OPENED_BYTES) } } impl OpenedReads { fn with_budget(budget: u64) -> Self { - OpenedReads { read: RefCell::default(), bytes: std::cell::Cell::new(0), budget } + OpenedReads { read: RefCell::default(), bytes: Cell::new(0), budget } } } +/// The most bytes of texts a walk reads before a step that opens one requires everything. The same +/// on every computer, since what a project requires is saved in it, and small enough to bound the +/// time a save spends on it (about 4 ms per MB with real structure, so a quarter of a second at the +/// limit), which no legitimate template comes near. +const OPENED_BYTES: u64 = 64 << 20; + /// How many projects deep a saved step's opened project is read for what it requires. const MAX_OPENED_DEPTH: usize = 32; @@ -222,16 +226,17 @@ const MAX_OPENED_DEPTH: usize = 32; /// isn't a project requires nothing. /// /// Two limits keep the walk small: [`MAX_OPENED_DEPTH`] levels, and a budget of bytes -/// ([`OpenedReads::budget`]) in all the texts read. A `text` that holds a project escapes it, -/// so only so much nests; a `data` template (base64, a zip) doesn't get longer. Past either limit a +/// ([`OpenedReads::budget`]) in all the texts read. A `text` that holds a project escapes it, so +/// only so much nests; a `data` template (base64, a zip) doesn't get longer. Past either limit a /// step that opens a text requires every capability a release knows, so an older one refuses it -/// instead of dropping what it can't see, and the text isn't decoded; so does a `data` template that can't be decoded, as what a computer's limits say of it can't change what a project requires. This bounds this walk only: the -/// checks that read a style, layer or map given inline still start again from the top when that text -/// is a project. +/// instead of dropping what it can't see, and the text isn't decoded; so does a `data` template +/// that can't be decoded, as what a computer's limits say of it can't change what a project +/// requires. This bounds this walk only: the checks that read a style, layer or map given inline +/// still start again from the top when that text is a project. /// -/// Returns nothing: it is called from a walk over saved commands ([`command_uses`], a script's lines, -/// a model's graph) as `|id, params| { collect_opened_project(..); false }`, so that the walk visits -/// every command. +/// Returns nothing: it is called from a walk over saved commands ([`command_uses`], a script's +/// lines, a model's graph) as `|id, params| { collect_opened_project(..); false }`, so that the +/// walk visits every command. fn collect_opened_project(found: &RefCell>, reads: &OpenedReads, depth: usize, id: &str, params: &Value) { // What the step opens, as the command reads it: `project.openText` its `text` only, whatever // else the step holds; `project.fromTemplate` its `data` before its `text`. @@ -2353,8 +2358,9 @@ mod tests { assert_eq!(at(Some(text.len() as u64)), ["layout-extent-indicators"]); } - /// A walk reads as many bytes of opened texts as its budget and no more: past that a step that opens a text requires everything, as at the depth - /// limit, so a chain of templates that each inflate to a gigabyte can't make a save read them all. + /// A walk reads as many bytes of opened texts as its budget and no more: past that a step that + /// opens a text requires everything, as at the depth limit, so a chain of templates that each + /// inflate to a gigabyte can't make a save read them all. #[test] fn a_walk_reads_only_so_many_bytes() { let project = |name: &str| { @@ -2363,37 +2369,36 @@ mod tests { project.saved_text(None).unwrap().0 }; let (first, second) = (project("first"), project("second")); - { - let (seen, found) = (OpenedReads::with_budget(first.len() as u64 + 10), RefCell::new(Vec::new())); - collect_opened_project(&found, &seen, 0, "project.openText", &json!({"text": first})); - assert_eq!(found.take(), ["layout-extent-indicators"], "within the budget"); - collect_opened_project(&found, &seen, 0, "project.openText", &json!({"text": second})); - let mut all = found.take(); - all.sort_unstable(); - let mut known = crate::project::CAPABILITIES.to_vec(); - known.sort_unstable(); - assert_eq!(all, known, "past it"); - } - } - - /// Once the budget of bytes is spent, a `data` template isn't inflated at all: it requires - /// everything without being decoded, which an undecodable one shows (it requires nothing when - /// it is decoded and fails). + let (seen, found) = (OpenedReads::with_budget(first.len() as u64 + 10), RefCell::new(Vec::new())); + collect_opened_project(&found, &seen, 0, "project.openText", &json!({"text": first})); + assert_eq!(found.take(), ["layout-extent-indicators"], "within the budget"); + collect_opened_project(&found, &seen, 0, "project.openText", &json!({"text": second})); + let mut all = found.take(); + all.sort_unstable(); + let mut known = crate::project::CAPABILITIES.to_vec(); + known.sort_unstable(); + assert_eq!(all, known, "past it"); + } + + /// Once the budget of bytes is spent, a `data` template isn't decoded at all: the count of bytes + /// read stays where it was, and the step requires everything. #[test] fn a_walk_that_has_spent_its_bytes_decodes_no_more() { + use base64::Engine; let (first, _) = Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap().saved_text(None).unwrap(); - { - let (seen, found) = (OpenedReads::with_budget(first.len() as u64), RefCell::new(Vec::new())); - collect_opened_project(&found, &seen, 0, "project.openText", &json!({"text": first})); - assert_eq!(found.take(), ["layout-extent-indicators"], "within the budget"); - collect_opened_project(&found, &seen, 0, "project.fromTemplate", &json!({"data": "not base64!"})); - let mut all = found.take(); - all.sort_unstable(); - let mut known = crate::project::CAPABILITIES.to_vec(); - known.sort_unstable(); - assert_eq!(all, known, "the budget is spent before it is decoded"); - } + let (seen, found) = (OpenedReads::with_budget(first.len() as u64), RefCell::new(Vec::new())); + collect_opened_project(&found, &seen, 0, "project.openText", &json!({"text": first})); + assert_eq!(found.take(), ["layout-extent-indicators"], "within the budget"); + let spent = seen.bytes.get(); + let data = base64::engine::general_purpose::STANDARD.encode(&first); + collect_opened_project(&found, &seen, 0, "project.fromTemplate", &json!({"data": data})); + let mut all = found.take(); + all.sort_unstable(); + let mut known = crate::project::CAPABILITIES.to_vec(); + known.sort_unstable(); + assert_eq!(all, known, "the step requires everything"); + assert_eq!(seen.bytes.get(), spent, "and nothing was decoded"); } /// What a walk keeps of the texts it has read is a digest of where each came from, never the diff --git a/crates/engine/src/tests/capabilities_inline_project.rs b/crates/engine/src/tests/capabilities_inline_project.rs index ec20a7cf7f..f82b77d79e 100644 --- a/crates/engine/src/tests/capabilities_inline_project.rs +++ b/crates/engine/src/tests/capabilities_inline_project.rs @@ -83,7 +83,7 @@ fn an_opened_project_with_several_extent_indicators_requires_them() { /// A project with nothing new in it, and text that is no project, ask for nothing. #[test] -fn what_needs_nothing_requires_nothing() { +fn a_project_with_nothing_new_requires_nothing() { let plain = Project::default().saved_text(None).unwrap().0; for text in [plain.as_str(), "not a project", "{\"maps\": 1}", ""] { for id in ["project.openText", "project.fromTemplate"] { From 8742b0a98167b33260e32b62bee5d76371b57429 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 09:55:45 -0500 Subject: [PATCH 14/19] fix(engine): inflate a zipped template only within the walk's budget (#3462) inline_text_within bounded the base64 only, so a package was inflated up to 1 GiB before the walk's budget applied. The package is read within the limit it is given, and a template past it requires everything. --- crates/engine/src/cmd/items.rs | 16 ++++++++++++---- crates/engine/src/project_capabilities.rs | 18 +++++++++++++++++- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index dc7a58d7a6..abf1f587c6 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -486,7 +486,13 @@ pub(crate) fn read_text(p: &Value) -> Result { /// The project JSON inside a package. pub fn package_text(bytes: &[u8]) -> Result { - let entries = rustgis_data::zip::read_matching(bytes, |n| crate::project::is_project_file(n) || n.ends_with(".rgismap"))?; + package_text_within(bytes, rustgis_data::zip::MAX_TOTAL) +} + +/// [`package_text`] inflating at most `budget` bytes (and never more than [`rustgis_data::zip::MAX_TOTAL`]). +pub fn package_text_within(bytes: &[u8], budget: usize) -> Result { + let entries = + rustgis_data::zip::read_matching_within(bytes, |n| crate::project::is_project_file(n) || n.ends_with(".rgismap"), budget)?; let (_, data) = entries .into_iter() .find(|(n, _)| crate::project::is_project_file(n) || n.ends_with(".rgismap")) @@ -2154,8 +2160,9 @@ pub(crate) fn inline_text(p: &Value) -> Result>, String> { inline_text_within(p, max_file()) } -/// [`inline_text`] with the largest file it takes given: the limit of this computer for a file, or -/// another that doesn't follow the computer's memory. +/// [`inline_text`] with the most it takes given: the limit of this computer for a file, or another +/// that doesn't follow the computer's memory. It bounds the base64 and, for a package, what is +/// inflated from it. pub(crate) fn inline_text_within(p: &Value, limit: u64) -> Result>, String> { if let Some(d) = ps(p, "data") { use base64::Engine; @@ -2164,7 +2171,8 @@ pub(crate) fn inline_text_within(p: &Value, limit: u64) -> Result Date: Wed, 2 Dec 2026 10:10:57 -0500 Subject: [PATCH 15/19] fix(engine): keep the zip limit of inline_text, and make the stack test reach the depth limit (#3462) The zip budget of the walk also cut what the other readers of inline_text take, so a package that inflated past the limit of the computer for a file but under the zip limit was refused inline and read by path. inline_text takes the inflation limit apart from the text's. The stack test moves next to the walk, with a budget no chain reaches, and asserts that a text was read at each depth. A very large limit no longer overflows. --- crates/engine/src/cmd/items.rs | 15 +++--- crates/engine/src/project_capabilities.rs | 49 ++++++++++++++++++- .../src/tests/capabilities_inline_project.rs | 19 ------- 3 files changed, 54 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index abf1f587c6..76527ec229 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -2157,22 +2157,21 @@ pub(crate) fn durable_bytes_with( /// Decodes the same data-before-text choice without opening a path. `text` is lent, not copied: /// every save asks each capability check about it. pub(crate) fn inline_text(p: &Value) -> Result>, String> { - inline_text_within(p, max_file()) + inline_text_within(p, max_file(), rustgis_data::zip::MAX_TOTAL) } -/// [`inline_text`] with the most it takes given: the limit of this computer for a file, or another -/// that doesn't follow the computer's memory. It bounds the base64 and, for a package, what is -/// inflated from it. -pub(crate) fn inline_text_within(p: &Value, limit: u64) -> Result>, String> { +/// [`inline_text`] with the most it takes given: `limit` for the text or the base64, the limit of this +/// computer for a file or another that doesn't follow the computer's memory, and `inflated` for what +/// is inflated from a package (at most [`rustgis_data::zip::MAX_TOTAL`]). +pub(crate) fn inline_text_within(p: &Value, limit: u64, inflated: usize) -> Result>, String> { if let Some(d) = ps(p, "data") { use base64::Engine; - if d.len() as u64 > limit / 3 * 4 { + if d.len() as u64 > (limit / 3).saturating_mul(4) { return Err(too_large()); } let bytes = base64::engine::general_purpose::STANDARD.decode(d.trim()).map_err(|_| "data must be base64".to_string())?; if bytes.starts_with(b"PK") { - let inflated = usize::try_from(limit).unwrap_or(usize::MAX).min(rustgis_data::zip::MAX_TOTAL); - return package_text_within(&bytes, inflated).map(|t| Some(t.into())); + return package_text_within(&bytes, inflated.min(rustgis_data::zip::MAX_TOTAL)).map(|t| Some(t.into())); } return String::from_utf8(bytes).map(|t| Some(t.into())).map_err(|_| "not a RustGIS file".to_string()); } diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index c8bd01b912..bc24becb1d 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -274,7 +274,7 @@ fn collect_opened_project(found: &RefCell>, reads: &OpenedRead let text = if spent { None } else if tag == "data" { - crate::cmd::items::inline_text_within(params, budget).ok().flatten() + crate::cmd::items::inline_text_within(params, budget, usize::try_from(budget).unwrap_or(usize::MAX)).ok().flatten() } else { Some(Cow::Borrowed(source)) }; @@ -2359,6 +2359,49 @@ mod tests { assert_eq!(at(Some(text.len() as u64)), ["layout-extent-indicators"]); } + /// A chain of projects each opening the next from base64 `data`, one more than the walk reads, + /// is read down to the depth limit on a thread with the stack of Windows' main one (1 MiB): a + /// stack overflow aborts the process, and nothing catches it. The walk has a budget no chain + /// reaches, so that it is the depth that stops it (a chain this long is more bytes than the + /// fixed budget). + #[test] + fn the_deepest_chain_of_opened_projects_fits_a_small_stack() { + use base64::Engine; + let (mut text, _) = + Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap().saved_text(None).unwrap(); + for _ in 0..=MAX_OPENED_DEPTH { + let data = base64::engine::general_purpose::STANDARD.encode(&text); + let step = json!({"title": "Open", "command": "project.fromTemplate", "params": {"data": data}}); + text = with_tasks(json!([{"name": "Open", "steps": [step]}])); + } + let outer = Project::from_peer_raw(&text).unwrap(); + let (required, depths) = std::thread::Builder::new() + .stack_size(1 << 20) + .spawn(move || { + let reads = OpenedReads::with_budget(u64::MAX); + let required = outer.required_capabilities_at(0, &reads).len(); + (required, reads.read.borrow().len()) + }) + .unwrap() + .join() + .unwrap(); + assert_eq!(depths, MAX_OPENED_DEPTH, "a text read at each depth, down to the limit"); + assert!(required > 50, "past the depth limit a step requires everything: {required}"); + } + + /// What the walk asks of a zip doesn't change what the other readers of `inline_text` take: a + /// package inflates up to `zip::MAX_TOTAL` whatever the limit of this computer for a file. + #[test] + fn inline_text_still_inflates_a_package_up_to_the_zip_limit() { + use base64::Engine; + let project = Project { name: "x".repeat(200_000), ..Project::default() }; + let (text, _) = project.clone().saved_text(None).unwrap(); + let zip = rustgis_data::zip::write(&[("p.rgis".to_string(), text.clone().into_bytes())]).unwrap(); + let params = json!({"data": base64::engine::general_purpose::STANDARD.encode(zip)}); + let read = crate::project::with_max_bytes(100_000, || crate::cmd::items::inline_text(¶ms).map(|t| t.map(|t| t.len()))); + assert_eq!(read, Ok(Some(text.len()))); + } + /// A zip is inflated only within the budget, not up to the 1 GiB a package may hold: a template /// that inflates past it is refused as it is read, which the walk takes as one it can't decode. #[test] @@ -2369,7 +2412,9 @@ mod tests { let zip = rustgis_data::zip::write(&[("p.rgis".to_string(), text.clone().into_bytes())]).unwrap(); let params = json!({"data": base64::engine::general_purpose::STANDARD.encode(zip)}); assert!(params["data"].as_str().unwrap().len() < 10_000, "it is small zipped"); - let within = |limit: u64| crate::cmd::items::inline_text_within(¶ms, limit).map(|t| t.map(|t| t.len())); + let within = |limit: u64| { + crate::cmd::items::inline_text_within(¶ms, limit, usize::try_from(limit).unwrap_or(usize::MAX)).map(|t| t.map(|t| t.len())) + }; assert_eq!(within(1 << 30), Ok(Some(text.len()))); assert!(within(100_000).is_err(), "it inflates past the budget"); } diff --git a/crates/engine/src/tests/capabilities_inline_project.rs b/crates/engine/src/tests/capabilities_inline_project.rs index f82b77d79e..d2ceb35409 100644 --- a/crates/engine/src/tests/capabilities_inline_project.rs +++ b/crates/engine/src/tests/capabilities_inline_project.rs @@ -93,22 +93,3 @@ fn a_project_with_nothing_new_requires_nothing() { } } } - -/// A chain of projects each opening the next from base64 `data`, as deep as the walk goes and one -/// more, is read on a thread with the stack of Windows' main one (1 MiB): a stack overflow aborts -/// the process, and nothing catches it. -#[test] -fn the_deepest_chain_of_opened_projects_fits_a_small_stack() { - let (_, innermost, _) = fixtures().into_iter().find(|(n, _, _)| n == "layout_extent_indicators.rgis").unwrap(); - let mut text = innermost; - for _ in 0..33 { - let data = base64::engine::general_purpose::STANDARD.encode(&text); - let step = json!({"title": "Open", "command": "project.fromTemplate", "params": {"data": data}}); - let mut project = serde_json::to_value(Project::default()).unwrap(); - project["tasks"] = json!([{"name": "Open", "steps": [step]}]); - text = project.to_string(); - } - let outer = Project::from_peer_raw(&text).unwrap(); - let found = std::thread::Builder::new().stack_size(1 << 20).spawn(move || outer.required_capabilities()).unwrap().join().unwrap(); - assert!(found.len() > 50, "past the depth limit a step requires everything: {}", found.len()); -} From 17983bc531ec307cc352db63a38768697fb27226 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 10:21:29 -0500 Subject: [PATCH 16/19] test(engine): the stack test compares every capability the depth limit requires (#3462) --- crates/engine/src/project_capabilities.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index bc24becb1d..d98eb67a3e 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -2379,14 +2379,18 @@ mod tests { .stack_size(1 << 20) .spawn(move || { let reads = OpenedReads::with_budget(u64::MAX); - let required = outer.required_capabilities_at(0, &reads).len(); + let required = outer.required_capabilities_at(0, &reads); (required, reads.read.borrow().len()) }) .unwrap() .join() .unwrap(); assert_eq!(depths, MAX_OPENED_DEPTH, "a text read at each depth, down to the limit"); - assert!(required > 50, "past the depth limit a step requires everything: {required}"); + let mut required = required; + required.sort_unstable(); + let mut known = crate::project::CAPABILITIES.to_vec(); + known.sort_unstable(); + assert_eq!(required, known, "past the depth limit a step requires everything"); } /// What the walk asks of a zip doesn't change what the other readers of `inline_text` take: a @@ -2563,8 +2567,8 @@ mod tests { s.project } - /// What a step that opens an inline project requires is asked without reading anything that project names, - /// as saved, without its header, from a script and from a step of a step (#3530). + /// What a step that opens an inline project requires is asked without reading anything that + /// project names, as saved, without its header, from a script and from a step of a step (#3530). #[test] fn asking_what_an_inline_project_needs_reads_nothing_it_names() { let checks = [ From 170e565f051317c06a10e723d403417f031f1365 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 10:30:31 -0500 Subject: [PATCH 17/19] docs(engine): say which limit each argument of inline_text_within is (#3462) --- crates/engine/src/cmd/items.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index 76527ec229..3ce202f8e1 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -2160,9 +2160,10 @@ pub(crate) fn inline_text(p: &Value) -> Result>, String> { inline_text_within(p, max_file(), rustgis_data::zip::MAX_TOTAL) } -/// [`inline_text`] with the most it takes given: `limit` for the text or the base64, the limit of this -/// computer for a file or another that doesn't follow the computer's memory, and `inflated` for what -/// is inflated from a package (at most [`rustgis_data::zip::MAX_TOTAL`]). +/// [`inline_text`] with the sizes given: `limit` for the text, or for the base64 of `data`, and +/// `inflated` for what a package inflates to (at most [`rustgis_data::zip::MAX_TOTAL`]). +/// [`inline_text`] passes this computer's file limit and the zip limit; the project walk passes its +/// own budget for both. pub(crate) fn inline_text_within(p: &Value, limit: u64, inflated: usize) -> Result>, String> { if let Some(d) = ps(p, "data") { use base64::Engine; From 6c90ffac6186f87c9b6e2a2ce6857891487590e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 10:42:29 -0500 Subject: [PATCH 18/19] docs(engine): say the walk of opened projects has no Cancel check (#3462) --- crates/engine/src/project_capabilities.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index d98eb67a3e..243136327c 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -171,11 +171,11 @@ pub(crate) fn task_capabilities(steps: &[super::TaskStep]) -> Vec<&'static str> if steps.iter().any(|s| command_uses_table_export_order(&s.command, &s.params)) { required.push("table-export-order"); } - let (opened, seen) = (RefCell::new(Vec::new()), OpenedReads::default()); + let (opened, reads) = (RefCell::new(Vec::new()), OpenedReads::default()); for step in steps { command_uses( &|id: &str, params: &Value| { - collect_opened_project(&opened, &seen, 0, id, params); + collect_opened_project(&opened, &reads, 0, id, params); false }, &step.command, @@ -237,7 +237,8 @@ const MAX_OPENED_DEPTH: usize = 32; /// /// Returns nothing: it is called from a walk over saved commands ([`command_uses`], a script's /// lines, a model's graph) as `|id, params| { collect_opened_project(..); false }`, so that the -/// walk visits every command. +/// walk visits every command. It has no Cancel check: a walk parses at most [`OPENED_BYTES`] of +/// opened texts (about a quarter of a second at the limit), on each save that calls it. fn collect_opened_project(found: &RefCell>, reads: &OpenedReads, depth: usize, id: &str, params: &Value) { // What the step opens, as the command reads it: `project.openText` its `text` only, whatever // else the step holds; `project.fromTemplate` its `data` before its `text`. @@ -1578,9 +1579,9 @@ fn imported_layout_text<'a>(id: &str, params: &'a Value) -> Option> pub(crate) fn model_capabilities(steps: &[ModelStep], graph: Option<&ModelGraph>) -> Vec<&'static str> { let mut required: Vec<&'static str> = COMMAND_CAPABILITIES.iter().filter_map(|&(name, uses)| model_uses(steps, graph, &uses).then_some(name)).collect(); - let (opened, seen) = (RefCell::new(Vec::new()), OpenedReads::default()); + let (opened, reads) = (RefCell::new(Vec::new()), OpenedReads::default()); model_uses(steps, graph, &|id: &str, params: &Value| { - collect_opened_project(&opened, &seen, 0, id, params); + collect_opened_project(&opened, &reads, 0, id, params); false }); merge_opened(&mut required, opened); From 7b2f5efdb7612ecd5a6eebf0b946bc738ffbfb5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 10:51:02 -0500 Subject: [PATCH 19/19] fix(engine): answer a text longer than the walk's budget before hashing it (#3462) The SHA-256 of a step's source ran before the budget was looked at, so a text past the whole budget was hashed in full on every save. Its answer is known: it requires everything. --- crates/engine/src/project_capabilities.rs | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 243136327c..9bf09c981e 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -260,7 +260,10 @@ fn collect_opened_project(found: &RefCell>, reads: &OpenedRead _ => return, }; let Some(source) = source else { return }; - let names: Vec<&'static str> = if depth >= MAX_OPENED_DEPTH { + // A source longer than the whole budget (as base64, a third more for a `data`) is known to + // require everything, and isn't hashed. + let longest = if tag == "data" { (reads.budget / 3).saturating_mul(4) } else { reads.budget }; + let names: Vec<&'static str> = if depth >= MAX_OPENED_DEPTH || source.len() as u64 > longest { super::CAPABILITIES.to_vec() } else { let digest = format!("{tag}:{}", rustgis_plugins::package::sha256_hex(source.as_bytes())); @@ -2446,6 +2449,23 @@ mod tests { assert_eq!(all, known, "past it"); } + /// A text longer than the whole budget requires everything without being hashed, or read, or + /// kept: its answer is known, and a hash of a gigabyte would cost more than the walk is meant to. + #[test] + fn a_text_longer_than_the_budget_is_not_even_hashed() { + let (text, _) = + Project::from_json(include_str!("../../../schema/fixtures/layout_extent_indicators.rgis")).unwrap().saved_text(None).unwrap(); + let (reads, found) = (OpenedReads::with_budget(text.len() as u64 - 1), RefCell::new(Vec::new())); + collect_opened_project(&found, &reads, 0, "project.openText", &json!({"text": text})); + let mut all = found.take(); + all.sort_unstable(); + let mut known = crate::project::CAPABILITIES.to_vec(); + known.sort_unstable(); + assert_eq!(all, known, "it requires everything"); + assert!(reads.read.borrow().is_empty(), "and nothing was hashed or kept"); + assert_eq!(reads.bytes.get(), 0, "nor counted"); + } + /// Once the budget of bytes is spent, a `data` template isn't decoded at all: the count of bytes /// read stays where it was, and the step requires everything. #[test]