From ab099c651a5d324487b53ffab5872eba936f0048 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Tue, 19 May 2026 10:34:28 +0000 Subject: [PATCH] feat(reader): apply ManifestAugmentingReader in ResultReaderFactory MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `augment_schema_with_manifest` was added on `ResultReaderAdapter` to attach Databricks-specific per-column metadata (`databricks.type_name`, `databricks.type_text`, precision, scale, interval kind) from the SEA `ResultManifest` onto the result schema's fields. Bindings consume these to recover the precise server-reported type for columns whose Arrow shape collapses (VARIANT → Utf8, intervals → Interval, GEOMETRY/GEOGRAPHY → Utf8). But the augmenter was only reachable through ResultReaderAdapter (the Arrow-FFI shape); the live execute path uses the kernel's own ResultReader trait directly, so the metadata never reached ResultStream::schema() consumers. Surfaced when the Python connector (databricks-sql-python#793) added VARIANT detection via `field.metadata[b"databricks.type_name"]` and saw empty metadata everywhere — VARIANT columns kept reporting as `string` rather than `variant`. Fix: introduce ManifestAugmentingReader — a thin wrapper implementing the kernel's ResultReader trait. Exposes the augmented schema via schema() and re-projects each emitted RecordBatch onto that schema so batch.schema() carries the metadata too. Wired at ResultReaderFactory::create_reader rather than at SeaRestTransport::execute_and_read: create_reader is the single seam every consumer goes through, so any future caller (beyond the current execute_and_read path) automatically benefits without having to remember to wrap. Split create_reader into a thin public wrapper that calls create_inner_reader (does the CloudFetch vs inline vs empty selection) and wraps the result once. Pass-through when manifest = None so paths without column info (test mocks, edge cases) don't change shape. Two new unit tests cover metadata-attached + pass-through paths. Signed-off-by: Vikrant Puppala --- src/client/sea.rs | 9 +++ src/reader/mod.rs | 169 +++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 176 insertions(+), 2 deletions(-) diff --git a/src/client/sea.rs b/src/client/sea.rs index 07262129..a47ecd3e 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -368,7 +368,16 @@ impl SeaRestTransport { .await?; let response = self.wait_for_completion(response).await?; let reader_factory = self.reader_factory()?; + // `create_reader` wraps in a `ManifestAugmentingReader` + // internally, so the reader returned here already carries + // the server-reported per-column metadata + // (`databricks.type_name` etc.) on its schema and on every + // emitted batch. Bindings (PySQL, future ADBC) read those + // attributes to recover the precise type for columns whose + // Arrow shape collapses (VARIANT → Utf8, intervals → Interval, + // GEOMETRY/GEOGRAPHY → Utf8). let reader = reader_factory.create_reader(&response.statement_id, &response)?; + // `server_state` carries the terminal state forward so the // executed handle can skip a redundant CloseStatement when // the server already cleaned up (state=Closed). diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 42ccf5e9..4abac058 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -70,11 +70,41 @@ impl ResultReaderFactory { /// Create a reader from a statement execution response. /// - /// Automatically selects CloudFetch, inline, or other reader based on response. + /// Automatically selects CloudFetch, inline, or other reader based + /// on response. The returned reader is wrapped in a + /// [`ManifestAugmentingReader`] when the response carries a + /// [`ResultManifest`], so per-column metadata + /// (`databricks.type_name`, `databricks.type_text`, precision / + /// scale / interval kind) is attached to the schema and to every + /// emitted batch. Single insertion point for the ResultReader-trait + /// consumers — every caller of `create_reader` benefits automatically. + /// + /// There is one other augmentation site for Arrow-FFI consumers: + /// [`ResultReaderAdapter::new`] also applies the same + /// [`augment_schema_with_manifest`](ResultReaderAdapter::augment_schema_with_manifest) + /// to the wrapped reader's schema. Both sites share the same helper, + /// so the metadata-attachment behaviour is consistent across the + /// two surfaces. pub(crate) fn create_reader( &self, statement_id: &str, response: &ExecuteResponse, + ) -> Result> { + let inner = self.create_inner_reader(statement_id, response)?; + Ok(Box::new(ManifestAugmentingReader::new( + inner, + response.manifest.as_ref(), + )?)) + } + + /// Pick the right concrete reader for `response`: CloudFetch, + /// inline Arrow, or a typed empty stream. Split from + /// [`create_reader`] so the manifest-augmentation wrap lives at + /// exactly one site. + fn create_inner_reader( + &self, + statement_id: &str, + response: &ExecuteResponse, ) -> Result> { // Log manifest info for debugging if let Some(ref manifest) = response.manifest { @@ -430,6 +460,76 @@ pub mod metadata_keys { pub const TYPE_INTERVAL_TYPE: &str = "databricks.type_interval_type"; } +/// Wrapper that augments an upstream `ResultReader`'s schema with +/// Databricks per-column metadata from the SEA `ResultManifest` +/// (server-reported `type_name`, `type_text`, precision, scale, +/// interval kind), and re-projects each emitted `RecordBatch` onto +/// that augmented schema so downstream consumers see the metadata +/// both on `ResultStream::schema()` and on `batch.schema()`. +/// +/// Active in the live `execute_and_read` path; transparent when +/// the manifest is absent (e.g. queries without column info). See +/// also [`ResultReaderAdapter`] for the Arrow-FFI-shaped wrapper. +pub(crate) struct ManifestAugmentingReader { + inner: Box, + schema: SchemaRef, +} + +impl ManifestAugmentingReader { + /// Build an augmenting wrapper around `inner`. + /// + /// When `manifest` is `Some`, the upstream schema is rewritten + /// to attach Databricks column metadata under the + /// `databricks.*` keys. When it's `None`, the wrapper is a + /// pass-through (so callers don't need to special-case the + /// metadata-less path). + pub(crate) fn new( + inner: Box, + manifest: Option<&ResultManifest>, + ) -> Result { + let schema = inner.schema()?; + let schema = match manifest { + Some(m) => ResultReaderAdapter::augment_schema_with_manifest(&schema, m), + None => schema, + }; + Ok(Self { inner, schema }) + } +} + +impl ResultReader for ManifestAugmentingReader { + fn schema(&self) -> Result { + Ok(self.schema.clone()) + } + + fn next_batch(&mut self) -> Result> { + match self.inner.next_batch()? { + None => Ok(None), + Some(batch) => { + // Re-project the batch's columns onto our augmented + // schema. Column count, types, and order are + // unchanged — only `Field::metadata()` differs — so + // this is a cheap rebuild that reuses the same + // `ArrayRef`s under the hood. + // + // A `try_new` failure here means the inner reader + // returned a batch whose array count / types don't + // match the schema it itself advertised — an internal + // invariant violation, not data corruption or a + // partial server response. Map to `Error::internal` + // so the error category matches the actual cause. + let columns: Vec = batch.columns().to_vec(); + RecordBatch::try_new(self.schema.clone(), columns) + .map(Some) + .map_err(|e| { + crate::kernel_error::Error::internal().message(format!( + "ManifestAugmentingReader: upstream batch shape disagrees with the schema it advertised: {e}" + )) + }) + } + } + } +} + /// Adapter to make ResultReader work as arrow's RecordBatchReader. pub struct ResultReaderAdapter { inner: Box, @@ -457,7 +557,10 @@ impl ResultReaderAdapter { /// attach `databricks.*` key-value metadata to the field. This preserves /// server-provided type_name, type_text, precision, scale, etc. through the /// Arrow C Data Interface FFI boundary. - fn augment_schema_with_manifest(schema: &SchemaRef, manifest: &ResultManifest) -> SchemaRef { + pub(crate) fn augment_schema_with_manifest( + schema: &SchemaRef, + manifest: &ResultManifest, + ) -> SchemaRef { use std::collections::HashMap; let col_by_pos: HashMap = manifest @@ -872,4 +975,66 @@ mod tests { .metadata() .contains_key(metadata_keys::TYPE_NAME)); } + + // --- ManifestAugmentingReader tests --- + + #[test] + fn test_manifest_augmenting_reader_attaches_metadata_to_schema_and_batches() { + // Server-shape: Utf8 column the kernel doesn't otherwise know + // is a VARIANT. The manifest carries the precise type. + let batch = make_test_batch(vec!["{\"a\":1}"]); + let reader: Box = Box::new(MockReader::new(vec![batch])); + let manifest = make_manifest(vec![make_column_info( + "name", "VARIANT", "VARIANT", 0, None, None, None, + )]); + + let mut wrapper = ManifestAugmentingReader::new(reader, Some(&manifest)).unwrap(); + + // Stream-level schema carries the metadata. + let schema = wrapper.schema().unwrap(); + assert_eq!( + schema.field(0).metadata().get(metadata_keys::TYPE_NAME), + Some(&"VARIANT".to_string()) + ); + + // Batches emitted by `next_batch` are re-projected onto the + // augmented schema, so consumers reading `batch.schema()` + // also see the metadata. + let batch = wrapper.next_batch().unwrap().expect("one batch"); + assert_eq!( + batch + .schema() + .field(0) + .metadata() + .get(metadata_keys::TYPE_NAME), + Some(&"VARIANT".to_string()) + ); + assert!(wrapper.next_batch().unwrap().is_none()); + } + + #[test] + fn test_manifest_augmenting_reader_passes_through_when_manifest_absent() { + let batch = make_test_batch(vec!["plain"]); + let reader: Box = Box::new(MockReader::new(vec![batch])); + + let mut wrapper = ManifestAugmentingReader::new(reader, None).unwrap(); + let schema = wrapper.schema().unwrap(); + assert!( + !schema + .field(0) + .metadata() + .contains_key(metadata_keys::TYPE_NAME), + "no manifest → no databricks.* metadata" + ); + + let batch = wrapper.next_batch().unwrap().expect("one batch"); + assert!( + !batch + .schema() + .field(0) + .metadata() + .contains_key(metadata_keys::TYPE_NAME), + "no manifest → batch schema also clean" + ); + } }