Repository navigation
feat(reader): apply ManifestAugmentingReader in ResultReaderFactory - #35
Conversation
6670bab to
6627b6e
Compare
|
Important I1. RecordBatch::try_new failure on re-projection is documented as a data_loss error, but is also effectively unreachable — worth either upgrading to Error::internal or testing the failure path reader/mod.rs:505-513: augment_schema_with_manifest preserves field types, order, and count (it only mutates Field::metadata()). So the only way RecordBatch::try_new fails here is if the inner reader returned a batch whose array Two thoughts:
Not blocking; the case is exceptional. Worth a one-line follow-up. I2. The wrapper allocates per next_batch call — fine, but worth a doc note Every next_batch allocates:
For CloudFetch streams with thousands of small batches, this is N small allocations. The Vec reuses the column Arcs (no data copy), but the Vec itself is fresh per call. Performance: in practice, the per-batch overhead is dominated by the network fetch + Arrow IPC decode upstream of this. The augmentation overhead is microseconds per batch. ✓ Suggestion: add a one-line doc note acknowledging the per-batch Vec allocation. Sets expectations for future maintainers who profile and wonder if there's a no-op path when manifest = None: /// The pass-through path ( Or — if you want to actually optimize — store an Option for the augmented schema and skip the rebuild when it's None. ~10 LOC; saves the per-batch Vec + try_new for the manifest-less path. Smaller comments S1. ManifestAugmentingReader::new returns Result but the only failure path is inner.schema()? reader/mod.rs:483-491: inner.schema() is the only fallible call — augment_schema_with_manifest is infallible. Constructor returns Result only because of that one ?. Fine; the alternative (panic on schema fetch failure) is worse. S2. metadata_v0's list_* path goes through Transport::list_* which all call execute_and_read — covered automatically The PR description claims metadata_v0's list_* methods benefit too. Verified: every Transport::list_catalogs / list_schemas / list_tables / list_columns / list_primary_keys / list_foreign_keys / So metadata results (which already get JDBC-shape reshape via PR #33) also get manifest metadata attached. The two stack cleanly — ThriftReshapingReader wraps ManifestAugmentingReader wraps the inner reader. That means: after PR #33's reshape, the augmented metadata is still present on the inner Arrow arrays but the outer batch's Field objects are the JDBC-shape ones constructed in thrift_shape::GET__SCHEMA, Worth verifying: is this a real issue or is the metadata only needed on the execute-path (not metadata-path)? The PR description points at the connector's VARIANT detection on execute results — fine for that Suggestion: confirm with the connector folks whether m.list_columns(...) results need the databricks.* metadata on the column fields. If yes, follow-up on PR #33's reshape_columns to copy through manifest S3. Test helper reuse — MockReader::new(vec![batch]) The tests use MockReader::new(vec![batch]) which presumably already exists in the test module. ✓ No new helpers needed for the two new tests. S4. PR description's "single insertion point" framing The doc comment at reader/mod.rs:74-83 and the PR description both lean on "single insertion point." Worth noting in code that the other create_reader-like path is ResultReaderAdapter::new (Arrow-FFI shape, Not a bug. Just worth knowing for whoever maintains this in a year: "augmentation happens at two sites, both call augment_schema_with_manifest." S5. ResultManifest is passed as Option<&ResultManifest> — borrow lifetime is fine The constructor borrows manifest: Option<&ResultManifest> and never stores it (only the derived schema is stored). The augmented schema is a fresh SchemaRef, so there's no lifetime entanglement between the S6. next_batch re-projection happens unconditionally even when manifest was absent When manifest = None, self.schema is just the inner reader's schema — identical content. The RecordBatch::try_new rebuild creates an identical batch (same data, same schema). Cheap (Arcs reused) but |
`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 <vikrant.puppala@databricks.com>
6627b6e to
ab099c6
Compare
|
Thanks for the careful pass. Addressed in
Final state: 382 lib + 15 metadata wiremock + all integration suites still pass. |
Consolidates `ManifestAugmentingReader` (PR #35) into a new `ResultPostProcessor` that owns every per-batch transform the kernel does on the way out to consumers, in a single pass: - manifest-driven metadata attachment (`databricks.type_name` / `type_text` / precision / scale / interval kind); - optional compact-JSON stringification of `List` / `LargeList` / `FixedSizeList` / `Map` / `Struct` columns, opted into per session via `ResultConfig::complex_types_as_json`. A single `Option<BatchTransform>` closure captures the active transforms at construction time. When neither is active, `next_batch` is true pass-through (no `RecordBatch::try_new` rebuild). When at least one is active, both run in one fused walk so we never pay multiple rebuilds for the same upstream batch. The JSON format mirrors the Thrift wire form the server emits when `complexTypesAsArrow=false` — what PySQL's Thrift backend and JDBC's `DatabricksArray.toString()` / `DatabricksMap.toString()` / `DatabricksStruct.toString()` already deliver to callers today. Bindings that surface a flat-text view (PySQL when `_use_arrow_native_complex_types=False`, future JDBC kernel migration) flip the flag; ADBC and Arrow-native consumers leave it off and pay no cost. Verified e2e against pecotesting: default path returns native Arrow complex shapes, JSON-on path returns the expected compact JSON including nested ARRAY<STRUCT>. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
Consolidates `ManifestAugmentingReader` (PR #35) into a new `ResultPostProcessor` that owns every per-batch transform the kernel does on the way out to consumers, in a single pass: - manifest-driven metadata attachment (`databricks.type_name` / `type_text` / precision / scale / interval kind); - optional compact-JSON stringification of `List` / `LargeList` / `FixedSizeList` / `Map` / `Struct` columns, opted into per session via `ResultConfig::complex_types_as_json`. A single `Option<BatchTransform>` closure captures the active transforms at construction time. When neither is active, `next_batch` is true pass-through (no `RecordBatch::try_new` rebuild). When at least one is active, both run in one fused walk so we never pay multiple rebuilds for the same upstream batch. The JSON format mirrors the Thrift wire form the server emits when `complexTypesAsArrow=false` — what PySQL's Thrift backend and JDBC's `DatabricksArray.toString()` / `DatabricksMap.toString()` / `DatabricksStruct.toString()` already deliver to callers today. Bindings that surface a flat-text view (PySQL when `_use_arrow_native_complex_types=False`, future JDBC kernel migration) flip the flag; ADBC and Arrow-native consumers leave it off and pay no cost. Verified e2e against pecotesting: default path returns native Arrow complex shapes, JSON-on path returns the expected compact JSON including nested ARRAY<STRUCT>. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
## Summary Adds an opt-in kernel feature that converts complex columns (`ARRAY` / `MAP` / `STRUCT`, plus VARIANT / GEOMETRY / GEOGRAPHY pass-through) into compact JSON `Utf8` strings, byte-for-byte matching what the Databricks server emits on the Thrift wire when `complexTypesAsArrow=false` and what JDBC's `DatabricksArray.toString()` / `DatabricksMap.toString()` / `DatabricksStruct.toString()` produce. Also folds `ManifestAugmentingReader` (PR #35) into a new `ResultPostProcessor` that owns *every* per-batch transform the kernel does on the way out, in a single pass. ## Why Two consumers already produce the same byte-for-byte JSON today: - **JDBC**'s `DatabricksArray.toString()` / `DatabricksMap.toString()` / `DatabricksStruct.toString()` (~200 LOC of hand-rolled serialization). - **The Python connector's Thrift backend**, where the server stringifies server-side when `complexTypesAsArrow=false`. The new SEA-family paths (PySQL native SEA backend, kernel backend) don't have this path. The Thrift vs Kernel comparator currently surfaces 5 diffs in the `COMPLEX_TYPES_DISABLED` suite from exactly this gap. Putting the JSON serialization in the kernel means **one implementation**, **one source of truth on the format**, and every binding that wants the flat-text view (PySQL, JDBC's eventual kernel migration, future Go / Node) opts in without re-implementing it. ADBC leaves the flag off and pays no cost. ## What's in this PR ### Design doc — \`docs/designs/complex-types-json-stringify.md\` - Problem statement + why per-binding implementations are the wrong factoring. - API shape (session-level bool, no wire change). - JSON format rules (compact, JDBC-matching) per Databricks type. - Why one consolidated post-processor instead of stacked wrappers. - Migration shape per binding. ### Implementation - \`src/config.rs\`: \`ResultConfig::complex_types_as_json\` (default \`false\`). - \`src/reader/post_processor/mod.rs\`: \`ResultPostProcessor\` with \`Option<BatchTransform>\`. Constructor inspects upstream schema + manifest + options once and picks the closure shape (none / re-project-only / fused-walk). Hot path is one \`match\` per batch. - \`src/reader/post_processor/json.rs\`: pure per-type encoder (\`append_json\`) handling primitives, decimals, dates/timestamps, binary→base64, intervals, ARRAY/MAP/STRUCT recursion, and VARIANT/GEOMETRY/GEOGRAPHY metadata-driven pass-through. - \`src/reader/mod.rs\`: \`ResultReaderFactory\` now wraps with \`ResultPostProcessor\`; the old \`ManifestAugmentingReader\` is gone (folded in). - \`src/session.rs\`: \`result_to_post_process_options(...)\` plumbs the flag from \`ResultConfig\` into the factory. ### Performance shape - Single \`next_batch\` indirection regardless of how many transforms are active. - Pass-through (no manifest + no JSON) is genuinely free — no \`RecordBatch::try_new\`, no \`Vec<ArrayRef>\` rebuild. - Manifest-only path: one cheap re-project reusing upstream \`ArrayRef\`s. - Both transforms active: one fused walk emits the new \`RecordBatch\` in one pass. ## Test plan - [x] 13 unit tests in \`json.rs\` covering each primitive, ARRAY / MAP / STRUCT recursion, escape rules, NaN / Inf handling, empty containers, VARIANT pass-through, GEOMETRY quoting. - [x] 8 integration tests in \`post_processor/mod.rs\` covering: pass-through path, manifest-only path, JSON path for List / Map / Struct, null handling, JSON-off doesn't touch complex columns. - [x] \`cargo +stable fmt --all\` clean. - [x] \`cargo clippy --all-targets -- -D warnings\` clean. - [x] Full lib + integration suite passes (\`cargo test\`). - [x] \`cargo test --test v0_execute_e2e -- --ignored\` against pecotesting: 11/11 pass, including new \`complex_types_as_json_flag_stringifies_complex_columns\` verifying: - Default flag → server returns native \`List\` / \`Map\` / \`Struct\`. - Flag on → kernel rewrites them to \`Utf8\` carrying \`[1,2,3]\`, \`{\"k1\":\"v1\",\"k2\":\"v2\"}\`, \`{\"a\":\"foo\",\"b\":1}\`, and nested \`[{\"a\":\"x\",\"b\":1},{\"a\":\"y\",\"b\":2}]\`. - [ ] Follow-up: comparator \`THRIFT_VS_KERNEL_COMPLEX_DISABLED\` suite (in \`databricks-driver-test\`) — should drop from 5 diffs to 0 once the connector flips the flag. ## Migration - Default \`false\`: kernel behaviour unchanged for existing consumers. - PySQL connector will flip the flag when \`_use_arrow_native_complex_types=False\` (follow-up in \`databricks-sql-python\`). - JDBC: when it migrates to the kernel, can drop its ~200 LOC of Java JSON serialization. - ADBC: leaves the flag off, no change. This pull request and its description were written by Claude Code. --------- Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
Summary
augment_schema_with_manifestwas already in the kernel onResultReaderAdapter, attaching Databricks-specific per-column metadata (databricks.type_name,databricks.type_text, precision, scale, interval kind) from the SEAResultManifestonto 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 ownResultReadertrait directly, so the metadata never reachedResultStream::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 asstringrather thanvariant.Fix
Introduce
ManifestAugmentingReader— a thin wrapper implementing the kernel'sResultReadertrait. Exposes the augmented schema viaschema()and re-projects each emittedRecordBatchonto that schema sobatch.schema()carries the metadata too.Wired at
ResultReaderFactory::create_readerrather than at the call site (SeaRestTransport::execute_and_read).create_readeris the single seam every consumer goes through — syncexecute, asyncsubmit/await_result, all ofmetadata_v0'slist_*— so any future caller automatically benefits without having to remember to wrap.create_readeris split into a thin public wrapper that calls a new privatecreate_inner_reader(does the CloudFetch / inline / empty selection) and wraps the result once.Pass-through when
manifest = Noneso paths without column info (test mocks, edge cases) don't change shape.Test plan
cargo +stable fmt --all -- --checkcleancargo clippy --all-targets -- -D warningscleancargo test --workspace— 382 lib + 15 metadata wiremock + all integration suites passManifestAugmentingReader(metadata-attached + pass-through paths)variantend-to-end, closing 3 comparator diffs.This pull request and its description were written by Claude Code.