Skip to content
Merged
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
2 changes: 2 additions & 0 deletions .github/workflows/napi-checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ on:
branches: [main]
paths:
- "napi/**"
- "src/**"
# Root Cargo.toml change can affect napi via its `path = ".."`
# kernel dep, so this workflow re-runs to catch mismatches.
- "Cargo.toml"
Expand All @@ -40,6 +41,7 @@ on:
branches: [main]
paths:
- "napi/**"
- "src/**"
- "Cargo.toml"
- ".github/workflows/napi-checks.yml"

Expand Down
2 changes: 2 additions & 0 deletions .github/workflows/pyo3-checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,15 @@ on:
branches: [main]
paths:
- "pyo3/**"
- "src/**"
- "Cargo.toml"
- "Cargo.lock"
- ".github/workflows/pyo3-checks.yml"
pull_request:
branches: [main]
paths:
- "pyo3/**"
- "src/**"
- "Cargo.toml"
- "Cargo.lock"
- ".github/workflows/pyo3-checks.yml"
Expand Down
5 changes: 5 additions & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,13 @@ changes go in their respective binding's NEXT_CHANGELOG.

### Added

- `ExecutedAsyncStatement::reader()` creates independent read-only handles that retain session routing without owning cancellation, cleanup or execution telemetry.

### Changed

- SQL sessions open through the warehouse sessions URL and use warehouse statement URLs for owned statements when the create response enables real-time routing. Detached statement reads use standard SQL URLs. Lakehouse Real-Time supports asynchronous execution through the original session and statement handle; cross-session polling and fetching are not supported.
- Warehouse session requests carry parent IDs only in the URL. The Rust wire request structs now use `Option<String>` for `warehouse_id`; use `Some(id)` when building a standard SQL request body.

### Updated

### Fixed
Expand Down
2 changes: 1 addition & 1 deletion docs/designs/cloudfetch-implementation-plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ Implements `DatabricksClient` for the Databricks SQL Statement Execution API (RE

| Endpoint | Purpose |
|----------|---------|
| `POST /api/2.0/sql/sessions` | Create session |
| `POST /api/2.0/sql/warehouses/{warehouse_id}/sessions` | Create session |
| `DELETE /api/2.0/sql/sessions/{id}` | Delete session |
| `POST /api/2.0/sql/statements` | Execute statement |
| `GET /api/2.0/sql/statements/{id}` | Get status |
Expand Down
2 changes: 1 addition & 1 deletion napi/src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -706,7 +706,7 @@ mod tests {
async fn build_statement_forwards_raw_params_and_rejects_mixed_binding() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/2.0/sql/sessions"))
.and(path("/api/2.0/sql/warehouses/test_wh/sessions"))
.respond_with(
ResponseTemplate::new(200).set_body_json(json!({ "session_id": "sess-napi-raw" })),
)
Expand Down
2 changes: 1 addition & 1 deletion napi/src/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@ mod tests {

async fn open_mock_connection(server: &MockServer) -> Connection {
Mock::given(method("POST"))
.and(path("/api/2.0/sql/sessions"))
.and(path("/api/2.0/sql/warehouses/test_wh/sessions"))
.respond_with(
ResponseTemplate::new(200)
.set_body_json(json!({ "session_id": "sess-napi-metadata" })),
Expand Down
2 changes: 2 additions & 0 deletions pyo3/NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ changes go in the root `NEXT_CHANGELOG.md`.

### Added

- `ExecutedAsyncStatement.reader()` returns an independent `AsyncStatementReader` for status and result reads with the source handle's session routing.

### Changed

### Updated
Expand Down
72 changes: 56 additions & 16 deletions pyo3/src/executed_async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ use crate::errors::to_py_err;
use crate::result_stream::ResultStream;
use crate::runtime::KernelRuntime;
use databricks_sql_kernel::{
AsyncStatementReader as KAsyncStatementReader,
ExecutedAsyncStatement as KExecutedAsyncStatement, ExecutedStatementHandle, StatementStatus,
};
use pyo3::prelude::*;
Expand Down Expand Up @@ -58,6 +59,16 @@ impl ExecutedAsyncStatement {
&self.statement_id
}

/// Create an independent read-only handle retaining this statement's session routing.
/// The owning handle controls cancellation, cleanup and execution telemetry.
fn reader(&self, py: Python<'_>) -> PyResult<AsyncStatementReader> {
let inner = alive!(self, "ExecutedAsyncStatement");
Ok(AsyncStatementReader {
inner: inner.exec.reader().map_err(|error| to_py_err(py, error))?,
runtime: Arc::clone(&inner.runtime),
})
}

/// Single-shot status check. Returns a tuple
/// `(state: str, failure: Optional[KernelError])` where:
///
Expand All @@ -78,22 +89,7 @@ impl ExecutedAsyncStatement {
let inner = alive!(self, "ExecutedAsyncStatement");
let runtime = inner.runtime.clone();
let status = run_kernel!(py, runtime, inner.exec.status())?;
// String mapping lives on the kernel `StatementStatus::as_str`
// so all bindings share one taxonomy.
let state = status.as_str();
let failure: Bound<'py, PyAny> = match &status {
StatementStatus::Failed(err) => {
// 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());
py_err.value(py).clone().into_any()
}
_ => py.None().into_bound(py),
};
let tuple = pyo3::types::PyTuple::new(py, [state.into_pyobject(py)?.into_any(), failure])?;
Ok(tuple.into_any())
status_to_python(py, status)
}

/// Block until the statement reaches a terminal state, then
Expand Down Expand Up @@ -151,3 +147,47 @@ impl ExecutedAsyncStatement {
)
}
}

/// Independent status and result access without server lifecycle ownership.
#[pyclass(name = "AsyncStatementReader")]
pub(crate) struct AsyncStatementReader {
inner: KAsyncStatementReader,
runtime: Arc<KernelRuntime>,
}

#[pymethods]
impl AsyncStatementReader {
#[getter]
fn statement_id(&self) -> &str {
self.inner.statement_id()
}

/// Read server status as `(state, failure)`.
fn status<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
let status = run_kernel!(py, Arc::clone(&self.runtime), self.inner.status())?;
status_to_python(py, status)
}

/// Poll until terminal and return a fresh result stream. Interrupted reads do not cancel.
fn await_result(&self, py: Python<'_>) -> PyResult<ResultStream> {
let runtime = Arc::clone(&self.runtime);
let stream = run_kernel!(py, runtime, self.inner.await_result())?;
Ok(ResultStream::new(stream, runtime))
}

/// Return a fresh result stream; raises InvalidState if execution is not terminal.
fn fetch_result(&self, py: Python<'_>) -> PyResult<ResultStream> {
let runtime = Arc::clone(&self.runtime);
let stream = run_kernel!(py, runtime, self.inner.fetch_result())?;
Ok(ResultStream::new(stream, runtime))
}
}

fn status_to_python<'py>(py: Python<'py>, status: StatementStatus) -> PyResult<Bound<'py, PyAny>> {
let state = status.as_str();
let failure = match &status {
StatementStatus::Failed(err) => to_py_err(py, err.clone()).value(py).clone().into_any(),
_ => py.None().into_bound(py),
};
Ok(pyo3::types::PyTuple::new(py, [state.into_pyobject(py)?.into_any(), failure])?.into_any())
}
1 change: 1 addition & 0 deletions pyo3/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ fn databricks_sql_kernel(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<statement::ExecutedStatement>()?;
m.add_class::<statement::StatementCanceller>()?;
m.add_class::<executed_async::ExecutedAsyncStatement>()?;
m.add_class::<executed_async::AsyncStatementReader>()?;
m.add_class::<metadata::Metadata>()?;
m.add_class::<result_stream::ResultStream>()?;
m.add_function(wrap_pyfunction!(init_logging, m)?)?;
Expand Down
10 changes: 3 additions & 7 deletions pyo3/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -695,13 +695,9 @@ impl Session {

/// Re-attach to an already-submitted server statement by its id,
/// returning an `ExecutedAsyncStatement` the caller can poll
/// (`status()`), await (`await_result()`), or cancel/close — without
/// having been the handle that submitted it.
///
/// This is the resume path the connector uses for
/// `get_query_state` / `get_async_execution_result`: server
/// statement state is keyed solely by the id, so a caller holding
/// only the id can recover a working handle bound to this session.
/// (`status()`) or await (`await_result()`) without lifecycle ownership.
/// ID-only reads use standard SQL URLs. Use `ExecutedAsyncStatement.reader()`
/// to retain the originating session's routing for independent reads.
///
/// Issues one `GetStatementStatus` to seed the handle. Raises
/// `KernelError` with code `NotFound` if the server doesn't
Expand Down
135 changes: 135 additions & 0 deletions pyo3/tests/test_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,15 @@

from __future__ import annotations

import base64
import json
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

import databricks_sql_kernel as k
import pyarrow as pa
import pytest

from conftest import live

Expand Down Expand Up @@ -114,3 +120,132 @@ def test_use_after_close_raises_kernel_error(session):
else:
raise AssertionError("expected KernelError on use-after-close")
stmt.close()


@pytest.mark.parametrize("failed", [False, True], ids=["succeeded", "failed"])
def test_reader_preserves_session_and_maps_errors(failed):
requests = []
statement_path = "/api/2.0/sql/warehouses/test-wh/sessions/test-session/statements/test-statement"
response = {
"statement_id": "test-statement",
"status": {
"state": "FAILED",
"sql_state": "42P01",
"error": {"message": "invalid query", "error_code": "TABLE_OR_VIEW_NOT_FOUND"},
},
}
if not failed:
batch = pa.record_batch([pa.array([1, 2], type=pa.int64())], names=["n"])
buffer = pa.BufferOutputStream()
with pa.ipc.new_stream(buffer, batch.schema) as writer:
writer.write_batch(batch)
attachment = base64.b64encode(buffer.getvalue()).decode()
response = {
"statement_id": "test-statement",
"status": {"state": "SUCCEEDED"},
"manifest": {
"format": "ARROW_STREAM",
"schema": {
"column_count": 1,
"columns": [{"name": "n", "type_name": "BIGINT", "type_text": "BIGINT", "position": 0}],
},
"total_chunk_count": 1,
"total_row_count": 2,
},
"result": {"chunk_index": 0, "row_offset": 0, "row_count": 2, "attachment": attachment},
}

class Handler(BaseHTTPRequestHandler):
def respond(self, body, realtime=False):
requests.append((self.command, self.path))
self.rfile.read(int(self.headers.get("Content-Length", 0)))
payload = json.dumps(body).encode()
self.send_response(200)
self.send_header("Content-Length", str(len(payload)))
if realtime:
self.send_header("x-databricks-rt-session", "true")
self.end_headers()
self.wfile.write(payload)

def do_POST(self):
if self.path.endswith("/sessions"):
self.respond({"session_id": "test-session"}, realtime=True)
else:
self.respond({"statement_id": "test-statement", "status": {"state": "PENDING"}})

def do_GET(self):
self.respond(response)

def do_DELETE(self):
self.respond({})

def log_message(self, *_args):
pass

with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
worker = threading.Thread(target=server.serve_forever, daemon=True)
worker.start()
session = None
try:
session = k.Session(
host=f"http://127.0.0.1:{server.server_port}",
http_path="/sql/1.0/warehouses/test-wh",
access_token="test-token",
telemetry_enabled=False,
)
stmt = session.statement()
stmt.set_sql("SELECT 1")
owner = stmt.submit()
before_reader = len(requests)
reader = owner.reader()
assert len(requests) == before_reader
assert isinstance(reader, k.AsyncStatementReader)
assert reader.statement_id == owner.statement_id
assert not hasattr(reader, "cancel")
assert not hasattr(reader, "close")
state, failure = reader.status()
streams = []
if failed:
assert state == "Failed"
assert isinstance(failure, k.KernelError)
assert failure.code == "SqlError"
assert failure.sql_state == "42P01"
for read in (reader.await_result, reader.fetch_result):
with pytest.raises(k.KernelError) as error:
read()
assert error.value.code == "SqlError"
assert error.value.sql_state == "42P01"
del read
else:
assert (state, failure) == ("Succeeded", None)
streams = [reader.await_result(), reader.fetch_result()]
assert all(isinstance(stream, k.ResultStream) for stream in streams)
expected_reads = 3 if failed else 4
assert [path for method, path in requests if method == "GET"] == [statement_path] * expected_reads
owner.close()
before_release_reads = len(requests)
for read in (reader.status, reader.await_result, reader.fetch_result):
with pytest.raises(k.KernelError) as error:
read()
assert error.value.code == "InvalidStatementHandle"
del read
with pytest.raises(k.KernelError) as error:
owner.reader()
assert error.value.code == "InvalidStatementHandle"
assert len(requests) == before_release_reads
stmt.close()
session.close()
session = None
del owner, stmt
with pytest.raises(k.KernelError) as error:
reader.status()
assert error.value.code == "InvalidStatementHandle"
del reader
for stream in streams:
assert stream.fetch_all_arrow().to_pydict() == {"n": [1, 2]}
stream.close()
finally:
if session is not None:
session.close()
server.shutdown()
worker.join(timeout=5)
1 change: 1 addition & 0 deletions pyo3/tests/test_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ def test_exports_expected_classes():
"Statement",
"ExecutedStatement",
"ExecutedAsyncStatement",
"AsyncStatementReader",
"Metadata",
"ResultStream",
"KernelError",
Expand Down
4 changes: 2 additions & 2 deletions src/c_abi/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2770,7 +2770,7 @@ mod tests {
let server = MockServer::start().await;
let counter = attempts.clone();
Mock::given(method("POST"))
.and(path("/api/2.0/sql/sessions"))
.and(path("/api/2.0/sql/warehouses/test_wh/sessions"))
.respond_with(move |_req: &wiremock::Request| {
// First attempt 503 (retryable); a retrying policy would
// then see the 200 below.
Expand Down Expand Up @@ -3140,7 +3140,7 @@ mod tests {
let (server, session, exporter) = rt.block_on(async {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/2.0/sql/sessions"))
.and(path("/api/2.0/sql/warehouses/test_wh/sessions"))
.respond_with(ResponseTemplate::new(200).set_body_string(
r#"{"session_id":"sess-cabi-telemetry-close","warehouse_id":"test_wh"}"#,
))
Expand Down
Loading
Loading