You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@sedona.apache.org by "2010YOUY01 (via GitHub)" <gi...@apache.org> on 2026/02/06 10:27:48 UTC

[PR] feat(rust/sedona-geoparquet): Support WKB validation in `read_parquet()` [sedona-db]

2010YOUY01 opened a new pull request, #578:
URL: https://github.com/apache/sedona-db/pull/578

   Follow up to https://github.com/apache/sedona-db/pull/560
   
   ## Rationale
   
   `read_parquet()` now supports an override option, `geometry_columns`, to cast Binary columns to geometries. This is an unsafe operation, so adding a validation step is helpful.
   
   This PR currently limits validation to WKB validity. In the long term, additional metadata properties can also be validated. If any entry fails validation, an error will be returned.
   
   Geo columns are inferred from {(Geo)Parquet metadata, user-provided `geometry_columns` override options}. The `validate` option applies uniformly in all cases—if `validate = true`, geometry columns are always validated. I think this approach is more general and simpler.
   
   ## Implementation
   
   Propagate the `validate` option to `GeoParquetFileOpener` (which yields the final decoded batches as the data source output), and use it to optionally validate the decoded batches for WKB validity.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(rust/sedona-geoparquet): Support WKB validation in `read_parquet()` [sedona-db]

Posted by "2010YOUY01 (via GitHub)" <gi...@apache.org>.
2010YOUY01 commented on code in PR #578:
URL: https://github.com/apache/sedona-db/pull/578#discussion_r2773421391


##########
rust/sedona-geoparquet/src/file_opener.rs:
##########
@@ -98,11 +106,11 @@ pub(crate) struct GeoParquetFileOpener {
     pub inner: Arc<dyn FileOpener>,
     pub object_store: Arc<dyn ObjectStore>,
     pub metadata_size_hint: Option<usize>,
-    pub predicate: Arc<dyn PhysicalExpr>,
+    pub predicate: Option<Arc<dyn PhysicalExpr>>,
     pub file_schema: SchemaRef,
     pub enable_pruning: bool,
     pub metrics: GeoParquetFileOpenerMetrics,
-    pub overrides: Option<HashMap<String, GeoParquetColumnMetadata>>,
+    pub options: TableGeoParquetOptions,

Review Comment:
   refactor 2: before `overrides` lives inside `TableGeoParquetOptions`, the new `validate` flag also lives inside that option, so I think only keeping the option here can make it simpler.



##########
rust/sedona-geoparquet/src/format.rs:
##########
@@ -361,7 +362,7 @@ pub struct GeoParquetFileSource {
     inner: ParquetSource,
     metadata_size_hint: Option<usize>,
     predicate: Option<Arc<dyn PhysicalExpr>>,
-    overrides: Option<HashMap<String, GeoParquetColumnMetadata>>,
+    options: TableGeoParquetOptions,

Review Comment:
   refactor 3: similar to another refactor in `file_opener.rs`



##########
rust/sedona-geoparquet/src/file_opener.rs:
##########
@@ -98,11 +106,11 @@ pub(crate) struct GeoParquetFileOpener {
     pub inner: Arc<dyn FileOpener>,
     pub object_store: Arc<dyn ObjectStore>,
     pub metadata_size_hint: Option<usize>,
-    pub predicate: Arc<dyn PhysicalExpr>,
+    pub predicate: Option<Arc<dyn PhysicalExpr>>,

Review Comment:
   refactor 1: before it's required since `GeoParquetFileOpener` is only used when there is geo column, and also there is valid spatial predicate, otherwise it fall back to inner parquet opener.
   
   Now it also have to be used if validation is enabled, and there is no spatial predicate, so making it optional.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(rust/sedona-geoparquet): Support WKB validation in `read_parquet()` [sedona-db]

Posted by "2010YOUY01 (via GitHub)" <gi...@apache.org>.
2010YOUY01 commented on code in PR #578:
URL: https://github.com/apache/sedona-db/pull/578#discussion_r2778495539


##########
python/sedonadb/tests/test_context.py:
##########
@@ -313,3 +313,79 @@ def test_read_parquet_invalid_azure_option():
         match="Unknown Azure option.*azure.unknown_option.*Valid options are",
     ):
         con.read_parquet(url, options={"azure.unknown_option": "value"})
+
+
+def test_read_parquet_validate_wkb_single_valid_row(con, tmp_path):
+    valid_wkb = bytes.fromhex("0101000000000000000000F03F0000000000000040")
+
+    table = pa.table({"id": [1], "geom": [valid_wkb]})
+    path = tmp_path / "single_valid_wkb.parquet"
+    pq.write_table(table, path)

Review Comment:
   updated in 99d52a2



##########
rust/sedona-geoparquet/src/file_opener.rs:
##########
@@ -158,12 +170,108 @@ impl FileOpener for GeoParquetFileOpener {
             // We could also consider filtering using null_count here in the future (i.e.,
             // skip row groups that are all null)
             let file = file.with_extensions(Arc::new(access_plan));
+            let stream = self_clone.inner.open(file)?.await?;
+
+            // Validate geometry columns when enabled from read option.
+            let validation_columns = if self_clone.options.validate {
+                maybe_geoparquet_metadata
+                    .as_ref()
+                    .map(|metadata| wkb_validation_columns(&self_clone.file_schema, metadata))
+                    .unwrap_or_default()
+            } else {
+                Vec::new()
+            };
 
-            self_clone.inner.open(file)?.await
+            if !self_clone.options.validate || validation_columns.is_empty() {
+                return Ok(stream);
+            }
+
+            let validated_stream = stream.map(move |batch_result| {
+                let batch = batch_result?;
+                validate_wkb_batch(&batch, &validation_columns)?;
+                Ok(batch)
+            });
+
+            Ok(Box::pin(validated_stream))
         }))
     }
 }
 
+fn wkb_validation_columns(
+    file_schema: &SchemaRef,
+    metadata: &GeoParquetMetadata,
+) -> Vec<(usize, String)> {
+    file_schema
+        .fields()
+        .iter()
+        .enumerate()
+        .filter_map(|(column_index, field)| {
+            metadata
+                .columns
+                .get(field.name())
+                .and_then(|column_metadata| {
+                    if matches!(column_metadata.encoding, GeoParquetColumnEncoding::WKB) {
+                        Some((column_index, field.name().clone()))
+                    } else {
+                        None
+                    }
+                })
+        })
+        .collect()
+}
+
+fn validate_wkb_batch(batch: &RecordBatch, validation_columns: &[(usize, String)]) -> Result<()> {
+    for (column_index, column_name) in validation_columns {
+        let column = batch.column(*column_index);
+        validate_wkb_array(column.as_ref(), column_name)?;
+    }
+    Ok(())
+}
+
+fn validate_wkb_array(array: &dyn Array, column_name: &str) -> Result<()> {
+    match array.data_type() {
+        DataType::Binary => {
+            let array = as_binary_array(array)?;
+            for (row_index, maybe_wkb) in array.iter().enumerate() {
+                if let Some(wkb_bytes) = maybe_wkb {
+                    if let Err(e) = wkb::reader::read_wkb(wkb_bytes) {
+                        return exec_err!(
+                            "WKB validation failed for column '{}' at row {}: {}",
+                            column_name,
+                            row_index,
+                            e
+                        );
+                    }
+                }
+            }
+        }

Review Comment:
   fixed in  99d52a2



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(rust/sedona-geoparquet): Support WKB validation in `read_parquet()` [sedona-db]

Posted by "paleolimbot (via GitHub)" <gi...@apache.org>.
paleolimbot commented on code in PR #578:
URL: https://github.com/apache/sedona-db/pull/578#discussion_r2776190324


##########
python/sedonadb/tests/test_context.py:
##########
@@ -313,3 +313,79 @@ def test_read_parquet_invalid_azure_option():
         match="Unknown Azure option.*azure.unknown_option.*Valid options are",
     ):
         con.read_parquet(url, options={"azure.unknown_option": "value"})
+
+
+def test_read_parquet_validate_wkb_single_valid_row(con, tmp_path):
+    valid_wkb = bytes.fromhex("0101000000000000000000F03F0000000000000040")
+
+    table = pa.table({"id": [1], "geom": [valid_wkb]})
+    path = tmp_path / "single_valid_wkb.parquet"
+    pq.write_table(table, path)

Review Comment:
   Optional, but there is a io/test_parquet.py that is possibly a better fit for these tests (and the geometry_columns tests) since there are now a lot of them!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(rust/sedona-geoparquet): Support WKB validation in `read_parquet()` [sedona-db]

Posted by "paleolimbot (via GitHub)" <gi...@apache.org>.
paleolimbot merged PR #578:
URL: https://github.com/apache/sedona-db/pull/578


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(rust/sedona-geoparquet): Support WKB validation in `read_parquet()` [sedona-db]

Posted by "paleolimbot (via GitHub)" <gi...@apache.org>.
paleolimbot commented on code in PR #578:
URL: https://github.com/apache/sedona-db/pull/578#discussion_r2776196192


##########
python/sedonadb/python/sedonadb/context.py:
##########
@@ -176,9 +177,18 @@ def read_parquet(
 
 
                 Safety:
-                - Columns specified here are not validated against the provided options
-                  (e.g., WKB encoding checks); inconsistent data may cause undefined
-                  behavior.
+                - Columns specified here can optionally be validated according to the
+                  `validate` option (e.g., WKB encoding checks). If validation is not
+                  enabled, inconsistent data may cause undefined behavior.
+            validate:
+                When set to `True`, geometry column contents are validated against
+                their metadata. Metadata can come from the source Parquet file or
+                the user-provided `geometry_columns` option.
+                Only supported properties are validated; unsupported properties are
+                ignored. If validation fails, execution stops with an error.
+
+                Supported validation properties:
+                - WKB encoding

Review Comment:
   ```suggestion
                   Currently the only property that is validated is the WKB of input geometry
                   columns.
   ```



##########
rust/sedona-geoparquet/src/file_opener.rs:
##########
@@ -158,12 +170,108 @@ impl FileOpener for GeoParquetFileOpener {
             // We could also consider filtering using null_count here in the future (i.e.,
             // skip row groups that are all null)
             let file = file.with_extensions(Arc::new(access_plan));
+            let stream = self_clone.inner.open(file)?.await?;
+
+            // Validate geometry columns when enabled from read option.
+            let validation_columns = if self_clone.options.validate {
+                maybe_geoparquet_metadata
+                    .as_ref()
+                    .map(|metadata| wkb_validation_columns(&self_clone.file_schema, metadata))
+                    .unwrap_or_default()
+            } else {
+                Vec::new()
+            };
 
-            self_clone.inner.open(file)?.await
+            if !self_clone.options.validate || validation_columns.is_empty() {
+                return Ok(stream);
+            }
+
+            let validated_stream = stream.map(move |batch_result| {
+                let batch = batch_result?;
+                validate_wkb_batch(&batch, &validation_columns)?;
+                Ok(batch)
+            });
+
+            Ok(Box::pin(validated_stream))
         }))
     }
 }
 
+fn wkb_validation_columns(
+    file_schema: &SchemaRef,
+    metadata: &GeoParquetMetadata,
+) -> Vec<(usize, String)> {
+    file_schema
+        .fields()
+        .iter()
+        .enumerate()
+        .filter_map(|(column_index, field)| {
+            metadata
+                .columns
+                .get(field.name())
+                .and_then(|column_metadata| {
+                    if matches!(column_metadata.encoding, GeoParquetColumnEncoding::WKB) {
+                        Some((column_index, field.name().clone()))
+                    } else {
+                        None
+                    }
+                })
+        })
+        .collect()
+}
+
+fn validate_wkb_batch(batch: &RecordBatch, validation_columns: &[(usize, String)]) -> Result<()> {
+    for (column_index, column_name) in validation_columns {
+        let column = batch.column(*column_index);
+        validate_wkb_array(column.as_ref(), column_name)?;
+    }
+    Ok(())
+}
+
+fn validate_wkb_array(array: &dyn Array, column_name: &str) -> Result<()> {
+    match array.data_type() {
+        DataType::Binary => {
+            let array = as_binary_array(array)?;
+            for (row_index, maybe_wkb) in array.iter().enumerate() {
+                if let Some(wkb_bytes) = maybe_wkb {
+                    if let Err(e) = wkb::reader::read_wkb(wkb_bytes) {
+                        return exec_err!(
+                            "WKB validation failed for column '{}' at row {}: {}",
+                            column_name,
+                            row_index,
+                            e
+                        );
+                    }
+                }
+            }
+        }

Review Comment:
   While we're here, it would be good to handle the `LargeBinary` case (this can happen for reasons outside a GeoParquet producer's control due to various auto-store/load of schemas)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(rust/sedona-geoparquet): Support WKB validation in `read_parquet()` [sedona-db]

Posted by "2010YOUY01 (via GitHub)" <gi...@apache.org>.
2010YOUY01 commented on PR #578:
URL: https://github.com/apache/sedona-db/pull/578#issuecomment-3866102343

   > A few optional things to consider...thank you!
   > 
   > Just curious...have you run into files where this is a problem? I imagine if it does happen the existing error would be rather cryptic (although I believe we're good about validating WKB payload in every operator).
   
   Thank you for the review! I have not encountered corrupted file so far, but my concern is the same: if this error is caught inside operators, the error might get propagated several times and produce confusing error messages.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org