Skip to content

feat(reader): comparator parity — intervals_as_string + empty-result schema + composite + TIMESTAMP tz + getTables/getColumns metadata + named params - #64

Merged
vikrantpuppala merged 1 commit into
docs/complex-types-json-stringifyfrom
feat/intervals-as-string
May 25, 2026
Merged

vikrantpuppala merged 1 commit into
docs/complex-types-json-stringifyfrom
feat/intervals-as-string

Conversation

@vikrantpuppala

@vikrantpuppala vikrantpuppala commented May 23, 2026 •

Copy link
Copy Markdown
Collaborator

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) 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:

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

  • cargo test --lib — 421/421 pass (3 new tests on top of prior baseline: named StatementParameter JSON shape, named TypedValue helper, named Binary rejection)
  • cargo test --lib metadata::type_mapping — 20/20 (12 existing + 8 new composite-type parser tests; TIMESTAMP test updated)
  • 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)
  • cargo test --lib reader::tests — 19/19
  • cargo test --lib reader::post_processor — 21/21
  • cargo test --test v0_execute_wiremock — 11/11 (execute_rejects_named_params_in_v0 flipped to execute_sends_named_params_in_wire_form)
  • 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.
  • 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.

@vikrantpuppala
vikrantpuppala force-pushed the feat/intervals-as-string branch from 50d1454 to e938946 Compare May 23, 2026 17:01
@vikrantpuppala vikrantpuppala changed the title feat(reader): intervals_as_string post-processor + PyO3 result-config bindings feat(reader): comparator parity — intervals_as_string + empty-result schema fix May 23, 2026
@vikrantpuppala
vikrantpuppala force-pushed the feat/intervals-as-string branch from e938946 to 1a0d209 Compare May 24, 2026 04:40
@vikrantpuppala vikrantpuppala changed the title feat(reader): comparator parity — intervals_as_string + empty-result schema fix feat(reader): comparator parity — intervals_as_string + empty-result schema fix + composite-type parser May 24, 2026
@vikrantpuppala
vikrantpuppala force-pushed the feat/intervals-as-string branch from 1a0d209 to 865d0b8 Compare May 24, 2026 05:00
@vikrantpuppala vikrantpuppala changed the title feat(reader): comparator parity — intervals_as_string + empty-result schema fix + composite-type parser feat(reader): comparator parity — intervals_as_string + empty-result schema fix + composite + TIMESTAMP tz May 24, 2026
vikrantpuppala added a commit that referenced this pull request May 24, 2026
…schema fix + composite + TIMESTAMP tz + getTables/getColumns metadata fixes

Comparator parity work in the kernel's result-reader pipeline,
surfaced by databricks-driver-test/tests/comparator-tests/python.

## 1. intervals_as_string post-processor option

pyarrow's Python bindings cannot decode Arrow's `month_interval` type
(id 21) at all — `.as_py()`, `.to_pylist()`, `cast(string)`, and
`to_pandas()` all fail with KeyError / ArrowNotImplementedError. Result
sets with INTERVAL YEAR TO MONTH columns are therefore unreadable from
Python on the kernel backend today. 32/88 audit diffs ("bucket A").

- Adds `ResultConfig::intervals_as_string` (default false) +
  `PostProcessOptions::intervals_as_string`. When true, the post-
  processor stringifies `Interval(*)` / `Duration(*)` columns to
  `Utf8` via the existing `format_interval` / `format_duration`
  helpers.
- Disjoint with the JSON-rewrite path; fused into one per-batch walk.
  Renames `build_json_batch` → `build_rewritten_batch`.
- Default false. The Python connector (PR #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: shared type-mapper + composite parsing

`extract_schema_from_manifest` (used when a query succeeds with zero
rows, e.g. `WHERE 1=0`) was calling a *local* `map_databricks_type`
that handled only ~10 type names. DECIMAL, INTERVAL, VOID, ARRAY,
MAP, STRUCT etc. all fell through to `Utf8`.

- Delete the duplicate. Route `extract_schema_from_manifest` through
  the shared `metadata::type_mapping::databricks_type_to_arrow`. Pass
  `col.type_text` (`"DECIMAL(10,2)"`) rather than `col.type_name`
  (`"DECIMAL"`) so the shared mapper recovers precision/scale.

- Extend `databricks_type_to_arrow` to parse composite type text:
    `ARRAY<INT>`         → List(Field("element", Int32, true))
    `MAP<STRING,INT>`    → Map(Field("entries", Struct{key,value}))
    `STRUCT<x:INT,y:STR>` → Struct(Fields::from([Field("x", ...), ...]))
  Recursive descent with depth-aware comma/colon splitters so 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, mapping
both to `Timestamp(Microsecond, None)`. But in Databricks SQL, plain
TIMESTAMP is logically TIMESTAMP_LTZ — the non-empty wire schema (Arrow
IPC from SEA) emits `Timestamp(Microsecond, Some("Etc/UTC"))`.

- Split TIMESTAMP and TIMESTAMP_NTZ into separate match arms.
- TIMESTAMP and TIMESTAMP_LTZ both map to
  `Timestamp(Microsecond, Some("Etc/UTC"))` — exactly the tz string
  the non-empty wire path emits (was previously bare `"UTC"`, which
  would also have diverged).
- TIMESTAMP_NTZ stays tz-less.

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

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

- Remove the `if !types.is_empty()` guard so `Some(&[])` hits the
  filter path and produces zero rows.
- Renamed existing test `tables_empty_types_filter_passes_everything`
  → `tables_empty_types_filter_returns_zero_rows` (now asserts 0).
- Added `tables_none_types_passes_all` to lock the `None` path
  separately.

## 6. getColumns: REMARKS null → ""

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

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

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

The Thrift backend hardcodes `IS_AUTO_INCREMENT="NO"` for every
column (Databricks tables don't support auto-increment, so this is
domain-correct). Kernel was returning `""` (JDBC's "unknown"
sentinel) because the server omits the field — strictly less
informative than the known answer.

- Refactored `bool_string_to_yn(batch, name)` into a thin wrapper
  over `bool_string_to_yn_with_default(batch, name, default)`. The
  helper now lets each callsite pick its null-fallback.
- IS_NULLABLE keeps the `""` default (genuine "unknown" — server
  doesn't always know nullability for computed columns / views).
- IS_AUTO_INCREMENT uses `"NO"` default with a code comment
  explaining the Databricks domain assumption (no auto-increment).
- Server-provided `"true"`/`"false"` always wins, so if Databricks
  ever ships identity columns the kernel honours them.

## Test plan

- [x] `cargo test --lib` — 418/418 pass.
- [x] `cargo test --lib metadata::thrift_shape` — 17/17 (13 existing
  + 4 new: types=[]-returns-zero, None-types-passes-all,
  remarks-null-becomes-empty-string, is_auto_increment-defaults-to-no
  + is_auto_increment-honors-server-true +
  is_auto_increment-no-when-column-missing).
- [x] `cargo test --lib metadata::type_mapping` — 20/20 pass (12
  existing + 8 new composite-type tests).
- [x] `cargo test --lib reader::tests` — 19/19 pass.
- [x] `cargo test --lib reader::post_processor` — 21/21 pass.
- [x] Manual end-to-end via the python-comparator:
    Before any kernel work:                          60 match /  88 diff
    After PR #64 (intervals + schema fix) + #803:   103 match /  45 diff
    After this PR (adds getTables/getColumns fixes): 105 match /  43 diff
    Cumulative cell-level wins:
      - Bucket A (ArrowNotImplementedError):                32 → 0
      - decimal_column precision/scale (connector):         88 → 0
      - decimal_column type slot (empty-result schema):      7 → 0
      - Complex-type slot (ARRAY/MAP/STRUCT empty result):  12 → 0
      - timestamp_column tz slot (empty result):             1 → 0
      - getTables(types=[]) rows:                            8 → 0
      - getColumns IS_AUTO_INCREMENT cells:               5150 → 0
      - getColumns REMARKS cells:                         5122 → 3796
@vikrantpuppala
vikrantpuppala force-pushed the feat/intervals-as-string branch from 865d0b8 to 2e091c0 Compare May 24, 2026 10:56
@vikrantpuppala vikrantpuppala changed the title feat(reader): comparator parity — intervals_as_string + empty-result schema fix + composite + TIMESTAMP tz feat(reader): comparator parity — intervals + empty-result schema + composite types + TIMESTAMP tz + metadata fixes May 24, 2026
vikrantpuppala added a commit that referenced this pull request May 25, 2026
…schema + composite + TIMESTAMP tz + getTables/getColumns metadata + named params

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

### 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. Nested shapes
  parse correctly; bad input falls back to `Utf8`.

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

Plain TIMESTAMP is logically TIMESTAMP_LTZ; the non-empty wire
schema emits `Timestamp(Microsecond, Some("Etc/UTC"))`. Split the
TIMESTAMP / TIMESTAMP_NTZ match arms.

### 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". Picks Thrift's reading for parity.

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

`reshape_columns` (and `reshape_tables`) emitted Arrow nulls for
REMARKS when the server didn't supply a comment. New
`utf8_column_or_empty(batch, name)` helper substitutes "" for null
entries.

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

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

### 8. Named-parameter binding (new)

`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 was sourced from the kernel's local Rust
`StatementParameter` struct, which only had `ordinal`. The
canonical SEA proto (`sql_exec_api_service.proto`) defines:

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

## 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 (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 real diffs) |
| Bucket B1 (named params) | 1 | 0 ✅ |
| Fully-clean (config × suite) pairs | 12 / 30 | 18 / 30 |

Remaining diffs cluster into documented buckets — see
`~/docs/python-kernel/comparator-diff-tasklist.md`.

## Test plan

- [x] `cargo test --lib` — 421/421 pass (3 new tests on top of #64
      baseline: named StatementParameter JSON shape, named
      TypedValue helper, named Binary rejection)
- [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 pecotesting warehouse. New: `select_with_named_params`
      passes, `mixed_positional_and_named_params_is_server_side_error`
      documents the server-side constraint.
- [x] Full thrift-vs-kernel comparator (132 cases): 97 / 34 / 1
      skipped — bucket B1 confirmed dropped from 1 → 0.

Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
@vikrantpuppala
vikrantpuppala force-pushed the feat/intervals-as-string branch from 2e091c0 to 699a38f Compare May 25, 2026 04:50
@vikrantpuppala vikrantpuppala changed the title feat(reader): comparator parity — intervals + empty-result schema + composite types + TIMESTAMP tz + metadata fixes feat(reader): comparator parity — intervals_as_string + empty-result schema + composite + TIMESTAMP tz + getTables/getColumns metadata + named params May 25, 2026
@gopalldb

Copy link
Copy Markdown
Collaborator

P1 — Important (should fix before merge)

  1. List inner-field name mismatch: "element" vs wire's "item" — src/metadata/type_mapping.rs:139-147
    parse_array emits List(Field("element", inner, true)), but arrow-rs's canonical default is "item" and every other call site in this kernel (reader/post_processor/json.rs:575,588,604,
    reader/post_processor/mod.rs:425,477) uses "item". PyArrow also defaults to "item". The empty-result ARRAY schema will fail field-level == against the non-empty Arrow IPC payload — directly
    contradicting the PR's "byte-equal" goal.
    Fix: swap "element" → "item"; ideally use Field::new_list_field(...). Update tests at type_mapping.rs:382-397.

  2. Real INTERVAL type_text silently falls back to Utf8 — src/metadata/type_mapping.rs:94
    Production wire values are "INTERVAL YEAR TO MONTH" / "INTERVAL DAY TO SECOND" (confirmed at src/types/sea.rs:500, src/reader/mod.rs:868). The splitter only cuts on < / (, not whitespace, so base_upper =
    "INTERVAL YEAR TO MONTH" doesn't match the "INTERVAL" arm and goes to default Utf8. The new test uses synthetic "INTERVAL" which never appears in production.
    Fix: also split on whitespace, then use the manifest's type_interval_type (YEAR_MONTH vs DAY_TIME) to pick IntervalUnit::YearMonth vs IntervalUnit::DayTime. Add a test feeding the real wire string.

P2 — Minor (can merge with)

  • TIMESTAMP empty-result schema change (None → Some("Etc/UTC")) — also affects describe_result_to_schema callers in src/statement/params.rs:451; add a NEXT_CHANGELOG.md note.
  • MAP/STRUCT field names ("entries"/"key"/"value") not validated against a captured SEA wire payload — add an integration assertion via the comparator.
  • No depth limit on parse_type recursion (server-controlled input) — add a depth > 64 guard; trivial.
  • STRUCT<a:STRING>> parses silently as Struct{a:Utf8} instead of falling back to Utf8 — inside_angle_brackets uses rfind('>'). Validate bracket balance ends at depth 0.
  • DECIMAL(0,0) parses to invalid Decimal128(0,0) — clamp precision into [1,38], scale into [-38,38].
  • PostProcessOptions test literals are brittle — four test sites set every field; use ..Default::default().

@vikrantpuppala
vikrantpuppala force-pushed the docs/complex-types-json-stringify branch from d7bd822 to 5c0a1b9 Compare May 25, 2026 06:00
vikrantpuppala added a commit that referenced this pull request May 25, 2026
…schema + composite + TIMESTAMP tz + getTables/getColumns metadata + named params

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

### 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. Nested shapes
  parse correctly; bad input falls back to `Utf8`.

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

Plain TIMESTAMP is logically TIMESTAMP_LTZ; the non-empty wire
schema emits `Timestamp(Microsecond, Some("Etc/UTC"))`. Split the
TIMESTAMP / TIMESTAMP_NTZ match arms.

### 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". Picks Thrift's reading for parity.

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

`reshape_columns` (and `reshape_tables`) emitted Arrow nulls for
REMARKS when the server didn't supply a comment. New
`utf8_column_or_empty(batch, name)` helper substitutes "" for null
entries.

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

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

### 8. Named-parameter binding (new)

`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 was sourced from the kernel's local Rust
`StatementParameter` struct, which only had `ordinal`. The
canonical SEA proto (`sql_exec_api_service.proto`) defines:

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

## 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 (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 real diffs) |
| Bucket B1 (named params) | 1 | 0 ✅ |
| Fully-clean (config × suite) pairs | 12 / 30 | 18 / 30 |

Remaining diffs cluster into documented buckets — see
`~/docs/python-kernel/comparator-diff-tasklist.md`.

## Test plan

- [x] `cargo test --lib` — 421/421 pass (3 new tests on top of #64
      baseline: named StatementParameter JSON shape, named
      TypedValue helper, named Binary rejection)
- [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 pecotesting warehouse. New: `select_with_named_params`
      passes, `mixed_positional_and_named_params_is_server_side_error`
      documents the server-side constraint.
- [x] Full thrift-vs-kernel comparator (132 cases): 97 / 34 / 1
      skipped — bucket B1 confirmed dropped from 1 → 0.

Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
@vikrantpuppala
vikrantpuppala force-pushed the feat/intervals-as-string branch from 699a38f to fa69fd3 Compare May 25, 2026 06:28
vikrantpuppala added a commit that referenced this pull request May 25, 2026
…schema + composite + TIMESTAMP tz + getTables/getColumns metadata + named params

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

### 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. Nested shapes
  parse correctly; bad input falls back to `Utf8`.

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

Plain TIMESTAMP is logically TIMESTAMP_LTZ; the non-empty wire
schema emits `Timestamp(Microsecond, Some("Etc/UTC"))`. Split the
TIMESTAMP / TIMESTAMP_NTZ match arms.

### 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". Picks Thrift's reading for parity.

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

`reshape_columns` (and `reshape_tables`) emitted Arrow nulls for
REMARKS when the server didn't supply a comment. New
`utf8_column_or_empty(batch, name)` helper substitutes "" for null
entries.

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

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

### 8. Named-parameter binding (new)

`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 was sourced from the kernel's local Rust
`StatementParameter` struct, which only had `ordinal`. The
canonical SEA proto (`sql_exec_api_service.proto`) defines:

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

## 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 (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 real diffs) |
| Bucket B1 (named params) | 1 | 0 ✅ |
| Fully-clean (config × suite) pairs | 12 / 30 | 18 / 30 |

Remaining diffs cluster into documented buckets — see
`~/docs/python-kernel/comparator-diff-tasklist.md`.

## Test plan

- [x] `cargo test --lib` — 421/421 pass (3 new tests on top of #64
      baseline: named StatementParameter JSON shape, named
      TypedValue helper, named Binary rejection)
- [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 pecotesting warehouse. New: `select_with_named_params`
      passes, `mixed_positional_and_named_params_is_server_side_error`
      documents the server-side constraint.
- [x] Full thrift-vs-kernel comparator (132 cases): 97 / 34 / 1
      skipped — bucket B1 confirmed dropped from 1 → 0.

Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
@vikrantpuppala
vikrantpuppala force-pushed the feat/intervals-as-string branch from fa69fd3 to dd1a864 Compare May 25, 2026 06:30
@vikrantpuppala
vikrantpuppala requested a review from a team as a code owner May 25, 2026 06:30
vikrantpuppala added a commit that referenced this pull request May 25, 2026
…schema + composite + TIMESTAMP tz + getTables/getColumns metadata + named params

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

### 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. Nested shapes
  parse correctly; bad input falls back to `Utf8`.

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

Plain TIMESTAMP is logically TIMESTAMP_LTZ; the non-empty wire
schema emits `Timestamp(Microsecond, Some("Etc/UTC"))`. Split the
TIMESTAMP / TIMESTAMP_NTZ match arms.

### 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". Picks Thrift's reading for parity.

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

`reshape_columns` (and `reshape_tables`) emitted Arrow nulls for
REMARKS when the server didn't supply a comment. New
`utf8_column_or_empty(batch, name)` helper substitutes "" for null
entries.

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

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

### 8. Named-parameter binding (new)

`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 was sourced from the kernel's local Rust
`StatementParameter` struct, which only had `ordinal`. The
canonical SEA proto (`sql_exec_api_service.proto`) defines:

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

## 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 (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 real diffs) |
| Bucket B1 (named params) | 1 | 0 ✅ |
| Fully-clean (config × suite) pairs | 12 / 30 | 18 / 30 |

Remaining diffs cluster into documented buckets — see
`~/docs/python-kernel/comparator-diff-tasklist.md`.

## Test plan

- [x] `cargo test --lib` — 421/421 pass (3 new tests on top of #64
      baseline: named StatementParameter JSON shape, named
      TypedValue helper, named Binary rejection)
- [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 pecotesting warehouse. New: `select_with_named_params`
      passes, `mixed_positional_and_named_params_is_server_side_error`
      documents the server-side constraint.
- [x] Full thrift-vs-kernel comparator (132 cases): 97 / 34 / 1
      skipped — bucket B1 confirmed dropped from 1 → 0.

Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
@vikrantpuppala
vikrantpuppala force-pushed the feat/intervals-as-string branch from dd1a864 to 9996717 Compare May 25, 2026 07:04
@vikrantpuppala

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. Summary of what's addressed in the new push (9996717):

P1 — fixed

1. element → item ✅

  • parse_array now uses Field::new_list_field(...) (which emits "item", the arrow-rs canonical default matching every other call site in this kernel).
  • New regression test test_array_field_name_is_item_not_element locks in the convention so an empty-result ARRAY<INT> schema stays field-equal with the non-empty wire payload.

2. INTERVAL whitespace split + type_interval_type ✅

  • parse_type now splits the base on < / ( or whitespace, so canonical SEA type_text "INTERVAL YEAR TO MONTH" / "INTERVAL DAY TO SECOND" parses with base = "INTERVAL" instead of falling to Utf8.
  • New databricks_type_to_arrow_with_interval(type_text, type_interval_type) accepts the manifest's hint. resolve_interval_unit prefers the hint ("YEAR_MONTH" → IntervalUnit::YearMonth, "DAY_TIME" → IntervalUnit::DayTime); falls back to keyword-matching type_text when the hint is absent; bare "INTERVAL" keeps the historical DayTime default.
  • Caller in reader/mod.rs:240 plumbs col.type_interval_type.as_deref() through.
  • Existing test updated to use the real wire strings; new test_interval_real_wire_strings_resolve_to_correct_unit, test_interval_type_interval_type_hint_wins, and test_extract_schema_from_manifest_interval_keyword_fallback cover the full matrix.

P2 — fixed

3. NEXT_CHANGELOG.md note — skipped. Confirmed there's no CHANGELOG.md / NEXT_CHANGELOG.md in the kernel repo (pre-1.0, no release process gated on changelog yet). Happy to add one in a follow-up if the repo grows a changelog convention.

5. Recursion depth guard ✅

  • Added MAX_PARSE_DEPTH = 64 + if depth >= MAX_PARSE_DEPTH { return None; } at the top of parse_type. parse_array/parse_map/parse_struct pass depth + 1. New test test_parse_type_deeply_nested_falls_back_to_utf8 covers this.

7. DECIMAL(0,0) / out-of-range clamps ✅

  • parse_decimal_params now clamps precision into [1, 38] and scale into [-38, 38]. New test test_decimal_clamps_invalid_precision_scale covers both ends.

8. ..Default::default() in test literals ✅

  • All four PostProcessOptions { ... } test literals now use ..Default::default() so future fields don't break tests.

P2 — punted

4. MAP/STRUCT field names validated against captured SEA wire payload — punted. The comparator (full thrift-vs-kernel run, 132 cases) exercises the full surface end-to-end on real warehouses, including non-empty ARRAY/MAP/STRUCT columns; the field-name parity is implicitly validated by the byte-equal row comparison. If you want a dedicated unit test against a captured IPC payload I can add it in a follow-up.

6. STRUCT<a:STRING>> bracket-balance — punted. Corner-case input the server wouldn't emit; current rfind('>') silently parses it as Struct{a:Utf8}. The fix is to validate bracket depth ends at 0 — easy if it ever bites, but tracking down a real reproducer first.

Test results

  • cargo test --lib: 435 / 435 pass (was 428 — 7 new tests)
  • cargo test --test v0_execute_wiremock: 11 / 11 pass
  • Live e2e on the pecotesting warehouse — unchanged from prior run
  • Full thrift-vs-kernel comparator unchanged (97/34/1 of 132)

Signed off the amended commit.

…schema + composite + TIMESTAMP tz + getTables/getColumns metadata + named params

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

### 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. Nested shapes
  parse correctly; bad input falls back to `Utf8`.

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

Plain TIMESTAMP is logically TIMESTAMP_LTZ; the non-empty wire
schema emits `Timestamp(Microsecond, Some("Etc/UTC"))`. Split the
TIMESTAMP / TIMESTAMP_NTZ match arms.

### 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". Picks Thrift's reading for parity.

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

`reshape_columns` (and `reshape_tables`) emitted Arrow nulls for
REMARKS when the server didn't supply a comment. New
`utf8_column_or_empty(batch, name)` helper substitutes "" for null
entries.

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

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

### 8. Named-parameter binding (new)

`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 was sourced from the kernel's local Rust
`StatementParameter` struct, which only had `ordinal`. The
canonical SEA proto (`sql_exec_api_service.proto`) defines:

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

## 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 (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 real diffs) |
| Bucket B1 (named params) | 1 | 0 ✅ |
| Fully-clean (config × suite) pairs | 12 / 30 | 18 / 30 |

Remaining diffs cluster into documented buckets — see
`~/docs/python-kernel/comparator-diff-tasklist.md`.

## Test plan

- [x] `cargo test --lib` — 421/421 pass (3 new tests on top of #64
      baseline: named StatementParameter JSON shape, named
      TypedValue helper, named Binary rejection)
- [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 pecotesting warehouse. New: `select_with_named_params`
      passes, `mixed_positional_and_named_params_is_server_side_error`
      documents the server-side constraint.
- [x] Full thrift-vs-kernel comparator (132 cases): 97 / 34 / 1
      skipped — bucket B1 confirmed dropped from 1 → 0.

Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
@vikrantpuppala
vikrantpuppala force-pushed the feat/intervals-as-string branch from 9996717 to d96879a Compare May 25, 2026 07:31
@vikrantpuppala
vikrantpuppala merged commit fd2c576 into docs/complex-types-json-stringify May 25, 2026
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