Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
10 changes: 10 additions & 0 deletions crates/data/src/source/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,16 @@ 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()))
}
/// Whether [`FeatureSource::visit_ids_chunks`] is available.
fn visits_ids(&self) -> bool {
false
}
/// The features with these ids ([`Feature::id`], in order), visited a chunk at a time in
/// source order, as [`FeatureSource::visit_chunks`] visits them: for a read of features
/// someone already knows by id. Ids the source doesn't hold are left out.
fn visit_ids_chunks(&self, _ids: &[u64], _bytes: usize, _visit: &mut dyn FnMut(Vec<Feature>) -> Result<()>) -> Result<Batch> {
Err(DataError::Unsupported("a source that can't be read by feature id".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
Expand Down
259 changes: 144 additions & 115 deletions crates/data/src/source/shp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,141 @@ impl ShpSource {
}
}

impl ShpSource {
/// A complete visit of a request's records, or of those numbered `numbered` (from 0, in
/// order), parsed and given a chunk at a time ([`FeatureSource::visit_request_chunks`],
/// [`FeatureSource::visit_ids_chunks`]). Only a whole read looks at the stored boxes.
fn visit_with(
&self,
req: &Request,
numbered: Option<&[u32]>,
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 { 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() });
}
// 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 =
numbered.is_none() && 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.
let mut unchecked = false;
let mut shp = Cursor::open(&self.shp)?;
let mut dbf = Cursor::open(&self.dbf)?;
let mut buf = Vec::new();
let mut row = vec![0u8; self.table.row_len];
let (mut skipped, mut unread_dates, mut null_text, mut boxed_off, mut not_utf8) = (0, Vec::new(), Vec::new(), 0u64, Vec::new());
let mut deleted = 0usize;
// The same directory, ordering, extent rules and read-only scan fallback as sampled
// reads, with no interaction row cap. The index visits records without materializing
// their directory or the complete feature collection in memory.
// Every record id fits u32. This format bound visits them all while keeping SQLite'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.

Nits in visit_with, grouped: the comment at lines 309-311 about the u32 id bound and SQLite's LIMIT was carried over from visit_complete and no longer matches what this function does. The comment at line 354 ("As in read, the shape itself is checked.") is followed by a second comment about a read by area that says the same thing again. The doc on visit_with ("from 0, in order") also doesn't say whether numbered must be sorted, which it doesn't need to be. 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.

Left for the release quality pass.

// LIMIT within its signed integer range on 64-bit hosts.
crate::progress::begin(self.info.count.and_then(|n| usize::try_from(n).ok()).unwrap_or(0));
let mut each = |i: u32, place: Place| -> Result<()> {
crate::progress::step(1)?;
if u64::from(place.len) > MAX_RECORD {
skipped += 1;
return Ok(());
}
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) {
// A coordinate that isn't a number (NaN or infinite) has no place: the record is
// left out and counted, as one that can't be converted (#1985). One under a stored
// box the index takes ([`index::usable`]) is counted apart too, as the index framed
// it by that box; a backwards one it can't frame, and counts as unboxed instead.
Ok(Some(g)) if !g.is_finite() => {
skipped += 1;
boxed_off += u64::from(index::usable(record_box(&buf, u64::from(place.len))));
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.place(g, &req) {
Some(placed) => Some(placed),
None => {
skipped += 1;
return Ok(());
}
}
}
Ok(None) => None,
Err(()) => {
skipped += 1;
return Ok(());
}
};
// As in `read`, the shape itself is checked.
// As a read by area, its box in the file's 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);
let attrs = if u64::from(i) < self.table.rows {
let at = self.table.header_len + u64::from(i) * self.table.row_len as u64;
if dbf.read_at(at, &mut row).is_err() {
skipped += 1;
return Ok(());
}
// A deleted row: its shape is left out too, and counted.
if row.first() == Some(&b'*') {
deleted += 1;
return Ok(());
}
self.table.values(&row, &encoding, &self.encoding, &mut unread_dates, &mut null_text, &mut not_utf8)
} else {
vec![Value::Null; self.table.columns.len()]
};
chunks.push(Feature { id: u64::from(i) + 1, geometry, attrs })
};
let (matched, complete) = match numbered {
Some(numbers) => self.index.visit_numbered(numbers, &mut each)?,
None => self.index.visit_complete(bounds, &mut each)?,
};
chunks.flush()?;
if checking && complete && (missed || !unchecked) {
self.boxes.store(if missed { BOXES_DONT } else { BOXES_HOLD }, Relaxed);
}
Ok(Batch {
features: Vec::new(),
matched,
complete,
skipped,
unread_dates,
rounded_dates: Vec::new(),
null_text,
notes: boxed_off_note(boxed_off, false, late).into_iter().chain(deleted_note(deleted, false)).collect(),
not_utf8,
})
}
}

impl FeatureSource for ShpSource {
fn info(&self) -> &SourceInfo {
&self.info
Expand Down Expand Up @@ -430,121 +565,15 @@ impl FeatureSource for ShpSource {
/// 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 { 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() });
}
// 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() && (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.
let mut unchecked = false;
let mut shp = Cursor::open(&self.shp)?;
let mut dbf = Cursor::open(&self.dbf)?;
let mut buf = Vec::new();
let mut row = vec![0u8; self.table.row_len];
let (mut skipped, mut unread_dates, mut null_text, mut boxed_off, mut not_utf8) = (0, Vec::new(), Vec::new(), 0u64, Vec::new());
let mut deleted = 0usize;
// The same directory, ordering, extent rules and read-only scan fallback as sampled
// reads, with no interaction row cap. The index visits records without materializing
// their directory or the complete feature collection in memory.
// Every record id fits u32. This format bound visits them all while keeping SQLite's
// LIMIT within its signed integer range on 64-bit hosts.
crate::progress::begin(self.info.count.and_then(|n| usize::try_from(n).ok()).unwrap_or(0));
let (matched, complete) = self.index.visit_complete(bounds, |i, place| {
crate::progress::step(1)?;
if u64::from(place.len) > MAX_RECORD {
skipped += 1;
return Ok(());
}
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) {
// A coordinate that isn't a number (NaN or infinite) has no place: the record is
// left out and counted, as one that can't be converted (#1985). One under a stored
// box the index takes ([`index::usable`]) is counted apart too, as the index framed
// it by that box; a backwards one it can't frame, and counts as unboxed instead.
Ok(Some(g)) if !g.is_finite() => {
skipped += 1;
boxed_off += u64::from(index::usable(record_box(&buf, u64::from(place.len))));
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.place(g, &req) {
Some(placed) => Some(placed),
None => {
skipped += 1;
return Ok(());
}
}
}
Ok(None) => None,
Err(()) => {
skipped += 1;
return Ok(());
}
};
// As in `read`, the shape itself is checked; a read by area, its box in the file's
// 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);
let attrs = if u64::from(i) < self.table.rows {
let at = self.table.header_len + u64::from(i) * self.table.row_len as u64;
if dbf.read_at(at, &mut row).is_err() {
skipped += 1;
return Ok(());
}
// A deleted row: its shape is left out too, and counted.
if row.first() == Some(&b'*') {
deleted += 1;
return Ok(());
}
self.table.values(&row, &encoding, &self.encoding, &mut unread_dates, &mut null_text, &mut not_utf8)
} else {
vec![Value::Null; self.table.columns.len()]
};
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,
complete,
skipped,
unread_dates,
rounded_dates: Vec::new(),
null_text,
notes: boxed_off_note(boxed_off, false, late).into_iter().chain(deleted_note(deleted, false)).collect(),
not_utf8,
})
self.visit_with(req, None, bytes, visit)
}
fn visits_ids(&self) -> bool {
true
}
/// The records whose features have these ids (record numbers from 1), in file order.
fn visit_ids_chunks(&self, ids: &[u64], bytes: usize, visit: &mut dyn FnMut(Vec<Feature>) -> Result<()>) -> Result<Batch> {
let numbers: Vec<u32> = ids.iter().filter_map(|id| id.checked_sub(1).and_then(|n| u32::try_from(n).ok())).collect();

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.

Performance / memory: visit_ids_chunks builds a second full-size list (numbers: Vec<u32>) from the Vec<u64> that DrawnIndex::query returned. Together those are about 12 bytes per matched feature, transient, and bounded only by half the file (around 38 MB at 3.2 million features). The PR's memory section reports only the index (about 21 bytes per feature) and does not count this. Under the "Size for real data" rule, please either state this transient in the PR, or pass the u64 ids through and convert them lazily inside visit_numbered.

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.

Stated in the PR body's memory section now: the ids of a read by ids (8 bytes each, plus 4 for the record numbers) are held while it runs, at most half the layer's features since more than half reads the whole file, so at most about 6 bytes a feature.

self.visit_with(&Request { extent: None, limit: usize::MAX, own: None }, Some(&numbers), bytes, visit)
}
}

Expand Down
53 changes: 52 additions & 1 deletion crates/data/src/source/shp/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ impl DiskIndex {
/// 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)> {
fn visit_matches(&self, db: &Connection, extent: [f32; 4], 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();
Expand Down Expand Up @@ -197,6 +197,18 @@ impl DiskIndex {
}
}
}
self.visit_hits(db, &hits, matched, visit)
}

/// Every record marked in `hits` (one bit a record), `matched` of them, in file order: by id
/// when few are, else in one pass over the directory.
fn visit_hits(
&self,
db: &Connection,
hits: &[u64],
matched: u64,
mut visit: impl FnMut(u32, Place) -> Result<()>,
) -> Result<(u64, bool)> {
// 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);
Expand Down Expand Up @@ -419,6 +431,45 @@ impl Index {
pub fn indexed(&self) -> bool {
matches!(self.storage, Storage::Disk(_))
}
/// The records numbered in `ids` (from 0, in order; numbers past the file's are left out), in
/// file order, for a read of the features someone already knows by number.
pub fn visit_numbered(&self, ids: &[u32], mut visit: impl FnMut(u32, Place) -> Result<()>) -> Result<(u64, bool)> {
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;
for &id in ids {
let id = u64::from(id);
if id >= self.count {
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;
}
}
// None of the file's: nothing to read, not even its directory.
if matched == 0 {
crate::progress::check()?;
return Ok((0, true));
}
match &self.storage {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Storage::Disk(disk) => {
let db = connect(disk._lease.path(), false)?;
disk.visit_hits(&db, &hits, matched, visit)
}
// Without an index, the record headers are scanned and those numbered visited.
Storage::Scan { path, len } => {
crate::progress::begin(usize::try_from(matched).unwrap_or(usize::MAX));
let hit = |id: u32| usize::try_from(id / 64).ok().and_then(|w| hits.get(w)).is_some_and(|w| w & (1u64 << (id % 64)) != 0);
scan_for(path, *len, false, |id, place, _| if hit(id) { visit(id, place) } else { Ok(()) })?;
Ok((matched, true))
}
}
}
pub fn visit(&self, extent: Option<[f32; 4]>, limit: usize, mut visit: impl FnMut(u32, Place) -> Result<()>) -> Result<(u64, bool)> {
match &self.storage {
Storage::Disk(disk) => disk.visit(extent, limit, visit),
Expand Down
Loading
Loading