Skip to content

Commit ebebf52

Browse files
feat(statement): add independent async statement readers
Preserve session attribution and parent invalidation in derived read-only handles without transferring cleanup or execution telemetry ownership. Expose the reader API through PyO3 and cover routing, independent reads, timeout and drop safety, error mapping, and runtime retention. Signed-off-by: Aakash Saravanan <aakash.saravanan@databricks.com>
1 parent 1bf5b12 commit ebebf52

13 files changed

Lines changed: 537 additions & 51 deletions

File tree

‎NEXT_CHANGELOG.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,11 @@ changes go in their respective binding's NEXT_CHANGELOG.
1111

1212
### Added
1313

14+
- `ExecutedAsyncStatement::reader()` creates independent read-only handles that retain session routing without owning cancellation, cleanup or execution telemetry.
15+
1416
### Changed
1517

16-
- 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.
18+
- 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.
1719
- 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.
1820

1921
### Updated

‎pyo3/NEXT_CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ changes go in the root `NEXT_CHANGELOG.md`.
1313

1414
### Added
1515

16+
- `ExecutedAsyncStatement.reader()` returns an independent `AsyncStatementReader` for status and result reads with the source handle's session routing.
17+
1618
### Changed
1719

1820
### Updated

‎pyo3/src/executed_async.rs‎

Lines changed: 56 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ use crate::errors::to_py_err;
2424
use crate::result_stream::ResultStream;
2525
use crate::runtime::KernelRuntime;
2626
use databricks_sql_kernel::{
27+
AsyncStatementReader as KAsyncStatementReader,
2728
ExecutedAsyncStatement as KExecutedAsyncStatement, ExecutedStatementHandle, StatementStatus,
2829
};
2930
use pyo3::prelude::*;
@@ -58,6 +59,16 @@ impl ExecutedAsyncStatement {
5859
&self.statement_id
5960
}
6061

62+
/// Create an independent read-only handle retaining this statement's session routing.
63+
/// The owning handle controls cancellation, cleanup and execution telemetry.
64+
fn reader(&self, py: Python<'_>) -> PyResult<AsyncStatementReader> {
65+
let inner = alive!(self, "ExecutedAsyncStatement");
66+
Ok(AsyncStatementReader {
67+
inner: inner.exec.reader().map_err(|error| to_py_err(py, error))?,
68+
runtime: Arc::clone(&inner.runtime),
69+
})
70+
}
71+
6172
/// Single-shot status check. Returns a tuple
6273
/// `(state: str, failure: Optional[KernelError])` where:
6374
///
@@ -78,22 +89,7 @@ impl ExecutedAsyncStatement {
7889
let inner = alive!(self, "ExecutedAsyncStatement");
7990
let runtime = inner.runtime.clone();
8091
let status = run_kernel!(py, runtime, inner.exec.status())?;
81-
// String mapping lives on the kernel `StatementStatus::as_str`
82-
// so all bindings share one taxonomy.
83-
let state = status.as_str();
84-
let failure: Bound<'py, PyAny> = match &status {
85-
StatementStatus::Failed(err) => {
86-
// Build the KernelError instance the same way every
87-
// other failure path does, then hand it to Python as
88-
// a plain value (not raised). Callers read .code /
89-
// .sql_state / .query_id directly.
90-
let py_err = to_py_err(py, err.clone());
91-
py_err.value(py).clone().into_any()
92-
}
93-
_ => py.None().into_bound(py),
94-
};
95-
let tuple = pyo3::types::PyTuple::new(py, [state.into_pyobject(py)?.into_any(), failure])?;
96-
Ok(tuple.into_any())
92+
status_to_python(py, status)
9793
}
9894

9995
/// Block until the statement reaches a terminal state, then
@@ -151,3 +147,47 @@ impl ExecutedAsyncStatement {
151147
)
152148
}
153149
}
150+
151+
/// Independent status and result access without server lifecycle ownership.
152+
#[pyclass(name = "AsyncStatementReader")]
153+
pub(crate) struct AsyncStatementReader {
154+
inner: KAsyncStatementReader,
155+
runtime: Arc<KernelRuntime>,
156+
}
157+
158+
#[pymethods]
159+
impl AsyncStatementReader {
160+
#[getter]
161+
fn statement_id(&self) -> &str {
162+
self.inner.statement_id()
163+
}
164+
165+
/// Read server status as `(state, failure)`.
166+
fn status<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
167+
let status = run_kernel!(py, Arc::clone(&self.runtime), self.inner.status())?;
168+
status_to_python(py, status)
169+
}
170+
171+
/// Poll until terminal and return a fresh result stream. Interrupted reads do not cancel.
172+
fn await_result(&self, py: Python<'_>) -> PyResult<ResultStream> {
173+
let runtime = Arc::clone(&self.runtime);
174+
let stream = run_kernel!(py, runtime, self.inner.await_result())?;
175+
Ok(ResultStream::new(stream, runtime))
176+
}
177+
178+
/// Return a fresh result stream; raises InvalidState if execution is not terminal.
179+
fn fetch_result(&self, py: Python<'_>) -> PyResult<ResultStream> {
180+
let runtime = Arc::clone(&self.runtime);
181+
let stream = run_kernel!(py, runtime, self.inner.fetch_result())?;
182+
Ok(ResultStream::new(stream, runtime))
183+
}
184+
}
185+
186+
fn status_to_python<'py>(py: Python<'py>, status: StatementStatus) -> PyResult<Bound<'py, PyAny>> {
187+
let state = status.as_str();
188+
let failure = match &status {
189+
StatementStatus::Failed(err) => to_py_err(py, err.clone()).value(py).clone().into_any(),
190+
_ => py.None().into_bound(py),
191+
};
192+
Ok(pyo3::types::PyTuple::new(py, [state.into_pyobject(py)?.into_any(), failure])?.into_any())
193+
}

‎pyo3/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ fn databricks_sql_kernel(m: &Bound<'_, PyModule>) -> PyResult<()> {
8484
m.add_class::<statement::ExecutedStatement>()?;
8585
m.add_class::<statement::StatementCanceller>()?;
8686
m.add_class::<executed_async::ExecutedAsyncStatement>()?;
87+
m.add_class::<executed_async::AsyncStatementReader>()?;
8788
m.add_class::<metadata::Metadata>()?;
8889
m.add_class::<result_stream::ResultStream>()?;
8990
m.add_function(wrap_pyfunction!(init_logging, m)?)?;

‎pyo3/src/session.rs‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -695,13 +695,9 @@ impl Session {
695695

696696
/// Re-attach to an already-submitted server statement by its id,
697697
/// returning an `ExecutedAsyncStatement` the caller can poll
698-
/// (`status()`), await (`await_result()`), or cancel/close — without
699-
/// having been the handle that submitted it.
700-
///
701-
/// This is the resume path the connector uses for
702-
/// `get_query_state` / `get_async_execution_result`: server
703-
/// statement state is keyed solely by the id, so a caller holding
704-
/// only the id can recover a working handle bound to this session.
698+
/// (`status()`) or await (`await_result()`) without lifecycle ownership.
699+
/// ID-only reads use standard SQL URLs. Use `ExecutedAsyncStatement.reader()`
700+
/// to retain the originating session's routing for independent reads.
705701
///
706702
/// Issues one `GetStatementStatus` to seed the handle. Raises
707703
/// `KernelError` with code `NotFound` if the server doesn't

‎pyo3/tests/test_async.py‎

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,15 @@
1717

1818
from __future__ import annotations
1919

20+
import base64
21+
import json
22+
import threading
2023
import time
24+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
2125

2226
import databricks_sql_kernel as k
27+
import pyarrow as pa
28+
import pytest
2329

2430
from conftest import live
2531

@@ -114,3 +120,125 @@ def test_use_after_close_raises_kernel_error(session):
114120
else:
115121
raise AssertionError("expected KernelError on use-after-close")
116122
stmt.close()
123+
124+
125+
@pytest.mark.parametrize("failed", [False, True], ids=["succeeded", "failed"])
126+
def test_reader_preserves_session_and_maps_errors(failed):
127+
requests = []
128+
statement_path = "/api/2.0/sql/warehouses/test-wh/sessions/test-session/statements/test-statement"
129+
response = {
130+
"statement_id": "test-statement",
131+
"status": {
132+
"state": "FAILED",
133+
"sql_state": "42P01",
134+
"error": {"message": "invalid query", "error_code": "TABLE_OR_VIEW_NOT_FOUND"},
135+
},
136+
}
137+
if not failed:
138+
batch = pa.record_batch([pa.array([1, 2], type=pa.int64())], names=["n"])
139+
buffer = pa.BufferOutputStream()
140+
with pa.ipc.new_stream(buffer, batch.schema) as writer:
141+
writer.write_batch(batch)
142+
attachment = base64.b64encode(buffer.getvalue()).decode()
143+
response = {
144+
"statement_id": "test-statement",
145+
"status": {"state": "SUCCEEDED"},
146+
"manifest": {
147+
"format": "ARROW_STREAM",
148+
"schema": {
149+
"column_count": 1,
150+
"columns": [{"name": "n", "type_name": "BIGINT", "type_text": "BIGINT", "position": 0}],
151+
},
152+
"total_chunk_count": 1,
153+
"total_row_count": 2,
154+
},
155+
"result": {"chunk_index": 0, "row_offset": 0, "row_count": 2, "attachment": attachment},
156+
}
157+
158+
class Handler(BaseHTTPRequestHandler):
159+
def respond(self, body, realtime=False):
160+
requests.append((self.command, self.path))
161+
self.rfile.read(int(self.headers.get("Content-Length", 0)))
162+
payload = json.dumps(body).encode()
163+
self.send_response(200)
164+
self.send_header("Content-Length", str(len(payload)))
165+
if realtime:
166+
self.send_header("x-databricks-rt-session", "true")
167+
self.end_headers()
168+
self.wfile.write(payload)
169+
170+
def do_POST(self):
171+
if self.path.endswith("/sessions"):
172+
self.respond({"session_id": "test-session"}, realtime=True)
173+
else:
174+
self.respond({"statement_id": "test-statement", "status": {"state": "PENDING"}})
175+
176+
def do_GET(self):
177+
self.respond(response)
178+
179+
def do_DELETE(self):
180+
self.respond({})
181+
182+
def log_message(self, *_args):
183+
pass
184+
185+
with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
186+
worker = threading.Thread(target=server.serve_forever, daemon=True)
187+
worker.start()
188+
session = None
189+
try:
190+
session = k.Session(
191+
host=f"http://127.0.0.1:{server.server_port}",
192+
http_path="/sql/1.0/warehouses/test-wh",
193+
access_token="test-token",
194+
telemetry_enabled=False,
195+
)
196+
stmt = session.statement()
197+
stmt.set_sql("SELECT 1")
198+
owner = stmt.submit()
199+
before_reader = len(requests)
200+
reader = owner.reader()
201+
assert len(requests) == before_reader
202+
assert isinstance(reader, k.AsyncStatementReader)
203+
assert reader.statement_id == owner.statement_id
204+
assert not hasattr(reader, "cancel")
205+
assert not hasattr(reader, "close")
206+
state, failure = reader.status()
207+
streams = []
208+
if failed:
209+
assert state == "Failed"
210+
assert isinstance(failure, k.KernelError)
211+
assert failure.code == "SqlError"
212+
assert failure.sql_state == "42P01"
213+
for read in (reader.await_result, reader.fetch_result):
214+
with pytest.raises(k.KernelError) as error:
215+
read()
216+
assert error.value.code == "SqlError"
217+
assert error.value.sql_state == "42P01"
218+
del read
219+
else:
220+
assert (state, failure) == ("Succeeded", None)
221+
streams = [reader.await_result(), reader.fetch_result()]
222+
assert all(isinstance(stream, k.ResultStream) for stream in streams)
223+
expected_reads = 3 if failed else 4
224+
assert [path for method, path in requests if method == "GET"] == [statement_path] * expected_reads
225+
stmt.close()
226+
with pytest.raises(k.KernelError) as error:
227+
owner.reader()
228+
assert error.value.code == "InvalidStatementHandle"
229+
owner.close()
230+
session.close()
231+
session = None
232+
del owner, stmt
233+
with pytest.raises(k.KernelError) as error:
234+
reader.status()
235+
assert error.value.code == "InvalidStatementHandle"
236+
del reader
237+
for stream in streams:
238+
assert stream.fetch_all_arrow().to_pydict() == {"n": [1, 2]}
239+
stream.close()
240+
finally:
241+
if session is not None:
242+
session.close()
243+
server.shutdown()
244+
worker.join(timeout=5)

‎pyo3/tests/test_module.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ def test_exports_expected_classes():
3030
"Statement",
3131
"ExecutedStatement",
3232
"ExecutedAsyncStatement",
33+
"AsyncStatementReader",
3334
"Metadata",
3435
"ResultStream",
3536
"KernelError",

‎src/client/sea.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1206,6 +1206,7 @@ impl Transport for SeaRestTransport {
12061206
}
12071207
} else {
12081208
SessionRoute::Standard {
1209+
// SEA requires warehouse_id on standard session close to avoid HTTP 400.
12091210
session_url: format!(
12101211
"{}/sessions/{}?warehouse_id={}",
12111212
self.base_url(),

‎src/lib.rs‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ pub use result_stream::{OwnedBatchIter, ResultBatch, ResultStream, Row, SchemaRe
149149
pub use session::{Session, SessionBuilder};
150150
pub use statement::executed::ExecutedStatement;
151151
pub use statement::executed_async::{
152-
AsyncStatementCanceller, ExecutedAsyncStatement, StatementStatus,
152+
AsyncStatementCanceller, AsyncStatementReader, ExecutedAsyncStatement, StatementStatus,
153153
};
154154
pub use statement::handle::ExecutedStatementHandle;
155155
pub use statement::mutable::{DirectStatement, Statement, StatementCanceller};
@@ -175,6 +175,7 @@ const _: fn() = || {
175175
assert_send_sync::<Statement>();
176176
assert_send_sync::<ExecutedStatement>();
177177
assert_send_sync::<ExecutedAsyncStatement>();
178+
assert_send_sync::<AsyncStatementReader>();
178179
assert_send_sync::<Metadata>();
179180
assert_send_sync::<ResultStream>();
180181

@@ -216,6 +217,11 @@ const _: fn() = || {
216217
assert_send(&exec.await_result());
217218
assert_send(&exec.fetch_result());
218219
};
220+
let _: fn(&AsyncStatementReader) = |reader| {
221+
assert_send(&reader.status());
222+
assert_send(&reader.await_result());
223+
assert_send(&reader.fetch_result());
224+
};
219225
let _: fn(Session) = |session| {
220226
assert_send(&session.close());
221227
};

‎src/session.rs‎

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -668,16 +668,21 @@ impl Session {
668668
}
669669

670670
/// Adopt an already-submitted server statement by its id, producing
671-
/// an [`ExecutedAsyncStatement`] that can poll [`status`] / await
672-
/// results / cancel — without having been the handle that submitted
673-
/// it.
671+
/// an [`ExecutedAsyncStatement`] that can poll [`status`] and fetch
672+
/// results without having been the handle that submitted it.
674673
///
675674
/// This is the resume path: a caller (or a different process) that
676675
/// holds only the statement id can re-attach and drive it to
677676
/// completion, fetch its result, or read its terminal state.
678677
/// Attached reads use standard SQL URLs because the statement ID does not
679678
/// identify its originating session.
680679
///
680+
/// Lakehouse Real-Time supports asynchronous execution through the handle
681+
/// returned by [`Statement::submit`]. Retain that handle for polling and result
682+
/// fetching, or derive independent readers with [`ExecutedAsyncStatement::reader`].
683+
/// Polling or fetching a Lakehouse Real-Time statement from another session
684+
/// is not supported.
685+
///
681686
/// Issues a single `GetStatementStatus` to seed the handle's initial
682687
/// status (mirrors how `submit` seeds it from the submit response),
683688
/// so the extended-status accessors return useful values before the
@@ -2884,6 +2889,17 @@ mod is_open_tests {
28842889
stmt.spec().sql("SELECT 1 AS n");
28852890
let async_exec = stmt.submit().await.expect("submit succeeds");
28862891
let _ = async_exec.status().await.expect("status succeeds");
2892+
let reader = async_exec.reader().expect("reader");
2893+
let _ = reader.status().await.expect("reader status");
2894+
let mut read_stream = reader.await_result().await.expect("reader result");
2895+
while read_stream
2896+
.next_batch()
2897+
.await
2898+
.expect("reader batch")
2899+
.is_some()
2900+
{}
2901+
drop(read_stream);
2902+
drop(reader);
28872903
let mut stream = async_exec.await_result().await.expect("await succeeds");
28882904
assert!(stream.next_batch().await.expect("first batch").is_some());
28892905
assert!(stream
@@ -2909,12 +2925,10 @@ mod is_open_tests {
29092925
statement_log["entry"]["sql_driver_log"]["sql_statement_id"],
29102926
"stmt-telemetry-async"
29112927
);
2912-
assert!(
2913-
detail["n_operation_status_calls"]
2914-
.as_i64()
2915-
.unwrap_or_default()
2916-
>= 2,
2917-
"status() plus await_result() should record status polls"
2928+
assert_eq!(
2929+
detail["n_operation_status_calls"].as_i64(),
2930+
Some(2),
2931+
"only owning status and await polls contribute to execution telemetry"
29182932
);
29192933
assert!(
29202934
detail["operation_status_latency_millis"]

0 commit comments

Comments
 (0)