Repository navigation
fix(backend/kernel): comparator parity — async retention + intervals_as_string + precision/scale + named params + utils.exc fix - #803
Conversation
291e18e to
312164a
Compare
312164a to
81f065f
Compare
81f065f to
932ec74
Compare
932ec74 to
73760c7
Compare
|
Minor Missing unit test for the new decimal precision/scale extraction (tests/unit/test_kernel_type_mapping.py) _async_statements[guid] = stmt overwrite leaks on duplicate statement_id (client.py:305) cancel_command does not release the parent Statement (client.py:333-346) intervals_as_string=True is hard-coded with no opt-out (client.py:188) Stale-wheel errors for intervals_as_string / bind_named_param surface as generic OperationalError("Unexpected error from databricks_sql_kernel: ...") (client.py:172-192, type_mapping.py:235) |
73760c7 to
ecd0d37
Compare
|
Thanks for the review. Summary of what's addressed in the new push ( Item 1 — fixedMissing decimal precision/scale unit test ✅
The existing
Items 2, 3, 4, 5 — accepted as documentedPer your own punt signals, leaving these as-is for follow-up:
Signed off the amended commit. |
…as_string + precision/scale + named params + utils.exc fix Five small comparator-parity fixes surfaced by the same audit run. All are independently small but ship together because they share the kernel-backend client surface and the audit baseline. ### 1. Async Statement retention `KernelDatabricksClient.execute_command` closed the parent `Statement` in `finally` regardless of `async_op`. The kernel's `Statement.close()` invalidates child handles (see databricks-sql-kernel `src/statement/validity.rs`), so the async handle died before the user could poll it — breaking `execute_async` → `is_query_pending` → `get_async_execution_result`. Fix: when `async_op=True`, retain the parent Statement in a new `_async_statements` dict alongside `_async_handles`, and close it from `close_command`, `close_session`, and `get_execution_result` after the executed handle is done. Comparator outcome: STATEMENT_ASYNC suite 3/3 match (was 0/3). ### 2. `intervals_as_string` wire-through pyarrow's Python bindings cannot decode Arrow's `month_interval` type (id 21 — `KeyError` from `.as_py`, `to_pylist`, `cast(string)`, `to_pandas`). Every kernel-backend `SELECT *` over a table with an `INTERVAL YEAR TO MONTH` column raised `ArrowNotImplementedError` — 32 / 88 audit diffs. Fix: pass `intervals_as_string=True` to the kernel `Session(...)` constructor unconditionally. The kernel post-processor stringifies `Interval` / `Duration` columns server-side to `Utf8` (kernel PR #64). Comparator outcome: bucket A (ArrowNotImplementedError) 32 → 0. ### 3. Decimal precision/scale extraction `description_from_arrow_schema` hard-coded `None` for PEP 249 description-tuple slots 4 and 5. For DECIMAL columns the Arrow schema carries `precision` / `scale` on `Decimal128Type`, but they were silently dropped — 88 cell diffs (44 precision + 44 scale). Fix: factor out `_precision_scale_for_arrow_type(arrow_type)` and call it from the description builder. Today it only handles decimals; future extensions slot in here. Comparator outcome: 88 precision+scale diffs → 0. ### 4. Named-parameter binding `bind_tspark_params` raised `NotSupportedError` for any `TSparkParameter` with `name` set. The canonical SEA proto marks `StatementParameter.name` as `openapi_required=true` (named is the spec-required public form; `ordinal` is `PUBLIC_UNDOCUMENTED`). Kernel PR #65 added a `Statement.bind_named_param` PyO3 API. Fix: route named bindings via the new API. Positional ordinals self-increment so a named entry in the middle of the list doesn't claim a positional slot. Comparator outcome: PREPARED_STATEMENT_NAMED 1/1 match (was 0/1). Full thrift-vs-kernel run: 97/132 match (was 96/132). ### 5. `utils.ParamEscaper` `exc.ProgrammingError` import fix `ParamEscaper.escape_args` and `escape_item` both raised `exc.ProgrammingError(...)`, but `exc` was never imported. On any unsupported parameter shape the user saw `NameError: name 'exc' is not defined` instead of a clean PEP 249 `ProgrammingError`. Surfaced via the same audit harness running INLINE_PARAMS: both backends raised `NameError`, which the comparator's class+message match treated as parity — a false-positive that hid both the driver bug and the underlying caller-side type mismatch. Fix: import `ProgrammingError` directly from `databricks.sql.exc` (matching the pattern used in `session.py`, `client.py`, `result_set.py`, etc.) and replace the two `exc.ProgrammingError(...)` sites with bare `ProgrammingError(...)`. ## Dependencies Items #2, #3, and #4 require the matching databricks-sql-kernel changes: PR #64 (`intervals_as_string` + empty-result schema fix) and PR #65 (named-param binding). For local testing the comparator harness uses `KERNEL_FREEZE=1` against a kernel checkout of the feature branches. ## Headline comparator results (full thrift-vs-kernel run) | | Before | After | |------------------------------------|--------|-------| | match / diff / skipped | 60 / 88 / 0 | **97 / 34 / 1** | | Bucket A (ArrowNotImplementedError)| 32 | 0 | | `decimal_column` precision/scale | 88 | 0 | | Bucket B1 (named params) | 1 | 0 | | Suites fully clean | 12 / 30 | **17 / 30** | Remaining 34 diffs cluster into documented causes (complex types in `fetchall_arrow`, timestamp tz on Arrow path, VOID surface, METADATA pattern semantics) — tracked in `~/docs/python-kernel/comparator-diff-tasklist.md`. ## Test plan - [x] Manual repro of async path: `cur.execute_async("SELECT 1")` → `is_query_pending` → `get_async_execution_result` → `fetchall` succeeds on `use_kernel=True` - [x] Manual repro of interval path: `cur.execute("SELECT ym_interval_column FROM ...")` returns string-shaped rows matching the Thrift surface - [x] Manual repro of decimal path: `cur.description` for a `DECIMAL(10,2)` column now reports `precision=10, scale=2` - [x] Live e2e: `test_parameterized_query_named_params` / `test_parameterized_query_named_param_with_null` (added) - [x] Unit tests: `bind_tspark_params` named/positional/mixed routing (`tests/unit/test_kernel_type_mapping.py`) - [x] Manual repro of utils fix: `ParamEscaper().escape_args(object())` raises `ProgrammingError`, not `NameError` - [x] Full thrift-vs-kernel comparator: 97 / 34 / 1 of 132 - [x] Existing connector unit suite: 752 passed Co-authored-by: Isaac Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
ecd0d37 to
7adb049
Compare
…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>
Summary
Five comparator-parity fixes bundled because they share the same audit baseline and the same kernel-backend client surface.
1. Async Statement retention
KernelDatabricksClient.execute_commandclosed the parentStatementinfinallyregardless ofasync_op. The kernel'sStatement.close()invalidates child handles (seedatabricks-sql-kernel/src/statement/validity.rs), so the async handle was being killed before the user could poll it — breaking the entire async surface (execute_async→is_query_pending→get_async_execution_result).Fix: when
async_op=True, retain the parent Statement in a new_async_statementsdict alongside_async_handles, and close it fromclose_command,close_session, andget_execution_resultafter the executed handle is done.Comparator outcome: STATEMENT_ASYNC suite 3/3 match (was 0/3).
2.
intervals_as_stringwire-through (companion to kernel PR #64)pyarrow's Python bindings cannot decode Arrow's
month_intervaltype at all (id 21 — raisesKeyErrorfrom.as_py,to_pylist,cast(string),to_pandas). Every kernel-backendSELECT *over any table with anINTERVAL YEAR TO MONTHcolumn threwArrowNotImplementedError— 32 / 88 audit diffs.Fix: pass
intervals_as_string=Trueto the kernelSession(...)constructor unconditionally. The kernel post-processor then stringifiesInterval/Durationcolumns server-side toUtf8(see kernel PR #64), so pyarrow never sees the unreadable type.Comparator outcome: bucket A (ArrowNotImplementedError) drops from 32 → 0 diffs.
3. Decimal precision/scale extraction
description_from_arrow_schemahard-codedNonefor slots 4 and 5 of the PEP 249 description tuple. For DECIMAL columns the Arrow schema carriesprecision/scaleonDecimal128Type, but we were silently dropping them. The kernel backend returned:while Thrift returned:
Any consumer that reads PEP 249 slots 4/5 (SQLAlchemy, pandas-read-sql, etc.) can't distinguish
DECIMAL(10,2)fromDECIMAL(38,18)on the kernel backend. 88 comparator diffs (44 precision + 44 scale).Fix: factor out
_precision_scale_for_arrow_type(arrow_type)and call it from the description builder. Today it only handles decimals; future extensions (e.g. fractional-second precision fromTime64Type) slot in here without touching the description builder.Comparator outcome: 88 precision+scale diffs → 0.
4. Named-parameter binding (companion to kernel PR #65)
bind_tspark_paramspreviously raisedNotSupportedErrorfor anyTSparkParameterwithnameset. The canonical SEA proto marksStatementParameter.nameasopenapi_required=true— named binding is the spec-required public form, andordinalisPUBLIC_UNDOCUMENTED. Kernel PR #65 added aStatement.bind_named_paramPyO3 API mirroringbind_param.Fix: route named bindings via the new kernel API. Positional ordinals self-increment so a named entry in the middle of the list doesn't claim a positional slot.
Comparator outcome: PREPARED_STATEMENT_NAMED 1/1 match (was 0/1). Bucket B1 in
comparator-diff-tasklist.mddrops to 0 diffs.5.
utils.ParamEscaperexc.ProgrammingErrorimport fix (was PR #802)ParamEscaper.escape_argsandParamEscaper.escape_itemboth raisedexc.ProgrammingError(...)(lines 551 and 609 ofutils.py), butexcwas never imported. On any unsupported parameter shape the user sawNameError: name 'exc' is not definedinstead of a clean PEP 249ProgrammingError.Surfaced via the python-comparator audit harness running the
INLINE_PARAMSconnection config: both backends raisedNameError, which the comparator's class+message match treated as parity — a false-positive that hid both the real driver bug and the underlying caller-side type mismatch.Fix: import
ProgrammingErrordirectly fromdatabricks.sql.exc(matching the pattern used insession.py,client.py,result_set.py, etc.) and replace the twoexc.ProgrammingError(...)sites with bareProgrammingError(...).Dependencies
Items #2, #3, and #4 require the matching
databricks-sql-kernelchanges:intervals_as_stringpost-processor + empty-result schema fix + composite type parser + TIMESTAMP tz + metadata reshape fixesStatementParameter.name+bind_named_paramAPI (to be opened)For local testing the comparator harness uses
KERNEL_FREEZE=1against a kernel checkout of the feature branches.Headline comparator results (full thrift-vs-kernel run)
decimal_columnprecision/scaleRemaining 34 diffs cluster into documented causes (complex types in
fetchall_arrow, timestamp tz on Arrow path, VOID surface, METADATA pattern semantics, empty-result nullability) — tracked in~/docs/python-kernel/comparator-diff-tasklist.md.Test plan
cur.execute_async("SELECT 1"); while cur.is_query_pending(): time.sleep(0.2); cur.get_async_execution_result(); cur.fetchall()succeeds onuse_kernel=Truecur.execute("SELECT ym_interval_column FROM ...")returns string-shaped rows matching the Thrift surfacecur.descriptionfor aDECIMAL(10,2)column now reportsprecision=10, scale=2on both backendstest_parameterized_query_named_params/test_parameterized_query_named_param_with_null(added) pass against pecotesting warehousebind_tspark_paramsnamed/positional/mixed routing (tests/unit/test_kernel_type_mapping.py)ParamEscaper().escape_args(object())raisesProgrammingError, notNameErrorThis pull request and its description were written by Isaac.