diff --git a/.github/workflows/napi-checks.yml b/.github/workflows/napi-checks.yml index f4959728..6a31d1ff 100644 --- a/.github/workflows/napi-checks.yml +++ b/.github/workflows/napi-checks.yml @@ -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" @@ -40,6 +41,7 @@ on: branches: [main] paths: - "napi/**" + - "src/**" - "Cargo.toml" - ".github/workflows/napi-checks.yml" diff --git a/.github/workflows/pyo3-checks.yml b/.github/workflows/pyo3-checks.yml index 3eaef161..1dda66f7 100644 --- a/.github/workflows/pyo3-checks.yml +++ b/.github/workflows/pyo3-checks.yml @@ -22,6 +22,7 @@ on: branches: [main] paths: - "pyo3/**" + - "src/**" - "Cargo.toml" - "Cargo.lock" - ".github/workflows/pyo3-checks.yml" @@ -29,6 +30,7 @@ on: branches: [main] paths: - "pyo3/**" + - "src/**" - "Cargo.toml" - "Cargo.lock" - ".github/workflows/pyo3-checks.yml" diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 2ebce050..a2fe0cb9 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -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` for `warehouse_id`; use `Some(id)` when building a standard SQL request body. + ### Updated ### Fixed diff --git a/docs/designs/cloudfetch-implementation-plan.md b/docs/designs/cloudfetch-implementation-plan.md index 415501e9..cee2a99f 100644 --- a/docs/designs/cloudfetch-implementation-plan.md +++ b/docs/designs/cloudfetch-implementation-plan.md @@ -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 | diff --git a/napi/src/connection.rs b/napi/src/connection.rs index 5333e1ec..7aba91ff 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -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" })), ) diff --git a/napi/src/metadata.rs b/napi/src/metadata.rs index b4cfeef5..fc835eca 100644 --- a/napi/src/metadata.rs +++ b/napi/src/metadata.rs @@ -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" })), diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index e0881e54..968da6ca 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -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 diff --git a/pyo3/src/executed_async.rs b/pyo3/src/executed_async.rs index 1189c9db..03463172 100644 --- a/pyo3/src/executed_async.rs +++ b/pyo3/src/executed_async.rs @@ -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::*; @@ -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 { + 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: /// @@ -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 @@ -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, +} + +#[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> { + 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 { + 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 { + 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> { + 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()) +} diff --git a/pyo3/src/lib.rs b/pyo3/src/lib.rs index adafe292..f42ffa85 100644 --- a/pyo3/src/lib.rs +++ b/pyo3/src/lib.rs @@ -84,6 +84,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::()?; m.add_function(wrap_pyfunction!(init_logging, m)?)?; diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 291c054b..c626ee89 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -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 diff --git a/pyo3/tests/test_async.py b/pyo3/tests/test_async.py index e793e0de..c26cb682 100644 --- a/pyo3/tests/test_async.py +++ b/pyo3/tests/test_async.py @@ -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 @@ -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) diff --git a/pyo3/tests/test_module.py b/pyo3/tests/test_module.py index d059dfab..4ea65618 100644 --- a/pyo3/tests/test_module.py +++ b/pyo3/tests/test_module.py @@ -30,6 +30,7 @@ def test_exports_expected_classes(): "Statement", "ExecutedStatement", "ExecutedAsyncStatement", + "AsyncStatementReader", "Metadata", "ResultStream", "KernelError", diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 0be472fc..73764e74 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -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. @@ -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"}"#, )) diff --git a/src/client/sea.rs b/src/client/sea.rs index 62b967cb..2a490aac 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -49,6 +49,7 @@ use tokio::runtime::Handle as RuntimeHandle; /// advisory — a server that does not recognise it ignores it — so there is /// nothing for a caller to configure. const SEA_SYNC_METADATA_HEADER: &str = "x-databricks-sea-can-run-fully-sync"; +const REALTIME_SESSION_HEADER: &str = "x-databricks-rt-session"; /// DBSQL omits session versions, while server-issued FAST versions start at 1. const NO_SESSION_VERSION: i64 = 0; @@ -114,6 +115,12 @@ enum StatementOutcome { Err(Error), } +#[derive(Debug)] +enum SessionRoute { + Standard { session_url: String }, + Realtime { session_url: String }, +} + /// Mapped terminal outcome from the synchronous execution phase. /// /// `statement_id` is captured from the initial execute response for cleanup; @@ -171,6 +178,7 @@ pub(crate) struct SeaRestTransport { host: String, warehouse_id: String, config: TransportConfig, + session_route: OnceLock, session_version: AtomicI64, reader_factory: OnceLock, runtime_handle: OnceLock, @@ -212,6 +220,7 @@ impl SeaRestTransport { host: host.into(), warehouse_id: warehouse_id.into(), config, + session_route: OnceLock::new(), session_version: AtomicI64::new(NO_SESSION_VERSION), reader_factory: OnceLock::new(), runtime_handle: OnceLock::new(), @@ -234,9 +243,30 @@ impl SeaRestTransport { }) } - /// Build the base URL for API requests. fn base_url(&self) -> String { - format!("{}/api/2.0/sql", self.host.trim_end_matches('/')) + match self.session_route.get() { + Some(SessionRoute::Realtime { session_url }) => session_url.clone(), + Some(SessionRoute::Standard { .. }) | None => { + format!("{}/api/2.0/sql", self.host.trim_end_matches('/')) + } + } + } + + fn warehouse_sessions_url(&self) -> String { + format!( + "{}/api/2.0/sql/warehouses/{}/sessions", + self.host.trim_end_matches('/'), + self.warehouse_id + ) + } + + fn statement_read_base_url(&self, session_attribution: SessionAttribution) -> String { + match session_attribution { + SessionAttribution::Current => self.base_url(), + SessionAttribution::Detached => { + format!("{}/api/2.0/sql", self.host.trim_end_matches('/')) + } + } } fn current_session_version(&self) -> Option { @@ -293,7 +323,13 @@ impl SeaRestTransport { /// when adding more. /// /// See: - fn result_chunks_url(&self, statement_id: &str, chunk_index: i64, row_offset: i64) -> String { + fn result_chunks_url( + &self, + statement_id: &str, + chunk_index: i64, + row_offset: i64, + session_attribution: SessionAttribution, + ) -> String { debug_assert!( row_offset >= 0, "row_offset must be non-negative on the SEA wire (got {row_offset})", @@ -301,7 +337,7 @@ impl SeaRestTransport { if row_offset > 0 { format!( "{}/statements/{}/result/chunks/{}?row_offset={}", - self.base_url(), + self.statement_read_base_url(session_attribution), statement_id, chunk_index, row_offset @@ -309,7 +345,7 @@ impl SeaRestTransport { } else { format!( "{}/statements/{}/result/chunks/{}", - self.base_url(), + self.statement_read_base_url(session_attribution), statement_id, chunk_index ) @@ -348,7 +384,11 @@ impl SeaRestTransport { statement_id: &str, session_attribution: SessionAttribution, ) -> Result { - let url = format!("{}/statements/{}", self.base_url(), statement_id); + let url = format!( + "{}/statements/{}", + self.statement_read_base_url(session_attribution), + statement_id + ); debug!("Getting statement status at {}", url); @@ -404,7 +444,8 @@ impl SeaRestTransport { let mut response = self .get_statement_status_raw(statement_id, session_attribution) .await?; - self.enrich_num_modified_rows(&mut response).await; + self.enrich_num_modified_rows(&mut response, session_attribution) + .await; Ok(response) } @@ -420,7 +461,11 @@ impl SeaRestTransport { /// /// Gated on the manifest's column signature so SELECTs (real columns) never /// hit the decode path; a DML-count result is always tiny and inline. - async fn enrich_num_modified_rows(&self, response: &mut ExecuteResponse) { + async fn enrich_num_modified_rows( + &self, + response: &mut ExecuteResponse, + session_attribution: SessionAttribution, + ) { if response.status.num_modified_rows.is_some() { return; } @@ -435,7 +480,7 @@ impl SeaRestTransport { // any later fetch the caller makes (a fresh GetStatement builds its own // reader), so result consumption is unaffected. let reader = match factory - .create_reader(&response.statement_id, response) + .create_reader(&response.statement_id, response, session_attribution) .await { Ok(r) => r, @@ -637,10 +682,17 @@ impl SeaRestTransport { } else { "INLINE" }; + let (warehouse_id, session_id) = match self.session_route.get() { + Some(SessionRoute::Standard { .. }) | None => ( + Some(self.warehouse_id.clone()), + Some(session_id.to_string()), + ), + Some(SessionRoute::Realtime { .. }) => (None, None), + }; let request_body = ExecuteStatementRequest { - warehouse_id: self.warehouse_id.clone(), + warehouse_id, statement: sql.to_string(), - session_id: Some(session_id.to_string()), + session_id, session_version: self.current_session_version(), catalog: params.catalog.clone(), schema: params.schema.clone(), @@ -833,7 +885,11 @@ impl SeaRestTransport { // rewrite in the same pass and can eagerly download CloudFetch chunk 0 // to extract its schema. let reader = reader_factory - .create_reader(&response.statement_id, &response) + .create_reader( + &response.statement_id, + &response, + SessionAttribution::Current, + ) .await?; // Carry the full status forward so the executed handle can skip a @@ -971,7 +1027,8 @@ impl SeaRestTransport { // after terminal mapping, keeping this result work out of the execution // phase without shifting it onto the public result stream. if response_from_poll { - self.enrich_num_modified_rows(&mut response).await; + self.enrich_num_modified_rows(&mut response, SessionAttribution::Current) + .await; } let reader_factory = self.reader_factory()?; @@ -1101,10 +1158,10 @@ impl Transport for SeaRestTransport { schema: Option<&str>, session_config: HashMap, ) -> Result { - let url = format!("{}/sessions", self.base_url()); + let url = self.warehouse_sessions_url(); let request_body = CreateSessionRequest { - warehouse_id: self.warehouse_id.clone(), + warehouse_id: None, catalog: catalog.map(|s| s.to_string()), schema: schema.map(|s| s.to_string()), session_confs: session_config, @@ -1128,6 +1185,11 @@ impl Transport for SeaRestTransport { .http_client .execute(request, RequestType::CreateSession) .await?; + let realtime = response + .headers() + .get(REALTIME_SESSION_HEADER) + .and_then(|value| value.to_str().ok()) + .is_some_and(|value| value.eq_ignore_ascii_case("true")); let body = response .text() .await @@ -1138,7 +1200,24 @@ impl Transport for SeaRestTransport { "Failed to parse session response: {e} - body: {body}" )) })?; - + let route = if realtime { + SessionRoute::Realtime { + session_url: format!("{}/{}", url, session_response.session_id), + } + } else { + SessionRoute::Standard { + // SEA requires warehouse_id on standard session close to avoid HTTP 400. + session_url: format!( + "{}/sessions/{}?warehouse_id={}", + self.base_url(), + session_response.session_id, + self.warehouse_id + ), + } + }; + self.session_route.set(route).map_err(|_| { + Error::invalid_state().message("SQL transport already created a session") + })?; self.observe_session_version(session_response.session_version); debug!("Created session: {}", session_response.session_id); @@ -1148,26 +1227,22 @@ impl Transport for SeaRestTransport { }) } - async fn delete_session(&self, session_id: &str) -> Result<()> { - // SEA requires `warehouse_id` as a query parameter on - // `DELETE /api/2.0/sql/sessions/{id}`. Without it the server - // returns HTTP 400 ("Required field is not specified: - // warehouse_id"), the session never gets cleaned up via the - // explicit close path, and instead waits for the idle-timeout - // reaper to drop it. - let url = format!( - "{}/sessions/{}?warehouse_id={}", - self.base_url(), - session_id, - self.warehouse_id - ); + async fn delete_session(&self) -> Result<()> { + let route = self.session_route.get().ok_or_else(|| { + Error::invalid_state().message("SQL transport has not created a session") + })?; + let url = match route { + SessionRoute::Standard { session_url } | SessionRoute::Realtime { session_url } => { + session_url + } + }; debug!("Deleting session at {}", url); let request = self .http_client .inner() - .request(Method::DELETE, &url) + .request(Method::DELETE, url.as_str()) .build() .map_err(|e| { Error::invalid_argument().message(format!("Failed to build request: {e}")) @@ -1186,12 +1261,12 @@ impl Transport for SeaRestTransport { .await { crate::klog::warn!( - session_id = %session_id, + session_url = %url, error = %e, "delete_session failed after HTTP retries; server-side session will be reclaimed by idle timeout" ); } else { - debug!("Deleted session: {}", session_id); + debug!("Deleted session at {}", url); } Ok(()) @@ -1280,7 +1355,10 @@ impl Transport for SeaRestTransport { // reader from the inline result (no extra GetStatementResult). StatementOutcome::Done(r) => { let reader_factory = self.reader_factory()?; - let reader = match reader_factory.create_reader(&r.statement_id, &r).await { + let reader = match reader_factory + .create_reader(&r.statement_id, &r, SessionAttribution::Current) + .await + { Ok(reader) => reader, Err(e) => { self.close_orphaned_statement(&statement_id, "create_reader (direct)") @@ -1322,7 +1400,9 @@ impl Transport for SeaRestTransport { match Self::terminal_outcome(response) { StatementOutcome::Done(r) => { let reader_factory = self.reader_factory()?; - let reader = reader_factory.create_reader(&r.statement_id, &r).await?; + let reader = reader_factory + .create_reader(&r.statement_id, &r, session_attribution) + .await?; let telemetry_result_format = Self::telemetry_result_format(&r); let telemetry_is_compressed = Self::telemetry_is_compressed(&r); Ok(Some(ExecuteResult { @@ -1353,8 +1433,10 @@ impl Transport for SeaRestTransport { statement_id: &str, chunk_index: i64, row_offset: i64, + session_attribution: SessionAttribution, ) -> Result { - let url = self.result_chunks_url(statement_id, chunk_index, row_offset); + let url = + self.result_chunks_url(statement_id, chunk_index, row_offset, session_attribution); debug!("Getting result chunks at {}", url); @@ -1398,6 +1480,7 @@ impl Transport for SeaRestTransport { statement_id: &str, chunk_index: i64, row_offset: i64, + session_attribution: SessionAttribution, ) -> Result { // Same endpoint as CloudFetch chunk-link fetching, but on // the inline-Arrow path the response carries Arrow IPC bytes @@ -1416,7 +1499,7 @@ impl Transport for SeaRestTransport { let row_offset = row_offset.max(0); let url = format!( "{}/statements/{}/result/chunks/{}?row_offset={}", - self.base_url(), + self.statement_read_base_url(session_attribution), statement_id, chunk_index, row_offset, @@ -2539,7 +2622,7 @@ mod tests { // CloudFetch path: row_offset=0 is the kernel default and must // produce the legacy URL shape (no `?row_offset=...`). assert_eq!( - client.result_chunks_url("01abc", 7, 0), + client.result_chunks_url("01abc", 7, 0, SessionAttribution::Current), "https://test.databricks.com/api/2.0/sql/statements/01abc/result/chunks/7" ); } @@ -2560,7 +2643,7 @@ mod tests { // the right rowOffset. let client = create_test_client(); assert_eq!( - client.result_chunks_url("01abc", 3, 12345), + client.result_chunks_url("01abc", 3, 12345, SessionAttribution::Current), "https://test.databricks.com/api/2.0/sql/statements/01abc/result/chunks/3?row_offset=12345" ); } @@ -2572,7 +2655,7 @@ mod tests { // would still match `12345` and `i64::MAX`) is caught. let client = create_test_client(); assert_eq!( - client.result_chunks_url("01abc", 3, 1), + client.result_chunks_url("01abc", 3, 1, SessionAttribution::Current), "https://test.databricks.com/api/2.0/sql/statements/01abc/result/chunks/3?row_offset=1" ); } @@ -2585,7 +2668,7 @@ mod tests { // offsets at request-time. The URL builder must not panic // or truncate for the legal range. let client = create_test_client(); - let url = client.result_chunks_url("01abc", 0, i64::MAX); + let url = client.result_chunks_url("01abc", 0, i64::MAX, SessionAttribution::Current); assert!( url.ends_with(&format!("?row_offset={}", i64::MAX)), "i64::MAX must serialise as decimal: got {url}", @@ -2610,6 +2693,316 @@ mod tests { ) } + #[tokio::test] + async fn realtime_session_uses_warehouse_urls_for_owned_lifecycle() { + use wiremock::matchers::{body_json, method, path, query_param}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/warehouses/warehouse-123/sessions")) + .and(body_json(json!({ "execution_mode": "FAST" }))) + .respond_with( + ResponseTemplate::new(200) + .insert_header(REALTIME_SESSION_HEADER, "true") + .set_body_json(json!({ + "session_id": "session-1", + "session_version": { "version_id": 7 }, + })), + ) + .expect(1) + .mount(&server) + .await; + + Mock::given(method("POST")) + .and(path( + "/api/2.0/sql/warehouses/warehouse-123/sessions/session-1/statements", + )) + .and(body_json(json!({ + "statement": "SELECT 1", + "session_version": { "version_id": 7 }, + "disposition": "INLINE_OR_EXTERNAL_LINKS", + "format": "ARROW_STREAM", + "wait_timeout": "0s", + "on_wait_timeout": "CONTINUE", + "result_compression": "LZ4_FRAME", + }))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "statement_id": "statement-1", + "status": { "state": "PENDING" }, + }))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path( + "/api/2.0/sql/warehouses/warehouse-123/sessions/session-1/statements/statement-1", + )) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "statement_id": "statement-1", + "status": { "state": "RUNNING" }, + }))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/warehouses/warehouse-123/sessions/session-1/statements/statement-1/result/chunks/0")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "external_links": [], + "next_chunk_index": null, + }))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path( + "/api/2.0/sql/warehouses/warehouse-123/sessions/session-1/statements/inline-statement/result/chunks/1", + )) + .and(query_param("row_offset", "3")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "chunk_index": 1, + "row_offset": 3, + "row_count": 1, + "next_chunk_index": null, + "attachment": "AQ==", + }))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/warehouses/warehouse-123/sessions/session-1/statements/statement-1/cancel")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path( + "/api/2.0/sql/warehouses/warehouse-123/sessions/session-1/statements/statement-1", + )) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path( + "/api/2.0/sql/warehouses/warehouse-123/sessions/session-1", + )) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + + let transport = create_test_client_against(&server.uri()); + let session = transport + .create_session(None, None, HashMap::new()) + .await + .expect("session creation must succeed"); + transport + .submit_statement(&session.session_id, "SELECT 1", &ExecuteParams::default()) + .await + .expect("execute must succeed"); + transport + .get_statement_status("statement-1", SessionAttribution::Current) + .await + .expect("owned status must succeed"); + transport + .get_result_chunks("statement-1", 0, 0, SessionAttribution::Current) + .await + .expect("owned chunk fetch must succeed"); + transport + .get_inline_chunk("inline-statement", 1, 3, SessionAttribution::Current) + .await + .expect("owned inline chunk fetch must succeed"); + transport + .cancel_statement("statement-1") + .await + .expect("cancel must succeed"); + transport + .close_statement("statement-1") + .await + .expect("statement close must succeed"); + transport + .delete_session() + .await + .expect("session close must succeed"); + + server.verify().await; + let requests = server.received_requests().await.unwrap(); + let close = requests + .iter() + .find(|request| { + request.method == Method::DELETE + && request.url.path() + == "/api/2.0/sql/warehouses/warehouse-123/sessions/session-1" + }) + .expect("session close request must be recorded"); + assert!(close.url.query().is_none()); + assert!(requests + .iter() + .all(|request| request.headers.get(REALTIME_SESSION_HEADER).is_none())); + } + + #[tokio::test] + async fn create_session_response_selects_session_statement_urls() { + use wiremock::matchers::{body_json, method, path, query_param}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let cases = [(Some("TRUE"), true), (Some("false"), false), (None, false)]; + + for (header_value, realtime) in cases { + let server = MockServer::start().await; + let mut create_response = ResponseTemplate::new(200).set_body_json(json!({ + "session_id": "session-1", + })); + if let Some(value) = header_value { + create_response = create_response.insert_header(REALTIME_SESSION_HEADER, value); + } + + Mock::given(method("POST")) + .and(path("/api/2.0/sql/warehouses/warehouse-123/sessions")) + .and(body_json(json!({ "execution_mode": "FAST" }))) + .respond_with(create_response) + .expect(1) + .mount(&server) + .await; + let statement_path = if realtime { + "/api/2.0/sql/warehouses/warehouse-123/sessions/session-1/statements" + } else { + "/api/2.0/sql/statements" + }; + let mut statement_body = json!({ + "statement": "SELECT 1", + "disposition": "INLINE_OR_EXTERNAL_LINKS", + "format": "ARROW_STREAM", + "wait_timeout": "0s", + "on_wait_timeout": "CONTINUE", + "result_compression": "LZ4_FRAME", + }); + if !realtime { + statement_body["warehouse_id"] = json!("warehouse-123"); + statement_body["session_id"] = json!("session-1"); + } + Mock::given(method("POST")) + .and(path(statement_path)) + .and(body_json(statement_body)) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "statement_id": "statement-1", + "status": { "state": "PENDING" }, + }))) + .expect(1) + .mount(&server) + .await; + let close_path = if realtime { + "/api/2.0/sql/warehouses/warehouse-123/sessions/session-1" + } else { + "/api/2.0/sql/sessions/session-1" + }; + let mut close_mock = Mock::given(method("DELETE")).and(path(close_path)); + if !realtime { + close_mock = close_mock.and(query_param("warehouse_id", "warehouse-123")); + } + close_mock + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + + let transport = create_test_client_against(&server.uri()); + let session = transport + .create_session(None, None, HashMap::new()) + .await + .expect("session creation must succeed"); + transport + .submit_statement(&session.session_id, "SELECT 1", &ExecuteParams::default()) + .await + .expect("execute must succeed"); + transport + .delete_session() + .await + .expect("session close must succeed"); + + server.verify().await; + let requests = server.received_requests().await.unwrap(); + assert!(requests + .iter() + .any(|request| request.url.path() == statement_path)); + assert!(requests + .iter() + .any(|request| request.url.path() == close_path)); + } + } + + #[tokio::test] + async fn attached_dml_reads_use_standard_urls_without_advancing_session_version() { + use wiremock::matchers::{method, path, query_param}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/warehouses/warehouse-123/sessions")) + .respond_with( + ResponseTemplate::new(200) + .insert_header(REALTIME_SESSION_HEADER, "true") + .set_body_json(json!({ + "session_id": "session-1", + "session_version": { "version_id": 7 }, + })), + ) + .expect(1) + .mount(&server) + .await; + + let mut response: serde_json::Value = + serde_json::from_str(&succeeded_inline_dml_body("attached", 9)).unwrap(); + let mut chunk = response["result"].clone(); + chunk["chunk_index"] = json!(1); + let schema = Schema::new(vec![Field::new( + "num_affected_rows", + DataType::Int64, + false, + )]); + let mut empty_ipc = Vec::new(); + StreamWriter::try_new(&mut empty_ipc, &schema) + .unwrap() + .finish() + .unwrap(); + response["status"]["session_version"] = json!({ "version_id": 11 }); + response["manifest"]["total_chunk_count"] = json!(2); + response["result"]["attachment"] = json!(STANDARD.encode(&empty_ipc)); + response["result"]["row_count"] = json!(0); + response["result"]["next_chunk_index"] = json!(1); + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/attached")) + .respond_with(ResponseTemplate::new(200).set_body_json(response)) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/attached/result/chunks/1")) + .and(query_param("row_offset", "0")) + .respond_with(ResponseTemplate::new(200).set_body_json(chunk)) + .expect(1) + .mount(&server) + .await; + + let transport = create_ready_test_client_against(&server.uri(), TransportConfig::default()); + transport + .create_session(None, None, HashMap::new()) + .await + .expect("session creation must succeed"); + let status = transport + .get_statement_status("attached", SessionAttribution::Detached) + .await + .expect("attached status must succeed"); + + assert_eq!(status.status.num_modified_rows, Some(9)); + assert_eq!( + transport.current_session_version(), + Some(SessionVersion { version_id: 7 }) + ); + server.verify().await; + } + #[tokio::test] async fn exchanges_session_versions_on_create_and_execute() { use serde_json::json; @@ -2618,9 +3011,8 @@ mod tests { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/sql/warehouses/warehouse-123/sessions")) .and(body_json(json!({ - "warehouse_id": "warehouse-123", "execution_mode": "FAST", }))) .respond_with(ResponseTemplate::new(200).set_body_json(json!({ @@ -2725,7 +3117,7 @@ mod tests { let server = MockServer::start().await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/sql/warehouses/warehouse-123/sessions")) .respond_with( ResponseTemplate::new(200).set_body_string(r#"{"session_id":"session-1"}"#), ) @@ -2841,7 +3233,7 @@ mod tests { let transport = create_test_client_against(&server.uri()); let _ = transport - .get_result_chunks("01abc", 3, 100) + .get_result_chunks("01abc", 3, 100, SessionAttribution::Current) .await .expect("get_result_chunks must succeed against the mock"); @@ -2879,7 +3271,7 @@ mod tests { let transport = create_test_client_against(&server.uri()); let _ = transport - .get_result_chunks("01abc", 3, 0) + .get_result_chunks("01abc", 3, 0, SessionAttribution::Current) .await .expect("get_result_chunks must succeed against the mock"); diff --git a/src/client/transport.rs b/src/client/transport.rs index 4415f78d..8f58cfe7 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -298,8 +298,8 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug { session_config: HashMap, ) -> Result; - /// Delete/close a session. - async fn delete_session(&self, session_id: &str) -> Result<()>; + /// Close the session created by this transport. + async fn delete_session(&self) -> Result<()>; // --- Statement Execution --- @@ -398,6 +398,7 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug { statement_id: &str, chunk_index: i64, row_offset: i64, + session_attribution: SessionAttribution, ) -> Result; /// Fetch one inline-Arrow chunk by `chunk_index` (+ server-side @@ -419,6 +420,7 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug { statement_id: &str, chunk_index: i64, row_offset: i64, + session_attribution: SessionAttribution, ) -> Result; /// Polling cadence + ceiling the kernel should use when driving diff --git a/src/lib.rs b/src/lib.rs index 76c91b48..00340e94 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -149,7 +149,7 @@ pub use result_stream::{OwnedBatchIter, ResultBatch, ResultStream, Row, SchemaRe pub use session::{Session, SessionBuilder}; pub use statement::executed::ExecutedStatement; pub use statement::executed_async::{ - AsyncStatementCanceller, ExecutedAsyncStatement, StatementStatus, + AsyncStatementCanceller, AsyncStatementReader, ExecutedAsyncStatement, StatementStatus, }; pub use statement::handle::ExecutedStatementHandle; pub use statement::mutable::{DirectStatement, Statement, StatementCanceller}; @@ -175,6 +175,7 @@ const _: fn() = || { assert_send_sync::(); assert_send_sync::(); assert_send_sync::(); + assert_send_sync::(); assert_send_sync::(); assert_send_sync::(); @@ -216,6 +217,11 @@ const _: fn() = || { assert_send(&exec.await_result()); assert_send(&exec.fetch_result()); }; + let _: fn(&AsyncStatementReader) = |reader| { + assert_send(&reader.status()); + assert_send(&reader.await_result()); + assert_send(&reader.fetch_result()); + }; let _: fn(Session) = |session| { assert_send(&session.close()); }; diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 2ee9314a..c0fcf8ac 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -40,7 +40,7 @@ //! 3. Check if prefetch should be triggered (async, non-blocking) //! 4. Background task fetches links and caches them -use crate::client::{ChunkLinkFetchResult, Transport}; +use crate::client::{ChunkLinkFetchResult, SessionAttribution, Transport}; use crate::kernel_error::{Error, Result}; use crate::klog::{debug, error}; use crate::types::cloudfetch::CloudFetchLink; @@ -157,6 +157,7 @@ pub(crate) struct SeaChunkLinkFetcher { client: Arc, /// Statement ID this fetcher is bound to statement_id: String, + session_attribution: SessionAttribution, /// Cached links by chunk index links: DashMap, /// Next chunk index to ask the server for. Initialised from the @@ -365,6 +366,7 @@ impl SeaChunkLinkFetcher { total_chunk_count: Option, link_prefetch_window: i64, runtime_handle: tokio::runtime::Handle, + session_attribution: SessionAttribution, ) -> Self { let statement_id = statement_id.into(); let links = DashMap::new(); @@ -433,6 +435,7 @@ impl SeaChunkLinkFetcher { let fetcher = Self { client, statement_id, + session_attribution, links, next_server_fetch_index: AtomicI64::new(next_server_fetch_index), all_links_fetched: AtomicBool::new(all_links_fetched), @@ -747,7 +750,12 @@ impl SeaChunkLinkFetcher { match self .client - .get_result_chunks(&self.statement_id, server_fetch_idx, row_offset) + .get_result_chunks( + &self.statement_id, + server_fetch_idx, + row_offset, + self.session_attribution, + ) .await { Ok(result) => { @@ -940,7 +948,12 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle { ); let result = fetcher .client - .get_result_chunks(&fetcher.statement_id, start_chunk_index, start_row_offset) + .get_result_chunks( + &fetcher.statement_id, + start_chunk_index, + start_row_offset, + fetcher.session_attribution, + ) .await?; // Cache the new links. @@ -1003,7 +1016,12 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle { let result = self .inner .client - .get_result_chunks(&self.inner.statement_id, chunk_index, 0) + .get_result_chunks( + &self.inner.statement_id, + chunk_index, + 0, + self.inner.session_attribution, + ) .await?; let link = result @@ -1028,7 +1046,12 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle { let result = self .inner .client - .get_result_chunks(&self.inner.statement_id, chunk_index, row_offset) + .get_result_chunks( + &self.inner.statement_id, + chunk_index, + row_offset, + self.inner.session_attribution, + ) .await?; // The SEA contract today caps the number of links in a @@ -1127,7 +1150,7 @@ mod tests { }) } - async fn delete_session(&self, _session_id: &str) -> Result<()> { + async fn delete_session(&self) -> Result<()> { Ok(()) } @@ -1195,6 +1218,7 @@ mod tests { _statement_id: &str, chunk_index: i64, _row_offset: i64, + _session_attribution: SessionAttribution, ) -> Result { let index = chunk_index as usize; if index >= self.chunks.len() { @@ -1222,6 +1246,7 @@ mod tests { _statement_id: &str, _chunk_index: i64, _row_offset: i64, + _session_attribution: SessionAttribution, ) -> Result { unimplemented!("get_inline_chunk not used by the link-fetcher mock") } @@ -1391,6 +1416,7 @@ mod tests { None, 128, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); let handle = SeaChunkLinkFetcherHandle::new(fetcher); @@ -1427,6 +1453,7 @@ mod tests { None, 128, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); let handle = SeaChunkLinkFetcherHandle::new(fetcher); @@ -1451,6 +1478,7 @@ mod tests { None, 128, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); let handle = SeaChunkLinkFetcherHandle::new(fetcher); @@ -1477,6 +1505,7 @@ mod tests { None, 128, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); let handle = SeaChunkLinkFetcherHandle::new(fetcher); @@ -1499,6 +1528,7 @@ mod tests { None, 128, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); let handle = SeaChunkLinkFetcherHandle::new(fetcher); @@ -1535,6 +1565,7 @@ mod tests { None, 128, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); let handle = SeaChunkLinkFetcherHandle::new(fetcher); @@ -1566,6 +1597,7 @@ mod tests { None, 128, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); let handle = SeaChunkLinkFetcherHandle::new(fetcher); @@ -1601,6 +1633,7 @@ mod tests { None, 128, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); let handle = SeaChunkLinkFetcherHandle::new(fetcher); @@ -1651,6 +1684,7 @@ mod tests { None, 128, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); let handle = SeaChunkLinkFetcherHandle::new(fetcher); @@ -1679,6 +1713,7 @@ mod tests { None, 128, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); // Should be marked as all fetched since we have all chunks @@ -1711,6 +1746,7 @@ mod tests { None, 0, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); assert!( fetcher.all_links_fetched(), @@ -1743,6 +1779,7 @@ mod tests { None, /* link_prefetch_window = */ 0, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); // Wrap directly in the handle without triggering the prefetch // bell — `link_prefetch_window=0` keeps it idle anyway. @@ -1805,6 +1842,7 @@ mod tests { None, /* link_prefetch_window = */ 0, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); assert_eq!( fetcher.next_row_offset.load(Ordering::Acquire), @@ -1853,6 +1891,7 @@ mod tests { /* total_chunk_count = */ Some(2), 0, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); // Crucial: fetcher must NOT mark all_links_fetched at // construction even though the per-link signal would say so. @@ -1990,6 +2029,7 @@ mod tests { None, 0, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); assert!( fetcher.next_server_fetch_index.load(Ordering::Acquire) >= 6, @@ -2019,6 +2059,7 @@ mod tests { None, // total_chunk_count also absent 0, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); assert!( fetcher.silent_eos_warned.load(Ordering::Acquire), @@ -2044,6 +2085,7 @@ mod tests { Some(1), // total says we're at the last chunk 0, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); assert!( !fetcher.silent_eos_warned.load(Ordering::Acquire), @@ -2065,6 +2107,7 @@ mod tests { None, 0, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); // Each warn helper takes the swap-true path on first @@ -2097,6 +2140,7 @@ mod tests { Some(50), 0, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); // 10 × 50 = 500, but floor = 10_000 wins assert_eq!(with_small_total.runaway_prefetch_ceiling(), 10_000); @@ -2108,6 +2152,7 @@ mod tests { Some(5_000), 0, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); // 10 × 5_000 = 50_000 beats the floor assert_eq!(with_large_total.runaway_prefetch_ceiling(), 50_000); @@ -2119,6 +2164,7 @@ mod tests { None, 0, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); // No hint → hard floor only assert_eq!(without_total.runaway_prefetch_ceiling(), 10_000); @@ -2137,6 +2183,7 @@ mod tests { None, 0, tokio::runtime::Handle::current(), + SessionAttribution::Current, ); // Pre-seed the cursor to a high value (simulates a fast diff --git a/src/reader/inline/streaming.rs b/src/reader/inline/streaming.rs index 0ae25e2e..79a1c933 100644 --- a/src/reader/inline/streaming.rs +++ b/src/reader/inline/streaming.rs @@ -63,7 +63,7 @@ //! respectively. End-of-stream is the absence of `next_chunk_index` //! on a fetched chunk — never synthesised from `chunk_index + 1`. -use crate::client::{InlineChunkFetchResult, Transport}; +use crate::client::InlineChunkFetchResult; use crate::kernel_error::{Error, Result}; use crate::klog::{debug, error}; use crate::reader::cloudfetch::parse_arrow_ipc; @@ -80,8 +80,7 @@ use tracing::instrument; /// /// Lets the streaming provider depend on just the one method it /// needs (so tests don't have to build a full `Transport` mock with -/// `unreachable!()` for the 20-odd metadata RPCs). Production code -/// uses the blanket impl on `Arc`. +/// `unreachable!()` for the 20-odd metadata RPCs). #[async_trait] pub(crate) trait InlineChunkSource: Send + Sync + std::fmt::Debug { async fn get_inline_chunk( @@ -92,18 +91,6 @@ pub(crate) trait InlineChunkSource: Send + Sync + std::fmt::Debug { ) -> Result; } -#[async_trait] -impl InlineChunkSource for Arc { - async fn get_inline_chunk( - &self, - statement_id: &str, - chunk_index: i64, - row_offset: i64, - ) -> Result { - Transport::get_inline_chunk(self.as_ref(), statement_id, chunk_index, row_offset).await - } -} - /// One pre-decoded inline-Arrow chunk sitting in the rolling window. #[derive(Debug)] struct InlineChunkEntry { diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 3ee1e7c4..c9532fbf 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -25,7 +25,9 @@ pub mod post_processor; #[cfg(test)] pub(crate) mod test_utils; -use crate::client::{DatabricksHttpClient, ExecuteResponse, Transport}; +use crate::client::{ + DatabricksHttpClient, ExecuteResponse, InlineChunkFetchResult, SessionAttribution, Transport, +}; use crate::config::GeospatialResultRepresentation; use crate::kernel_error::{Error, Result}; use crate::reader::cloudfetch::chunk_downloader::ChunkDownloader; @@ -105,8 +107,9 @@ impl ResultReaderFactory { &self, statement_id: &str, response: &ExecuteResponse, + session_attribution: SessionAttribution, ) -> Result> { - let inner = self.create_inner_reader(statement_id, response)?; + let inner = self.create_inner_reader(statement_id, response, session_attribution)?; Ok(Box::new( ResultPostProcessor::new( inner, @@ -125,6 +128,7 @@ impl ResultReaderFactory { &self, statement_id: &str, response: &ExecuteResponse, + session_attribution: SessionAttribution, ) -> Result> { // Log manifest info for debugging if let Some(ref manifest) = response.manifest { @@ -216,6 +220,7 @@ impl ResultReaderFactory { external_links, total_chunk_count, compression, + session_attribution, ); } } @@ -330,6 +335,7 @@ impl ResultReaderFactory { Some(next_idx), compression, manifest_schema, + session_attribution, ); } @@ -517,6 +523,7 @@ impl ResultReaderFactory { external_links: &[CloudFetchLink], total_chunk_count: Option, compression: CompressionCodec, + session_attribution: SessionAttribution, ) -> Result> { crate::klog::debug!( statement_id, @@ -540,6 +547,7 @@ impl ResultReaderFactory { total_chunk_count, self.config.link_prefetch_window as i64, self.runtime_handle.clone(), + session_attribution, ); let link_fetcher: Arc = Arc::new(SeaChunkLinkFetcherHandle::new(fetcher)); @@ -602,6 +610,7 @@ impl ResultReaderFactory { next_chunk_index: Option, compression: CompressionCodec, manifest_schema: Option, + session_attribution: SessionAttribution, ) -> Result> { crate::klog::debug!( "Creating inline-Arrow streaming reader: stmt={}, initial_chunk={}, \ @@ -612,19 +621,11 @@ impl ResultReaderFactory { self.config.inline_max_chunks_in_memory, ); - // Note: `Arc::new(self.client.clone())` produces - // `Arc>` because the blanket impl of - // `InlineChunkSource` is on `Arc` (not on - // `dyn Transport`), and trait-objects of different traits - // don't share a vtable so direct coercion - // `Arc` → `Arc` - // isn't legal. The outer `Arc::new` is the price of using a - // narrow trait so test mocks don't have to stub the full - // 20-method `Transport` surface; net cost is one extra - // pointer + one extra deref per RPC, negligible vs the SEA - // round-trip. let source: Arc = - Arc::new(self.client.clone()); + Arc::new(AttributedInlineChunkSource { + client: Arc::clone(&self.client), + session_attribution, + }); let provider = InlineStreamingProvider::new( source, statement_id.to_string(), @@ -643,6 +644,31 @@ impl ResultReaderFactory { } } +#[derive(Debug)] +struct AttributedInlineChunkSource { + client: Arc, + session_attribution: SessionAttribution, +} + +#[async_trait] +impl inline::InlineChunkSource for AttributedInlineChunkSource { + async fn get_inline_chunk( + &self, + statement_id: &str, + chunk_index: i64, + row_offset: i64, + ) -> Result { + self.client + .get_inline_chunk( + statement_id, + chunk_index, + row_offset, + self.session_attribution, + ) + .await + } +} + /// Trait for result readers. /// /// Readers are `Send + Sync` so a `Box` can live @@ -1916,7 +1942,7 @@ mod tests { ) -> Result { unreachable!("PanickingTransport: not used by these tests") } - async fn delete_session(&self, _: &str) -> Result<()> { + async fn delete_session(&self) -> Result<()> { unreachable!() } async fn execute_statement( @@ -1958,7 +1984,13 @@ mod tests { ) -> Result { unreachable!() } - async fn get_result_chunks(&self, _: &str, _: i64, _: i64) -> Result { + async fn get_result_chunks( + &self, + _: &str, + _: i64, + _: i64, + _: SessionAttribution, + ) -> Result { unreachable!() } async fn get_inline_chunk( @@ -1966,6 +1998,7 @@ mod tests { _: &str, _: i64, _: i64, + _: SessionAttribution, ) -> Result { unreachable!() } @@ -2137,10 +2170,11 @@ mod tests { }), }; - let err = match factory.create_inner_reader("stmt-1", &response) { - Ok(_) => panic!("rollout-skew must surface as Err"), - Err(e) => e, - }; + let err = + match factory.create_inner_reader("stmt-1", &response, SessionAttribution::Current) { + Ok(_) => panic!("rollout-skew must surface as Err"), + Err(e) => e, + }; assert_eq!(err.code, ErrorCode::DataLoss); assert!( err.message.contains("total_chunk_count"), @@ -2178,7 +2212,7 @@ mod tests { }), }; - match factory.create_inner_reader("stmt-1", &response) { + match factory.create_inner_reader("stmt-1", &response, SessionAttribution::Current) { // OK or any non-rollout-guard error is acceptable — // we're proving the guard is *not* the failure mode. Ok(_) => {} @@ -2214,10 +2248,11 @@ mod tests { }), }; - let err = match factory.create_inner_reader("stmt-1", &response) { - Ok(_) => panic!("missing row_count on streaming response must surface as Err"), - Err(e) => e, - }; + let err = + match factory.create_inner_reader("stmt-1", &response, SessionAttribution::Current) { + Ok(_) => panic!("missing row_count on streaming response must surface as Err"), + Err(e) => e, + }; assert_eq!(err.code, ErrorCode::DataLoss); assert!( err.message.to_lowercase().contains("row_count"), @@ -2244,10 +2279,11 @@ mod tests { }), }; - let err = match factory.create_inner_reader("stmt-1", &response) { - Ok(_) => panic!("missing chunk_index on streaming response must surface as Err"), - Err(e) => e, - }; + let err = + match factory.create_inner_reader("stmt-1", &response, SessionAttribution::Current) { + Ok(_) => panic!("missing chunk_index on streaming response must surface as Err"), + Err(e) => e, + }; assert_eq!(err.code, ErrorCode::DataLoss); assert!( err.message.to_lowercase().contains("chunk_index"), @@ -2291,7 +2327,7 @@ mod tests { }; let mut reader = factory - .create_inner_reader("stmt-1", &response) + .create_inner_reader("stmt-1", &response, SessionAttribution::Current) .expect("zero-chunk manifest must succeed without parsing inline bytes"); assert!( reader.next_batch().await.unwrap().is_none(), @@ -2316,7 +2352,7 @@ mod tests { }; let mut reader = factory - .create_inner_reader("stmt-1", &response) + .create_inner_reader("stmt-1", &response, SessionAttribution::Current) .expect("absent total_chunk_count + Succeeded state must yield empty reader"); assert!(reader.next_batch().await.unwrap().is_none()); } @@ -2351,7 +2387,7 @@ mod tests { // a parse error. If the short-circuit had fired, this would // return `Ok` and we'd never reach the IPC parser. let err = factory - .create_inner_reader("stmt-1", &response) + .create_inner_reader("stmt-1", &response, SessionAttribution::Current) .err() .expect("non-zero total_chunk_count + garbage inline must surface parse error"); assert!( diff --git a/src/session.rs b/src/session.rs index 8a8ae6f0..72d63d64 100644 --- a/src/session.rs +++ b/src/session.rs @@ -239,9 +239,8 @@ impl SessionInner { return; // already closed / closing } let transport = Arc::clone(&self.transport); - let session_id = self.session_id.clone(); self.runtime_handle.spawn(async move { - let _ = transport.delete_session(&session_id).await; + let _ = transport.delete_session().await; }); } } @@ -669,19 +668,20 @@ impl Session { } /// Adopt an already-submitted server statement by its id, producing - /// an [`ExecutedAsyncStatement`] that can poll [`status`] / await - /// results / cancel — without having been the handle that submitted - /// it. + /// an [`ExecutedAsyncStatement`] that can poll [`status`] and fetch + /// results without having been the handle that submitted it. /// /// This is the resume path: a caller (or a different process) that /// holds only the statement id can re-attach and drive it to - /// completion, fetch its result, or read its terminal state. Server - /// statement state is keyed solely by the id — every - /// `GetStatementStatus` / `GetStatementResult` / cancel / close RPC - /// takes just the id — so the only thing the originating handle - /// carried that a bare id does not is *this session's* transport - /// (auth, retry, poll cadence). Binding the id to this session is - /// exactly what `attach` does. + /// completion, fetch its result, or read its terminal state. + /// Attached reads use standard SQL URLs because the statement ID does not + /// identify its originating session. + /// + /// Lakehouse Real-Time supports asynchronous execution through the handle + /// returned by [`Statement::submit`]. Retain that handle for polling and result + /// fetching, or derive independent readers with [`ExecutedAsyncStatement::reader`]. + /// Polling or fetching a Lakehouse Real-Time statement from another session + /// is not supported. /// /// Issues a single `GetStatementStatus` to seed the handle's initial /// status (mirrors how `submit` seeds it from the submit response), @@ -790,12 +790,7 @@ impl Session { async { let telemetry = self.inner.telemetry.connection(); let delete_started = Instant::now(); - if let Err(error) = self - .inner - .transport - .delete_session(&self.inner.session_id) - .await - { + if let Err(error) = self.inner.transport.delete_session().await { telemetry.emit_operation( OperationType::DeleteSession, delete_started.elapsed(), @@ -2119,12 +2114,11 @@ mod is_open_tests { use wiremock::{Mock, MockServer, ResponseTemplate}; #[tokio::test] - async fn sessions_enable_version_exchange_on_standard_path() { + async fn sessions_enable_version_exchange() { 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")) .and(body_json(json!({ - "warehouse_id": "test_wh", "execution_mode": "FAST", }))) .respond_with(ResponseTemplate::new(200).set_body_json(json!({ @@ -2149,7 +2143,7 @@ mod is_open_tests { }) .open() .await - .expect("FAST session must open on the standard path"); + .expect("FAST session must open"); session.close().await.expect("FAST session must close"); } @@ -2166,7 +2160,7 @@ mod is_open_tests { async fn is_open_flips_true_to_false_on_delete() { 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-is-open","warehouse_id":"test_wh"}"#), @@ -2217,7 +2211,7 @@ mod is_open_tests { 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-test-conn","warehouse_id":"test_wh"}"#), @@ -2309,7 +2303,7 @@ mod is_open_tests { async fn test_connection_fails_when_server_unreachable() { 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-dead","warehouse_id":"test_wh"}"#), @@ -2360,7 +2354,7 @@ mod is_open_tests { async fn transaction_controls_are_noop_when_ignored() { 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-txn","warehouse_id":"test_wh"}"#), @@ -2551,7 +2545,7 @@ mod is_open_tests { .iter() .position(|request| { request.method.as_str() == "POST" - && request.url.path() == "/api/2.0/sql/sessions" + && request.url.path() == "/api/2.0/sql/warehouses/test_wh/sessions" }) .expect("CreateSession must be sent"); assert!( @@ -2581,7 +2575,8 @@ mod is_open_tests { let create_session_requests = requests .iter() .filter(|request| { - request.method.as_str() == "POST" && request.url.path() == "/api/2.0/sql/sessions" + request.method.as_str() == "POST" + && request.url.path() == "/api/2.0/sql/warehouses/test_wh/sessions" }) .count(); assert_eq!(feature_flag_requests, 1, "sessions share the flag cache"); @@ -2894,6 +2889,17 @@ mod is_open_tests { stmt.spec().sql("SELECT 1 AS n"); let async_exec = stmt.submit().await.expect("submit succeeds"); let _ = async_exec.status().await.expect("status succeeds"); + let reader = async_exec.reader().expect("reader"); + let _ = reader.status().await.expect("reader status"); + let mut read_stream = reader.await_result().await.expect("reader result"); + while read_stream + .next_batch() + .await + .expect("reader batch") + .is_some() + {} + drop(read_stream); + drop(reader); let mut stream = async_exec.await_result().await.expect("await succeeds"); assert!(stream.next_batch().await.expect("first batch").is_some()); assert!(stream @@ -2919,12 +2925,10 @@ mod is_open_tests { statement_log["entry"]["sql_driver_log"]["sql_statement_id"], "stmt-telemetry-async" ); - assert!( - detail["n_operation_status_calls"] - .as_i64() - .unwrap_or_default() - >= 2, - "status() plus await_result() should record status polls" + assert_eq!( + detail["n_operation_status_calls"].as_i64(), + Some(2), + "only owning status and await polls contribute to execution telemetry" ); assert!( detail["operation_status_latency_millis"] @@ -3555,7 +3559,7 @@ mod is_open_tests { async fn mount_session_create_delete(server: &MockServer, session_id: &str) { 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(format!( r#"{{"session_id":"{session_id}","warehouse_id":"test_wh"}}"# ))) diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 78afc2b1..59b8379e 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -182,6 +182,8 @@ pub struct ExecutedAsyncStatement { /// short-circuited) `close()`. Tells `Drop` to skip its /// fire-and-forget cleanup. closed: Arc, + /// Server auto-close can retain results, so owner release has a separate flag. + owner_released: Arc, /// Whether this handle *owns* the server statement's lifecycle. /// /// `true` for handles produced by [`Statement::submit`] (the @@ -199,6 +201,7 @@ pub struct ExecutedAsyncStatement { /// server-side cancel. (`Drop` / `close()` are already inert on /// attached handles via `closed=true`.) owning: bool, + session_attribution: SessionAttribution, /// Last SEA `StatementStatus` observed by this handle (initial /// `submit_statement` response or any subsequent `status()` / /// `await_result` poll). Read by the `num_modified_rows()` / @@ -275,6 +278,7 @@ impl ExecutedAsyncStatement { /// best-effort server cleanup when a deadline retained across /// caller-driven status polls expires. pub(crate) fn expire_client_query_timeout(&self) -> Error { + self.owner_released.store(true, Ordering::Release); if !self.client_timeout_expired.swap(true, Ordering::AcqRel) { self.session .dispatch_timeout_cleanup(Some(self.statement_id.clone())); @@ -284,14 +288,6 @@ impl ExecutedAsyncStatement { error } - fn session_attribution(&self) -> SessionAttribution { - if self.owning { - SessionAttribution::Current - } else { - SessionAttribution::Detached - } - } - /// Crate-internal constructor. Built by [`Statement::submit`]. /// /// `closed` is shared with the parent [`Statement`] so flipping it @@ -330,8 +326,10 @@ impl ExecutedAsyncStatement { statement_id, valid, closed, + owner_released: Arc::new(AtomicBool::new(false)), // The submitting handle owns the statement lifecycle. owning: true, + session_attribution: SessionAttribution::Current, latest_status: Arc::new(std::sync::Mutex::new(initial_status)), statement_telemetry, result_stream_owns_success_telemetry: AtomicBool::new(false), @@ -363,14 +361,34 @@ impl ExecutedAsyncStatement { session: Arc, statement_id: String, initial_status: crate::types::sea::StatementStatus, + ) -> Self { + Self::new_read_only( + session, + statement_id, + ValidityFlag::new(), + Arc::new(AtomicBool::new(false)), + SessionAttribution::Detached, + initial_status, + ) + } + + fn new_read_only( + session: Arc, + statement_id: String, + valid: ValidityFlag, + owner_released: Arc, + session_attribution: SessionAttribution, + initial_status: crate::types::sea::StatementStatus, ) -> Self { let initial_terminal = initial_status.state.is_terminal(); Self { session, statement_id, - valid: ValidityFlag::new(), + valid, closed: Arc::new(AtomicBool::new(true)), + owner_released, owning: false, + session_attribution, latest_status: Arc::new(std::sync::Mutex::new(initial_status)), statement_telemetry: StatementTelemetry::noop(), result_stream_owns_success_telemetry: AtomicBool::new(false), @@ -381,6 +399,44 @@ impl ExecutedAsyncStatement { } } + /// Create an independent [`AsyncStatementReader`] without a server request. + pub fn reader(&self) -> Result { + self.valid.check()?; + self.check_owner_available()?; + let status = self + .latest_status + .lock() + .map_err(|error| Error::internal().message(format!("Statement status lock: {error}")))? + .clone(); + Ok(AsyncStatementReader { + inner: Self::new_read_only( + Arc::clone(&self.session), + self.statement_id.clone(), + self.valid.clone(), + Arc::clone(&self.owner_released), + self.session_attribution, + status, + ), + }) + } + + fn check_owner_available(&self) -> Result<()> { + if self.owner_released.load(Ordering::Acquire) { + return Err(Error::invalid_statement_handle() + .message("the owning asynchronous statement has been closed or dropped") + .with_query_id(&self.statement_id)); + } + Ok(()) + } + + fn check_read_validity(&self) -> Result<()> { + self.valid.check()?; + if !self.owning { + self.check_owner_available()?; + } + Ok(()) + } + /// Number of rows modified by the statement (UPDATE / INSERT / /// DELETE / MERGE). Reflects the most recent SEA /// `StatementStatus` this handle has seen (initial submit @@ -500,7 +556,7 @@ impl ExecutedAsyncStatement { pub async fn status(&self) -> Result { let span = self.session.log_span().clone(); let result = async { - self.valid.check()?; + self.check_read_validity()?; // The client deadline governs only the pre-terminal window // ("initial submit through observed terminal status"). Once // this handle has observed a terminal state, `status()` @@ -521,7 +577,7 @@ impl ExecutedAsyncStatement { let poll = self .session .transport() - .statement_status(&self.statement_id, self.session_attribution()); + .statement_status(&self.statement_id, self.session_attribution); let response = match self.client_deadline { Some(deadline) if enforce_deadline => { let poll_deadline = deadline @@ -539,6 +595,7 @@ impl ExecutedAsyncStatement { } _ => poll.await?, }; + self.check_read_validity()?; self.statement_telemetry .record_poll(status_started.elapsed()); // Cache the wire status so the extended-field accessors @@ -603,7 +660,7 @@ impl ExecutedAsyncStatement { pub async fn await_result(&self) -> Result { let span = self.session.log_span().clone(); let result = async { - self.valid.check()?; + self.check_read_validity()?; let cfg = self.session.transport().poll_config(); let start = std::time::Instant::now(); @@ -630,7 +687,7 @@ impl ExecutedAsyncStatement { }; loop { - self.valid.check()?; + self.check_read_validity()?; // The client deadline governs only the pre-terminal // window. Once this handle has observed a terminal state // (here or via a prior `status()` / initial-submit @@ -655,7 +712,7 @@ impl ExecutedAsyncStatement { let poll = self .session .transport() - .statement_status(&self.statement_id, self.session_attribution()); + .statement_status(&self.statement_id, self.session_attribution); let response = match self.client_deadline { Some(deadline) if enforce_deadline => { let poll_deadline = deadline @@ -680,6 +737,7 @@ impl ExecutedAsyncStatement { } _ => poll.await?, }; + self.check_read_validity()?; self.statement_telemetry .record_poll(status_started.elapsed()); // Cache the wire status so the extended-field @@ -767,12 +825,7 @@ impl ExecutedAsyncStatement { /// when the caller has already confirmed completion themselves. pub async fn fetch_result(&self) -> Result { let span = self.session.log_span().clone(); - let result = async { - self.valid.check()?; - self.materialise_result().await - } - .instrument(span) - .await; + let result = self.materialise_result().instrument(span).await; if let Err(error) = &result { self.statement_telemetry.finalize(Some(error)); } @@ -785,12 +838,14 @@ impl ExecutedAsyncStatement { /// status so callers don't have to re-query, and points at the /// actionable follow-up. async fn materialise_result(&self) -> Result { - match self + self.check_read_validity()?; + let result = self .session .transport() - .fetch_completed_result(&self.statement_id, self.session_attribution()) - .await? - { + .fetch_completed_result(&self.statement_id, self.session_attribution) + .await?; + self.check_read_validity()?; + match result { Some(result) => { self.statement_telemetry.on_result_metadata( result.telemetry_result_format, @@ -824,6 +879,7 @@ impl ExecutedAsyncStatement { } } } + self.check_read_validity()?; self.result_stream_owns_success_telemetry .store(true, Ordering::Release); Ok(stream) @@ -836,7 +892,7 @@ impl ExecutedAsyncStatement { let observed = match self .session .transport() - .statement_status(&self.statement_id, self.session_attribution()) + .statement_status(&self.statement_id, self.session_attribution) .await { Ok(r) => match r.status.state { @@ -846,6 +902,7 @@ impl ExecutedAsyncStatement { }, Err(_) => "non-terminal", }; + self.check_read_validity()?; Err(Error::invalid_state().message(format!( "Statement {} is not terminal yet (status: {}); call await_result() to \ block until done, or poll status() and re-call fetch_result() once it \ @@ -857,6 +914,43 @@ impl ExecutedAsyncStatement { } } +/// Independent read access to an asynchronous statement, created by +/// [`ExecutedAsyncStatement::reader`]. +/// +/// Session attribution is inherited from the source handle, including unknown +/// attribution for ID-only attachments. The reader shares parent-statement +/// invalidation but has independent status and result state. It does not inherit +/// the execution deadline or emit execution telemetry. Dropping a reader never +/// cancels or closes the statement; the owner controls its server lifetime. +/// Derived readers become invalid when the owner closes, drops, or starts timeout cleanup. +pub struct AsyncStatementReader { + inner: ExecutedAsyncStatement, +} + +impl AsyncStatementReader { + pub fn statement_id(&self) -> &str { + &self.inner.statement_id + } + + /// Read the current server status. See [`ExecutedAsyncStatement::status`]. + pub async fn status(&self) -> Result { + self.inner.status().await + } + + /// Poll until terminal and return a fresh result stream. + /// + /// The session's polling timeout applies to this read. Timing out or + /// dropping the future leaves the server statement running. + pub async fn await_result(&self) -> Result { + self.inner.await_result().await + } + + /// Return a fresh result stream, or `InvalidState` if execution is not terminal. + pub async fn fetch_result(&self) -> Result { + self.inner.fetch_result().await + } +} + /// RAII guard that fires a fire-and-forget `cancel_statement` on /// drop unless [`defuse`](AwaitResultCancelGuard::defuse) was called. /// @@ -959,6 +1053,9 @@ impl ExecutedAsyncStatement { } async fn close_server_statement(&self) -> Result<()> { + if self.owning { + self.owner_released.store(true, Ordering::Release); + } // Idempotent on success: a prior successful close sets // `closed=true` and subsequent calls short-circuit. // @@ -1081,6 +1178,9 @@ impl AsyncStatementCanceller { impl Drop for ExecutedAsyncStatement { fn drop(&mut self) { + if self.owning { + self.owner_released.store(true, Ordering::Release); + } // Ensure submit-and-drop / status-only async statements still // emit one terminal telemetry event. Once a result stream has // been returned, that stream owns success finalization so it can diff --git a/src/statement/mod.rs b/src/statement/mod.rs index 2c20d9a9..4f2f92df 100644 --- a/src/statement/mod.rs +++ b/src/statement/mod.rs @@ -40,7 +40,9 @@ pub(crate) mod validity; // of the deeper submodule paths. The crate-root re-exports in `lib.rs` // also resolve here, so both paths work. pub use executed::ExecutedStatement; -pub use executed_async::{AsyncStatementCanceller, ExecutedAsyncStatement, StatementStatus}; +pub use executed_async::{ + AsyncStatementCanceller, AsyncStatementReader, ExecutedAsyncStatement, StatementStatus, +}; pub use handle::ExecutedStatementHandle; pub use mutable::{DirectStatement, Statement, StatementCanceller}; pub use spec::{ResultFormat, StatementSpec, TypedValue}; diff --git a/src/types/sea.rs b/src/types/sea.rs index 177b987e..977a7b02 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -382,7 +382,8 @@ pub struct QueryTag { /// Request body for statement execution. #[derive(Debug, Clone, Serialize)] pub struct ExecuteStatementRequest { - pub warehouse_id: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub warehouse_id: Option, pub statement: String, #[serde(skip_serializing_if = "Option::is_none")] pub session_id: Option, @@ -473,7 +474,8 @@ pub struct SessionVersion { /// Request body for session creation. #[derive(Debug, Clone, Serialize)] pub struct CreateSessionRequest { - pub warehouse_id: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub warehouse_id: Option, #[serde(skip_serializing_if = "Option::is_none")] pub catalog: Option, #[serde(skip_serializing_if = "Option::is_none")] @@ -556,7 +558,7 @@ mod tests { let mut confs = HashMap::new(); confs.insert("USE_CACHED_RESULT".to_string(), "false".to_string()); let req = CreateSessionRequest { - warehouse_id: "wh-1".to_string(), + warehouse_id: None, catalog: None, schema: None, session_confs: confs, @@ -585,7 +587,7 @@ mod tests { #[test] fn test_execute_statement_request_serialization() { let req = ExecuteStatementRequest { - warehouse_id: "abc123".to_string(), + warehouse_id: Some("abc123".to_string()), statement: "SELECT 1".to_string(), session_id: Some("session-1".to_string()), session_version: None, @@ -612,7 +614,7 @@ mod tests { #[test] fn test_execute_statement_request_serializes_query_tags_as_array() { let req = ExecuteStatementRequest { - warehouse_id: "abc123".to_string(), + warehouse_id: Some("abc123".to_string()), statement: "SELECT 1".to_string(), session_id: Some("session-1".to_string()), session_version: None, diff --git a/tests/klog_bridge.rs b/tests/klog_bridge.rs index efd36c7a..80612026 100644 --- a/tests/klog_bridge.rs +++ b/tests/klog_bridge.rs @@ -159,7 +159,7 @@ async fn empty_logging_config_open_does_not_install_subscriber() { 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-gate-213","warehouse_id":"test_wh"}"#), diff --git a/tests/token_federation_wiremock.rs b/tests/token_federation_wiremock.rs index 086f6fe3..50c008b7 100644 --- a/tests/token_federation_wiremock.rs +++ b/tests/token_federation_wiremock.rs @@ -227,7 +227,7 @@ async fn auth_config_federation_client_id_reaches_exchange() { .mount(&server) .await; Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) + .and(path("/api/2.0/sql/warehouses/warehouse-id/sessions")) .and(header("authorization", "Bearer wif-token")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "session_id": "session-id", diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index 82675e24..18d53cbd 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -15,7 +15,7 @@ //! Wiremock tests for the v0 `Statement::submit` / `ExecutedAsyncStatement` //! path. //! -//! Each test stubs SEA's `POST /sessions`, `POST /statements`, and the +//! Each test stubs SEA's `CreateSession`, `POST /statements`, and the //! `GET /statements/{id}` / `POST /statements/{id}/cancel` / //! `DELETE /statements/{id}` endpoints as needed, then drives a //! `Statement::submit()` through the async pipeline: @@ -55,7 +55,7 @@ async fn open_session(server: &MockServer) -> Session { async fn mount_create_session(server: &MockServer) { 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-test","warehouse_id":"test_wh"}"#), @@ -375,9 +375,8 @@ async fn submit_returns_pending_handle_without_polling() { async fn owning_async_status_advances_session_version_for_next_execute() { 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")) .and(body_json(json!({ - "warehouse_id": "test_wh", "execution_mode": "FAST", }))) .respond_with(ResponseTemplate::new(200).set_body_json(json!({ @@ -642,6 +641,7 @@ async fn re_submit_invalidates_prior_async_handle() { stmt.spec().sql("SELECT 1"); let async_exec_x = stmt.submit().await.expect("submit X"); assert_eq!(async_exec_x.statement_id(), "stmt-X"); + let reader = async_exec_x.reader().expect("reader"); // Re-submit invalidates async_exec_x. let _async_exec_y = stmt.submit().await.expect("submit Y"); @@ -650,6 +650,22 @@ async fn re_submit_invalidates_prior_async_handle() { .await .expect_err("stale async handle cancel must fail"); assert_eq!(err.code, ErrorCode::InvalidStatementHandle); + assert_eq!( + reader.status().await.unwrap_err().code, + ErrorCode::InvalidStatementHandle + ); + assert_eq!( + reader.await_result().await.err().unwrap().code, + ErrorCode::InvalidStatementHandle + ); + assert_eq!( + reader.fetch_result().await.err().unwrap().code, + ErrorCode::InvalidStatementHandle + ); + assert_eq!( + async_exec_x.reader().err().unwrap().code, + ErrorCode::InvalidStatementHandle + ); } #[tokio::test] @@ -1375,6 +1391,354 @@ async fn async_await_result_cancelled_carries_extended_status_fields_onto_error( let _ = ErrorCode::SqlError; // silence unused-import warning if the assert above changes } +#[tokio::test] +async fn async_readers_preserve_session_routes() { + use wiremock::matchers::{body_partial_json, query_param}; + + for (realtime, cloudfetch) in [(false, false), (false, true), (true, false), (true, true)] { + let server = MockServer::start().await; + let session_prefix = if realtime { + "/api/2.0/sql/warehouses/test_wh/sessions/sess-test" + } else { + "/api/2.0/sql" + }; + let mut create_response = + ResponseTemplate::new(200).set_body_json(json!({ "session_id": "sess-test" })); + if realtime { + create_response = create_response.insert_header("x-databricks-rt-session", "true"); + } + Mock::given(method("POST")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) + .respond_with(create_response) + .expect(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path(format!("{session_prefix}/statements"))) + .and(body_partial_json(json!({ "wait_timeout": "0s" }))) + .respond_with(ResponseTemplate::new(200).set_body_string(pending_body("stmt-result"))) + .expect(1) + .mount(&server) + .await; + + let batches = [int64_batch("n", vec![1, 2]), int64_batch("n", vec![3, 4])]; + let mut response: serde_json::Value = + serde_json::from_str(&succeeded_inline_body("stmt-result", &batches[0])).unwrap(); + response["manifest"]["total_chunk_count"] = json!(2); + response["manifest"]["total_row_count"] = json!(4); + response["result"]["next_chunk_index"] = json!(1); + let mut continuation = json!({ + "chunk_index": 1, + "row_offset": 2, + "row_count": 2, + "attachment": STANDARD.encode(arrow_ipc_bytes(&batches[1])), + }); + if cloudfetch { + let mut links = Vec::new(); + for (index, batch) in batches.iter().enumerate() { + let bytes = arrow_ipc_bytes(batch); + let chunk_path = format!("/cloud-fetch/chunk-{index}.arrow"); + links.push(json!({ + "external_link": format!("{}{chunk_path}", server.uri()), + "expiration": "2099-01-01T00:00:00.000Z", + "chunk_index": index, + "row_offset": index * 2, + "row_count": 2, + "byte_count": bytes.len(), + "next_chunk_index": if index == 0 { Some(1) } else { None }, + })); + Mock::given(method("GET")) + .and(path(chunk_path)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) + .expect(3) + .mount(&server) + .await; + } + Mock::given(method("GET")) + .and(path(format!( + "{session_prefix}/statements/stmt-result/result/chunks/0" + ))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "external_links": [links[0].clone()], + }))) + .expect(3) + .mount(&server) + .await; + let mut expired_link = links[0].clone(); + expired_link["external_link"] = json!(format!("{}/expired-link", server.uri())); + expired_link["expiration"] = json!("2000-01-01T00:00:00.000Z"); + response["result"] = json!({ "external_links": [expired_link] }); + continuation = json!({ "external_links": [links[1].clone()] }); + } + Mock::given(method("GET")) + .and(path(format!("{session_prefix}/statements/stmt-result"))) + .respond_with(ResponseTemplate::new(200).set_body_json(&response)) + .expect(7) + .mount(&server) + .await; + let chunk_mock = Mock::given(method("GET")).and(path(format!( + "{session_prefix}/statements/stmt-result/result/chunks/1" + ))); + let chunk_mock = if cloudfetch { + chunk_mock + } else { + chunk_mock.and(query_param("row_offset", "2")) + }; + chunk_mock + .respond_with(ResponseTemplate::new(200).set_body_json(&continuation)) + .expect(1..) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path(format!("{session_prefix}/statements/stmt-result"))) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path(if realtime { + session_prefix.to_string() + } else { + format!("{session_prefix}/sessions/sess-test") + })) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + + let session = open_session(&server).await; + let mut statement = session.statement(); + statement.spec().sql("SELECT n FROM range(1, 5) AS t(n)"); + let owned = statement.submit().await.expect("owned submit"); + let owned_stream = owned.await_result().await.expect("owned result"); + let reader = owned.reader().expect("reader"); + let refetch = owned.reader().expect("refetch reader"); + assert_eq!(reader.statement_id(), owned.statement_id()); + let (reader_status, owned_status) = tokio::join!(reader.status(), owned.status()); + assert!(matches!(reader_status.unwrap(), StatementStatus::Succeeded)); + assert!(matches!(owned_status.unwrap(), StatementStatus::Succeeded)); + let (read_stream, refetch_stream) = + tokio::join!(reader.await_result(), refetch.fetch_result()); + for mut stream in [owned_stream, read_stream.unwrap(), refetch_stream.unwrap()] { + let fetched = drain(&mut stream).await; + assert_eq!(fetched.len(), 2); + let values: Vec = fetched + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_primitive::() + .values() + .iter() + .copied() + }) + .collect(); + assert_eq!(values, vec![1, 2, 3, 4]); + } + drop(reader); + drop(refetch); + owned.close().await.expect("owned close"); + session.close().await.expect("session close"); + server.verify().await; + } +} + +#[tokio::test] +async fn owner_release_invalidates_readers() { + use std::time::Duration; + use tokio::sync::Notify; + + for close_owner in [true, false] { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_submit(&server, pending_body("stmt-reader")).await; + let polled = Arc::new(Notify::new()); + let notify = Arc::clone(&polled); + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/stmt-reader")) + .respond_with(move |_: &wiremock::Request| { + notify.notify_one(); + ResponseTemplate::new(200).set_body_string(running_body("stmt-reader")) + }) + .expect(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/stmt-reader/cancel")) + .respond_with(ResponseTemplate::new(200)) + .expect(0) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/statements/stmt-reader")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + + let session = open_session(&server).await; + let mut statement = session.statement(); + statement.spec().sql("SELECT 1"); + let mut owner = Some(statement.submit().await.unwrap()); + let reader = owner.as_ref().unwrap().reader().unwrap(); + let release_owner = async { + polled.notified().await; + if close_owner { + let owner = owner.as_mut().unwrap(); + owner.close().await.unwrap(); + assert_eq!( + owner.reader().err().unwrap().code, + ErrorCode::InvalidStatementHandle + ); + } else { + drop(owner.take()); + } + }; + let (result, ()) = tokio::time::timeout(Duration::from_secs(5), async { + tokio::join!(reader.await_result(), release_owner) + }) + .await + .expect("reader stops polling after owner release"); + assert_eq!( + result.err().unwrap().code, + ErrorCode::InvalidStatementHandle + ); + for result in [ + reader.status().await.map(|_| ()), + reader.await_result().await.map(|_| ()), + reader.fetch_result().await.map(|_| ()), + ] { + assert_eq!(result.unwrap_err().code, ErrorCode::InvalidStatementHandle); + } + assert_eq!( + wait_for_close_delete(&server, "stmt-reader", 1, Duration::from_secs(5)).await, + 1 + ); + statement.close().await.unwrap(); + session.close().await.unwrap(); + server.verify().await; + } +} + +#[tokio::test] +async fn owner_query_timeout_invalidates_readers() { + use std::time::Duration; + + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + mount_submit(&server, pending_body("stmt-reader-timeout")).await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/stmt-reader-timeout")) + .respond_with( + ResponseTemplate::new(200).set_body_string(closed_body("stmt-reader-timeout")), + ) + .expect(0) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/stmt-reader-timeout/cancel")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .expect(1) + .mount(&server) + .await; + + let session = open_session(&server).await; + let mut statement = session.statement(); + statement.spec().sql("SELECT 1"); + let owner = statement + .submit_with_timeout(Duration::from_secs(1)) + .await + .unwrap(); + let reader = owner.reader().unwrap(); + + tokio::time::sleep(Duration::from_secs(1)).await; + let error = owner.status().await.unwrap_err(); + assert_eq!(error.code, ErrorCode::Timeout); + assert_eq!(error.sql_state.as_deref(), Some("HYT00")); + assert_eq!( + owner.reader().err().unwrap().code, + ErrorCode::InvalidStatementHandle + ); + for result in [ + reader.status().await.map(|_| ()), + reader.await_result().await.map(|_| ()), + reader.fetch_result().await.map(|_| ()), + ] { + assert_eq!(result.unwrap_err().code, ErrorCode::InvalidStatementHandle); + } + let error = owner.await_result().await.err().unwrap(); + assert_eq!(error.code, ErrorCode::Timeout); + assert_eq!(error.sql_state.as_deref(), Some("HYT00")); + assert_eq!( + wait_for_close_delete(&server, "stmt-reader-timeout", 1, Duration::from_secs(5)).await, + 1 + ); + + owner.close().await.unwrap(); + statement.close().await.unwrap(); + session.close().await.unwrap(); + server.verify().await; +} + +#[tokio::test] +async fn reader_timeout_and_drop_leave_statement_owned() { + use std::time::Duration; + + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_submit(&server, pending_body("stmt-reader")).await; + mount_status_once(&server, "stmt-reader", running_body("stmt-reader")).await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/stmt-reader/cancel")) + .respond_with(ResponseTemplate::new(200)) + .expect(0) + .mount(&server) + .await; + + let session = open_session(&server).await; + let mut statement = session.statement(); + statement.spec().sql("SELECT 1"); + let owned = statement + .submit_with_timeout(Duration::from_secs(1)) + .await + .unwrap(); + let reader = owned.reader().unwrap(); + let no_close = Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/statements/stmt-reader")) + .respond_with(ResponseTemplate::new(200)) + .expect(0) + .mount_as_scoped(&server) + .await; + + tokio::time::sleep(Duration::from_secs(1)).await; + assert!(matches!( + reader.status().await.unwrap(), + StatementStatus::Running + )); + assert!( + tokio::time::timeout(Duration::from_millis(100), reader.await_result()) + .await + .is_err() + ); + drop(reader); + tokio::time::sleep(Duration::from_millis(150)).await; + drop(no_close); + + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/statements/stmt-reader")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + owned.close().await.unwrap(); + session.close().await.unwrap(); + server.verify().await; +} + // ─── attach_async_statement (resume-by-id) ────────────────────────── #[tokio::test] @@ -1398,6 +1762,211 @@ async fn attach_seeds_status_and_reports_server_state() { assert!(matches!(status, StatementStatus::Running), "{status:?}"); } +#[tokio::test] +async fn attached_statement_inline_reads_use_standard_urls() { + use wiremock::matchers::query_param; + + for realtime in [true, false] { + let server = MockServer::start().await; + let mut create_response = + ResponseTemplate::new(200).set_body_json(json!({ "session_id": "sess-test" })); + if realtime { + create_response = create_response.insert_header("x-databricks-rt-session", "true"); + } + Mock::given(method("POST")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) + .respond_with(create_response) + .expect(1) + .mount(&server) + .await; + + let session_prefix = if realtime { + "/api/2.0/sql/warehouses/test_wh/sessions/sess-test" + } else { + "/api/2.0/sql" + }; + let first_batch = int64_batch("n", vec![1, 2]); + let last_batch = int64_batch("n", vec![3, 4]); + let mut status: serde_json::Value = + serde_json::from_str(&succeeded_inline_body("stmt-attach", &first_batch)).unwrap(); + status["manifest"]["total_chunk_count"] = json!(2); + status["manifest"]["total_row_count"] = json!(4); + status["result"]["next_chunk_index"] = json!(1); + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/stmt-attach")) + .respond_with(ResponseTemplate::new(200).set_body_json(status)) + .expect(3) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/stmt-attach/result/chunks/1")) + .and(query_param("row_offset", "2")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "chunk_index": 1, + "row_offset": 2, + "row_count": 2, + "attachment": STANDARD.encode(arrow_ipc_bytes(&last_batch)), + }))) + .expect(1) + .mount(&server) + .await; + let close_path = if realtime { + session_prefix.to_string() + } else { + format!("{session_prefix}/sessions/sess-test") + }; + Mock::given(method("DELETE")) + .and(path(close_path)) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path(format!("{session_prefix}/statements"))) + .respond_with(ResponseTemplate::new(200).set_body_string(pending_body("stmt-owned"))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path(format!("{session_prefix}/statements/stmt-owned"))) + .respond_with(ResponseTemplate::new(200).set_body_string(running_body("stmt-owned"))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path(format!("{session_prefix}/statements/stmt-owned"))) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + + let session = open_session(&server).await; + let attached = session + .attach_async_statement("stmt-attach") + .await + .expect("attach"); + let reader = attached.reader().expect("reader"); + assert!(matches!( + reader.status().await.expect("status"), + StatementStatus::Succeeded + )); + let mut stream = reader.fetch_result().await.expect("fetch_result"); + let batches = drain(&mut stream).await; + let values: Vec = batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_primitive::() + .values() + .iter() + .copied() + }) + .collect(); + assert_eq!(values, vec![1, 2, 3, 4]); + let mut statement = session.statement(); + statement.spec().sql("SELECT 5"); + let owned = statement.submit().await.expect("owned submit"); + assert!(matches!( + owned.status().await.expect("owned status"), + StatementStatus::Running + )); + owned.close().await.expect("owned close"); + session.close().await.expect("session close"); + server.verify().await; + } +} + +#[tokio::test] +async fn attached_cloudfetch_pagination_and_refresh_use_standard_urls() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) + .respond_with( + ResponseTemplate::new(200) + .insert_header("x-databricks-rt-session", "true") + .set_body_json(json!({ "session_id": "session-b" })), + ) + .expect(1) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions/session-b")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + + let batches = [int64_batch("n", vec![1, 2]), int64_batch("n", vec![3, 4])]; + let mut links = Vec::new(); + for (index, batch) in batches.iter().enumerate() { + let bytes = arrow_ipc_bytes(batch); + let chunk_path = format!("/cloud-fetch/chunk-{index}.arrow"); + links.push(json!({ + "external_link": format!("{}{chunk_path}", server.uri()), + "expiration": "2099-01-01T00:00:00.000Z", + "chunk_index": index, + "row_offset": index * 2, + "row_count": 2, + "byte_count": bytes.len(), + "next_chunk_index": if index == 0 { Some(1) } else { None }, + })); + Mock::given(method("GET")) + .and(path(chunk_path)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path(format!( + "/api/2.0/sql/statements/statement-a/result/chunks/{index}" + ))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "external_links": [links[index].clone()], + }))) + .expect(1..) + .mount(&server) + .await; + } + let mut expired_link = links[0].clone(); + expired_link["external_link"] = json!(format!("{}/expired-link", server.uri())); + expired_link["expiration"] = json!("2000-01-01T00:00:00.000Z"); + let mut response: serde_json::Value = + serde_json::from_str(&succeeded_inline_body("statement-a", &batches[0])).unwrap(); + response["manifest"]["total_chunk_count"] = json!(2); + response["manifest"]["total_row_count"] = json!(4); + response["result"] = json!({ "external_links": [expired_link] }); + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/statement-a")) + .respond_with(ResponseTemplate::new(200).set_body_json(response)) + .expect(2) + .mount(&server) + .await; + + let session = open_session(&server).await; + let attached = session + .attach_async_statement("statement-a") + .await + .expect("attach"); + let reader = attached.reader().expect("reader"); + drop(attached); + let mut stream = reader.fetch_result().await.expect("fetch_result"); + let fetched = drain(&mut stream).await; + let values: Vec = fetched + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_primitive::() + .values() + .iter() + .copied() + }) + .collect(); + assert_eq!(values, vec![1, 2, 3, 4]); + session.close().await.expect("session close"); + server.verify().await; +} + #[tokio::test] async fn attach_reports_closed_for_a_closed_statement() { // The connector relies on this: a closed async command must report @@ -1618,6 +2187,9 @@ async fn await_result_closed_status_skips_close_statement() { .value(0), 7 ); + let reader = async_exec.reader().expect("reader after server auto-close"); + let mut refetched = reader.fetch_result().await.expect("refetch closed result"); + assert_eq!(drain(&mut refetched).await, batches); // An explicit close() on a CLOSED statement must also be a no-op. async_exec.close().await.expect("close"); // async_exec (and stmt) drop here — a redundant close guard fires now. diff --git a/tests/v0_c_abi_canceller_wiremock.rs b/tests/v0_c_abi_canceller_wiremock.rs index 9bff47ec..4d3df1ee 100644 --- a/tests/v0_c_abi_canceller_wiremock.rs +++ b/tests/v0_c_abi_canceller_wiremock.rs @@ -712,7 +712,7 @@ fn async_c_abi_get_result_stream_state_guards() { async fn mount_create_session(server: &MockServer) { 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-test","warehouse_id":"test_wh"}"#), diff --git a/tests/v0_c_abi_metadata_table_types_wiremock.rs b/tests/v0_c_abi_metadata_table_types_wiremock.rs index 2ca95dea..220c2ac0 100644 --- a/tests/v0_c_abi_metadata_table_types_wiremock.rs +++ b/tests/v0_c_abi_metadata_table_types_wiremock.rs @@ -51,7 +51,7 @@ fn list_table_types_returns_table_type_column() { 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-table-types","warehouse_id":"test_wh"}"#, )) diff --git a/tests/v0_c_abi_result_config_wiremock.rs b/tests/v0_c_abi_result_config_wiremock.rs index ce834d42..442ff88e 100644 --- a/tests/v0_c_abi_result_config_wiremock.rs +++ b/tests/v0_c_abi_result_config_wiremock.rs @@ -44,7 +44,7 @@ use wiremock::{Mock, MockServer, ResponseTemplate}; async fn mount_create_session(server: &MockServer) { 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-test","warehouse_id":"test_wh"}"#), @@ -207,9 +207,10 @@ fn recorded_create_session_geospatial_conf(enabled: bool) -> Option { let create = recorded .iter() .find(|request| { - request.url.path() == "/api/2.0/sql/sessions" && request.method.as_str() == "POST" + request.url.path() == "/api/2.0/sql/warehouses/test_wh/sessions" + && request.method.as_str() == "POST" }) - .expect("a POST /sessions request was made"); + .expect("a CreateSession request was made"); let body: serde_json::Value = serde_json::from_slice(&create.body).expect("create-session body must be valid JSON"); body.pointer("/session_confs/EnableGeoSpatialSupport") diff --git a/tests/v0_c_abi_result_stream_canceller_wiremock.rs b/tests/v0_c_abi_result_stream_canceller_wiremock.rs index e05c99bb..a2e51467 100644 --- a/tests/v0_c_abi_result_stream_canceller_wiremock.rs +++ b/tests/v0_c_abi_result_stream_canceller_wiremock.rs @@ -85,7 +85,7 @@ fn exported_canceller_aborts_the_stream() { let server = 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-rs-cancel","warehouse_id":"test_wh"}"#), diff --git a/tests/v0_c_abi_session_close_wiremock.rs b/tests/v0_c_abi_session_close_wiremock.rs index a06ab437..e1b98189 100644 --- a/tests/v0_c_abi_session_close_wiremock.rs +++ b/tests/v0_c_abi_session_close_wiremock.rs @@ -48,7 +48,7 @@ fn session_close_initiates_delete_with_statement_still_open() { 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-c-abi-close","warehouse_id":"test_wh"}"#, )) diff --git a/tests/v0_c_abi_session_test_wiremock.rs b/tests/v0_c_abi_session_test_wiremock.rs index 6160b907..0c633b7c 100644 --- a/tests/v0_c_abi_session_test_wiremock.rs +++ b/tests/v0_c_abi_session_test_wiremock.rs @@ -118,7 +118,7 @@ fn session_test_returns_success_when_server_reachable() { 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-c-abi-test","warehouse_id":"test_wh"}"#, )) @@ -179,7 +179,7 @@ fn session_test_returns_error_when_server_unreachable() { 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-c-abi-dead","warehouse_id":"test_wh"}"#, )) @@ -216,7 +216,7 @@ fn session_test_honours_per_call_timeout() { 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-c-abi-slow","warehouse_id":"test_wh"}"#, )) diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 1e9a14fe..e428abf3 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -14,7 +14,7 @@ //! Wiremock tests for the v0 `Statement::execute` path. //! -//! Each test stubs SEA's `POST /sessions`, `POST /statements`, and +//! Each test stubs SEA's `CreateSession`, `POST /statements`, and //! (where needed) `GET /statements/{id}`, then drives a //! `Statement::execute()` through the full pipeline: //! Session::open → Statement::execute → ExecutedStatement → @@ -133,7 +133,7 @@ async fn recorded_execute_disposition(server: &MockServer) -> String { async fn mount_create_session(server: &MockServer) { 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-test","warehouse_id":"test_wh"}"#), @@ -985,7 +985,7 @@ async fn execute_geospatial_string_mode_uses_manifest_tags_for_untagged_arrow_ip let requests = server.received_requests().await.unwrap(); let create = requests .iter() - .find(|request| request.url.path() == "/api/2.0/sql/sessions") + .find(|request| request.url.path() == "/api/2.0/sql/warehouses/test_wh/sessions") .expect("create-session request"); let body: serde_json::Value = serde_json::from_slice(&create.body).unwrap(); let forwarded_geo_setting = body diff --git a/tests/v0_logging_wiremock.rs b/tests/v0_logging_wiremock.rs index 69705006..ecb126a5 100644 --- a/tests/v0_logging_wiremock.rs +++ b/tests/v0_logging_wiremock.rs @@ -42,7 +42,7 @@ use wiremock::{Mock, MockServer, ResponseTemplate}; /// Mount a successful CreateSession stub. async fn mock_create_session_ok(server: &MockServer) { 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-log-213","warehouse_id":"test_wh"}"#), diff --git a/tests/v0_metadata_wiremock.rs b/tests/v0_metadata_wiremock.rs index 8ba43918..e23914ef 100644 --- a/tests/v0_metadata_wiremock.rs +++ b/tests/v0_metadata_wiremock.rs @@ -15,7 +15,7 @@ //! Wiremock end-to-end tests for the v0 `Metadata::*` surface. //! //! For each wire-driven `Metadata::*` RPC, we stub the SEA -//! `POST /sessions` and `POST /statements` endpoints, encoding a +//! `CreateSession` and `POST /statements` endpoints, encoding a //! synthesised Databricks Arrow batch as inline base64. We then drive //! the call through `Session::open` + `Metadata::*` and assert that //! the returned `ResultStream` exposes the **Thrift-compatible** @@ -74,7 +74,7 @@ async fn open_session_with_default_catalog(server: &MockServer, catalog: Option< async fn mount_create_session(server: &MockServer) { 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-test","warehouse_id":"test_wh"}"#), diff --git a/tests/v0_session_wiremock.rs b/tests/v0_session_wiremock.rs index 62130046..d04d0629 100644 --- a/tests/v0_session_wiremock.rs +++ b/tests/v0_session_wiremock.rs @@ -14,14 +14,6 @@ //! Wiremock end-to-end tests for `Session::open` HTTP-status mapping. //! -//! Stubs the SEA `POST /api/2.0/sql/sessions` endpoint with each -//! status code in the migration plan's mapping table and asserts the -//! resulting `kernel_error::Error` carries the right `ErrorCode` and -//! `retryable` flag. This is the §7 follow-up that PR 1 deferred — -//! `Session::open` is the natural place to drive it because it -//! exercises the full HTTP path (auth header injection, request -//! dispatch, response decoding) end to end. -//! //! Retries are disabled because these tests verify status mapping, not //! retry orchestration (which has dedicated coverage in the HTTP client //! tests). This keeps retryable responses from sleeping through the @@ -58,7 +50,7 @@ async fn open_session_against(server: &MockServer) -> databricks_sql_kernel::Res /// Mount a single-response mock for the create-session endpoint. async fn mock_create_session_returns(server: &MockServer, status: u16, body: &'static str) { 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(status).set_body_string(body)) .mount(server) .await; @@ -104,7 +96,7 @@ async fn create_session_404_maps_to_not_found() { async fn create_session_429_maps_to_resource_exhausted_retryable() { 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(429).set_body_string("rate limited")) .mount(&server) .await; @@ -120,7 +112,7 @@ async fn create_session_429_maps_to_resource_exhausted_retryable() { async fn create_session_503_maps_to_unavailable_retryable() { 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(503).set_body_string("warehouse cold")) .mount(&server) .await; @@ -136,7 +128,7 @@ async fn create_session_503_maps_to_unavailable_retryable() { async fn create_session_504_maps_to_timeout_retryable() { 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(504).set_body_string("upstream timeout")) .mount(&server) .await; @@ -168,7 +160,7 @@ async fn create_session_500_maps_to_internal() { // Internal per the plan's mapping table. 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(500).set_body_string("server bug")) .mount(&server) .await; @@ -364,8 +356,11 @@ async fn assert_no_can_cloud_download_on_create(server: &MockServer) { .expect("server must have request log enabled"); let create = recorded .iter() - .find(|r| r.url.path() == "/api/2.0/sql/sessions" && r.method.as_str() == "POST") - .expect("a POST /sessions request was made"); + .find(|r| { + r.url.path() == "/api/2.0/sql/warehouses/test_wh/sessions" + && r.method.as_str() == "POST" + }) + .expect("a CreateSession request was made"); let body: serde_json::Value = serde_json::from_slice(&create.body).expect("create-session body must be valid JSON"); if let Some(obj) = body.get("session_confs").and_then(|v| v.as_object()) { @@ -388,8 +383,11 @@ async fn create_session_body(server: &MockServer) -> serde_json::Value { .expect("server must have request log enabled"); let create = recorded .iter() - .find(|r| r.url.path() == "/api/2.0/sql/sessions" && r.method.as_str() == "POST") - .expect("a POST /sessions request was made"); + .find(|r| { + r.url.path() == "/api/2.0/sql/warehouses/test_wh/sessions" + && r.method.as_str() == "POST" + }) + .expect("a CreateSession request was made"); serde_json::from_slice(&create.body).expect("create-session body must be valid JSON") } @@ -405,7 +403,7 @@ async fn create_session_with_cloudfetch_disabled_omits_can_cloud_download() { // opens and the poisoned conf never reaches the wire. 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-cf-off","warehouse_id":"test_wh"}"#), @@ -431,7 +429,7 @@ async fn create_session_forwards_user_supplied_session_conf_unchanged() { // through unchanged; validation belongs to the server. 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-dropped","warehouse_id":"test_wh"}"#), @@ -496,7 +494,7 @@ async fn open_session_with_geospatial_config( async fn mount_geospatial_session(server: &MockServer, session_id: &str) { 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(serde_json::json!({ "session_id": session_id, "warehouse_id": "test_wh", @@ -615,7 +613,7 @@ async fn create_session_with_cloudfetch_enabled_omits_can_cloud_download() { // here on either branch now. 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-cf-on","warehouse_id":"test_wh"}"#), diff --git a/tests/v0_statement_canceller_reexecute.rs b/tests/v0_statement_canceller_reexecute.rs index 26fed249..be0b54d6 100644 --- a/tests/v0_statement_canceller_reexecute.rs +++ b/tests/v0_statement_canceller_reexecute.rs @@ -58,7 +58,7 @@ async fn open_session(server: &MockServer) -> Session { async fn mount_create_session(server: &MockServer) { 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-test","warehouse_id":"test_wh"}"#),