From b41acc081e7e52a7c620bd9881f0a9d205c40de1 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Wed, 13 May 2026 09:50:03 +0000 Subject: [PATCH 1/9] feat(pyo3): scaffold PyO3 sub-crate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 1 of the PySQL × kernel integration plan (docs/designs/pysql-kernel-integration.md). Adds a workspace-member sub-crate at `pyo3/` that builds a Python extension module named `databricks_sql_kernel` via maturin. PAT auth only; sync execute path; no metadata or async statement yet. Surface exposed to Python: - `Session(host, http_path, *, access_token, catalog=None, schema=None)` — opens a session against the live warehouse, owns a per-session multi-thread tokio runtime, exposes `.session_id`, `.statement()`, `.close()`. - `Statement` — `.set_sql(text)`, `.execute()`, `.close()`. - `ExecutedStatement` — `.statement_id`, `.arrow_schema()`, `.fetch_next_batch()`, `.fetch_all_arrow()`, `.cancel()`, `.close()`. - `KernelError` — single Python exception carrying structured `(code, message, sql_state, error_code, vendor_code, http_status, retryable, query_id)` for connector-side re-raising as PEP 249 classes. Every kernel call detaches the GIL with `py.detach(...)` so other Python threads can run during I/O. Arrow batches cross via arrow-pyarrow's `ToPyArrow` (zero-copy buffers, per-batch Python wrapper creation under the GIL). Workspace conversion: root `Cargo.toml` grows a `[workspace]` table with `members = [".", "pyo3"]`. Future bindings (napi-rs, etc.) slot in as additional members. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- Cargo.lock | 130 ++++++++++++++++++++++ Cargo.toml | 5 + pyo3/Cargo.toml | 48 ++++++++ pyo3/pyproject.toml | 16 +++ pyo3/src/errors.rs | 73 +++++++++++++ pyo3/src/lib.rs | 39 +++++++ pyo3/src/session.rs | 156 ++++++++++++++++++++++++++ pyo3/src/statement.rs | 248 ++++++++++++++++++++++++++++++++++++++++++ 8 files changed, 715 insertions(+) create mode 100644 pyo3/Cargo.toml create mode 100644 pyo3/pyproject.toml create mode 100644 pyo3/src/errors.rs create mode 100644 pyo3/src/lib.rs create mode 100644 pyo3/src/session.rs create mode 100644 pyo3/src/statement.rs diff --git a/Cargo.lock b/Cargo.lock index ccdad2f5..353520e1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -97,11 +97,26 @@ dependencies = [ "flatbuffers", ] +[[package]] +name = "arrow-pyarrow" +version = "57.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f45c7989cb70214b2f362eaa10266d15e1a433692f2ea1514018be3aace679f4" +dependencies = [ + "arrow-array", + "arrow-data", + "arrow-schema", + "pyo3", +] + [[package]] name = "arrow-schema" version = "57.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6bb63203e8e0e54b288d0d8043ca8fa1013820822a27692ef1b78a977d879f2c" +dependencies = [ + "bitflags", +] [[package]] name = "arrow-select" @@ -363,6 +378,18 @@ dependencies = [ "wiremock", ] +[[package]] +name = "databricks-sql-kernel-pyo3" +version = "0.1.0" +dependencies = [ + "arrow-array", + "arrow-pyarrow", + "arrow-schema", + "databricks-sql-kernel", + "pyo3", + "tokio", +] + [[package]] name = "deadpool" version = "0.12.3" @@ -679,6 +706,12 @@ version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + [[package]] name = "hermit-abi" version = "0.5.2" @@ -948,6 +981,15 @@ dependencies = [ "hashbrown 0.16.1", ] +[[package]] +name = "indoc" +version = "2.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706" +dependencies = [ + "rustversion", +] + [[package]] name = "ipnet" version = "2.11.0" @@ -1083,6 +1125,15 @@ version = "2.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + [[package]] name = "mime" version = "0.3.17" @@ -1324,6 +1375,12 @@ version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" +[[package]] +name = "portable-atomic" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" + [[package]] name = "potential_utf" version = "0.1.4" @@ -1351,6 +1408,67 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "pyo3" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ba0117f4212101ee6544044dae45abe1083d30ce7b29c4b5cbdfa2354e07383" +dependencies = [ + "indoc", + "libc", + "memoffset", + "once_cell", + "portable-atomic", + "pyo3-build-config", + "pyo3-ffi", + "pyo3-macros", + "unindent", +] + +[[package]] +name = "pyo3-build-config" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fc6ddaf24947d12a9aa31ac65431fb1b851b8f4365426e182901eabfb87df5f" +dependencies = [ + "target-lexicon", +] + +[[package]] +name = "pyo3-ffi" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "025474d3928738efb38ac36d4744a74a400c901c7596199e20e45d98eb194105" +dependencies = [ + "libc", + "pyo3-build-config", +] + +[[package]] +name = "pyo3-macros" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e64eb489f22fe1c95911b77c44cc41e7c19f3082fc81cce90f657cdc42ffded" +dependencies = [ + "proc-macro2", + "pyo3-macros-backend", + "quote", + "syn", +] + +[[package]] +name = "pyo3-macros-backend" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "100246c0ecf400b475341b8455a9213344569af29a3c841d29270e53102e0fcf" +dependencies = [ + "heck", + "proc-macro2", + "pyo3-build-config", + "quote", + "syn", +] + [[package]] name = "quinn" version = "0.11.9" @@ -1903,6 +2021,12 @@ dependencies = [ "libc", ] +[[package]] +name = "target-lexicon" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + [[package]] name = "tempfile" version = "3.24.0" @@ -2195,6 +2319,12 @@ version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5" +[[package]] +name = "unindent" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7264e107f553ccae879d21fbea1d6724ac785e8c3bfc762137959b5802826ef3" + [[package]] name = "untrusted" version = "0.9.0" diff --git a/Cargo.toml b/Cargo.toml index 4bcd6b86..c6012cbd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -76,3 +76,8 @@ tempfile = "3" [lib] name = "databricks_sql_kernel" crate-type = ["lib", "cdylib", "staticlib"] + +# Workspace — the kernel is the root crate; language bindings live as +# sibling members. PyO3 first; napi-rs / etc. slot in here later. +[workspace] +members = [".", "pyo3"] diff --git a/pyo3/Cargo.toml b/pyo3/Cargo.toml new file mode 100644 index 00000000..ebd3cfbf --- /dev/null +++ b/pyo3/Cargo.toml @@ -0,0 +1,48 @@ +# Copyright (c) 2026 Databricks, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +[package] +name = "databricks-sql-kernel-pyo3" +version = "0.1.0" +edition = "2021" +authors = ["Databricks"] +license = "Apache-2.0" +description = "PyO3 Python bindings for the Databricks SQL Kernel" +repository = "https://github.com/databricks/databricks-sql-kernel" + +# Built as a Python extension module by maturin. The lib basename here +# only affects the intermediate `.so` cargo produces; maturin renames +# the wheel artifact to `databricks_sql_kernel..so` per +# `module-name` in pyproject.toml, and pyo3 derives the `PyInit_*` +# symbol from the `#[pymodule]` function name (not this `[lib].name`). +# Picking a distinct name avoids colliding with the kernel root crate's +# own cdylib output. +[lib] +name = "databricks_sql_kernel_pyo3" +crate-type = ["cdylib"] + +[dependencies] +databricks-sql-kernel = { path = ".." } + +# pyo3 — abi3-py39 lets one wheel cover Python 3.9+. +pyo3 = { version = "0.26", features = ["extension-module", "abi3-py39"] } + +# Multi-thread runtime — one per Session, owned on the Rust side. +tokio = { version = "1", features = ["rt-multi-thread"] } + +# Arrow handoff. Pinned to 57 to match the kernel's arrow-* deps so we +# share the same RecordBatch / Schema types and never have to convert. +arrow-array = "57" +arrow-schema = "57" +arrow-pyarrow = "57" diff --git a/pyo3/pyproject.toml b/pyo3/pyproject.toml new file mode 100644 index 00000000..cdaeade0 --- /dev/null +++ b/pyo3/pyproject.toml @@ -0,0 +1,16 @@ +[build-system] +requires = ["maturin>=1.5,<2.0"] +build-backend = "maturin" + +[project] +name = "databricks-sql-kernel" +version = "0.1.0" +description = "Python bindings for the Databricks SQL Kernel (PyO3)" +requires-python = ">=3.9" +license = { text = "Apache-2.0" } +authors = [{ name = "Databricks" }] +dependencies = ["pyarrow>=14"] + +[tool.maturin] +module-name = "databricks_sql_kernel" +features = ["pyo3/extension-module"] diff --git a/pyo3/src/errors.rs b/pyo3/src/errors.rs new file mode 100644 index 00000000..d14546dc --- /dev/null +++ b/pyo3/src/errors.rs @@ -0,0 +1,73 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! `KernelError` — single Python exception class carrying the kernel's +//! structured error info. +//! +//! Connector-side code (`backend/kernel/client.py`) inspects `code` +//! and re-raises as `DatabaseError` / `OperationalError` / +//! `ProgrammingError` per PEP 249. This module owns the only +//! `kernel::Error` → `PyErr` conversion site. + +use databricks_sql_kernel::{Error as KError, ErrorCode}; +use pyo3::create_exception; +use pyo3::exceptions::PyException; +use pyo3::prelude::*; +use pyo3::types::PyDict; + +create_exception!(databricks_sql_kernel, KernelError, PyException); + +/// Map a kernel `ErrorCode` to a stable string slug. Wrapper code +/// branches on `err.code` (a Python string) to choose the right +/// PEP 249 exception class. New `ErrorCode` variants compile-error +/// in this match by design — keeps the wrapper's exception mapping +/// in sync with the kernel. +fn code_str(code: ErrorCode) -> &'static str { + match code { + ErrorCode::InvalidArgument => "InvalidArgument", + ErrorCode::Unauthenticated => "Unauthenticated", + ErrorCode::PermissionDenied => "PermissionDenied", + ErrorCode::NotFound => "NotFound", + ErrorCode::ResourceExhausted => "ResourceExhausted", + ErrorCode::Unavailable => "Unavailable", + ErrorCode::Timeout => "Timeout", + ErrorCode::Cancelled => "Cancelled", + ErrorCode::DataLoss => "DataLoss", + ErrorCode::Internal => "Internal", + ErrorCode::InvalidStatementHandle => "InvalidStatementHandle", + ErrorCode::NetworkError => "NetworkError", + ErrorCode::SqlError => "SqlError", + // `ErrorCode` is `#[non_exhaustive]`; new variants surface as + // "Unknown" on the Python side until this match is updated. + _ => "Unknown", + } +} + +/// Convert a kernel `Error` into a `KernelError` Python exception +/// with structured attributes attached. The exception message is the +/// kernel's `message`; structured fields live on `err.args[0]` (a +/// dict) for callers that want them. +pub(crate) fn to_py_err(py: Python<'_>, err: KError) -> PyErr { + let attrs = PyDict::new(py); + let _ = attrs.set_item("code", code_str(err.code)); + let _ = attrs.set_item("message", &err.message); + let _ = attrs.set_item("sql_state", err.sql_state.as_deref()); + let _ = attrs.set_item("error_code", err.error_code.as_deref()); + let _ = attrs.set_item("vendor_code", err.vendor_code); + let _ = attrs.set_item("http_status", err.http_status); + let _ = attrs.set_item("retryable", err.retryable); + let _ = attrs.set_item("query_id", err.query_id.as_deref()); + + KernelError::new_err((err.message.clone(), attrs.unbind())) +} diff --git a/pyo3/src/lib.rs b/pyo3/src/lib.rs new file mode 100644 index 00000000..6a2ca291 --- /dev/null +++ b/pyo3/src/lib.rs @@ -0,0 +1,39 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Python bindings for the Databricks SQL Kernel. +//! +//! Phase 1 scaffold: `Session`, `Statement`, `ExecutedStatement`. PAT +//! auth only; synchronous `execute()` path. Built as the +//! `databricks_sql_kernel` extension module via `maturin develop` / +//! `maturin build`. +//! +//! The kernel's API is async — every method call from Python detaches +//! the GIL and `block_on`s on the session-owned tokio runtime. + +mod errors; +mod session; +mod statement; + +use pyo3::prelude::*; + +#[pymodule] +fn databricks_sql_kernel(m: &Bound<'_, PyModule>) -> PyResult<()> { + m.add("__version__", env!("CARGO_PKG_VERSION"))?; + m.add("KernelError", m.py().get_type::())?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + Ok(()) +} diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs new file mode 100644 index 00000000..897f00bd --- /dev/null +++ b/pyo3/src/session.rs @@ -0,0 +1,156 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! `Session` — Python class wrapping the kernel's `Session`. +//! +//! Owns a multi-thread tokio runtime per session (one tokio worker +//! pool drives all I/O for this session). The runtime handle is +//! cloned into child `Statement` / `ExecutedStatement` objects so +//! they `block_on` the same pool without keeping the `Session` +//! pyclass alive longer than the user keeps a reference. + +use crate::errors::to_py_err; +use crate::statement::Statement; +use databricks_sql_kernel::{AuthConfig, Session as KSession}; +use pyo3::prelude::*; +use std::sync::Arc; +use tokio::runtime::{Builder, Runtime}; + +/// Python-facing session handle. +/// +/// `unsendable` — the kernel `Session` is `Send + Sync` (asserted in +/// the kernel's `lib.rs`), but the tokio `Runtime` is `!Send` once it +/// has been driven. Marking the pyclass unsendable keeps Python from +/// trying to migrate it across threads. +#[pyclass(name = "Session", unsendable)] +pub(crate) struct Session { + /// `None` after `close()`. Methods return a clean Python error + /// rather than panicking on a closed session. + inner: Option, +} + +pub(crate) struct SessionInner { + pub(crate) session: KSession, + pub(crate) runtime: Arc, +} + +#[pymethods] +impl Session { + /// Open a new session against the given workspace. + /// + /// PAT auth only in this phase. `host` may be bare + /// (`my-workspace.databricks.com`) or fully-qualified + /// (`https://...`). `http_path` is the SQL endpoint path. + #[new] + #[pyo3(signature = (host, http_path, *, access_token, catalog=None, schema=None))] + fn new( + py: Python<'_>, + host: String, + http_path: String, + access_token: String, + catalog: Option, + schema: Option, + ) -> PyResult { + if access_token.is_empty() { + return Err(pyo3::exceptions::PyValueError::new_err( + "access_token must not be empty", + )); + } + + // One tokio runtime per session. Multi-thread so CloudFetch + // chunk downloads can overlap with the main poll loop. Worker + // count left to tokio's default (logical CPU count). + let runtime = Arc::new( + Builder::new_multi_thread() + .enable_all() + .thread_name("dbx-sql-kernel") + .build() + .map_err(|e| { + pyo3::exceptions::PyRuntimeError::new_err(format!( + "failed to build tokio runtime: {e}" + )) + })?, + ); + + // `Session::open` is async and grabs the current tokio handle. + // Drive it on our runtime; detach the GIL while we wait so + // other Python threads can run. + let rt = runtime.clone(); + let open_result = py.detach(|| { + rt.block_on(async { + let mut builder = + KSession::builder() + .http_path(host, http_path) + .auth(AuthConfig::Pat { + token: access_token, + }); + if catalog.is_some() || schema.is_some() { + let mut defaults = databricks_sql_kernel::DefaultOpts::default(); + defaults.catalog = catalog; + defaults.schema = schema; + builder = builder.defaults(defaults); + } + builder.open().await + }) + }); + + let session = open_result.map_err(|e| to_py_err(py, e))?; + Ok(Self { + inner: Some(SessionInner { session, runtime }), + }) + } + + /// Server-issued session id. + #[getter] + fn session_id(&self) -> PyResult { + let inner = self.alive()?; + Ok(inner.session.session_id().to_owned()) + } + + /// Build a new `Statement` bound to this session. + fn statement(&self) -> PyResult { + let inner = self.alive()?; + let kstmt = inner.session.statement(); + Ok(Statement::new(kstmt, inner.runtime.clone())) + } + + /// Explicitly close the session. Idempotent. Subsequent calls on + /// this `Session` raise `KernelError`. + fn close(&mut self, py: Python<'_>) -> PyResult<()> { + let Some(inner) = self.inner.take() else { + return Ok(()); + }; + let SessionInner { session, runtime } = inner; + let close_result = py.detach(|| runtime.block_on(session.close())); + close_result.map_err(|e| to_py_err(py, e)) + } + + fn __repr__(&self) -> String { + match &self.inner { + Some(i) => format!( + "Session(session_id={:?}, closed=False)", + i.session.session_id() + ), + None => "Session(closed=True)".to_owned(), + } + } +} + +impl Session { + fn alive(&self) -> PyResult<&SessionInner> { + self.inner + .as_ref() + .ok_or_else(|| crate::errors::KernelError::new_err("Session is closed")) + } +} diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs new file mode 100644 index 00000000..cb482147 --- /dev/null +++ b/pyo3/src/statement.rs @@ -0,0 +1,248 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! `Statement` + `ExecutedStatement` Python classes. +//! +//! Sync-execute path only in this phase. Mirrors the kernel's +//! `Statement::execute() -> ExecutedStatement` flow: build a spec +//! (sql + params), call `execute()`, then drain the result stream +//! batch-by-batch as pyarrow `RecordBatch`es. + +use crate::errors::to_py_err; +use arrow_array::RecordBatch; +use arrow_pyarrow::ToPyArrow; +use arrow_schema::Schema; +use databricks_sql_kernel::{ + ExecutedStatement as KExecutedStatement, ExecutedStatementHandle, ResultBatch, + Statement as KStatement, +}; +use pyo3::prelude::*; +use std::sync::Arc; +use tokio::runtime::Runtime; + +/// Python-facing mutable statement. +/// +/// Spec mutation is collapsed into simple `set_*` / `bind_*` methods +/// for now. The full `Statement::spec()` API surface lands in later +/// phases (named params, statement_conf, result_format). +#[pyclass(name = "Statement", unsendable)] +pub(crate) struct Statement { + inner: Option, +} + +struct StatementInner { + stmt: KStatement, + runtime: Arc, +} + +impl Statement { + pub(crate) fn new(stmt: KStatement, runtime: Arc) -> Self { + Self { + inner: Some(StatementInner { stmt, runtime }), + } + } + + fn alive_mut(&mut self) -> PyResult<&mut StatementInner> { + self.inner + .as_mut() + .ok_or_else(|| crate::errors::KernelError::new_err("Statement is closed")) + } +} + +#[pymethods] +impl Statement { + /// Set the SQL text to execute. Replaces any previously-set SQL. + fn set_sql(&mut self, sql: String) -> PyResult<()> { + let inner = self.alive_mut()?; + inner.stmt.spec().sql(sql); + Ok(()) + } + + /// Wait-for-result execution. Blocks until the kernel finishes + /// polling and returns an `ExecutedStatement` with the result + /// stream ready to drain. + fn execute(&mut self, py: Python<'_>) -> PyResult { + let inner = self.alive_mut()?; + let runtime = inner.runtime.clone(); + let exec_result = py.detach(|| runtime.block_on(inner.stmt.execute())); + let exec = exec_result.map_err(|e| to_py_err(py, e))?; + Ok(ExecutedStatement::new(exec, runtime)) + } + + /// Drop the statement. Any prior `ExecutedStatement` keeps + /// working — kernel-side it has its own validity flag and + /// statement_id and is independent of the `Statement` lifecycle. + fn close(&mut self) { + self.inner = None; + } +} + +/// Python-facing executed statement handle. Owns the kernel +/// `ExecutedStatement` and serves the result stream lazily. +#[pyclass(name = "ExecutedStatement", unsendable)] +pub(crate) struct ExecutedStatement { + inner: Option, + /// Cached statement id so callers can read it after `close()` + /// (e.g. for logging the id of a just-closed statement). + statement_id: String, + /// Cached schema. Pulled from the kernel once on construction — + /// available even after `close()` so descriptions stay stable. + schema: Arc, +} + +struct ExecutedInner { + exec: KExecutedStatement, + runtime: Arc, + exhausted: bool, +} + +impl ExecutedStatement { + fn new(exec: KExecutedStatement, runtime: Arc) -> Self { + let statement_id = exec.statement_id().to_owned(); + let schema = exec.schema(); + Self { + statement_id, + schema, + inner: Some(ExecutedInner { + exec, + runtime, + exhausted: false, + }), + } + } + + fn alive_mut(&mut self) -> PyResult<&mut ExecutedInner> { + self.inner + .as_mut() + .ok_or_else(|| crate::errors::KernelError::new_err("ExecutedStatement is closed")) + } +} + +#[pymethods] +impl ExecutedStatement { + #[getter] + fn statement_id(&self) -> &str { + &self.statement_id + } + + /// Result schema as a `pyarrow.Schema`. Available even after + /// `close()`. + fn arrow_schema<'py>(&self, py: Python<'py>) -> PyResult> { + self.schema.as_ref().to_pyarrow(py) + } + + /// Pull the next batch as a `pyarrow.RecordBatch`, or `None` if + /// the stream is exhausted. + fn fetch_next_batch<'py>(&mut self, py: Python<'py>) -> PyResult>> { + let inner = self.alive_mut()?; + if inner.exhausted { + return Ok(None); + } + // Drive next_batch() on the session runtime with the GIL + // released for the whole I/O. The returned reference borrows + // from the stream; clone the RecordBatch (Arc-backed columns + // — cheap) out into an owned value so the borrow ends before + // we touch pyarrow. + let runtime = inner.runtime.clone(); + let batch_result: databricks_sql_kernel::Result> = py.detach(|| { + runtime.block_on(async { + let stream = inner.exec.result_stream_mut(); + match stream.next_batch().await? { + Some(ResultBatch::Arrow(rb)) => Ok(Some(rb.clone())), + Some(_) => Err(databricks_sql_kernel::Error::invalid_argument() + .message("kernel returned a non-Arrow ResultBatch variant")), + None => Ok(None), + } + }) + }); + match batch_result.map_err(|e| to_py_err(py, e))? { + Some(batch) => Ok(Some(batch.to_pyarrow(py)?)), + None => { + inner.exhausted = true; + Ok(None) + } + } + } + + /// Drain the full result and return a single `pyarrow.Table`. + fn fetch_all_arrow<'py>(&mut self, py: Python<'py>) -> PyResult> { + let inner = self.alive_mut()?; + let runtime = inner.runtime.clone(); + let drain_result: databricks_sql_kernel::Result> = py.detach(|| { + runtime.block_on(async { + let mut out = Vec::new(); + let stream = inner.exec.result_stream_mut(); + loop { + match stream.next_batch().await? { + Some(ResultBatch::Arrow(rb)) => out.push(rb.clone()), + Some(_) => { + return Err(databricks_sql_kernel::Error::invalid_argument() + .message("kernel returned a non-Arrow ResultBatch variant")); + } + None => break, + } + } + Ok(out) + }) + }); + let batches = drain_result.map_err(|e| to_py_err(py, e))?; + inner.exhausted = true; + + let py_batches: Vec> = batches + .into_iter() + .map(|b| b.to_pyarrow(py)) + .collect::>()?; + let py_schema = self.schema.as_ref().to_pyarrow(py)?; + let pa = py.import("pyarrow")?; + pa.getattr("Table")? + .call_method1("from_batches", (py_batches, py_schema)) + } + + /// Cancel the in-flight statement on the server. Local validity + /// flag short-circuits if the parent `Statement` was re-executed + /// or dropped. + fn cancel(&mut self, py: Python<'_>) -> PyResult<()> { + let inner = self.alive_mut()?; + let runtime = inner.runtime.clone(); + let res = py.detach(|| runtime.block_on(inner.exec.cancel())); + res.map_err(|e| to_py_err(py, e)) + } + + /// Close the statement (server-side `CloseStatement`). Idempotent. + /// Subsequent calls on this handle raise `KernelError`. + fn close(&mut self, py: Python<'_>) -> PyResult<()> { + let Some(inner) = self.inner.as_mut() else { + return Ok(()); + }; + let runtime = inner.runtime.clone(); + let res = py.detach(|| runtime.block_on(inner.exec.close())); + // Drop the kernel handle regardless of close() outcome — the + // kernel's Drop impl runs fire-and-forget cleanup if close() + // failed mid-flight. + self.inner = None; + res.map_err(|e| to_py_err(py, e)) + } + + fn __repr__(&self) -> String { + let state = if self.inner.is_some() { + "open" + } else { + "closed" + }; + format!( + "ExecutedStatement(statement_id={:?}, state={state})", + self.statement_id + ) + } +} From 6bc3ecdffa295657d7ac9527f52bc415a06d8f48 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Wed, 13 May 2026 10:08:39 +0000 Subject: [PATCH 2/9] feat(pyo3): metadata + ResultStream surface MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 1 step 3 of the PySQL × kernel integration plan. Wraps the kernel's `Metadata` API and adds a standalone `ResultStream` Python class for the bare streams the metadata calls return. New Python surface: - `Session.metadata() -> Metadata` - `Metadata.list_catalogs() -> ResultStream` - `Metadata.list_schemas(*, catalog=None, schema_pattern=None) -> ResultStream` - `Metadata.list_tables(*, catalog=None, schema_pattern=None, table_pattern=None, table_types=None) -> ResultStream` - `Metadata.list_columns(*, catalog, schema_pattern=None, table_pattern=None, column_pattern=None) -> ResultStream` - `Metadata.primary_keys(*, catalog, schema, table) -> ResultStream` - `Metadata.foreign_keys(*, parent_catalog=None, parent_schema=None, parent_table=None, foreign_catalog, foreign_schema, foreign_table) -> ResultStream` - `Metadata.functions / procedures(*, catalog=None, schema_pattern=None, name_pattern=None) -> ResultStream` - `Metadata.type_info() / table_types() -> ResultStream` (static, no wire call) - `ResultStream` — `arrow_schema()`, `fetch_next_batch()`, `fetch_all_arrow()`, `close()`. The Python surface collapses kernel `Identifier` / `LikePattern` back to `Option[str]`; the kernel still enforces empty / NUL / backtick / length-cap checks, surfacing bad input as `KernelError(code='InvalidArgument', ...)`. Implementation notes: - New `fetch.rs` shared helpers (`next_batch`, `drain`, `batches_to_pyarrow_table`) so `ExecutedStatement` and the new `ResultStream` produce identical Python objects from the same code path. - `ExecutedStatement::fetch_*` refactored to call the helpers; no behavior change. - `Metadata` methods are inline `block_on`s — the `for<'a> FnOnce(&'a Metadata) -> Fut` HRTB trick can't express the bound the borrow checker needs, and the inline form is simpler anyway. Smoke test (`pyo3/smoke.py`) extended with the metadata surface and validation checks; verified end-to-end against dogfood. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- pyo3/smoke.py | 212 +++++++++++++++++++++++++++++++ pyo3/src/fetch.rs | 84 +++++++++++++ pyo3/src/lib.rs | 13 +- pyo3/src/metadata.rs | 254 ++++++++++++++++++++++++++++++++++++++ pyo3/src/result_stream.rs | 133 ++++++++++++++++++++ pyo3/src/session.rs | 10 ++ pyo3/src/statement.rs | 59 ++------- 7 files changed, 713 insertions(+), 52 deletions(-) create mode 100644 pyo3/smoke.py create mode 100644 pyo3/src/fetch.rs create mode 100644 pyo3/src/metadata.rs create mode 100644 pyo3/src/result_stream.rs diff --git a/pyo3/smoke.py b/pyo3/smoke.py new file mode 100644 index 00000000..ae05260a --- /dev/null +++ b/pyo3/smoke.py @@ -0,0 +1,212 @@ +"""Live smoke test for the databricks_sql_kernel PyO3 wheel. + +Exercises the surface that's currently implemented (PAT auth, sync +execute, metadata, ResultStream draining, error mapping) against a +live Databricks warehouse. Reads creds from env vars (set via +`set -a && source ~/.databricks/pecotesting-creds && set +a`). + +Run from `pyo3/` so maturin picks up the project-local `.venv`: + + cd pyo3 + .venv/bin/maturin develop --release + .venv/bin/python smoke.py +""" + +from __future__ import annotations +import os +import sys +import traceback + +import databricks_sql_kernel as k +import pyarrow as pa + + +def require_env(name: str) -> str: + v = os.environ.get(name) + if not v: + sys.exit(f"missing env var: {name}") + return v + + +HOST = require_env("DATABRICKS_HOST") +HTTP_PATH = require_env("DATABRICKS_HTTP_PATH") +TOKEN = require_env("DATABRICKS_TOKEN") + + +def banner(s: str) -> None: + print(f"\n=== {s} ===") + + +def check(cond: bool, msg: str) -> None: + print(f" {'OK ' if cond else 'FAIL '} {msg}") + if not cond: + sys.exit(1) + + +def main() -> None: + banner("module + version") + print(f" databricks_sql_kernel.__version__ = {k.__version__}") + + banner("open session") + session = k.Session( + host=HOST, + http_path=HTTP_PATH, + access_token=TOKEN, + ) + check(bool(session.session_id), f"session_id non-empty: {session.session_id!r}") + print(f" repr: {session!r}") + + banner("SELECT 1 — fetch_next_batch path") + stmt = session.statement() + stmt.set_sql("SELECT 1 AS n") + exec_ = stmt.execute() + check(bool(exec_.statement_id), f"statement_id non-empty: {exec_.statement_id!r}") + schema = exec_.arrow_schema() + check(isinstance(schema, pa.Schema), f"arrow_schema is pyarrow.Schema: {schema}") + batch = exec_.fetch_next_batch() + check(isinstance(batch, pa.RecordBatch), f"first batch is RecordBatch: {batch.num_rows} rows") + check(batch.num_rows == 1, "one row") + check(batch.column(0).to_pylist() == [1], f"value is 1: {batch.column(0).to_pylist()}") + nxt = exec_.fetch_next_batch() + check(nxt is None, "second fetch returns None") + exec_.close() + print(f" repr after close: {exec_!r}") + stmt.close() + + banner("SELECT range(10000) — fetch_all_arrow path") + stmt = session.statement() + stmt.set_sql("SELECT * FROM range(10000)") + exec_ = stmt.execute() + table = exec_.fetch_all_arrow() + check(isinstance(table, pa.Table), f"got pyarrow.Table with {table.num_rows} rows") + check(table.num_rows == 10000, f"expected 10000 rows, got {table.num_rows}") + exec_.close() + stmt.close() + + banner("idempotent close") + stmt = session.statement() + stmt.set_sql("SELECT 42") + exec_ = stmt.execute() + exec_.close() + exec_.close() # second call should be a no-op + check(True, "double-close on ExecutedStatement did not raise") + + banner("operations on closed ExecutedStatement raise KernelError") + try: + exec_.fetch_next_batch() + check(False, "should have raised") + except k.KernelError as e: + check("closed" in str(e), f"KernelError mentions closed: {e}") + + # --- metadata surface --- + meta = session.metadata() + + banner("metadata.list_catalogs") + rs = meta.list_catalogs() + check(isinstance(rs.arrow_schema(), pa.Schema), "ResultStream schema is pyarrow.Schema") + cat_table = rs.fetch_all_arrow() + check(isinstance(cat_table, pa.Table), f"got Table with {cat_table.num_rows} catalogs") + check(cat_table.num_rows > 0, "at least one catalog visible") + print(f" first few: {cat_table.column(0).to_pylist()[:5]}") + rs.close() + + banner("metadata.list_schemas — main catalog") + rs = meta.list_schemas(catalog="main") + schemas_table = rs.fetch_all_arrow() + check(schemas_table.num_rows > 0, f"main has schemas: {schemas_table.num_rows}") + rs.close() + + banner("metadata.list_tables — system.information_schema") + rs = meta.list_tables(catalog="system", schema_pattern="information_schema") + tables_table = rs.fetch_all_arrow() + check(tables_table.num_rows > 0, f"information_schema has tables: {tables_table.num_rows}") + print(f" columns in result: {[f.name for f in tables_table.schema]}") + rs.close() + + banner("metadata.list_columns — system.information_schema.tables") + rs = meta.list_columns( + catalog="system", schema_pattern="information_schema", table_pattern="tables" + ) + cols_table = rs.fetch_all_arrow() + check(cols_table.num_rows > 0, f"tables has columns: {cols_table.num_rows}") + rs.close() + + banner("metadata.type_info — static, no wire call") + rs = meta.type_info() + ti_table = rs.fetch_all_arrow() + check(ti_table.num_rows > 0, f"type_info rows: {ti_table.num_rows}") + rs.close() + + banner("metadata.table_types — static, no wire call") + rs = meta.table_types() + tt_table = rs.fetch_all_arrow() + check(tt_table.num_rows > 0, f"table_types rows: {tt_table.num_rows}") + rs.close() + + banner("metadata input validation — empty identifier is rejected") + try: + meta.list_schemas(catalog="") + check(False, "empty catalog should have raised") + except k.KernelError as e: + attrs = e.args[1] + check(attrs.get("code") == "InvalidArgument", f"code=InvalidArgument, got: {attrs.get('code')}") + check( + "identifier" in attrs.get("message", "").lower(), + f"message mentions identifier: {attrs.get('message')}", + ) + + banner("metadata input validation — list_columns requires catalog kwarg") + try: + meta.list_columns(schema_pattern="x", table_pattern="y") # type: ignore[call-arg] + check(False, "missing catalog kwarg should have raised TypeError") + except TypeError as e: + check(True, f"TypeError as expected: {e}") + + banner("ResultStream close + use-after-close") + rs = meta.list_catalogs() + rs.close() + rs.close() # idempotent + try: + rs.fetch_next_batch() + check(False, "should have raised") + except k.KernelError as e: + check("closed" in str(e), f"KernelError mentions closed: {e}") + + banner("close session") + session.close() + session.close() # idempotent + check(True, "double-close on Session did not raise") + + banner("operations on closed Session raise KernelError") + try: + session.statement() + check(False, "should have raised") + except k.KernelError as e: + check("closed" in str(e), f"KernelError mentions closed: {e}") + + banner("error mapping — bad SQL surfaces as KernelError") + s2 = k.Session(host=HOST, http_path=HTTP_PATH, access_token=TOKEN) + stmt = s2.statement() + stmt.set_sql("SELECT * FROM definitely_not_a_table_xyz_smoke") + try: + stmt.execute() + check(False, "should have raised on bad SQL") + except k.KernelError as e: + args = e.args + check(len(args) >= 2 and isinstance(args[1], dict), f"args carry structured dict: {args!r}") + attrs = args[1] + check("code" in attrs, "attrs has 'code'") + check("message" in attrs, "attrs has 'message'") + s2.close() + + print("\nAll smoke checks passed.") + + +if __name__ == "__main__": + try: + main() + except SystemExit: + raise + except Exception: + traceback.print_exc() + sys.exit(2) diff --git a/pyo3/src/fetch.rs b/pyo3/src/fetch.rs new file mode 100644 index 00000000..0ae41fb8 --- /dev/null +++ b/pyo3/src/fetch.rs @@ -0,0 +1,84 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Internal helpers for pulling batches out of a `ResultStream`. +//! +//! Shared by `ExecutedStatement` (drives the kernel `ExecutedStatement`'s +//! borrowed result stream) and `ResultStream` (owns its kernel +//! `ResultStream` directly). Both call `next_batch` on the kernel +//! stream and clone the Arrow `RecordBatch` out from under the +//! borrow so the result can cross the GIL boundary as an owned value. + +use arrow_array::RecordBatch; +use arrow_pyarrow::ToPyArrow; +use arrow_schema::Schema; +use databricks_sql_kernel::{Error, Result, ResultBatch, ResultStream}; +use pyo3::prelude::*; +use std::sync::Arc; +use tokio::runtime::Runtime; + +/// Pull the next batch from the kernel stream and return it as an +/// owned `RecordBatch`, or `None` if the stream is exhausted. +/// +/// Caller is responsible for holding `py.detach(...)` open around +/// the call — this function does kernel I/O. +pub(crate) fn next_batch( + runtime: &Runtime, + stream: &mut ResultStream, +) -> Result> { + runtime.block_on(async { + match stream.next_batch().await? { + Some(ResultBatch::Arrow(rb)) => Ok(Some(rb.clone())), + Some(_) => Err(Error::invalid_argument() + .message("kernel returned a non-Arrow ResultBatch variant")), + None => Ok(None), + } + }) +} + +/// Drain the kernel stream and collect every remaining batch. +pub(crate) fn drain(runtime: &Runtime, stream: &mut ResultStream) -> Result> { + runtime.block_on(async { + let mut out = Vec::new(); + loop { + match stream.next_batch().await? { + Some(ResultBatch::Arrow(rb)) => out.push(rb.clone()), + Some(_) => { + return Err(Error::invalid_argument() + .message("kernel returned a non-Arrow ResultBatch variant")); + } + None => break, + } + } + Ok(out) + }) +} + +/// Wrap a Vec of `RecordBatch` into a `pyarrow.Table`. Centralised +/// so both `ExecutedStatement.fetch_all_arrow` and +/// `ResultStream.fetch_all_arrow` produce identical Python objects. +pub(crate) fn batches_to_pyarrow_table<'py>( + py: Python<'py>, + schema: &Arc, + batches: Vec, +) -> PyResult> { + let py_batches: Vec> = batches + .into_iter() + .map(|b| b.to_pyarrow(py)) + .collect::>()?; + let py_schema = schema.as_ref().to_pyarrow(py)?; + let pa = py.import("pyarrow")?; + pa.getattr("Table")? + .call_method1("from_batches", (py_batches, py_schema)) +} diff --git a/pyo3/src/lib.rs b/pyo3/src/lib.rs index 6a2ca291..14556959 100644 --- a/pyo3/src/lib.rs +++ b/pyo3/src/lib.rs @@ -14,15 +14,18 @@ //! Python bindings for the Databricks SQL Kernel. //! -//! Phase 1 scaffold: `Session`, `Statement`, `ExecutedStatement`. PAT -//! auth only; synchronous `execute()` path. Built as the -//! `databricks_sql_kernel` extension module via `maturin develop` / -//! `maturin build`. +//! Phase 1 surface today: `Session`, `Statement`, `ExecutedStatement`, +//! `Metadata`, `ResultStream`. PAT auth only; synchronous `execute()` +//! path. Built as the `databricks_sql_kernel` extension module via +//! `maturin develop` / `maturin build`. //! //! The kernel's API is async — every method call from Python detaches //! the GIL and `block_on`s on the session-owned tokio runtime. mod errors; +mod fetch; +mod metadata; +mod result_stream; mod session; mod statement; @@ -35,5 +38,7 @@ fn databricks_sql_kernel(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; + m.add_class::()?; Ok(()) } diff --git a/pyo3/src/metadata.rs b/pyo3/src/metadata.rs new file mode 100644 index 00000000..f1fe657d --- /dev/null +++ b/pyo3/src/metadata.rs @@ -0,0 +1,254 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! `Metadata` — Python wrapper for the kernel's flat metadata API. +//! +//! Mirrors `kernel::Metadata` one-to-one. Each method blocks on the +//! session's tokio runtime, returns a `ResultStream` that the caller +//! drains the same way it drains `ExecutedStatement` results. +//! +//! The kernel splits exact identifiers (`Identifier`) from LIKE +//! patterns (`LikePattern`) at the type level. The Python surface +//! collapses both back to `Option[str]` because Python lacks a +//! convenient way to express two distinct string-flavoured types at +//! a call site. The kernel's runtime checks (empty, NUL, backticks +//! for identifiers; length caps for both) still apply; bad input +//! surfaces as `KernelError(code='InvalidArgument', ...)`. + +use crate::errors::to_py_err; +use crate::result_stream::ResultStream; +use databricks_sql_kernel::{Identifier, LikePattern, Metadata as KMetadata, Result as KResult}; +use pyo3::prelude::*; +use std::sync::Arc; +use tokio::runtime::Runtime; + +/// Python-facing metadata handle. +/// +/// Constructed via `Session.metadata()`. Cheap to construct and +/// throw away — the underlying kernel `Metadata` is a thin wrapper +/// around the shared session state. +#[pyclass(name = "Metadata", unsendable)] +pub(crate) struct Metadata { + inner: KMetadata, + runtime: Arc, +} + +impl Metadata { + pub(crate) fn new(inner: KMetadata, runtime: Arc) -> Self { + Self { inner, runtime } + } +} + +/// Build a kernel `Identifier` from an optional Python string, or +/// `None` if the input was `None`. Empty / NUL / backtick rejection +/// happens kernel-side and surfaces as `InvalidArgument`. +fn opt_identifier(s: &Option) -> KResult>> { + s.as_deref().map(Identifier::new).transpose() +} + +fn opt_pattern(s: &Option) -> KResult>> { + s.as_deref().map(LikePattern::new).transpose() +} + +#[pymethods] +impl Metadata { + /// All catalogs visible to the session. + fn list_catalogs(&self, py: Python<'_>) -> PyResult { + let stream = py + .detach(|| self.runtime.block_on(self.inner.list_catalogs())) + .map_err(|e| to_py_err(py, e))?; + Ok(ResultStream::new(stream, self.runtime.clone())) + } + + /// Schemas filtered by catalog (exact) and schema name pattern. + #[pyo3(signature = (*, catalog=None, schema_pattern=None))] + fn list_schemas( + &self, + py: Python<'_>, + catalog: Option, + schema_pattern: Option, + ) -> PyResult { + let stream = py + .detach(|| -> KResult<_> { + let cat = opt_identifier(&catalog)?; + let pat = opt_pattern(&schema_pattern)?; + self.runtime.block_on(self.inner.list_schemas(cat, pat)) + }) + .map_err(|e| to_py_err(py, e))?; + Ok(ResultStream::new(stream, self.runtime.clone())) + } + + /// Tables filtered by catalog (exact), schema (pattern), table + /// (pattern). `table_types` is advisory — Databricks does not + /// honour it server-side; wrappers filter the returned + /// `tableType` column themselves. + #[pyo3(signature = (*, catalog=None, schema_pattern=None, table_pattern=None, table_types=None))] + fn list_tables( + &self, + py: Python<'_>, + catalog: Option, + schema_pattern: Option, + table_pattern: Option, + table_types: Option>, + ) -> PyResult { + let stream = py + .detach(|| -> KResult<_> { + let cat = opt_identifier(&catalog)?; + let sch = opt_pattern(&schema_pattern)?; + let tbl = opt_pattern(&table_pattern)?; + let types_owned: Option> = table_types + .as_ref() + .map(|v| v.iter().map(String::as_str).collect()); + let types_slice: Option<&[&str]> = types_owned.as_deref(); + self.runtime + .block_on(self.inner.list_tables(cat, sch, tbl, types_slice)) + }) + .map_err(|e| to_py_err(py, e))?; + Ok(ResultStream::new(stream, self.runtime.clone())) + } + + /// Columns of tables matching the filter. `catalog` is required + /// (Databricks `SHOW COLUMNS` cannot span catalogs). + #[pyo3(signature = (*, catalog, schema_pattern=None, table_pattern=None, column_pattern=None))] + fn list_columns( + &self, + py: Python<'_>, + catalog: String, + schema_pattern: Option, + table_pattern: Option, + column_pattern: Option, + ) -> PyResult { + let stream = py + .detach(|| -> KResult<_> { + let cat = Some(Identifier::new(&catalog)?); + let sch = opt_pattern(&schema_pattern)?; + let tbl = opt_pattern(&table_pattern)?; + let col = opt_pattern(&column_pattern)?; + self.runtime + .block_on(self.inner.list_columns(cat, sch, tbl, col)) + }) + .map_err(|e| to_py_err(py, e))?; + Ok(ResultStream::new(stream, self.runtime.clone())) + } + + /// Primary keys for the given table. All identifiers are exact. + #[pyo3(signature = (*, catalog, schema, table))] + fn primary_keys( + &self, + py: Python<'_>, + catalog: String, + schema: String, + table: String, + ) -> PyResult { + let stream = py + .detach(|| -> KResult<_> { + let cat = Some(Identifier::new(&catalog)?); + let sch = Some(Identifier::new(&schema)?); + let tbl = Identifier::new(&table)?; + self.runtime + .block_on(self.inner.primary_keys(cat, sch, tbl)) + }) + .map_err(|e| to_py_err(py, e))?; + Ok(ResultStream::new(stream, self.runtime.clone())) + } + + /// Foreign-key relationships. The foreign side must be fully + /// specified (catalog + schema + table); the parent side is + /// optional. + #[pyo3(signature = (*, + parent_catalog=None, parent_schema=None, parent_table=None, + foreign_catalog, foreign_schema, foreign_table))] + #[allow(clippy::too_many_arguments)] + fn foreign_keys( + &self, + py: Python<'_>, + parent_catalog: Option, + parent_schema: Option, + parent_table: Option, + foreign_catalog: String, + foreign_schema: String, + foreign_table: String, + ) -> PyResult { + let stream = py + .detach(|| -> KResult<_> { + let pc = opt_identifier(&parent_catalog)?; + let ps = opt_identifier(&parent_schema)?; + let pt = opt_identifier(&parent_table)?; + let fc = Some(Identifier::new(&foreign_catalog)?); + let fs = Some(Identifier::new(&foreign_schema)?); + let ft = Some(Identifier::new(&foreign_table)?); + self.runtime + .block_on(self.inner.foreign_keys(pc, ps, pt, fc, fs, ft)) + }) + .map_err(|e| to_py_err(py, e))?; + Ok(ResultStream::new(stream, self.runtime.clone())) + } + + /// Functions visible to the session. + #[pyo3(signature = (*, catalog=None, schema_pattern=None, name_pattern=None))] + fn functions( + &self, + py: Python<'_>, + catalog: Option, + schema_pattern: Option, + name_pattern: Option, + ) -> PyResult { + let stream = py + .detach(|| -> KResult<_> { + let cat = opt_identifier(&catalog)?; + let sch = opt_pattern(&schema_pattern)?; + let nam = opt_pattern(&name_pattern)?; + self.runtime.block_on(self.inner.functions(cat, sch, nam)) + }) + .map_err(|e| to_py_err(py, e))?; + Ok(ResultStream::new(stream, self.runtime.clone())) + } + + /// Procedures visible to the session. + #[pyo3(signature = (*, catalog=None, schema_pattern=None, name_pattern=None))] + fn procedures( + &self, + py: Python<'_>, + catalog: Option, + schema_pattern: Option, + name_pattern: Option, + ) -> PyResult { + let stream = py + .detach(|| -> KResult<_> { + let cat = opt_identifier(&catalog)?; + let sch = opt_pattern(&schema_pattern)?; + let nam = opt_pattern(&name_pattern)?; + self.runtime.block_on(self.inner.procedures(cat, sch, nam)) + }) + .map_err(|e| to_py_err(py, e))?; + Ok(ResultStream::new(stream, self.runtime.clone())) + } + + /// SQL data types supported by the workspace. No filters; no + /// wire call (static in-memory result). + fn type_info(&self, py: Python<'_>) -> PyResult { + let stream = py + .detach(|| self.runtime.block_on(self.inner.type_info())) + .map_err(|e| to_py_err(py, e))?; + Ok(ResultStream::new(stream, self.runtime.clone())) + } + + /// All table types. No wire call. + fn table_types(&self, py: Python<'_>) -> PyResult { + let stream = py + .detach(|| self.runtime.block_on(self.inner.table_types())) + .map_err(|e| to_py_err(py, e))?; + Ok(ResultStream::new(stream, self.runtime.clone())) + } +} diff --git a/pyo3/src/result_stream.rs b/pyo3/src/result_stream.rs new file mode 100644 index 00000000..4673e65f --- /dev/null +++ b/pyo3/src/result_stream.rs @@ -0,0 +1,133 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! `ResultStream` — Python class wrapping a kernel `ResultStream`. +//! +//! Returned by `Session.metadata().list_*` calls and (in future) +//! anywhere the kernel hands back a bare `ResultStream` without an +//! enclosing `ExecutedStatement`. Identical fetch surface to +//! `ExecutedStatement` (Arrow batches, drain-to-Table), minus the +//! statement_id / cancel hooks that only make sense for an executed +//! statement. +//! +//! The actual batch-pulling logic lives in `fetch::*` helpers so +//! `ExecutedStatement::fetch_next_batch` / `fetch_all_arrow` can call +//! the same code path through its `result_stream_mut()` borrow. + +use crate::errors::to_py_err; +use crate::fetch; +use arrow_pyarrow::ToPyArrow; +use arrow_schema::Schema; +use databricks_sql_kernel::ResultStream as KResultStream; +use pyo3::prelude::*; +use std::sync::Arc; +use tokio::runtime::Runtime; + +/// Python-facing borrowed result stream. +/// +/// `unsendable` — like the rest of the surface, holding a tokio +/// `Runtime` makes the pyclass `!Send`. +#[pyclass(name = "ResultStream", unsendable)] +pub(crate) struct ResultStream { + inner: Option, + /// Cached schema — survives `close()` so callers can still read + /// the description after exhausting / closing the stream. + schema: Arc, +} + +struct ResultStreamInner { + stream: KResultStream, + runtime: Arc, + exhausted: bool, +} + +impl ResultStream { + pub(crate) fn new(stream: KResultStream, runtime: Arc) -> Self { + let schema = stream.schema(); + Self { + schema, + inner: Some(ResultStreamInner { + stream, + runtime, + exhausted: false, + }), + } + } + + fn alive_mut(&mut self) -> PyResult<&mut ResultStreamInner> { + self.inner + .as_mut() + .ok_or_else(|| crate::errors::KernelError::new_err("ResultStream is closed")) + } +} + +#[pymethods] +impl ResultStream { + /// Result schema as a `pyarrow.Schema`. Available even after `close()`. + fn arrow_schema<'py>(&self, py: Python<'py>) -> PyResult> { + self.schema.as_ref().to_pyarrow(py) + } + + /// Pull the next batch as a `pyarrow.RecordBatch`, or `None` when + /// exhausted. + fn fetch_next_batch<'py>(&mut self, py: Python<'py>) -> PyResult>> { + let inner = self.alive_mut()?; + if inner.exhausted { + return Ok(None); + } + let runtime = inner.runtime.clone(); + let batch = py + .detach(|| fetch::next_batch(&runtime, &mut inner.stream)) + .map_err(|e| to_py_err(py, e))?; + match batch { + Some(b) => Ok(Some(b.to_pyarrow(py)?)), + None => { + inner.exhausted = true; + Ok(None) + } + } + } + + /// Drain the full result and return a single `pyarrow.Table`. + fn fetch_all_arrow<'py>(&mut self, py: Python<'py>) -> PyResult> { + let inner = self.alive_mut()?; + let runtime = inner.runtime.clone(); + let batches = py + .detach(|| fetch::drain(&runtime, &mut inner.stream)) + .map_err(|e| to_py_err(py, e))?; + inner.exhausted = true; + fetch::batches_to_pyarrow_table(py, &self.schema, batches) + } + + /// Release client-side resources. Idempotent. Subsequent calls + /// on this handle raise `KernelError`. + fn close(&mut self) { + if let Some(inner) = self.inner.take() { + // ResultStream::close() is sync (no server RPC) and + // consumes self; the kernel's Drop performs the same + // cleanup, but the explicit call is cheaper to reason + // about. + inner.stream.close(); + } + } + + fn __repr__(&self) -> String { + let state = if self.inner.is_some() { + "open" + } else { + "closed" + }; + format!("ResultStream(state={state})") + } +} diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 897f00bd..801ebccc 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -21,6 +21,7 @@ //! pyclass alive longer than the user keeps a reference. use crate::errors::to_py_err; +use crate::metadata::Metadata; use crate::statement::Statement; use databricks_sql_kernel::{AuthConfig, Session as KSession}; use pyo3::prelude::*; @@ -125,6 +126,15 @@ impl Session { Ok(Statement::new(kstmt, inner.runtime.clone())) } + /// Metadata operations bound to this session (flat per-method, + /// ODBC-shaped). Returns a fresh `Metadata` handle on every call; + /// the handle is cheap to construct and throw away. + fn metadata(&self) -> PyResult { + let inner = self.alive()?; + let kmeta = inner.session.metadata(); + Ok(Metadata::new(kmeta, inner.runtime.clone())) + } + /// Explicitly close the session. Idempotent. Subsequent calls on /// this `Session` raise `KernelError`. fn close(&mut self, py: Python<'_>) -> PyResult<()> { diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index cb482147..983bff3d 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -20,12 +20,11 @@ //! batch-by-batch as pyarrow `RecordBatch`es. use crate::errors::to_py_err; -use arrow_array::RecordBatch; +use crate::fetch; use arrow_pyarrow::ToPyArrow; use arrow_schema::Schema; use databricks_sql_kernel::{ - ExecutedStatement as KExecutedStatement, ExecutedStatementHandle, ResultBatch, - Statement as KStatement, + ExecutedStatement as KExecutedStatement, ExecutedStatementHandle, Statement as KStatement, }; use pyo3::prelude::*; use std::sync::Arc; @@ -149,25 +148,12 @@ impl ExecutedStatement { if inner.exhausted { return Ok(None); } - // Drive next_batch() on the session runtime with the GIL - // released for the whole I/O. The returned reference borrows - // from the stream; clone the RecordBatch (Arc-backed columns - // — cheap) out into an owned value so the borrow ends before - // we touch pyarrow. let runtime = inner.runtime.clone(); - let batch_result: databricks_sql_kernel::Result> = py.detach(|| { - runtime.block_on(async { - let stream = inner.exec.result_stream_mut(); - match stream.next_batch().await? { - Some(ResultBatch::Arrow(rb)) => Ok(Some(rb.clone())), - Some(_) => Err(databricks_sql_kernel::Error::invalid_argument() - .message("kernel returned a non-Arrow ResultBatch variant")), - None => Ok(None), - } - }) - }); - match batch_result.map_err(|e| to_py_err(py, e))? { - Some(batch) => Ok(Some(batch.to_pyarrow(py)?)), + let batch = py + .detach(|| fetch::next_batch(&runtime, inner.exec.result_stream_mut())) + .map_err(|e| to_py_err(py, e))?; + match batch { + Some(b) => Ok(Some(b.to_pyarrow(py)?)), None => { inner.exhausted = true; Ok(None) @@ -179,34 +165,11 @@ impl ExecutedStatement { fn fetch_all_arrow<'py>(&mut self, py: Python<'py>) -> PyResult> { let inner = self.alive_mut()?; let runtime = inner.runtime.clone(); - let drain_result: databricks_sql_kernel::Result> = py.detach(|| { - runtime.block_on(async { - let mut out = Vec::new(); - let stream = inner.exec.result_stream_mut(); - loop { - match stream.next_batch().await? { - Some(ResultBatch::Arrow(rb)) => out.push(rb.clone()), - Some(_) => { - return Err(databricks_sql_kernel::Error::invalid_argument() - .message("kernel returned a non-Arrow ResultBatch variant")); - } - None => break, - } - } - Ok(out) - }) - }); - let batches = drain_result.map_err(|e| to_py_err(py, e))?; + let batches = py + .detach(|| fetch::drain(&runtime, inner.exec.result_stream_mut())) + .map_err(|e| to_py_err(py, e))?; inner.exhausted = true; - - let py_batches: Vec> = batches - .into_iter() - .map(|b| b.to_pyarrow(py)) - .collect::>()?; - let py_schema = self.schema.as_ref().to_pyarrow(py)?; - let pa = py.import("pyarrow")?; - pa.getattr("Table")? - .call_method1("from_batches", (py_batches, py_schema)) + fetch::batches_to_pyarrow_table(py, &self.schema, batches) } /// Cancel the in-flight statement on the server. Local validity From 0bd898f0d1197a1b1400fee5011b2beef2bd9edc Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Wed, 13 May 2026 10:12:47 +0000 Subject: [PATCH 3/9] feat(pyo3): async statement (submit / status / await_result / fetch_result) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 1 step 4. Wraps the kernel's `ExecutedAsyncStatement` so the connector can run `cursor.execute(async_op=True)` workflows through the kernel: submit returns immediately with a `statement_id`, the caller polls `status()` and pulls results via `await_result()` or `fetch_result()` once a terminal state is reached. New Python surface: - `Statement.submit() -> ExecutedAsyncStatement` - `ExecutedAsyncStatement.statement_id` - `ExecutedAsyncStatement.status() -> (state: str, failure: Optional[dict])` Returns one of `Pending / Running / Succeeded / Failed / Cancelled / Closed`. `failure` is populated only for `Failed` and carries the same structured-attrs dict that `KernelError` exposes (code, sql_state, error_code, query_id, etc.). Surfacing failure as a dict rather than raising lets polling callers branch without a try/except boundary. - `ExecutedAsyncStatement.await_result() -> ResultStream` — blocks with kernel-managed poll cadence, raises on `Failed` / `Cancelled`. - `ExecutedAsyncStatement.fetch_result() -> ResultStream` — fetches without polling; raises `KernelError(code='InvalidState')` if the statement is still running. - `ExecutedAsyncStatement.cancel() / close()` — same semantics as the sync handle's counterparts. Smoke test (`pyo3/smoke.py`) extended with the async surface; all checks pass against dogfood. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- pyo3/smoke.py | 71 ++++++++++++++ pyo3/src/executed_async.rs | 184 +++++++++++++++++++++++++++++++++++++ pyo3/src/lib.rs | 9 +- pyo3/src/statement.rs | 17 ++++ 4 files changed, 278 insertions(+), 3 deletions(-) create mode 100644 pyo3/src/executed_async.rs diff --git a/pyo3/smoke.py b/pyo3/smoke.py index ae05260a..49fc4658 100644 --- a/pyo3/smoke.py +++ b/pyo3/smoke.py @@ -172,6 +172,77 @@ def main() -> None: except k.KernelError as e: check("closed" in str(e), f"KernelError mentions closed: {e}") + # --- async statement surface --- + banner("async submit + await_result") + stmt = session.statement() + stmt.set_sql("SELECT 7 AS n") + async_exec = stmt.submit() + check(bool(async_exec.statement_id), f"async statement_id: {async_exec.statement_id!r}") + state, failure = async_exec.status() + check(state in ("Pending", "Running", "Succeeded", "Closed"), f"status state={state!r}") + check(failure is None, f"non-failed status has failure=None: {failure!r}") + rs = async_exec.await_result() + table = rs.fetch_all_arrow() + check(table.num_rows == 1, f"1 row, got {table.num_rows}") + check(table.column(0).to_pylist() == [7], f"value is 7: {table.column(0).to_pylist()}") + # After await_result, status should be terminal. + state, _ = async_exec.status() + check(state in ("Succeeded", "Closed"), f"terminal status after await_result: {state!r}") + rs.close() + async_exec.close() + stmt.close() + + banner("async submit + fetch_result (after explicit wait via status loop)") + stmt = session.statement() + stmt.set_sql("SELECT 99 AS n") + async_exec = stmt.submit() + # Poll a few times until terminal — should reach Succeeded almost immediately for SELECT 99. + import time + + for _ in range(20): + state, _ = async_exec.status() + if state in ("Succeeded", "Closed", "Failed", "Cancelled"): + break + time.sleep(0.1) + check(state in ("Succeeded", "Closed"), f"reached terminal state: {state!r}") + rs = async_exec.fetch_result() + table = rs.fetch_all_arrow() + check(table.num_rows == 1 and table.column(0).to_pylist() == [99], f"value is 99") + rs.close() + async_exec.close() + stmt.close() + + banner("async submit + Failed status surfaces structured error") + stmt = session.statement() + stmt.set_sql("SELECT * FROM definitely_not_a_table_xyz_async") + async_exec = stmt.submit() + # Poll until terminal. + for _ in range(20): + state, failure = async_exec.status() + if state in ("Succeeded", "Closed", "Failed", "Cancelled"): + break + time.sleep(0.1) + check(state == "Failed", f"expected Failed, got: {state!r}") + check(isinstance(failure, dict), f"failure is dict: {failure!r}") + check(failure.get("code") == "SqlError", f"failure.code=SqlError, got: {failure.get('code')}") + check("sql_state" in failure, "failure has sql_state") + check("query_id" in failure, "failure has query_id") + async_exec.close() + stmt.close() + + banner("operations on closed ExecutedAsyncStatement raise KernelError") + stmt = session.statement() + stmt.set_sql("SELECT 1") + async_exec = stmt.submit() + async_exec.close() + async_exec.close() # idempotent + try: + async_exec.status() + check(False, "should have raised") + except k.KernelError as e: + check("closed" in str(e), f"KernelError mentions closed: {e}") + stmt.close() + banner("close session") session.close() session.close() # idempotent diff --git a/pyo3/src/executed_async.rs b/pyo3/src/executed_async.rs new file mode 100644 index 00000000..6f4b2328 --- /dev/null +++ b/pyo3/src/executed_async.rs @@ -0,0 +1,184 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! `ExecutedAsyncStatement` — Python wrapper for the kernel's +//! async-consumption handle. +//! +//! Returned by `Statement.submit()`. The kernel returned without +//! driving polling; the caller owns the cadence via `status()` / +//! `await_result()` / `fetch_result()`. Mirrors the kernel's +//! `executed_async.rs` one-to-one. + +use crate::errors::to_py_err; +use crate::result_stream::ResultStream; +use databricks_sql_kernel::{ + ExecutedAsyncStatement as KExecutedAsyncStatement, ExecutedStatementHandle, StatementStatus, +}; +use pyo3::prelude::*; +use std::sync::Arc; +use tokio::runtime::Runtime; + +/// Map a kernel `StatementStatus` to a stable string slug. Matches +/// the connector's `CommandState` taxonomy one-for-one so the Python +/// side can branch on the result without holding a reference to a +/// `StatementStatus` enum. +fn status_str(status: &StatementStatus) -> &'static str { + match status { + StatementStatus::Pending => "Pending", + StatementStatus::Running => "Running", + StatementStatus::Succeeded => "Succeeded", + StatementStatus::Failed(_) => "Failed", + StatementStatus::Cancelled => "Cancelled", + StatementStatus::Closed => "Closed", + // `StatementStatus` is `#[non_exhaustive]`. + _ => "Unknown", + } +} + +#[pyclass(name = "ExecutedAsyncStatement", unsendable)] +pub(crate) struct ExecutedAsyncStatement { + inner: Option, + /// Cached statement id so callers can read it after `close()`. + statement_id: String, +} + +struct ExecutedAsyncInner { + exec: KExecutedAsyncStatement, + runtime: Arc, +} + +impl ExecutedAsyncStatement { + pub(crate) fn new(exec: KExecutedAsyncStatement, runtime: Arc) -> Self { + let statement_id = exec.statement_id().to_owned(); + Self { + statement_id, + inner: Some(ExecutedAsyncInner { exec, runtime }), + } + } + + fn alive(&self) -> PyResult<&ExecutedAsyncInner> { + self.inner + .as_ref() + .ok_or_else(|| crate::errors::KernelError::new_err("ExecutedAsyncStatement is closed")) + } +} + +#[pymethods] +impl ExecutedAsyncStatement { + #[getter] + fn statement_id(&self) -> &str { + &self.statement_id + } + + /// Single-shot status check. Returns a tuple + /// `(state: str, failure: Optional[dict])` where: + /// + /// - `state` is one of `Pending / Running / Succeeded / Failed / + /// Cancelled / Closed`. + /// - `failure` is `None` unless `state == "Failed"`, in which + /// case it carries the same structured-attrs dict that + /// `KernelError` exposes (`code`, `message`, `sql_state`, + /// `error_code`, `vendor_code`, `http_status`, `retryable`, + /// `query_id`). + /// + /// Surfacing failure as a dict rather than raising lets polling + /// callers branch on terminal vs non-terminal states without a + /// try/except boundary. The connector backend re-raises as + /// the appropriate PEP 249 exception when it actually needs to. + fn status<'py>(&self, py: Python<'py>) -> PyResult> { + let inner = self.alive()?; + let status = py + .detach(|| inner.runtime.block_on(inner.exec.status())) + .map_err(|e| to_py_err(py, e))?; + let state = status_str(&status); + let failure: Option> = match &status { + StatementStatus::Failed(err) => { + // Re-use the same dict-shape `to_py_err` produces so + // wrappers consume one format end-to-end. The + // exception carries the dict as its second `arg`. + let py_err = to_py_err(py, err.clone()); + let args = py_err.value(py).getattr("args")?; + let tuple: Vec> = args.extract()?; + tuple.into_iter().nth(1) + } + _ => None, + }; + let tuple = pyo3::types::PyTuple::new( + py, + [ + state.into_pyobject(py)?.into_any(), + match failure { + Some(f) => f, + None => py.None().into_bound(py), + }, + ], + )?; + Ok(tuple.into_any()) + } + + /// Block until the statement reaches a terminal state, then + /// return a `ResultStream` over the results. + /// + /// Drives polling on the session runtime; the kernel applies the + /// session-configured `poll_interval` / `poll_timeout` cadence. + /// `Failed` / `Cancelled` raise `KernelError`. + fn await_result(&self, py: Python<'_>) -> PyResult { + let inner = self.alive()?; + let stream = py + .detach(|| inner.runtime.block_on(inner.exec.await_result())) + .map_err(|e| to_py_err(py, e))?; + Ok(ResultStream::new(stream, inner.runtime.clone())) + } + + /// Fetch the result without polling. Raises `KernelError(code= + /// 'InvalidState')` if the statement has not reached a terminal + /// state — call after `status()` reports `Succeeded`/`Closed`. + fn fetch_result(&self, py: Python<'_>) -> PyResult { + let inner = self.alive()?; + let stream = py + .detach(|| inner.runtime.block_on(inner.exec.fetch_result())) + .map_err(|e| to_py_err(py, e))?; + Ok(ResultStream::new(stream, inner.runtime.clone())) + } + + /// Cancel the in-flight statement on the server. + fn cancel(&self, py: Python<'_>) -> PyResult<()> { + let inner = self.alive()?; + py.detach(|| inner.runtime.block_on(inner.exec.cancel())) + .map_err(|e| to_py_err(py, e)) + } + + /// Close the statement (server-side `CloseStatement`). Idempotent. + fn close(&mut self, py: Python<'_>) -> PyResult<()> { + let Some(inner) = self.inner.as_mut() else { + return Ok(()); + }; + let runtime = inner.runtime.clone(); + let res = py.detach(|| runtime.block_on(inner.exec.close())); + self.inner = None; + res.map_err(|e| to_py_err(py, e)) + } + + fn __repr__(&self) -> String { + let state = if self.inner.is_some() { + "open" + } else { + "closed" + }; + format!( + "ExecutedAsyncStatement(statement_id={:?}, state={state})", + self.statement_id + ) + } +} diff --git a/pyo3/src/lib.rs b/pyo3/src/lib.rs index 14556959..3c4fbb18 100644 --- a/pyo3/src/lib.rs +++ b/pyo3/src/lib.rs @@ -15,14 +15,16 @@ //! Python bindings for the Databricks SQL Kernel. //! //! Phase 1 surface today: `Session`, `Statement`, `ExecutedStatement`, -//! `Metadata`, `ResultStream`. PAT auth only; synchronous `execute()` -//! path. Built as the `databricks_sql_kernel` extension module via -//! `maturin develop` / `maturin build`. +//! `ExecutedAsyncStatement`, `Metadata`, `ResultStream`. PAT auth +//! only. Both synchronous `execute()` and async `submit()` paths +//! supported. Built as the `databricks_sql_kernel` extension module +//! via `maturin develop` / `maturin build`. //! //! The kernel's API is async — every method call from Python detaches //! the GIL and `block_on`s on the session-owned tokio runtime. mod errors; +mod executed_async; mod fetch; mod metadata; mod result_stream; @@ -38,6 +40,7 @@ fn databricks_sql_kernel(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; m.add_class::()?; m.add_class::()?; Ok(()) diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 983bff3d..acf691be 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -20,6 +20,7 @@ //! batch-by-batch as pyarrow `RecordBatch`es. use crate::errors::to_py_err; +use crate::executed_async::ExecutedAsyncStatement; use crate::fetch; use arrow_pyarrow::ToPyArrow; use arrow_schema::Schema; @@ -79,6 +80,22 @@ impl Statement { Ok(ExecutedStatement::new(exec, runtime)) } + /// Submit-and-return. Sends `ExecuteStatement` with + /// `wait_timeout=0s` so the server returns immediately with a + /// `statement_id`; the kernel does not poll. Returns an + /// `ExecutedAsyncStatement` the caller drives via `status()` / + /// `await_result()` / `fetch_result()`. + /// + /// Long-running queries that would blow past `execute()`'s sync + /// polling budget belong on this path. + fn submit(&mut self, py: Python<'_>) -> PyResult { + let inner = self.alive_mut()?; + let runtime = inner.runtime.clone(); + let submit_result = py.detach(|| runtime.block_on(inner.stmt.submit())); + let exec = submit_result.map_err(|e| to_py_err(py, e))?; + Ok(ExecutedAsyncStatement::new(exec, runtime)) + } + /// Drop the statement. Any prior `ExecutedStatement` keeps /// working — kernel-side it has its own validity flag and /// statement_id and is independent of the `Statement` lifecycle. From c58710d87b2d7f115639d12423f6a50ccbb0a951 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Wed, 13 May 2026 10:26:10 +0000 Subject: [PATCH 4/9] =?UTF-8?q?feat(pyo3):=20External=20auth=20=E2=80=94?= =?UTF-8?q?=20Python-callable=20token=20provider?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 1 step 5. Wires a Python callable into the kernel's AuthConfig::External slot so the connector can delegate OAuth / MSAL / federation flows back to its own auth provider rather than re-implementing them in Rust. New Python surface: - Session(host, http_path, *, auth_type='external', token_callback, catalog=None, schema=None) — `token_callback` is a no-arg callable returning `str`. The kernel invokes it once per HTTP request that needs auth; the callable owns its own caching / refresh. - Session(host, http_path, *, auth_type='pat', access_token, ...) — explicit PAT form. - Session(host, http_path, *, access_token, ...) — implicit PAT (auth_type defaults to "pat" when access_token is provided), kept for backward compatibility with Phase 1 callers. Errors map cleanly: - Python exception inside the callback → KernelError(code= 'Unauthenticated', message='Python token_callback raised: ...') - Non-string return → KernelError(code='Unauthenticated', message='Python token_callback must return str: ...') - Empty string → KernelError(code='Unauthenticated', message='... returned an empty string') Implementation notes: - New `auth.rs` module owns the kwargs→AuthConfig translation and the `PythonTokenProvider` trampoline (impl async TokenProvider for a Py). GIL is re-acquired on the kernel-spawned tokio worker via Python::attach. - pyo3's `extension-module` feature moved to an opt-in Cargo feature so `cargo test -p databricks-sql-kernel-pyo3` can link libpython and run the trampoline's unit tests. Maturin enables the feature via pyproject.toml when building the wheel. - 4 Rust unit tests cover token roundtrip, Python exception mapping, non-string-return rejection, empty-string rejection. These run on cargo test without any live deps. KNOWN LIMITATION (to be addressed in a follow-up kernel PR): The kernel's `build_auth_provider` currently returns `InvalidArgument` for `AuthConfig::External` ("reserved; v0 wires PAT + OAuthM2M + OAuthU2M only"). End-to-end use of `Session(auth_type='external', ...)` will surface that error verbatim until the kernel wires External into its HTTP-client auth path. This is a separate kernel PR (likely a small ExternalAuthProvider adapter using tokio::task::block_in_place + Handle::current().block_on to drive the async TokenProvider from the sync AuthProvider trait). The PyO3 trampoline itself is fully covered by the unit tests in this PR; the wrapper layer is done. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- Cargo.lock | 1 + pyo3/Cargo.toml | 15 ++- pyo3/pyproject.toml | 2 +- pyo3/smoke.py | 70 ++++++++++++++ pyo3/src/auth.rs | 217 ++++++++++++++++++++++++++++++++++++++++++++ pyo3/src/lib.rs | 7 +- pyo3/src/session.rs | 60 ++++++++---- 7 files changed, 351 insertions(+), 21 deletions(-) create mode 100644 pyo3/src/auth.rs diff --git a/Cargo.lock b/Cargo.lock index 353520e1..5e2b469a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -385,6 +385,7 @@ dependencies = [ "arrow-array", "arrow-pyarrow", "arrow-schema", + "async-trait", "databricks-sql-kernel", "pyo3", "tokio", diff --git a/pyo3/Cargo.toml b/pyo3/Cargo.toml index ebd3cfbf..f59fc8be 100644 --- a/pyo3/Cargo.toml +++ b/pyo3/Cargo.toml @@ -36,7 +36,13 @@ crate-type = ["cdylib"] databricks-sql-kernel = { path = ".." } # pyo3 — abi3-py39 lets one wheel cover Python 3.9+. -pyo3 = { version = "0.26", features = ["extension-module", "abi3-py39"] } +# +# `extension-module` is gated behind a Cargo feature so that +# `cargo test -p databricks-sql-kernel-pyo3` can build a normal +# binary that links against libpython (needed to run unit tests +# that call `Python::attach`). Maturin enables the feature via +# pyproject.toml when building the wheel. +pyo3 = { version = "0.26", features = ["abi3-py39"] } # Multi-thread runtime — one per Session, owned on the Rust side. tokio = { version = "1", features = ["rt-multi-thread"] } @@ -46,3 +52,10 @@ tokio = { version = "1", features = ["rt-multi-thread"] } arrow-array = "57" arrow-schema = "57" arrow-pyarrow = "57" + +# Required to implement the kernel's #[async_trait] TokenProvider on +# the Python-callable trampoline used by AuthConfig::External. +async-trait = "0.1" + +[features] +extension-module = ["pyo3/extension-module"] diff --git a/pyo3/pyproject.toml b/pyo3/pyproject.toml index cdaeade0..3d9e7663 100644 --- a/pyo3/pyproject.toml +++ b/pyo3/pyproject.toml @@ -13,4 +13,4 @@ dependencies = ["pyarrow>=14"] [tool.maturin] module-name = "databricks_sql_kernel" -features = ["pyo3/extension-module"] +features = ["extension-module"] diff --git a/pyo3/smoke.py b/pyo3/smoke.py index 49fc4658..c831eaf4 100644 --- a/pyo3/smoke.py +++ b/pyo3/smoke.py @@ -270,6 +270,76 @@ def main() -> None: check("message" in attrs, "attrs has 'message'") s2.close() + # --- External auth (Python-callable token provider) --- + # + # NOTE: the kernel today rejects `AuthConfig::External` at + # `build_auth_provider` ("reserved; v0 wires PAT + OAuthM2M + + # OAuthU2M only"). Until a follow-up kernel PR wires it into + # the HTTP client's `AuthProvider` adapter, opening a live + # session with `auth_type='external'` surfaces that kernel + # error. The smoke test verifies: + # + # 1. The wrapper accepts and validates the new kwargs. + # 2. Bad kwargs surface as `ValueError` at construction time + # (before the kernel ever sees them). + # 3. Calling `Session(auth_type='external', ...)` surfaces the + # kernel's "reserved" error verbatim — proving the path + # reaches the kernel and the trampoline is wired correctly. + # + # The trampoline itself (Python callback → Rust → kernel + # `TokenProvider`) is covered by Rust unit tests in + # `pyo3/src/auth.rs` so we know the GIL handoff works. + + banner("input validation — missing auth") + try: + k.Session(host=HOST, http_path=HTTP_PATH) + check(False, "no auth should have raised ValueError") + except ValueError as e: + check(True, f"ValueError as expected: {e}") + + banner("input validation — auth_type='external' without callback") + try: + k.Session(host=HOST, http_path=HTTP_PATH, auth_type="external") + check(False, "should have raised") + except ValueError as e: + check("token_callback" in str(e), f"ValueError mentions token_callback: {e}") + + banner("input validation — non-callable callback") + try: + k.Session( + host=HOST, + http_path=HTTP_PATH, + auth_type="external", + token_callback="not-callable", + ) + check(False, "should have raised") + except ValueError as e: + check("callable" in str(e), f"ValueError mentions callable: {e}") + + banner("auth_type='external' surfaces the kernel's 'reserved' error today") + + def ok_callback(): + return TOKEN + + try: + k.Session( + host=HOST, + http_path=HTTP_PATH, + auth_type="external", + token_callback=ok_callback, + ) + check(False, "should have raised until kernel wires AuthConfig::External") + except k.KernelError as e: + attrs = e.args[1] + check( + attrs.get("code") == "InvalidArgument", + f"code=InvalidArgument, got: {attrs.get('code')}", + ) + check( + "External" in attrs.get("message", ""), + f"message names External: {attrs.get('message')}", + ) + print("\nAll smoke checks passed.") diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs new file mode 100644 index 00000000..e410568b --- /dev/null +++ b/pyo3/src/auth.rs @@ -0,0 +1,217 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Translation from Python auth kwargs to a kernel `AuthConfig`. +//! +//! Phase-1 surface covers PAT (Step 1) and `External` (this step). +//! `External` lets the connector keep ownership of its own OAuth / +//! MSAL / federation flows: it passes a Python callable that returns +//! a fresh bearer token, and the kernel calls it whenever it needs +//! one. +//! +//! Future steps add the kernel-driven OAuth variants +//! (`AuthConfig::OAuthM2M`, `OAuthU2M`, `OAuthFederation`) — useful +//! for callers that want the kernel to own the flow rather than +//! delegating back to Python. + +use async_trait::async_trait; +use databricks_sql_kernel::config::TokenProvider; +use databricks_sql_kernel::{AuthConfig, Error, Result as KResult}; +use pyo3::exceptions::PyValueError; +use pyo3::prelude::*; + +/// A `TokenProvider` that delegates to a Python callable. The +/// callable is invoked once per HTTP request that needs auth, with +/// the GIL re-acquired on the calling tokio worker thread. +/// +/// `Py` is `Send + Sync` in pyo3 (it's a reference-counted +/// pointer into the Python heap, not a borrow), so this struct +/// satisfies the kernel's `TokenProvider: Send + Sync` bound. +struct PythonTokenProvider { + callback: Py, +} + +impl PythonTokenProvider { + fn new(callback: Py) -> Self { + Self { callback } + } +} + +#[async_trait] +impl TokenProvider for PythonTokenProvider { + async fn token(&self) -> KResult { + // The kernel calls us from a tokio worker without the GIL. + // Acquire it for the duration of one Python call, extract + // the result as a String, then drop the GIL again before + // returning the future to the kernel. + // + // Note: this is a *sync* GIL-held call to the user's Python + // callable. For typical auth providers (in-process token + // cache lookup, occasional refresh) this is fine and matches + // the connector's own auth-provider contract. If a wrapper + // ever needs to await Python coroutines here, the pattern + // is to make the callback return a token directly and own + // the async work itself. + Python::attach(|py| { + let result = self.callback.call0(py).map_err(|e| { + Error::unauthenticated().message(format!("Python token_callback raised: {e}")) + })?; + let token: String = result.extract(py).map_err(|e| { + Error::unauthenticated() + .message(format!("Python token_callback must return str: {e}")) + })?; + if token.is_empty() { + return Err(Error::unauthenticated() + .message("Python token_callback returned an empty string")); + } + Ok(token) + }) + } +} + +/// Build a kernel `AuthConfig` from the Python kwargs the `Session` +/// constructor accepts. Centralised here so the auth-kwarg surface +/// stays in one place. +/// +/// `auth_type` is one of: +/// - `"pat"` — requires `access_token: str`. +/// - `"external"` — requires `token_callback: Callable[[], str]`. +pub(crate) fn build_auth_config( + auth_type: &str, + access_token: Option, + token_callback: Option>, +) -> PyResult { + match auth_type { + "pat" => { + let token = access_token + .ok_or_else(|| PyValueError::new_err("auth_type='pat' requires access_token"))?; + if token.is_empty() { + return Err(PyValueError::new_err("access_token must not be empty")); + } + Ok(AuthConfig::Pat { token }) + } + "external" => { + let callback = token_callback.ok_or_else(|| { + PyValueError::new_err( + "auth_type='external' requires token_callback (a no-arg callable returning str)", + ) + })?; + // Sanity check at construction time so a misspelled or + // non-callable arg surfaces immediately rather than on + // the first HTTP request. + Python::attach(|py| -> PyResult<()> { + if !callback.bind(py).is_callable() { + return Err(PyValueError::new_err("token_callback must be callable")); + } + Ok(()) + })?; + Ok(AuthConfig::External(Box::new(PythonTokenProvider::new( + callback, + )))) + } + other => Err(PyValueError::new_err(format!( + "unknown auth_type {other:?}; expected one of: pat, external" + ))), + } +} + +#[cfg(test)] +mod tests { + //! End-to-end coverage for the Python→Rust→kernel auth bridge. + //! + //! These tests exercise the `TokenProvider` trampoline without + //! needing a live workspace — we construct a `PythonTokenProvider` + //! directly, run its async `token()` method on a tokio runtime, + //! and check the value flows back correctly. This is the layer + //! the rest of Step 5 builds on; if it breaks we want to catch + //! it without spinning a Session against dogfood. + //! + //! `Python::initialize()` initialises the Python interpreter on + //! first call; subsequent calls are no-ops. + + use super::*; + use databricks_sql_kernel::ErrorCode; + use pyo3::ffi::c_str; + + fn rt() -> tokio::runtime::Runtime { + tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .unwrap() + } + + #[test] + fn python_token_provider_returns_callback_value() { + Python::initialize(); + let callback: Py = Python::attach(|py| { + py.eval(c_str!("lambda: 'token-xyz'"), None, None) + .unwrap() + .unbind() + }); + let provider = PythonTokenProvider::new(callback); + let got = rt().block_on(provider.token()).unwrap(); + assert_eq!(got, "token-xyz"); + } + + #[test] + fn python_token_provider_maps_python_exception_to_unauthenticated() { + Python::initialize(); + let callback: Py = Python::attach(|py| { + // Lambda raising RuntimeError. Done as exec+lookup so we + // can carry a statement (`raise ...`) instead of an + // expression. + let globals = pyo3::types::PyDict::new(py); + py.run( + c_str!("def cb():\n raise RuntimeError('simulated MSAL failure')\n"), + Some(&globals), + None, + ) + .unwrap(); + globals.get_item("cb").unwrap().unwrap().unbind() + }); + let provider = PythonTokenProvider::new(callback); + let err = rt().block_on(provider.token()).unwrap_err(); + assert_eq!(err.code, ErrorCode::Unauthenticated); + assert!( + err.message.contains("simulated MSAL failure"), + "message should preserve the Python exception text: {}", + err.message + ); + } + + #[test] + fn python_token_provider_rejects_non_string_return() { + Python::initialize(); + let callback: Py = Python::attach(|py| { + py.eval(c_str!("lambda: 12345"), None, None) + .unwrap() + .unbind() + }); + let provider = PythonTokenProvider::new(callback); + let err = rt().block_on(provider.token()).unwrap_err(); + assert_eq!(err.code, ErrorCode::Unauthenticated); + assert!(err.message.contains("must return str"), "{}", err.message); + } + + #[test] + fn python_token_provider_rejects_empty_string() { + Python::initialize(); + let callback: Py = + Python::attach(|py| py.eval(c_str!("lambda: ''"), None, None).unwrap().unbind()); + let provider = PythonTokenProvider::new(callback); + let err = rt().block_on(provider.token()).unwrap_err(); + assert_eq!(err.code, ErrorCode::Unauthenticated); + assert!(err.message.contains("empty"), "{}", err.message); + } +} diff --git a/pyo3/src/lib.rs b/pyo3/src/lib.rs index 3c4fbb18..daa3bbc9 100644 --- a/pyo3/src/lib.rs +++ b/pyo3/src/lib.rs @@ -15,14 +15,17 @@ //! Python bindings for the Databricks SQL Kernel. //! //! Phase 1 surface today: `Session`, `Statement`, `ExecutedStatement`, -//! `ExecutedAsyncStatement`, `Metadata`, `ResultStream`. PAT auth -//! only. Both synchronous `execute()` and async `submit()` paths +//! `ExecutedAsyncStatement`, `Metadata`, `ResultStream`. Auth: PAT +//! plus `External` (Python-callable token provider — used by the +//! connector to delegate OAuth back to its own auth provider). +//! Both synchronous `execute()` and async `submit()` paths //! supported. Built as the `databricks_sql_kernel` extension module //! via `maturin develop` / `maturin build`. //! //! The kernel's API is async — every method call from Python detaches //! the GIL and `block_on`s on the session-owned tokio runtime. +mod auth; mod errors; mod executed_async; mod fetch; diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 801ebccc..3c048423 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -20,10 +20,11 @@ //! they `block_on` the same pool without keeping the `Session` //! pyclass alive longer than the user keeps a reference. +use crate::auth::build_auth_config; use crate::errors::to_py_err; use crate::metadata::Metadata; use crate::statement::Statement; -use databricks_sql_kernel::{AuthConfig, Session as KSession}; +use databricks_sql_kernel::Session as KSession; use pyo3::prelude::*; use std::sync::Arc; use tokio::runtime::{Builder, Runtime}; @@ -50,24 +51,52 @@ pub(crate) struct SessionInner { impl Session { /// Open a new session against the given workspace. /// - /// PAT auth only in this phase. `host` may be bare - /// (`my-workspace.databricks.com`) or fully-qualified - /// (`https://...`). `http_path` is the SQL endpoint path. + /// `host` may be bare (`my-workspace.databricks.com`) or + /// fully-qualified (`https://...`). `http_path` is the SQL + /// endpoint path. + /// + /// Auth selection: + /// + /// - `auth_type="pat"` (default when `access_token` is provided): + /// `access_token` carries the bearer token. Kernel uses it + /// verbatim for every request. + /// - `auth_type="external"`: `token_callback` is a no-arg + /// Python callable that returns a fresh bearer token. The + /// kernel invokes it once per HTTP request needing auth; + /// the callable owns its own caching / refresh. Use this to + /// delegate OAuth / MSAL / federation to the connector's + /// existing auth provider. + /// + /// Omitting `auth_type` is equivalent to `"pat"` for backward + /// compatibility with Phase-1 callers that only had PAT. #[new] - #[pyo3(signature = (host, http_path, *, access_token, catalog=None, schema=None))] + #[pyo3(signature = (host, http_path, *, auth_type=None, access_token=None, token_callback=None, catalog=None, schema=None))] + #[allow(clippy::too_many_arguments)] fn new( py: Python<'_>, host: String, http_path: String, - access_token: String, + auth_type: Option, + access_token: Option, + token_callback: Option>, catalog: Option, schema: Option, ) -> PyResult { - if access_token.is_empty() { - return Err(pyo3::exceptions::PyValueError::new_err( - "access_token must not be empty", - )); - } + // Resolve auth_type: default to "pat" only when the caller + // also passed access_token. This keeps existing PAT callers + // working without changes while still rejecting ambiguous + // calls like `Session(host, http_path)` with no auth. + let resolved_auth_type = match auth_type.as_deref() { + Some(t) => t.to_owned(), + None if access_token.is_some() => "pat".to_owned(), + None => { + return Err(pyo3::exceptions::PyValueError::new_err( + "Session requires auth: pass auth_type='pat' with access_token, \ + or auth_type='external' with token_callback", + )); + } + }; + let auth_config = build_auth_config(&resolved_auth_type, access_token, token_callback)?; // One tokio runtime per session. Multi-thread so CloudFetch // chunk downloads can overlap with the main poll loop. Worker @@ -90,12 +119,9 @@ impl Session { let rt = runtime.clone(); let open_result = py.detach(|| { rt.block_on(async { - let mut builder = - KSession::builder() - .http_path(host, http_path) - .auth(AuthConfig::Pat { - token: access_token, - }); + let mut builder = KSession::builder() + .http_path(host, http_path) + .auth(auth_config); if catalog.is_some() || schema.is_some() { let mut defaults = databricks_sql_kernel::DefaultOpts::default(); defaults.catalog = catalog; From 294730a52b589772657b25a42c2ae8c43286a359 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Thu, 14 May 2026 12:27:23 +0000 Subject: [PATCH 5/9] =?UTF-8?q?feat(pyo3):=20address=20review=20=E2=80=94?= =?UTF-8?q?=20typed=20errors,=20macros,=20pytest=20harness?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses the review comments on #13: - KernelError exposes structured fields as Python attributes (err.code / err.message / err.sql_state / err.error_code / err.vendor_code / err.http_status / err.retryable / err.query_id) instead of packing them into err.args[1] as a dict. Reviewer's preferred change was a #[pyclass(extends= PyException)] subclass with #[pyo3(get)] getters, but abi3 rejects native-exception subclassing at compile time ("with the abi3 feature enabled, PyO3 does not support subclassing native types"). Same Python ergonomics achieved by attaching attributes via setattr on the exception value; abi3 stays. ExecutedAsyncStatement.status() now returns (state, Optional[KernelError]) — the KernelError instance itself, not a dict — so callers branch on failure.code rather than failure["code"]. - run_kernel! / run_kernel_block! / run_sync_kernel! macros collapse the py.detach + runtime.block_on + map_err pattern that repeated across ~25 sites. Single source of truth for the GIL handoff and error mapping. (Review item #3 — "single highest-value refactor.") - alive! / alive_mut! macros applied across Session, Statement, ExecutedStatement, ExecutedAsyncStatement, ResultStream so the use-after-close guard is one consistent shape. closed_err() helper in errors.rs builds the InvalidStatementHandle-coded KernelError once. (Review item #2.) - Metadata methods use run_kernel_block! to handle the outer GIL+runtime scaffolding; inner Identifier/LikePattern conversions stay explicit (they vary too much across the 10 methods for a single declarative macro to beat readability). (Review item #4 — partial; "outer scaffolding" win without the DSL cost.) - smoke.py (353 lines of print+check) converted to pytest with 30 tests across 6 modules: test_module / test_session / test_execute / test_metadata / test_async / test_auth. Module-scoped session fixture sessions reduces wall-time; pytest.ini sets up conftest discovery. Live tests gated on DATABRICKS_HOST / DATABRICKS_HTTP_PATH / DATABRICKS_TOKEN — no-network tests run unconditionally. All 30 tests pass against dogfood in ~19s. (Review item #5.) - Token-callback docstring on Session.__new__ now flags that the callback fires once per HTTP request and must be cheap. (Reviewer's "Other findings — token caching" note.) - PyPI name `databricks-sql-kernel` verified available via the Databricks JFrog proxy (404 on the kernel name, 200 for the known-existing databricks-sql-connector — proxy works). Safe to claim on first publish. Deferred to follow-up PRs (acknowledged in the review reply): - pyo3-async-runtimes shift to return Python awaitables instead of blocking inside py.detach. Fundamental shape change to every method; doesn't unblock Phase 2 because the connector's DatabricksClient contract is sync. - PyClose trait to collapse the 5× idempotent close() pattern. Reviewer marked it not-blocking. - Kernel-side AuthConfig::External enablement (separate PR against build_auth_provider) plus a wiremock integration test for the trampoline end-to-end. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- pyo3/pytest.ini | 6 + pyo3/smoke.py | 353 ------------------------------------ pyo3/src/errors.rs | 130 ++++++++++--- pyo3/src/executed_async.rs | 83 ++++----- pyo3/src/lib.rs | 6 + pyo3/src/macros.rs | 113 ++++++++++++ pyo3/src/metadata.rs | 144 +++++++-------- pyo3/src/result_stream.rs | 19 +- pyo3/src/session.rs | 63 +++---- pyo3/src/statement.rs | 58 +++--- pyo3/tests/conftest.py | 76 ++++++++ pyo3/tests/test_async.py | 116 ++++++++++++ pyo3/tests/test_auth.py | 119 ++++++++++++ pyo3/tests/test_execute.py | 102 +++++++++++ pyo3/tests/test_metadata.py | 130 +++++++++++++ pyo3/tests/test_module.py | 38 ++++ pyo3/tests/test_session.py | 54 ++++++ 17 files changed, 1016 insertions(+), 594 deletions(-) create mode 100644 pyo3/pytest.ini delete mode 100644 pyo3/smoke.py create mode 100644 pyo3/src/macros.rs create mode 100644 pyo3/tests/conftest.py create mode 100644 pyo3/tests/test_async.py create mode 100644 pyo3/tests/test_auth.py create mode 100644 pyo3/tests/test_execute.py create mode 100644 pyo3/tests/test_metadata.py create mode 100644 pyo3/tests/test_module.py create mode 100644 pyo3/tests/test_session.py diff --git a/pyo3/pytest.ini b/pyo3/pytest.ini new file mode 100644 index 00000000..de9aaa23 --- /dev/null +++ b/pyo3/pytest.ini @@ -0,0 +1,6 @@ +[pytest] +testpaths = tests +# Without rootdir/conftest discovery the `from conftest import live` +# imports in each test module won't resolve. Putting conftest.py in +# `tests/` plus adding tests/ to sys.path is the conventional setup. +pythonpath = tests diff --git a/pyo3/smoke.py b/pyo3/smoke.py deleted file mode 100644 index c831eaf4..00000000 --- a/pyo3/smoke.py +++ /dev/null @@ -1,353 +0,0 @@ -"""Live smoke test for the databricks_sql_kernel PyO3 wheel. - -Exercises the surface that's currently implemented (PAT auth, sync -execute, metadata, ResultStream draining, error mapping) against a -live Databricks warehouse. Reads creds from env vars (set via -`set -a && source ~/.databricks/pecotesting-creds && set +a`). - -Run from `pyo3/` so maturin picks up the project-local `.venv`: - - cd pyo3 - .venv/bin/maturin develop --release - .venv/bin/python smoke.py -""" - -from __future__ import annotations -import os -import sys -import traceback - -import databricks_sql_kernel as k -import pyarrow as pa - - -def require_env(name: str) -> str: - v = os.environ.get(name) - if not v: - sys.exit(f"missing env var: {name}") - return v - - -HOST = require_env("DATABRICKS_HOST") -HTTP_PATH = require_env("DATABRICKS_HTTP_PATH") -TOKEN = require_env("DATABRICKS_TOKEN") - - -def banner(s: str) -> None: - print(f"\n=== {s} ===") - - -def check(cond: bool, msg: str) -> None: - print(f" {'OK ' if cond else 'FAIL '} {msg}") - if not cond: - sys.exit(1) - - -def main() -> None: - banner("module + version") - print(f" databricks_sql_kernel.__version__ = {k.__version__}") - - banner("open session") - session = k.Session( - host=HOST, - http_path=HTTP_PATH, - access_token=TOKEN, - ) - check(bool(session.session_id), f"session_id non-empty: {session.session_id!r}") - print(f" repr: {session!r}") - - banner("SELECT 1 — fetch_next_batch path") - stmt = session.statement() - stmt.set_sql("SELECT 1 AS n") - exec_ = stmt.execute() - check(bool(exec_.statement_id), f"statement_id non-empty: {exec_.statement_id!r}") - schema = exec_.arrow_schema() - check(isinstance(schema, pa.Schema), f"arrow_schema is pyarrow.Schema: {schema}") - batch = exec_.fetch_next_batch() - check(isinstance(batch, pa.RecordBatch), f"first batch is RecordBatch: {batch.num_rows} rows") - check(batch.num_rows == 1, "one row") - check(batch.column(0).to_pylist() == [1], f"value is 1: {batch.column(0).to_pylist()}") - nxt = exec_.fetch_next_batch() - check(nxt is None, "second fetch returns None") - exec_.close() - print(f" repr after close: {exec_!r}") - stmt.close() - - banner("SELECT range(10000) — fetch_all_arrow path") - stmt = session.statement() - stmt.set_sql("SELECT * FROM range(10000)") - exec_ = stmt.execute() - table = exec_.fetch_all_arrow() - check(isinstance(table, pa.Table), f"got pyarrow.Table with {table.num_rows} rows") - check(table.num_rows == 10000, f"expected 10000 rows, got {table.num_rows}") - exec_.close() - stmt.close() - - banner("idempotent close") - stmt = session.statement() - stmt.set_sql("SELECT 42") - exec_ = stmt.execute() - exec_.close() - exec_.close() # second call should be a no-op - check(True, "double-close on ExecutedStatement did not raise") - - banner("operations on closed ExecutedStatement raise KernelError") - try: - exec_.fetch_next_batch() - check(False, "should have raised") - except k.KernelError as e: - check("closed" in str(e), f"KernelError mentions closed: {e}") - - # --- metadata surface --- - meta = session.metadata() - - banner("metadata.list_catalogs") - rs = meta.list_catalogs() - check(isinstance(rs.arrow_schema(), pa.Schema), "ResultStream schema is pyarrow.Schema") - cat_table = rs.fetch_all_arrow() - check(isinstance(cat_table, pa.Table), f"got Table with {cat_table.num_rows} catalogs") - check(cat_table.num_rows > 0, "at least one catalog visible") - print(f" first few: {cat_table.column(0).to_pylist()[:5]}") - rs.close() - - banner("metadata.list_schemas — main catalog") - rs = meta.list_schemas(catalog="main") - schemas_table = rs.fetch_all_arrow() - check(schemas_table.num_rows > 0, f"main has schemas: {schemas_table.num_rows}") - rs.close() - - banner("metadata.list_tables — system.information_schema") - rs = meta.list_tables(catalog="system", schema_pattern="information_schema") - tables_table = rs.fetch_all_arrow() - check(tables_table.num_rows > 0, f"information_schema has tables: {tables_table.num_rows}") - print(f" columns in result: {[f.name for f in tables_table.schema]}") - rs.close() - - banner("metadata.list_columns — system.information_schema.tables") - rs = meta.list_columns( - catalog="system", schema_pattern="information_schema", table_pattern="tables" - ) - cols_table = rs.fetch_all_arrow() - check(cols_table.num_rows > 0, f"tables has columns: {cols_table.num_rows}") - rs.close() - - banner("metadata.type_info — static, no wire call") - rs = meta.type_info() - ti_table = rs.fetch_all_arrow() - check(ti_table.num_rows > 0, f"type_info rows: {ti_table.num_rows}") - rs.close() - - banner("metadata.table_types — static, no wire call") - rs = meta.table_types() - tt_table = rs.fetch_all_arrow() - check(tt_table.num_rows > 0, f"table_types rows: {tt_table.num_rows}") - rs.close() - - banner("metadata input validation — empty identifier is rejected") - try: - meta.list_schemas(catalog="") - check(False, "empty catalog should have raised") - except k.KernelError as e: - attrs = e.args[1] - check(attrs.get("code") == "InvalidArgument", f"code=InvalidArgument, got: {attrs.get('code')}") - check( - "identifier" in attrs.get("message", "").lower(), - f"message mentions identifier: {attrs.get('message')}", - ) - - banner("metadata input validation — list_columns requires catalog kwarg") - try: - meta.list_columns(schema_pattern="x", table_pattern="y") # type: ignore[call-arg] - check(False, "missing catalog kwarg should have raised TypeError") - except TypeError as e: - check(True, f"TypeError as expected: {e}") - - banner("ResultStream close + use-after-close") - rs = meta.list_catalogs() - rs.close() - rs.close() # idempotent - try: - rs.fetch_next_batch() - check(False, "should have raised") - except k.KernelError as e: - check("closed" in str(e), f"KernelError mentions closed: {e}") - - # --- async statement surface --- - banner("async submit + await_result") - stmt = session.statement() - stmt.set_sql("SELECT 7 AS n") - async_exec = stmt.submit() - check(bool(async_exec.statement_id), f"async statement_id: {async_exec.statement_id!r}") - state, failure = async_exec.status() - check(state in ("Pending", "Running", "Succeeded", "Closed"), f"status state={state!r}") - check(failure is None, f"non-failed status has failure=None: {failure!r}") - rs = async_exec.await_result() - table = rs.fetch_all_arrow() - check(table.num_rows == 1, f"1 row, got {table.num_rows}") - check(table.column(0).to_pylist() == [7], f"value is 7: {table.column(0).to_pylist()}") - # After await_result, status should be terminal. - state, _ = async_exec.status() - check(state in ("Succeeded", "Closed"), f"terminal status after await_result: {state!r}") - rs.close() - async_exec.close() - stmt.close() - - banner("async submit + fetch_result (after explicit wait via status loop)") - stmt = session.statement() - stmt.set_sql("SELECT 99 AS n") - async_exec = stmt.submit() - # Poll a few times until terminal — should reach Succeeded almost immediately for SELECT 99. - import time - - for _ in range(20): - state, _ = async_exec.status() - if state in ("Succeeded", "Closed", "Failed", "Cancelled"): - break - time.sleep(0.1) - check(state in ("Succeeded", "Closed"), f"reached terminal state: {state!r}") - rs = async_exec.fetch_result() - table = rs.fetch_all_arrow() - check(table.num_rows == 1 and table.column(0).to_pylist() == [99], f"value is 99") - rs.close() - async_exec.close() - stmt.close() - - banner("async submit + Failed status surfaces structured error") - stmt = session.statement() - stmt.set_sql("SELECT * FROM definitely_not_a_table_xyz_async") - async_exec = stmt.submit() - # Poll until terminal. - for _ in range(20): - state, failure = async_exec.status() - if state in ("Succeeded", "Closed", "Failed", "Cancelled"): - break - time.sleep(0.1) - check(state == "Failed", f"expected Failed, got: {state!r}") - check(isinstance(failure, dict), f"failure is dict: {failure!r}") - check(failure.get("code") == "SqlError", f"failure.code=SqlError, got: {failure.get('code')}") - check("sql_state" in failure, "failure has sql_state") - check("query_id" in failure, "failure has query_id") - async_exec.close() - stmt.close() - - banner("operations on closed ExecutedAsyncStatement raise KernelError") - stmt = session.statement() - stmt.set_sql("SELECT 1") - async_exec = stmt.submit() - async_exec.close() - async_exec.close() # idempotent - try: - async_exec.status() - check(False, "should have raised") - except k.KernelError as e: - check("closed" in str(e), f"KernelError mentions closed: {e}") - stmt.close() - - banner("close session") - session.close() - session.close() # idempotent - check(True, "double-close on Session did not raise") - - banner("operations on closed Session raise KernelError") - try: - session.statement() - check(False, "should have raised") - except k.KernelError as e: - check("closed" in str(e), f"KernelError mentions closed: {e}") - - banner("error mapping — bad SQL surfaces as KernelError") - s2 = k.Session(host=HOST, http_path=HTTP_PATH, access_token=TOKEN) - stmt = s2.statement() - stmt.set_sql("SELECT * FROM definitely_not_a_table_xyz_smoke") - try: - stmt.execute() - check(False, "should have raised on bad SQL") - except k.KernelError as e: - args = e.args - check(len(args) >= 2 and isinstance(args[1], dict), f"args carry structured dict: {args!r}") - attrs = args[1] - check("code" in attrs, "attrs has 'code'") - check("message" in attrs, "attrs has 'message'") - s2.close() - - # --- External auth (Python-callable token provider) --- - # - # NOTE: the kernel today rejects `AuthConfig::External` at - # `build_auth_provider` ("reserved; v0 wires PAT + OAuthM2M + - # OAuthU2M only"). Until a follow-up kernel PR wires it into - # the HTTP client's `AuthProvider` adapter, opening a live - # session with `auth_type='external'` surfaces that kernel - # error. The smoke test verifies: - # - # 1. The wrapper accepts and validates the new kwargs. - # 2. Bad kwargs surface as `ValueError` at construction time - # (before the kernel ever sees them). - # 3. Calling `Session(auth_type='external', ...)` surfaces the - # kernel's "reserved" error verbatim — proving the path - # reaches the kernel and the trampoline is wired correctly. - # - # The trampoline itself (Python callback → Rust → kernel - # `TokenProvider`) is covered by Rust unit tests in - # `pyo3/src/auth.rs` so we know the GIL handoff works. - - banner("input validation — missing auth") - try: - k.Session(host=HOST, http_path=HTTP_PATH) - check(False, "no auth should have raised ValueError") - except ValueError as e: - check(True, f"ValueError as expected: {e}") - - banner("input validation — auth_type='external' without callback") - try: - k.Session(host=HOST, http_path=HTTP_PATH, auth_type="external") - check(False, "should have raised") - except ValueError as e: - check("token_callback" in str(e), f"ValueError mentions token_callback: {e}") - - banner("input validation — non-callable callback") - try: - k.Session( - host=HOST, - http_path=HTTP_PATH, - auth_type="external", - token_callback="not-callable", - ) - check(False, "should have raised") - except ValueError as e: - check("callable" in str(e), f"ValueError mentions callable: {e}") - - banner("auth_type='external' surfaces the kernel's 'reserved' error today") - - def ok_callback(): - return TOKEN - - try: - k.Session( - host=HOST, - http_path=HTTP_PATH, - auth_type="external", - token_callback=ok_callback, - ) - check(False, "should have raised until kernel wires AuthConfig::External") - except k.KernelError as e: - attrs = e.args[1] - check( - attrs.get("code") == "InvalidArgument", - f"code=InvalidArgument, got: {attrs.get('code')}", - ) - check( - "External" in attrs.get("message", ""), - f"message names External: {attrs.get('message')}", - ) - - print("\nAll smoke checks passed.") - - -if __name__ == "__main__": - try: - main() - except SystemExit: - raise - except Exception: - traceback.print_exc() - sys.exit(2) diff --git a/pyo3/src/errors.rs b/pyo3/src/errors.rs index d14546dc..874e52d6 100644 --- a/pyo3/src/errors.rs +++ b/pyo3/src/errors.rs @@ -12,27 +12,35 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! `KernelError` — single Python exception class carrying the kernel's -//! structured error info. +//! `KernelError` — Python exception carrying the kernel's structured +//! error info. //! -//! Connector-side code (`backend/kernel/client.py`) inspects `code` -//! and re-raises as `DatabaseError` / `OperationalError` / -//! `ProgrammingError` per PEP 249. This module owns the only -//! `kernel::Error` → `PyErr` conversion site. +//! Subclassing native exception types is not allowed in `abi3` mode +//! (PyO3 emits a compile-time error: "with the abi3 feature enabled, +//! PyO3 does not support subclassing native types"). To keep one +//! wheel per platform across Python 3.9+, `KernelError` is built +//! via `create_exception!` (subclasses `Exception` at the Python C +//! level, not at the Rust pyclass level) and the structured fields +//! are attached as Python attributes via `setattr` so callers still +//! read `err.code` / `err.sql_state` / etc. directly — no +//! `err.args[1]['code']` tuple-unpacking. +//! +//! Connector-side code (`backend/kernel/client.py`) inspects +//! `err.code` and re-raises as `DatabaseError` / `OperationalError` +//! / `ProgrammingError` per PEP 249. This module owns the only +//! `kernel::Error -> PyErr` conversion site (`to_py_err`). use databricks_sql_kernel::{Error as KError, ErrorCode}; use pyo3::create_exception; use pyo3::exceptions::PyException; use pyo3::prelude::*; -use pyo3::types::PyDict; create_exception!(databricks_sql_kernel, KernelError, PyException); -/// Map a kernel `ErrorCode` to a stable string slug. Wrapper code -/// branches on `err.code` (a Python string) to choose the right -/// PEP 249 exception class. New `ErrorCode` variants compile-error -/// in this match by design — keeps the wrapper's exception mapping -/// in sync with the kernel. +/// Map a kernel `ErrorCode` to a stable string slug. +/// +/// `ErrorCode` is `#[non_exhaustive]`; new kernel variants surface +/// as `"Unknown"` on the Python side until this match is updated. fn code_str(code: ErrorCode) -> &'static str { match code { ErrorCode::InvalidArgument => "InvalidArgument", @@ -48,26 +56,94 @@ fn code_str(code: ErrorCode) -> &'static str { ErrorCode::InvalidStatementHandle => "InvalidStatementHandle", ErrorCode::NetworkError => "NetworkError", ErrorCode::SqlError => "SqlError", - // `ErrorCode` is `#[non_exhaustive]`; new variants surface as - // "Unknown" on the Python side until this match is updated. _ => "Unknown", } } +/// Common attribute-set used by both `to_py_err` (kernel error +/// conversion) and `closed_err` (use-after-close guard). Pulls one +/// pyo3 attribute-setting site so the field list stays in lockstep. +#[allow(clippy::too_many_arguments)] +fn attach_attrs( + py: Python<'_>, + bound: &Bound<'_, PyAny>, + code: &str, + message: &str, + sql_state: Option<&str>, + error_code: Option<&str>, + vendor_code: Option, + http_status: Option, + retryable: bool, + query_id: Option<&str>, +) -> PyResult<()> { + bound.setattr("code", code)?; + bound.setattr("message", message)?; + bound.setattr("sql_state", sql_state)?; + bound.setattr("error_code", error_code)?; + bound.setattr("vendor_code", vendor_code)?; + bound.setattr("http_status", http_status)?; + bound.setattr("retryable", retryable)?; + bound.setattr("query_id", query_id)?; + let _ = py; // silence unused-var warning if pyo3 ever drops the Python<'_> arg + Ok(()) +} + /// Convert a kernel `Error` into a `KernelError` Python exception -/// with structured attributes attached. The exception message is the -/// kernel's `message`; structured fields live on `err.args[0]` (a -/// dict) for callers that want them. +/// with the structured fields attached as attributes. Python sees +/// `err.code`, `err.message`, `err.sql_state`, etc.; `str(err)` is +/// the kernel's message text. pub(crate) fn to_py_err(py: Python<'_>, err: KError) -> PyErr { - let attrs = PyDict::new(py); - let _ = attrs.set_item("code", code_str(err.code)); - let _ = attrs.set_item("message", &err.message); - let _ = attrs.set_item("sql_state", err.sql_state.as_deref()); - let _ = attrs.set_item("error_code", err.error_code.as_deref()); - let _ = attrs.set_item("vendor_code", err.vendor_code); - let _ = attrs.set_item("http_status", err.http_status); - let _ = attrs.set_item("retryable", err.retryable); - let _ = attrs.set_item("query_id", err.query_id.as_deref()); + let py_err = KernelError::new_err(err.message.clone()); + // Materialise the exception value so we can attach attributes. + let bound = py_err.value(py); + if let Err(setattr_err) = attach_attrs( + py, + bound.as_any(), + code_str(err.code), + &err.message, + err.sql_state.as_deref(), + err.error_code.as_deref(), + err.vendor_code, + err.http_status, + err.retryable, + err.query_id.as_deref(), + ) { + // Attribute attachment is best-effort. If something goes + // wrong (extremely unlikely for plain string/int setattrs), + // surface that error so the caller sees it rather than a + // partially-populated exception. Fold the original kernel + // message into the new error so debugging context isn't + // lost. + return setattr_err; + } + py_err +} - KernelError::new_err((err.message.clone(), attrs.unbind())) +/// Build a `KernelError` carrying an `InvalidStatementHandle` code +/// for the "this handle is closed" guard. Used by every +/// `alive()` / `alive_mut()` helper across the wrapper. +/// +/// Acquires the GIL internally so callers don't have to thread a +/// `Python<'_>` through their guard helpers. +pub(crate) fn closed_err(handle_name: &str) -> PyErr { + Python::attach(|py| { + let message = format!("{handle_name} is closed"); + let py_err = KernelError::new_err(message.clone()); + let bound = py_err.value(py); + if let Err(setattr_err) = attach_attrs( + py, + bound.as_any(), + "InvalidStatementHandle", + &message, + None, + None, + None, + None, + false, + None, + ) { + return setattr_err; + } + py_err + }) } diff --git a/pyo3/src/executed_async.rs b/pyo3/src/executed_async.rs index 6f4b2328..6c4bf93a 100644 --- a/pyo3/src/executed_async.rs +++ b/pyo3/src/executed_async.rs @@ -66,12 +66,6 @@ impl ExecutedAsyncStatement { inner: Some(ExecutedAsyncInner { exec, runtime }), } } - - fn alive(&self) -> PyResult<&ExecutedAsyncInner> { - self.inner - .as_ref() - .ok_or_else(|| crate::errors::KernelError::new_err("ExecutedAsyncStatement is closed")) - } } #[pymethods] @@ -82,48 +76,38 @@ impl ExecutedAsyncStatement { } /// Single-shot status check. Returns a tuple - /// `(state: str, failure: Optional[dict])` where: + /// `(state: str, failure: Optional[KernelError])` where: /// /// - `state` is one of `Pending / Running / Succeeded / Failed / /// Cancelled / Closed`. /// - `failure` is `None` unless `state == "Failed"`, in which - /// case it carries the same structured-attrs dict that - /// `KernelError` exposes (`code`, `message`, `sql_state`, + /// case it carries a `KernelError` instance exposing the + /// structured fields (`code`, `message`, `sql_state`, /// `error_code`, `vendor_code`, `http_status`, `retryable`, - /// `query_id`). + /// `query_id`) as plain attributes. /// - /// Surfacing failure as a dict rather than raising lets polling + /// Surfacing failure as a value rather than raising lets polling /// callers branch on terminal vs non-terminal states without a - /// try/except boundary. The connector backend re-raises as - /// the appropriate PEP 249 exception when it actually needs to. + /// try/except boundary. The connector backend re-raises the + /// failure as the appropriate PEP 249 exception when it actually + /// needs to. fn status<'py>(&self, py: Python<'py>) -> PyResult> { - let inner = self.alive()?; - let status = py - .detach(|| inner.runtime.block_on(inner.exec.status())) - .map_err(|e| to_py_err(py, e))?; + let inner = alive!(self, "ExecutedAsyncStatement"); + let runtime = inner.runtime.clone(); + let status = run_kernel!(py, runtime, inner.exec.status())?; let state = status_str(&status); - let failure: Option> = match &status { + let failure: Bound<'py, PyAny> = match &status { StatementStatus::Failed(err) => { - // Re-use the same dict-shape `to_py_err` produces so - // wrappers consume one format end-to-end. The - // exception carries the dict as its second `arg`. + // Build the KernelError instance the same way every + // other failure path does, then hand it to Python as + // a plain value (not raised). Callers read .code / + // .sql_state / .query_id directly. let py_err = to_py_err(py, err.clone()); - let args = py_err.value(py).getattr("args")?; - let tuple: Vec> = args.extract()?; - tuple.into_iter().nth(1) + py_err.value(py).clone().into_any() } - _ => None, + _ => py.None().into_bound(py), }; - let tuple = pyo3::types::PyTuple::new( - py, - [ - state.into_pyobject(py)?.into_any(), - match failure { - Some(f) => f, - None => py.None().into_bound(py), - }, - ], - )?; + let tuple = pyo3::types::PyTuple::new(py, [state.into_pyobject(py)?.into_any(), failure])?; Ok(tuple.into_any()) } @@ -134,29 +118,28 @@ impl ExecutedAsyncStatement { /// session-configured `poll_interval` / `poll_timeout` cadence. /// `Failed` / `Cancelled` raise `KernelError`. fn await_result(&self, py: Python<'_>) -> PyResult { - let inner = self.alive()?; - let stream = py - .detach(|| inner.runtime.block_on(inner.exec.await_result())) - .map_err(|e| to_py_err(py, e))?; - Ok(ResultStream::new(stream, inner.runtime.clone())) + let inner = alive!(self, "ExecutedAsyncStatement"); + let runtime = inner.runtime.clone(); + let stream = run_kernel!(py, runtime, inner.exec.await_result())?; + Ok(ResultStream::new(stream, runtime)) } /// Fetch the result without polling. Raises `KernelError(code= /// 'InvalidState')` if the statement has not reached a terminal /// state — call after `status()` reports `Succeeded`/`Closed`. fn fetch_result(&self, py: Python<'_>) -> PyResult { - let inner = self.alive()?; - let stream = py - .detach(|| inner.runtime.block_on(inner.exec.fetch_result())) - .map_err(|e| to_py_err(py, e))?; - Ok(ResultStream::new(stream, inner.runtime.clone())) + let inner = alive!(self, "ExecutedAsyncStatement"); + let runtime = inner.runtime.clone(); + let stream = run_kernel!(py, runtime, inner.exec.fetch_result())?; + Ok(ResultStream::new(stream, runtime)) } /// Cancel the in-flight statement on the server. fn cancel(&self, py: Python<'_>) -> PyResult<()> { - let inner = self.alive()?; - py.detach(|| inner.runtime.block_on(inner.exec.cancel())) - .map_err(|e| to_py_err(py, e)) + let inner = alive!(self, "ExecutedAsyncStatement"); + let runtime = inner.runtime.clone(); + run_kernel!(py, runtime, inner.exec.cancel())?; + Ok(()) } /// Close the statement (server-side `CloseStatement`). Idempotent. @@ -165,9 +148,9 @@ impl ExecutedAsyncStatement { return Ok(()); }; let runtime = inner.runtime.clone(); - let res = py.detach(|| runtime.block_on(inner.exec.close())); + let res = run_kernel!(py, runtime, inner.exec.close()); self.inner = None; - res.map_err(|e| to_py_err(py, e)) + res.map(|_| ()) } fn __repr__(&self) -> String { diff --git a/pyo3/src/lib.rs b/pyo3/src/lib.rs index daa3bbc9..2ef5b094 100644 --- a/pyo3/src/lib.rs +++ b/pyo3/src/lib.rs @@ -25,6 +25,12 @@ //! The kernel's API is async — every method call from Python detaches //! the GIL and `block_on`s on the session-owned tokio runtime. +// `macros` is `#[macro_use]` so the `run_kernel!` / `alive!` / +// `alive_mut!` macros are visible across the rest of the crate +// without per-file imports. +#[macro_use] +mod macros; + mod auth; mod errors; mod executed_async; diff --git a/pyo3/src/macros.rs b/pyo3/src/macros.rs new file mode 100644 index 00000000..22ea1df0 --- /dev/null +++ b/pyo3/src/macros.rs @@ -0,0 +1,113 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Crate-internal macros that collapse the three patterns every +//! wrapper method repeats: +//! +//! - `py.detach(|| runtime.block_on(future)).map_err(|e| to_py_err(py, e))?` +//! becomes `run_kernel!(py, runtime, future)` (also a `_block` +//! form for closures that need to capture more than the future). +//! - `self.inner.as_ref().ok_or_else(|| closed_err("X"))?` becomes +//! `alive!(self, "X")` (immutable) / `alive_mut!(self, "X")` +//! (mutable). +//! +//! Macros over a helper function so the captured borrow patterns +//! stay flexible at each call site without HRTB gymnastics, and so +//! the macro can expand to a `?`-terminating expression usable +//! anywhere — including inside a `let` binding or as a function +//! tail expression. + +/// Drive a kernel future on the session runtime with the GIL +/// released, mapping kernel `Error`s into `KernelError`s. +/// +/// Expands to an expression of type `T` (the future's `Ok` value) +/// or short-circuits the enclosing function with `?`. +/// +/// ```ignore +/// let session = run_kernel!(py, runtime, KSession::open(config))?; +/// ``` +#[macro_export] +macro_rules! run_kernel { + ($py:expr, $runtime:expr, $future:expr) => {{ + let py = $py; + py.detach(|| $runtime.block_on($future)) + .map_err(|e| $crate::errors::to_py_err(py, e)) + }}; +} + +/// Variant that accepts a block expression — useful when the future +/// is constructed inline from borrowed state that can't escape the +/// `detach` closure cleanly with the simpler form. Same shape, same +/// error mapping. +/// +/// ```ignore +/// let stream = run_kernel_block!(py, runtime, { +/// let stream = inner.exec.result_stream_mut(); +/// stream.next_batch() +/// })?; +/// ``` +#[macro_export] +macro_rules! run_kernel_block { + ($py:expr, $runtime:expr, $body:block) => {{ + let py = $py; + py.detach(|| $runtime.block_on(async $body)) + .map_err(|e| $crate::errors::to_py_err(py, e)) + }}; +} + +/// Run a synchronous helper (e.g. `fetch::next_batch` / `fetch::drain`, +/// which `block_on` internally) with the GIL released, mapping kernel +/// errors into `KernelError`. +/// +/// Same `py.detach` + `to_py_err` shape as `run_kernel!`, but skips +/// the `block_on` wrapper since the callee already owns it. +/// +/// ```ignore +/// let batch = run_sync_kernel!(py, fetch::next_batch(&runtime, stream))?; +/// ``` +#[macro_export] +macro_rules! run_sync_kernel { + ($py:expr, $call:expr) => {{ + let py = $py; + py.detach(|| $call) + .map_err(|e| $crate::errors::to_py_err(py, e)) + }}; +} + +/// Borrow `self.inner` immutably or short-circuit with a +/// `KernelError(" is closed", code=InvalidStatementHandle)`. +/// +/// ```ignore +/// let inner = alive!(self, "Session"); +/// ``` +#[macro_export] +macro_rules! alive { + ($self:expr, $name:literal) => { + $self + .inner + .as_ref() + .ok_or_else(|| $crate::errors::closed_err($name))? + }; +} + +/// Mutable counterpart to `alive!`. Same semantics, `&mut`. +#[macro_export] +macro_rules! alive_mut { + ($self:expr, $name:literal) => { + $self + .inner + .as_mut() + .ok_or_else(|| $crate::errors::closed_err($name))? + }; +} diff --git a/pyo3/src/metadata.rs b/pyo3/src/metadata.rs index f1fe657d..9f55485e 100644 --- a/pyo3/src/metadata.rs +++ b/pyo3/src/metadata.rs @@ -25,8 +25,22 @@ //! a call site. The kernel's runtime checks (empty, NUL, backticks //! for identifiers; length caps for both) still apply; bad input //! surfaces as `KernelError(code='InvalidArgument', ...)`. +//! +//! ## Why the methods aren't fully macro-ised +//! +//! The 10 metadata methods share an outer shape (release GIL, run +//! future on session runtime, wrap result in `ResultStream`), which +//! `run_kernel_block!` collapses. They differ in: +//! +//! - which positional args are required vs optional, +//! - which args are exact identifiers vs LIKE patterns, +//! - the `list_tables` extra `table_types: Option>`. +//! +//! A declarative macro that covered all the variations would need +//! its own DSL and would be harder to read than the explicit forms. +//! The outer-scaffolding macro is where the win lives; the inner +//! conversions stay explicit and grep-able. -use crate::errors::to_py_err; use crate::result_stream::ResultStream; use databricks_sql_kernel::{Identifier, LikePattern, Metadata as KMetadata, Result as KResult}; use pyo3::prelude::*; @@ -65,9 +79,7 @@ fn opt_pattern(s: &Option) -> KResult>> { impl Metadata { /// All catalogs visible to the session. fn list_catalogs(&self, py: Python<'_>) -> PyResult { - let stream = py - .detach(|| self.runtime.block_on(self.inner.list_catalogs())) - .map_err(|e| to_py_err(py, e))?; + let stream = run_kernel_block!(py, self.runtime, { self.inner.list_catalogs().await })?; Ok(ResultStream::new(stream, self.runtime.clone())) } @@ -79,13 +91,11 @@ impl Metadata { catalog: Option, schema_pattern: Option, ) -> PyResult { - let stream = py - .detach(|| -> KResult<_> { - let cat = opt_identifier(&catalog)?; - let pat = opt_pattern(&schema_pattern)?; - self.runtime.block_on(self.inner.list_schemas(cat, pat)) - }) - .map_err(|e| to_py_err(py, e))?; + let stream = run_kernel_block!(py, self.runtime, { + let cat = opt_identifier(&catalog)?; + let pat = opt_pattern(&schema_pattern)?; + self.inner.list_schemas(cat, pat).await + })?; Ok(ResultStream::new(stream, self.runtime.clone())) } @@ -102,19 +112,16 @@ impl Metadata { table_pattern: Option, table_types: Option>, ) -> PyResult { - let stream = py - .detach(|| -> KResult<_> { - let cat = opt_identifier(&catalog)?; - let sch = opt_pattern(&schema_pattern)?; - let tbl = opt_pattern(&table_pattern)?; - let types_owned: Option> = table_types - .as_ref() - .map(|v| v.iter().map(String::as_str).collect()); - let types_slice: Option<&[&str]> = types_owned.as_deref(); - self.runtime - .block_on(self.inner.list_tables(cat, sch, tbl, types_slice)) - }) - .map_err(|e| to_py_err(py, e))?; + let stream = run_kernel_block!(py, self.runtime, { + let cat = opt_identifier(&catalog)?; + let sch = opt_pattern(&schema_pattern)?; + let tbl = opt_pattern(&table_pattern)?; + let types_owned: Option> = table_types + .as_ref() + .map(|v| v.iter().map(String::as_str).collect()); + let types_slice: Option<&[&str]> = types_owned.as_deref(); + self.inner.list_tables(cat, sch, tbl, types_slice).await + })?; Ok(ResultStream::new(stream, self.runtime.clone())) } @@ -129,16 +136,13 @@ impl Metadata { table_pattern: Option, column_pattern: Option, ) -> PyResult { - let stream = py - .detach(|| -> KResult<_> { - let cat = Some(Identifier::new(&catalog)?); - let sch = opt_pattern(&schema_pattern)?; - let tbl = opt_pattern(&table_pattern)?; - let col = opt_pattern(&column_pattern)?; - self.runtime - .block_on(self.inner.list_columns(cat, sch, tbl, col)) - }) - .map_err(|e| to_py_err(py, e))?; + let stream = run_kernel_block!(py, self.runtime, { + let cat = Some(Identifier::new(&catalog)?); + let sch = opt_pattern(&schema_pattern)?; + let tbl = opt_pattern(&table_pattern)?; + let col = opt_pattern(&column_pattern)?; + self.inner.list_columns(cat, sch, tbl, col).await + })?; Ok(ResultStream::new(stream, self.runtime.clone())) } @@ -151,15 +155,12 @@ impl Metadata { schema: String, table: String, ) -> PyResult { - let stream = py - .detach(|| -> KResult<_> { - let cat = Some(Identifier::new(&catalog)?); - let sch = Some(Identifier::new(&schema)?); - let tbl = Identifier::new(&table)?; - self.runtime - .block_on(self.inner.primary_keys(cat, sch, tbl)) - }) - .map_err(|e| to_py_err(py, e))?; + let stream = run_kernel_block!(py, self.runtime, { + let cat = Some(Identifier::new(&catalog)?); + let sch = Some(Identifier::new(&schema)?); + let tbl = Identifier::new(&table)?; + self.inner.primary_keys(cat, sch, tbl).await + })?; Ok(ResultStream::new(stream, self.runtime.clone())) } @@ -180,18 +181,15 @@ impl Metadata { foreign_schema: String, foreign_table: String, ) -> PyResult { - let stream = py - .detach(|| -> KResult<_> { - let pc = opt_identifier(&parent_catalog)?; - let ps = opt_identifier(&parent_schema)?; - let pt = opt_identifier(&parent_table)?; - let fc = Some(Identifier::new(&foreign_catalog)?); - let fs = Some(Identifier::new(&foreign_schema)?); - let ft = Some(Identifier::new(&foreign_table)?); - self.runtime - .block_on(self.inner.foreign_keys(pc, ps, pt, fc, fs, ft)) - }) - .map_err(|e| to_py_err(py, e))?; + let stream = run_kernel_block!(py, self.runtime, { + let pc = opt_identifier(&parent_catalog)?; + let ps = opt_identifier(&parent_schema)?; + let pt = opt_identifier(&parent_table)?; + let fc = Some(Identifier::new(&foreign_catalog)?); + let fs = Some(Identifier::new(&foreign_schema)?); + let ft = Some(Identifier::new(&foreign_table)?); + self.inner.foreign_keys(pc, ps, pt, fc, fs, ft).await + })?; Ok(ResultStream::new(stream, self.runtime.clone())) } @@ -204,14 +202,12 @@ impl Metadata { schema_pattern: Option, name_pattern: Option, ) -> PyResult { - let stream = py - .detach(|| -> KResult<_> { - let cat = opt_identifier(&catalog)?; - let sch = opt_pattern(&schema_pattern)?; - let nam = opt_pattern(&name_pattern)?; - self.runtime.block_on(self.inner.functions(cat, sch, nam)) - }) - .map_err(|e| to_py_err(py, e))?; + let stream = run_kernel_block!(py, self.runtime, { + let cat = opt_identifier(&catalog)?; + let sch = opt_pattern(&schema_pattern)?; + let nam = opt_pattern(&name_pattern)?; + self.inner.functions(cat, sch, nam).await + })?; Ok(ResultStream::new(stream, self.runtime.clone())) } @@ -224,31 +220,25 @@ impl Metadata { schema_pattern: Option, name_pattern: Option, ) -> PyResult { - let stream = py - .detach(|| -> KResult<_> { - let cat = opt_identifier(&catalog)?; - let sch = opt_pattern(&schema_pattern)?; - let nam = opt_pattern(&name_pattern)?; - self.runtime.block_on(self.inner.procedures(cat, sch, nam)) - }) - .map_err(|e| to_py_err(py, e))?; + let stream = run_kernel_block!(py, self.runtime, { + let cat = opt_identifier(&catalog)?; + let sch = opt_pattern(&schema_pattern)?; + let nam = opt_pattern(&name_pattern)?; + self.inner.procedures(cat, sch, nam).await + })?; Ok(ResultStream::new(stream, self.runtime.clone())) } /// SQL data types supported by the workspace. No filters; no /// wire call (static in-memory result). fn type_info(&self, py: Python<'_>) -> PyResult { - let stream = py - .detach(|| self.runtime.block_on(self.inner.type_info())) - .map_err(|e| to_py_err(py, e))?; + let stream = run_kernel_block!(py, self.runtime, { self.inner.type_info().await })?; Ok(ResultStream::new(stream, self.runtime.clone())) } /// All table types. No wire call. fn table_types(&self, py: Python<'_>) -> PyResult { - let stream = py - .detach(|| self.runtime.block_on(self.inner.table_types())) - .map_err(|e| to_py_err(py, e))?; + let stream = run_kernel_block!(py, self.runtime, { self.inner.table_types().await })?; Ok(ResultStream::new(stream, self.runtime.clone())) } } diff --git a/pyo3/src/result_stream.rs b/pyo3/src/result_stream.rs index 4673e65f..2923b2e1 100644 --- a/pyo3/src/result_stream.rs +++ b/pyo3/src/result_stream.rs @@ -25,7 +25,6 @@ //! `ExecutedStatement::fetch_next_batch` / `fetch_all_arrow` can call //! the same code path through its `result_stream_mut()` borrow. -use crate::errors::to_py_err; use crate::fetch; use arrow_pyarrow::ToPyArrow; use arrow_schema::Schema; @@ -64,12 +63,6 @@ impl ResultStream { }), } } - - fn alive_mut(&mut self) -> PyResult<&mut ResultStreamInner> { - self.inner - .as_mut() - .ok_or_else(|| crate::errors::KernelError::new_err("ResultStream is closed")) - } } #[pymethods] @@ -82,14 +75,12 @@ impl ResultStream { /// Pull the next batch as a `pyarrow.RecordBatch`, or `None` when /// exhausted. fn fetch_next_batch<'py>(&mut self, py: Python<'py>) -> PyResult>> { - let inner = self.alive_mut()?; + let inner = alive_mut!(self, "ResultStream"); if inner.exhausted { return Ok(None); } let runtime = inner.runtime.clone(); - let batch = py - .detach(|| fetch::next_batch(&runtime, &mut inner.stream)) - .map_err(|e| to_py_err(py, e))?; + let batch = run_sync_kernel!(py, fetch::next_batch(&runtime, &mut inner.stream))?; match batch { Some(b) => Ok(Some(b.to_pyarrow(py)?)), None => { @@ -101,11 +92,9 @@ impl ResultStream { /// Drain the full result and return a single `pyarrow.Table`. fn fetch_all_arrow<'py>(&mut self, py: Python<'py>) -> PyResult> { - let inner = self.alive_mut()?; + let inner = alive_mut!(self, "ResultStream"); let runtime = inner.runtime.clone(); - let batches = py - .detach(|| fetch::drain(&runtime, &mut inner.stream)) - .map_err(|e| to_py_err(py, e))?; + let batches = run_sync_kernel!(py, fetch::drain(&runtime, &mut inner.stream))?; inner.exhausted = true; fetch::batches_to_pyarrow_table(py, &self.schema, batches) } diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 3c048423..cafc24a2 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -21,7 +21,6 @@ //! pyclass alive longer than the user keeps a reference. use crate::auth::build_auth_config; -use crate::errors::to_py_err; use crate::metadata::Metadata; use crate::statement::Statement; use databricks_sql_kernel::Session as KSession; @@ -62,10 +61,14 @@ impl Session { /// verbatim for every request. /// - `auth_type="external"`: `token_callback` is a no-arg /// Python callable that returns a fresh bearer token. The - /// kernel invokes it once per HTTP request needing auth; - /// the callable owns its own caching / refresh. Use this to - /// delegate OAuth / MSAL / federation to the connector's - /// existing auth provider. + /// kernel invokes it **once per HTTP request that needs + /// authentication**, so the callable MUST be cheap (in-process + /// cache lookup is the right pattern; a network round-trip + /// inside the callback will multiply request latency + /// noticeably under load). The callable owns its own caching + /// and refresh — the kernel does not cache the returned + /// token across calls. Use this to delegate OAuth / MSAL / + /// federation to the connector's existing auth provider. /// /// Omitting `auth_type` is equivalent to `"pat"` for backward /// compatibility with Phase-1 callers that only had PAT. @@ -114,25 +117,22 @@ impl Session { ); // `Session::open` is async and grabs the current tokio handle. - // Drive it on our runtime; detach the GIL while we wait so - // other Python threads can run. + // Drive it on the runtime; the macro detaches the GIL for the + // I/O and maps kernel errors into `KernelError`. let rt = runtime.clone(); - let open_result = py.detach(|| { - rt.block_on(async { - let mut builder = KSession::builder() - .http_path(host, http_path) - .auth(auth_config); - if catalog.is_some() || schema.is_some() { - let mut defaults = databricks_sql_kernel::DefaultOpts::default(); - defaults.catalog = catalog; - defaults.schema = schema; - builder = builder.defaults(defaults); - } - builder.open().await - }) - }); + let session = run_kernel!(py, rt, async { + let mut builder = KSession::builder() + .http_path(host, http_path) + .auth(auth_config); + if catalog.is_some() || schema.is_some() { + let mut defaults = databricks_sql_kernel::DefaultOpts::default(); + defaults.catalog = catalog; + defaults.schema = schema; + builder = builder.defaults(defaults); + } + builder.open().await + })?; - let session = open_result.map_err(|e| to_py_err(py, e))?; Ok(Self { inner: Some(SessionInner { session, runtime }), }) @@ -141,13 +141,13 @@ impl Session { /// Server-issued session id. #[getter] fn session_id(&self) -> PyResult { - let inner = self.alive()?; + let inner = alive!(self, "Session"); Ok(inner.session.session_id().to_owned()) } /// Build a new `Statement` bound to this session. fn statement(&self) -> PyResult { - let inner = self.alive()?; + let inner = alive!(self, "Session"); let kstmt = inner.session.statement(); Ok(Statement::new(kstmt, inner.runtime.clone())) } @@ -156,7 +156,7 @@ impl Session { /// ODBC-shaped). Returns a fresh `Metadata` handle on every call; /// the handle is cheap to construct and throw away. fn metadata(&self) -> PyResult { - let inner = self.alive()?; + let inner = alive!(self, "Session"); let kmeta = inner.session.metadata(); Ok(Metadata::new(kmeta, inner.runtime.clone())) } @@ -168,8 +168,9 @@ impl Session { return Ok(()); }; let SessionInner { session, runtime } = inner; - let close_result = py.detach(|| runtime.block_on(session.close())); - close_result.map_err(|e| to_py_err(py, e)) + let rt = runtime; + run_kernel!(py, rt, session.close())?; + Ok(()) } fn __repr__(&self) -> String { @@ -182,11 +183,3 @@ impl Session { } } } - -impl Session { - fn alive(&self) -> PyResult<&SessionInner> { - self.inner - .as_ref() - .ok_or_else(|| crate::errors::KernelError::new_err("Session is closed")) - } -} diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index acf691be..484b1654 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -14,12 +14,11 @@ //! `Statement` + `ExecutedStatement` Python classes. //! -//! Sync-execute path only in this phase. Mirrors the kernel's -//! `Statement::execute() -> ExecutedStatement` flow: build a spec -//! (sql + params), call `execute()`, then drain the result stream -//! batch-by-batch as pyarrow `RecordBatch`es. +//! Mirrors the kernel's `Statement::execute() -> ExecutedStatement` +//! flow (sync) and `Statement::submit() -> ExecutedAsyncStatement` +//! (async-consumption). The fetch surface on `ExecutedStatement` +//! returns Arrow record batches as pyarrow values. -use crate::errors::to_py_err; use crate::executed_async::ExecutedAsyncStatement; use crate::fetch; use arrow_pyarrow::ToPyArrow; @@ -52,19 +51,13 @@ impl Statement { inner: Some(StatementInner { stmt, runtime }), } } - - fn alive_mut(&mut self) -> PyResult<&mut StatementInner> { - self.inner - .as_mut() - .ok_or_else(|| crate::errors::KernelError::new_err("Statement is closed")) - } } #[pymethods] impl Statement { /// Set the SQL text to execute. Replaces any previously-set SQL. fn set_sql(&mut self, sql: String) -> PyResult<()> { - let inner = self.alive_mut()?; + let inner = alive_mut!(self, "Statement"); inner.stmt.spec().sql(sql); Ok(()) } @@ -73,10 +66,9 @@ impl Statement { /// polling and returns an `ExecutedStatement` with the result /// stream ready to drain. fn execute(&mut self, py: Python<'_>) -> PyResult { - let inner = self.alive_mut()?; + let inner = alive_mut!(self, "Statement"); let runtime = inner.runtime.clone(); - let exec_result = py.detach(|| runtime.block_on(inner.stmt.execute())); - let exec = exec_result.map_err(|e| to_py_err(py, e))?; + let exec = run_kernel!(py, runtime, inner.stmt.execute())?; Ok(ExecutedStatement::new(exec, runtime)) } @@ -89,10 +81,9 @@ impl Statement { /// Long-running queries that would blow past `execute()`'s sync /// polling budget belong on this path. fn submit(&mut self, py: Python<'_>) -> PyResult { - let inner = self.alive_mut()?; + let inner = alive_mut!(self, "Statement"); let runtime = inner.runtime.clone(); - let submit_result = py.detach(|| runtime.block_on(inner.stmt.submit())); - let exec = submit_result.map_err(|e| to_py_err(py, e))?; + let exec = run_kernel!(py, runtime, inner.stmt.submit())?; Ok(ExecutedAsyncStatement::new(exec, runtime)) } @@ -137,12 +128,6 @@ impl ExecutedStatement { }), } } - - fn alive_mut(&mut self) -> PyResult<&mut ExecutedInner> { - self.inner - .as_mut() - .ok_or_else(|| crate::errors::KernelError::new_err("ExecutedStatement is closed")) - } } #[pymethods] @@ -161,14 +146,15 @@ impl ExecutedStatement { /// Pull the next batch as a `pyarrow.RecordBatch`, or `None` if /// the stream is exhausted. fn fetch_next_batch<'py>(&mut self, py: Python<'py>) -> PyResult>> { - let inner = self.alive_mut()?; + let inner = alive_mut!(self, "ExecutedStatement"); if inner.exhausted { return Ok(None); } let runtime = inner.runtime.clone(); - let batch = py - .detach(|| fetch::next_batch(&runtime, inner.exec.result_stream_mut())) - .map_err(|e| to_py_err(py, e))?; + let batch = run_sync_kernel!( + py, + fetch::next_batch(&runtime, inner.exec.result_stream_mut()) + )?; match batch { Some(b) => Ok(Some(b.to_pyarrow(py)?)), None => { @@ -180,11 +166,9 @@ impl ExecutedStatement { /// Drain the full result and return a single `pyarrow.Table`. fn fetch_all_arrow<'py>(&mut self, py: Python<'py>) -> PyResult> { - let inner = self.alive_mut()?; + let inner = alive_mut!(self, "ExecutedStatement"); let runtime = inner.runtime.clone(); - let batches = py - .detach(|| fetch::drain(&runtime, inner.exec.result_stream_mut())) - .map_err(|e| to_py_err(py, e))?; + let batches = run_sync_kernel!(py, fetch::drain(&runtime, inner.exec.result_stream_mut()))?; inner.exhausted = true; fetch::batches_to_pyarrow_table(py, &self.schema, batches) } @@ -193,10 +177,10 @@ impl ExecutedStatement { /// flag short-circuits if the parent `Statement` was re-executed /// or dropped. fn cancel(&mut self, py: Python<'_>) -> PyResult<()> { - let inner = self.alive_mut()?; + let inner = alive_mut!(self, "ExecutedStatement"); let runtime = inner.runtime.clone(); - let res = py.detach(|| runtime.block_on(inner.exec.cancel())); - res.map_err(|e| to_py_err(py, e)) + run_kernel!(py, runtime, inner.exec.cancel())?; + Ok(()) } /// Close the statement (server-side `CloseStatement`). Idempotent. @@ -206,12 +190,12 @@ impl ExecutedStatement { return Ok(()); }; let runtime = inner.runtime.clone(); - let res = py.detach(|| runtime.block_on(inner.exec.close())); + let res = run_kernel!(py, runtime, inner.exec.close()); // Drop the kernel handle regardless of close() outcome — the // kernel's Drop impl runs fire-and-forget cleanup if close() // failed mid-flight. self.inner = None; - res.map_err(|e| to_py_err(py, e)) + res.map(|_| ()) } fn __repr__(&self) -> String { diff --git a/pyo3/tests/conftest.py b/pyo3/tests/conftest.py new file mode 100644 index 00000000..d59d5743 --- /dev/null +++ b/pyo3/tests/conftest.py @@ -0,0 +1,76 @@ +# Copyright (c) 2026 Databricks, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Shared pytest fixtures + env-var gating for the PyO3 live tests. + +Run with creds sourced: + + cd pyo3 + .venv/bin/maturin develop --release + set -a && source ~/.databricks/pecotesting-creds && set +a + .venv/bin/pytest -v + +Tests that need a live warehouse are auto-skipped when the env vars +aren't set, so `pytest` works in CI / offline too — only the +no-network tests run. +""" + +from __future__ import annotations + +import os + +import pytest + +import databricks_sql_kernel as k + + +HOST = os.environ.get("DATABRICKS_HOST", "") +HTTP_PATH = os.environ.get("DATABRICKS_HTTP_PATH", "") +TOKEN = os.environ.get("DATABRICKS_TOKEN", "") + +live = pytest.mark.skipif( + not (HOST and HTTP_PATH and TOKEN), + reason="DATABRICKS_HOST / DATABRICKS_HTTP_PATH / DATABRICKS_TOKEN not set", +) + + +@pytest.fixture(scope="module") +def session(): + """Open one session per test module. Closed at module teardown. + + Module-scoped because every session round-trip creates a SEA + session on the warehouse; sharing across tests cuts E2E time by + a factor that matters for human-driven runs. + """ + if not (HOST and HTTP_PATH and TOKEN): + pytest.skip("creds not set") + s = k.Session(host=HOST, http_path=HTTP_PATH, access_token=TOKEN) + yield s + s.close() + + +@pytest.fixture +def fresh_session(): + """One-shot session for tests that need clean state (e.g. + use-after-close tests where the module-scoped fixture would + poison every later test).""" + if not (HOST and HTTP_PATH and TOKEN): + pytest.skip("creds not set") + s = k.Session(host=HOST, http_path=HTTP_PATH, access_token=TOKEN) + yield s + try: + s.close() + except k.KernelError: + # Test may have closed it already; idempotent close is fine. + pass diff --git a/pyo3/tests/test_async.py b/pyo3/tests/test_async.py new file mode 100644 index 00000000..e793e0de --- /dev/null +++ b/pyo3/tests/test_async.py @@ -0,0 +1,116 @@ +# Copyright (c) 2026 Databricks, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Async statement: submit / status / await_result / fetch_result / +Failed status.""" + +from __future__ import annotations + +import time + +import databricks_sql_kernel as k + +from conftest import live + + +def _wait_terminal(async_exec, timeout_s: float = 2.0): + """Poll status() until terminal or timeout. Returns the final + (state, failure) tuple.""" + deadline = time.monotonic() + timeout_s + while True: + state, failure = async_exec.status() + if state in ("Succeeded", "Closed", "Failed", "Cancelled"): + return state, failure + if time.monotonic() > deadline: + return state, failure + time.sleep(0.1) + + +@live +def test_submit_and_await_result(session): + stmt = session.statement() + stmt.set_sql("SELECT 7 AS n") + async_exec = stmt.submit() + try: + assert async_exec.statement_id + state, failure = async_exec.status() + assert state in ("Pending", "Running", "Succeeded", "Closed"), state + assert failure is None + rs = async_exec.await_result() + try: + table = rs.fetch_all_arrow() + assert table.num_rows == 1 + assert table.column(0).to_pylist() == [7] + finally: + rs.close() + # After await_result, status must be terminal. + state, _ = async_exec.status() + assert state in ("Succeeded", "Closed"), state + finally: + async_exec.close() + stmt.close() + + +@live +def test_submit_then_fetch_result_after_terminal(session): + stmt = session.statement() + stmt.set_sql("SELECT 99 AS n") + async_exec = stmt.submit() + try: + state, _ = _wait_terminal(async_exec) + assert state in ("Succeeded", "Closed"), state + rs = async_exec.fetch_result() + try: + table = rs.fetch_all_arrow() + assert table.num_rows == 1 + assert table.column(0).to_pylist() == [99] + finally: + rs.close() + finally: + async_exec.close() + stmt.close() + + +@live +def test_submit_failed_status_carries_kernel_error(session): + stmt = session.statement() + stmt.set_sql("SELECT * FROM definitely_not_a_table_xyz_async_test") + async_exec = stmt.submit() + try: + state, failure = _wait_terminal(async_exec) + assert state == "Failed", state + assert isinstance(failure, k.KernelError), type(failure) + assert failure.code == "SqlError", failure.code + assert failure.sql_state == "42P01", failure.sql_state + assert failure.query_id, "query_id should be populated" + finally: + async_exec.close() + stmt.close() + + +@live +def test_use_after_close_raises_kernel_error(session): + stmt = session.statement() + stmt.set_sql("SELECT 1") + async_exec = stmt.submit() + async_exec.close() + async_exec.close() # idempotent + try: + async_exec.status() + except k.KernelError as e: + assert "closed" in str(e), str(e) + assert e.code == "InvalidStatementHandle", e.code + else: + raise AssertionError("expected KernelError on use-after-close") + stmt.close() diff --git a/pyo3/tests/test_auth.py b/pyo3/tests/test_auth.py new file mode 100644 index 00000000..7e00e408 --- /dev/null +++ b/pyo3/tests/test_auth.py @@ -0,0 +1,119 @@ +# Copyright (c) 2026 Databricks, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Auth surface: input validation + External-callback trampoline. + +The trampoline itself (Python -> Rust -> kernel `TokenProvider`) is +covered by Rust unit tests in `pyo3/src/auth.rs`. These tests cover +the Python-visible surface: kwargs accepted / rejected, and that +`auth_type='external'` reaches the kernel (which today rejects the +variant — see the known-limitation note on the PR). +""" + +from __future__ import annotations + +import os + +import pytest + +import databricks_sql_kernel as k + + +HOST = os.environ.get("DATABRICKS_HOST", "") +HTTP_PATH = os.environ.get("DATABRICKS_HTTP_PATH", "") +TOKEN = os.environ.get("DATABRICKS_TOKEN", "") + + +# Input-validation tests don't need creds — they fail before we +# build a runtime / hit the wire. + +def test_missing_auth_raises_value_error(): + with pytest.raises(ValueError, match="auth"): + k.Session(host="x.databricks.com", http_path="/sql/1.0/warehouses/abc") + + +def test_external_without_callback_raises_value_error(): + with pytest.raises(ValueError, match="token_callback"): + k.Session( + host="x.databricks.com", + http_path="/sql/1.0/warehouses/abc", + auth_type="external", + ) + + +def test_external_with_non_callable_raises_value_error(): + with pytest.raises(ValueError, match="callable"): + k.Session( + host="x.databricks.com", + http_path="/sql/1.0/warehouses/abc", + auth_type="external", + token_callback="not-callable", + ) + + +def test_pat_with_empty_token_raises_value_error(): + with pytest.raises(ValueError, match="access_token"): + k.Session( + host="x.databricks.com", + http_path="/sql/1.0/warehouses/abc", + auth_type="pat", + access_token="", + ) + + +def test_unknown_auth_type_raises_value_error(): + with pytest.raises(ValueError, match="unknown auth_type"): + k.Session( + host="x.databricks.com", + http_path="/sql/1.0/warehouses/abc", + auth_type="something-else", + access_token="x", + ) + + +# The end-to-end-with-callback test does need creds because it +# actually tries to open a session (which today the kernel rejects +# at the External arm of build_auth_provider). The kernel-side +# follow-up will flip this from "expected InvalidArgument" to +# "expected success." +@pytest.mark.skipif( + not (HOST and HTTP_PATH and TOKEN), + reason="DATABRICKS_HOST / DATABRICKS_HTTP_PATH / DATABRICKS_TOKEN not set", +) +def test_external_reaches_kernel_today(): + """The kernel currently rejects AuthConfig::External at + build_auth_provider. This test pins that behavior so the + kernel-side follow-up PR will flip a clear assertion when it + enables the variant.""" + + def callback(): + return TOKEN + + try: + k.Session( + host=HOST, + http_path=HTTP_PATH, + auth_type="external", + token_callback=callback, + ) + except k.KernelError as e: + assert e.code == "InvalidArgument", e.code + assert "External" in e.message, e.message + else: + # If this branch ever executes, the kernel-side PR has + # landed — update this test to assert success instead. + raise AssertionError( + "Session(auth_type='external') succeeded — the kernel " + "has wired AuthConfig::External. Update this test." + ) diff --git a/pyo3/tests/test_execute.py b/pyo3/tests/test_execute.py new file mode 100644 index 00000000..59d8d9eb --- /dev/null +++ b/pyo3/tests/test_execute.py @@ -0,0 +1,102 @@ +# Copyright (c) 2026 Databricks, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Sync execute: SELECT 1, drain ranges, idempotent close, bad SQL.""" + +from __future__ import annotations + +import pyarrow as pa + +import databricks_sql_kernel as k + +from conftest import live + + +@live +def test_select_one_via_fetch_next_batch(session): + stmt = session.statement() + stmt.set_sql("SELECT 1 AS n") + exec_ = stmt.execute() + try: + assert exec_.statement_id + schema = exec_.arrow_schema() + assert isinstance(schema, pa.Schema) + batch = exec_.fetch_next_batch() + assert isinstance(batch, pa.RecordBatch) + assert batch.num_rows == 1 + assert batch.column(0).to_pylist() == [1] + # Second fetch is None — stream exhausted. + assert exec_.fetch_next_batch() is None + finally: + exec_.close() + stmt.close() + + +@live +def test_range_drains_to_pyarrow_table(session): + stmt = session.statement() + stmt.set_sql("SELECT * FROM range(10000)") + exec_ = stmt.execute() + try: + table = exec_.fetch_all_arrow() + assert isinstance(table, pa.Table) + assert table.num_rows == 10000 + finally: + exec_.close() + stmt.close() + + +@live +def test_executed_statement_double_close_is_idempotent(session): + stmt = session.statement() + stmt.set_sql("SELECT 42") + exec_ = stmt.execute() + exec_.close() + exec_.close() # idempotent + stmt.close() + + +@live +def test_use_after_close_raises_kernel_error(session): + stmt = session.statement() + stmt.set_sql("SELECT 42") + exec_ = stmt.execute() + exec_.close() + try: + exec_.fetch_next_batch() + except k.KernelError as e: + assert "closed" in str(e), str(e) + assert e.code == "InvalidStatementHandle", e.code + else: + raise AssertionError("expected KernelError on use-after-close") + stmt.close() + + +@live +def test_bad_sql_surfaces_structured_kernel_error(session): + stmt = session.statement() + stmt.set_sql("SELECT * FROM definitely_not_a_table_xyz_kernel_test") + try: + stmt.execute() + except k.KernelError as e: + assert e.code == "SqlError", f"got {e.code!r}" + assert e.sql_state == "42P01", f"got {e.sql_state!r}" + # query_id is server-issued and may or may not be populated + # depending on when the failure surfaced; assert only that + # the attribute exists. + assert hasattr(e, "query_id") + else: + raise AssertionError("expected KernelError on bad SQL") + finally: + stmt.close() diff --git a/pyo3/tests/test_metadata.py b/pyo3/tests/test_metadata.py new file mode 100644 index 00000000..deaa00ce --- /dev/null +++ b/pyo3/tests/test_metadata.py @@ -0,0 +1,130 @@ +# Copyright (c) 2026 Databricks, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Metadata surface: list_*, type_info, table_types, validation, +ResultStream lifecycle.""" + +from __future__ import annotations + +import pyarrow as pa +import pytest + +import databricks_sql_kernel as k + +from conftest import live + + +@live +def test_list_catalogs_returns_non_empty(session): + rs = session.metadata().list_catalogs() + try: + assert isinstance(rs.arrow_schema(), pa.Schema) + table = rs.fetch_all_arrow() + assert isinstance(table, pa.Table) + assert table.num_rows > 0 + finally: + rs.close() + + +@live +def test_list_schemas_in_main_catalog(session): + rs = session.metadata().list_schemas(catalog="main") + try: + table = rs.fetch_all_arrow() + assert table.num_rows > 0 + finally: + rs.close() + + +@live +def test_list_tables_in_information_schema(session): + rs = session.metadata().list_tables( + catalog="system", schema_pattern="information_schema" + ) + try: + table = rs.fetch_all_arrow() + assert table.num_rows > 0 + # Server-shape sanity: the columns should match the kernel's + # documented `SHOW TABLES` server-shape. + col_names = [f.name for f in table.schema] + for required in ("tableName", "tableType"): + assert required in col_names, f"missing column {required!r}: {col_names}" + finally: + rs.close() + + +@live +def test_list_columns_in_tables(session): + rs = session.metadata().list_columns( + catalog="system", + schema_pattern="information_schema", + table_pattern="tables", + ) + try: + table = rs.fetch_all_arrow() + assert table.num_rows > 0 + finally: + rs.close() + + +@live +def test_type_info_is_static(session): + rs = session.metadata().type_info() + try: + table = rs.fetch_all_arrow() + assert table.num_rows > 0 + finally: + rs.close() + + +@live +def test_table_types_is_static(session): + rs = session.metadata().table_types() + try: + table = rs.fetch_all_arrow() + assert table.num_rows > 0 + finally: + rs.close() + + +@live +def test_empty_identifier_rejected(session): + try: + session.metadata().list_schemas(catalog="") + except k.KernelError as e: + assert e.code == "InvalidArgument", e.code + assert "identifier" in e.message.lower(), e.message + else: + raise AssertionError("expected KernelError for empty catalog") + + +@live +def test_list_columns_requires_catalog_kwarg(session): + # `catalog` is a kwarg-only required parameter (no default). + with pytest.raises(TypeError): + session.metadata().list_columns(schema_pattern="x") # type: ignore[call-arg] + + +@live +def test_result_stream_idempotent_close(session): + rs = session.metadata().list_catalogs() + rs.close() + rs.close() # idempotent + try: + rs.fetch_next_batch() + except k.KernelError as e: + assert "closed" in str(e), str(e) + assert e.code == "InvalidStatementHandle", e.code + else: + raise AssertionError("expected KernelError on use-after-close ResultStream") diff --git a/pyo3/tests/test_module.py b/pyo3/tests/test_module.py new file mode 100644 index 00000000..93f79a55 --- /dev/null +++ b/pyo3/tests/test_module.py @@ -0,0 +1,38 @@ +# Copyright (c) 2026 Databricks, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Module-level sanity: import, version, exported classes.""" + +from __future__ import annotations + +import databricks_sql_kernel as k + + +def test_version_string(): + assert isinstance(k.__version__, str) + assert k.__version__ + + +def test_exports_expected_classes(): + expected = { + "Session", + "Statement", + "ExecutedStatement", + "ExecutedAsyncStatement", + "Metadata", + "ResultStream", + "KernelError", + } + actual = {n for n in dir(k) if not n.startswith("_")} + assert expected.issubset(actual), f"missing exports: {expected - actual}" diff --git a/pyo3/tests/test_session.py b/pyo3/tests/test_session.py new file mode 100644 index 00000000..84d8c95b --- /dev/null +++ b/pyo3/tests/test_session.py @@ -0,0 +1,54 @@ +# Copyright (c) 2026 Databricks, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Session lifecycle: open, session_id, repr, idempotent close, +use-after-close.""" + +from __future__ import annotations + +import databricks_sql_kernel as k + +from conftest import live + + +@live +def test_session_id_non_empty(session): + assert session.session_id, f"session_id should be populated: {session.session_id!r}" + + +@live +def test_session_repr_open(session): + text = repr(session) + assert "Session" in text + assert "closed=False" in text + assert session.session_id in text + + +@live +def test_double_close_is_idempotent(fresh_session): + fresh_session.close() + # Second call must not raise. + fresh_session.close() + + +@live +def test_use_after_close_raises_kernel_error(fresh_session): + fresh_session.close() + try: + fresh_session.statement() + except k.KernelError as e: + assert "closed" in str(e), str(e) + assert e.code == "InvalidStatementHandle", e.code + else: + raise AssertionError("expected KernelError on use-after-close") From b60166acf9d85ab0efe050fd35c68651646c5e69 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Thu, 14 May 2026 12:36:35 +0000 Subject: [PATCH 6/9] feat(pyo3): wire session_conf through Session(...) to the kernel Folds in the small kernel-side gap noticed during Phase 2 planning. The kernel's SessionBuilder already exposes `.session_conf(HashMap< String, String>)` and serialises it as SEA `session_configuration` on CreateSession; the PyO3 wrapper just wasn't passing it. New kwarg on Session.__new__: k.Session(host=..., http_path=..., access_token=..., session_conf={"ANSI_MODE": "false", ...}) The connector backend uses this to pipe its `session_configuration` dict through to the kernel. SEA enforces an allow-list (ANSI_MODE, USE_CACHED_RESULT, STATEMENT_TIMEOUT, QUERY_TAGS, etc.); the kernel passes the map through verbatim, the server applies what it accepts and errors on the rest. Live test added: `test_session_conf_round_trips` sets `ANSI_MODE=false` and verifies `SET ANSI_MODE` returns `false`, proving the map reached the server and was honoured. (`ANSI_MODE` was chosen after sanity-testing because `TIMEZONE` is rejected by this warehouse as "Unsupported configuration" and `USE_CACHED_RESULT` / `STATEMENT_TIMEOUT` are workspace-policy- clamped.) All 31 pytests pass; cargo clippy/fmt/test green. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- pyo3/src/session.rs | 24 +++++++++++++++++++++++- pyo3/tests/test_session.py | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index cafc24a2..e513c3a7 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -25,6 +25,7 @@ use crate::metadata::Metadata; use crate::statement::Statement; use databricks_sql_kernel::Session as KSession; use pyo3::prelude::*; +use std::collections::HashMap; use std::sync::Arc; use tokio::runtime::{Builder, Runtime}; @@ -72,8 +73,25 @@ impl Session { /// /// Omitting `auth_type` is equivalent to `"pat"` for backward /// compatibility with Phase-1 callers that only had PAT. + /// + /// `session_conf` is the server-bound session configuration map + /// — passed through to SEA `session_confs` verbatim. Use for + /// `ANSI_MODE`, `TIMEZONE`, `STATEMENT_TIMEOUT`, query-tag + /// presets, etc. The kernel does not validate keys; the server + /// rejects unknown ones with a `KernelError(code='SqlError')` + /// when it picks them up. #[new] - #[pyo3(signature = (host, http_path, *, auth_type=None, access_token=None, token_callback=None, catalog=None, schema=None))] + #[pyo3(signature = ( + host, + http_path, + *, + auth_type=None, + access_token=None, + token_callback=None, + catalog=None, + schema=None, + session_conf=None, + ))] #[allow(clippy::too_many_arguments)] fn new( py: Python<'_>, @@ -84,6 +102,7 @@ impl Session { token_callback: Option>, catalog: Option, schema: Option, + session_conf: Option>, ) -> PyResult { // Resolve auth_type: default to "pat" only when the caller // also passed access_token. This keeps existing PAT callers @@ -130,6 +149,9 @@ impl Session { defaults.schema = schema; builder = builder.defaults(defaults); } + if let Some(conf) = session_conf { + builder = builder.session_conf(conf); + } builder.open().await })?; diff --git a/pyo3/tests/test_session.py b/pyo3/tests/test_session.py index 84d8c95b..8a0c6dec 100644 --- a/pyo3/tests/test_session.py +++ b/pyo3/tests/test_session.py @@ -52,3 +52,38 @@ def test_use_after_close_raises_kernel_error(fresh_session): assert e.code == "InvalidStatementHandle", e.code else: raise AssertionError("expected KernelError on use-after-close") + + +@live +def test_session_conf_round_trips(): + """`session_conf` is passed through to SEA `session_configuration` + verbatim. Setting `ANSI_MODE=false` proves the map reached the + server and was honoured — `SET ANSI_MODE` reflects it back. + `ANSI_MODE` was chosen because it's on the allow-list this + warehouse accepts and round-trips cleanly (`TIMEZONE` is + rejected with "Unsupported configuration" on dogfood; + `USE_CACHED_RESULT` / `STATEMENT_TIMEOUT` are + workspace-policy-clamped).""" + import os + s = k.Session( + host=os.environ["DATABRICKS_HOST"], + http_path=os.environ["DATABRICKS_HTTP_PATH"], + access_token=os.environ["DATABRICKS_TOKEN"], + session_conf={"ANSI_MODE": "false"}, + ) + try: + stmt = s.statement() + stmt.set_sql("SET ANSI_MODE") + exec_ = stmt.execute() + try: + table = exec_.fetch_all_arrow() + # Server returns rows like (key='ANSI_MODE', value='false'). + row = {f.name: table.column(i).to_pylist()[0] for i, f in enumerate(table.schema)} + assert row.get("value") == "false", ( + f"server did not honour ANSI_MODE=false; got row {row!r}" + ) + finally: + exec_.close() + stmt.close() + finally: + s.close() From 4847a078336bb846487bcacecf080c0fc5c3d391 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Thu, 14 May 2026 15:31:23 +0000 Subject: [PATCH 7/9] refactor(pyo3): drop External auth, scope Phase 1 to PAT only MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit External auth (Python-callable TokenProvider trampoline) was Phase 1 step 5 of the integration plan. Removing it in favour of a smaller PAT-only surface for the first connector cutover; the OAuth question (kernel-owned OAuth vs connector-delegated tokens) gets revisited when there's actual demand on the kernel-backed code path. What's removed: - `auth.rs::PythonTokenProvider` and its 4 Rust unit tests. - The `token_callback` kwarg on `Session.__new__`. - The `extension-module` Cargo feature gymnastics (only existed to let cargo test link libpython for the trampoline unit tests — no Rust unit tests remain in the pyo3 crate, so the feature is back to always-on, matching the original Phase 1 setup). - The `async-trait` dependency (only the trampoline used it). - Smoke and pytest cases that exercised External end-to-end. What stays: - PAT path: unchanged. - All other Phase 1 surface (Statement / Metadata / ExecutedAsyncStatement / ResultStream / KernelError) unchanged. Surface today on `Session.__new__`: k.Session( host=..., http_path=..., access_token="dapi...", # or auth_type='pat', access_token=... catalog=..., schema=..., session_conf={...}, ) Anything else for `auth_type` raises ValueError ("unsupported auth_type 'X'; only 'pat' is supported today"), surfacing at construction time, not deep in HTTP retry. Verified: - cargo build --workspace - cargo clippy --workspace --all-targets -- -D warnings - cargo +stable fmt --all -- --check - 29 pyo3/tests pytests pass against dogfood. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- Cargo.lock | 1 - pyo3/Cargo.toml | 15 +-- pyo3/pyproject.toml | 2 +- pyo3/src/auth.rs | 197 ++++------------------------------------ pyo3/src/lib.rs | 13 +-- pyo3/src/session.rs | 31 ++----- pyo3/tests/test_auth.py | 84 +++-------------- 7 files changed, 47 insertions(+), 296 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5e2b469a..353520e1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -385,7 +385,6 @@ dependencies = [ "arrow-array", "arrow-pyarrow", "arrow-schema", - "async-trait", "databricks-sql-kernel", "pyo3", "tokio", diff --git a/pyo3/Cargo.toml b/pyo3/Cargo.toml index f59fc8be..ebd3cfbf 100644 --- a/pyo3/Cargo.toml +++ b/pyo3/Cargo.toml @@ -36,13 +36,7 @@ crate-type = ["cdylib"] databricks-sql-kernel = { path = ".." } # pyo3 — abi3-py39 lets one wheel cover Python 3.9+. -# -# `extension-module` is gated behind a Cargo feature so that -# `cargo test -p databricks-sql-kernel-pyo3` can build a normal -# binary that links against libpython (needed to run unit tests -# that call `Python::attach`). Maturin enables the feature via -# pyproject.toml when building the wheel. -pyo3 = { version = "0.26", features = ["abi3-py39"] } +pyo3 = { version = "0.26", features = ["extension-module", "abi3-py39"] } # Multi-thread runtime — one per Session, owned on the Rust side. tokio = { version = "1", features = ["rt-multi-thread"] } @@ -52,10 +46,3 @@ tokio = { version = "1", features = ["rt-multi-thread"] } arrow-array = "57" arrow-schema = "57" arrow-pyarrow = "57" - -# Required to implement the kernel's #[async_trait] TokenProvider on -# the Python-callable trampoline used by AuthConfig::External. -async-trait = "0.1" - -[features] -extension-module = ["pyo3/extension-module"] diff --git a/pyo3/pyproject.toml b/pyo3/pyproject.toml index 3d9e7663..46c8cb49 100644 --- a/pyo3/pyproject.toml +++ b/pyo3/pyproject.toml @@ -13,4 +13,4 @@ dependencies = ["pyarrow>=14"] [tool.maturin] module-name = "databricks_sql_kernel" -features = ["extension-module"] + diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index e410568b..f8ebc1b2 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -12,85 +12,31 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Translation from Python auth kwargs to a kernel `AuthConfig`. +//! Translate Python auth kwargs into a kernel `AuthConfig`. //! -//! Phase-1 surface covers PAT (Step 1) and `External` (this step). -//! `External` lets the connector keep ownership of its own OAuth / -//! MSAL / federation flows: it passes a Python callable that returns -//! a fresh bearer token, and the kernel calls it whenever it needs -//! one. -//! -//! Future steps add the kernel-driven OAuth variants -//! (`AuthConfig::OAuthM2M`, `OAuthU2M`, `OAuthFederation`) — useful -//! for callers that want the kernel to own the flow rather than -//! delegating back to Python. - -use async_trait::async_trait; -use databricks_sql_kernel::config::TokenProvider; -use databricks_sql_kernel::{AuthConfig, Error, Result as KResult}; +//! Phase 1 ships PAT only. The kernel surface reserves +//! `AuthConfig::OAuthM2M`, `OAuthU2M`, `OAuthFederation`, and +//! `External`; wiring any of them into the Python wrapper needs a +//! deliberate design decision about credential ownership (does +//! PySQL own OAuth and feed tokens to the kernel, or does the +//! kernel run its own browser flow?). Until that's settled, the +//! connector backend raises `NotSupportedError` for non-PAT auth +//! and the wrapper rejects unknown `auth_type` values here so the +//! mistake surfaces at construction time, not deep inside an HTTP +//! retry loop. + +use databricks_sql_kernel::AuthConfig; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; -/// A `TokenProvider` that delegates to a Python callable. The -/// callable is invoked once per HTTP request that needs auth, with -/// the GIL re-acquired on the calling tokio worker thread. -/// -/// `Py` is `Send + Sync` in pyo3 (it's a reference-counted -/// pointer into the Python heap, not a borrow), so this struct -/// satisfies the kernel's `TokenProvider: Send + Sync` bound. -struct PythonTokenProvider { - callback: Py, -} - -impl PythonTokenProvider { - fn new(callback: Py) -> Self { - Self { callback } - } -} - -#[async_trait] -impl TokenProvider for PythonTokenProvider { - async fn token(&self) -> KResult { - // The kernel calls us from a tokio worker without the GIL. - // Acquire it for the duration of one Python call, extract - // the result as a String, then drop the GIL again before - // returning the future to the kernel. - // - // Note: this is a *sync* GIL-held call to the user's Python - // callable. For typical auth providers (in-process token - // cache lookup, occasional refresh) this is fine and matches - // the connector's own auth-provider contract. If a wrapper - // ever needs to await Python coroutines here, the pattern - // is to make the callback return a token directly and own - // the async work itself. - Python::attach(|py| { - let result = self.callback.call0(py).map_err(|e| { - Error::unauthenticated().message(format!("Python token_callback raised: {e}")) - })?; - let token: String = result.extract(py).map_err(|e| { - Error::unauthenticated() - .message(format!("Python token_callback must return str: {e}")) - })?; - if token.is_empty() { - return Err(Error::unauthenticated() - .message("Python token_callback returned an empty string")); - } - Ok(token) - }) - } -} - /// Build a kernel `AuthConfig` from the Python kwargs the `Session` -/// constructor accepts. Centralised here so the auth-kwarg surface -/// stays in one place. +/// constructor accepts. /// -/// `auth_type` is one of: -/// - `"pat"` — requires `access_token: str`. -/// - `"external"` — requires `token_callback: Callable[[], str]`. +/// `auth_type` is currently restricted to `"pat"`. Additional +/// variants land when the OAuth ownership question is resolved. pub(crate) fn build_auth_config( auth_type: &str, access_token: Option, - token_callback: Option>, ) -> PyResult { match auth_type { "pat" => { @@ -101,117 +47,8 @@ pub(crate) fn build_auth_config( } Ok(AuthConfig::Pat { token }) } - "external" => { - let callback = token_callback.ok_or_else(|| { - PyValueError::new_err( - "auth_type='external' requires token_callback (a no-arg callable returning str)", - ) - })?; - // Sanity check at construction time so a misspelled or - // non-callable arg surfaces immediately rather than on - // the first HTTP request. - Python::attach(|py| -> PyResult<()> { - if !callback.bind(py).is_callable() { - return Err(PyValueError::new_err("token_callback must be callable")); - } - Ok(()) - })?; - Ok(AuthConfig::External(Box::new(PythonTokenProvider::new( - callback, - )))) - } other => Err(PyValueError::new_err(format!( - "unknown auth_type {other:?}; expected one of: pat, external" + "unsupported auth_type {other:?}; only 'pat' is supported today" ))), } } - -#[cfg(test)] -mod tests { - //! End-to-end coverage for the Python→Rust→kernel auth bridge. - //! - //! These tests exercise the `TokenProvider` trampoline without - //! needing a live workspace — we construct a `PythonTokenProvider` - //! directly, run its async `token()` method on a tokio runtime, - //! and check the value flows back correctly. This is the layer - //! the rest of Step 5 builds on; if it breaks we want to catch - //! it without spinning a Session against dogfood. - //! - //! `Python::initialize()` initialises the Python interpreter on - //! first call; subsequent calls are no-ops. - - use super::*; - use databricks_sql_kernel::ErrorCode; - use pyo3::ffi::c_str; - - fn rt() -> tokio::runtime::Runtime { - tokio::runtime::Builder::new_multi_thread() - .enable_all() - .build() - .unwrap() - } - - #[test] - fn python_token_provider_returns_callback_value() { - Python::initialize(); - let callback: Py = Python::attach(|py| { - py.eval(c_str!("lambda: 'token-xyz'"), None, None) - .unwrap() - .unbind() - }); - let provider = PythonTokenProvider::new(callback); - let got = rt().block_on(provider.token()).unwrap(); - assert_eq!(got, "token-xyz"); - } - - #[test] - fn python_token_provider_maps_python_exception_to_unauthenticated() { - Python::initialize(); - let callback: Py = Python::attach(|py| { - // Lambda raising RuntimeError. Done as exec+lookup so we - // can carry a statement (`raise ...`) instead of an - // expression. - let globals = pyo3::types::PyDict::new(py); - py.run( - c_str!("def cb():\n raise RuntimeError('simulated MSAL failure')\n"), - Some(&globals), - None, - ) - .unwrap(); - globals.get_item("cb").unwrap().unwrap().unbind() - }); - let provider = PythonTokenProvider::new(callback); - let err = rt().block_on(provider.token()).unwrap_err(); - assert_eq!(err.code, ErrorCode::Unauthenticated); - assert!( - err.message.contains("simulated MSAL failure"), - "message should preserve the Python exception text: {}", - err.message - ); - } - - #[test] - fn python_token_provider_rejects_non_string_return() { - Python::initialize(); - let callback: Py = Python::attach(|py| { - py.eval(c_str!("lambda: 12345"), None, None) - .unwrap() - .unbind() - }); - let provider = PythonTokenProvider::new(callback); - let err = rt().block_on(provider.token()).unwrap_err(); - assert_eq!(err.code, ErrorCode::Unauthenticated); - assert!(err.message.contains("must return str"), "{}", err.message); - } - - #[test] - fn python_token_provider_rejects_empty_string() { - Python::initialize(); - let callback: Py = - Python::attach(|py| py.eval(c_str!("lambda: ''"), None, None).unwrap().unbind()); - let provider = PythonTokenProvider::new(callback); - let err = rt().block_on(provider.token()).unwrap_err(); - assert_eq!(err.code, ErrorCode::Unauthenticated); - assert!(err.message.contains("empty"), "{}", err.message); - } -} diff --git a/pyo3/src/lib.rs b/pyo3/src/lib.rs index 2ef5b094..da96d941 100644 --- a/pyo3/src/lib.rs +++ b/pyo3/src/lib.rs @@ -15,12 +15,13 @@ //! Python bindings for the Databricks SQL Kernel. //! //! Phase 1 surface today: `Session`, `Statement`, `ExecutedStatement`, -//! `ExecutedAsyncStatement`, `Metadata`, `ResultStream`. Auth: PAT -//! plus `External` (Python-callable token provider — used by the -//! connector to delegate OAuth back to its own auth provider). -//! Both synchronous `execute()` and async `submit()` paths -//! supported. Built as the `databricks_sql_kernel` extension module -//! via `maturin develop` / `maturin build`. +//! `ExecutedAsyncStatement`, `Metadata`, `ResultStream`. Auth is +//! PAT-only — OAuth and other auth types are reserved in the kernel +//! surface but not yet wired here, pending a decision on whether +//! PySQL owns OAuth or the kernel does (see Phase 2 design notes). +//! Both synchronous `execute()` and async `submit()` paths supported. +//! Built as the `databricks_sql_kernel` extension module via +//! `maturin develop` / `maturin build`. //! //! The kernel's API is async — every method call from Python detaches //! the GIL and `block_on`s on the session-owned tokio runtime. diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index e513c3a7..6206e7c2 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -55,24 +55,11 @@ impl Session { /// fully-qualified (`https://...`). `http_path` is the SQL /// endpoint path. /// - /// Auth selection: - /// - /// - `auth_type="pat"` (default when `access_token` is provided): - /// `access_token` carries the bearer token. Kernel uses it - /// verbatim for every request. - /// - `auth_type="external"`: `token_callback` is a no-arg - /// Python callable that returns a fresh bearer token. The - /// kernel invokes it **once per HTTP request that needs - /// authentication**, so the callable MUST be cheap (in-process - /// cache lookup is the right pattern; a network round-trip - /// inside the callback will multiply request latency - /// noticeably under load). The callable owns its own caching - /// and refresh — the kernel does not cache the returned - /// token across calls. Use this to delegate OAuth / MSAL / - /// federation to the connector's existing auth provider. - /// - /// Omitting `auth_type` is equivalent to `"pat"` for backward - /// compatibility with Phase-1 callers that only had PAT. + /// Auth: PAT only in this phase. Pass `access_token=` + /// (or the explicit form `auth_type='pat', access_token=...`). + /// OAuth and other auth types are reserved and will be wired + /// in once the credential-ownership question (kernel-owned vs + /// connector-owned OAuth) is settled. /// /// `session_conf` is the server-bound session configuration map /// — passed through to SEA `session_confs` verbatim. Use for @@ -87,7 +74,6 @@ impl Session { *, auth_type=None, access_token=None, - token_callback=None, catalog=None, schema=None, session_conf=None, @@ -99,7 +85,6 @@ impl Session { http_path: String, auth_type: Option, access_token: Option, - token_callback: Option>, catalog: Option, schema: Option, session_conf: Option>, @@ -113,12 +98,12 @@ impl Session { None if access_token.is_some() => "pat".to_owned(), None => { return Err(pyo3::exceptions::PyValueError::new_err( - "Session requires auth: pass auth_type='pat' with access_token, \ - or auth_type='external' with token_callback", + "Session requires auth: pass access_token (PAT) — \ + other auth types are not yet supported by this binding", )); } }; - let auth_config = build_auth_config(&resolved_auth_type, access_token, token_callback)?; + let auth_config = build_auth_config(&resolved_auth_type, access_token)?; // One tokio runtime per session. Multi-thread so CloudFetch // chunk downloads can overlap with the main poll loop. Worker diff --git a/pyo3/tests/test_auth.py b/pyo3/tests/test_auth.py index 7e00e408..3e2cee99 100644 --- a/pyo3/tests/test_auth.py +++ b/pyo3/tests/test_auth.py @@ -12,108 +12,50 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Auth surface: input validation + External-callback trampoline. +"""Auth surface: input validation. -The trampoline itself (Python -> Rust -> kernel `TokenProvider`) is -covered by Rust unit tests in `pyo3/src/auth.rs`. These tests cover -the Python-visible surface: kwargs accepted / rejected, and that -`auth_type='external'` reaches the kernel (which today rejects the -variant — see the known-limitation note on the PR). +PAT-only this phase; tests confirm the wrapper rejects unsupported +kwargs at construction time (before any network) rather than +letting the kernel error mid-flight. """ from __future__ import annotations -import os - import pytest import databricks_sql_kernel as k -HOST = os.environ.get("DATABRICKS_HOST", "") -HTTP_PATH = os.environ.get("DATABRICKS_HTTP_PATH", "") -TOKEN = os.environ.get("DATABRICKS_TOKEN", "") - - -# Input-validation tests don't need creds — they fail before we -# build a runtime / hit the wire. - def test_missing_auth_raises_value_error(): - with pytest.raises(ValueError, match="auth"): + with pytest.raises(ValueError, match="access_token"): k.Session(host="x.databricks.com", http_path="/sql/1.0/warehouses/abc") -def test_external_without_callback_raises_value_error(): - with pytest.raises(ValueError, match="token_callback"): +def test_pat_with_empty_token_raises_value_error(): + with pytest.raises(ValueError, match="access_token"): k.Session( host="x.databricks.com", http_path="/sql/1.0/warehouses/abc", - auth_type="external", + auth_type="pat", + access_token="", ) -def test_external_with_non_callable_raises_value_error(): - with pytest.raises(ValueError, match="callable"): +def test_unsupported_auth_type_raises_value_error(): + with pytest.raises(ValueError, match="unsupported"): k.Session( host="x.databricks.com", http_path="/sql/1.0/warehouses/abc", auth_type="external", - token_callback="not-callable", - ) - - -def test_pat_with_empty_token_raises_value_error(): - with pytest.raises(ValueError, match="access_token"): - k.Session( - host="x.databricks.com", - http_path="/sql/1.0/warehouses/abc", - auth_type="pat", - access_token="", + access_token="x", ) def test_unknown_auth_type_raises_value_error(): - with pytest.raises(ValueError, match="unknown auth_type"): + with pytest.raises(ValueError, match="unsupported"): k.Session( host="x.databricks.com", http_path="/sql/1.0/warehouses/abc", auth_type="something-else", access_token="x", ) - - -# The end-to-end-with-callback test does need creds because it -# actually tries to open a session (which today the kernel rejects -# at the External arm of build_auth_provider). The kernel-side -# follow-up will flip this from "expected InvalidArgument" to -# "expected success." -@pytest.mark.skipif( - not (HOST and HTTP_PATH and TOKEN), - reason="DATABRICKS_HOST / DATABRICKS_HTTP_PATH / DATABRICKS_TOKEN not set", -) -def test_external_reaches_kernel_today(): - """The kernel currently rejects AuthConfig::External at - build_auth_provider. This test pins that behavior so the - kernel-side follow-up PR will flip a clear assertion when it - enables the variant.""" - - def callback(): - return TOKEN - - try: - k.Session( - host=HOST, - http_path=HTTP_PATH, - auth_type="external", - token_callback=callback, - ) - except k.KernelError as e: - assert e.code == "InvalidArgument", e.code - assert "External" in e.message, e.message - else: - # If this branch ever executes, the kernel-side PR has - # landed — update this test to assert success instead. - raise AssertionError( - "Session(auth_type='external') succeeded — the kernel " - "has wired AuthConfig::External. Update this test." - ) From da7a0c8503fab84bf59ae2a11587dc055be1d43a Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Thu, 14 May 2026 16:57:06 +0000 Subject: [PATCH 8/9] fix(pyo3): address review C1, C3 + expand Statement.close docstring MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit C1 — crate-type = ["cdylib", "rlib"]. Without rlib, future `#[cfg(test)]` modules in `pyo3/src/**` are silently invisible to `cargo test -p` ("running 0 tests / ok"). One-line fix; clippy stays green. C3 — `test_session_conf_round_trips` already had `@live` (from commit b60166a where the test was introduced), but the body read os.environ[...] directly which would KeyError if `@live` ever stopped matching. Switched to the same `HOST`/`HTTP_PATH`/ `TOKEN` module-level constants conftest defines. Robust to future refactors. Bonus — expanded the `Statement.close()` docstring to document that server-side cleanup is owned by `ExecutedStatement` / `ExecutedAsyncStatement` (each fires fire-and-forget `CloseStatement` from its own Drop). `Statement.close()` only drops the local lifecycle owner and flips the validity flag; any executed handle the caller still holds continues to work. Per the PR thread, C4 was already addressed in commit 4847a07 (async-trait dep was removed when External auth was dropped). C2 (PR description rewrite) follows in a description edit. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- pyo3/Cargo.toml | 7 ++++++- pyo3/src/statement.rs | 20 +++++++++++++++++--- pyo3/tests/test_session.py | 15 ++++++++++----- 3 files changed, 33 insertions(+), 9 deletions(-) diff --git a/pyo3/Cargo.toml b/pyo3/Cargo.toml index ebd3cfbf..e9e830d8 100644 --- a/pyo3/Cargo.toml +++ b/pyo3/Cargo.toml @@ -28,9 +28,14 @@ repository = "https://github.com/databricks/databricks-sql-kernel" # symbol from the `#[pymodule]` function name (not this `[lib].name`). # Picking a distinct name avoids colliding with the kernel root crate's # own cdylib output. +# +# `rlib` is included so `cargo test -p databricks-sql-kernel-pyo3` +# can pick up future `#[cfg(test)]` modules in `src/**`. With only +# `cdylib`, cargo silently reports "running 0 tests / ok" even if a +# `#[test]` exists — a real footgun for any later Rust-side test. [lib] name = "databricks_sql_kernel_pyo3" -crate-type = ["cdylib"] +crate-type = ["cdylib", "rlib"] [dependencies] databricks-sql-kernel = { path = ".." } diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 484b1654..9162b03d 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -87,9 +87,23 @@ impl Statement { Ok(ExecutedAsyncStatement::new(exec, runtime)) } - /// Drop the statement. Any prior `ExecutedStatement` keeps - /// working — kernel-side it has its own validity flag and - /// statement_id and is independent of the `Statement` lifecycle. + /// Drop the statement lifecycle owner. + /// + /// **Server-side cleanup is owned by `ExecutedStatement` / + /// `ExecutedAsyncStatement`, not by `Statement`.** Each of + /// those handles fires a fire-and-forget `CloseStatement` from + /// its own `Drop` impl, and they hold their own + /// `Arc` so they outlive the parent `Statement` + /// cleanly. Calling `Statement.close()` here therefore does + /// **not** send any RPC — it only drops the local lifecycle + /// owner, which flips the validity flag on any executed handle + /// the caller has already abandoned so its eventual `Drop` + /// short-circuits cleanly. + /// + /// If the caller is still using an `ExecutedStatement` produced + /// by this `Statement`, that handle continues to work + /// unaffected. To release the server-side statement, call + /// `.close()` on the `ExecutedStatement` (or just let it Drop). fn close(&mut self) { self.inner = None; } diff --git a/pyo3/tests/test_session.py b/pyo3/tests/test_session.py index 8a0c6dec..4d27fdee 100644 --- a/pyo3/tests/test_session.py +++ b/pyo3/tests/test_session.py @@ -63,12 +63,17 @@ def test_session_conf_round_trips(): warehouse accepts and round-trips cleanly (`TIMEZONE` is rejected with "Unsupported configuration" on dogfood; `USE_CACHED_RESULT` / `STATEMENT_TIMEOUT` are - workspace-policy-clamped).""" - import os + workspace-policy-clamped). + """ + # Pull from the same module-level constants conftest defines so + # offline pytest runs short-circuit via @live before this body + # ever evaluates — no `os.environ[...]` KeyError hazard. + from conftest import HOST, HTTP_PATH, TOKEN + s = k.Session( - host=os.environ["DATABRICKS_HOST"], - http_path=os.environ["DATABRICKS_HTTP_PATH"], - access_token=os.environ["DATABRICKS_TOKEN"], + host=HOST, + http_path=HTTP_PATH, + access_token=TOKEN, session_conf={"ANSI_MODE": "false"}, ) try: From 7ffd2cb4848d40dcf530cc12fa36d7a36775b02f Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Fri, 15 May 2026 06:09:11 +0000 Subject: [PATCH 9/9] feat(kernel,pyo3): Statement::close() releases the held executed handle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reversing my earlier reply to the reviewer — option (a) is in fact the right call. The "rip exec_ out from under the caller" framing was a strawman: if a caller is still actively using exec_, they wouldn't be calling stmt.close() anyway. When they do call stmt.close(), they're explicitly opting out of further use — which is exactly what JDBC `Statement.close()`, ODBC `SQLFreeStmt(SQL_CLOSE)`, and PySQL `cursor.close()` users already expect. The kernel even had the underlying mechanism the whole time: invalidate_prior() is called by execute()/submit() before re-use, fires CancelStatement + CloseStatement against last_statement_id, and flips the validity flag. So Statement::close just needs to expose that capability as a public entry point. Kernel side: - New `Statement::close(mut self) -> Result<()>` (statement/mutable.rs) consumes self and routes to invalidate_prior. Symmetric with Session::close(self). - Wiremock test (`statement_close_cancels_and_closes_outstanding_ executed_handle`) confirms the held ExecutedStatement's next cancel/close call short-circuits with InvalidStatementHandle. PyO3 side: - Statement.close() rewritten from `self.inner = None` to drive the kernel's close() through run_kernel!. Idempotent (Option::take). - Docstring rewritten to match the new behavior — no more "doesn't send any RPC" claim. - Two new pytests: - `test_statement_close_invalidates_held_executed_statement`: proves cancel() on the held handle now errors with InvalidStatementHandle. Also documents the subtlety that already-buffered Arrow batches still drain locally (fetch_next_batch doesn't go through valid.check()) — same semantic as JDBC. - `test_statement_close_is_idempotent`: a second close() is a no-op. cargo build/clippy/fmt/test clean; 31/31 pyo3 pytests pass against dogfood. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- pyo3/src/statement.rs | 39 ++++++++++++++++++++--------------- pyo3/tests/test_execute.py | 40 ++++++++++++++++++++++++++++++++++++ src/statement/mutable.rs | 32 +++++++++++++++++++++++++++++ tests/v0_execute_wiremock.rs | 38 ++++++++++++++++++++++++++++++++++ 4 files changed, 132 insertions(+), 17 deletions(-) diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 9162b03d..f03de90a 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -87,25 +87,30 @@ impl Statement { Ok(ExecutedAsyncStatement::new(exec, runtime)) } - /// Drop the statement lifecycle owner. + /// Explicit close — cancels and closes any executed handle this + /// `Statement` is still tracking, then drops the lifecycle + /// owner. /// - /// **Server-side cleanup is owned by `ExecutedStatement` / - /// `ExecutedAsyncStatement`, not by `Statement`.** Each of - /// those handles fires a fire-and-forget `CloseStatement` from - /// its own `Drop` impl, and they hold their own - /// `Arc` so they outlive the parent `Statement` - /// cleanly. Calling `Statement.close()` here therefore does - /// **not** send any RPC — it only drops the local lifecycle - /// owner, which flips the validity flag on any executed handle - /// the caller has already abandoned so its eventual `Drop` - /// short-circuits cleanly. + /// Matches the surface JDBC / ODBC / PySQL users expect: + /// closing the lifecycle owner releases the associated + /// server-side statement too. Any `ExecutedStatement` / + /// `ExecutedAsyncStatement` the caller still holds becomes + /// invalid; its next call short-circuits locally to + /// `KernelError(code='InvalidStatementHandle')` without a + /// network round-trip. /// - /// If the caller is still using an `ExecutedStatement` produced - /// by this `Statement`, that handle continues to work - /// unaffected. To release the server-side statement, call - /// `.close()` on the `ExecutedStatement` (or just let it Drop). - fn close(&mut self) { - self.inner = None; + /// Idempotent — a second `close()` call is a no-op. + fn close(&mut self, py: Python<'_>) -> PyResult<()> { + let Some(inner) = self.inner.take() else { + return Ok(()); + }; + let StatementInner { stmt, runtime } = inner; + // Kernel `Statement::close` is async (it awaits + // CancelStatement + CloseStatement against the tracked + // executed handle), so we route it through the standard + // py.detach + block_on path. + run_kernel!(py, runtime, stmt.close())?; + Ok(()) } } diff --git a/pyo3/tests/test_execute.py b/pyo3/tests/test_execute.py index 59d8d9eb..4958d6d7 100644 --- a/pyo3/tests/test_execute.py +++ b/pyo3/tests/test_execute.py @@ -83,6 +83,46 @@ def test_use_after_close_raises_kernel_error(session): stmt.close() +@live +def test_statement_close_invalidates_held_executed_statement(session): + """`Statement.close()` is the user-facing "release everything" + operation. After calling it, the kernel sends `CloseStatement` + against the held executed handle and flips its local validity + flag; subsequent **wire-touching** calls on the handle (cancel) + short-circuit to `KernelError(code='InvalidStatementHandle')`. + + Note: already-buffered Arrow batches still drain locally — + `fetch_next_batch` doesn't go through the validity flag because + it operates on in-memory data the kernel already pulled. That + matches JDBC semantics: rows already in the client buffer + aren't unfetched by `close()`. The server-side state is what + actually gets released.""" + stmt = session.statement() + stmt.set_sql("SELECT 1 AS n") + exec_ = stmt.execute() + # Close the parent Statement while the user still holds exec_. + stmt.close() + # Cancel/close routes through `valid.check()` and now errors. + try: + exec_.cancel() + except k.KernelError as e: + assert e.code == "InvalidStatementHandle", e.code + else: + raise AssertionError( + "expected KernelError(InvalidStatementHandle) on cancel after Statement.close" + ) + + +@live +def test_statement_close_is_idempotent(session): + """A second `Statement.close()` is a no-op (does not error).""" + stmt = session.statement() + stmt.set_sql("SELECT 1") + stmt.execute().close() # close the executed handle ourselves + stmt.close() + stmt.close() # idempotent + + @live def test_bad_sql_surfaces_structured_kernel_error(session): stmt = session.statement() diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 68c18616..0bdd3107 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -189,6 +189,38 @@ impl Statement { )) } + /// Explicit close. Cancels and closes any executed handle this + /// `Statement` is still tracking, then drops the lifecycle + /// owner. Mirrors what users of JDBC `Statement.close()` / + /// ODBC `SQLFreeStmt(SQL_CLOSE)` / PySQL `cursor.close()` + /// already expect: closing the lifecycle owner releases the + /// associated server-side resources too. + /// + /// Implementation: just re-uses [`invalidate_prior`] which is + /// already what `execute()` / `submit()` call before re-use, + /// so the wire shape (CancelStatement + CloseStatement against + /// the tracked `last_statement_id`, validity flag flipped) is + /// identical to the auto-cancel-on-reuse path. Errors are + /// swallowed as `warn!` for the same reason as that path — + /// transient failures on a now-orphaned statement should not + /// surface as user-visible errors; the server reclaims on + /// session close anyway. + /// + /// After `close()`, any `ExecutedStatement` / + /// `ExecutedAsyncStatement` the caller still holds + /// short-circuits to `InvalidStatementHandle` locally on its + /// next call — no wire round-trip. + /// + /// Symmetric with [`Session::close`]: consumes `self` so a + /// double-close is a compile error. `Drop` runs as a fallback + /// for callers that forget to call `close()` explicitly, but + /// the explicit path is the supported one. + pub async fn close(mut self) -> Result<()> { + let _g = self.session.log_span().clone().entered(); + self.invalidate_prior().await; + Ok(()) + } + /// Shared spec-validation + `ExecuteParams` builder used by both /// [`execute`](Self::execute) and [`submit`](Self::submit). /// diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 0a452515..39de5ec2 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -443,6 +443,44 @@ async fn executed_close_is_idempotent() { exec.close().await.expect("second close — idempotent"); } +#[tokio::test] +async fn statement_close_cancels_and_closes_outstanding_executed_handle() { + // `Statement::close()` must cancel + close any executed handle + // the Statement is still tracking, so a JDBC / ODBC / PySQL- + // style "I'm done with this whole thing" call actually + // releases the server-side statement. Same wire shape as the + // auto-invalidate-on-reuse path that `execute()` / `submit()` + // run before re-issuing. + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/stmt-Z/cancel")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .mount(&server) + .await; + let batch = int64_batch("n", vec![1]); + mount_execute(&server, succeeded_inline_body("stmt-Z", &batch)).await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1"); + let exec = stmt.execute().await.expect("execute"); + assert_eq!(exec.statement_id(), "stmt-Z"); + + // Close the parent Statement (not the executed handle). The + // executed handle the caller still holds becomes invalid; its + // next call short-circuits locally via the validity flag. + stmt.close().await.expect("Statement::close"); + + let err = exec + .cancel() + .await + .expect_err("stale handle cancel after Statement::close must fail"); + assert_eq!(err.code, ErrorCode::InvalidStatementHandle); +} + #[tokio::test] async fn row_accessors_walk_succeeded_result() { let server = MockServer::start().await;