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
37 changes: 37 additions & 0 deletions crates/data/src/progress.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,30 @@ impl Drop for Installed {
}
}

/// Makes the run on this thread stop also once `stop` is set, its progress counted as before,
/// until the guard is dropped: for a caller with a stop of its own (a map frame no longer
/// wanted), so that a reader's long loops that only look at Cancel see it too.
pub fn also_stop_when(stop: Arc<std::sync::atomic::AtomicBool>) -> Installed {
struct Either(Option<Arc<dyn Probe>>, Arc<std::sync::atomic::AtomicBool>);
impl Probe for Either {
fn cancelled(&self) -> bool {
self.1.load(std::sync::atomic::Ordering::Relaxed) || self.0.as_ref().is_some_and(|p| p.cancelled())
}
fn begin(&self, total: u64) {
if let Some(p) = &self.0 {
p.begin(total);
}
}
fn advance(&self, n: u64) {
if let Some(p) = &self.0 {
p.advance(n);
}
}
}
let before = CURRENT.with(|c| c.borrow().clone());
install(Some(Arc::new(Either(before, stop))))
}

/// Starts counting a step of `total` items for the progress.
pub fn begin(total: usize) {
CURRENT.with(|c| {
Expand Down Expand Up @@ -158,5 +182,18 @@ pub(crate) mod tests {
}
assert!(check().is_ok());
assert!(step(1).is_ok(), "the guard put back no probe");
// A stop of the caller's own stops the run too, and the progress still reaches the probe.
let p = Arc::new(Counted::default());
let _g = install(Some(p.clone()));
let stop = Arc::new(AtomicBool::new(false));
{
let _also = also_stop_when(stop.clone());
begin(4);
step(1).unwrap();
stop.store(true, Ordering::Relaxed);
assert!(matches!(check(), Err(DataError::Cancelled)));
}
assert_eq!((p.done.load(Ordering::Relaxed), p.total.load(Ordering::Relaxed)), (1, 4));
assert!(check().is_ok(), "the caller's stop is gone with its guard");
}
}
7 changes: 7 additions & 0 deletions crates/data/src/source/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,13 @@ pub trait FeatureSource: Send + Sync {
fn visits_chunks(&self) -> bool {
self.streams_chunks()
}
/// Whether a read by area ([`FeatureSource::visit_chunks`] with an extent) gives every
/// feature of a whole read whose shape meets the area: false where some can't be placed by
/// area (a Shapefile's records without a usable box, left out of reads by area), and for a
/// source that doesn't say.
fn finds_all_by_area(&self) -> bool {
false
}
/// Whether a complete bounded traversal for a geographic extent is available. This also
/// covers readers whose view and whole-export paths still use their existing sample or
/// whole-read contracts.
Expand Down
64 changes: 56 additions & 8 deletions crates/data/src/source/shp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
use std::fs::File;
use std::io::{BufReader, Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use std::sync::atomic::AtomicU8;
use std::sync::atomic::Ordering::Relaxed;

mod cache;
mod index;
Expand Down Expand Up @@ -68,6 +70,24 @@ pub struct ShpSource {
table: Table,
encoding: crate::dbf::DbfEncoding,
reproject: Reproject,
/// Whether every record's stored box holds its shape, as reads by area take the boxes on
/// trust: [`BOXES_UNKNOWN`] until a whole read has looked, then [`BOXES_HOLD`] or
/// [`BOXES_DONT`].
boxes: AtomicU8,
}

/// Not yet looked at ([`ShpSource::boxes`]).
const BOXES_UNKNOWN: u8 = 0;
/// Every stored box holds its shape.
const BOXES_HOLD: u8 = 1;
/// Some stored box misses part of its shape: reads by area leave that shape out.
const BOXES_DONT: u8 = 2;

/// Whether `b`, a stored box as [`record_box`] gives it (rounded outward to f32, as the index
/// keeps it), holds `e`: a box that held the shape still does once rounded outward.
fn holds(b: [f32; 4], e: &Extent) -> bool {
let [x0, y0, x1, y1] = b.map(f64::from);
x0 <= e.min_x && y0 <= e.min_y && x1 >= e.max_x && y1 >= e.max_y
}

/// Bytes read ahead from the files: shapes and rows near each other in a read share a fill.
Expand Down Expand Up @@ -205,7 +225,9 @@ impl ShpSource {
if matches!(shape_type, 11 | 13 | 15 | 18 | 21 | 23 | 25 | 28) {
info.drop_zm(Some(index.count));
}
Ok(ShpSource { info, shp: path.to_path_buf(), dbf, index, table, encoding, reproject })
// Points too: each record's own type is read, whatever the header says.
let boxes = AtomicU8::new(BOXES_UNKNOWN);
Ok(ShpSource { info, shp: path.to_path_buf(), dbf, index, table, encoding, reproject, boxes })
}
}

Expand Down Expand Up @@ -350,6 +372,13 @@ impl FeatureSource for ShpSource {
fn streams_chunks(&self) -> bool {
true
}
/// Once a whole read has found every stored box holding its shape, and the index placed every
/// record (those without a usable box are left out of reads by area, said when the file is
/// opened). Until then, and for a file whose boxes miss their shapes, reads by area may leave
/// shapes out.
fn finds_all_by_area(&self) -> bool {
self.index.unboxed == 0 && self.boxes.load(Relaxed) == BOXES_HOLD
}
/// 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> {
Expand All @@ -360,9 +389,17 @@ impl FeatureSource for ShpSource {
if extent.is_some_and(|e| e.is_empty()) {
return Ok(Batch { complete: true, ..Batch::default() });
}
let bounds = extent.map(|e| [e.min_x as f32, e.min_y as f32, e.max_x as f32, e.max_y as f32]);
// Rounded outward, as the index keeps the records' boxes, so a box reaching the extent by
// less than an f32 step is still found.
let bounds = extent.map(|e| [f32_down(e.min_x), f32_down(e.min_y), f32_up(e.max_x), f32_up(e.max_y)]);
// 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 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.
let mut unchecked = false;
let mut shp = Cursor::open(&self.shp)?;
let mut dbf = Cursor::open(&self.dbf)?;
let mut buf = Vec::new();
Expand All @@ -384,6 +421,7 @@ impl FeatureSource for ShpSource {
buf.resize(place.len as usize, 0);
if shp.read_at(u64::from(place.offset), &mut buf).is_err() {
skipped += 1;
unchecked = true;
return Ok(());
}
let geometry = match parse_shape(&buf) {
Expand All @@ -396,13 +434,20 @@ impl FeatureSource for ShpSource {
boxed_off += u64::from(index::usable(record_box(&buf, u64::from(place.len))));
return Ok(());
}
Ok(Some(g)) => match self.reproject.read(g) {
Some(placed) => Some(placed),
None => {
skipped += 1;
return Ok(());
Ok(Some(g)) => {
// A box the index took as stored (one in order) that misses part of the shape.
if checking && !missed {
let stored = record_box(&buf, u64::from(place.len));
missed = index::usable(stored) && !holds(stored, &g.extent());
}
},
match self.reproject.read(g) {
Some(placed) => Some(placed),
None => {
skipped += 1;
return Ok(());
}
}
}
Ok(None) => None,
Err(()) => {
skipped += 1;
Expand Down Expand Up @@ -432,6 +477,9 @@ impl FeatureSource for ShpSource {
chunks.push(Feature { id: u64::from(i) + 1, geometry, attrs })
})?;
chunks.flush()?;
if checking && complete && (missed || !unchecked) {
self.boxes.store(if missed { BOXES_DONT } else { BOXES_HOLD }, Relaxed);
}
Ok(Batch {
features: Vec::new(),
matched,
Expand Down
142 changes: 140 additions & 2 deletions crates/data/src/source/shp/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,21 @@

use super::{BUFFER, Place, bad, be_i32, le_i32, record_box};
use crate::Result;
use rusqlite::{Connection, OpenFlags, params};
use rusqlite::{Connection, OpenFlags, OptionalExtension, params};
use std::io::{BufReader, Read};
use std::path::Path;
use std::sync::Mutex;

/// A complete read by area takes the record directory in one pass, rather than id by id, once at
/// least one record in this many matches. Measured on a directory of 3.2 million records (8 MB of
/// page cache, as [`connect`] sets): about 170 ns a record in one pass, about 13 µs a record by id,
/// so the two cost the same near one record in 75.
const PASS_ABOVE: u64 = 64;

/// How many index rows a read by area goes through between looks at Cancel (few in tests, so
/// that a small file reaches one).
const LOOK_EVERY: usize = if cfg!(test) { 64 } else { 1 << 16 };

struct DiskIndex {
db: Mutex<Connection>,
pub count: u64,
Expand Down Expand Up @@ -148,7 +158,81 @@ impl DiskIndex {
/// interaction connection's mutex. The index lease keeps this immutable file alive.
fn visit_complete(&self, extent: Option<[f32; 4]>, visit: impl FnMut(u32, Place) -> Result<()>) -> Result<(u64, bool)> {
let db = connect(self._lease.path(), false)?;
self.visit_on(&db, extent, u32::MAX as usize, visit)
match extent.filter(|e| u64::from(self.covered) != self.count || !self.covers_bbox(*e)) {
Some(e) => self.visit_matches(&db, e, visit),
None => self.visit_on(&db, None, u32::MAX as usize, visit),
}
}

/// Every record whose box meets `extent`, in file order (#1065). The R-tree gives the
/// matching ids alone, marked in a bitmap of one bit a record; the places are then read
/// through the directory in order: by id when few match, else in one pass over it. A join
/// of the two tables sorted by id instead costs several seconds a few hundred thousand
/// matches, and was run twice, once to count.
fn visit_matches(&self, db: &Connection, extent: [f32; 4], mut visit: impl FnMut(u32, Place) -> Result<()>) -> Result<(u64, bool)> {
let [x0, y0, x1, y1] = extent;
let words = usize::try_from(self.count.div_ceil(64)).map_err(|_| bad("spatial index: too many records"))?;
let mut hits: Vec<u64> = Vec::new();
hits.try_reserve_exact(words).map_err(|e| bad(format!("spatial index: {e}")))?;
hits.resize(words, 0);
let mut matched = 0u64;
{
let mut stmt = db.prepare("SELECT id FROM bounds WHERE x0<=?1 AND x1>=?2 AND y0<=?3 AND y1>=?4").map_err(sql)?;
let mut rows = stmt.query(params![x1, x0, y1, y0]).map_err(sql)?;
let mut seen = 0usize;
while let Some(r) = rows.next().map_err(sql)? {
seen += 1;
if seen.is_multiple_of(LOOK_EVERY) {
crate::progress::check()?;
}
// An id past the directory is no record of this file.
let Some(id) = r.get::<_, i64>(0).ok().and_then(|id| u64::try_from(id).ok()).filter(|id| *id < self.count) else {
continue;
};
let Some(word) = usize::try_from(id / 64).ok().and_then(|w| hits.get_mut(w)) else { continue };
let bit = 1u64 << (id % 64);
if *word & bit == 0 {
*word |= bit;
matched += 1;
}
}
}
// What the progress counts from here: the records read, not every record of the file.
crate::progress::begin(usize::try_from(matched).unwrap_or(usize::MAX));
let hit = |id: u64| usize::try_from(id / 64).ok().and_then(|w| hits.get(w)).is_some_and(|w| w & (1u64 << (id % 64)) != 0);
if matched.saturating_mul(PASS_ABOVE) >= self.count {

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 one-in-eight crossover (PASS_ABOVE = 8) is not yet measured, and the PR body says timings are still pending. Below it, each matched record costs one query_row on the directory (a B-tree lookup). Near the threshold, with a 3.2M-record file, that is about 400K lookups on every frame, which may be slower than the single ordered pass it replaces. Please measure the crossover on the 3.2M-building file before merging, and set PASS_ABOVE from that result (a lower ratio is likely), or say in the code comment that the value is a guess.

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.

Measured in 6fa0372 on the 3.2-million-record directory with the index's settings (8 MB page cache): about 170 ns a record in one ordered pass, about 13 µs a record by id, so the two cost the same near one record in 75. PASS_ABOVE is now 64, with the measurement in its doc. An id the directory lacks is now skipped on the by-id path, as it is in the pass.

let mut stmt = db.prepare("SELECT id, offset, len FROM records ORDER BY id").map_err(sql)?;
let mut rows = stmt.query([]).map_err(sql)?;
let mut seen = 0usize;
while let Some(r) = rows.next().map_err(sql)? {
seen += 1;
if seen.is_multiple_of(LOOK_EVERY) {
crate::progress::check()?;
}
let id: u32 = r.get(0).map_err(sql)?;
if hit(u64::from(id)) {
visit(id, Place { offset: r.get(1).map_err(sql)?, len: r.get(2).map_err(sql)? })?;
}
}
} else {
let mut stmt = db.prepare("SELECT offset, len FROM records WHERE id=?1").map_err(sql)?;
for (w, word) in hits.iter().enumerate() {
if w.is_multiple_of(LOOK_EVERY / 64) {
crate::progress::check()?;
}
let mut bits = *word;
while bits != 0 {
let id = (w * 64) as u64 + u64::from(bits.trailing_zeros());
bits &= bits - 1;
// An id the directory lacks is no record of this file, as in the pass above.
let place = stmt.query_row([id as i64], |r| Ok(Place { offset: r.get(0)?, len: r.get(1)? })).optional().map_err(sql)?;
if let Some(place) = place {
visit(id as u32, place)?;
}
}
}
}
Ok((matched, true))
}

fn visit_on(
Expand Down Expand Up @@ -531,6 +615,60 @@ mod tests {
use super::*;
use crate::{Coord, Dataset, Geometry, GeometryType};

/// A complete read by area gives the records whose boxes meet it in file order, as a read
/// through the R-tree joined to the directory does, whether a few match (read by id) or many
/// (one pass over the directory), and nothing for an area off the records (#1065).
#[test]
fn a_complete_read_by_area_gives_the_matching_records_in_file_order() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("grid.shp");
let mut ds = Dataset::new("grid", GeometryType::Point, vec![]);
// 400 points, in an order unlike their places, so file order isn't the R-tree's.
for i in 0..400u32 {
let k = (i * 151) % 400;
ds.push(Some(Geometry::Point(Coord::new(f64::from(k % 20), f64::from(k / 20)))), vec![]);
}
crate::io::write_path(&ds, &path).unwrap();
let len = std::fs::metadata(&path).unwrap().len();
super::super::cache::with_index_dir(tmp.path().join("cache"), || {
let index = Index::open(&path, len, &mut Vec::new()).unwrap();
assert!(index.indexed());
for (area, many) in [([2.5f32, 2.5, 4.5, 5.5], false), ([0.0, 0.0, 12.0, 15.0], true), ([50.0, 50.0, 60.0, 60.0], false)] {
let mut expected = Vec::new();
index
.visit(Some(area), usize::MAX, |id, place| {
expected.push((id, place.offset, place.len));
Ok(())
})
.unwrap();
let mut got = Vec::new();
let (matched, complete) = index
.visit_complete(Some(area), |id, place| {
got.push((id, place.offset, place.len));
Ok(())
})
.unwrap();
assert!(complete);
assert_eq!(got, expected, "{area:?}");
assert_eq!(matched, got.len() as u64);
assert!(got.windows(2).all(|w| w[0].0 < w[1].0), "in file order");
assert_eq!(matched * PASS_ABOVE >= 400, many, "{area:?}: {matched} matched");
// Its progress counts the records read, and Cancel stops it before any is.
let probe = std::sync::Arc::new(crate::progress::tests::Counted::default());
let _probe = crate::progress::install(Some(probe.clone()));
index.visit_complete(Some(area), |_, _| Ok(())).unwrap();
assert_eq!(probe.total.load(std::sync::atomic::Ordering::Relaxed), matched);
probe.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
let mut read = 0;
let stopped = index.visit_complete(Some(area), |_, _| {
read += 1;
Ok(())
});
assert!(matches!(stopped, Err(crate::DataError::Cancelled)) && read == 0, "{area:?}: {read} read");
}
});
}

/// Scanning record headers, when no index can be written, gathers the records' boxes as an
/// index does (`union`): a NaN shape's box is left out, the others framed (#1985).
#[test]
Expand Down
Loading
Loading