From f8405dd6c1da763d9aded9efbca6ed56ef9809d5 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Wed, 7 Oct 2026 00:07:36 +0000 Subject: [PATCH 1/8] feat(bindings): expose geospatial result representation Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- CONNECTION_PARAMETERS.md | 11 +++- NEXT_CHANGELOG.md | 5 ++ include/databricks_kernel.h | 12 ++++ napi/NEXT_CHANGELOG.md | 3 + napi/index.d.ts | 8 +++ napi/src/database.rs | 39 +++++++++++- pyo3/NEXT_CHANGELOG.md | 3 + pyo3/src/session.rs | 77 ++++++++++++++++++----- src/c_abi/session.rs | 79 +++++++++++++++++++++++- src/config.rs | 17 +++-- src/metadata/type_mapping.rs | 13 ++-- src/reader/post_processor/mod.rs | 12 ++-- tests/c/session_smoke.c | 17 +++++ tests/v0_c_abi_result_config_wiremock.rs | 53 ++++++++++++++-- tests/v0_execute_wiremock.rs | 13 ++-- tests/v0_session_wiremock.rs | 14 ++--- 16 files changed, 322 insertions(+), 54 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index b4dc22be..dfd528ae 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -185,8 +185,8 @@ Arrow representation of `GEOMETRY` and `GEOGRAPHY` values. | Value | Arrow representation | |-------|----------------------| -| `GeospatialResultRepresentation::String` | Arrow `Utf8` containing EWKT (the default). | -| `GeospatialResultRepresentation::Binary` | Arrow `struct` containing the SRID and little-endian OGC WKB. The WKB itself is not EWKB. | +| `GeospatialResultRepresentation::String` | Arrow `Utf8` containing WKT / EWKT. | +| `GeospatialResultRepresentation::Binary` | Arrow `struct` containing the SRID and little-endian OGC WKB. The WKB itself is not EWKB. This is the default. | Reyden returns every geo value as that native struct. The physical attachment can omit the canonical Arrow tags, while Reyder's structured manifest reports @@ -203,10 +203,15 @@ string mode preserves those values. Binary mode requires Reyden's native the kernel does not parse server-rendered text back into WKB. This is entirely client-side and is never forwarded to SEA. Set it through -the typed kernel or binding API. A `geospatial_as_string` entry placed +the typed kernel or binding API. An `EnableGeoSpatialSupport` entry placed directly in `session_conf` is not interpreted by the kernel and is forwarded unchanged; SEA/Reyden does not define that server configuration. +Bindings expose the same default-enabled boolean as Python +`enable_geospatial_support`, Node.js `enableGeoSpatialSupport`, and C +`kernel_session_config_set_enable_geospatial_support`. Enabled returns the +native SRID+WKB Arrow representation; disabled returns WKT / EWKT strings. + The structured manifest type text is authoritative for identifying geo leaves; the attachment supplies the physical values. The same post-processing step produces the requested client-facing schema for non-empty and empty results. diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 254cd71b..bfa8ee43 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -20,9 +20,14 @@ changes go in their respective binding's NEXT_CHANGELOG. - Added typed client-side `GEOMETRY` / `GEOGRAPHY` result representation selection. String mode renders the native WKB as EWKT locally; binary mode retains the tagged Arrow struct. No representation setting is sent to SEA. +- Added the default-enabled + `kernel_session_config_set_enable_geospatial_support` C ABI setting. Enabled + returns native SRID+WKB Arrow results; disabled returns WKT / EWKT strings. ### Changed +- Native SRID+WKB is now the default geospatial result representation. + - Route function metadata through the Thrift-native metadata path when supported by the server. - Authenticated SEA requests now use `Accept-Encoding: identity` by default to avoid gzipping inline LZ4-compressed Arrow results. Response compression can diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 1c9817a5..8098fc48 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -344,6 +344,18 @@ KernelStatusCode kernel_session_config_set_session_conf(KernelSessionConfig* con const char* key, const char* value); +/* Select whether GEOMETRY / GEOGRAPHY results use their native Arrow + * representation. `enabled = true` requests Arrow + * `struct` values; `false` requests WKT / EWKT in + * Arrow UTF-8 values. Omitting this setter uses the enabled kernel default. + * Binary mode requires the native Reyden Arrow path; legacy text-only results + * cannot be reconstructed as WKB. This client-side setting is never sent to + * SEA. A raw `EnableGeoSpatialSupport` entry set through + * kernel_session_config_set_session_conf remains server-bound and is forwarded + * unchanged. */ +KernelStatusCode kernel_session_config_set_enable_geospatial_support( + KernelSessionConfig* config, bool enabled); + /* Append one HTTP header sent on every request. Call once per header * (order preserved); `name` and `value` are both required. */ KernelStatusCode kernel_session_config_set_custom_header(KernelSessionConfig* config, diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index 8c2fb66f..ed2ce0f7 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -14,6 +14,9 @@ layout, or npm publishing. Pure-kernel changes go in the root ### Added +- Added the default-enabled `ConnectionOptions.enableGeoSpatialSupport` option. + Enabled returns native SRID+WKB Arrow results; disabled returns WKT / EWKT + strings. - Added `ConnectionOptions.seaResponseCompressionEnabled` to opt back into HTTP compression for bandwidth-constrained SEA connections. diff --git a/napi/index.d.ts b/napi/index.d.ts index 57e595ff..3e4b2030 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -318,6 +318,14 @@ export interface ConnectionOptions { * `session_confs`. Unknown keys are rejected server-side. */ sessionConf?: Record + /** + * Select whether `GEOMETRY` / `GEOGRAPHY` results use their native Arrow + * representation. `true` (the default) requests Arrow + * `struct` values; `false` requests WKT / EWKT + * in Arrow UTF-8 values. Binary mode requires the native Reyden Arrow + * path. This choice is applied locally and never sent to SEA. + */ + enableGeoSpatialSupport?: boolean /** * Driver name reported in telemetry system configuration. Omitted ⇒ * kernel default. diff --git a/napi/src/database.rs b/napi/src/database.rs index 93e5b6dd..4e5decf2 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -34,8 +34,9 @@ use napi::bindgen_prelude::Buffer; type Buffer = Vec; use databricks_sql_kernel::{ - AuthConfig, DefaultOpts, DriverSystemConfiguration, Error as KernelError, HttpConfig, - ProxyConfig, ResultConfig, Session, TelemetryConfig, TlsConfig, TokenCacheConfig, + AuthConfig, DefaultOpts, DriverSystemConfiguration, Error as KernelError, + GeospatialResultRepresentation, HttpConfig, ProxyConfig, ResultConfig, Session, + TelemetryConfig, TlsConfig, TokenCacheConfig, }; /// NodeJS-driver-appropriate default for `pool_max_idle_per_host`. @@ -231,6 +232,12 @@ pub struct ConnectionOptions { /// query-tag presets, …). Forwarded verbatim to SEA /// `session_confs`. Unknown keys are rejected server-side. pub session_conf: Option>, + /// Select whether `GEOMETRY` / `GEOGRAPHY` results use their native Arrow + /// representation. `true` (the default) requests Arrow + /// `struct` values; `false` requests WKT / EWKT + /// in Arrow UTF-8 values. Binary mode requires the native Reyden Arrow + /// path. This choice is applied locally and never sent to SEA. + pub enable_geo_spatial_support: Option, /// Driver name reported in telemetry system configuration. Omitted ⇒ /// kernel default. pub driver_name: Option, @@ -768,6 +775,14 @@ fn build_driver_system_configuration( }) } +fn geospatial_result_representation(enabled: Option) -> GeospatialResultRepresentation { + if enabled.unwrap_or(true) { + GeospatialResultRepresentation::Binary + } else { + GeospatialResultRepresentation::String + } +} + /// Open a Databricks SQL session and return an opaque `Connection` /// wrapping the kernel `Session`. Authentication is selected by /// `options.auth_mode` (PAT / OAuth M2M / OAuth U2M) — see @@ -828,6 +843,9 @@ pub async fn open_session(mut options: ConnectionOptions) -> napi::Result GeospatialResultRepresentation { + if enabled { + GeospatialResultRepresentation::Binary + } else { + GeospatialResultRepresentation::String + } +} + #[allow(clippy::too_many_arguments)] fn build_http_config( sea_response_compression_enabled: bool, @@ -328,6 +336,13 @@ impl Session { /// presets, etc. The kernel does not validate keys; the server /// rejects unknown ones with a `KernelError(code='SqlError')` /// when it picks them up. + /// + /// `enable_geospatial_support` selects whether `GEOMETRY` / `GEOGRAPHY` + /// results use their native Arrow representation. `True` (the default) + /// requests Arrow `struct` values; `False` + /// requests WKT / EWKT in Arrow UTF-8 values. Binary mode requires the + /// native Reyden Arrow path. This choice is applied locally and never sent + /// to SEA. #[new] #[pyo3(signature = ( host, @@ -368,6 +383,7 @@ impl Session { catalog=None, schema=None, session_conf=None, + enable_geospatial_support=true, driver_name=None, driver_version=None, runtime_name=None, @@ -434,6 +450,7 @@ impl Session { catalog: Option, schema: Option, session_conf: Option>, + enable_geospatial_support: bool, driver_name: Option, driver_version: Option, runtime_name: Option, @@ -631,6 +648,9 @@ impl Session { if let Some(conf) = session_conf { builder = builder.session_conf(conf); } + builder = builder.geospatial_result_representation(geospatial_result_representation( + enable_geospatial_support, + )); // Merge result-config knobs into one `ResultConfig` so two // toggles don't clobber each other when both are set. if complex_types_as_json || intervals_as_string { @@ -742,6 +762,18 @@ mod send_sync_tests { assert_send_sync::(); } + #[test] + fn enable_geospatial_support_maps_to_kernel_representation() { + assert_eq!( + geospatial_result_representation(true), + GeospatialResultRepresentation::Binary + ); + assert_eq!( + geospatial_result_representation(false), + GeospatialResultRepresentation::String + ); + } + #[test] fn telemetry_kwargs_map_to_kernel_config() { let telemetry = build_telemetry_config(TelemetryKwargs { @@ -822,12 +854,16 @@ mod send_sync_tests { #[test] fn request_timeout_kwarg_maps_to_http_config() { let default = databricks_sql_kernel::HttpConfig::default(); - assert!(build_http_config(false, None, None, None, None, None, None, None) - .unwrap() - .is_none()); - assert!(build_http_config(false, Some(0.0), None, None, None, None, None, None) - .unwrap() - .is_none()); + assert!( + build_http_config(false, None, None, None, None, None, None, None) + .unwrap() + .is_none() + ); + assert!( + build_http_config(false, Some(0.0), None, None, None, None, None, None) + .unwrap() + .is_none() + ); let http = build_http_config(false, Some(0.5), None, None, None, None, None, None) .unwrap() @@ -837,17 +873,26 @@ mod send_sync_tests { assert_eq!(http.overall_timeout, default.overall_timeout); let one_ns = std::time::Duration::from_nanos(1).as_secs_f64(); - assert!( - build_http_config(false, Some(one_ns / 1_000.0), None, None, None, None, None, None) - .is_err() - ); + assert!(build_http_config( + false, + Some(one_ns / 1_000.0), + None, + None, + None, + None, + None, + None + ) + .is_err()); let http = build_http_config(false, Some(one_ns), None, None, None, None, None, None) .unwrap() .expect("one-nanosecond request timeout should be accepted"); assert_eq!(http.request_timeout, std::time::Duration::from_nanos(1)); assert!(build_http_config(false, Some(-1.0), None, None, None, None, None, None).is_err()); - assert!(build_http_config(false, Some(f64::NAN), None, None, None, None, None, None).is_err()); + assert!( + build_http_config(false, Some(f64::NAN), None, None, None, None, None, None).is_err() + ); } #[test] @@ -864,9 +909,11 @@ mod send_sync_tests { #[test] fn sea_response_compression_kwarg_maps_to_http_config() { - assert!(build_http_config(false, None, None, None, None, None, None, None) - .unwrap() - .is_none()); + assert!( + build_http_config(false, None, None, None, None, None, None, None) + .unwrap() + .is_none() + ); let http = build_http_config(true, None, None, None, None, None, None, None) .unwrap() .expect("enabling SEA response compression should build an HTTP config"); diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 8f1bfc6d..65926dad 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -27,8 +27,8 @@ use super::{block_on_ffi, KernelStatusCode}; use crate::config::{ - AuthConfig, ConnectionConfig, HttpConfig, ProxyConfig, ResultConfig, TelemetryConfig, - TlsConfig, TokenCacheConfig, + AuthConfig, ConnectionConfig, GeospatialResultRepresentation, HttpConfig, ProxyConfig, + ResultConfig, TelemetryConfig, TlsConfig, TokenCacheConfig, }; use crate::kernel_error::Error; use crate::logging::{LoggingOutcome, LoggingSink}; @@ -122,6 +122,9 @@ pub struct KernelSessionConfig { connection: Option, auth: Option, session_conf: HashMap, + /// Optional client-facing representation for GEOMETRY / GEOGRAPHY results. + /// `None` uses the kernel native/binary default. + geospatial_result_representation: Option, /// Programmatic HTTP proxy (populated by `..._set_proxy`). `None` ⇒ /// reqwest's env-var proxy behaviour. proxy: Option, @@ -264,6 +267,7 @@ pub unsafe extern "C" fn kernel_session_config_new( connection: None, auth: None, session_conf: HashMap::new(), + geospatial_result_representation: None, proxy: None, tls: TlsSpec::default(), custom_headers: Vec::new(), @@ -1089,6 +1093,34 @@ pub unsafe extern "C" fn kernel_session_config_set_session_conf( }) } +/// Select whether `GEOMETRY` and `GEOGRAPHY` result columns use their native +/// Arrow representation. `enabled = true` requests Arrow +/// `struct` values; `false` requests WKT / EWKT in +/// Arrow `Utf8` values. +/// +/// Omitting this setter uses the enabled kernel default. Binary mode requires +/// the native Reyden Arrow path. The choice is applied locally and never sent +/// to SEA. A raw `EnableGeoSpatialSupport` entry supplied through +/// [`kernel_session_config_set_session_conf`] remains server-bound and is +/// forwarded unchanged. +/// +/// # Safety +/// `config` must be a live config handle. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_enable_geospatial_support( + config: *mut KernelSessionConfig, + enabled: bool, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.geospatial_result_representation = Some(if enabled { + GeospatialResultRepresentation::Binary + } else { + GeospatialResultRepresentation::String + }); + Ok(()) + }) +} + /// Read an optional C string: null → `None`, else an owned `String` /// (errors on non-UTF-8). /// @@ -1572,6 +1604,7 @@ fn build_session(config: KernelSessionConfig) -> Result Result` containing little-endian OGC /// WKB. The SRID is carried by the sibling `srid` value, not by EWKB. - /// Requires the native Reyden Arrow result path. + /// This is the kernel default and requires the native Reyden Arrow result + /// path. + #[default] Binary, } @@ -1573,7 +1574,7 @@ pub struct SessionConfig { /// Optional typed override for the physical representation of /// `GEOMETRY` / `GEOGRAPHY` values in Arrow results. /// - /// `None` uses [`GeospatialResultRepresentation::String`]. The + /// `None` uses [`GeospatialResultRepresentation::Binary`]. The /// choice is applied locally and is not forwarded to SEA. pub geospatial_result_representation: Option, @@ -1592,6 +1593,14 @@ pub struct SessionConfig { mod tests { use super::*; + #[test] + fn geospatial_result_representation_defaults_to_binary() { + assert_eq!( + GeospatialResultRepresentation::default(), + GeospatialResultRepresentation::Binary + ); + } + // ─── token cache policy ──────────────────────────────────────── #[test] diff --git a/src/metadata/type_mapping.rs b/src/metadata/type_mapping.rs index 4253a931..d0f459c2 100644 --- a/src/metadata/type_mapping.rs +++ b/src/metadata/type_mapping.rs @@ -112,10 +112,9 @@ pub(crate) const JDBC_ARRAY: i16 = 2003; /// panicking; the kernel always returns *some* schema even when the /// type is unknown. /// -/// `GEOMETRY` / `GEOGRAPHY` also default to `DataType::Utf8`: this public -/// mapping describes the string representation exposed by default, whose -/// values are rendered locally as EWKT. The result reader uses the internal -/// representation-aware mapper below when it needs the tagged binary schema. +/// `GEOMETRY` / `GEOGRAPHY` map to `DataType::Utf8` in this legacy public +/// helper. The result reader uses the internal representation-aware mapper +/// below to apply the session's native/binary default or explicit string mode. pub fn databricks_type_to_arrow(type_text: &str) -> DataType { databricks_type_to_arrow_with_interval(type_text, None) } @@ -132,8 +131,8 @@ pub fn databricks_type_to_arrow(type_text: &str) -> DataType { /// real SEA columns is `"INTERVAL YEAR TO MONTH"` / /// `"INTERVAL DAY TO SECOND"`. /// -/// Like [`databricks_type_to_arrow`], this public helper maps geospatial -/// leaves to their default EWKT `DataType::Utf8` representation. +/// Like [`databricks_type_to_arrow`], this legacy public helper maps +/// geospatial leaves to the EWKT `DataType::Utf8` representation. pub fn databricks_type_to_arrow_with_interval( type_text: &str, type_interval_type: Option<&str>, @@ -711,7 +710,7 @@ mod tests { } #[test] - fn test_geospatial_types_default_to_ewkt_string() { + fn test_legacy_geospatial_type_mapping_uses_ewkt_string() { for type_text in [ "GEOGRAPHY", "GEOGRAPHY(4326)", diff --git a/src/reader/post_processor/mod.rs b/src/reader/post_processor/mod.rs index 155cb8f6..2475922c 100644 --- a/src/reader/post_processor/mod.rs +++ b/src/reader/post_processor/mod.rs @@ -901,10 +901,13 @@ mod tests { column_info("geog", "GEOGRAPHY", "GEOGRAPHY(4326)", 1), ]); - let mut pp = - ResultPostProcessor::new(inner, Some(&manifest), PostProcessOptions::default()) - .await - .unwrap(); + let options = PostProcessOptions { + geospatial_result_representation: GeospatialResultRepresentation::String, + ..Default::default() + }; + let mut pp = ResultPostProcessor::new(inner, Some(&manifest), options) + .await + .unwrap(); assert_eq!( pp.schema().await.unwrap().field(0).data_type(), &DataType::Utf8 @@ -1041,6 +1044,7 @@ mod tests { ]); let options = PostProcessOptions { complex_types_as_json: true, + geospatial_result_representation: GeospatialResultRepresentation::String, ..Default::default() }; diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index bdb63e06..f6b78c2c 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -294,6 +294,22 @@ static void test_client_conf_setter(void) { CHECK(rc == KernelStatusCode_InvalidArgument, "set_client_conf(NULL cfg) → InvalidArgument"); } +/* Geospatial support maps true to SRID+WKB and false to WKT / EWKT strings. */ +static void test_enable_geospatial_support_setter(void) { + KernelSessionConfig* config = NULL; + (void)kernel_session_config_new(&config); + + KernelStatusCode rc = kernel_session_config_set_enable_geospatial_support(config, true); + CHECK(rc == KernelStatusCode_Success, "set_enable_geospatial_support(true) succeeds"); + rc = kernel_session_config_set_enable_geospatial_support(config, false); + CHECK(rc == KernelStatusCode_Success, "set_enable_geospatial_support(false) succeeds"); + kernel_session_config_free(config); + + rc = kernel_session_config_set_enable_geospatial_support(NULL, true); + CHECK(rc == KernelStatusCode_InvalidArgument, + "set_enable_geospatial_support(NULL cfg) -> InvalidArgument"); +} + static void capture_log(const char* level, const char* target, const char* message, void* user_data) { (void)level; @@ -375,6 +391,7 @@ int main(void) { test_u2m_and_header_setters(); test_identity_federation_client_id_setter(); test_client_conf_setter(); + test_enable_geospatial_support_setter(); test_init_logging(); test_is_open_null_guards(); test_submit_stub_rejects(); diff --git a/tests/v0_c_abi_result_config_wiremock.rs b/tests/v0_c_abi_result_config_wiremock.rs index 1151c6e6..ce834d42 100644 --- a/tests/v0_c_abi_result_config_wiremock.rs +++ b/tests/v0_c_abi_result_config_wiremock.rs @@ -30,8 +30,8 @@ use std::ffi::CString; use databricks_sql_kernel::c_abi::session::{ kernel_session_close, kernel_session_config_free, kernel_session_config_new, kernel_session_config_set_auth_pat, kernel_session_config_set_client_conf, - kernel_session_config_set_http_path, kernel_session_new_statement, kernel_session_open, - kernel_session_t, KernelSessionConfig, + kernel_session_config_set_enable_geospatial_support, kernel_session_config_set_http_path, + kernel_session_new_statement, kernel_session_open, kernel_session_t, KernelSessionConfig, }; use databricks_sql_kernel::c_abi::statement::{ kernel_executed_statement_close, kernel_executed_statement_t, kernel_statement_execute, @@ -95,7 +95,11 @@ async fn mount_execute(server: &MockServer) { /// /// # Safety /// Caller owns the returned handle and must `kernel_session_close` it. -unsafe fn open_session_c_abi(uri: &str, cloudfetch_enabled: Option) -> *mut kernel_session_t { +unsafe fn open_session_c_abi( + uri: &str, + cloudfetch_enabled: Option, + enable_geospatial_support: Option, +) -> *mut kernel_session_t { let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); assert_eq!( kernel_session_config_new(&mut config), @@ -122,6 +126,12 @@ unsafe fn open_session_c_abi(uri: &str, cloudfetch_enabled: Option) -> *mu KernelStatusCode::Success ); } + if let Some(enabled) = enable_geospatial_support { + assert_eq!( + kernel_session_config_set_enable_geospatial_support(config, enabled), + KernelStatusCode::Success + ); + } let mut session: *mut kernel_session_t = std::ptr::null_mut(); assert_eq!( kernel_session_open(config, &mut session), @@ -145,7 +155,7 @@ fn recorded_execute_disposition(cloudfetch_enabled: Option) -> String { let uri = server.uri(); unsafe { - let session = open_session_c_abi(&uri, cloudfetch_enabled); + let session = open_session_c_abi(&uri, cloudfetch_enabled, None); let mut stmt: *mut kernel_statement_t = std::ptr::null_mut(); assert_eq!( kernel_session_new_statement(session, &mut stmt), @@ -178,6 +188,35 @@ fn recorded_execute_disposition(cloudfetch_enabled: Option) -> String { .to_string() } +fn recorded_create_session_geospatial_conf(enabled: bool) -> Option { + let rt = tokio::runtime::Runtime::new().unwrap(); + let server = rt.block_on(async { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_close_any(&server).await; + server + }); + let uri = server.uri(); + + unsafe { + let session = open_session_c_abi(&uri, None, Some(enabled)); + kernel_session_close(session); + } + + let recorded = rt.block_on(async { server.received_requests().await.unwrap() }); + let create = recorded + .iter() + .find(|request| { + request.url.path() == "/api/2.0/sql/sessions" && request.method.as_str() == "POST" + }) + .expect("a POST /sessions request was made"); + let body: serde_json::Value = + serde_json::from_slice(&create.body).expect("create-session body must be valid JSON"); + body.pointer("/session_confs/EnableGeoSpatialSupport") + .and_then(|value| value.as_str()) + .map(str::to_string) +} + #[test] fn c_abi_client_conf_cloudfetch_disabled_sends_inline_disposition() { // The headline: a C-ABI host that disables CloudFetch via @@ -205,6 +244,12 @@ fn c_abi_default_result_config_sends_inline_or_external_links_disposition() { ); } +#[test] +fn c_abi_geospatial_mode_stays_client_side() { + assert_eq!(recorded_create_session_geospatial_conf(true), None); + assert_eq!(recorded_create_session_geospatial_conf(false), None); +} + #[test] fn c_abi_set_client_conf_rejects_unknown_key_and_bad_value() { use databricks_sql_kernel::c_abi::error::{kernel_get_last_error, KernelError}; diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index e16360ee..72508344 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -702,7 +702,7 @@ async fn execute_geospatial_string_mode_uses_manifest_tags_for_untagged_arrow_ip .is_some_and(|confs| { confs .keys() - .any(|key| key.eq_ignore_ascii_case("geospatial_as_string")) + .any(|key| key.eq_ignore_ascii_case("EnableGeoSpatialSupport")) }); assert!( !forwarded_geo_setting, @@ -711,7 +711,7 @@ async fn execute_geospatial_string_mode_uses_manifest_tags_for_untagged_arrow_ip } #[tokio::test] -async fn execute_geospatial_binary_mode_applies_manifest_tags_to_arrow_ipc() { +async fn execute_default_geospatial_mode_applies_manifest_tags_to_arrow_ipc() { let server = MockServer::start().await; mount_create_session(&server).await; mount_delete_session(&server).await; @@ -723,8 +723,7 @@ async fn execute_geospatial_binary_mode_applies_manifest_tags_to_arrow_ipc() { ) .await; - let session = - open_session_with_geospatial(&server, GeospatialResultRepresentation::Binary).await; + let session = open_session(&server).await; let mut stmt = session.statement(); stmt.spec().sql("SELECT geom, geog FROM geo_values"); let mut exec = stmt.execute().await.expect("execute"); @@ -815,7 +814,8 @@ async fn execute_legacy_geospatial_text_is_preserved() { ) .await; - let session = open_session(&server).await; + let session = + open_session_with_geospatial(&server, GeospatialResultRepresentation::String).await; let mut stmt = session.statement(); stmt.spec().sql("SELECT geom, geog FROM legacy_geo_values"); let mut exec = stmt.execute().await.expect("execute"); @@ -1056,7 +1056,8 @@ async fn execute_empty_legacy_geospatial_result_uses_physical_text_schema() { ) .await; - let session = open_session(&server).await; + let session = + open_session_with_geospatial(&server, GeospatialResultRepresentation::String).await; let mut stmt = session.statement(); stmt.spec() .sql("SELECT geom, geog FROM empty_legacy_geo_values"); diff --git a/tests/v0_session_wiremock.rs b/tests/v0_session_wiremock.rs index f6ca5546..62130046 100644 --- a/tests/v0_session_wiremock.rs +++ b/tests/v0_session_wiremock.rs @@ -521,7 +521,7 @@ async fn create_session_keeps_geospatial_string_mode_client_side() { let body = create_session_body(&server).await; assert!(body - .pointer("/session_confs/geospatial_as_string") + .pointer("/session_confs/EnableGeoSpatialSupport") .is_none()); } @@ -540,7 +540,7 @@ async fn create_session_keeps_geospatial_binary_mode_client_side() { let body = create_session_body(&server).await; assert!(body - .pointer("/session_confs/geospatial_as_string") + .pointer("/session_confs/EnableGeoSpatialSupport") .is_none()); } @@ -559,7 +559,7 @@ async fn create_session_omits_geospatial_conf_when_unset() { .is_some_and(|confs| { confs .keys() - .any(|key| key.eq_ignore_ascii_case("geospatial_as_string")) + .any(|key| key.eq_ignore_ascii_case("EnableGeoSpatialSupport")) }); assert!( !has_geospatial_conf, @@ -573,8 +573,8 @@ async fn typed_geospatial_config_does_not_reinterpret_raw_session_conf() { mount_geospatial_session(&server, "sess-geo-pass-through").await; let session_conf = std::collections::HashMap::from([ - ("GEOSPATIAL_AS_STRING".to_string(), "true".to_string()), - ("Geospatial_As_String".to_string(), "false".to_string()), + ("ENABLEGEOSPATIALSUPPORT".to_string(), "true".to_string()), + ("EnableGeoSpatialSupport".to_string(), "false".to_string()), ("ansi_mode".to_string(), "true".to_string()), ]); let session = open_session_with_geospatial_config( @@ -592,13 +592,13 @@ async fn typed_geospatial_config_does_not_reinterpret_raw_session_conf() { .expect("session_confs object"); assert_eq!( confs - .get("GEOSPATIAL_AS_STRING") + .get("ENABLEGEOSPATIALSUPPORT") .and_then(|value| value.as_str()), Some("true") ); assert_eq!( confs - .get("Geospatial_As_String") + .get("EnableGeoSpatialSupport") .and_then(|value| value.as_str()), Some("false") ); From 315a00e8c02d61740134d8e9e23c6253b4f9b8d7 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 8 Oct 2026 22:35:49 +0000 Subject: [PATCH 2/8] fix(results): normalize geospatial text to native Arrow Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- CONNECTION_PARAMETERS.md | 21 +- Cargo.lock | 13 + Cargo.toml | 1 + NEXT_CHANGELOG.md | 5 +- include/databricks_kernel.h | 6 +- napi/Cargo.lock | 13 + napi/index.d.ts | 5 +- napi/src/database.rs | 5 +- pyo3/Cargo.lock | 13 + pyo3/src/session.rs | 6 +- src/c_abi/session.rs | 10 +- src/config.rs | 16 +- src/reader/post_processor/geospatial.rs | 423 ++++++++++++++++++++++-- tests/v0_execute_wiremock.rs | 60 +++- 14 files changed, 512 insertions(+), 85 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index dfd528ae..edcf6001 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -188,19 +188,14 @@ Arrow representation of `GEOMETRY` and `GEOGRAPHY` values. | `GeospatialResultRepresentation::String` | Arrow `Utf8` containing WKT / EWKT. | | `GeospatialResultRepresentation::Binary` | Arrow `struct` containing the SRID and little-endian OGC WKB. The WKB itself is not EWKB. This is the default. | -Reyden returns every geo value as that native struct. The physical attachment -can omit the canonical Arrow tags, while Reyder's structured manifest reports -the logical `GEOMETRY(...)` or `GEOGRAPHY(...)` type and is the source of -truth. The kernel reconciles the attachment with that logical schema: binary -mode attaches `geometry=true` or `geography=true` and the type-level `srid` -(`-1` for `ANY`) to the `wkb` field, and string mode recursively converts the -WKB to EWKT. Every row's sibling `srid` carries the actual value. Nested values -in arrays, maps, and structs and null outer structs are preserved. - -On legacy SEA paths that already return geospatial columns as Arrow `Utf8`, -string mode preserves those values. Binary mode requires Reyden's native -`struct` attachment and returns an error when only text is available; -the kernel does not parse server-rendered text back into WKB. +Reyden returns every geo value as that native struct; standard DBSQL warehouses +return WKT / EWKT as Arrow `Utf8` or `LargeUtf8`. The structured manifest +reports the logical `GEOMETRY(...)` or `GEOGRAPHY(...)` type and is the source +of truth for either attachment. The kernel normalizes both paths: binary mode +attaches the canonical tags to a Reyden struct or parses standard-warehouse +text into the same tagged SRID+WKB struct, while string mode preserves existing +text or renders a native struct as EWKT. Nested values in arrays, maps, and +structs, per-row SRIDs, and null outer values are preserved. This is entirely client-side and is never forwarded to SEA. Set it through the typed kernel or binding API. An `EnableGeoSpatialSupport` entry placed diff --git a/Cargo.lock b/Cargo.lock index 1c9ff3b8..aef08f9b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -677,6 +677,7 @@ dependencies = [ "tracing-subscriber", "wiremock", "wkb", + "wkt", "zeroize", ] @@ -3482,6 +3483,18 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "wkt" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "efb2b923ccc882312e559ffaa832a055ba9d1ac0cc8e86b3e25453247e4b81d7" +dependencies = [ + "geo-traits", + "log", + "num-traits", + "thiserror 1.0.69", +] + [[package]] name = "writeable" version = "0.6.3" diff --git a/Cargo.toml b/Cargo.toml index 04fc5867..69eccb18 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,6 +69,7 @@ base64 = "0.22" hex = "0.4" # Hex encoding (binary param literals, token cache key) wkb = "0.9.2" # OGC WKB parser for geospatial result rendering geo-traits = "0.3" # Generic geometry traversal for WKB-to-EWKT rendering +wkt = { version = "0.14", default-features = false } # OGC WKT parser for legacy SEA results # Date/time handling chrono = { version = "0.4", features = ["serde"] } diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index bfa8ee43..99e174d8 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -18,8 +18,9 @@ changes go in their respective binding's NEXT_CHANGELOG. reconciles attachments that omit the canonical tags without copying child buffers. - Added typed client-side `GEOMETRY` / `GEOGRAPHY` result representation - selection. String mode renders the native WKB as EWKT locally; binary mode - retains the tagged Arrow struct. No representation setting is sent to SEA. + selection. The kernel normalizes both standard-warehouse WKT / EWKT and + Reyden's native SRID+WKB struct to the requested representation. No + representation setting is sent to SEA. - Added the default-enabled `kernel_session_config_set_enable_geospatial_support` C ABI setting. Enabled returns native SRID+WKB Arrow results; disabled returns WKT / EWKT strings. diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 8098fc48..4376625b 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -348,9 +348,9 @@ KernelStatusCode kernel_session_config_set_session_conf(KernelSessionConfig* con * representation. `enabled = true` requests Arrow * `struct` values; `false` requests WKT / EWKT in * Arrow UTF-8 values. Omitting this setter uses the enabled kernel default. - * Binary mode requires the native Reyden Arrow path; legacy text-only results - * cannot be reconstructed as WKB. This client-side setting is never sent to - * SEA. A raw `EnableGeoSpatialSupport` entry set through + * The kernel normalizes both standard-warehouse text and Reyden native Arrow + * results locally; this setting is never sent to SEA. A raw + * `EnableGeoSpatialSupport` entry set through * kernel_session_config_set_session_conf remains server-bound and is forwarded * unchanged. */ KernelStatusCode kernel_session_config_set_enable_geospatial_support( diff --git a/napi/Cargo.lock b/napi/Cargo.lock index 39f6ea6c..561614c6 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -612,6 +612,7 @@ dependencies = [ "tracing", "tracing-subscriber", "wkb", + "wkt", "zeroize", ] @@ -3129,6 +3130,18 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "wkt" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "efb2b923ccc882312e559ffaa832a055ba9d1ac0cc8e86b3e25453247e4b81d7" +dependencies = [ + "geo-traits", + "log", + "num-traits", + "thiserror 1.0.69", +] + [[package]] name = "writeable" version = "0.6.3" diff --git a/napi/index.d.ts b/napi/index.d.ts index 3e4b2030..bcb54502 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -322,8 +322,9 @@ export interface ConnectionOptions { * Select whether `GEOMETRY` / `GEOGRAPHY` results use their native Arrow * representation. `true` (the default) requests Arrow * `struct` values; `false` requests WKT / EWKT - * in Arrow UTF-8 values. Binary mode requires the native Reyden Arrow - * path. This choice is applied locally and never sent to SEA. + * in Arrow UTF-8 values. The kernel normalizes both standard-warehouse + * text and Reyden native Arrow results locally and never sends this choice + * to SEA. */ enableGeoSpatialSupport?: boolean /** diff --git a/napi/src/database.rs b/napi/src/database.rs index 4e5decf2..535a9c11 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -235,8 +235,9 @@ pub struct ConnectionOptions { /// Select whether `GEOMETRY` / `GEOGRAPHY` results use their native Arrow /// representation. `true` (the default) requests Arrow /// `struct` values; `false` requests WKT / EWKT - /// in Arrow UTF-8 values. Binary mode requires the native Reyden Arrow - /// path. This choice is applied locally and never sent to SEA. + /// in Arrow UTF-8 values. The kernel normalizes both standard-warehouse + /// text and Reyden native Arrow results locally and never sends this choice + /// to SEA. pub enable_geo_spatial_support: Option, /// Driver name reported in telemetry system configuration. Omitted ⇒ /// kernel default. diff --git a/pyo3/Cargo.lock b/pyo3/Cargo.lock index b9ff31d6..26faf441 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -608,6 +608,7 @@ dependencies = [ "tracing", "tracing-subscriber", "wkb", + "wkt", "zeroize", ] @@ -3024,6 +3025,18 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "wkt" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "efb2b923ccc882312e559ffaa832a055ba9d1ac0cc8e86b3e25453247e4b81d7" +dependencies = [ + "geo-traits", + "log", + "num-traits", + "thiserror 1.0.69", +] + [[package]] name = "writeable" version = "0.6.3" diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 5d2180af..c87b1ee8 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -340,9 +340,9 @@ impl Session { /// `enable_geospatial_support` selects whether `GEOMETRY` / `GEOGRAPHY` /// results use their native Arrow representation. `True` (the default) /// requests Arrow `struct` values; `False` - /// requests WKT / EWKT in Arrow UTF-8 values. Binary mode requires the - /// native Reyden Arrow path. This choice is applied locally and never sent - /// to SEA. + /// requests WKT / EWKT in Arrow UTF-8 values. The kernel normalizes both + /// standard-warehouse text and Reyden native Arrow results locally and + /// never sends this choice to SEA. #[new] #[pyo3(signature = ( host, diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 65926dad..2e843e67 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -1098,11 +1098,11 @@ pub unsafe extern "C" fn kernel_session_config_set_session_conf( /// `struct` values; `false` requests WKT / EWKT in /// Arrow `Utf8` values. /// -/// Omitting this setter uses the enabled kernel default. Binary mode requires -/// the native Reyden Arrow path. The choice is applied locally and never sent -/// to SEA. A raw `EnableGeoSpatialSupport` entry supplied through -/// [`kernel_session_config_set_session_conf`] remains server-bound and is -/// forwarded unchanged. +/// Omitting this setter uses the enabled kernel default. The kernel normalizes +/// both standard-warehouse text and Reyden native Arrow results locally and +/// never sends this choice to SEA. A raw `EnableGeoSpatialSupport` entry +/// supplied through [`kernel_session_config_set_session_conf`] remains +/// server-bound and is forwarded unchanged. /// /// # Safety /// `config` must be a live config handle. diff --git a/src/config.rs b/src/config.rs index a4a59c00..ea98a28e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1503,14 +1503,11 @@ pub enum TransportMode { /// `struct` values. /// /// This is a client-side result setting and is never sent to SEA. Reyden -/// returns `struct` values, and Reyder's structured manifest carries -/// their logical `GEOMETRY(...)` / `GEOGRAPHY(...)` types. The manifest is the -/// source of truth when an attachment omits the canonical tags. The kernel -/// reconciles the two, then exposes tagged binary values or recursively renders -/// EWKT strings. Legacy SEA paths that already return `Utf8` EWKT satisfy -/// string mode directly; requesting binary mode on such a path returns an -/// error because the original WKB cannot be recovered losslessly. Empty and -/// non-empty results use the same client-facing schema. +/// returns `struct` values, while standard DBSQL warehouses return +/// `Utf8` WKT / EWKT. The structured manifest carries the logical +/// `GEOMETRY(...)` / `GEOGRAPHY(...)` type and is the source of truth for both +/// paths. The kernel normalizes either physical representation to the requested +/// client schema. Empty and non-empty results use the same schema. #[non_exhaustive] #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum GeospatialResultRepresentation { @@ -1518,8 +1515,7 @@ pub enum GeospatialResultRepresentation { String, /// Arrow `struct` containing little-endian OGC /// WKB. The SRID is carried by the sibling `srid` value, not by EWKB. - /// This is the kernel default and requires the native Reyden Arrow result - /// path. + /// This is the kernel default. #[default] Binary, } diff --git a/src/reader/post_processor/geospatial.rs b/src/reader/post_processor/geospatial.rs index 6ec75d5c..20ec679e 100644 --- a/src/reader/post_processor/geospatial.rs +++ b/src/reader/post_processor/geospatial.rs @@ -12,30 +12,32 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Local rendering of Reyden GEOMETRY / GEOGRAPHY Arrow results. +//! Reconciliation of GEOMETRY / GEOGRAPHY Arrow results. //! -//! Reyden encodes each value as -//! `struct`. Reyder's structured -//! manifest retains the logical `GEOMETRY(...)` / `GEOGRAPHY(...)` type and is -//! the source of truth for interpreting result attachments. An attachment can -//! contain the same struct without the canonical Arrow tags. This module uses -//! the logical schema to reconstruct the tags in binary mode without copying -//! child buffers, or to recursively render each declared geo value as EWKT in -//! string mode. +//! Reyden encodes each value as `struct`, while the standard DBSQL path encodes it as WKT / EWKT in Arrow +//! `Utf8`. Reyder's structured manifest retains the logical `GEOMETRY(...)` / +//! `GEOGRAPHY(...)` type and is the source of truth for interpreting either +//! result attachment. This module recursively normalizes both physical inputs +//! to the client-requested representation. use crate::config::GeospatialResultRepresentation; use crate::kernel_error::{Error, Result}; -use arrow_array::builder::StringBuilder; +use arrow_array::builder::{BinaryBuilder, Int32Builder, StringBuilder}; use arrow_array::{ Array, ArrayRef, BinaryArray, FixedSizeListArray, Int32Array, LargeListArray, - LargeListViewArray, ListArray, ListViewArray, MapArray, StructArray, + LargeListViewArray, LargeStringArray, ListArray, ListViewArray, MapArray, StringArray, + StructArray, }; +use arrow_buffer::NullBufferBuilder; use arrow_schema::{DataType, Field, FieldRef, Fields}; use geo_traits::{ CoordTrait, Dimensions, GeometryCollectionTrait, GeometryTrait, GeometryType, LineStringTrait, MultiLineStringTrait, MultiPointTrait, MultiPolygonTrait, PointTrait, PolygonTrait, }; +use std::borrow::Cow; use std::fmt::Write as _; +use std::str::FromStr; use std::sync::Arc; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -129,19 +131,19 @@ fn plan_data_type( let physical_tag = native_geo_tag(physical)?; if let Some(expected) = logical_tag { - // DBR/legacy SEA paths can already serialize geo values as EWKT even - // though the structured manifest declares GEOMETRY / GEOGRAPHY. That - // satisfies string mode without another conversion. Binary mode must - // fail explicitly: an EWKT attachment cannot be losslessly turned back - // into Reyden's canonical `struct` representation here. + // The standard DBSQL path serializes geo values as WKT / EWKT even + // though the structured manifest declares GEOMETRY / GEOGRAPHY. Keep + // that physical type in string mode, or parse it into the same + // canonical native struct that Reyden returns in binary mode. if matches!(physical, DataType::Utf8 | DataType::LargeUtf8) { - if target == GeospatialResultRepresentation::Binary { - return Err(Error::not_implemented().message(format!( - "binary geospatial result representation is unavailable for '{path}': the server returned {physical:?}" - ))); - } + let output_type = match target { + GeospatialResultRepresentation::String => physical.clone(), + GeospatialResultRepresentation::Binary => { + logical.expect("logical_tag implies a logical type").clone() + } + }; return Ok(TypePlan { - output_type: physical.clone(), + output_type, contains_geo: true, is_root_geo: true, }); @@ -480,6 +482,9 @@ fn native_geo_family(data_type: &DataType) -> Result> { fn rewrite_array(array: &ArrayRef, output_type: &DataType, path: &str) -> Result { if let Some(output_tag) = native_geo_tag(output_type)? { + if matches!(array.data_type(), DataType::Utf8 | DataType::LargeUtf8) { + return text_to_native(array, output_type, path); + } validate_geo_source(array.data_type(), output_tag, path)?; if array.data_type() == output_type { return Ok(array.clone()); @@ -625,6 +630,218 @@ fn rewrite_array(array: &ArrayRef, output_type: &DataType, path: &str) -> Result } } +fn text_to_native(array: &ArrayRef, output_type: &DataType, path: &str) -> Result { + let DataType::Struct(output_fields) = output_type else { + unreachable!("a geo tag is only valid on a struct") + }; + + match array.data_type() { + DataType::Utf8 => { + let values = downcast::(array, path, "StringArray")?; + ewkt_values_to_native(values.iter(), values.len(), output_fields, path) + } + DataType::LargeUtf8 => { + let values = downcast::(array, path, "LargeStringArray")?; + ewkt_values_to_native(values.iter(), values.len(), output_fields, path) + } + other => Err(Error::internal().message(format!( + "geospatial text conversion for '{path}' received unexpected Arrow type {other:?}" + ))), + } +} + +fn ewkt_values_to_native<'a>( + values: impl Iterator>, + len: usize, + output_fields: &Fields, + path: &str, +) -> Result { + let mut srids = Int32Builder::with_capacity(len); + let mut wkbs = BinaryBuilder::with_capacity(len, len.saturating_mul(32)); + let mut nulls = NullBufferBuilder::new(len); + + for (row, value) in values.enumerate() { + let Some(value) = value else { + // Geo struct children are non-nullable. Use ignored placeholders + // beneath a null outer struct, matching Reyden's representation. + srids.append_value(0); + wkbs.append_value([]); + nulls.append_null(); + continue; + }; + + let (srid, wkt_body) = split_ewkt(value) + .map_err(|detail| malformed_text(path, row, &format!("has invalid EWKT: {detail}")))?; + let normalized = normalize_multipoint_empty_members(wkt_body); + let geometry = wkt::Wkt::::from_str(&normalized).map_err(|error| { + malformed_text(path, row, &format!("contains invalid WKT: {error}")) + })?; + let mut wkb = Vec::with_capacity(wkb::writer::geometry_wkb_size(&geometry)); + wkb::writer::write_geometry(&mut wkb, &geometry, &Default::default()).map_err(|error| { + malformed_text( + path, + row, + &format!("could not be encoded as OGC WKB: {error}"), + ) + })?; + + srids.append_value(srid); + wkbs.append_value(wkb); + nulls.append_non_null(); + } + + let output = StructArray::try_new( + output_fields.clone(), + vec![Arc::new(srids.finish()), Arc::new(wkbs.finish())], + nulls.finish(), + ) + .map_err(|error| rebuild_error(path, error))?; + Ok(Arc::new(output)) +} + +/// The `wkt` parser currently rejects empty point members inside a +/// `MULTIPOINT`, even though Databricks emits valid values such as +/// `MULTIPOINT(EMPTY,(1 2))`. WKB represents an empty point as an all-NaN +/// coordinate, so substitute parseable NaN coordinates before handing the +/// value to the generic WKT-to-WKB pipeline. +fn normalize_multipoint_empty_members(value: &str) -> Cow<'_, str> { + let bytes = value.as_bytes(); + let mut replacements = Vec::new(); + let mut cursor = 0; + + while cursor < bytes.len() { + if !bytes[cursor].is_ascii_alphabetic() { + cursor += 1; + continue; + } + + let word_start = cursor; + while cursor < bytes.len() && bytes[cursor].is_ascii_alphabetic() { + cursor += 1; + } + let word = &bytes[word_start..cursor]; + let (mut dimension, mut body_start) = if word.eq_ignore_ascii_case(b"MULTIPOINT") { + (2, skip_ascii_whitespace(bytes, cursor)) + } else if word.eq_ignore_ascii_case(b"MULTIPOINTZ") + || word.eq_ignore_ascii_case(b"MULTIPOINTM") + { + (3, skip_ascii_whitespace(bytes, cursor)) + } else if word.eq_ignore_ascii_case(b"MULTIPOINTZM") { + (4, skip_ascii_whitespace(bytes, cursor)) + } else { + continue; + }; + + if dimension == 2 { + let dimension_end = bytes[body_start..] + .iter() + .position(|byte| !byte.is_ascii_alphabetic()) + .map(|offset| body_start + offset) + .unwrap_or(bytes.len()); + let dimension_word = &bytes[body_start..dimension_end]; + if dimension_word.eq_ignore_ascii_case(b"Z") + || dimension_word.eq_ignore_ascii_case(b"M") + { + dimension = 3; + body_start = skip_ascii_whitespace(bytes, dimension_end); + } else if dimension_word.eq_ignore_ascii_case(b"ZM") { + dimension = 4; + body_start = skip_ascii_whitespace(bytes, dimension_end); + } + } + + // `MULTIPOINT EMPTY` describes an empty collection. Only a parenthesized + // body can contain empty point members that need normalization. + if bytes.get(body_start) != Some(&b'(') { + continue; + } + + let mut depth = 1; + let mut index = body_start + 1; + while index < bytes.len() && depth != 0 { + match bytes[index] { + b'(' => { + depth += 1; + index += 1; + } + b')' => { + depth -= 1; + index += 1; + } + byte if byte.is_ascii_alphabetic() => { + let start = index; + while index < bytes.len() && bytes[index].is_ascii_alphabetic() { + index += 1; + } + if bytes[start..index].eq_ignore_ascii_case(b"EMPTY") { + replacements.push((start, index, dimension)); + } + } + _ => index += 1, + } + } + cursor = index; + } + + if replacements.is_empty() { + return Cow::Borrowed(value); + } + + let mut output = String::with_capacity(value.len() + replacements.len() * 16); + let mut copied_through = 0; + for (start, end, dimension) in replacements { + output.push_str(&value[copied_through..start]); + for ordinate in 0..dimension { + if ordinate != 0 { + output.push(' '); + } + // A leading `+` makes `NaN` number-like to the `wkt` tokenizer. + output.push_str("+NaN"); + } + copied_through = end; + } + output.push_str(&value[copied_through..]); + Cow::Owned(output) +} + +fn skip_ascii_whitespace(bytes: &[u8], mut index: usize) -> usize { + while index < bytes.len() && bytes[index].is_ascii_whitespace() { + index += 1; + } + index +} + +/// Split a standard-warehouse WKT / EWKT value into its row SRID and WKT +/// body. Databricks omits the EWKT prefix for SRID 0, including values in a +/// `GEOMETRY(ANY)` column, so an absent prefix deliberately maps to zero. +fn split_ewkt(value: &str) -> std::result::Result<(i32, &str), String> { + let value = value.trim(); + if value.is_empty() { + return Err("value is empty".to_string()); + } + + let Some(prefix) = value.get(..5) else { + return Ok((0, value)); + }; + if !prefix.eq_ignore_ascii_case("SRID=") { + return Ok((0, value)); + } + + let rest = &value[5..]; + let separator = rest + .find(';') + .ok_or_else(|| "SRID prefix is missing ';'".to_string())?; + let srid_text = rest[..separator].trim(); + let srid = srid_text + .parse::() + .map_err(|error| format!("invalid SRID '{srid_text}': {error}"))?; + let wkt_body = rest[separator + 1..].trim(); + if wkt_body.is_empty() { + return Err("WKT body is empty".to_string()); + } + Ok((srid, wkt_body)) +} + fn native_to_ewkt(array: &ArrayRef, path: &str) -> Result { let values = downcast::(array, path, "StructArray")?; let srids = values @@ -974,6 +1191,12 @@ fn malformed_native(path: &str, detail: &str) -> Error { )) } +fn malformed_text(path: &str, row: usize, detail: &str) -> Error { + Error::data_loss().message(format!( + "geospatial value '{path}' row {row} has malformed text data: {detail}" + )) +} + fn rebuild_error(path: &str, error: arrow_schema::ArrowError) -> Error { Error::data_loss().message(format!( "failed to rebuild Arrow container '{path}' after geospatial conversion: {error}" @@ -983,8 +1206,7 @@ fn rebuild_error(path: &str, error: arrow_schema::ArrowError) -> Error { #[cfg(test)] mod tests { use super::*; - use arrow_array::builder::{BinaryBuilder, Int32Builder}; - use arrow_buffer::NullBuffer; + use arrow_buffer::{NullBuffer, OffsetBuffer, ScalarBuffer}; use std::collections::HashMap; const POINT_1_2_WKB: &[u8] = &[ @@ -1134,18 +1356,15 @@ mod tests { assert!(!string.needs_rewrite); assert_eq!(string.output_type, text_type); - let error = plan( + let binary = plan( &text, Some(&logical), GeospatialResultRepresentation::Binary, ) - .unwrap_err(); - assert!( - error - .message - .contains(&format!("server returned {text_type:?}")), - "{error:?}" - ); + .unwrap() + .unwrap(); + assert!(binary.needs_rewrite); + assert_eq!(binary.output_type, logical.data_type().clone()); } assert!( @@ -1204,6 +1423,146 @@ mod tests { assert_eq!(output.value(0), "POINT(1 2)"); } + #[test] + fn text_geometry_converts_to_native_and_preserves_outer_null() { + for array in [ + Arc::new(StringArray::from(vec![ + Some("SRID=4326;POINT (1 2)"), + Some("POINT ZM (1 2 3 4)"), + None, + ])) as ArrayRef, + Arc::new(LargeStringArray::from(vec![ + Some("SRID=4326;POINT (1 2)"), + Some("POINT ZM (1 2 3 4)"), + None, + ])) as ArrayRef, + ] { + let output_type = geo_type(GeoFamily::Geometry, -1); + let output = rewrite(&array, &output_type, "g").unwrap(); + let output = output.as_any().downcast_ref::().unwrap(); + assert_eq!(output.data_type(), &output_type); + assert_eq!(output.null_count(), 1); + assert!(output.is_null(2)); + + let srids = output + .column_by_name("srid") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(srids.values(), &[4326, 0, 0]); + assert_eq!(srids.null_count(), 0); + + let wkbs = output + .column_by_name("wkb") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(wkbs.value(0), POINT_1_2_WKB); + assert_eq!(wkbs.null_count(), 0); + let geometry = wkb::reader::read_wkb(wkbs.value(1)).unwrap(); + let mut rendered = String::new(); + write_ogc_wkt(&mut rendered, &geometry).unwrap(); + assert_eq!(rendered, "POINT ZM (1 2 3 4)"); + } + } + + #[test] + fn text_geometry_converts_to_native_inside_nested_container() { + let values: ArrayRef = + Arc::new(StringArray::from(vec![Some("SRID=3857;POINT(1 2)"), None])); + let list: ArrayRef = Arc::new(ListArray::new( + Arc::new(Field::new("item", DataType::Utf8, true)), + OffsetBuffer::new(ScalarBuffer::from(vec![0_i32, 2, 2])), + values, + Some(NullBuffer::from(vec![true, false])), + )); + let output_type = DataType::List(Arc::new(Field::new( + "item", + geo_type(GeoFamily::Geometry, -1), + true, + ))); + + let output = rewrite(&list, &output_type, "nested_geometry").unwrap(); + let output = output.as_any().downcast_ref::().unwrap(); + assert_eq!(output.data_type(), &output_type); + assert!(output.is_null(1)); + + let values = output + .values() + .as_any() + .downcast_ref::() + .unwrap(); + assert!(values.is_null(1)); + let srids = values + .column_by_name("srid") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + let wkbs = values + .column_by_name("wkb") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(srids.value(0), 3857); + assert_eq!(wkbs.value(0), POINT_1_2_WKB); + } + + #[test] + fn text_to_native_handles_every_ogc_family_dimensions_and_empties() { + let cases = [ + "POINT EMPTY", + "POINT Z (1 2 3)", + "LINESTRING M (0 1 2,3 4 5)", + "POLYGON ZM ((0 0 1 2,0 1 2 3,1 0 3 4,0 0 1 2))", + "MULTIPOINT((1 2),EMPTY,(3 4))", + "MULTIPOINT Z ((1 2 3),EMPTY,(4 5 6))", + "MULTIPOINT M (EMPTY,(1 2 3),EMPTY)", + "MULTIPOINT ZM ((1 2 3 4),EMPTY,(5 6 7 8))", + "MULTILINESTRING(EMPTY,(1 2,3 4))", + "MULTIPOLYGON(EMPTY,((0 0,0 1,1 0,0 0)))", + "GEOMETRYCOLLECTION(POINT(1 2),LINESTRING EMPTY)", + "GEOMETRYCOLLECTION ZM (POINT ZM EMPTY,MULTIPOINT ZM (EMPTY,(1 2 3 4)),GEOMETRYCOLLECTION ZM (MULTIPOINT ZM ((5 6 7 8),EMPTY)))", + ]; + + for expected in cases { + let array: ArrayRef = Arc::new(StringArray::from(vec![expected])); + let output = rewrite(&array, &geo_type(GeoFamily::Geometry, -1), "geometry") + .unwrap_or_else(|error| panic!("failed to convert {expected}: {error:?}")); + let output = output.as_any().downcast_ref::().unwrap(); + let wkbs = output + .column_by_name("wkb") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + let geometry = wkb::reader::read_wkb(wkbs.value(0)).unwrap(); + let mut actual = String::new(); + write_ogc_wkt(&mut actual, &geometry).unwrap(); + assert_eq!(actual, expected); + } + } + + #[test] + fn malformed_text_is_reported_as_data_loss_without_echoing_the_value() { + for value in [ + "SRID=invalid;POINT(1 2)", + "SRID=4326POINT(1 2)", + "SRID=4326;", + "not sensitive result contents", + ] { + let array: ArrayRef = Arc::new(StringArray::from(vec![value])); + let error = + rewrite(&array, &geo_type(GeoFamily::Geometry, -1), "geometry").unwrap_err(); + assert_eq!(error.code, crate::kernel_error::ErrorCode::DataLoss); + assert!(error.message.contains("'geometry' row 0"), "{error:?}"); + assert!(!error.message.contains(value), "{error:?}"); + } + } + #[test] fn invalid_wkb_is_reported_as_data_loss() { let DataType::Struct(fields) = geo_type(GeoFamily::Geometry, 0) else { diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 72508344..b973a063 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -836,7 +836,7 @@ async fn execute_legacy_geospatial_text_is_preserved() { } #[tokio::test] -async fn execute_legacy_geospatial_text_rejects_binary_mode() { +async fn execute_standard_warehouse_geospatial_text_converts_to_binary_mode() { for data_type in [DataType::Utf8, DataType::LargeUtf8] { for include_rows in [true, false] { let server = MockServer::start().await; @@ -857,18 +857,52 @@ async fn execute_legacy_geospatial_text_rejects_binary_mode() { let session = open_session_with_geospatial(&server, GeospatialResultRepresentation::Binary).await; let mut stmt = session.statement(); - stmt.spec().sql("SELECT geom FROM legacy_geo_values"); - let error = match stmt.execute().await { - Ok(_) => panic!("binary mode must reject a legacy {data_type:?} geo attachment"), - Err(error) => error, - }; - assert_eq!(error.code, ErrorCode::InvalidArgument); - assert!( - error - .message - .contains(&format!("server returned {data_type:?}")), - "{error:?}" - ); + stmt.spec() + .sql("SELECT geom, geog FROM standard_geo_values"); + let mut exec = stmt.execute().await.expect("execute"); + + let schema = exec.schema(); + for (index, family, type_srid) in [(0, "geometry", "-1"), (1, "geography", "4326")] { + let DataType::Struct(fields) = schema.field(index).data_type() else { + panic!("binary geo field must use the tagged struct encoding") + }; + assert_eq!( + fields[1].metadata().get(family).map(String::as_str), + Some("true") + ); + assert_eq!( + fields[1].metadata().get("srid").map(String::as_str), + Some(type_srid) + ); + } + + let batches = drain(exec.result_stream_mut()).await; + if include_rows { + assert_eq!(batches.len(), 1); + let geometry = batches[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + let srids = geometry + .column_by_name("srid") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + let wkbs = geometry + .column_by_name("wkb") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(srids.value(0), 3857); + assert_eq!(wkbs.value(0), POINT_1_2_WKB); + assert!(geometry.is_null(1)); + } else { + assert!(batches.is_empty()); + } + exec.close().await.expect("close"); } } } From af046b7a651c42e6a4f096fdc8898c84406f878f Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Tue, 13 Oct 2026 18:57:59 +0000 Subject: [PATCH 3/8] fix: harden geospatial result reconciliation Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/reader/post_processor/geospatial.rs | 265 ++++++++++++++++++++++-- tests/v0_execute_wiremock.rs | 161 ++++++++++++++ 2 files changed, 405 insertions(+), 21 deletions(-) diff --git a/src/reader/post_processor/geospatial.rs b/src/reader/post_processor/geospatial.rs index 20ec679e..e7591de9 100644 --- a/src/reader/post_processor/geospatial.rs +++ b/src/reader/post_processor/geospatial.rs @@ -29,7 +29,7 @@ use arrow_array::{ LargeListViewArray, LargeStringArray, ListArray, ListViewArray, MapArray, StringArray, StructArray, }; -use arrow_buffer::NullBufferBuilder; +use arrow_buffer::{NullBuffer, NullBufferBuilder}; use arrow_schema::{DataType, Field, FieldRef, Fields}; use geo_traits::{ CoordTrait, Dimensions, GeometryCollectionTrait, GeometryTrait, GeometryType, LineStringTrait, @@ -118,7 +118,7 @@ pub(super) fn rewrite( output_type: &DataType, column_name: &str, ) -> Result { - rewrite_array(array, output_type, column_name) + rewrite_array(array, output_type, column_name, None) } fn plan_data_type( @@ -480,10 +480,15 @@ fn native_geo_family(data_type: &DataType) -> Result> { Ok(native_geo_tag(data_type)?.map(|tag| tag.family)) } -fn rewrite_array(array: &ArrayRef, output_type: &DataType, path: &str) -> Result { +fn rewrite_array( + array: &ArrayRef, + output_type: &DataType, + path: &str, + parent_validity: Option<&NullBuffer>, +) -> Result { if let Some(output_tag) = native_geo_tag(output_type)? { if matches!(array.data_type(), DataType::Utf8 | DataType::LargeUtf8) { - return text_to_native(array, output_type, path); + return text_to_native(array, output_type, output_tag.srid, path, parent_validity); } validate_geo_source(array.data_type(), output_tag, path)?; if array.data_type() == output_type { @@ -503,7 +508,7 @@ fn rewrite_array(array: &ArrayRef, output_type: &DataType, path: &str) -> Result } if output_type == &DataType::Utf8 && is_geo_struct_shape(array.data_type()) { - return native_to_ewkt(array, path); + return native_to_ewkt(array, path, parent_validity); } if native_geo_family(array.data_type())?.is_some() { @@ -515,6 +520,11 @@ fn rewrite_array(array: &ArrayRef, output_type: &DataType, path: &str) -> Result match (array.data_type(), output_type) { (DataType::Struct(source_fields), DataType::Struct(output_fields)) => { let values = downcast::(array, path, "StructArray")?; + // A child slot under a null struct is an unspecified placeholder, + // even when that child is declared non-nullable. Carry the + // effective ancestor validity into geo conversions so placeholder + // text or WKB is never parsed as a real value. + let child_validity = NullBuffer::union(parent_validity, values.nulls()); let columns = values .columns() .iter() @@ -525,6 +535,7 @@ fn rewrite_array(array: &ArrayRef, output_type: &DataType, path: &str) -> Result column, output.data_type(), &format!("{path}.{}", source.name()), + child_validity.as_ref(), ) }) .collect::>>()?; @@ -535,7 +546,7 @@ fn rewrite_array(array: &ArrayRef, output_type: &DataType, path: &str) -> Result } (DataType::List(_), DataType::List(output_field)) => { let values = downcast::(array, path, "ListArray")?; - let child = rewrite_array(values.values(), output_field.data_type(), path)?; + let child = rewrite_array(values.values(), output_field.data_type(), path, None)?; let output = ListArray::try_new( output_field.clone(), values.offsets().clone(), @@ -547,7 +558,7 @@ fn rewrite_array(array: &ArrayRef, output_type: &DataType, path: &str) -> Result } (DataType::LargeList(_), DataType::LargeList(output_field)) => { let values = downcast::(array, path, "LargeListArray")?; - let child = rewrite_array(values.values(), output_field.data_type(), path)?; + let child = rewrite_array(values.values(), output_field.data_type(), path, None)?; let output = LargeListArray::try_new( output_field.clone(), values.offsets().clone(), @@ -559,7 +570,7 @@ fn rewrite_array(array: &ArrayRef, output_type: &DataType, path: &str) -> Result } (DataType::ListView(_), DataType::ListView(output_field)) => { let values = downcast::(array, path, "ListViewArray")?; - let child = rewrite_array(values.values(), output_field.data_type(), path)?; + let child = rewrite_array(values.values(), output_field.data_type(), path, None)?; let output = ListViewArray::try_new( output_field.clone(), values.offsets().clone(), @@ -572,7 +583,7 @@ fn rewrite_array(array: &ArrayRef, output_type: &DataType, path: &str) -> Result } (DataType::LargeListView(_), DataType::LargeListView(output_field)) => { let values = downcast::(array, path, "LargeListViewArray")?; - let child = rewrite_array(values.values(), output_field.data_type(), path)?; + let child = rewrite_array(values.values(), output_field.data_type(), path, None)?; let output = LargeListViewArray::try_new( output_field.clone(), values.offsets().clone(), @@ -588,7 +599,7 @@ fn rewrite_array(array: &ArrayRef, output_type: &DataType, path: &str) -> Result DataType::FixedSizeList(output_field, output_size), ) if source_size == output_size => { let values = downcast::(array, path, "FixedSizeListArray")?; - let child = rewrite_array(values.values(), output_field.data_type(), path)?; + let child = rewrite_array(values.values(), output_field.data_type(), path, None)?; let output = FixedSizeListArray::try_new( output_field.clone(), *output_size, @@ -603,7 +614,7 @@ fn rewrite_array(array: &ArrayRef, output_type: &DataType, path: &str) -> Result { let values = downcast::(array, path, "MapArray")?; let entries: ArrayRef = Arc::new(values.entries().clone()); - let entries = rewrite_array(&entries, output_field.data_type(), path)?; + let entries = rewrite_array(&entries, output_field.data_type(), path, None)?; let entries = entries .as_any() .downcast_ref::() @@ -630,7 +641,13 @@ fn rewrite_array(array: &ArrayRef, output_type: &DataType, path: &str) -> Result } } -fn text_to_native(array: &ArrayRef, output_type: &DataType, path: &str) -> Result { +fn text_to_native( + array: &ArrayRef, + output_type: &DataType, + type_srid: i32, + path: &str, + parent_validity: Option<&NullBuffer>, +) -> Result { let DataType::Struct(output_fields) = output_type else { unreachable!("a geo tag is only valid on a struct") }; @@ -638,11 +655,25 @@ fn text_to_native(array: &ArrayRef, output_type: &DataType, path: &str) -> Resul match array.data_type() { DataType::Utf8 => { let values = downcast::(array, path, "StringArray")?; - ewkt_values_to_native(values.iter(), values.len(), output_fields, path) + ewkt_values_to_native( + values.iter(), + values.len(), + output_fields, + type_srid, + path, + parent_validity, + ) } DataType::LargeUtf8 => { let values = downcast::(array, path, "LargeStringArray")?; - ewkt_values_to_native(values.iter(), values.len(), output_fields, path) + ewkt_values_to_native( + values.iter(), + values.len(), + output_fields, + type_srid, + path, + parent_validity, + ) } other => Err(Error::internal().message(format!( "geospatial text conversion for '{path}' received unexpected Arrow type {other:?}" @@ -654,13 +685,22 @@ fn ewkt_values_to_native<'a>( values: impl Iterator>, len: usize, output_fields: &Fields, + type_srid: i32, path: &str, + parent_validity: Option<&NullBuffer>, ) -> Result { let mut srids = Int32Builder::with_capacity(len); let mut wkbs = BinaryBuilder::with_capacity(len, len.saturating_mul(32)); let mut nulls = NullBufferBuilder::new(len); + let fallback_srid = if type_srid >= 0 { type_srid } else { 0 }; for (row, value) in values.enumerate() { + if parent_validity.is_some_and(|validity| validity.is_null(row)) { + srids.append_value(0); + wkbs.append_value([]); + nulls.append_non_null(); + continue; + } let Some(value) = value else { // Geo struct children are non-nullable. Use ignored placeholders // beneath a null outer struct, matching Reyden's representation. @@ -670,7 +710,7 @@ fn ewkt_values_to_native<'a>( continue; }; - let (srid, wkt_body) = split_ewkt(value) + let (srid, wkt_body) = split_ewkt(value, fallback_srid) .map_err(|detail| malformed_text(path, row, &format!("has invalid EWKT: {detail}")))?; let normalized = normalize_multipoint_empty_members(wkt_body); let geometry = wkt::Wkt::::from_str(&normalized).map_err(|error| { @@ -812,19 +852,19 @@ fn skip_ascii_whitespace(bytes: &[u8], mut index: usize) -> usize { } /// Split a standard-warehouse WKT / EWKT value into its row SRID and WKT -/// body. Databricks omits the EWKT prefix for SRID 0, including values in a -/// `GEOMETRY(ANY)` column, so an absent prefix deliberately maps to zero. -fn split_ewkt(value: &str) -> std::result::Result<(i32, &str), String> { +/// body. An absent prefix uses the fixed logical SRID when one exists; `ANY` +/// columns use zero because their type does not supply a row SRID. +fn split_ewkt(value: &str, fallback_srid: i32) -> std::result::Result<(i32, &str), String> { let value = value.trim(); if value.is_empty() { return Err("value is empty".to_string()); } let Some(prefix) = value.get(..5) else { - return Ok((0, value)); + return Ok((fallback_srid, value)); }; if !prefix.eq_ignore_ascii_case("SRID=") { - return Ok((0, value)); + return Ok((fallback_srid, value)); } let rest = &value[5..]; @@ -842,7 +882,11 @@ fn split_ewkt(value: &str) -> std::result::Result<(i32, &str), String> { Ok((srid, wkt_body)) } -fn native_to_ewkt(array: &ArrayRef, path: &str) -> Result { +fn native_to_ewkt( + array: &ArrayRef, + path: &str, + parent_validity: Option<&NullBuffer>, +) -> Result { let values = downcast::(array, path, "StructArray")?; let srids = values .column_by_name("srid") @@ -855,6 +899,10 @@ fn native_to_ewkt(array: &ArrayRef, path: &str) -> Result { let mut output = StringBuilder::with_capacity(values.len(), values.len() * 32); for row in 0..values.len() { + if parent_validity.is_some_and(|validity| validity.is_null(row)) { + output.append_value(""); + continue; + } if values.is_null(row) { output.append_null(); continue; @@ -1468,6 +1516,181 @@ mod tests { } } + #[test] + fn unprefixed_text_uses_fixed_type_srid_and_any_uses_zero() { + for (type_srid, expected_row_srid) in [(4326, 4326), (-1, 0)] { + let array: ArrayRef = Arc::new(StringArray::from(vec!["POINT (1 2)"])); + let output = rewrite( + &array, + &geo_type(GeoFamily::Geography, type_srid), + "geography", + ) + .unwrap(); + let output = output.as_any().downcast_ref::().unwrap(); + let srids = output + .column_by_name("srid") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(srids.value(0), expected_row_srid); + } + } + + #[test] + fn null_parent_struct_masks_invalid_geo_placeholders() { + let text_child: ArrayRef = Arc::new(StringArray::from(vec!["not valid WKT"])); + let text_parent_type = DataType::Struct(Fields::from(vec![Field::new( + "geom", + DataType::Utf8, + false, + )])); + let DataType::Struct(text_parent_fields) = &text_parent_type else { + unreachable!() + }; + let text_parent: ArrayRef = Arc::new(StructArray::new( + text_parent_fields.clone(), + vec![text_child], + Some(NullBuffer::new_null(1)), + )); + let native_parent_type = DataType::Struct(Fields::from(vec![Field::new( + "geom", + geo_type(GeoFamily::Geometry, 4326), + false, + )])); + + let native = rewrite(&text_parent, &native_parent_type, "value").unwrap(); + let native = native.as_any().downcast_ref::().unwrap(); + assert!(native.is_null(0)); + let geom = native + .column_by_name("geom") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert!(geom.is_valid(0)); + assert_eq!( + geom.column_by_name("srid") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + 0 + ); + assert_eq!( + geom.column_by_name("wkb") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + b"" + ); + + let DataType::Struct(plain_geo_fields) = plain_geo_type() else { + unreachable!() + }; + let invalid_native: ArrayRef = Arc::new(StructArray::new( + plain_geo_fields, + vec![ + Arc::new(Int32Array::from(vec![4326])), + Arc::new(BinaryArray::from(vec![&b"not WKB"[..]])), + ], + None, + )); + let native_parent: ArrayRef = Arc::new(StructArray::new( + Fields::from(vec![Field::new("geom", plain_geo_type(), false)]), + vec![invalid_native], + Some(NullBuffer::new_null(1)), + )); + let string_parent_type = DataType::Struct(Fields::from(vec![Field::new( + "geom", + DataType::Utf8, + false, + )])); + + let string = rewrite(&native_parent, &string_parent_type, "value").unwrap(); + let string = string.as_any().downcast_ref::().unwrap(); + assert!(string.is_null(0)); + let geom = string + .column_by_name("geom") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert!(geom.is_valid(0)); + assert_eq!(geom.value(0), ""); + } + + #[test] + fn non_nullable_untagged_nested_geo_is_recovered_in_both_modes() { + let DataType::Struct(plain_fields) = plain_geo_type() else { + unreachable!() + }; + let geom: ArrayRef = Arc::new(StructArray::new( + plain_fields, + vec![ + Arc::new(Int32Array::from(vec![4326])), + Arc::new(BinaryArray::from(vec![POINT_1_2_WKB])), + ], + None, + )); + let physical_type = DataType::Struct(Fields::from(vec![Field::new( + "geom", + plain_geo_type(), + false, + )])); + let DataType::Struct(physical_fields) = &physical_type else { + unreachable!() + }; + let physical: ArrayRef = + Arc::new(StructArray::new(physical_fields.clone(), vec![geom], None)); + let logical_type = DataType::Struct(Fields::from(vec![Field::new( + "geom", + geo_type(GeoFamily::Geometry, 4326), + false, + )])); + let physical_field = Field::new("value", physical_type, true); + let logical_field = Field::new("value", logical_type, true); + + for representation in [ + GeospatialResultRepresentation::Binary, + GeospatialResultRepresentation::String, + ] { + let plan = plan(&physical_field, Some(&logical_field), representation) + .unwrap() + .unwrap(); + let output = rewrite(&physical, &plan.output_type, "value").unwrap(); + let output = output.as_any().downcast_ref::().unwrap(); + let DataType::Struct(fields) = output.data_type() else { + unreachable!() + }; + assert!(!fields[0].is_nullable()); + + match representation { + GeospatialResultRepresentation::Binary => { + assert_eq!( + native_geo_tag(fields[0].data_type()).unwrap(), + Some(GeoTag { + family: GeoFamily::Geometry, + srid: 4326, + }) + ); + } + GeospatialResultRepresentation::String => { + assert_eq!(fields[0].data_type(), &DataType::Utf8); + let values = output + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(values.value(0), "SRID=4326;POINT(1 2)"); + } + } + } + } + #[test] fn text_geometry_converts_to_native_inside_nested_container() { let values: ArrayRef = diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index b973a063..406f9f50 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -461,6 +461,63 @@ fn legacy_geospatial_batch(data_type: DataType) -> RecordBatch { RecordBatch::try_new(schema, columns).unwrap() } +fn nested_geospatial_batch(native: bool) -> RecordBatch { + let geometry: ArrayRef = if native { + geospatial_array(4326) + } else { + Arc::new(StringArray::from(vec![Some("SRID=4326;POINT (1 2)"), None])) + }; + let blob: ArrayRef = Arc::new(BinaryArray::from(vec![ + Some(&b"\x00\xffblob"[..]), + Some(&b"still here"[..]), + ])); + let nested_fields = Fields::from(vec![ + Field::new("geom", geometry.data_type().clone(), true), + Field::new("blob", DataType::Binary, true), + ]); + let nested: ArrayRef = Arc::new(StructArray::new(nested_fields, vec![geometry, blob], None)); + let schema = Arc::new(Schema::new(vec![Field::new( + "col_0", + nested.data_type().clone(), + true, + )])); + RecordBatch::try_new(schema, vec![nested]).unwrap() +} + +fn succeeded_nested_geospatial_body(statement_id: &str, batch: &RecordBatch) -> String { + let ipc = arrow_ipc_bytes(batch); + let physical_schema = arrow_schema_ipc_bytes(batch.schema().as_ref()); + json!({ + "statement_id": statement_id, + "status": { "state": "SUCCEEDED" }, + "manifest": { + "format": "ARROW_STREAM", + "schema": { + "column_count": 1, + "columns": [{ + "name": "mixed", + "type_name": "STRUCT", + "type_text": "STRUCT", + "position": 0, + }], + }, + "arrow_schema": STANDARD.encode(physical_schema), + "total_chunk_count": 1, + "total_row_count": batch.num_rows() as i64, + "total_byte_count": ipc.len() as i64, + "truncated": false, + }, + "result": { + "chunk_index": 0, + "row_offset": 0, + "row_count": batch.num_rows() as i64, + "byte_count": ipc.len() as i64, + "attachment": STANDARD.encode(&ipc), + }, + }) + .to_string() +} + fn logical_geospatial_schema() -> Schema { Schema::new(vec![ Field::new("geom", geospatial_type("geometry", -1), true), @@ -907,6 +964,110 @@ async fn execute_standard_warehouse_geospatial_text_converts_to_binary_mode() { } } +#[tokio::test] +async fn execute_nested_native_and_text_geospatial_preserve_mixed_binary_field() { + for native_source in [true, false] { + for representation in [ + GeospatialResultRepresentation::String, + GeospatialResultRepresentation::Binary, + ] { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + let batch = nested_geospatial_batch(native_source); + let statement_id = format!( + "stmt-nested-geo-{}-{}", + if native_source { "native" } else { "text" }, + if representation == GeospatialResultRepresentation::Binary { + "binary" + } else { + "string" + } + ); + mount_execute( + &server, + succeeded_nested_geospatial_body(&statement_id, &batch), + ) + .await; + + let session = open_session_with_geospatial(&server, representation).await; + let mut stmt = session.statement(); + stmt.spec() + .sql("SELECT named_struct('geom', geom, 'blob', blob)"); + let mut exec = stmt.execute().await.expect("execute"); + let batches = drain(exec.result_stream_mut()).await; + assert_eq!(batches.len(), 1); + + let mixed = batches[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + let blob = mixed + .column_by_name("blob") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(blob.value(0), b"\x00\xffblob"); + assert_eq!(blob.value(1), b"still here"); + + match representation { + GeospatialResultRepresentation::String => { + let geom = mixed + .column_by_name("geom") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!( + geom.value(0), + if native_source { + "SRID=4326;POINT(1 2)" + } else { + "SRID=4326;POINT (1 2)" + } + ); + assert!(geom.is_null(1)); + } + GeospatialResultRepresentation::Binary => { + let geom = mixed + .column_by_name("geom") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + let DataType::Struct(fields) = geom.data_type() else { + unreachable!() + }; + assert_eq!( + fields[1].metadata().get("geometry").map(String::as_str), + Some("true") + ); + let srids = geom + .column_by_name("srid") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + let wkbs = geom + .column_by_name("wkb") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(srids.value(0), 4326); + assert_eq!(wkbs.value(0), POINT_1_2_WKB); + assert!(geom.is_null(1)); + } + _ => unreachable!("test covers every current representation"), + } + exec.close().await.expect("close"); + } + } +} + #[tokio::test] async fn execute_cloudfetch_geospatial_reconciles_manifest_and_untagged_payload() { for representation in [ From 0bddd8af90df64cfa94a8608119c99eb1e33a316 Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Thu, 15 Oct 2026 18:57:08 +0000 Subject: [PATCH 4/8] fix: honor nested nulls and reject trailing geospatial text Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> --- src/reader/post_processor/geospatial.rs | 392 +++++++++++++++++++++++- 1 file changed, 383 insertions(+), 9 deletions(-) diff --git a/src/reader/post_processor/geospatial.rs b/src/reader/post_processor/geospatial.rs index e7591de9..5223a55b 100644 --- a/src/reader/post_processor/geospatial.rs +++ b/src/reader/post_processor/geospatial.rs @@ -29,7 +29,7 @@ use arrow_array::{ LargeListViewArray, LargeStringArray, ListArray, ListViewArray, MapArray, StringArray, StructArray, }; -use arrow_buffer::{NullBuffer, NullBufferBuilder}; +use arrow_buffer::{BooleanBufferBuilder, NullBuffer, NullBufferBuilder}; use arrow_schema::{DataType, Field, FieldRef, Fields}; use geo_traits::{ CoordTrait, Dimensions, GeometryCollectionTrait, GeometryTrait, GeometryType, LineStringTrait, @@ -546,7 +546,21 @@ fn rewrite_array( } (DataType::List(_), DataType::List(output_field)) => { let values = downcast::(array, path, "ListArray")?; - let child = rewrite_array(values.values(), output_field.data_type(), path, None)?; + let validity = container_child_validity( + values, + parent_validity, + values.values().len(), + values + .value_offsets() + .windows(2) + .map(|pair| pair[0] as usize..pair[1] as usize), + ); + let child = rewrite_array( + values.values(), + output_field.data_type(), + path, + validity.as_ref(), + )?; let output = ListArray::try_new( output_field.clone(), values.offsets().clone(), @@ -558,7 +572,21 @@ fn rewrite_array( } (DataType::LargeList(_), DataType::LargeList(output_field)) => { let values = downcast::(array, path, "LargeListArray")?; - let child = rewrite_array(values.values(), output_field.data_type(), path, None)?; + let validity = container_child_validity( + values, + parent_validity, + values.values().len(), + values + .value_offsets() + .windows(2) + .map(|pair| pair[0] as usize..pair[1] as usize), + ); + let child = rewrite_array( + values.values(), + output_field.data_type(), + path, + validity.as_ref(), + )?; let output = LargeListArray::try_new( output_field.clone(), values.offsets().clone(), @@ -570,7 +598,22 @@ fn rewrite_array( } (DataType::ListView(_), DataType::ListView(output_field)) => { let values = downcast::(array, path, "ListViewArray")?; - let child = rewrite_array(values.values(), output_field.data_type(), path, None)?; + let validity = container_child_validity( + values, + parent_validity, + values.values().len(), + values + .value_offsets() + .iter() + .zip(values.value_sizes()) + .map(|(&offset, &size)| offset as usize..offset as usize + size as usize), + ); + let child = rewrite_array( + values.values(), + output_field.data_type(), + path, + validity.as_ref(), + )?; let output = ListViewArray::try_new( output_field.clone(), values.offsets().clone(), @@ -583,7 +626,22 @@ fn rewrite_array( } (DataType::LargeListView(_), DataType::LargeListView(output_field)) => { let values = downcast::(array, path, "LargeListViewArray")?; - let child = rewrite_array(values.values(), output_field.data_type(), path, None)?; + let validity = container_child_validity( + values, + parent_validity, + values.values().len(), + values + .value_offsets() + .iter() + .zip(values.value_sizes()) + .map(|(&offset, &size)| offset as usize..offset as usize + size as usize), + ); + let child = rewrite_array( + values.values(), + output_field.data_type(), + path, + validity.as_ref(), + )?; let output = LargeListViewArray::try_new( output_field.clone(), values.offsets().clone(), @@ -599,7 +657,19 @@ fn rewrite_array( DataType::FixedSizeList(output_field, output_size), ) if source_size == output_size => { let values = downcast::(array, path, "FixedSizeListArray")?; - let child = rewrite_array(values.values(), output_field.data_type(), path, None)?; + let size = *source_size as usize; + let validity = container_child_validity( + values, + parent_validity, + values.values().len(), + (0..values.len()).map(|row| row * size..(row + 1) * size), + ); + let child = rewrite_array( + values.values(), + output_field.data_type(), + path, + validity.as_ref(), + )?; let output = FixedSizeListArray::try_new( output_field.clone(), *output_size, @@ -614,7 +684,17 @@ fn rewrite_array( { let values = downcast::(array, path, "MapArray")?; let entries: ArrayRef = Arc::new(values.entries().clone()); - let entries = rewrite_array(&entries, output_field.data_type(), path, None)?; + let validity = container_child_validity( + values, + parent_validity, + entries.len(), + values + .value_offsets() + .windows(2) + .map(|pair| pair[0] as usize..pair[1] as usize), + ); + let entries = + rewrite_array(&entries, output_field.data_type(), path, validity.as_ref())?; let entries = entries .as_any() .downcast_ref::() @@ -641,6 +721,28 @@ fn rewrite_array( } } +/// Translate container-row validity into child positions. Start with no visible +/// children so backing values outside a sliced array are ignored too. List-view +/// ranges can overlap: a child is visible if *any* valid row references it. +fn container_child_validity( + array: &dyn Array, + parent_validity: Option<&NullBuffer>, + child_len: usize, + ranges: impl Iterator>, +) -> Option { + let mut validity = BooleanBufferBuilder::new(child_len); + validity.append_n(child_len, false); + for (row, range) in ranges.enumerate() { + if array.is_valid(row) && parent_validity.is_none_or(|mask| mask.is_valid(row)) { + for child in range { + validity.set_bit(child, true); + } + } + } + let validity = NullBuffer::new(validity.finish()); + (validity.null_count() != 0).then_some(validity) +} + fn text_to_native( array: &ArrayRef, output_type: &DataType, @@ -712,6 +814,7 @@ fn ewkt_values_to_native<'a>( let (srid, wkt_body) = split_ewkt(value, fallback_srid) .map_err(|detail| malformed_text(path, row, &format!("has invalid EWKT: {detail}")))?; + validate_wkt_boundary(wkt_body).map_err(|detail| malformed_text(path, row, detail))?; let normalized = normalize_multipoint_empty_members(wkt_body); let geometry = wkt::Wkt::::from_str(&normalized).map_err(|error| { malformed_text(path, row, &format!("contains invalid WKT: {error}")) @@ -739,6 +842,52 @@ fn ewkt_values_to_native<'a>( Ok(Arc::new(output)) } +/// `wkt::Wkt::from_str` accepts a valid geometry followed by arbitrary tokens. +/// Check the top-level boundary before parsing; the parser validates its body. +fn validate_wkt_boundary(value: &str) -> std::result::Result<(), &'static str> { + let invalid = "contains invalid WKT or trailing input"; + if value.contains('\0') { + return Err(invalid); + } + let type_end = value + .find(|c: char| !c.is_ascii_alphabetic()) + .unwrap_or(value.len()); + let mut body = value[type_end..].trim_start(); + let word_end = body + .find(|c: char| !c.is_ascii_alphabetic()) + .unwrap_or(body.len()); + if ["Z", "M", "ZM"] + .iter() + .any(|dim| body[..word_end].eq_ignore_ascii_case(dim)) + { + body = body[word_end..].trim_start(); + } + if body.eq_ignore_ascii_case("EMPTY") { + return Ok(()); + } + if !body.starts_with('(') { + return Err(invalid); + } + let mut depth = 0; + for (index, byte) in body.bytes().enumerate() { + match byte { + b'(' => depth += 1, + b')' => { + depth -= 1; + if depth == 0 { + return if body[index + 1..].trim().is_empty() { + Ok(()) + } else { + Err(invalid) + }; + } + } + _ => {} + } + } + Err(invalid) +} + /// The `wkt` parser currently rejects empty point members inside a /// `MULTIPOINT`, even though Databricks emits valid values such as /// `MULTIPOINT(EMPTY,(1 2))`. WKB represents an empty point as an all-NaN @@ -874,7 +1023,7 @@ fn split_ewkt(value: &str, fallback_srid: i32) -> std::result::Result<(i32, &str let srid_text = rest[..separator].trim(); let srid = srid_text .parse::() - .map_err(|error| format!("invalid SRID '{srid_text}': {error}"))?; + .map_err(|error| format!("invalid SRID: {error}"))?; let wkt_body = rest[separator + 1..].trim(); if wkt_body.is_empty() { return Err("WKT body is empty".to_string()); @@ -1623,6 +1772,213 @@ mod tests { assert_eq!(geom.value(0), ""); } + fn containers_with_geo_child(child: ArrayRef) -> Vec { + let field = Arc::new(Field::new("item", child.data_type().clone(), false)); + let nulls = Some(NullBuffer::from(vec![true, true, true, false, true, true])); + let offsets = OffsetBuffer::new(ScalarBuffer::from(vec![0_i32, 1, 2, 3, 4, 5, 6])); + let large_offsets = OffsetBuffer::new(ScalarBuffer::from(vec![0_i64, 1, 2, 3, 4, 5, 6])); + let entries = StructArray::new( + Fields::from(vec![ + Field::new("key", DataType::Int32, false), + Field::new("value", child.data_type().clone(), false), + ]), + vec![ + Arc::new(Int32Array::from(vec![0, 1, 2, 3, 4, 5])), + child.clone(), + ], + None, + ); + vec![ + Arc::new(ListArray::new( + field.clone(), + offsets.clone(), + child.clone(), + nulls.clone(), + )), + Arc::new(LargeListArray::new( + field.clone(), + large_offsets, + child.clone(), + nulls.clone(), + )), + Arc::new(ListViewArray::new( + field.clone(), + vec![0_i32, 1, 2, 3, 4, 5].into(), + vec![1_i32; 6].into(), + child.clone(), + nulls.clone(), + )), + Arc::new(LargeListViewArray::new( + field.clone(), + vec![0_i64, 1, 2, 3, 4, 5].into(), + vec![1_i64; 6].into(), + child.clone(), + nulls.clone(), + )), + Arc::new(FixedSizeListArray::new(field, 1, child, nulls.clone())), + Arc::new(MapArray::new( + Arc::new(Field::new("entries", entries.data_type().clone(), false)), + offsets, + entries, + nulls, + false, + )), + ] + } + + #[test] + fn container_nulls_and_slices_mask_invalid_geo_placeholders_in_both_modes() { + for family in [GeoFamily::Geometry, GeoFamily::Geography] { + let text: ArrayRef = Arc::new(StringArray::from(vec![ + "invalid outside slice", + "SRID=4326;POINT(1 2)", + "invalid under null struct", + "invalid under null container", + "SRID=4326;POINT(1 2)", + "invalid outside slice", + ])); + let DataType::Struct(fields) = geo_type(family, 4326) else { + unreachable!() + }; + let native: ArrayRef = Arc::new(StructArray::new( + fields, + vec![ + Arc::new(Int32Array::from(vec![4326; 6])), + Arc::new(BinaryArray::from(vec![ + &b""[..], + POINT_1_2_WKB, + &b""[..], + &b""[..], + POINT_1_2_WKB, + &b""[..], + ])), + ], + None, + )); + + for (source, target) in [(text.clone(), native.clone()), (native, text)] { + for (container, target_container) in containers_with_geo_child(source.clone()) + .into_iter() + .zip(containers_with_geo_child(target.clone())) + { + let parent: ArrayRef = Arc::new(StructArray::new( + Fields::from(vec![Field::new("g", container.data_type().clone(), true)]), + vec![container], + Some(NullBuffer::from(vec![true, true, false, true, true, true])), + )); + let output_type = DataType::Struct(Fields::from(vec![Field::new( + "g", + target_container.data_type().clone(), + true, + )])); + let output = rewrite(&parent.slice(1, 4), &output_type, "value").unwrap(); + let parent = output.as_any().downcast_ref::().unwrap(); + assert_eq!(parent.null_count(), 1); + assert!(parent.is_null(1)); + let container = parent.column(0); + assert_eq!(container.null_count(), 1); + assert!(container.is_null(2)); + let child = match container.data_type() { + DataType::List(_) => container + .as_any() + .downcast_ref::() + .unwrap() + .values(), + DataType::LargeList(_) => container + .as_any() + .downcast_ref::() + .unwrap() + .values(), + DataType::ListView(_) => container + .as_any() + .downcast_ref::() + .unwrap() + .values(), + DataType::LargeListView(_) => container + .as_any() + .downcast_ref::() + .unwrap() + .values(), + DataType::FixedSizeList(_, _) => container + .as_any() + .downcast_ref::() + .unwrap() + .values(), + DataType::Map(_, _) => container + .as_any() + .downcast_ref::() + .unwrap() + .entries() + .column(1), + _ => unreachable!(), + }; + assert_eq!( + child.null_count(), + 0, + "non-nullable child stays non-nullable" + ); + if let Some(values) = child.as_any().downcast_ref::() { + assert_eq!( + values + .iter() + .filter(|value| *value == Some("SRID=4326;POINT(1 2)")) + .count(), + 2 + ); + } else { + let values = child + .as_any() + .downcast_ref::() + .unwrap() + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!( + values + .iter() + .filter(|value| *value == Some(POINT_1_2_WKB)) + .count(), + 2 + ); + } + } + } + } + } + + #[test] + fn overlapping_list_view_ranges_keep_children_referenced_by_valid_rows() { + let child: ArrayRef = Arc::new(StringArray::from(vec!["ignored", "POINT(1 2)", "ignored"])); + let list: ArrayRef = Arc::new(ListViewArray::new( + Arc::new(Field::new("item", DataType::Utf8, false)), + vec![1, 0, 1].into(), + vec![1, 3, 1].into(), + child, + Some(NullBuffer::from(vec![true, false, true])), + )); + let output_type = DataType::ListView(Arc::new(Field::new( + "item", + geo_type(GeoFamily::Geometry, 0), + false, + ))); + let output = rewrite(&list, &output_type, "g").unwrap(); + let list = output.as_any().downcast_ref::().unwrap(); + let values = list + .values() + .as_any() + .downcast_ref::() + .unwrap(); + let wkbs = values + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(wkbs.value(0), b""); + assert_eq!(wkbs.value(1), POINT_1_2_WKB); + assert_eq!(wkbs.value(2), b""); + } + #[test] fn non_nullable_untagged_nested_geo_is_recovered_in_both_modes() { let DataType::Struct(plain_fields) = plain_geo_type() else { @@ -1738,6 +2094,12 @@ mod tests { fn text_to_native_handles_every_ogc_family_dimensions_and_empties() { let cases = [ "POINT EMPTY", + "POINT Z EMPTY", + "POINT M EMPTY", + "POINT ZM EMPTY", + "LINESTRING Z EMPTY", + "POLYGON M EMPTY", + "GEOMETRYCOLLECTION ZM EMPTY", "POINT Z (1 2 3)", "LINESTRING M (0 1 2,3 4 5)", "POLYGON ZM ((0 0 1 2,0 1 2 3,1 0 3 4,0 0 1 2))", @@ -1772,10 +2134,18 @@ mod tests { #[test] fn malformed_text_is_reported_as_data_loss_without_echoing_the_value() { for value in [ - "SRID=invalid;POINT(1 2)", + "SRID=sensitive_srid_marker;POINT(1 2)", "SRID=4326POINT(1 2)", "SRID=4326;", "not sensitive result contents", + "POINT(1 2))", + "POINT(1 2)POINT(3 4)", + "POINT EMPTY trailing", + "POINT EMPTY(1 2)", + "POINT Z EMPTY POINT Z (1 2 3)", + "POINT(1 2)\0ignored", + "GEOMETRYCOLLECTION(POINT EMPTY))", + "GEOMETRYCOLLECTION(POINT(1 2)", ] { let array: ArrayRef = Arc::new(StringArray::from(vec![value])); let error = @@ -1783,6 +2153,10 @@ mod tests { assert_eq!(error.code, crate::kernel_error::ErrorCode::DataLoss); assert!(error.message.contains("'geometry' row 0"), "{error:?}"); assert!(!error.message.contains(value), "{error:?}"); + assert!( + !error.message.contains("sensitive_srid_marker"), + "{error:?}" + ); } } From 576915ef56cfccfa7bfef869347c0c15b77e09b4 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 15 Oct 2026 21:37:13 +0000 Subject: [PATCH 5/8] fix: parse NOT NULL on nested geospatial manifest fields Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/metadata/type_mapping.rs | 99 ++++++++++++++++++++++++++++++-- src/reader/post_processor/mod.rs | 75 +++++++++++++++++++++++- 2 files changed, 169 insertions(+), 5 deletions(-) diff --git a/src/metadata/type_mapping.rs b/src/metadata/type_mapping.rs index d0f459c2..c7710b1f 100644 --- a/src/metadata/type_mapping.rs +++ b/src/metadata/type_mapping.rs @@ -388,8 +388,7 @@ fn parse_map( } /// Parse `STRUCT` into `Struct(Fields::from([Field; N]))`. -/// Each child field is nullable (SEA's manifest doesn't carry per-field -/// nullability) — same convention used elsewhere in the kernel. +/// Fields are nullable unless SEA's type text includes a `NOT NULL` qualifier. fn parse_struct( s: &str, type_interval_type: Option<&str>, @@ -407,7 +406,7 @@ fn parse_struct( // composites (none today, but be defensive). let colon_idx = depth_zero_colon(part)?; let name = part[..colon_idx].trim(); - let type_text = part[colon_idx + 1..].trim(); + let (type_text, nullable) = struct_field_nullability(part[colon_idx + 1..].trim()); if name.is_empty() { return None; } @@ -417,11 +416,27 @@ fn parse_struct( geospatial_representation, depth + 1, )?; - fields.push(Field::new(name, dt, true)); + fields.push(Field::new(name, dt, nullable)); } Some(DataType::Struct(Fields::from(fields))) } +/// Remove only a complete, whitespace-delimited `NOT NULL` field suffix. +/// In particular, leave malformed/trailing geospatial qualifiers for the strict +/// type parser to reject rather than assigning them canonical Arrow tags. +fn struct_field_nullability(type_text: &str) -> (&str, bool) { + if let Some((prefix, null)) = type_text.rsplit_once(char::is_whitespace) { + if null.eq_ignore_ascii_case("NULL") { + if let Some((sql_type, not)) = prefix.trim_end().rsplit_once(char::is_whitespace) { + if not.eq_ignore_ascii_case("NOT") { + return (sql_type.trim_end(), false); + } + } + } + } + (type_text, true) +} + /// Native Arrow representation emitted by DBR and Reyden. /// /// Besides the `struct` layout, the `wkb` child carries the exact @@ -831,6 +846,82 @@ mod tests { assert_eq!(string_items.data_type(), &DataType::Utf8); } + #[test] + fn test_nested_geospatial_fields_with_not_null_qualifiers() { + for representation in [ + GeospatialResultRepresentation::Binary, + GeospatialResultRepresentation::String, + ] { + let geo = + |sql_type| databricks_type_to_arrow_with_options(sql_type, None, representation); + let expected = DataType::Struct(Fields::from(vec![ + Field::new("geom", geo("GEOMETRY(ANY)"), false), + Field::new( + "arr", + DataType::List(Arc::new(Field::new_list_field( + DataType::Struct(Fields::from(vec![Field::new( + "g", + geo("GEOGRAPHY(4326)"), + false, + )])), + true, + ))), + false, + ), + Field::new( + "map", + DataType::Map( + Arc::new(Field::new( + "entries", + DataType::Struct(Fields::from(vec![ + Field::new("key", DataType::Utf8, false), + Field::new( + "value", + DataType::Struct(Fields::from(vec![Field::new( + "g", + geo("GEOMETRY(0)"), + false, + )])), + true, + ), + ])), + false, + )), + false, + ), + true, + ), + Field::new("blob", DataType::Binary, false), + Field::new("amount", DataType::Decimal128(10, 2), true), + ])); + assert_eq!( + geo("STRUCT> NOT NULL, \ + map: MAP>, \ + blob: BINARY NOT NULL, amount: DECIMAL(10,2)>"), + expected, + ); + } + + for invalid in [ + "GEOMETRY(0) NOTNULL", + "GEOMETRY(0)NOT NULL", + "GEOMETRY(0) NOT NOT NULL", + "GEOMETRY(0) NOT NULL trailing", + "GEOMETRY(garbage) NOT NULL", + ] { + assert_eq!( + databricks_type_to_arrow_with_options( + &format!("STRUCT"), + None, + GeospatialResultRepresentation::Binary, + ), + DataType::Utf8, + "malformed field type must not acquire geospatial tags: {invalid}", + ); + } + } + #[test] fn test_databricks_type_to_arrow_array_nested() { // ARRAY → List. Field name is "item" — the diff --git a/src/reader/post_processor/mod.rs b/src/reader/post_processor/mod.rs index 2475922c..1f5c136b 100644 --- a/src/reader/post_processor/mod.rs +++ b/src/reader/post_processor/mod.rs @@ -459,7 +459,9 @@ mod tests { use arrow_array::builder::{ BinaryBuilder, Int32Builder, ListBuilder, MapBuilder, StringBuilder, }; - use arrow_array::{Array, Int32Array, ListArray, MapArray, StringArray, StructArray}; + use arrow_array::{ + Array, BinaryArray, Int32Array, ListArray, MapArray, StringArray, StructArray, + }; use arrow_buffer::{NullBuffer, OffsetBuffer, ScalarBuffer}; use arrow_schema::Fields; @@ -1063,4 +1065,75 @@ mod tests { assert_eq!(value(1), "{\"g\":\"POINT(1 2)\"}"); assert_eq!(value(2), "{\"k\":\"SRID=4326;POINT(1 2)\"}"); } + + #[tokio::test] + async fn manifest_not_null_geo_text_is_converted_without_changing_siblings() { + let blob: ArrayRef = Arc::new(BinaryArray::from(vec![&b"\x00\x80\xff"[..]; 2])); + let timestamp: ArrayRef = Arc::new( + arrow_array::TimestampMicrosecondArray::from(vec![1234567_i64, 7654321]) + .with_timezone("Etc/UTC"), + ); + let fields = Fields::from(vec![ + Field::new("geom", DataType::Utf8, false), + Field::new("blob", DataType::Binary, false), + Field::new("ts", timestamp.data_type().clone(), false), + ]); + let values = StructArray::new( + fields.clone(), + vec![ + Arc::new(StringArray::from(vec![ + "POINT(1 2)", + "SRID=3857;POINT(1 2)", + ])), + blob.clone(), + timestamp.clone(), + ], + None, + ); + let schema = Arc::new(Schema::new(vec![Field::new( + "col_0", + DataType::Struct(fields), + true, + )])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(values)]).unwrap(); + let manifest = make_manifest(vec![column_info( + "value", + "STRUCT", + "STRUCT", + 0, + )]); + let mut pp = ResultPostProcessor::new( + Box::new(MockReader::new(vec![batch])), + Some(&manifest), + PostProcessOptions::default(), + ) + .await + .unwrap(); + let advertised = pp.schema().await.unwrap(); + let out = pp.next_batch().await.unwrap().unwrap(); + assert_eq!(out.schema(), advertised); + let values = out + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + let geo = values + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + let srids = geo.column(0).as_any().downcast_ref::().unwrap(); + assert_eq!(srids.values(), &[0, 3857]); + let wkb = geo + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(wkb.value(0), POINT_1_2_WKB); + assert_eq!(wkb.value(1), POINT_1_2_WKB); + assert!(Arc::ptr_eq(values.column(1), &blob)); + assert!(Arc::ptr_eq(values.column(2), ×tamp)); + assert!(!values.fields()[0].is_nullable()); + assert!(pp.next_batch().await.unwrap().is_none()); + } } From 1adf2484567109aa2a28d26232ae8476cd79ac3a Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 15 Oct 2026 22:09:37 +0000 Subject: [PATCH 6/8] test: use canonical list child naming in geospatial regression Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/metadata/type_mapping.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/metadata/type_mapping.rs b/src/metadata/type_mapping.rs index c7710b1f..5fb00b1a 100644 --- a/src/metadata/type_mapping.rs +++ b/src/metadata/type_mapping.rs @@ -854,11 +854,17 @@ mod tests { ] { let geo = |sql_type| databricks_type_to_arrow_with_options(sql_type, None, representation); + // Array child naming is independent of geospatial/nullability + // parsing; use the kernel's current convention for this assertion. + let DataType::List(list_field) = geo("ARRAY") else { + panic!("expected list") + }; let expected = DataType::Struct(Fields::from(vec![ Field::new("geom", geo("GEOMETRY(ANY)"), false), Field::new( "arr", - DataType::List(Arc::new(Field::new_list_field( + DataType::List(Arc::new(Field::new( + list_field.name(), DataType::Struct(Fields::from(vec![Field::new( "g", geo("GEOGRAPHY(4326)"), From ea41d163aef81fc41eb0363da93e5c941a9e8638 Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Fri, 16 Oct 2026 00:05:17 +0000 Subject: [PATCH 7/8] fix: keep geospatial parser details out of result errors Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> --- src/reader/post_processor/geospatial.rs | 33 +++++++++++++++++-------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/src/reader/post_processor/geospatial.rs b/src/reader/post_processor/geospatial.rs index 5223a55b..ee87178a 100644 --- a/src/reader/post_processor/geospatial.rs +++ b/src/reader/post_processor/geospatial.rs @@ -816,17 +816,11 @@ fn ewkt_values_to_native<'a>( .map_err(|detail| malformed_text(path, row, &format!("has invalid EWKT: {detail}")))?; validate_wkt_boundary(wkt_body).map_err(|detail| malformed_text(path, row, detail))?; let normalized = normalize_multipoint_empty_members(wkt_body); - let geometry = wkt::Wkt::::from_str(&normalized).map_err(|error| { - malformed_text(path, row, &format!("contains invalid WKT: {error}")) - })?; + let geometry = wkt::Wkt::::from_str(&normalized) + .map_err(|_| malformed_text(path, row, "contains invalid WKT"))?; let mut wkb = Vec::with_capacity(wkb::writer::geometry_wkb_size(&geometry)); - wkb::writer::write_geometry(&mut wkb, &geometry, &Default::default()).map_err(|error| { - malformed_text( - path, - row, - &format!("could not be encoded as OGC WKB: {error}"), - ) - })?; + wkb::writer::write_geometry(&mut wkb, &geometry, &Default::default()) + .map_err(|_| malformed_text(path, row, "could not be encoded as OGC WKB"))?; srids.append_value(srid); wkbs.append_value(wkb); @@ -2160,6 +2154,25 @@ mod tests { } } + #[test] + fn malformed_wkt_body_errors_do_not_echo_result_contents() { + for value in [ + "POINT(sensitive_coordinate 2)", + "GEOMETRYCOLLECTION(POINT(1 sensitive_coordinate))", + ] { + // These pass boundary validation and fail inside the third-party parser. + validate_wkt_boundary(value).unwrap(); + assert!(wkt::Wkt::::from_str(value).is_err()); + let array: ArrayRef = Arc::new(StringArray::from(vec![value])); + let error = + rewrite(&array, &geo_type(GeoFamily::Geometry, -1), "geometry").unwrap_err(); + assert_eq!(error.code, crate::kernel_error::ErrorCode::DataLoss); + assert!(error.message.contains("'geometry' row 0"), "{error:?}"); + assert!(error.message.contains("contains invalid WKT"), "{error:?}"); + assert!(!error.message.contains("sensitive_coordinate"), "{error:?}"); + } + } + #[test] fn invalid_wkb_is_reported_as_data_loss() { let DataType::Struct(fields) = geo_type(GeoFamily::Geometry, 0) else { From 4516fa5eebf71293a95c830f47d3246b2990ef00 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 16 Oct 2026 20:08:03 +0000 Subject: [PATCH 8/8] fix: default unprefixed geography text to SRID 4326 Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/reader/post_processor/geospatial.rs | 147 ++++++++++++++---------- 1 file changed, 85 insertions(+), 62 deletions(-) diff --git a/src/reader/post_processor/geospatial.rs b/src/reader/post_processor/geospatial.rs index ee87178a..cdf3f6c5 100644 --- a/src/reader/post_processor/geospatial.rs +++ b/src/reader/post_processor/geospatial.rs @@ -488,7 +488,7 @@ fn rewrite_array( ) -> Result { if let Some(output_tag) = native_geo_tag(output_type)? { if matches!(array.data_type(), DataType::Utf8 | DataType::LargeUtf8) { - return text_to_native(array, output_type, output_tag.srid, path, parent_validity); + return text_to_native(array, output_type, output_tag, path, parent_validity); } validate_geo_source(array.data_type(), output_tag, path)?; if array.data_type() == output_type { @@ -746,7 +746,7 @@ fn container_child_validity( fn text_to_native( array: &ArrayRef, output_type: &DataType, - type_srid: i32, + tag: GeoTag, path: &str, parent_validity: Option<&NullBuffer>, ) -> Result { @@ -761,7 +761,7 @@ fn text_to_native( values.iter(), values.len(), output_fields, - type_srid, + tag, path, parent_validity, ) @@ -772,7 +772,7 @@ fn text_to_native( values.iter(), values.len(), output_fields, - type_srid, + tag, path, parent_validity, ) @@ -787,14 +787,21 @@ fn ewkt_values_to_native<'a>( values: impl Iterator>, len: usize, output_fields: &Fields, - type_srid: i32, + tag: GeoTag, path: &str, parent_validity: Option<&NullBuffer>, ) -> Result { let mut srids = Int32Builder::with_capacity(len); let mut wkbs = BinaryBuilder::with_capacity(len, len.saturating_mul(32)); let mut nulls = NullBufferBuilder::new(len); - let fallback_srid = if type_srid >= 0 { type_srid } else { 0 }; + let fallback_srid = if tag.srid >= 0 { + tag.srid + } else { + match tag.family { + GeoFamily::Geography => 4326, + GeoFamily::Geometry => 0, + } + }; for (row, value) in values.enumerate() { if parent_validity.is_some_and(|validity| validity.is_null(row)) { @@ -996,7 +1003,7 @@ fn skip_ascii_whitespace(bytes: &[u8], mut index: usize) -> usize { /// Split a standard-warehouse WKT / EWKT value into its row SRID and WKT /// body. An absent prefix uses the fixed logical SRID when one exists; `ANY` -/// columns use zero because their type does not supply a row SRID. +/// columns use the family default (4326 for geography, zero for geometry). fn split_ewkt(value: &str, fallback_srid: i32) -> std::result::Result<(i32, &str), String> { let value = value.trim(); if value.is_empty() { @@ -1660,23 +1667,36 @@ mod tests { } #[test] - fn unprefixed_text_uses_fixed_type_srid_and_any_uses_zero() { - for (type_srid, expected_row_srid) in [(4326, 4326), (-1, 0)] { - let array: ArrayRef = Arc::new(StringArray::from(vec!["POINT (1 2)"])); - let output = rewrite( - &array, - &geo_type(GeoFamily::Geography, type_srid), - "geography", - ) - .unwrap(); - let output = output.as_any().downcast_ref::().unwrap(); - let srids = output - .column_by_name("srid") - .unwrap() - .as_any() - .downcast_ref::() - .unwrap(); - assert_eq!(srids.value(0), expected_row_srid); + fn unprefixed_text_uses_fixed_srid_or_family_default() { + for (family, type_srid, expected_row_srid) in [ + (GeoFamily::Geography, 4326, 4326), + (GeoFamily::Geography, -1, 4326), + (GeoFamily::Geometry, 0, 0), + (GeoFamily::Geometry, 3857, 3857), + (GeoFamily::Geometry, -1, 0), + ] { + for array in [ + Arc::new(StringArray::from(vec![Some("POINT (1 2)"), None])) as ArrayRef, + Arc::new(LargeStringArray::from(vec![Some("POINT (1 2)"), None])) as ArrayRef, + ] { + let output = rewrite(&array, &geo_type(family, type_srid), "g").unwrap(); + let output = output.as_any().downcast_ref::().unwrap(); + assert!(output.is_null(1)); + let srids = output + .column_by_name("srid") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(srids.value(0), expected_row_srid); + let wkbs = output + .column_by_name("wkb") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(wkbs.value(0), POINT_1_2_WKB); + } } } @@ -2042,46 +2062,49 @@ mod tests { } #[test] - fn text_geometry_converts_to_native_inside_nested_container() { - let values: ArrayRef = - Arc::new(StringArray::from(vec![Some("SRID=3857;POINT(1 2)"), None])); - let list: ArrayRef = Arc::new(ListArray::new( - Arc::new(Field::new("item", DataType::Utf8, true)), - OffsetBuffer::new(ScalarBuffer::from(vec![0_i32, 2, 2])), - values, - Some(NullBuffer::from(vec![true, false])), - )); - let output_type = DataType::List(Arc::new(Field::new( - "item", - geo_type(GeoFamily::Geometry, -1), - true, - ))); + fn text_geo_converts_to_native_inside_nested_container() { + for (family, text, expected_srid) in [ + (GeoFamily::Geometry, "SRID=3857;POINT(1 2)", 3857), + (GeoFamily::Geometry, "POINT(1 2)", 0), + (GeoFamily::Geography, "SRID=4326;POINT(1 2)", 4326), + (GeoFamily::Geography, "POINT(1 2)", 4326), + ] { + let values: ArrayRef = Arc::new(StringArray::from(vec![Some(text), None])); + let list: ArrayRef = Arc::new(ListArray::new( + Arc::new(Field::new("item", DataType::Utf8, true)), + OffsetBuffer::new(ScalarBuffer::from(vec![0_i32, 2, 2])), + values, + Some(NullBuffer::from(vec![true, false])), + )); + let output_type = + DataType::List(Arc::new(Field::new("item", geo_type(family, -1), true))); - let output = rewrite(&list, &output_type, "nested_geometry").unwrap(); - let output = output.as_any().downcast_ref::().unwrap(); - assert_eq!(output.data_type(), &output_type); - assert!(output.is_null(1)); + let output = rewrite(&list, &output_type, "nested_geo").unwrap(); + let output = output.as_any().downcast_ref::().unwrap(); + assert_eq!(output.data_type(), &output_type); + assert!(output.is_null(1)); - let values = output - .values() - .as_any() - .downcast_ref::() - .unwrap(); - assert!(values.is_null(1)); - let srids = values - .column_by_name("srid") - .unwrap() - .as_any() - .downcast_ref::() - .unwrap(); - let wkbs = values - .column_by_name("wkb") - .unwrap() - .as_any() - .downcast_ref::() - .unwrap(); - assert_eq!(srids.value(0), 3857); - assert_eq!(wkbs.value(0), POINT_1_2_WKB); + let values = output + .values() + .as_any() + .downcast_ref::() + .unwrap(); + assert!(values.is_null(1)); + let srids = values + .column_by_name("srid") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + let wkbs = values + .column_by_name("wkb") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(srids.value(0), expected_srid); + assert_eq!(wkbs.value(0), POINT_1_2_WKB); + } } #[test]