Skip to content

feat(session/metadata/pyo3): attach async statement by id, case-insensitive table_types, SEA error envelope, num_modified_rows - #139

Merged
vikrantpuppala merged 1 commit into
mainfrom
feat/use-kernel-cuj-batch3
Jun 8, 2026
Merged

vikrantpuppala merged 1 commit into
mainfrom
feat/use-kernel-cuj-batch3

Conversation

@vikrantpuppala

@vikrantpuppala vikrantpuppala commented Jun 6, 2026 •

Copy link
Copy Markdown
Collaborator

What

Batch-3 kernel changes backing the connector's use_kernel parity work (paired with databricks/databricks-sql-python#838).

table_types — case-insensitive (B2)

filter_tables_by_type matches requested types with eq_ignore_ascii_case, so tables(table_types=['view']) matches a VIEW row regardless of the server's canonical casing.

Parse the SEA error envelope on transport-level HTTP errors

client/http.rs now best-effort parses the SEA {error_code, message, sql_state} envelope (and the {"error": ...} wrapper) on non-2xx errors, attaching error_code / sql_state to the returned Error instead of discarding them into the raw message. Mirrors what the statement path (sea.rs terminal_outcome) already did.

Expose num_modified_rows through pyo3

#[getter] ExecutedStatement.num_modified_rows so the connector can surface DML rowcount as cursor.rowcount.

Session::attach_async_statement(id) — resume an async statement by id

Re-attach to an already-submitted server statement by its id, yielding an ExecutedAsyncStatement that can poll status() / await results / cancel — without having been the handle that submitted it. SEA keys GetStatementStatus/GetStatementResult purely on the id, so this enables resuming an async statement whose originating handle was dropped (or lives in another process).

Key design points:

  • Non-owning. The attached handle starts closed=true, so it does not close the server statement on Drop or via close(). Attach is a read-only adopt — the statement's lifecycle stays with whatever submitted it. Without this, a poll loop that re-attaches each tick would close the very statement it's watching. (Locked by attached_handle_drop_does_not_close_statement.)
  • Standalone validity. Fresh ValidityFlag (no parent Statement to share with), so a re-execute elsewhere can't invalidate it.
  • Seeds status from the wire. Issues one GetStatementStatus; an unknown/expired id surfaces ErrorCode::NotFound (404). A closed statement is not an error — the server keeps reporting CLOSED until the result TTL elapses.

Verified against a live SEA warehouse: GET after close → 200 state=CLOSED (idempotent); a closed-but-succeeded statement keeps reporting SUCCEEDED + result; an unknown well-formed id → 404 NOT_FOUND (distinct from a malformed-id 400 and a transient 5xx).

This is what lets the connector make async command state server-sourced — see databricks/databricks-sql-python#838, which deletes its _closed_commands local-state bookkeeping in favour of re-attaching by id.

Testing

  • Wiremock: attach_seeds_status_and_reports_server_state, attach_reports_closed_for_a_closed_statement, attach_errors_not_found_for_unknown_id, attached_handle_drop_does_not_close_statement; plus the existing B2 / HTTP-envelope / num_modified_rows tests.
  • cargo +stable fmt --all, cargo clippy --all-targets -- -D warnings (kernel + pyo3), full cargo test — all green.

…ror envelope, expose num_modified_rows, attach async statement

Batch-3 kernel changes backing the connector's use_kernel parity work:

- metadata: ``filter_tables_by_type`` matches ``table_types``
  case-insensitively (``eq_ignore_ascii_case``) so ``tables(['view'])``
  matches a ``VIEW`` row regardless of server casing.
- client/http: parse the SEA error envelope (``{error_code, message,
  sql_state}``, also the ``{"error": ...}`` wrapper) on transport-level
  HTTP errors, attaching ``error_code`` / ``sql_state`` to the returned
  ``Error`` instead of discarding them into the raw message.
- pyo3: expose ``ExecutedStatement.num_modified_rows`` so the connector
  can surface DML rowcount.
- session: add ``Session::attach_async_statement(id)`` (+ pyo3 getter) —
  re-attach to an already-submitted server statement by its id, yielding
  an ``ExecutedAsyncStatement`` that can poll ``status`` / await results
  without having been the submitting handle. SEA keys
  GetStatementStatus/Result purely on the id, so this enables resuming an
  async statement whose originating handle was dropped (or lives in
  another process). The handle is NON-OWNING: it does not close the
  server statement on ``Drop`` or ``close()`` (starts ``closed=true``),
  so re-attaching on every poll can't tear down the statement being
  watched. Seeds initial status from a ``GetStatementStatus``; an
  unknown/expired id surfaces ``ErrorCode::NotFound`` (404). Verified
  against a live SEA warehouse: GET after close returns 200 state=CLOSED
  until TTL, then 404 NOT_FOUND.

Co-authored-by: Isaac
Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
@vikrantpuppala
vikrantpuppala force-pushed the feat/use-kernel-cuj-batch3 branch from 3991d8b to 0ab1e0e Compare June 8, 2026 11:57
@vikrantpuppala vikrantpuppala changed the title feat(metadata/http/pyo3): case-insensitive table_types, parse HTTP error envelope, expose num_modified_rows feat(session/metadata/pyo3): attach async statement by id, case-insensitive table_types, SEA error envelope, num_modified_rows Jun 8, 2026
@vikrantpuppala
vikrantpuppala added this pull request to the merge queue Jun 8, 2026
@gopalldb

gopalldb commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator

P1 — Should fix

  1. Attached handle's await_result() fires cancel_statement on mid-poll drop, violating the "read-only adopt" contract
  • src/statement/executed_async.rs:382-383 (AwaitResultCancelGuard::new(...) is unconditional); contract claim in src/session.rs:374-398.
  • The new attach_async_statement doc says "non-owning… does NOT close the server statement on Drop or via close". The closed=true init delivers that for Drop and close(). But await_result() unconditionally
    installs AwaitResultCancelGuard, which fires cancel_statement(statement_id) if the await future is dropped mid-poll (canonical tokio::time::timeout pattern).
  • Concrete scenario: another caller owns the statement, this caller adopts the id to passively observe, wraps await_result() in a timeout, timeout fires → server statement gets cancelled out from under the
    owner. The wiremock test only asserts the DELETE case; the cancel-on-await-drop case is untested.
  • Fix: Add an "owning" flag parallel to closed, gate the cancel guard on it. For attached handles, either skip the guard or short-circuit await_result to a status poll with no guard. Or document loudly that
    await_result() is unsafe to drop mid-poll for attached handles and have callers use status() + fetch_result(). Add a wiremock test asserting zero POST .../cancel on dropped await_result() for an attached
    handle.
  1. ExecutedAsyncStatement::cancel() on attached handles fires cancel_statement against a statement the caller doesn't own
  • src/statement/executed_async.rs:563-573; surface claim in pyo3/src/executed_async.rs:122-128.
  • The docstring lists cancel/close as supported on an attached handle, so this may be intentional — but if attach is meant as passive read-only adopt (as the doc text repeatedly emphasises), an explicit
    cancel() lets a polling caller terminate another owner's statement. Doc is ambiguous about whether cancel is a first-class attach capability or a side-effect-on-the-other-owner footgun.
  • Fix: Decide explicitly. Either (a) keep cancel as first-class and document "cancel succeeds regardless of which handle submitted; use only when you intentionally want to interrupt the owner" — legitimate
    for admin tooling. Or (b) short-circuit cancel() to an error on attached handles via the "owning" flag.
  1. http_error accepts malformed SQLSTATE values that terminal_outcome rejects
  • src/client/http.rs:78-80 vs src/client/sea.rs:291.
  • The new http_error validates sql_state with only .filter(|s| !s.is_empty()). The sibling terminal_outcome requires .filter(|s| s.len() == 5) — the canonical SQLSTATE shape. The new code's docstring claims
    "same precedence as terminal_outcome" but the validation is weaker. A server returning "sql_state": "X" or "sql_state": "garbage" would populate Error.sql_state with junk that wrappers surface verbatim.
  • Fix: Use the same predicate as terminal_outcome:
    let sql_state = svc.sql_state
    .filter(|s| s.len() == 5)
    .or_else(|| crate::kernel_error::extract_sqlstate_from_message(msg));

P2 — Minor

  1. attach_async_statement doesn't attach query_id to the NotFound error
  • src/session.rs:399-403 + src/client/http.rs:51-93.
  • When statement_status(&statement_id).await? returns 404, http_error builds an Error from the body but doesn't call .with_query_id(statement_id). terminal_outcome sets query_id on every error it builds.
  • Fix: Two lines in attach_async_statement: .map_err(|e| e.with_query_id(&statement_id)).
  1. table_types filter is case-insensitive but list_table_types() advertises "SYSTEM TABLE" (space) while the new test expects "SYSTEM_TABLE" (underscore)
  • src/client/sea.rs:1213 vs src/metadata/thrift_shape.rs:1166.
  • Pre-existing inconsistency that the new case-insensitive test surfaces. A caller that fetches the canonical list via metadata.table_types() and round-trips it into list_tables(table_types=...) may or may
    not get results depending on what the server emits in TABLE_TYPE.
  • Fix: Follow-up PR to verify the actual SEA SHOW TABLES TABLE_TYPE casing and reconcile list_table_types() with the canonical server output. Not blocking this PR.
  1. http_error re-parses the entire response body twice for the wrapper-envelope path
  • src/client/http.rs:57-64. Two full JSON walks on the same body. Not a hot path.
  • Fix: Parse to serde_json::Value once, then try both shapes via serde_json::from_value. Skip if perf is a non-concern (it is).
  1. http_error falls back to using raw body as message when only error_code is set
  • src/client/http.rs:71. When envelope parses with error_code: Some(...) but message: None, let msg = svc.message.as_deref().unwrap_or(body) makes the human-readable message the raw JSON. Cosmetic but ugly
    in logs.
  • Fix: Synthesize a message like format!("server returned error_code {}", ec) instead of stuffing the raw JSON.
  1. Wiremock test doesn't exercise the cancel-on-await_result-drop case
  • tests/v0_async_execute_wiremock.rs:1088-1120. Only verifies DELETE is not fired on idle drop. Doesn't verify that dropping a mid-flight await_result() does or doesn't fire cancel_statement.
  • Fix: Add a test that wraps await_result() in a short timeout and asserts the cancel endpoint expectation matches the intended contract. If P1 Initial import: Databricks ADBC Rust driver as databricks-sql-kernel #1 is fixed, expect 0 cancels; if resolved by docs only, expect
    ≥1 (and pin the current behaviour).

Merged via the queue into main with commit 7ffb30d Jun 8, 2026
21 checks passed

This branch was previously deployed

1 inactive deployment
azure-prod — 0ab1e0e5 Deployed Jun 8, 2026 by vikrantpuppala via PyO3 build + test (Python 3.13) #114
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