Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
3089345
fix(raster): a large local tiled GeoTIFF is read in place, drawn at t…
Mavrick-F Nov 23, 2026
117eda9
fix(raster): say a plugin reads a tiled file's overview, reread on Re…
Mavrick-F Nov 23, 2026
5719e77
perf(raster): a batch reads a tiled file once for its items
Mavrick-F Nov 23, 2026
dc10b31
fix(raster): a batch keeps only the last tiled file it read
Mavrick-F Nov 23, 2026
d0fee2f
fix(raster): one notice for a plugin run's input notes; native-only t…
Mavrick-F Nov 23, 2026
cf9aaf4
fix(raster): suite tools refuse a moved tiled file; tool reads of til…
Mavrick-F Nov 23, 2026
8fa9312
fix(raster): a batch lets its kept file go before reading another; a …
Mavrick-F Nov 23, 2026
cb2550b
fix(raster): a tiled read stays counted as held while a batch keeps it
Mavrick-F Nov 23, 2026
61948da
fix(raster): Reload and Repair stop waiting for a tiled read asked to…
Mavrick-F Nov 23, 2026
d3042fc
fix(raster): grids of tiled files, suite tools by path, no whole read…
Mavrick-F Nov 23, 2026
2455625
fix(raster): a tiled file written while its overview is read is refus…
Mavrick-F Nov 23, 2026
8437e3b
fix(raster): a local tiled file written again while open is read again
Mavrick-F Nov 23, 2026
c4278f3
fix(raster): a local tiled file's revision travels with its header; s…
Mavrick-F Nov 23, 2026
d110c71
fix(raster): an in-place overview counts the values f32 rounded; a re…
Mavrick-F Nov 23, 2026
6927237
fix(raster): a tile read in flight across a rewrite isn't joined; rou…
Mavrick-F Nov 23, 2026
76a7672
docs(raster): the tiled probe's waits don't look at Cancel, and why
Mavrick-F Nov 23, 2026
2c1d10f
fix(raster): the tiled probe keeps an unchanged file's tiles
Mavrick-F Nov 23, 2026
628fb51
fix(raster): a tile's header is checked under the tiles' lock; the no…
Mavrick-F Nov 24, 2026
ad7a034
fix(raster): a sparse tile is kept only under its file's current header
Mavrick-F Nov 24, 2026
3b4f70c
fix(raster): the rounding notice of a raster read in place says it co…
Mavrick-F Nov 24, 2026
36a1f06
fix(raster): one note for a plugin run's held overviews; a file's nam…
Mavrick-F Nov 24, 2026
037f7d7
fix(raster): a GeoTIFF read in place says an assumed datum and keeps …
Mavrick-F Nov 24, 2026
019fd96
fix(raster): an in-place header asks for its Copyright bytes; a tool …
Mavrick-F Nov 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
184 changes: 172 additions & 12 deletions crates/engine/src/cmd/gp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ pub fn external_start(s: &mut Session, tool: &str, params: &Value) -> Result<Ext
return Err(format!("no GeoLibre tool '{tool}'"));
}
let params = params.clone();
let job = preparing(&continuation, || pin.prepare_suite(&map_inputs(s, Some(spec), &params)?, &params))?;
let job = preparing(&continuation, || pin.prepare_suite(&map_inputs(s, Some(spec), &params, Tiled::ByPath)?, &params))?;
s.next_pending = s.next_pending.wrapping_add(1);
let id = s.next_pending;
let run = ExternalRun {
Expand Down Expand Up @@ -534,14 +534,19 @@ pub fn plugin_start(s: &mut Session, tool: &str, params: &Value) -> Result<Plugi
let spec = pin.spec();
let plugin = pin.plugin().ok_or_else(|| format!("no plugin tool '{tool}'"))?;
let (_, tid) = rustgis_plugins::split_id(spec.id).ok_or("invalid plugin tool id")?;
let (job, full_ids) = preparing(&continuation, || {
let inputs = map_inputs(s, Some(spec), resolved)?;
let (job, full_ids, said) = preparing(&continuation, || {
let inputs = map_inputs(s, Some(spec), resolved, Tiled::Overview)?;
let job = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
rustgis_plugins::tools::prepare_pinned(plugin.plugin(), tid, &inputs, resolved)
}))
.unwrap_or_else(|_| Err(format!("{} failed unexpectedly", spec.name)))?;
Ok((job, full_ids(&inputs.loaded)))
Ok((job, full_ids(&inputs.loaded), inputs.messages.clone()))
})?;
// What reading its inputs approximated (a raster's overview read for a file read in place),
// said now: the run's result is the plugin's own.
for m in said {
s.notify(format!("{}: {m}", spec.name), false);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

With two or more tiled raster inputs, this loop gives one notice per input read (read at the … overview …), each repeating the same kind of approximation. AGENTS.md's "Never silent" rule asks for one notice per kind with a count, through Session::notify or ToolResult::messages. Joining the messages into a single notice keeps every name and number, and says it once for the run:

Suggested change
for m in said {
s.notify(format!("{}: {m}", spec.name), false);
}
if !said.is_empty() {
s.notify(format!("{}: {}", spec.name, said.join("; ")), false);
}

Confidence: medium. The rule is stated for kinds of loss, and these notes are about one kind (overview reads), so a reviewer could reasonably read it as allowing per-input notes. Either way the joined form is the one the rule describes.

Category: agents-md

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in d0fee2f with the suggested join: a plugin run's input notes are one notice. The same commit puts the test-only batch counters under cfg(all(test, not(target_arch = "wasm32"))), matching BATCH_READS (CodeRabbit's minor note).

let read = read_layers(s, spec, resolved);
s.next_pending = s.next_pending.wrapping_add(1);
let id = s.next_pending;
Expand Down Expand Up @@ -710,7 +715,7 @@ impl ToolRun {
// A bug in reading the inputs, like one in a tool, must not take the app down.
let mut done = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
crate::render::rustgis_tiles::cache::with_still(still, || {
let inputs = match inputs_of(snap, Some(spec), &params) {
let inputs = match inputs_of(snap, Some(spec), &params, Tiled::File) {
Ok(inputs) => inputs,
// A Cancel while the inputs are read names the tool, as one while it runs does.
Err(_) if control.is_cancelled() => {
Expand Down Expand Up @@ -1309,6 +1314,9 @@ struct MapInputs<'a> {
/// Import warnings from local file inputs, kept in the tool result and history.
messages: Vec<String>,
losses: Vec<LossMessage>,
/// Raster layers read in place from a file on this computer, read again from it for the run
/// ([`tiled_inputs`]), by lowercase name.
rasters: std::collections::HashMap<String, std::sync::Arc<rustgis_data::raster::Raster>>,
/// The flat map's projection (its name, the projection and its unit in metres), built the
/// first time a tool asks for it (Tissot's indicatrix does), once for the run; `None` on the
/// globe.
Expand Down Expand Up @@ -1363,14 +1371,40 @@ impl MapInputs<'_> {
}
}

fn map_inputs<'a>(s: &'a Session, spec: Option<&rustgis_analysis::ToolSpec>, params: &Value) -> Result<MapInputs<'a>, String> {
inputs_of(Snapshot::of(s), spec, params)
/// How a tool's inputs read a raster layer read in place from a file on this computer
/// ([`rustgis_map::raster::RasterLayer::tiled`]).
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Tiled {
/// From the file, at the finest level the run can hold ([`tiled_inputs`]): a built-in tool's
/// run, on its own thread or where the caller waits.
File,
/// The overview the layer holds, said: a plugin's run, whose inputs are read on the app's
/// thread.
Overview,
/// By its path: a suite tool stages the file itself.
ByPath,
}

/// [`inputs_of`] from the session as it is; `tiled` as there.
fn map_inputs<'a>(
s: &'a Session,
spec: Option<&rustgis_analysis::ToolSpec>,
params: &Value,
tiled: Tiled,
) -> Result<MapInputs<'a>, String> {
inputs_of(Snapshot::of(s), spec, params, tiled)
}

/// A tool's inputs from what it read of the session: the streamed layers and files it names read
/// whole, and the rows of each layer it runs on. It reads, so a background run does this on its
/// thread.
fn inputs_of<'a>(snap: Snapshot<'a>, spec: Option<&rustgis_analysis::ToolSpec>, params: &Value) -> Result<MapInputs<'a>, String> {
/// thread. `tiled` says how the raster layers it reads that are read in place from a file on this
/// computer are read ([`Tiled`]).
fn inputs_of<'a>(
snap: Snapshot<'a>,
spec: Option<&rustgis_analysis::ToolSpec>,
params: &Value,
tiled: Tiled,
) -> Result<MapInputs<'a>, String> {
let (full, said) = streamed_inputs(&snap.map, spec, params)?;
let (mut messages, mut losses) = (Vec::new(), Vec::new());
for m in said {
Expand Down Expand Up @@ -1401,6 +1435,13 @@ fn inputs_of<'a>(snap: Snapshot<'a>, spec: Option<&rustgis_analysis::ToolSpec>,
let mut rows = env_inputs(&snap.map, &full, &snap.env, params)?;
narrow_to_queries(&snap.map, spec, params, &full, &mut rows, &mut messages)?;
let unread = if work == Crs::LonLat { std::collections::HashSet::new() } else { attributes_only(spec, params) };
#[cfg(not(target_arch = "wasm32"))]
let rasters = tiled_inputs(&snap.map, spec, params, tiled, &mut messages)?;
#[cfg(target_arch = "wasm32")]
let rasters = {
let _ = tiled;
std::collections::HashMap::new()
};
Ok(MapInputs {
snap,
rows,
Expand All @@ -1409,11 +1450,122 @@ fn inputs_of<'a>(snap: Snapshot<'a>, spec: Option<&rustgis_analysis::ToolSpec>,
unread,
messages,
losses,
rasters,
flat: std::cell::OnceCell::new(),
view: std::cell::OnceCell::new(),
})
}

/// The raster layers `spec`'s parameters name that are read in place from a file on this
/// computer ([`rustgis_map::raster::RasterLayer::tiled`]), each read again from the file for the
/// run, by lowercase name: such a layer holds only the small overview the map draws from zoomed
/// out, and a tool reads the finest level of the file it can hold, the full image when it fits
/// (#2761). Read on the run's thread, stopping on its Cancel; one read from an overview is said.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This doc comment says the read stops on Cancel, but it doesn't. tiled_inputs calls read_path_with, which takes no control or Cancel check. A single decode of up to max_samples runs to completion before the run looks at Cancel, which is only checked after inputs_of returns. AGENTS.md requires a long step without a check to say so in its doc comment ("a long step without a check (one union, one read) is said in its doc comment"), and this comment says the opposite. Either state the limit (Cancel is seen only after the read) or add a check around the read.

Category: agents-md

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The read does look at Cancel. The GeoTIFF reader calls progress::check between chunks (geotiff.rs 1249–1294), and ToolRun::run installs the run's control as the progress probe (gp.rs 712) before inputs_of. So a run from tool_start, which is every built-in tool run in the app, stops partway through the read. A run made where the caller waits checks it only when that caller installed a probe. dc10b31 makes the doc comment say exactly that.

/// Read only for [`Tiled::File`]: for [`Tiled::Overview`] each such layer's held overview is said,
/// and for [`Tiled::ByPath`] nothing is read or said.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn tiled_inputs(
map: &rustgis_map::Map,
spec: Option<&rustgis_analysis::ToolSpec>,
params: &Value,
tiled: Tiled,
messages: &mut Vec<String>,
) -> Result<std::collections::HashMap<String, std::sync::Arc<rustgis_data::raster::Raster>>, String> {
use rustgis_analysis::ParamKind;
let mut read = std::collections::HashMap::new();
// Raster to PMTiles draws its input as the map does, in place at each zoom's level, and
// reads no pixels through the run's inputs.
let Some(spec) = spec.filter(|t| tiled != Tiled::ByPath && t.id != "rasterToPmtiles") else { return Ok(read) };
let mut seen = std::collections::HashSet::new();
for parameter in spec.params {
let value = params.get(parameter.name).unwrap_or(&Value::Null);
let names: Vec<&str> = match parameter.kind {
ParamKind::RasterLayer => value.as_str().into_iter().collect(),
ParamKind::RasterLayers => rustgis_analysis::layer_list(value).unwrap_or_default(),
_ => continue,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The ByPath refusal only covers raster-kinded parameters, so a GeoLibre file/other-kinded parameter can still stage the held overview silently.

tiled_inputs reads only ParamKind::RasterLayer and RasterLayers (_ => continue). GeoLibre maps Data::File and Data::Other to ParamKind::Path or Text (crates/geolibre/src/lib.rs around 289-297). For those parameters the missing-file check never runs. stage (geolibre/lib.rs:515-528) then finds the layer with r.path not on disk and no embedded bytes, and writes r.raster, the held 326 × 307 overview, as the input, with no notice.

Failure: a tiled layer whose file was moved, named in a GeoLibre tool parameter declared as a file. The tool runs on the overview and reports success.

Fix: in tiled_inputs, apply the ByPath existence check to every parameter whose value names a layer that is tiled, not only raster-kinded ones, or have stage refuse a layer that is tiled with no file on disk.

Category: bug

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 019fd96. In ByPath mode, tiled_inputs now looks at every parameter's value, a name, a ; list or an array of names, whatever the parameter's kind. A suite tool naming a tiled layer whose file is gone is refused through any of them. Values that don't name a tiled layer are passed over as before.

};
for name in names {
let Some(l) = map.layer_by_name(name) else { continue };
let key = l.name.to_ascii_lowercase();
let Some(path) = l.raster.as_ref().filter(|rl| rl.tiled).and_then(|rl| rl.path.as_deref()) else { continue };
if !seen.insert(key.clone()) {
continue;
}
if tiled == Tiled::Overview {
if let Some(held) = l.raster.as_ref().and_then(|rl| rl.data.as_ref())
&& let Some((fw, fh)) = held.overview
{
messages.push(format!(
"{}: read at the {} × {} overview of the {fw} × {fh} raster the layer holds, as plugin tools don't read a raster read in place from its file",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This pushes one message per tiled layer a plugin names. plugin_start joins them into one notice, but the synchronous path (execute, used by the CLI and scripts) returns them as separate messages in the result. A plugin with two tiled inputs therefore gets two notes of the same kind, which the "one notice per kind with a count" rule asks to avoid. Joining the names here, once per run, would make both paths match.

Confidence: medium. The join in plugin_start (d0fee2f) covers only the app path, so this is the same concern as the earlier thread on this line, with the code now changed and the problem still present on the execute path.

Category: agents-md

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 36a1f06. tiled_inputs now joins the held-overview notes into one note for the run, naming each layer, so the synchronous execute path gets one note too. The same commit takes the summary's file_name point: the name is split on / and \, so a local Windows path gives its file name.

l.name, held.width, held.height
));
}
continue;
}
let r = match BATCH_READS.with(|b| b.borrow().as_ref().and_then(|reads| reads.get(path).cloned())) {
Some(r) => r,
None => {
let r = std::sync::Arc::new(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The batch's kept raster is uncounted while the next file decodes, so two decodes can be planned as if there were one. BATCH_READS keeps the last file's decoded raster after its item ends, but the memory::Holding for it went with that item's MapInputs, so held() no longer counts it. The next file is decoded here (line 1530) before reads.clear() (line 1537) lets the old one go, so both are in memory, and read_path_with sizes its read from held(), which doesn't include the old raster. A batch over two tiled layers (for example Zonal Statistics over one then two) can peak near two max_samples reads, which AGENTS.md treats as a crash.

This re-raises the batch-cache thread with new evidence. Keeping one file fixed the number of reads, but not the memory plan the earlier review asked for, since the retained raster still isn't counted.

Suggested fix: let the old file go before the decode, and keep a Holding beside the cached raster for as long as it is kept, so concurrent runs count it too (the second part is not in the suggestion).

Suggested change
let r = std::sync::Arc::new(
BATCH_READS.with(|b| {
if let Some(reads) = b.borrow_mut().as_mut() {
reads.clear();
}
});
let r = std::sync::Arc::new(

Confidence: high on the ordering (read at 1530–1533, clear at 1537). Medium on how far the peak exceeds the plan, since I have not measured it. The existing test uses one file, so it wouldn't catch this.

Category: bug

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 8fa9312: a batch lets go of the file it kept before it reads a different one. The next decode is planned without it, and nothing is held uncounted meanwhile.

rustgis_data::raster::read_path_with(std::path::Path::new(path), None, None)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Concurrent tool runs on one tiled layer can each decode up to max_samples with no shared bound. Each run calls read_path_with here, sized by max_samples → memory::planned. Raster decodes do not register a memory::Holding (none in crates/data/src/raster), so held() does not count other runs' reads still in flight. Two or three background tool runs started together (the desktop starts each tool on its own thread) each plan against the same held() and each decode a near-full-size image. Before this PR a run read the layer's held overview, so this memory is new for the common case.

Failure: a 10.6 GB mosaic, three zonal-stats runs started at once, each decoding a multi-GB finest level, can exhaust memory. AGENTS.md counts that as a crash.

Suggested direction: share one in-flight budget across tiled-file reads (for example a Holding taken before the decode and held until the run drops it), or serialise tiled-file reads across runs. I have not measured this; the claim rests on reading the code.

Confidence: medium-low.

Category: bug

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in cf9aaf4. Reads of tiled files for tool runs now take turns across runs (a process-wide lock around the decode), and each read is counted as a memory::Holding held by the run's inputs until the run drops them. A run starting while another holds its read plans max_samples with that counted, so it reads a coarser level or refuses, instead of both decoding for the same memory.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

A built-in tool run on a tiled layer reads the file as it is now, not the file the layer's overview came from, and nothing says so.

The layer's map keeps drawing the overview read when the layer was added or reloaded. This read (read_path_with on path) takes whatever is on disk at run time. Scenario: add a large tiled GeoTIFF, overwrite the file on disk with a different image or extent, then run Zonal Statistics on the layer without Reload Data. The map shows the old image, the tool computes from the new one, and no notice is given.

The overview already records the revision it was read at (set_source_revision in read_overview), and Raster::check_original_file compares that with the live file. Checking it before this read, and refusing with "Use Reload Data" (as the image-grid path does), would make the run either match the map or say why it doesn't.

Confidence: medium. I traced the code path but did not run the scenario.

Category: bug

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is intended, so I've left it unchanged.

  • The map reads the file as it is now too: once a file is written again, the next header lookup sees the new revision, forgets the old header and tiles, and draws the part in view from the current file. A tool reading the current file therefore reads what the map draws.
  • What is left from before: only the layer's small held overview, until the next reload. Statistics and histograms read that, as before this PR.
  • On main: a rewritten file goes on drawing its old pixels until Reload Data, and a tool run reads those old pixels.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

A tool run on a tiled file drops the whole-file reader's rounding count, so its values are rounded with nothing said.

tiled_inputs reads the file with read_path_with, then looks only at r.overview and keeps the raster. It never reads r.rounded. The whole-file reader counts the values f32 rounds (for example Int32 values past 16,777,216), and the add-time notice counts only the 512 × 512 overview here. The layer notice says rounding shows "in the map and an export", not in tool results.

Failure: add a tiled Int32 GeoTIFF with values above 2^24 (large enough to be read in place), run Zonal Statistics on it. The tool computes from rounded values and the result carries no notice.

Fix: when a tool reads the file, push a message for r.rounded (a count per band, as the add-time notice does) into messages, the same way the overview note is pushed.

Category: bug

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 019fd96: when a built-in run reads a tiled file, the values f32 rounded in what it read go into one note for the run, naming each layer and its count, alongside the overview note.

.map_err(|e| format!("{}: {e}", l.name))?,
);
BATCH_READS.with(|b| {
if let Some(reads) = b.borrow_mut().as_mut() {
reads.insert(path.to_string(), r.clone());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Batch reads are never evicted, so a batch over several tiled rasters can exhaust memory. BATCH_READS keeps every distinct file read in place for the whole batch. batch_param defaults to a raster parameter, so a batch whose items are different tiled GeoTIFF layers (for example zonalStats over N layers) decodes each file to up to max_samples and keeps all N decoded rasters alive until the batch ends. Before this PR each item only held the small overview, so memory now grows with the number of distinct files. That contradicts the PR's claim that a tool run holds its read "only for the run", and running out of memory partway counts as a crash under AGENTS.md. Nothing in tiled_files::a_batch_over_a_tiled_file_reads_the_file_for_each_item covers this, since it uses one file.

Keeping only the last file still gives one read per item when a batch repeats a file:

Suggested change
reads.insert(path.to_string(), r.clone());
reads.clear();
reads.insert(path.to_string(), r.clone());

If interleaved files should also share a read, the cache needs a bound planned with memory::planned instead.

Category: bug

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in dc10b31 with the suggested eviction: the batch keeps only the last file it read, so a batch over several files holds one decoded raster at a time.

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
});
r
}
};
if let Some((fw, fh)) = r.overview {
messages.push(format!(
"{}: read at its {} × {} overview of the {fw} × {fh} raster, the finest it can hold",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Built-in tool runs add one overview note per tiled input, while plugin runs now join theirs into one notice. With two or more tiled raster inputs, this pushes one message for each layer (the same kind of overview read each time). The plugin path was changed to one joined notice (d0fee2f) for the same reason. Joining these messages here as well would keep the names and counts while saying it once per run. This is a nit; I'm leaving it for the release quality pass if the maintainers prefer, but it is the same pattern as the earlier plugin thread.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Done in 61948da: a built-in run now gives one note naming every tiled input read at an overview, as the plugin path does.

l.name, r.width, r.height
));
}
read.insert(key, r);
}
}
Ok(read)
}

#[cfg(not(target_arch = "wasm32"))]
thread_local! {
/// The raster files read in place that a batch's items read ([`tiled_inputs`]), by path, kept
/// while the batch runs on this thread ([`BatchReads`]): its items read each file once, not
/// once an item. `None` outside a batch, where nothing is kept past the run.
static BATCH_READS: std::cell::RefCell<Option<std::collections::HashMap<String, std::sync::Arc<rustgis_data::raster::Raster>>>> =
const { std::cell::RefCell::new(None) };
}

/// Keeps [`BATCH_READS`] while it lives: the outermost batch on this thread starts it and lets
/// it go, so a file it read is held only as long as the batch runs.
#[cfg(not(target_arch = "wasm32"))]
struct BatchReads(bool);

#[cfg(not(target_arch = "wasm32"))]
impl BatchReads {
fn start() -> BatchReads {
BatchReads(BATCH_READS.with(|b| {
let mut b = b.borrow_mut();
let outer = b.is_none();
if outer {
*b = Some(std::collections::HashMap::new());
}
outer
}))
}
}

#[cfg(not(target_arch = "wasm32"))]
impl Drop for BatchReads {
fn drop(&mut self) {
if self.0 {
BATCH_READS.with(|b| *b.borrow_mut() = None);
}
}
}

/// Narrows the rows a tool reads of each layer to the features its definition query keeps, as the
/// map draws them (#1995): a selection is cut to its drawn features, and a layer without one (or
/// with only the environment's extent) reads the kept features instead of every one. A layer whose
Expand Down Expand Up @@ -1990,9 +2142,11 @@ impl Inputs for MapInputs<'_> {
*self.view.get_or_init(|| view_extent(&self.snap))
}
fn raster(&self, layer: &str) -> Option<RasterInput<'_>> {
let rl = self.snap.map.layer_by_name(layer)?.raster.as_ref()?;
let l = self.snap.map.layer_by_name(layer)?;
let rl = l.raster.as_ref()?;
let read = self.rasters.get(&l.name.to_ascii_lowercase()).map(std::sync::Arc::as_ref);
Some(RasterInput {
raster: rl.data.as_deref()?,
raster: read.or(rl.data.as_deref())?,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

GeoLibre runs can silently stage the held overview of a tiled layer whose file has gone. external_start uses Tiled::ByPath, so tiled_inputs returns early and rasters stays empty. Inputs::raster then falls back to rl.data, the overview. In geolibre::stage (crates/geolibre/src/lib.rs:519), on_disk(p) is false when the file was moved or deleted after it was added. The code then goes to geotiff::write(r.raster) and stages the overview as the input, with no notice. A built-in run fails loudly in this case (read_path_with errors), so this is a GeoLibre-only gap.

Failure: add a 1 GB tiled GeoTIFF, move it, run a GeoLibre raster tool on the layer. The tool runs on a 326 × 307 image and reports success.

Fix: for Tiled::ByPath, check each tiled layer's file in tiled_inputs and return an error naming the layer and path when it is missing, rather than letting Inputs::raster supply the overview.

Confidence: medium-high on the code path; I did not run it.

Category: bug

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in cf9aaf4. In Tiled::ByPath mode, tiled_inputs now refuses a tiled layer whose file is no longer there ("its file … is no longer there: Reload Data or Repair Data Source first"), so a suite tool never stages the held overview. each_kind_of_run_reads_a_tiled_file_as_it_says moves the file and checks the refusal.

path: rl.path.as_deref(),
embedded: rl.embedded.as_deref().map(|b| (rl.file_name.as_deref().unwrap_or("raster.tif"), b.as_slice())),
})
Expand Down Expand Up @@ -2038,6 +2192,9 @@ fn batch(s: &mut Session, p: &Value) -> CmdResult {

/// Runs a geoprocessing tool in batch across multiple layers or files with cancellation and progress reporting.
pub fn run_batch_with(s: &mut Session, p: &Value, control: &std::sync::Arc<rustgis_analysis::control::Control>) -> CmdResult {
// A raster file read in place is read once for the batch, not once an item.
#[cfg(not(target_arch = "wasm32"))]
let _reads = BatchReads::start();
let tool_name = ps(p, "tool").ok_or("tool is required")?;
let tool_id = tool_id(tool_name).ok_or_else(|| format!("no tool '{tool_name}'"))?;
let spec = rustgis_analysis::tool(tool_id).ok_or_else(|| format!("no tool '{tool_name}'"))?;
Expand Down Expand Up @@ -3100,7 +3257,10 @@ pub(crate) fn execute(
}
#[cfg(not(target_arch = "wasm32"))]
let read = recording.then(|| Snapshot::owned(s));
let inputs = match map_inputs(s, Some(spec), params) {
// A built-in tool run here (the command line, a script on its own thread) reads a
// raster file read in place, as one the app starts on a thread does.
let tiled = if pin.plugin().is_none() { Tiled::File } else { Tiled::Overview };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

GeoLibre tools run here read the whole file and then never use it. Tiled::File is chosen for every non-plugin pin, and that includes GeoLibre suite tools. execute (CLI, scripts, batches) and the ToolRun path when no geolibre_run service is set both reach this. The suite stages a layer by its path whenever the file is on disk (geolibre::stage), so the decoded raster is used only for its CRS. That decode can run up to max_samples, and external_start already avoids it with Tiled::ByPath.

Suggested direction: give suite pins Tiled::ByPath, using the same pin.resolved().source() == Some(rustgis_geolibre::SOURCE) check that external_start uses. That check needs the geolibre feature gate, so this cannot be a plain drop-in suggestion.

Confidence: medium on the routing, high on the decode.

Category: performance

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in d3042fc. tiled_for(pin) gives suite pins Tiled::ByPath (behind the geolibre feature, with the same source check external_start uses), plugins Overview and built-ins File. It's used on both the synchronous execute path and ToolRun::run, so a GeoLibre run no longer decodes the file.

let inputs = match map_inputs(s, Some(spec), params, tiled) {
Ok(inputs) => inputs,
// A batch item that can't read its input is kept in the history as a failed run.
Err(e) if opts.record.is_some() => return apply_with(s, run_of(t0), kept(), Err(e), now_ms().saturating_sub(t0), opts),
Expand Down
80 changes: 74 additions & 6 deletions crates/engine/src/cmd/raster.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,15 +402,15 @@ pub(super) fn read_notices(s: &mut Session, name: &str, layer: &mut RasterLayer)
let lost = layer.lost_unsaid();
let pixels = layer.pixels_unsaid();
if let Some(r) = pixels.as_deref()
&& let Some((fw, fh)) = r.overview.filter(|_| !layer.in_place)
&& let Some((fw, fh)) = r.overview.filter(|_| !layer.reads_in_place())
{
s.notify(format!("{name}: showing a {} × {} overview of the {fw} × {fh} raster", r.width, r.height), false);
}
for loss in lost {
s.notify(format!("{name}: {loss}"), false);
}
if let Some(r) = pixels.as_deref() {
if let Some(held) = layer.in_place.then(|| crate::in_place_overview(r)).flatten() {
if let Some(held) = layer.reads_in_place().then(|| crate::in_place_overview(r, layer.tiled)).flatten() {
s.notify(format!("{name}: {held}"), false);
}
if let Some(count) = rounded_count(r) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

For a tiled layer read in place, pixels is the held overview, so rounded_count(r) counts rounded values in the overview's pixels only. The text says "rounded as the file was read ... so an export writes the rounded values", but the export draws the file's finer tiles, which can round more values than this count. The count is still accurate for what the layer holds, so the fix is wording rather than a new count. The same wording already applies to web-address COGs, so this predates the PR. Confidence: medium that the number and the sentence disagree; low that anyone is misled in practice.

Category: agents-md

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 3b4f70c. For a raster read in place, the notice now says the count is of its W × H overview as it was read, and that the map and an export read finer levels and so show rounded values in more places. A raster held whole keeps the old wording.

Expand Down Expand Up @@ -567,7 +567,7 @@ pub(crate) fn say_losses(s: &mut Session, losses: Vec<(String, String)>) {
/// Opens a raster file by path; `ignored` is said with what reading it lost (options given that
/// don't apply to it).
pub fn add_path(s: &mut Session, path: &str, name: Option<&str>, page: Option<&str>, scan: bool, ignored: Option<String>) -> CmdResult {
let mut r = match super::reads::take(s, &read_key(path, page, scan)) {
let (mut r, tiled) = match super::reads::take::<RasterRead>(s, &read_key(path, page, scan)) {
Some(r) => r,
None => read_raster_as(path, page, scan),
}?;
Expand All @@ -580,7 +580,7 @@ pub fn add_path(s: &mut Session, path: &str, name: Option<&str>, page: Option<&s
// gives plain paths on Windows rather than `\\?\` ones).
let full = std::path::absolute(path).map(|p| p.display().to_string()).unwrap_or_else(|_| path.to_string());
// A scan is laid over the view as it is added, and that placement makes it reopen as one.
let mut rl = RasterLayer::from_path(r, full);
let mut rl = if tiled { RasterLayer::tiled_file(r, full) } else { RasterLayer::from_path(r, full) };
// A PDF's page, kept so the project opens the same page again.
rl.subdataset = page.map(str::to_string);
add_raster(s, &name, rl)
Expand Down Expand Up @@ -639,10 +639,78 @@ pub fn read_download_shared_page(name: &str, bytes: std::sync::Arc<Vec<u8>>, pag

/// The raster at `path` (a PDF's `page`), read whole; for a `scan`, as the file holds it, without

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Doc nit: this comment still says the raster is "read whole", but read_raster_as now returns the overview of a large local tiled GeoTIFF ((r, true)), so the comment is out of date. The same kind of drift is in tiled_inputs' doc (gp.rs around line 1483): it says a Tiled::ByPath run reads or says nothing, but that path returns an error when the file is missing.

Left for the release quality pass.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 2c1d10f along with the probe change. read_raster_as's doc now says a large local tiled GeoTIFF gives its overview read in place. tiled_inputs' doc now says a ByPath run refuses a file that is no longer there.

/// the world file beside it (#2075).
pub(crate) fn read_raster_as(path: &str, page: Option<&str>, scan: bool) -> Result<Raster, String> {
pub(crate) fn read_raster_as(path: &str, page: Option<&str>, scan: bool) -> RasterRead {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Possible AGENTS.md gap: a project is now read differently, with no fixture.

A project's local tiled GeoTIFF layer is now read in place when it opens (through reload and repair, using the probe). That is a change to how a project is read, and "a change to how a project is read adds or updates a fixture in schema/fixtures/". The PR adds no fixture; its coverage is tiled_files::a_project_keeps_a_tiled_file_as_a_file_and_reads_it_in_place_again, which is a unit test. I am not certain the rule means this case, so I am raising it as a question for the maintainers, not a definite break.

Category: agents-md

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I checked this and don't think the fixture rule applies, so no fixture is added.

  • What changes: how a raster layer's pixels are read once the file is opened.
  • What doesn't: how a project document is read. A project keeps such a layer exactly as before (path, no in_place, and tiled is never saved). tiled_files::a_project_keeps_a_tiled_file_as_a_file_and_reads_it_in_place_again checks that the saved text has no new key.
  • Why the fixtures don't fit: the fixtures in schema/fixtures/ hold project documents checked against the schema, and nothing in a document decides this. Whether a layer is read in place depends only on the file at its path when it opens, which a document fixture can't hold.

// A large tiled GeoTIFF: its overview, the part in view read as the map draws. Read whole
// as before when its overview can't be read after all.
#[cfg(not(target_arch = "wasm32"))]
if !scan && page.is_none() {
let full = std::path::absolute(path).map(|p| p.display().to_string()).unwrap_or_else(|_| path.to_string());
if tiled_in_place(&full)
&& let Ok(mut r) = crate::render::rustgis_tiles::cog::raster::overview_blocking(&full)
{
r.name = Path::new(path).file_stem().and_then(|s| s.to_str()).unwrap_or("raster").to_string();
return Ok((r, true));
}
}
let p = Path::new(path);
let read = if scan { raster::read_path_unplaced(p, page, None) } else { raster::read_path_with(p, page, None) };
read.map_err(|e| format!("{path}: {e}"))
read.map(|r| (r, false)).map_err(|e| format!("{path}: {e}"))
}

/// The most samples a raster file is held whole with: [`raster::max_samples`], or under test what
/// [`HELD_WHOLE`] sets on this thread, as no small fixture reaches the real limit.
#[cfg(not(target_arch = "wasm32"))]
fn held_whole() -> usize {
#[cfg(test)]
if let Some(max) = HELD_WHOLE.with(std::cell::Cell::get) {
return max;
}
raster::max_samples()
}

#[cfg(test)]
thread_local! {
/// [`held_whole`]'s limit on this thread, under test.
pub(crate) static HELD_WHOLE: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
}

/// A raster file read for [`add_path`]: its pixels, and whether they are the overview of a large
/// tiled GeoTIFF read in place ([`tiled_in_place`]).
pub(crate) type RasterRead = Result<(Raster, bool), String>;

/// Whether the GeoTIFF at `path` (a full path on this computer) is read in place rather than
/// held, as a cloud-optimised GeoTIFF's web address is (#2761): the map then reads the part in
/// view at the level the view needs, where holding it means one overview at every zoom. It is
/// when the file is tiled with overviews, too large to hold whole ([`raster::max_samples`]), and
/// reading it in place loses nothing reading it whole keeps: its header reports no loss (a
/// transparency mask, metadata that can't be read) and no `.aux.xml` or world file is beside it.
/// Reads the file's header (a few reads of the file, on the fetch workers), afresh each time, as
/// the file may have been written again; forgotten when it isn't read in place.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn tiled_in_place(path: &str) -> bool {
use crate::render::rustgis_tiles::cog;
use crate::render::rustgis_tiles::{address::Reach, cache};
// A `#` would be taken for a look's start by the in-place reader. A document that may reach
// only public addresses reads no file in place, and nothing of it is looked at here.
if !cog::is_local_file(path) || path.contains('#') || cache::ceiling_for(path) != Reach::Local {
return false;
}
let p = Path::new(path);
if !p.is_file() || raster::pam::read(p).is_some() || raster::world::beside(p).is_some() {
return false;
}
cog::forget_local_file(path);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

tiled_in_place runs for every local GeoTIFF on every add, reload and project open, and drops the file's cached tiles each time, even when the file is unchanged.

The probe reads the header of each local .tif (info_blocking) before it knows whether the file is large enough to read in place. forget_local_file then discards that file's Ready tiles and header (here and again on the !tiled path below). Effects: a Reload Data on one layer clears the tile cache of another layer that draws the same file, and every small GeoTIFF pays a header parse and cache reset.

Cheaper alternatives: check the file's byte length (or a cheap size bound) before the header read, and forget only when the revision changed, using the forget_if_rewritten logic that already exists in cog.rs.

Confidence: medium. Cost is inferred from the code, not measured.

Category: performance

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 2c1d10f. The probe no longer forgets the file before reading its header. A kept header and its tiles are reused while the file is unchanged, and they are read again only once its revision differs (forget_if_rewritten). An untiled file's header is still let go after the probe.

let tiled = cog::info_blocking(path).is_ok_and(|info| {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

tiled_in_place waits on the header with cog::info_blocking(path), and read_raster_as (line 649) waits on the overview with overview_blocking. Both use a fresh stop flag that is never set and no progress check, so a Cancel or a replaced project can't end the wait. The wait is up to two minutes, and it runs before relinked or reload looks at the still. cog::info_until(url, &stop) already gives a stoppable wait. This is a long step without a check, and the doc comment on tiled_in_place (line 687) doesn't say so, which AGENTS.md asks for. Either pass a stop flag set from the run's control, or state in the doc comment that the header read ignores Cancel and is bounded by the two-minute wait. Confidence: medium-low. The wait is on a local file, so it is normally milliseconds and only long on a hung mount. I have not run it.

Category: agents-md

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Addressed in 76a7672 by documenting it, the second option: tiled_in_place's doc comment now says the header wait, and read_raster_as's overview wait, don't look at Cancel. A local file answers in milliseconds, and a hung one (an unreachable mount) is given up after two minutes.

let l = &info.layout;
let full = l.levels.first().map_or(0, |f| u64::from(f.width) * u64::from(f.height));
let samples = full.saturating_mul(l.bands.max(1) as u64);
let lossless = l.lost.is_empty() && l.described.as_ref().is_none_or(|d| d.lost.is_empty());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

lossless says a file is read in place only when the in-place reader loses nothing the whole-file reader keeps, but the in-place header parse drops one note the whole-file reader gives: the assumed datum.

For a geographic GeoTIFF with no EPSG code, geotiff::cog_geo returns Crs::LonLat with no note (crates/data/src/raster/geotiff.rs, None if geo.geographic_model => Crs::LonLat). The whole-file reader (geotiff.rs, around line 1845) notes "its geographic coordinate system has no EPSG code, so its datum isn't read; its coordinates are read as longitude/latitude on WGS 84" and sets crs_assumed. crates/data/src/raster/cog.rs adds only the planetary note to lost, and read_overview copies layout.lost. So a large local file of this kind is now read as WGS 84 with nothing said, where main said so.

Fix: have cog_geo return the note with the CRS, push it into the layout's lost the way planetary::note_of is, so lossless sends such files to the whole-file reader. Add a test that the header carries the note, and that a clean file doesn't.

Confidence: high on the code path (read, not run).

Category: agents-md

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 037f7d7, as suggested.

  • The note: cog_geo now reports when it assumed the datum, and the layout puts the whole-file reader's note (now one shared constant, NO_EPSG_GEOGRAPHIC) into its lost.
  • Effect on local files: lossless is then false, so such a file is read whole, and says it.
  • Web addresses: a web-address COG of this kind now says it too.
  • Test: cog::tests::a_layout_says_an_assumed_datum_and_keeps_the_copyright covers a file without an EPSG code against a clean one.

samples > held_whole() as u64 && lossless && cog::raster::overview_level(&info).is_some()
});
if !tiled {
cog::forget_local_file(path);
}
tiled
}

/// The key [`add_path`]'s read of `path` (a PDF's `page`) is taken by (see [`super::reads`]): a
Expand Down
Loading
Loading