From 222b4295126874fb8e6bf9e6f16b6d0df369f436 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Thu, 22 Oct 2026 04:29:02 +0000 Subject: [PATCH 1/5] fix(reader): preserve result column nullability Signed-off-by: Vu Anh Phung --- docs/designs/result-metadata-propagation.md | 14 ++-- src/reader/mod.rs | 68 +++++++++++++++- src/reader/post_processor/mod.rs | 61 +++++++++++--- src/types/sea.rs | 26 +++++- tests/v0_execute_wiremock.rs | 88 +++++++++++++++++++++ 5 files changed, 239 insertions(+), 18 deletions(-) diff --git a/docs/designs/result-metadata-propagation.md b/docs/designs/result-metadata-propagation.md index cb453458..7fb3e6c4 100644 --- a/docs/designs/result-metadata-propagation.md +++ b/docs/designs/result-metadata-propagation.md @@ -120,6 +120,11 @@ databricks.type_interval_type "YEAR_MONTH" (optional, for INTERVAL types) These keys are additive — they don't conflict with any existing Arrow metadata conventions. Values are string-encoded because Arrow field metadata is `HashMap`. +Manifest `nullable` overrides the Arrow field's nullability when provided. If it is +absent or null, the physical Arrow value is preserved; empty results without an +Arrow schema default to nullable. Nullability survives result type conversions +and propagates to the advertised schema and returned batches. + --- ## Detailed Design @@ -376,12 +381,11 @@ std::string AdbcResultSetMetadata::GetTypeName(int column_position, int16_t data | `databricks.type_text` | Full type text including parameters ("DECIMAL(10,2)", "ARRAY") | | `databricks.type_precision` | Correct DECIMAL precision from server, not Arrow physical type | | `databricks.type_scale` | Correct DECIMAL scale from server | -| (nullable default) | Default to SQL_NULLABLE for all result columns (matches JDBC) | +| Manifest `nullable` | Propagated through the Arrow field's nullability | -The nullable fix is a policy change in the ODBC driver (default to NULLABLE) rather than -a metadata propagation issue — the SEA manifest doesn't include per-column nullability either. -The JDBC driver simply defaults all result columns to NULLABLE, which is the correct semantic -for query results (any expression can return NULL). +Consumers can read nullability from the Arrow field. When the manifest omits it, +the kernel preserves physical Arrow nullability, or defaults to nullable if no +physical schema is available. --- diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 87aef6e4..c0c5cfa1 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -438,7 +438,7 @@ impl ResultReaderFactory { col.type_interval_type.as_deref(), GeospatialResultRepresentation::Binary, ); - Field::new(&col.name, data_type, true) // nullable by default + Field::new(&col.name, data_type, col.nullable.unwrap_or(true)) }) .collect(); @@ -934,6 +934,7 @@ impl ResultReaderAdapter { /// precision, scale, interval_type) for the Arrow C Data FFI boundary; /// - attach the Thrift-compatible `Spark:DataType:SqlName` (= type_text). /// - attach `Spark:DataType:JsonType` when the manifest provides `type_json`. + /// - apply manifest nullability when provided. /// /// Fields with no matching `ColumnInfo` are left unchanged. pub(crate) fn augment_schema_with_manifest( @@ -997,6 +998,7 @@ impl ResultReaderAdapter { .as_ref() .clone() .with_name(info.name.clone()) + .with_nullable(info.nullable.unwrap_or(field.is_nullable())) .with_metadata(metadata) } None => field.as_ref().clone(), @@ -1435,6 +1437,7 @@ mod tests { type_scale: scale, type_interval_type: interval_type.map(|s| s.to_string()), type_json: None, + nullable: None, } } @@ -1699,6 +1702,69 @@ mod tests { ); } + #[test] + fn test_augment_schema_applies_optional_nullability_by_position() { + for nullable in [Some(false), Some(true), None] { + for physical_nullable in [false, true] { + let field_metadata = std::collections::HashMap::from([( + "custom.key".to_string(), + "preserved".to_string(), + )]); + let schema = Arc::new(Schema::new_with_metadata( + vec![ + Field::new("col_0", DataType::Int32, physical_nullable) + .with_metadata(field_metadata.clone()), + Field::new("col_1", DataType::Utf8, true), + Field::new("unmatched", DataType::Int64, false) + .with_metadata(field_metadata), + ], + std::collections::HashMap::from([( + "schema.key".to_string(), + "preserved".to_string(), + )]), + )); + let mut column = make_column_info("id", "INT", "INT", 0, None, None, None); + column.nullable = nullable; + let manifest = make_manifest(vec![ + make_column_info("name", "STRING", "STRING", 1, None, None, None), + column, + ]); + + let augmented = + ResultReaderAdapter::augment_schema_with_manifest(&schema, &manifest); + let field = augmented.field(0); + assert_eq!(field.name(), "id"); + assert_eq!(field.is_nullable(), nullable.unwrap_or(physical_nullable)); + assert_eq!( + field.metadata().get("custom.key").map(String::as_str), + Some("preserved"), + ); + assert!(augmented.field(1).is_nullable()); + assert_eq!(augmented.field(2), schema.field(2)); + assert_eq!(augmented.metadata(), schema.metadata()); + } + } + } + + #[test] + fn test_extract_logical_schema_uses_manifest_nullability() { + let mut required = make_column_info("required", "INT", "INT", 0, None, None, None); + required.nullable = Some(false); + let mut optional = make_column_info("optional", "INT", "INT", 1, None, None, None); + optional.nullable = Some(true); + let manifest = make_manifest(vec![ + required, + optional, + make_column_info("unknown", "INT", "INT", 2, None, None, None), + ]); + + let schema = + ResultReaderFactory::extract_logical_schema_from_manifest(Some(&manifest)).unwrap(); + assert!(!schema.field(0).is_nullable()); + assert!(schema.field(1).is_nullable()); + assert!(schema.field(2).is_nullable()); + } + #[test] fn test_augment_schema_preserves_geospatial_identity_and_srid() { let binary_geo = DataType::Struct(Fields::from(vec![ diff --git a/src/reader/post_processor/mod.rs b/src/reader/post_processor/mod.rs index 3006ef59..2e7b1c2b 100644 --- a/src/reader/post_processor/mod.rs +++ b/src/reader/post_processor/mod.rs @@ -173,13 +173,11 @@ impl ResultPostProcessor { { json_columns.push(i); schema_changed = true; - Field::new(field.name(), DataType::Utf8, true) - .with_metadata(field.metadata().clone()) + normalized_field.clone().with_data_type(DataType::Utf8) } else if options.intervals_as_string && is_interval_or_duration_type(normalized_type) { interval_columns.push(i); schema_changed = true; - Field::new(field.name(), DataType::Utf8, true) - .with_metadata(field.metadata().clone()) + normalized_field.clone().with_data_type(DataType::Utf8) } else if matches!(normalized_type, DataType::Null) { // Untyped NULL (`SELECT NULL` / VOID) arrives as an Arrow // `Null`-typed column, but the server reports it as STRING @@ -193,8 +191,7 @@ impl ResultPostProcessor { // (DATATYPE-041). null_columns.push(i); schema_changed = true; - Field::new(field.name(), DataType::Utf8, true) - .with_metadata(field.metadata().clone()) + normalized_field.clone().with_data_type(DataType::Utf8) } else { normalized_field.clone() }; @@ -306,9 +303,7 @@ impl ResultReader for ResultPostProcessor { } /// Compare schemas by their field sequence including per-field -/// metadata. Faster than serialising both sides; sufficient because -/// the augmenter only rewrites `Field::metadata` (and the JSON path -/// rewrites field type, which `Field::eq` already covers). +/// metadata, names, and nullability. `Field::eq` also covers rewritten types. fn schemas_field_equal(a: &SchemaRef, b: &SchemaRef) -> bool { if Arc::ptr_eq(a, b) { return true; @@ -493,6 +488,7 @@ mod tests { type_scale: None, type_interval_type: None, type_json: None, + nullable: None, } } @@ -585,6 +581,53 @@ mod tests { ); } + #[tokio::test] + async fn manifest_nullability_survives_type_conversions() { + for nullable in [false, true] { + let mut lists = ListBuilder::new(Int32Builder::new()); + lists.values().append_value(42); + lists.append(true); + let lists = lists.finish(); + let intervals = arrow_array::DurationMicrosecondArray::from(vec![1_000_000]); + let schema = Arc::new(Schema::new(vec![ + Field::new("col_0", lists.data_type().clone(), !nullable), + Field::new("col_1", intervals.data_type().clone(), !nullable), + ])); + let batch = + RecordBatch::try_new(schema, vec![Arc::new(lists) as _, Arc::new(intervals) as _]) + .unwrap(); + let inner = Box::new(MockReader::new(vec![batch.clone(), batch])); + let mut columns = vec![ + column_info("values", "ARRAY", "ARRAY", 0), + column_info("duration", "INTERVAL", "INTERVAL DAY TO SECOND", 1), + ]; + for column in &mut columns { + column.nullable = Some(nullable); + } + let manifest = make_manifest(columns); + let options = PostProcessOptions { + complex_types_as_json: true, + intervals_as_string: true, + ..Default::default() + }; + let mut processor = ResultPostProcessor::new(inner, Some(&manifest), options) + .await + .unwrap(); + let schema = processor.schema().await.unwrap(); + for field in schema.fields() { + assert_eq!(field.data_type(), &DataType::Utf8); + assert_eq!(field.is_nullable(), nullable); + } + let batch = processor.next_batch().await.unwrap().unwrap(); + assert_eq!(batch.schema(), schema); + let TryNextBatch::Ready(batch) = processor.try_next_batch().unwrap() else { + panic!("expected a buffered batch"); + }; + assert_eq!(batch.schema(), schema); + assert!(processor.next_batch().await.unwrap().is_none()); + } + } + #[tokio::test] async fn manifest_overlays_real_names_onto_positional_columns_and_batches() { // Real names must appear on both the advertised schema and the diff --git a/src/types/sea.rs b/src/types/sea.rs index 74d1ad97..177b987e 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -236,6 +236,8 @@ pub struct ColumnInfo { pub type_interval_type: Option, #[serde(default)] pub type_json: Option, + #[serde(default)] + pub nullable: Option, } /// Information about a result chunk (metadata only). @@ -844,7 +846,8 @@ mod tests { "position": 0, "type_precision": 10, "type_scale": 2, - "type_json": "\"decimal(10,2)\"" + "type_json": "\"decimal(10,2)\"", + "nullable": false }"#; let col: ColumnInfo = serde_json::from_str(json).unwrap(); @@ -856,6 +859,7 @@ mod tests { assert_eq!(col.type_scale, Some(2)); assert_eq!(col.type_interval_type, None); assert_eq!(col.type_json.as_deref(), Some("\"decimal(10,2)\"")); + assert_eq!(col.nullable, Some(false)); } #[test] @@ -873,20 +877,36 @@ mod tests { assert_eq!(col.type_scale, None); assert_eq!(col.type_interval_type, None); assert_eq!(col.type_json, None); + assert_eq!(col.nullable, None); } #[test] - fn test_column_info_with_null_json_type() { + fn test_column_info_with_null_optional_metadata() { let json = r#"{ "name": "id", "type_name": "INT", "type_text": "INT", "position": 0, - "type_json": null + "type_json": null, + "nullable": null }"#; let col: ColumnInfo = serde_json::from_str(json).unwrap(); assert_eq!(col.type_json, None); + assert_eq!(col.nullable, None); + } + + #[test] + fn test_column_info_with_nullable_true() { + let col: ColumnInfo = serde_json::from_value(serde_json::json!({ + "name": "value", + "type_name": "STRING", + "type_text": "STRING", + "position": 0, + "nullable": true, + })) + .unwrap(); + assert_eq!(col.nullable, Some(true)); } #[test] diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 60e3b4a3..38f476b9 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -698,6 +698,94 @@ async fn execute_succeeded_inline_returns_one_row() { exec.close().await.expect("close"); } +#[tokio::test] +async fn execute_preserves_manifest_nullability_across_result_readers() { + for mode in ["inline", "cloudfetch", "empty", "empty_with_arrow_schema"] { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + let schema = Arc::new(Schema::new(vec![ + Field::new("col_0", DataType::Int64, true), + Field::new("col_1", DataType::Utf8, false), + Field::new("col_2", DataType::Utf8, false), + ])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int64Array::from(vec![42])) as _, + Arc::new(StringArray::from(vec!["label"])) as _, + Arc::new(StringArray::from(vec!["legacy"])) as _, + ], + ) + .unwrap(); + let mut body: serde_json::Value = + serde_json::from_str(&succeeded_inline_body("stmt-metadata", &batch)).unwrap(); + body["manifest"]["schema"]["columns"] = json!([ + {"name": "id", "type_name": "BIGINT", "type_text": "BIGINT", "position": 0, + "nullable": false}, + {"name": "label", "type_name": "STRING", "type_text": "STRING", "position": 1, + "nullable": true}, + {"name": "legacy", "type_name": "STRING", "type_text": "STRING", "position": 2, + "nullable": null}, + ]); + match mode { + "cloudfetch" => { + let ipc = arrow_ipc_bytes(&batch); + body["result"] = json!({"external_links": [{ + "external_link": format!("{}/chunk.arrow", server.uri()), + "expiration": "2099-01-01T00:00:00.000Z", + "chunk_index": 0, "row_offset": 0, "row_count": 1, + "byte_count": ipc.len(), + }]}); + Mock::given(method("GET")) + .and(path("/chunk.arrow")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(ipc)) + .expect(1) + .mount(&server) + .await; + } + "empty" | "empty_with_arrow_schema" => { + body.as_object_mut().unwrap().remove("result"); + body["manifest"]["total_row_count"] = json!(0); + body["manifest"]["total_chunk_count"] = json!(0); + body["manifest"]["total_byte_count"] = json!(0); + if mode == "empty_with_arrow_schema" { + body["manifest"]["arrow_schema"] = + json!(STANDARD.encode(arrow_schema_ipc_bytes(&schema))); + } + } + _ => {} + } + mount_execute(&server, body.to_string()).await; + let session = open_session(&server).await; + let mut statement = session.statement(); + statement.spec().sql("SELECT id, label, legacy FROM values"); + let mut executed = statement.execute().await.expect("execute"); + let advertised = executed.result_stream_mut().schema(); + assert_eq!(advertised.field(0).name(), "id", "{mode}"); + assert!(!advertised.field(0).is_nullable(), "{mode}"); + assert!(advertised.field(1).is_nullable(), "{mode}"); + assert_eq!(advertised.field(2).is_nullable(), mode == "empty", "{mode}"); + let batches = drain(executed.result_stream_mut()).await; + if mode.starts_with("empty") { + assert!(batches.is_empty(), "{mode}"); + } else { + assert_eq!(batches.len(), 1, "{mode}"); + assert_eq!(batches[0].schema(), advertised, "{mode}"); + assert_eq!(batches[0].num_rows(), 1, "{mode}"); + assert_eq!( + batches[0] + .column(0) + .as_primitive::() + .value(0), + 42 + ); + } + executed.close().await.unwrap(); + } +} + #[tokio::test] async fn execute_geospatial_string_mode_uses_manifest_tags_for_untagged_arrow_ipc() { let server = MockServer::start().await; From e1b02077c9a1bfaf0d469ed975bede28874f6149 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Thu, 22 Oct 2026 21:22:22 +0000 Subject: [PATCH 2/5] fix(reader): keep converted null columns nullable Signed-off-by: Vu Anh Phung --- docs/designs/result-metadata-propagation.md | 4 +- src/reader/post_processor/mod.rs | 46 ++++++++++++++++++++- 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/docs/designs/result-metadata-propagation.md b/docs/designs/result-metadata-propagation.md index 7fb3e6c4..1f8a1f43 100644 --- a/docs/designs/result-metadata-propagation.md +++ b/docs/designs/result-metadata-propagation.md @@ -122,8 +122,8 @@ Values are string-encoded because Arrow field metadata is `HashMap Date: Thu, 22 Oct 2026 21:59:14 +0000 Subject: [PATCH 3/5] fix(reader): limit nullability fix to schema fallback Signed-off-by: Vu Anh Phung --- docs/designs/result-metadata-propagation.md | 12 +-- src/reader/mod.rs | 65 ------------ src/reader/post_processor/mod.rs | 104 ++------------------ tests/v0_execute_wiremock.rs | 6 +- 4 files changed, 15 insertions(+), 172 deletions(-) diff --git a/docs/designs/result-metadata-propagation.md b/docs/designs/result-metadata-propagation.md index 1f8a1f43..54e44efc 100644 --- a/docs/designs/result-metadata-propagation.md +++ b/docs/designs/result-metadata-propagation.md @@ -120,11 +120,6 @@ databricks.type_interval_type "YEAR_MONTH" (optional, for INTERVAL types) These keys are additive — they don't conflict with any existing Arrow metadata conventions. Values are string-encoded because Arrow field metadata is `HashMap`. -Manifest `nullable` overrides the Arrow field's nullability when provided. If it is -absent or null, the physical Arrow value is preserved; empty results without an -Arrow schema default to nullable. Nullability propagates through type conversions -to the advertised schema and returned batches; Null → Utf8 fields remain nullable. - --- ## Detailed Design @@ -381,11 +376,10 @@ std::string AdbcResultSetMetadata::GetTypeName(int column_position, int16_t data | `databricks.type_text` | Full type text including parameters ("DECIMAL(10,2)", "ARRAY") | | `databricks.type_precision` | Correct DECIMAL precision from server, not Arrow physical type | | `databricks.type_scale` | Correct DECIMAL scale from server | -| Manifest `nullable` | Propagated through the Arrow field's nullability | +| Manifest `nullable` | Used for empty results without `arrow_schema` | -Consumers can read nullability from the Arrow field. When the manifest omits it, -the kernel preserves physical Arrow nullability, or defaults to nullable if no -physical schema is available. +Result schemas retain Arrow nullability. Empty results without `arrow_schema` use +manifest `nullable`, defaulting to nullable when it is absent or null. --- diff --git a/src/reader/mod.rs b/src/reader/mod.rs index c0c5cfa1..213d2f1d 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -934,7 +934,6 @@ impl ResultReaderAdapter { /// precision, scale, interval_type) for the Arrow C Data FFI boundary; /// - attach the Thrift-compatible `Spark:DataType:SqlName` (= type_text). /// - attach `Spark:DataType:JsonType` when the manifest provides `type_json`. - /// - apply manifest nullability when provided. /// /// Fields with no matching `ColumnInfo` are left unchanged. pub(crate) fn augment_schema_with_manifest( @@ -998,7 +997,6 @@ impl ResultReaderAdapter { .as_ref() .clone() .with_name(info.name.clone()) - .with_nullable(info.nullable.unwrap_or(field.is_nullable())) .with_metadata(metadata) } None => field.as_ref().clone(), @@ -1702,69 +1700,6 @@ mod tests { ); } - #[test] - fn test_augment_schema_applies_optional_nullability_by_position() { - for nullable in [Some(false), Some(true), None] { - for physical_nullable in [false, true] { - let field_metadata = std::collections::HashMap::from([( - "custom.key".to_string(), - "preserved".to_string(), - )]); - let schema = Arc::new(Schema::new_with_metadata( - vec![ - Field::new("col_0", DataType::Int32, physical_nullable) - .with_metadata(field_metadata.clone()), - Field::new("col_1", DataType::Utf8, true), - Field::new("unmatched", DataType::Int64, false) - .with_metadata(field_metadata), - ], - std::collections::HashMap::from([( - "schema.key".to_string(), - "preserved".to_string(), - )]), - )); - let mut column = make_column_info("id", "INT", "INT", 0, None, None, None); - column.nullable = nullable; - let manifest = make_manifest(vec![ - make_column_info("name", "STRING", "STRING", 1, None, None, None), - column, - ]); - - let augmented = - ResultReaderAdapter::augment_schema_with_manifest(&schema, &manifest); - let field = augmented.field(0); - assert_eq!(field.name(), "id"); - assert_eq!(field.is_nullable(), nullable.unwrap_or(physical_nullable)); - assert_eq!( - field.metadata().get("custom.key").map(String::as_str), - Some("preserved"), - ); - assert!(augmented.field(1).is_nullable()); - assert_eq!(augmented.field(2), schema.field(2)); - assert_eq!(augmented.metadata(), schema.metadata()); - } - } - } - - #[test] - fn test_extract_logical_schema_uses_manifest_nullability() { - let mut required = make_column_info("required", "INT", "INT", 0, None, None, None); - required.nullable = Some(false); - let mut optional = make_column_info("optional", "INT", "INT", 1, None, None, None); - optional.nullable = Some(true); - let manifest = make_manifest(vec![ - required, - optional, - make_column_info("unknown", "INT", "INT", 2, None, None, None), - ]); - - let schema = - ResultReaderFactory::extract_logical_schema_from_manifest(Some(&manifest)).unwrap(); - assert!(!schema.field(0).is_nullable()); - assert!(schema.field(1).is_nullable()); - assert!(schema.field(2).is_nullable()); - } - #[test] fn test_augment_schema_preserves_geospatial_identity_and_srid() { let binary_geo = DataType::Struct(Fields::from(vec![ diff --git a/src/reader/post_processor/mod.rs b/src/reader/post_processor/mod.rs index d32328e9..a57b5d5d 100644 --- a/src/reader/post_processor/mod.rs +++ b/src/reader/post_processor/mod.rs @@ -173,11 +173,13 @@ impl ResultPostProcessor { { json_columns.push(i); schema_changed = true; - normalized_field.clone().with_data_type(DataType::Utf8) + Field::new(field.name(), DataType::Utf8, true) + .with_metadata(field.metadata().clone()) } else if options.intervals_as_string && is_interval_or_duration_type(normalized_type) { interval_columns.push(i); schema_changed = true; - normalized_field.clone().with_data_type(DataType::Utf8) + Field::new(field.name(), DataType::Utf8, true) + .with_metadata(field.metadata().clone()) } else if matches!(normalized_type, DataType::Null) { // Untyped NULL (`SELECT NULL` / VOID) arrives as an Arrow // `Null`-typed column, but the server reports it as STRING @@ -191,10 +193,8 @@ impl ResultPostProcessor { // (DATATYPE-041). null_columns.push(i); schema_changed = true; - normalized_field - .clone() - .with_data_type(DataType::Utf8) - .with_nullable(true) + Field::new(field.name(), DataType::Utf8, true) + .with_metadata(field.metadata().clone()) } else { normalized_field.clone() }; @@ -306,7 +306,9 @@ impl ResultReader for ResultPostProcessor { } /// Compare schemas by their field sequence including per-field -/// metadata, names, and nullability. `Field::eq` also covers rewritten types. +/// metadata. Faster than serialising both sides; sufficient because +/// the augmenter only rewrites `Field::metadata` (and the JSON path +/// rewrites field type, which `Field::eq` already covers). fn schemas_field_equal(a: &SchemaRef, b: &SchemaRef) -> bool { if Arc::ptr_eq(a, b) { return true; @@ -584,53 +586,6 @@ mod tests { ); } - #[tokio::test] - async fn manifest_nullability_survives_type_conversions() { - for nullable in [false, true] { - let mut lists = ListBuilder::new(Int32Builder::new()); - lists.values().append_value(42); - lists.append(true); - let lists = lists.finish(); - let intervals = arrow_array::DurationMicrosecondArray::from(vec![1_000_000]); - let schema = Arc::new(Schema::new(vec![ - Field::new("col_0", lists.data_type().clone(), !nullable), - Field::new("col_1", intervals.data_type().clone(), !nullable), - ])); - let batch = - RecordBatch::try_new(schema, vec![Arc::new(lists) as _, Arc::new(intervals) as _]) - .unwrap(); - let inner = Box::new(MockReader::new(vec![batch.clone(), batch])); - let mut columns = vec![ - column_info("values", "ARRAY", "ARRAY", 0), - column_info("duration", "INTERVAL", "INTERVAL DAY TO SECOND", 1), - ]; - for column in &mut columns { - column.nullable = Some(nullable); - } - let manifest = make_manifest(columns); - let options = PostProcessOptions { - complex_types_as_json: true, - intervals_as_string: true, - ..Default::default() - }; - let mut processor = ResultPostProcessor::new(inner, Some(&manifest), options) - .await - .unwrap(); - let schema = processor.schema().await.unwrap(); - for field in schema.fields() { - assert_eq!(field.data_type(), &DataType::Utf8); - assert_eq!(field.is_nullable(), nullable); - } - let batch = processor.next_batch().await.unwrap().unwrap(); - assert_eq!(batch.schema(), schema); - let TryNextBatch::Ready(batch) = processor.try_next_batch().unwrap() else { - panic!("expected a buffered batch"); - }; - assert_eq!(batch.schema(), schema); - assert!(processor.next_batch().await.unwrap().is_none()); - } - } - #[tokio::test] async fn manifest_overlays_real_names_onto_positional_columns_and_batches() { // Real names must appear on both the advertised schema and the @@ -737,47 +692,6 @@ mod tests { assert!(col.is_null(0)); } - #[tokio::test] - async fn non_nullable_null_ipc_column_becomes_nullable_utf8() { - let schema = Arc::new(Schema::new(vec![Field::new( - "untyped_null", - DataType::Null, - false, - )])); - let batch = RecordBatch::try_new( - schema.clone(), - vec![Arc::new(arrow_array::NullArray::new(2)) as _], - ) - .unwrap(); - let mut ipc = Vec::new(); - { - let mut writer = arrow_ipc::writer::StreamWriter::try_new(&mut ipc, &schema).unwrap(); - writer.write(&batch).unwrap(); - writer.finish().unwrap(); - } - let batch = arrow_ipc::reader::StreamReader::try_new(std::io::Cursor::new(ipc), None) - .unwrap() - .next() - .unwrap() - .unwrap(); - assert!(!batch.schema().field(0).is_nullable()); - let manifest = make_manifest(vec![column_info("untyped_null", "NULL", "VOID", 0)]); - - for manifest in [None, Some(&manifest)] { - let inner = Box::new(MockReader::new(vec![batch.clone()])); - let mut pp = ResultPostProcessor::new(inner, manifest, PostProcessOptions::default()) - .await - .unwrap(); - let advertised = pp.schema().await.unwrap(); - let out = pp.next_batch().await.unwrap().unwrap(); - assert_eq!(advertised.field(0).data_type(), &DataType::Utf8); - assert!(advertised.field(0).is_nullable()); - assert_eq!(out.schema(), advertised); - assert_eq!(out.num_rows(), 2); - assert_eq!(out.column(0).null_count(), 2); - } - } - #[tokio::test] async fn untyped_null_carries_manifest_metadata_and_real_name() { // The Null→Utf8 rewrite must compose with manifest augmentation: diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 38f476b9..6ec8ddcc 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -699,7 +699,7 @@ async fn execute_succeeded_inline_returns_one_row() { } #[tokio::test] -async fn execute_preserves_manifest_nullability_across_result_readers() { +async fn execute_uses_manifest_nullability_only_without_arrow_schema() { for mode in ["inline", "cloudfetch", "empty", "empty_with_arrow_schema"] { let server = MockServer::start().await; mount_create_session(&server).await; @@ -764,8 +764,8 @@ async fn execute_preserves_manifest_nullability_across_result_readers() { let mut executed = statement.execute().await.expect("execute"); let advertised = executed.result_stream_mut().schema(); assert_eq!(advertised.field(0).name(), "id", "{mode}"); - assert!(!advertised.field(0).is_nullable(), "{mode}"); - assert!(advertised.field(1).is_nullable(), "{mode}"); + assert_eq!(advertised.field(0).is_nullable(), mode != "empty", "{mode}"); + assert_eq!(advertised.field(1).is_nullable(), mode == "empty", "{mode}"); assert_eq!(advertised.field(2).is_nullable(), mode == "empty", "{mode}"); let batches = drain(executed.result_stream_mut()).await; if mode.starts_with("empty") { From 17403ae666bd1c43d43a6d4de58ec8d7745c8243 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Thu, 22 Oct 2026 22:48:19 +0000 Subject: [PATCH 4/5] fix(reader): restrict manifest nullability to empty readers Signed-off-by: Vu Anh Phung --- docs/designs/result-metadata-propagation.md | 4 +- src/reader/mod.rs | 36 ++++++++- tests/v0_execute_wiremock.rs | 90 +++++++++++++++++++-- 3 files changed, 118 insertions(+), 12 deletions(-) diff --git a/docs/designs/result-metadata-propagation.md b/docs/designs/result-metadata-propagation.md index 54e44efc..b407afd4 100644 --- a/docs/designs/result-metadata-propagation.md +++ b/docs/designs/result-metadata-propagation.md @@ -378,8 +378,8 @@ std::string AdbcResultSetMetadata::GetTypeName(int column_position, int16_t data | `databricks.type_scale` | Correct DECIMAL scale from server | | Manifest `nullable` | Used for empty results without `arrow_schema` | -Result schemas retain Arrow nullability. Empty results without `arrow_schema` use -manifest `nullable`, defaulting to nullable when it is absent or null. +Empty results without `arrow_schema` use manifest `nullable`, defaulting to nullable +when absent or null. Inline-streaming fallback schemas do not use manifest nullability. --- diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 213d2f1d..3ee1e7c4 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -177,7 +177,7 @@ impl ResultReaderFactory { statement_id, "Manifest reports total_chunk_count=0; short-circuiting to empty reader", ); - let schema = Self::extract_physical_schema_from_manifest(response.manifest.as_ref())?; + let schema = Self::extract_empty_schema_from_manifest(response.manifest.as_ref())?; return Ok(Box::new(EmptyReader::new(schema))); } @@ -373,8 +373,7 @@ impl ResultReaderFactory { "Using empty reader: no result data present for {:?} statement", response.status.state ); - let schema = - Self::extract_physical_schema_from_manifest(response.manifest.as_ref())?; + let schema = Self::extract_empty_schema_from_manifest(response.manifest.as_ref())?; Ok(Box::new(EmptyReader::new(schema))) } StatementState::Pending | StatementState::Running => Err(Error::invalid_state() @@ -438,7 +437,7 @@ impl ResultReaderFactory { col.type_interval_type.as_deref(), GeospatialResultRepresentation::Binary, ); - Field::new(&col.name, data_type, col.nullable.unwrap_or(true)) + Field::new(&col.name, data_type, true) // nullable by default }) .collect(); @@ -483,6 +482,35 @@ impl ResultReaderFactory { Ok(physical) } + /// Apply manifest nullability only to empty results without `arrow_schema`. + fn extract_empty_schema_from_manifest(manifest: Option<&ResultManifest>) -> Result { + let schema = Self::extract_physical_schema_from_manifest(manifest)?; + let Some(manifest) = manifest.filter(|manifest| { + manifest + .arrow_schema + .as_deref() + .unwrap_or_default() + .is_empty() + }) else { + return Ok(schema); + }; + let fields: Vec = schema + .fields() + .iter() + .zip(&manifest.schema.columns) + .map(|(field, column)| { + field + .as_ref() + .clone() + .with_nullable(column.nullable.unwrap_or(true)) + }) + .collect(); + Ok(Arc::new(Schema::new_with_metadata( + fields, + schema.metadata().clone(), + ))) + } + fn create_cloudfetch_reader( &self, statement_id: &str, diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 6ec8ddcc..1cb3d09a 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -699,8 +699,14 @@ async fn execute_succeeded_inline_returns_one_row() { } #[tokio::test] -async fn execute_uses_manifest_nullability_only_without_arrow_schema() { - for mode in ["inline", "cloudfetch", "empty", "empty_with_arrow_schema"] { +async fn execute_uses_manifest_nullability_only_for_empty_results_without_arrow_schema() { + for mode in [ + "inline", + "cloudfetch", + "empty", + "empty_without_chunk_count", + "empty_with_arrow_schema", + ] { let server = MockServer::start().await; mount_create_session(&server).await; mount_delete_session(&server).await; @@ -745,7 +751,7 @@ async fn execute_uses_manifest_nullability_only_without_arrow_schema() { .mount(&server) .await; } - "empty" | "empty_with_arrow_schema" => { + "empty" | "empty_without_chunk_count" | "empty_with_arrow_schema" => { body.as_object_mut().unwrap().remove("result"); body["manifest"]["total_row_count"] = json!(0); body["manifest"]["total_chunk_count"] = json!(0); @@ -753,6 +759,11 @@ async fn execute_uses_manifest_nullability_only_without_arrow_schema() { if mode == "empty_with_arrow_schema" { body["manifest"]["arrow_schema"] = json!(STANDARD.encode(arrow_schema_ipc_bytes(&schema))); + } else if mode == "empty_without_chunk_count" { + body["manifest"] + .as_object_mut() + .unwrap() + .remove("total_chunk_count"); } } _ => {} @@ -763,10 +774,23 @@ async fn execute_uses_manifest_nullability_only_without_arrow_schema() { statement.spec().sql("SELECT id, label, legacy FROM values"); let mut executed = statement.execute().await.expect("execute"); let advertised = executed.result_stream_mut().schema(); + let uses_manifest_nullability = matches!(mode, "empty" | "empty_without_chunk_count"); assert_eq!(advertised.field(0).name(), "id", "{mode}"); - assert_eq!(advertised.field(0).is_nullable(), mode != "empty", "{mode}"); - assert_eq!(advertised.field(1).is_nullable(), mode == "empty", "{mode}"); - assert_eq!(advertised.field(2).is_nullable(), mode == "empty", "{mode}"); + assert_eq!( + advertised.field(0).is_nullable(), + !uses_manifest_nullability, + "{mode}" + ); + assert_eq!( + advertised.field(1).is_nullable(), + uses_manifest_nullability, + "{mode}" + ); + assert_eq!( + advertised.field(2).is_nullable(), + uses_manifest_nullability, + "{mode}" + ); let batches = drain(executed.result_stream_mut()).await; if mode.starts_with("empty") { assert!(batches.is_empty(), "{mode}"); @@ -786,6 +810,60 @@ async fn execute_uses_manifest_nullability_only_without_arrow_schema() { } } +#[tokio::test] +async fn execute_inline_streaming_fallback_does_not_apply_manifest_nullability() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + let schema = Arc::new(Schema::new(vec![Field::new( + "col_0", + DataType::Int64, + true, + )])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int64Array::from(vec![None::]))], + ) + .unwrap(); + let mut body: serde_json::Value = + serde_json::from_str(&succeeded_inline_body("stmt-streaming", &batch)).unwrap(); + body["manifest"]["schema"]["columns"][0]["nullable"] = json!(false); + body["manifest"]["total_chunk_count"] = json!(2); + let empty_chunk = arrow_schema_ipc_bytes(&schema); + body["result"]["attachment"] = json!(STANDARD.encode(&empty_chunk)); + body["result"]["byte_count"] = json!(empty_chunk.len()); + body["result"]["row_count"] = json!(0); + body["result"]["next_chunk_index"] = json!(1); + mount_execute(&server, body.to_string()).await; + Mock::given(method("GET")) + .and(path( + "/api/2.0/sql/statements/stmt-streaming/result/chunks/1", + )) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "chunk_index": 1, + "row_offset": 0, + "row_count": 1, + "attachment": STANDARD.encode(arrow_ipc_bytes(&batch)), + }))) + .expect(1) + .mount(&server) + .await; + + let session = open_session(&server).await; + let mut statement = session.statement(); + statement.spec().sql("SELECT value FROM nullable_values"); + let mut executed = statement.execute().await.expect("execute"); + let advertised = executed.schema(); + let batches = drain(executed.result_stream_mut()).await; + assert!(advertised.field(0).is_nullable()); + assert_eq!(batches.len(), 1); + assert_eq!(batches[0].schema(), advertised); + assert_eq!(batches[0].num_rows(), 1); + assert_eq!(batches[0].column(0).null_count(), 1); + executed.close().await.unwrap(); +} + #[tokio::test] async fn execute_geospatial_string_mode_uses_manifest_tags_for_untagged_arrow_ipc() { let server = MockServer::start().await; From 77d42fe53169d63114c6dde685c3709cd1db9451 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 23 Oct 2026 00:25:42 +0000 Subject: [PATCH 5/5] test(reader): pin nullable output from empty-result conversions Signed-off-by: Vu Anh Phung --- docs/designs/result-metadata-propagation.md | 2 + tests/v0_execute_wiremock.rs | 69 +++++++++++++++++++++ 2 files changed, 71 insertions(+) diff --git a/docs/designs/result-metadata-propagation.md b/docs/designs/result-metadata-propagation.md index b407afd4..cbc3e370 100644 --- a/docs/designs/result-metadata-propagation.md +++ b/docs/designs/result-metadata-propagation.md @@ -380,6 +380,8 @@ std::string AdbcResultSetMetadata::GetTypeName(int column_position, int16_t data Empty results without `arrow_schema` use manifest `nullable`, defaulting to nullable when absent or null. Inline-streaming fallback schemas do not use manifest nullability. +JSON and interval string conversions retain nullable `Utf8` fields, even for empty +results whose manifest reports `nullable: false`. --- diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 1cb3d09a..1e9a14fe 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -810,6 +810,75 @@ async fn execute_uses_manifest_nullability_only_for_empty_results_without_arrow_ } } +#[tokio::test] +async fn execute_empty_result_string_conversions_keep_nullable_output() { + for (complex_types_as_json, intervals_as_string) in + [(false, false), (true, false), (false, true), (true, true)] + { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + mount_execute( + &server, + json!({ + "statement_id": "stmt-empty-converted", + "status": {"state": "SUCCEEDED"}, + "manifest": { + "format": "ARROW_STREAM", + "schema": {"column_count": 4, "columns": [ + {"name": "array_value", "type_name": "ARRAY", "type_text": "ARRAY", + "position": 0, "nullable": false}, + {"name": "struct_value", "type_name": "STRUCT", "type_text": "STRUCT", + "position": 1, "nullable": false}, + {"name": "interval_value", "type_name": "INTERVAL", "type_text": "INTERVAL YEAR TO MONTH", + "type_interval_type": "YEAR_MONTH", "position": 2, "nullable": false}, + {"name": "id", "type_name": "BIGINT", "type_text": "BIGINT", + "position": 3, "nullable": false}, + ]}, + "total_chunk_count": 0, + "total_row_count": 0, + "truncated": false, + }, + }) + .to_string(), + ) + .await; + let mut result = ResultConfig::default(); + result.complex_types_as_json = complex_types_as_json; + result.intervals_as_string = intervals_as_string; + let session = open_session_with_result(&server, result).await; + let mut statement = session.statement(); + statement + .spec() + .sql("SELECT array_value, struct_value, interval_value, id FROM values WHERE 1=0"); + let mut executed = statement.execute().await.expect("execute"); + let schema = executed.schema(); + for index in [0, 1] { + assert_eq!(schema.field(index).is_nullable(), complex_types_as_json); + if complex_types_as_json { + assert_eq!(schema.field(index).data_type(), &DataType::Utf8); + } + } + if !complex_types_as_json { + assert!(matches!(schema.field(0).data_type(), DataType::List(_))); + assert!(matches!(schema.field(1).data_type(), DataType::Struct(_))); + } + assert_eq!(schema.field(2).is_nullable(), intervals_as_string); + assert_eq!( + schema.field(2).data_type(), + &if intervals_as_string { + DataType::Utf8 + } else { + DataType::Interval(arrow_schema::IntervalUnit::YearMonth) + } + ); + assert!(!schema.field(3).is_nullable()); + assert!(drain(executed.result_stream_mut()).await.is_empty()); + executed.close().await.unwrap(); + } +} + #[tokio::test] async fn execute_inline_streaming_fallback_does_not_apply_manifest_nullability() { let server = MockServer::start().await;