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
8 changes: 7 additions & 1 deletion crates/data/src/loss.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,12 @@ loss_codes! {
"A coordinate system's name or definition could not be written with the data, so the file holds the coordinates without it.",
"Keep the source file's coordinate system definition with the export, or export in WGS 84, which every format can name."
),
DroppedEpoch => (
"dropped.epoch",
Dropped,
"The date the coordinates are valid at (the coordinate epoch) was not kept, so positions are read as if the coordinate system did not change over time.",
"Keep the source file where the epoch matters, or convert the coordinates to a system that does not move with the ground before adding them."
),
DroppedFeature => (
"dropped.feature",
Dropped,
Expand Down Expand Up @@ -176,7 +182,7 @@ loss_codes! {
ApproximatedCurve => (
"approximated.curve",
Approximated,
"Curves, circles or rotated boxes were drawn or written as straight segments.",
"Curves, circles, rotated boxes or edges that follow the Earth's curve were read, drawn or written as straight segments.",
"Keep the source file where exact curves matter: RustGIS draws curves as straight segments."
),
AssumedNullMarker => (
Expand Down
4 changes: 4 additions & 0 deletions crates/data/src/source/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -818,6 +818,10 @@ pub type Queried = (Vec<crate::Field>, Batch);
fn query_now(file: &std::sync::Arc<remote::Remote>, columns: &[String], req: &Request) -> Result<Queried> {
let cols: Vec<&str> = columns.iter().map(String::as_str).collect();
let src = parquet::ParquetSource::open_remote(file.clone(), &url_name(file.url()))?.with_columns(&cols).exact();
// A caller takes the rows' places for longitude/latitude, and has no notices.
if let Some(why) = src.refusal() {

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.

Every projected GeoParquet is now refused by a catalog query, not only the rows that can't be placed. Before this PR, query_now read such a file and read already converted each row to longitude/latitude (place, parquet.rs around line 1014). A UTM file therefore returned its rows; now it fails with "its coordinates are in ..., not WGS 84 longitude/latitude". The test vectors_and_index_rows_by_address_keep_to_the_files_system asserts that refusal for EPSG:3857, so it looks deliberate, but the PR text gives no reason to refuse a projected file as a whole.

The silent loss this guards against is the rows place cannot place. Those are already counted in batch.skipped (parquet.rs line 1015). Refusing on that count keeps projected files working and still says what was dropped. Suggested change: drop the reprojection case from refusal() and, after the read, refuse when batch.skipped > 0 with the count.

Confidence: medium. I did not run the code. The refusal is intentional per the test, so the author may want to keep it. Please confirm.

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.

Kept: the refusal is needed. Reproject::place converts only the box it tests and returns the geometry as the file holds it (Fitted { geometry: g, inside }), so a UTM index would hand its metres to a caller that takes them for longitude/latitude (found in tiles/embeddings.rs uses them for footprints and distances). The result carries no system to convert by. Refusing on skipped wouldn't catch it, because those rows are placed and matched.

return Err(DataError::Format(format!("GeoParquet: {why}")));
}
let batch = src.read(req)?;
Ok((src.info().fields.clone(), batch))
}
Expand Down
269 changes: 205 additions & 64 deletions crates/data/src/source/parquet.rs

Large diffs are not rendered by default.

897 changes: 897 additions & 0 deletions crates/data/src/source/parquet/declared.rs

Large diffs are not rendered by default.

166 changes: 158 additions & 8 deletions crates/data/src/source/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3528,17 +3528,26 @@ fn a_csv_export_takes_x_and_y_in_a_system_asked_for() {
}

/// A catalog index as AlphaEarth's is (a `bbox` struct, a nested `assets.data.href`), and patch
/// embeddings as Earth Index's are (a fixed-size list of floats a point), in row groups of 50.
fn write_index_and_vectors() -> Vec<u8> {
/// embeddings as Earth Index's are (a fixed-size list of floats a point), in row groups of 50, with
/// `geo` metadata.
fn write_index_and_vectors(geo: &str, native: Option<::parquet::basic::LogicalType>) -> Vec<u8> {
write_index_and_vectors_with(geo, native, |_| {})
}

/// As [`write_index_and_vectors`], with the first point's WKB changed.
fn write_index_and_vectors_with(geo: &str, native: Option<::parquet::basic::LogicalType>, first: impl FnOnce(&mut Vec<u8>)) -> Vec<u8> {
use arrow_array::builder::{FixedSizeListBuilder, Float32Builder};
use arrow_array::{BinaryArray, Float64Array, RecordBatch, StringArray, StructArray};
use arrow_schema::{DataType, Field as AField, Fields, Schema};
let pts = points();
let wkbs: Vec<Vec<u8>> = pts.iter().map(|(c, ..)| wkb::encode(&Geometry::Point(*c))).collect();
let mut wkbs: Vec<Vec<u8>> = pts.iter().map(|(c, ..)| wkb::encode(&Geometry::Point(*c))).collect();
first(&mut wkbs[0]);
let bbox_fields: Fields =
["xmin", "ymin", "xmax", "ymax"].map(|n| Arc::new(AField::new(n, DataType::Float64, false))).into_iter().collect();
let coord =
|f: fn(&Coord) -> f64| Arc::new(Float64Array::from(pts.iter().map(|(c, ..)| f(c)).collect::<Vec<_>>())) as arrow_array::ArrayRef;
let coord = |f: fn(&Coord) -> f64| {
Arc::new(Float64Array::from(pts.iter().map(|(c, ..)| f(c) * if geo.contains("metres") { 1e5 } else { 1.0 }).collect::<Vec<_>>()))

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 helper chooses the fixture's coordinate scale and whether statistics are written by searching the geo JSON text for the words "metres" and "no-statistics". Those words are meant as labels, but any future geo string that contains them silently changes the fixture's data or statistics, which makes a failing test hard to trace. Passing the two settings as explicit arguments (a bool each, or a small enum) keeps each call site's behaviour visible.

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: a test helper's arguments.

as arrow_array::ArrayRef
};
let bbox = StructArray::new(bbox_fields.clone(), vec![coord(|c| c.x), coord(|c| c.y), coord(|c| c.x), coord(|c| c.y)], None);
let href =
Arc::new(StringArray::from(pts.iter().map(|p| format!("s3://bucket/{}.tiff", p.1)).collect::<Vec<_>>())) as arrow_array::ArrayRef;
Expand Down Expand Up @@ -3566,21 +3575,43 @@ fn write_index_and_vectors() -> Vec<u8> {
Arc::new(assets),
Arc::new(emb),
];
let geo = r#"{"version":"1.0.0","primary_column":"geometry","columns":{"geometry":{"encoding":"WKB","geometry_types":["Point"]}}}"#;
let props = ::parquet::file::properties::WriterProperties::builder()
.set_max_row_group_row_count(Some(50))
.set_statistics_enabled(if geo.contains("no-statistics") {
::parquet::file::properties::EnabledStatistics::None
} else {
::parquet::file::properties::EnabledStatistics::Chunk
})
.set_key_value_metadata(Some(vec![::parquet::file::metadata::KeyValue::new("geo".to_string(), geo.to_string())]))
.build();
let mut out = Vec::new();
let mut w = ::parquet::arrow::ArrowWriter::try_new(&mut out, schema.clone(), Some(props)).unwrap();
// The arrow writer gives a geometry column no native type, so it is put in the schema.
let parquet_schema = ::parquet::arrow::ArrowSchemaConverter::new().convert(&schema).unwrap();
let fields = parquet_schema.root_schema().get_fields().iter().map(|f| match native.clone().filter(|_| f.name() == "geometry") {
Some(ty) => Arc::new(
::parquet::schema::types::Type::primitive_type_builder("geometry", ::parquet::basic::Type::BYTE_ARRAY)
.with_repetition(::parquet::basic::Repetition::REQUIRED)
.with_logical_type(Some(ty))
.build()
.unwrap(),
),
None => f.clone(),
});
let root = ::parquet::schema::types::Type::group_type_builder("schema").with_fields(fields.collect()).build().unwrap();
let described = ::parquet::schema::types::SchemaDescriptor::new(Arc::new(root));
let options = ::parquet::arrow::arrow_writer::ArrowWriterOptions::new().with_properties(props).with_parquet_schema(described);
let mut w = ::parquet::arrow::ArrowWriter::try_new_with_options(&mut out, schema.clone(), options).unwrap();
w.write(&RecordBatch::try_new(schema, cols).unwrap()).unwrap();
w.close().unwrap();
out
}

#[test]
fn nested_columns_and_vectors_by_address() {
let bytes = write_index_and_vectors();
let bytes = write_index_and_vectors(
r#"{"version":"1.0.0","primary_column":"geometry","columns":{"geometry":{"encoding":"WKB","geometry_types":["Point"]}}}"#,
None,
);
let url = "https://test.example/index.parquet";
remote::testing::serve(url, bytes.clone());
let e = Extent::new(10.0, 10.0, 40.0, 30.0);
Expand Down Expand Up @@ -3614,6 +3645,121 @@ fn nested_columns_and_vectors_by_address() {
}
}

/// Points and rows found by place are in the file's own system, and refused when the file doesn't
/// say it.
#[test]
fn vectors_and_index_rows_by_address_keep_to_the_files_system() {
let geo = |crs: &str| {
format!(
r#"{{"version":"2.0.0","primary_column":"geometry","columns":{{"geometry":{{"encoding":"WKB","geometry_types":["Point"],"crs":{crs}}}}}}}"#
)
};
// Degrees' numbers as metres: all of them within a few metres of 0, 0.
let mercator = "https://test.example/mercator.parquet";
remote::testing::serve(mercator, write_index_and_vectors(&geo(r#"{"id":{"authority":"EPSG","code":3857}}"#), None));
let near = Extent::new(-0.01, -0.01, 0.01, 0.01);
let v = vectors_url_blocking(mercator, near, "embedding".into(), (100, 10_000)).unwrap();
assert_eq!(v.points.len(), points().len());
assert!(v.points.iter().all(|(x, y)| near.contains(Coord::new(*x, *y))));
let far = Extent::new(10.0, 10.0, 40.0, 30.0);
assert!(vectors_url_blocking(mercator, far, "embedding".into(), (100, 10_000)).unwrap().points.is_empty());
let refused = query_url_blocking(mercator, vec![], Request { extent: Some(near), limit: 10, own: None }).unwrap_err().to_string();
assert!(refused.contains("not WGS 84 longitude/latitude"), "{refused}");
for (name, more, why) in [
("nad27", r#"{"id":{"authority":"OGC","code":"CRS27"}}"#, "not WGS 84"),
("zm", r#"{"id":{"authority":"EPSG","code":4326}},"bbox":[0,0,0,1,1,1]"#, "Z"),
] {
let url = format!("https://test.example/{name}.parquet");
remote::testing::serve(&url, write_index_and_vectors(&geo(more), None));
let refused = query_url_blocking(&url, vec![], Request { extent: Some(far), limit: 10, own: None }).unwrap_err().to_string();
assert!(refused.contains(why), "{refused}");
}
let dated = "https://test.example/dated.parquet";
remote::testing::serve(dated, write_index_and_vectors(&geo(r#"{"id":{"authority":"EPSG","code":4326}},"epoch":2021.5"#), None));
let refused = query_url_blocking(dated, vec![], Request { extent: Some(far), limit: 10, own: None }).unwrap_err().to_string();
assert!(refused.contains("epoch"), "{refused}");
let unknown = "https://test.example/unknown.parquet";
remote::testing::serve(unknown, write_index_and_vectors(&geo("null"), None));
// Geography points have no edges to approximate, and a native type gives the system.
let native = |crs: &str| Some(::parquet::basic::LogicalType::geography(Some(crs.into()), None));
let geography = "https://test.example/geography.parquet";
remote::testing::serve(geography, write_index_and_vectors("{}", native("OGC:CRS84")));
assert_eq!(vectors_url_blocking(geography, far, "embedding".into(), (100, 10_000)).unwrap().points.len(), in_box(&far));
let native_mercator = "https://test.example/native-mercator.parquet";
remote::testing::serve(
native_mercator,
write_index_and_vectors("{}", Some(::parquet::basic::LogicalType::geometry(Some("EPSG:3857".into())))),
);
assert_eq!(vectors_url_blocking(native_mercator, near, "embedding".into(), (100, 10_000)).unwrap().points.len(), points().len());
// A point with a height, and one with no place, are refused rather than lost without a word.
let wgs84 = geo(r#"{"id":{"authority":"EPSG","code":4326}}"#);
let height = "https://test.example/height.parquet";
let with_z = |b: &mut Vec<u8>| {
// The ISO code of a Point Z, and its Z after x and y.
b[1..5].copy_from_slice(&1001u32.to_le_bytes());
b.extend(5f64.to_le_bytes());
};
remote::testing::serve(height, write_index_and_vectors_with(&wgs84, None, with_z));
let refused = vectors_url_blocking(height, far, "embedding".into(), (100, 10_000)).err().unwrap().to_string();
assert!(refused.contains("1 of its points have Z or M values"), "{refused}");
let refused = query_url_blocking(height, vec![], Request { extent: None, limit: 1000, own: None }).unwrap_err().to_string();
assert!(refused.contains("Z or M"), "{refused}");
// Points of a geography have no edges to say anything of; a line has.
assert_eq!(
query_url_blocking(geography, vec![], Request { extent: Some(far), limit: 1000, own: None }).unwrap().1.features.len(),
in_box(&far)
);
let curved = "https://test.example/curved.parquet";
let line = |b: &mut Vec<u8>| *b = wkb::encode(&Geometry::Line(vec![vec![Coord::new(0.0, 0.0), Coord::new(1.0, 1.0)]]));
remote::testing::serve(curved, write_index_and_vectors_with("{}", native("OGC:CRS84"), line));
let refused = query_url_blocking(curved, vec![], Request { extent: None, limit: 1000, own: None }).unwrap_err().to_string();
assert!(refused.contains("straight lines"), "{refused}");
let refused = vectors_url_blocking(curved, far, "embedding".into(), (100, 10_000)).err().unwrap().to_string();
assert!(refused.contains("1 of its geometries aren't single points"), "{refused}");
let lost = "https://test.example/lost.parquet";
let nowhere = |b: &mut Vec<u8>| b[5..13].copy_from_slice(&f64::INFINITY.to_le_bytes());
// Boxes in metres with no statistics to say so as the file opens, and the same in degrees.
for (writer, refused) in [("no-statistics metres", true), ("no-statistics", false)] {
let url = format!("https://test.example/{}.parquet", writer.replace(' ', "-"));
let more = format!(r#"{{"id":{{"authority":"EPSG","code":4326}}}},"writer":"{writer}""#);
remote::testing::serve(&url, write_index_and_vectors(&geo(&more), None));
let read = query_url_blocking(&url, vec![], Request { extent: Some(far), limit: 1000, own: None });
match refused {
true => assert!(read.unwrap_err().to_string().contains("not longitude/latitude")),
false => assert_eq!(read.unwrap().1.features.len(), in_box(&far)),
}
}
let east = "https://test.example/one-point-in-metres.parquet";
let beyond = |b: &mut Vec<u8>| b[5..13].copy_from_slice(&500_000f64.to_le_bytes());
remote::testing::serve(east, write_index_and_vectors_with(&geo(r#"{"id":{"authority":"EPSG","code":4326}}"#), None, beyond));
let refused = query_url_blocking(east, vec![], Request { extent: None, limit: 1000, own: None }).unwrap_err().to_string();
assert!(refused.contains("not longitude/latitude"), "{refused}");
// A box beyond degrees in a file that says it is in degrees.
let metres = "https://test.example/metres.parquet";
let bounded = geo(r#"{"id":{"authority":"EPSG","code":4326}},"bbox":[222146,3893937,222147,3893938]"#);
remote::testing::serve(metres, write_index_and_vectors(&bounded, None));
let refused = query_url_blocking(metres, vec![], Request { extent: Some(far), limit: 10, own: None }).unwrap_err().to_string();
assert!(refused.contains("not longitude/latitude"), "{refused}");
let polar = "https://test.example/beyond-the-pole.parquet";
let beyond = |b: &mut Vec<u8>| b[13..21].copy_from_slice(&95f64.to_le_bytes());
remote::testing::serve(polar, write_index_and_vectors_with(&wgs84, None, beyond));
let east = "https://test.example/beyond-the-edge.parquet";
let beyond = |b: &mut Vec<u8>| b[5..13].copy_from_slice(&500_000f64.to_le_bytes());
remote::testing::serve(east, write_index_and_vectors_with(&wgs84, None, beyond));
let refused = vectors_url_blocking(east, far, "embedding".into(), (100, 10_000)).err().unwrap().to_string();
assert!(refused.contains("1 of its rows have no place"), "{refused}");
let refused = vectors_url_blocking(polar, far, "embedding".into(), (100, 10_000)).err().unwrap().to_string();
assert!(refused.contains("1 of its rows have no place"), "{refused}");
let utm = geo(r#"{"id":{"authority":"EPSG","code":32616}}"#);
remote::testing::serve(lost, write_index_and_vectors_with(&utm, None, nowhere));
let refused = vectors_url_blocking(lost, far, "embedding".into(), (100, 10_000)).err().unwrap().to_string();
assert!(refused.contains("1 of its rows have no place"), "{refused}");
let refused = vectors_url_blocking(unknown, far, "embedding".into(), (100, 10_000)).err().unwrap().to_string();
assert!(refused.contains("coordinate system is unknown"), "{refused}");
let refused = query_url_blocking(unknown, vec![], Request { extent: Some(far), limit: 10, own: None }).unwrap_err().to_string();
assert!(refused.contains("coordinate system is unknown"), "{refused}");
}

#[test]
fn shapefile_complete_chunks_keep_all_rows_order_attributes_and_budget() {
let dir = tempfile::tempdir().unwrap();
Expand Down Expand Up @@ -3827,6 +3973,10 @@ fn geopackage_flatgeobuf_and_geoparquet_visit_what_a_whole_read_gives() {
let error = capped.visit_chunks(None, 4096, &mut |_| Ok(())).unwrap_err().to_string();
assert!(error.contains("row group 0 has 50 rows, more than the 40"), "{error}");
// A capped row group outside the extent is passed over, not refused.
// A catalog's read refuses the group, whichever of its rows would match.
let exact = parquet::ParquetSource::open_path(&pq, "grid").unwrap().with_group_rows(40).exact();
let world = Request { extent: Some(Extent::new(-180.0, -90.0, 180.0, 90.0)), limit: 1000, own: None };
assert!(exact.read(&world).unwrap_err().to_string().contains("more than the 40 read from one"));
let capped = parquet::ParquetSource::open_path(&pq, "grid").unwrap().with_group_rows(40);
assert!(visit_all(&capped, Some(Extent::new(178.0, 0.0, 179.0, 1.0)), 4096).0.is_empty());
// A GeoPackage put in place of the one added is refused, not read as the layer.
Expand Down
Loading
Loading