Skip to content

feat(reader): ResultPostProcessor + complex-types-as-JSON - #36

Merged
vikrantpuppala merged 4 commits into
mainfrom
docs/complex-types-json-stringify
May 25, 2026
Merged

vikrantpuppala merged 4 commits into
mainfrom
docs/complex-types-json-stringify

Conversation

@vikrantpuppala

@vikrantpuppala vikrantpuppala commented May 20, 2026 •

Copy link
Copy Markdown
Collaborator

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`. 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` 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

  • 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.
  • 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.
  • `cargo +stable fmt --all` clean.
  • `cargo clippy --all-targets -- -D warnings` clean.
  • Full lib + integration suite passes (`cargo test`).
  • `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.

Design for an opt-in kernel feature: when set, post-process result
batches to convert complex columns (ARRAY/MAP/STRUCT/VARIANT/
GEOMETRY/GEOGRAPHY) into compact JSON Utf8 strings, matching what
the Databricks server emits on the Thrift wire when
complexTypesAsArrow=false.

Today JDBC already does this in Java
(DatabricksArray/DatabricksMap/DatabricksStruct.toString — ~200
LOC of hand-rolled JSON serialization that matches the Thrift wire
format), and the Python connector's Thrift backend gets the same
shape directly from the server. Two consumers, same byte-for-byte
contract, implemented twice (more once the native SEA backend
catches up).

Pushing the JSON serialization into the kernel means one
implementation, one source of truth on the format, and every
binding that wants the flat-text view (PySQL, JDBC, future Go/Node)
opts in without re-implementing the serialization. ADBC and any
other Arrow-native consumer leave the flag off and pay no cost.

The doc covers:
- The problem and why per-binding implementations are wrong
- API shape (session-level bool, no wire change)
- JSON format rules (compact, JDBC-matching) per Databricks type
- Implementation sketch (new JsonStringifyingReader wrapped after
  ManifestAugmentingReader in ResultReaderFactory)
- Test plan (unit + golden Thrift fixtures + comparator
  end-to-end)
- Migration shape for each binding
- Open questions (VARIANT/GEOMETRY pass-through, DECIMAL
  canonicalisation, TIMESTAMP offset format, per-statement
  override)

Posting for review before implementation.

Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
Reframe the design so it doesn't add a second `ResultReader`
wrapper alongside `ManifestAugmentingReader`. Instead, rename the
existing wrapper to `ResultPostProcessor` and have it own *all*
per-batch transforms (manifest augmentation + JSON stringification,
plus any future ones like interval cast). One `next_batch` virtual
call regardless of how many transforms are active; one constructor-
time decision that builds a fused walk capturing only the work
that's needed; genuinely free pass-through when nothing's enabled
(no `RecordBatch::try_new` rebuild on the no-op path).

Why per-transform wrappers would have been wrong:

- Result batches arrive thousands at a time for CloudFetch streams;
  each wrapper layer adds a virtual call per batch. Today's two
  transforms could grow (interval stringification next). Each is
  microseconds but they compound and would force a measurement-
  driven cleanup later.
- Pass-through paths should actually be free. Per-transform
  wrappers force a `try_new` per batch even when the schema
  hasn't changed.
- JSON stringification reads metadata the augmenter wrote — the
  coupling exists either way; a fused walk expresses it directly.

Updated sections: result-stream integration, implementation sketch
(files-touched list, decision-logic algorithm, hot-path code,
JSON serialization details), migration of the existing
ManifestAugmentingReader.

Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
@vikrantpuppala vikrantpuppala changed the title docs(designs): complex types as JSON strings — kernel-level opt-in feat(reader): ResultPostProcessor + complex-types-as-JSON May 20, 2026
@gopalldb

Copy link
Copy Markdown
Collaborator

🟡 P1 — Important

  1. Panic on shape mismatch in JSON fused walk — src/reader/post_processor/mod.rs:229 (src/reader/post_processor/mod.rs#L229)

build_json_batch calls augmented.field(col_idx) inside the loop over batch.columns(). If upstream returns a batch with more columns than its advertised schema, Schema::field(col_idx) panics with
index-out-of-bounds before RecordBatch::try_new runs — aborts the worker thread instead of returning the typed Error::internal the surrounding code anticipates.

Fix:
let field = augmented.fields().get(col_idx).ok_or_else(|| {
Error::internal().message(format!(
"ResultPostProcessor: upstream batch has {} columns but schema only has {}",
batch.num_columns(), augmented.fields().len()
))
})?;

  1. Nested VARIANT / GEOMETRY / GEOGRAPHY loses metadata-driven pass-through — src/reader/post_processor/json.rs:188-216 (src/reader/post_processor/json.rs#L188-L216) + src/reader/mod.rs:500-554
    (src/reader/mod.rs#L500-L554)

augment_schema_with_manifest attaches databricks.type_name=VARIANT only to top-level Arrow fields. The recursive append_json passes inner fields (List's item, Map's key/value, Struct's children) to
append_utf8_value, which keys VARIANT pass-through off field.metadata().get(TYPE_NAME). For ARRAY or STRUCT<v: VARIANT> the inner field has no databricks.* metadata, so each VARIANT element is
double-escaped (""{\"a\":1}"" instead of {"a":1}). Same for nested GEOMETRY/GEOGRAPHY.

Silent byte-format divergence with Thrift/JDBC. Affects every ARRAY / STRUCT<v: VARIANT> column.

Fix: Either propagate databricks.type_name into inner Arrow fields when the manifest's type_text reveals them (parse ARRAY from type_text), or document the limitation and add an ARRAY e2e
test that asserts the current (buggy) output until parity lands.

  1. Timestamp precision fixed at milliseconds; JDBC uses native precision — src/reader/post_processor/json.rs:169-173 (src/reader/post_processor/json.rs#L169-L173)

Both TZ and NTZ paths use %.3f formatter regardless of the Arrow TimeUnit. JDBC's DatabricksArray.toString() chain emits the native precision (0/3/6/9 digits depending on the underlying type). A TIMESTAMP(6)
value 2024-01-15 10:30:00.123456 renders as "2024-01-15T10:30:00.123Z" here — silently drops the last 3 digits.

The kernel↔JDBC comparator will trip on any nested timestamp column with non-millisecond precision.

Fix: Drive the precision off the Arrow TimeUnit (Microsecond → %.6f, Nanosecond → %.9f, etc.) and add a fixture against the JDBC reference. Or document the millisecond-truncation as intentional in the design
doc.

  1. Base64 padding may diverge from JDBC — src/reader/post_processor/json.rs:402-404 (src/reader/post_processor/json.rs#L402-L404)

Uses base64::engine::general_purpose::STANDARD (with = padding). JDBC drivers conventionally strip padding for SQL — kernel output "aGVsbG8=" won't byte-match JDBC's "aGVsbG8".

Fix: Capture a JDBC reference fixture for BINARY-in-ARRAY and pick whichever it emits (padded or unpadded). Add a unit test pinning the choice.

  1. MAP NaN/Inf float key collides with null key — src/reader/post_processor/json.rs:284-308 (src/reader/post_processor/json.rs#L284-L308)

A floating-point map key with value NaN/Inf renders as bare null via append_float. The map-key wrapping logic then sees "doesn't start with "" and wraps in quotes → "null". A literally-null map key
(validity bit off) also emits "null". Two distinct shapes collapse to identical output.

Edge case (MAP<FLOAT, ...> with NaN key is exotic), but the kernel loses information.

Fix: Special-case non-finite numeric keys (emit "NaN" / "Infinity" distinguishable from null), or assert on construction that float-keyed MAPs aren't allowed.

🟢 P2 — Minor (acceptable to merge with)

#: 1
File:line: src/client/sea.rs:371-378 (src/client/sea.rs#L371-L378)
Issue: Stale block comment still references ManifestAugmentingReader; it's now ResultPostProcessor. PR otherwise updated docstrings — this one slipped.
Suggested fix: Update comment.
────────────────────────────────────────
#: 2
File:line: src/reader/post_processor/json.rs:365-376 (src/reader/post_processor/json.rs#L365-L376)
Issue: format_decimal128/256 return raw.to_string() for negative scale, ignoring the implicit multiplier. Dormant (Databricks doesn't emit negative-scale decimals) but the impl silently lies.
Suggested fix: Either implement negative-scale multiplication (raw * 10^|scale| with trailing zeros) or assert / error on negative scale.
────────────────────────────────────────
#: 3
File:line: src/reader/post_processor/mod.rs:91 (src/reader/post_processor/mod.rs#L91)
Issue: Constructor unconditionally calls inner.schema()?, which for CloudFetch blocks until chunk 0 downloads. When manifest=None && !complex_types_as_json, this is wasted work. Matches PR #35's baseline so
not a regression, but contradicts the PR description's "pass-through is free" claim.
Suggested fix: Short-circuit when both are absent: skip schema fetch, store a lazily-computed schema. Or rephrase the description to "free per-batch, costs one upstream schema fetch at construction."
────────────────────────────────────────
#: 4
File:line: tests/v0_execute_e2e.rs:567 (tests/v0_execute_e2e.rs#L567)
Issue: assert_eq!(strs[1], "{"k1":"v1","k2":"v2"}", "c_map") relies on the server preserving insertion order through MAP('k1','v1','k2','v2'). Spark generally preserves it but planner changes could
break this. Test is #[ignore], so blast radius is local.
Suggested fix: Deserialize JSON and assert key-set equality, or document the order assumption.
────────────────────────────────────────
#: 5
File:line: json.rs test module
Issue: No test for STRUCT<a: STRING, b: INT> with b = null. The code path through is_null looks correct but isn't pinned.
Suggested fix: Add a struct_field_null_renders_json_null test.
────────────────────────────────────────
#: 6
File:line: src/reader/post_processor/json.rs:421-437 (src/reader/post_processor/json.rs#L421-L437)
Issue: MonthDayNano interval branch falls through to DAY_TIME for (0, 0, 0), emitting "0 00:00:00.000000000" for a zero YEAR_MONTH interval. Dormant in practice (Databricks uses explicit interval subtypes).
Suggested fix: Add a code-comment documenting the disambiguation assumption.

Ship gate

Before merge:

  1. Fix P1 Initial import: Databricks ADBC Rust driver as databricks-sql-kernel #1 (panic on shape mismatch). 8 LOC.
  2. Decide on P1 refactor(adbc): quarantine ADBC surface and add v0 kernel skeleton #2 (nested VARIANT metadata propagation) — implement, or document the limitation with a test pinning current behavior.
  3. Run the THRIFT_VS_KERNEL_COMPLEX_DISABLED comparator suite against this branch. It will surface P1 feat(spec): add v0 Kernel public API skeleton (review-only) #3 (timestamp precision) and P1 docs: add kernel-v0 migration plan #4 (base64 padding) as concrete diffs, if they apply. Use that as ground
    truth instead of guessing the JDBC output format.

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>
@vikrantpuppala
vikrantpuppala force-pushed the docs/complex-types-json-stringify branch from d7bd822 to 5c0a1b9 Compare May 25, 2026 06:00
@vikrantpuppala

Copy link
Copy Markdown
Collaborator Author

Thanks for the thorough review — addressed in the force-pushed amend (d7bd822 → 5c0a1b9).

P1

  1. Panic on shape mismatch — Fixed. build_json_batch now uses augmented.fields().get(col_idx).ok_or_else(...) returning Error::internal with both lengths in the message, instead of indexing into Schema::field directly. (src/reader/post_processor/mod.rs)

  2. Nested VARIANT / GEOMETRY / GEOGRAPHY metadata loss — Documented as a known limitation, with a pinning test. Propagating databricks.type_name into inner Arrow fields would require parsing the manifest's type_text (ARRAY<VARIANT> etc.) — that's a follow-up. Added nested_variant_inside_list_is_escaped_known_limitation in json.rs and a doc-comment on append_utf8_value calling out the limitation so a future fix surfaces loudly.

  3. Timestamp precision fixed at milliseconds — Fixed. Subsecond precision now keys off TimeUnit (Second→0, Milli→%.3f, Micro→%.6f, Nano→%.9f). Comment updated; added timestamp_microsecond_precision_preserved and timestamp_nanosecond_with_tz_keeps_nine_digits_and_z tests.

  4. Base64 padding — Confirmed/pinned. JDBC's DatabricksArray.toString() chain defers to java.util.Base64.getEncoder() which is the standard padded encoder, so the existing STANDARD engine matches. Added a doc-comment to base64_encode recording the choice and the JDBC rationale; existing binary_renders_base64 test pins "aGVsbG8=".

  5. MAP NaN/Inf float key collides with null key — Fixed. The map-key wrapper now distinguishes the "rendered as bare null because the value is non-finite" case from a literal null-key entry by looking up the underlying float and emitting "NaN" / "Infinity" / "-Infinity". Added map_float_key_nan_renders_as_nan_not_null test covering all three.

P2

  1. Stale ManifestAugmentingReader comment in sea.rs — Updated to reference ResultPostProcessor and mention the JSON rewrite passes through the same path.

  2. Negative-scale decimals — Implemented multiplication. For scale < 0, both format_decimal128 and format_decimal256 now emit the magnified integer with trailing zeros (raw × 10^|scale|) instead of returning the bare unscaled int. Dormant on Databricks today but no longer silently lies.

  3. Constructor schema fetch on inner.schema() — Intentionally deferred. As you noted, this matches PR feat(reader): apply ManifestAugmentingReader in ResultReaderFactory #35's baseline and isn't a regression here. Rewording the perf claim in the description for accuracy is the lower-cost option; the lazy-schema rework belongs in its own change.

  4. MAP test order-independent — Test now parses the rendered string with serde_json and asserts a 2-entry object with k1→v1, k2→v2, no longer relying on insertion order. (tests/v0_execute_e2e.rs)

  5. struct_field_null test — Added struct_field_null_renders_json_null.

  6. MonthDayNano (0,0,0) disambiguation comment — Added inline comment explaining that since Databricks emits explicit interval subtypes upstream, a MonthDayNano column reaching here is in DAY_TIME semantics by construction, so the (0,0,0) fall-through to DAY_TIME formatting is intentional.

Verification

  • cargo +stable fmt --all clean
  • cargo clippy --all-targets -- -D warnings clean
  • cargo test — 406 lib + integration tests pass, including 6 new unit tests
  • THRIFT_VS_KERNEL_COMPLEX_DISABLED comparator follow-up still applies — will run that to confirm the precision/base64 picks are right against ground truth.

@vikrantpuppala
vikrantpuppala merged commit 04c8625 into main May 25, 2026
1 check passed
msrathore-db added a commit that referenced this pull request May 25, 2026
Bring in PR #36 (ResultPostProcessor + complex-types-as-JSON), re-applying
PR #26's async-ification on top: ResultReader trait stays async; create_reader
stays async; ResultPostProcessor adopts async constructor where it needs to
.await an inner schema/batch.

Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>

# Conflicts:
#	src/client/sea.rs
#	src/reader/mod.rs
vikrantpuppala added a commit that referenced this pull request May 25, 2026
…schema + composite + TIMESTAMP tz + getTables/getColumns metadata + named params (#64)

## Summary

Eight comparator-parity fixes in the kernel's result-reader,
metadata-reshape, and parameter-binding pipelines, surfaced by the
python-comparator audit.

### 1. `intervals_as_string` post-processor option

pyarrow's Python bindings can't decode Arrow's `month_interval` (id 21)
at all. Every kernel-backend `SELECT *` over a table with `INTERVAL YEAR
TO MONTH` columns threw `ArrowNotImplementedError`. **32 / 88**
comparator diffs.

- `ResultConfig::intervals_as_string` (default `false`) +
`PostProcessOptions::intervals_as_string`. When true, the post-processor
stringifies `Interval(*)` / `Duration(*)` columns to `Utf8`.
- Disjoint with the JSON-rewrite path; fused into one per-batch walk.
Renames `build_json_batch` → `build_rewritten_batch`.
- The Python connector ([PR
#803](databricks/databricks-sql-python#803))
sets it `true`.

### 2. PyO3 binding for both result-config knobs

Exposes `complex_types_as_json` and `intervals_as_string` as kwargs on
`Session(...)`. Merged into one `ResultConfig` so the toggles don't
clobber each other.

### 3. Empty-result schema fix: shared type-mapper + composite parsing

`extract_schema_from_manifest` was calling a local `map_databricks_type`
that handled ~10 type names. DECIMAL, INTERVAL, VOID, ARRAY, MAP, STRUCT
all fell through to `Utf8`.

- Delete the duplicate. Route through the shared
`metadata::type_mapping::databricks_type_to_arrow`. Pass `col.type_text`
instead of `col.type_name` so precision/scale come through.
- Parse composite type text via recursive descent: `ARRAY<INT>` →
`List<Int32>`, `MAP<STRING,INT>` → `Map<Struct{key,value}>`,
`STRUCT<x:INT,y:STRING>` → `Struct<...>`. Nested shapes
(`ARRAY<ARRAY<INT>>`, `MAP<STRING,MAP<STRING,INT>>`,
`STRUCT<a:ARRAY<INT>,b:MAP<STRING,INT>>`) parse correctly. Bad input
falls back to `Utf8`.

### 4. TIMESTAMP is tz-aware (was reported as tz-less)

The TIMESTAMP arm was sharing a match case with TIMESTAMP_NTZ. Plain
TIMESTAMP is logically TIMESTAMP_LTZ; the non-empty wire schema emits
`Timestamp(Microsecond, Some("Etc/UTC"))`.

- Split TIMESTAMP/TIMESTAMP_NTZ into separate arms.
- TIMESTAMP and TIMESTAMP_LTZ → `Timestamp(Microsecond,
Some("Etc/UTC"))` (matches wire path exactly).
- TIMESTAMP_NTZ → `Timestamp(Microsecond, None)`.

### 5. `getTables`: `types=[]` returns zero rows (was: returned all)

In `reshape_tables`, the `table_types` filter was treating `Some(&[])`
identically to `None` ("no filter"). Thrift backend returns *zero rows*
on an explicit empty array — the literal reading of "filter accepting
nothing". JDBC Javadoc is silent on the empty case; this picks Thrift's
reading for parity.

- Remove the `if !types.is_empty()` guard so `Some(&[])` hits the filter
path.
- Existing test renamed (`..._passes_everything` →
`..._returns_zero_rows`); new test locks the `None` path separately.

### 6. `getColumns`: REMARKS null → `""`

`reshape_columns` (and `reshape_tables`) emitted Arrow nulls for REMARKS
when the server didn't supply a comment. JDBC spec allows null, but the
Thrift backend has historically returned `""` and consumers expect a
`String`.

- New `utf8_column_or_empty(batch, name)` helper that substitutes `""`
for null entries.
- Used for REMARKS in both `reshape_tables` and `reshape_columns`.

### 7. `getColumns`: IS_AUTO_INCREMENT defaults to `"NO"`

Kernel returned `""` (JDBC's "unknown" sentinel) because the server
omits the field. Databricks tables don't support auto-increment, so
`"NO"` is the domain-correct answer.

- Refactored `bool_string_to_yn` into a thin wrapper over
`bool_string_to_yn_with_default(batch, name, default)`. Each callsite
picks its null-fallback.
- IS_NULLABLE keeps the `""` default (genuine unknown for computed
columns / views).
- IS_AUTO_INCREMENT uses `"NO"` default. Server-provided
`"true"`/`"false"` still wins, so the kernel honours real identity
columns if Databricks ever ships them.

### 8. Named-parameter binding (new — folds in former PR #65 scope)

`StatementSpec.named_params` was rejected at execute time with "named
parameter bindings are not supported in v0 — SEA wire format carries
positional bindings only".

That conclusion came from the kernel's local Rust `StatementParameter`
struct, which only had `ordinal`. The canonical SEA proto
(`sql_exec_api_service.proto`) defines:

```proto
message StatementParameter {
  optional int32 ordinal = 1 [(visibility) = PUBLIC_UNDOCUMENTED];
  optional string name = 2 [(databricks.openapi.field).openapi_required = true];
  optional string value = 3;
  optional string type = 4;
  repeated StatementParameterValueArg args = 5;
}
```

`name` is the documented public field; `ordinal` is
`PUBLIC_UNDOCUMENTED` "for future extension to positional parameters".
The kernel's local types were out of sync.

- `StatementParameter` gains `name: Option<String>`; `ordinal` becomes
`Option<i32>`. Both serialize with `skip_serializing_if =
"Option::is_none"` so the JSON shape on the wire matches the proto: a
positional param sends only `ordinal`, a named one sends only `name`.
- `named_typed_value_to_sea_parameter(name, value)` helper mirrors the
existing positional helper.
- `Statement::execute` forwards `spec.named_params` via the new helper
instead of rejecting.
- PyO3 gains `Statement.bind_named_param(name, value_str, sql_type)`
mirroring `bind_param`.

Server side: live e2e against a real warehouse confirms named-only
binding works. Mixed positional + named in one statement is rejected by
the server with `INVALID_PARAMETER_MARKER_VALUE.MISSING_NAME` — bindings
must be uniformly one or the other. The kernel surfaces this server-side
rejection cleanly (covered by
`mixed_positional_and_named_params_is_server_side_error`).

## Comparator outcome

| | Before any kernel work | After this PR + connector #803 |
|---|---|---|
| **match / diff (of 132 cases)** | 60 / 88 | **97 / 34 / 1 skipped** |
| Bucket A (ArrowNotImplementedError) | 32 | **0** ✅ |
| `decimal_column` precision/scale | 88 (connector) | **0** ✅ |
| `decimal_column` type slot (empty) | 7 | **0** ✅ |
| Complex-type slots (`ARRAY`/`MAP`/`STRUCT` in `fetchall_arrow`) | 12 |
**0** ✅ |
| `timestamp_column` tz slot | 1 | **0** ✅ |
| `getTables(types=[])` rows | 8 | **0** ✅ |
| `getColumns` IS_AUTO_INCREMENT cells | 5150 | **0** ✅ |
| `getColumns` REMARKS cells | 5122 | **3796** (residual is real text
differences, not null-vs-empty) |
| Bucket B1 (named params) | 1 | **0** ✅ |
| Fully-clean (config × suite) pairs | 12 / 30 | **18 / 30** |

Remaining diffs cluster into documented buckets (METADATA `_` wildcards
+ system schemas as accepted divergences; empty-result nullability —
fixable in a follow-up; Thrift backend per-row bugs to be fixed in
`databricks-sql-python` separately) — see
`~/docs/python-kernel/comparator-diff-tasklist.md`.

## Test plan

- [x] `cargo test --lib` — **421/421 pass** (3 new tests on top of prior
baseline: named StatementParameter JSON shape, named TypedValue helper,
named Binary rejection)
- [x] `cargo test --lib metadata::type_mapping` — 20/20 (12 existing + 8
new composite-type parser tests; TIMESTAMP test updated)
- [x] `cargo test --lib metadata::thrift_shape` — 17/17 (13 existing + 4
new for `types=[]`, REMARKS null→`""`, IS_AUTO_INCREMENT default→`"NO"`,
honors-server-true, no-when-column-missing)
- [x] `cargo test --lib reader::tests` — 19/19
- [x] `cargo test --lib reader::post_processor` — 21/21
- [x] `cargo test --test v0_execute_wiremock` — 11/11
(`execute_rejects_named_params_in_v0` flipped to
`execute_sends_named_params_in_wire_form`)
- [x] `cargo test --test v0_execute_e2e -- --ignored` — live against the
pecotesting warehouse. New: `select_with_named_params` passes,
`mixed_positional_and_named_params_is_server_side_error` documents the
server-side constraint.
- [x] End-to-end via the python-comparator: numbers above; bucket B1
confirmed 1 → 0.

## Stacking

Base: `docs/complex-types-json-stringify` (PR #36). That PR adds
`ResultConfig::complex_types_as_json` and the post-processor framework;
this PR adds the PyO3 binding for it, extends the post-processor with
`intervals_as_string`, fixes the empty-result schema path, adds
composite-type parsing + TIMESTAMP tz correctness, aligns `getTables` /
`getColumns` reshaping with Thrift's behavior where the JDBC spec is
ambiguous or the kernel was less informative, and adds named-parameter
binding support.

This pull request and its description were written by Isaac.

Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
vikrantpuppala added a commit that referenced this pull request May 25, 2026
…, empty-result schema, composite types, TIMESTAMP tz, metadata reshape, named params) (#72)

## Re-land of #64

PR #64 was filed as a stacked PR with base
\`docs/complex-types-json-stringify\`. That parent branch's content
reached \`main\` via #36 (squash-merge) on 2026-05-25 06:16Z. PR #64
then merged at 07:33Z — but **into the parent branch**, which by that
point was effectively detached from \`main\`. The merge commit
(\`fd2c576\`) is not an ancestor of \`origin/main\`, so #64's content
never reached the public branch even though GitHub reports it as
\`MERGED\`.

This is verifiable:

\`\`\`
$ git merge-base --is-ancestor fd2c576 origin/main && echo on || echo
off
off
\`\`\`

This PR cherry-picks \`fd2c576\` onto \`main\` so the eight
comparator-parity fixes (most importantly: named-parameter binding,
required by released connector PR #803 in \`databricks-sql-python\`)
actually land. **Connector #803 is currently broken in the wild**
because it calls \`Statement.bind_named_param\` which doesn't exist on
the public kernel.

## Cherry-pick details

Single content conflict: \`src/reader/mod.rs\` imports. \`main\`
requires \`DataType\` + \`async_trait\` (added by #26 after #64 was
filed); the cherry-pick branch didn't. Resolved by keeping \`main\`'s
wider import set and dropping the now-unused \`DataType\` (the
cherry-picked content uses other identifiers, not \`DataType\`, at this
site).

## Verification

- \`cargo build --workspace\` — clean
- \`cargo test --lib\` — **436/436 pass**
- \`cargo test --test v0_execute_wiremock\` — **11/11 pass**

## Original #64 description (preserved below for review continuity)

Eight comparator-parity fixes in the kernel's result-reader,
metadata-reshape, and parameter-binding pipelines, surfaced by the
python-comparator audit:

1. **\`intervals_as_string\` post-processor option** — pyarrow's Python
bindings can't decode Arrow's \`month_interval\` (id 21) at all. Every
kernel-backend \`SELECT *\` over a table with \`INTERVAL YEAR TO MONTH\`
columns threw \`ArrowNotImplementedError\`. 32 / 88 comparator diffs.
2. **PyO3 binding for both result-config knobs** —
\`complex_types_as_json\` + \`intervals_as_string\` as \`Session(...)\`
kwargs.
3. **Empty-result schema fix** — \`extract_schema_from_manifest\` now
routes through the shared \`databricks_type_to_arrow\` mapper;
DECIMAL/INTERVAL/VOID/ARRAY/MAP/STRUCT no longer fall through to
\`Utf8\`. Recursive parser for composite type text.
4. **TIMESTAMP tz-aware** — plain TIMESTAMP maps to
\`Timestamp(Microsecond, Some("Etc/UTC"))\` to match the non-empty wire
path.
5. **\`getTables(types=[])\` returns zero rows** — matches Thrift; was
returning all rows.
6. **\`getColumns\` REMARKS null → \`""\`** — matches Thrift consumers'
expectations.
7. **\`getColumns\` IS_AUTO_INCREMENT defaults to \`"NO"\`** —
Databricks tables don't support auto-increment; \`"NO"\` is the
domain-correct answer.
8. **Named-parameter binding** — \`StatementParameter.name\` is
\`openapi_required=true\` per the canonical SEA proto; kernel now
exposes \`Statement::bind_named_param\` (Rust + PyO3) and forwards
\`spec.named_params\` through the SEA \`parameters\` array.

Full original PR description and comparator outcome table:
#64

This pull request and its description were written by Isaac.

Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants