From f6cabf959c73595840671f32f90f93eb9f329cae Mon Sep 17 00:00:00 2001 From: JosiahParry Date: Thu, 10 Sep 2026 19:16:03 -0700 Subject: [PATCH] fix: honour the vctr selection in GeoArrowVctr chunk accessors A nanoarrow_vctr is an integer vector of 1 based rows into its chunks, and slicing one in R usually narrows those integers while leaving the chunks whole. iter_arrow() read only the chunks, so a slice was silently ignored: as_point_chunks() on a 3 row slice of a 100 row column returned all 100. Rows are now selected in the order the vctr gives them, with NA read as a null element. The unsliced case still returns the chunks untouched and a contiguous run is a zero copy slice, so neither pays for the fix. Claude-Session: https://claude.ai/code/session_01BcijTjvRjrx9ETvZtpHSBR --- CHANGELOG.md | 6 ++ Cargo.lock | 2 +- Cargo.toml | 2 +- src/geoarrow/mod.rs | 139 ++++++++++++++++++++++++++++++++++++++++++-- tests/geoarrow.rs | 108 ++++++++++++++++++++++++++++++++++ 5 files changed, 251 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bb6616f..03a2bf6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +## 58.1.1 + +### Bug fixes + +- `GeoArrowVctr`'s chunk accessors now honour the vctr's selection. A `nanoarrow_vctr` is an integer vector of 1 based rows into its chunks, and slicing one in R usually narrows those integers while leaving the chunks whole. The accessors read only the chunks, so a slice was silently ignored and the caller got every row: `as_point_chunks()` on a 3 row slice of a 100 row column returned all 100. Rows are now selected in the order the vctr gives them, with `NA` read as a null element. A contiguous run is a zero copy slice and the unsliced case still returns the chunks untouched, so neither pays for the fix. + ## 58.1.0 ### New features diff --git a/Cargo.lock b/Cargo.lock index 264e937..f2290a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -301,7 +301,7 @@ dependencies = [ [[package]] name = "arrow_extendr" -version = "58.1.0" +version = "58.1.1" dependencies = [ "anyhow", "arrow", diff --git a/Cargo.toml b/Cargo.toml index 736deec..c7f2cc4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "arrow_extendr" -version = "58.1.0" +version = "58.1.1" edition = "2024" # matches arrow rust-version = "1.85.0" diff --git a/src/geoarrow/mod.rs b/src/geoarrow/mod.rs index 643cc98..8cb2426 100644 --- a/src/geoarrow/mod.rs +++ b/src/geoarrow/mod.rs @@ -51,7 +51,8 @@ use std::sync::Arc; use anyhow::{anyhow, bail}; use arrow::{ - array::{Array, make_array}, + array::{Array, UInt32Array, make_array}, + compute::take, datatypes::Field, ffi::{self, FFI_ArrowSchema}, }; @@ -174,6 +175,12 @@ impl_to_arrow_robj_geoarrow!( /// with a list of `chunks` where each is its own geoarrow array /// the `schema` is stored in the attribute `schema` /// classes are: "geoarrow_vctr" "nanoarrow_vctr" +/// +/// The integer vector itself is the selection: each element is a 1 based row +/// into the chunks laid end to end, and `NA` is a null element. The `offsets` +/// attribute says where each chunk starts in that run. Slicing a vctr in R +/// usually narrows the integers and leaves the chunks whole, so the chunk +/// accessors apply the selection rather than returning the chunks as they are. pub struct GeoArrowVctr(Integers); impl TryFrom<&Robj> for GeoArrowVctr { @@ -215,18 +222,142 @@ impl GeoArrowVctr { .ok_or_else(|| anyhow!("`schema` attribute missing")) } + /// Where each chunk starts among the rows the index vector addresses. + fn offsets(&self) -> anyhow::Result> { + let attr = self + .0 + .get_attrib("offsets") + .ok_or_else(|| anyhow!("`offsets` attribute missing"))?; + let offsets = Integers::try_from(attr).map_err(|e| anyhow!("{e}"))?; + offsets + .iter() + .map(|o| { + Option::::from(o) + .filter(|v| *v >= 0) + .map(|v| v as usize) + .ok_or_else(|| anyhow!("`offsets` must hold no NA or negative value")) + }) + .collect() + } + + /// Which chunk a 1 based row falls in, or `None` when the row is `NA`. + fn chunk_of( + offsets: &[usize], + row: Option, + total: usize, + ) -> anyhow::Result> { + let Some(row) = row else { + return Ok(None); + }; + if row < 1 || row as usize > total { + bail!("row {row} is out of bounds for a vctr of {total} rows"); + } + // partition_point rather than binary_search, so a zero length chunk is skipped + Ok(Some(offsets.partition_point(|&o| o < row as usize) - 1)) + } + + /// Pull one run of rows, all in the same chunk or all `NA`, out as a single array. + fn gather( + chunks: &[Arc], + offsets: &[usize], + chunk: Option, + rows: &[Option], + ) -> anyhow::Result> { + let Some(chunk) = chunk else { + // an NA row is a null element, which a null index makes for any type + let nulls = UInt32Array::from(vec![None; rows.len()]); + return Ok(take(chunks[0].as_ref(), &nulls, None)?); + }; + + let base = offsets[chunk]; + let positions = rows + .iter() + .filter_map(|row| *row) + .map(|row| (row as usize - 1 - base) as u32) + .collect::>(); + + // a contiguous ascending run is a slice, which copies nothing + if positions.windows(2).all(|w| w[1] == w[0] + 1) { + if let Some(first) = positions.first().copied() { + return Ok(chunks[chunk].slice(first as usize, positions.len())); + } + } + + let idx = UInt32Array::from(positions); + Ok(take(chunks[chunk].as_ref(), &idx, None)?) + } + + /// Narrow the chunks to the rows the vctr selects, in the order it selects them. + fn select(&self, chunks: Vec>) -> anyhow::Result>> { + let offsets = self.offsets()?; + if offsets.len() != chunks.len() + 1 { + bail!( + "`offsets` has {} entries for {} chunks, expected {}", + offsets.len(), + chunks.len(), + chunks.len() + 1 + ); + } + if offsets[0] != 0 { + bail!("`offsets` must start at 0, got {}", offsets[0]); + } + + let total = offsets[chunks.len()]; + let rows = self.0.iter().map(Option::::from).collect::>(); + + // the whole vctr in order, where the chunks already are the answer + if rows.len() == total + && rows + .iter() + .enumerate() + .all(|(i, row)| *row == Some(i as i32 + 1)) + { + return Ok(chunks); + } + + if chunks.is_empty() { + return Ok(chunks); + } + + let mut out = Vec::new(); + let mut start = 0; + while start < rows.len() { + let here = Self::chunk_of(&offsets, rows[start], total)?; + let mut end = start + 1; + while end < rows.len() && Self::chunk_of(&offsets, rows[end], total)? == here { + end += 1; + } + out.push(Self::gather(&chunks, &offsets, here, &rows[start..end])?); + start = end; + } + + // an empty selection still needs a chunk to carry the type + if out.is_empty() { + out.push(chunks[0].slice(0, 0)); + } + + Ok(out) + } + fn iter_arrow(&self) -> anyhow::Result, Field)>> { let schema = self.schema()?; let ffi_schema = crate::nanoarrow::c_export_schema(&schema)?; let field = Field::try_from(ffi_schema)?; - self.chunks()? + let chunks = self + .chunks()? .iter() .map(|(_, chunk)| { let ffi_array = crate::nanoarrow::c_export_array(&chunk)?; let array_data = unsafe { ffi::from_ffi(ffi_array, ffi_schema)? }; - Ok((make_array(array_data), field.clone())) + Ok(make_array(array_data)) }) - .collect() + .collect::>>()?; + + Ok(self + .select(chunks)? + .into_iter() + .map(|array| (array, field.clone())) + .collect()) } pub fn as_point_chunks(&self) -> anyhow::Result> { diff --git a/tests/geoarrow.rs b/tests/geoarrow.rs index 3df485d..055b302 100644 --- a/tests/geoarrow.rs +++ b/tests/geoarrow.rs @@ -204,3 +204,111 @@ fn test_geoarrow_geometry_collection_roundtrip() -> anyhow::Result<()> { .map_err(|e| anyhow::anyhow!("{e}"))?; Ok(()) } + +/// The WKT of every row the chunks hold, laid end to end, as R sees it. +fn chunks_wkt(chunks: Vec) -> extendr_api::Result { + let parts = chunks + .into_iter() + .map(|chunk| chunk.into_arrow_robj()) + .collect::>>()?; + let list = extendr_api::prelude::List::from_values(parts); + R!("unlist(lapply({{list}}, function(a) geoarrow::geoarrow_handle(a, wk::wkt_writer())))") +} + +fn point_chunks_of(r_expr: &str) -> extendr_api::Result> { + let vctr = extendr_api::eval_string(r_expr)?; + arrow_extendr::geoarrow::GeoArrowVctr::try_from(&vctr) + .and_then(|v| v.as_point_chunks()) + .map_err(|e| extendr_api::Error::Other(e.to_string())) +} + +fn assert_wkt(r_expr: &str, expected: &str) -> anyhow::Result<()> { + with_r(|| { + let chunks = point_chunks_of(r_expr)?; + let got = chunks_wkt(chunks)?; + let report = format!("{got:?}"); + let expected_robj = extendr_api::eval_string(expected)?; + let same = R!("identical({{got}}, {{expected_robj}})")?; + assert!( + same.as_logical().map(|v| v.is_true()).unwrap_or(false), + "{r_expr} gave {report}, expected {expected}" + ); + Ok::<(), extendr_api::Error>(()) + }) + .map_err(|e| anyhow::anyhow!("{e}"))?; + Ok(()) +} + +const PTS: &str = "geoarrow::as_geoarrow_vctr(wk::xy(1:5, 6:10))"; + +#[test] +#[serial] +fn test_geoarrow_vctr_reads_every_row() -> anyhow::Result<()> { + assert_wkt( + PTS, + "c('POINT (1 6)', 'POINT (2 7)', 'POINT (3 8)', 'POINT (4 9)', 'POINT (5 10)')", + ) +} + +#[test] +#[serial] +fn test_geoarrow_vctr_respects_a_contiguous_slice() -> anyhow::Result<()> { + assert_wkt( + &format!("{PTS}[2:4]"), + "c('POINT (2 7)', 'POINT (3 8)', 'POINT (4 9)')", + ) +} + +#[test] +#[serial] +fn test_geoarrow_vctr_respects_a_single_row() -> anyhow::Result<()> { + assert_wkt(&format!("{PTS}[4]"), "'POINT (4 9)'") +} + +#[test] +#[serial] +fn test_geoarrow_vctr_respects_a_reordering() -> anyhow::Result<()> { + assert_wkt( + &format!("{PTS}[c(5L, 1L, 3L)]"), + "c('POINT (5 10)', 'POINT (1 6)', 'POINT (3 8)')", + ) +} + +#[test] +#[serial] +fn test_geoarrow_vctr_respects_a_repeat() -> anyhow::Result<()> { + assert_wkt( + &format!("{PTS}[c(2L, 2L)]"), + "c('POINT (2 7)', 'POINT (2 7)')", + ) +} + +#[test] +#[serial] +fn test_geoarrow_vctr_reads_na_as_a_null() -> anyhow::Result<()> { + assert_wkt(&format!("{PTS}[NA_integer_]"), "NA_character_") +} + +#[test] +#[serial] +fn test_geoarrow_vctr_reads_an_empty_selection() -> anyhow::Result<()> { + with_r(|| { + let chunks = point_chunks_of(&format!("{PTS}[0]"))?; + assert_eq!(chunks.iter().map(|c| c.len()).sum::(), 0); + // an empty selection still carries the type, so callers can read it + assert_eq!(chunks.len(), 1); + Ok::<(), extendr_api::Error>(()) + }) + .map_err(|e| anyhow::anyhow!("{e}"))?; + Ok(()) +} + +#[test] +#[serial] +fn test_geoarrow_vctr_slices_across_chunks() -> anyhow::Result<()> { + let two = format!("vctrs::vec_c({PTS}, {PTS})"); + assert_wkt( + &format!("{two}[4:7]"), + "c('POINT (4 9)', 'POINT (5 10)', 'POINT (1 6)', 'POINT (2 7)')", + ) +}