Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions pyo3/smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
184 changes: 184 additions & 0 deletions pyo3/src/executed_async.rs
Original file line number Diff line number Diff line change
@@ -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<ExecutedAsyncInner>,
/// Cached statement id so callers can read it after `close()`.
statement_id: String,
}

struct ExecutedAsyncInner {
exec: KExecutedAsyncStatement,
runtime: Arc<Runtime>,
}

impl ExecutedAsyncStatement {
pub(crate) fn new(exec: KExecutedAsyncStatement, runtime: Arc<Runtime>) -> 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<Bound<'py, PyAny>> {
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<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`.
let py_err = to_py_err(py, err.clone());
let args = py_err.value(py).getattr("args")?;
let tuple: Vec<Bound<'py, PyAny>> = 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<ResultStream> {
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<ResultStream> {
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
)
}
}
9 changes: 6 additions & 3 deletions pyo3/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -38,6 +40,7 @@ fn databricks_sql_kernel(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<session::Session>()?;
m.add_class::<statement::Statement>()?;
m.add_class::<statement::ExecutedStatement>()?;
m.add_class::<executed_async::ExecutedAsyncStatement>()?;
m.add_class::<metadata::Metadata>()?;
m.add_class::<result_stream::ResultStream>()?;
Ok(())
Expand Down
17 changes: 17 additions & 0 deletions pyo3/src/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<ExecutedAsyncStatement> {
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.
Expand Down