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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 23 additions & 4 deletions crates/data/src/source/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,12 @@ impl Request {
}
}

/// A box over the whole plane: as [`Request::own`], every feature in the source's own system,
/// those longitude/latitude can't place included (a map in that system draws them as they are).
pub fn whole_plane() -> Extent {
Extent::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::INFINITY)
}

/// Refuses an unknown count rather than reporting an unbounded view as empty. A zero-limit
/// request does not start the full geometry scan needed to determine its matches.
pub(crate) fn unbounded_count() -> DataError {
Expand Down Expand Up @@ -419,6 +425,17 @@ pub trait FeatureSource: Send + Sync {
fn visit_chunks(&self, _extent: Option<Extent>, _bytes: usize, _visit: &mut dyn FnMut(Vec<Feature>) -> Result<()>) -> Result<Batch> {
Err(DataError::Unsupported("a source that can't be read a chunk at a time".into()))
}
/// [`FeatureSource::visit_chunks`] for a whole request, its box in the source's own system
/// ([`Request::own`]) too (one over the whole plane, [`whole_plane`], reads every feature as a
/// map in that system draws them): a source that reads one this way tests each feature's own box
/// against it, converting nothing. One that doesn't visits every feature when given a box in
/// its own system, never fewer than it holds (its extent, in longitude/latitude, may hold
/// less), and reads the extent otherwise (no box, or one in another system).
fn visit_request_chunks(&self, req: &Request, bytes: usize, visit: &mut dyn FnMut(Vec<Feature>) -> Result<()>) -> Result<Batch> {

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.

Several sources say reads_own_box() is true (fgb.rs:831, geojson.rs:319, gpkg.rs:436, gpkg_mem.rs:338, parquet.rs:489) but don't override visit_request_chunks, so an own-box request on them visits every feature. That is correct today, because the render path gates own reads on finds_all_by_area, which only the Shapefile sets. But it contradicts the reads_own_box doc, which says a source given its own box tests features against it. If one of these later gains finds_all_by_area without an override, it would silently read whole files on every frame. Either override the method there or narrow the reads_own_box doc.

Confidence: medium.

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 115ade7: reads_own_box's doc now says it is about read, and that a complete visit tests an own box only where the source overrides visit_request_chunks (the default visits every feature when given one).

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 default ignores req.extent whenever req.own is present, even when the box is in another system. Request::own says a source in another system "reads extent, as without it", so a mismatched box here visits every feature instead. That is a superset, so no wrong results, but it's a full read where the contract asks for the extent. Only the render path reaches this, and it always passes the matching system, so this is a contract mismatch, not a live defect. Matching the system here keeps the default in line with Request::own:

Suggested change
fn visit_request_chunks(&self, req: &Request, bytes: usize, visit: &mut dyn FnMut(Vec<Feature>) -> Result<()>) -> Result<Batch> {
fn visit_request_chunks(&self, req: &Request, bytes: usize, visit: &mut dyn FnMut(Vec<Feature>) -> Result<()>) -> Result<Batch> {
let in_own = req.own.is_some_and(|(crs, _)| crs == self.coord_crs());
self.visit_chunks(if in_own { None } else { req.extent }, bytes, visit)
}

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 eb01419: the default reads the extent when the own box is in another system, and visits every feature only for a box in its own system it can't use; the doc says so.

// A box in another system is read as if absent, as `Request::own` has it.
let in_own = req.own.is_some_and(|(crs, _)| crs == self.coord_crs());
self.visit_chunks(if in_own { None } else { req.extent }, bytes, visit)
}
fn info(&self) -> &SourceInfo;
/// The coordinate system of the features it gives: a file read in place gives them as the file
/// holds them, in its own system (Shapefile, GeoPackage, FlatGeobuf, GeoParquet, GeoJSON); a
Expand All @@ -429,9 +446,10 @@ pub trait FeatureSource: Send + Sync {
crate::raster::Crs::LonLat
}

/// Whether a read given its box in the source's own system ([`Request::own`]) tests its
/// features against that box (a file read in place, PostGIS), so a map in that system keeps
/// its window in map units for it. A source that reads by the longitude/latitude extent
/// Whether a read ([`FeatureSource::read`]) given its box in the source's own system
/// ([`Request::own`]) tests its features against that box (a file read in place, PostGIS), so
/// a map in that system keeps its window in map units for it. A complete visit does so only
/// where the source says so through [`FeatureSource::visit_request_chunks`]. A source that reads by the longitude/latitude extent

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit: this doc paragraph was re-wrapped unevenly. Line 452 runs to about 170 characters, and the sentence that follows starts on a new line at a different width. Re-wrap the paragraph to the surrounding width, with no change of wording.

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.

Left for the release quality pass.

/// whatever it is given (another database, a service, a converted copy) says no: its window is
/// kept in longitude/latitude, as it reads.
fn reads_own_box(&self) -> bool {
Expand Down Expand Up @@ -1014,7 +1032,8 @@ impl Reproject {
if !g.is_finite() {
return None;
}
let inside = g.extent().intersects(&own);
// A box over the whole plane holds every shape, one with no place (an empty part) too.
let inside = own == whole_plane() || g.extent().intersects(&own);
return Some(Fitted { geometry: g, inside });
}
let Placed { geometry, lonlat } = self.read(g)?;
Expand Down
15 changes: 15 additions & 0 deletions crates/data/src/source/own_box_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,3 +152,18 @@ fn a_coordinate_that_isnt_a_number_is_left_out_in_its_own_system_too() {
let clean = Geometry::Line(vec![vec![Coord::new(451_500.0, 5_411_500.0), Coord::new(452_000.0, 5_411_500.0)]]);
assert!(r.place(clean, &req).unwrap().inside);
}

/// A box over the whole plane holds every shape, one with no place (a polygon of no parts)
/// included, as a read without a box keeps it (#2788).
#[test]
fn the_whole_plane_holds_a_shape_with_no_place() {
let utm = Crs::from_epsg(32631).unwrap();
let reproject = Reproject::known(Some((utm, utm.transformer().unwrap())));
let empty = Geometry::Polygon(Vec::new());
let whole = Request { extent: None, limit: usize::MAX, own: Some((utm, whole_plane())) };
let none = Request { extent: None, limit: usize::MAX, own: None };
let small = Request { extent: None, limit: usize::MAX, own: Some((utm, Extent::new(0.0, 0.0, 1.0, 1.0))) };
assert!(reproject.place(empty.clone(), &whole).is_some_and(|f| f.inside), "the whole plane");
assert!(reproject.place(empty.clone(), &none).is_some_and(|f| f.inside), "no box");
assert!(reproject.place(empty, &small).is_some_and(|f| !f.inside), "a box of somewhere");
}
21 changes: 16 additions & 5 deletions crates/data/src/source/shp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -425,10 +425,20 @@ impl FeatureSource for ShpSource {
/// Visits located shapes in a spatial request; geometry-less rows belong only to whole reads.
/// Counts scanned records and checks Cancel before filtering them.
fn visit_chunks(&self, extent: Option<Extent>, bytes: usize, visit: &mut dyn FnMut(Vec<Feature>) -> Result<()>) -> Result<Batch> {
self.visit_request_chunks(&Request { extent, limit: usize::MAX, own: None }, bytes, visit)
}
/// As [`FeatureSource::visit_chunks`], narrowed by the request's box in the file's own system
/// when it gives one ([`Request::own`]), and each shape's own box tested against it.
fn visit_request_chunks(&self, req: &Request, bytes: usize, visit: &mut dyn FnMut(Vec<Feature>) -> Result<()>) -> Result<Batch> {
let encoding = self.encoding.decoder();
let mut chunks = super::chunk_memory::Chunker::new(bytes, visit)?;
let req = Request { extent, limit: usize::MAX, own: None };
let extent = extent.and_then(|e| self.reproject.extent_from_lonlat(&e));
let req = Request { limit: usize::MAX, ..*req };
// The request's box in the file's own system, when it is one (a box in another system
// is read as if absent), and whether it is one over the whole plane, which narrows
// nothing: every record, those without a box too, as a whole read.
let own = self.reproject.own_box(&req);
let everywhere = own == Some(super::whole_plane());
let extent = self.reproject.request_box(&req).filter(|_| !everywhere);
if extent.is_some_and(|e| e.is_empty()) {
return Ok(Batch { complete: true, ..Batch::default() });
}
Expand All @@ -438,7 +448,7 @@ impl FeatureSource for ShpSource {
// As in `read`, an extent the file's system couldn't bound (#1925) visits every record.
let late = req.extent.is_some() && bounds.is_none();
// A whole read looks at whether the stored boxes hold their shapes, once.
let checking = req.extent.is_none() && self.boxes.load(Relaxed) == BOXES_UNKNOWN;
let checking = req.extent.is_none() && (own.is_none() || everywhere) && self.boxes.load(Relaxed) == BOXES_UNKNOWN;
let mut missed = false;
// A record a whole read couldn't read this time had its box left unchecked: the check
// waits for a read that reads them all.
Expand Down Expand Up @@ -497,8 +507,9 @@ impl FeatureSource for ShpSource {
return Ok(());
}
};
// As in `read`, the shape itself is checked.
if geometry.as_ref().map_or(req.extent.is_some(), |g| !g.inside) {
// As in `read`, the shape itself is checked; a read by area, its box in the file's

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 comment says the rule is "as in read", with an own box included. It isn't, for an own-box request with no longitude/latitude extent. read (line 350) still tests req.extent.is_some(), so it keeps geometry-less rows for that request, while this visit drops them. Nothing reaches the difference today: the render path sends such a request only through the visit, and the map's window read always passes an extent with its own box. So no drawn output changes. But the comment claims parity that the code doesn't have, and no test covers read with an own box alone. Either make read use the same own-box rule, or narrow this comment to the visit and add a test that pins the difference.

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.

Left for the release quality pass: no output differs today (the window read always passes an extent with its own box), and making read follow the same own-box rule, or narrowing the comment, with a test pinning it, fits there.

// own system included, gives no rows without a shape.
if geometry.as_ref().map_or(if own.is_some() { !everywhere } else { req.extent.is_some() }, |g| !g.inside) {
return Ok(());
}
let geometry = geometry.map(|p| p.geometry);
Expand Down
61 changes: 61 additions & 0 deletions crates/data/src/source/shp/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -917,3 +917,64 @@ fn a_shapefile_says_whether_it_is_as_it_was_opened() {
assert!(s.same_as_opened().is_err(), "gone");
});
}

/// The ids a complete read with this own box (no longitude/latitude extent) gives.
fn without_shape(s: &ShpSource, own: Option<(crate::raster::Crs, Extent)>) -> Vec<u64> {
let mut ids = Vec::new();
s.visit_request_chunks(&Request { extent: None, limit: usize::MAX, own }, 4096, &mut |chunk| {
ids.extend(chunk.iter().map(|f| f.id));
Ok(())
})
.unwrap();
ids
}

/// A complete read by a box in the file's own system (#2788) gives the shapes meeting it and no
/// row without a shape, as a read by area in longitude/latitude does, also when it gives no
/// longitude/latitude extent beside the box.
#[test]
fn a_complete_read_by_its_own_box_leaves_out_rows_without_a_shape() {
let utm = crate::raster::Crs::from_epsg(32631).unwrap();
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("pts.shp");
let mut ds = Dataset::new("pts", GeometryType::Point, vec![Field::new("n", FieldType::Integer)]);
for (i, p) in
[Some((450_000.0, 5_410_000.0)), None, Some((460_000.0, 5_420_000.0)), Some((900_000.0, 5_000_000.0))].into_iter().enumerate()
{
ds.push(p.map(|(x, y)| Geometry::Point(Coord::new(x, y))), vec![Value::Int(i as i64)]);
}
ds.held_in = utm;
crate::io::write_path_in(&ds, &path, utm).unwrap();
// The first record made a shape of no geometry (its type, at 108, 0), as other writers give
// a feature without one.
let mut b = std::fs::read(&path).unwrap();
b[108..112].copy_from_slice(&0i32.to_le_bytes());
std::fs::write(&path, b).unwrap();
cache::with_index_dir(tmp.path().join("cache"), || {
let s = ShpSource::open_path(&path, "pts").unwrap();
let own = Extent::new(440_000.0, 5_400_000.0, 470_000.0, 5_430_000.0);
let mut got = Vec::new();
s.visit_request_chunks(&Request { extent: None, limit: usize::MAX, own: Some((utm, own)) }, 4096, &mut |chunk| {
got.extend(chunk.iter().map(|f| f.id));
Ok(())
})
.unwrap();
// What a whole read gives, the features with a shape in the box.
let mut expected = Vec::new();
let mut rows = 0;
s.visit_chunks(None, 4096, &mut |chunk| {
rows += chunk.len();
expected.extend(chunk.iter().filter(|f| f.geometry.as_ref().is_some_and(|g| g.extent().intersects(&own))).map(|f| f.id));
Ok(())
})
.unwrap();
assert!(rows > expected.len() && !expected.is_empty(), "{rows} rows, {expected:?} in the box");
assert_eq!(got, expected, "the points in the box, not a row without a shape or the far point");
assert!(without_shape(&s, None).contains(&1), "a whole read gives the row without a shape");
// A box in another system is read as if absent: every row, the one without a shape too.
let lonlat = Some((crate::raster::Crs::LonLat, own));
assert_eq!(without_shape(&s, lonlat), without_shape(&s, None), "a box in another system reads everything");
// A box over the whole plane reads everything too, as a whole read does.
assert_eq!(without_shape(&s, Some((utm, super::super::whole_plane()))), without_shape(&s, None));
});
}
Loading
Loading