From 3fb1b26b884aa35749e41b5d8a6ba645003ef91b Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 17 Nov 2026 23:49:29 +0000 Subject: [PATCH 1/9] perf(pyo3): avoid runtime entry for buffered fetch and drained close Signed-off-by: Aakash Saravanan --- pyo3/src/fetch.rs | 31 ++++- pyo3/src/result_stream.rs | 12 +- pyo3/src/statement.rs | 22 +++- pyo3/tests/test_fetch.py | 256 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 312 insertions(+), 9 deletions(-) create mode 100644 pyo3/tests/test_fetch.py diff --git a/pyo3/src/fetch.rs b/pyo3/src/fetch.rs index 9e7d859c..85c1eeab 100644 --- a/pyo3/src/fetch.rs +++ b/pyo3/src/fetch.rs @@ -23,11 +23,40 @@ use arrow_array::RecordBatch; use arrow_pyarrow::ToPyArrow; use arrow_schema::Schema; -use databricks_sql_kernel::{Error, ExecutedStatement, Result, ResultBatch, ResultStream}; +use databricks_sql_kernel::{ + Error, ExecutedStatement, Result, ResultBatch, ResultStream, TryNextBatch, +}; use pyo3::prelude::*; use std::sync::Arc; use tokio::runtime::Runtime; +pub(crate) enum BatchRead { + Ready(RecordBatch), + Pending, + End, +} + +fn own_batch(read: TryNextBatch<'_>) -> Result { + match read { + TryNextBatch::Ready(ResultBatch::Arrow(batch)) => Ok(BatchRead::Ready(batch.clone())), + TryNextBatch::Ready(_) => { + Err(Error::invalid_argument() + .message("kernel returned a non-Arrow ResultBatch variant")) + } + TryNextBatch::Pending => Ok(BatchRead::Pending), + TryNextBatch::End => Ok(BatchRead::End), + _ => Err(Error::invalid_argument().message("kernel returned an unknown batch-read state")), + } +} + +pub(crate) fn try_next_batch(stream: &mut ResultStream) -> Result { + own_batch(stream.try_next_batch()?) +} + +pub(crate) fn try_next_batch_exec(exec: &mut ExecutedStatement) -> Result { + own_batch(exec.try_next_batch()?) +} + /// Pull the next batch from the kernel stream and return it as an /// owned `RecordBatch`, or `None` if the stream is exhausted. /// diff --git a/pyo3/src/result_stream.rs b/pyo3/src/result_stream.rs index cd193bb9..67c37493 100644 --- a/pyo3/src/result_stream.rs +++ b/pyo3/src/result_stream.rs @@ -76,8 +76,16 @@ impl ResultStream { if inner.exhausted { return Ok(None); } - let runtime = inner.runtime.clone(); - let batch = run_sync_kernel!(py, fetch::next_batch(&runtime, &mut inner.stream))?; + let batch = match fetch::try_next_batch(&mut inner.stream) + .map_err(|error| crate::errors::to_py_err(py, error))? + { + fetch::BatchRead::Ready(batch) => Some(batch), + fetch::BatchRead::End => None, + fetch::BatchRead::Pending => { + let runtime = inner.runtime.clone(); + run_sync_kernel!(py, fetch::next_batch(&runtime, &mut inner.stream))? + } + }; match batch { Some(b) => Ok(Some(b.to_pyarrow(py)?)), None => { diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 7f2dc3e8..81f5dd91 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -348,11 +348,16 @@ impl ExecutedStatement { if inner.exhausted { return Ok(None); } - let runtime = inner.runtime.clone(); - // `next_batch_exec` drives the ExecutedStatement so the kernel's - // auto-close-on-drain fires the server CloseStatement once the - // stream is exhausted (after all lazy CloudFetch link fetches). - let batch = run_sync_kernel!(py, fetch::next_batch_exec(&runtime, &mut inner.exec))?; + let batch = match fetch::try_next_batch_exec(&mut inner.exec) + .map_err(|error| crate::errors::to_py_err(py, error))? + { + fetch::BatchRead::Ready(batch) => Some(batch), + fetch::BatchRead::End => None, + fetch::BatchRead::Pending => { + let runtime = inner.runtime.clone(); + run_sync_kernel!(py, fetch::next_batch_exec(&runtime, &mut inner.exec))? + } + }; match batch { Some(b) => Ok(Some(b.to_pyarrow(py)?)), None => { @@ -397,7 +402,12 @@ impl ExecutedStatement { return Ok(()); }; let runtime = inner.runtime.clone(); - let res = run_kernel!(py, runtime, KExecutedStatement::close(&mut inner.exec)); + // Exhaustion finalizes telemetry and schedules server cleanup. + let res = if inner.exhausted { + Ok(()) + } else { + run_kernel!(py, runtime, KExecutedStatement::close(&mut inner.exec)) + }; // Drop the kernel handle regardless of close() outcome — the // kernel's Drop impl runs fire-and-forget cleanup if close() // failed mid-flight. diff --git a/pyo3/tests/test_fetch.py b/pyo3/tests/test_fetch.py new file mode 100644 index 00000000..456d1949 --- /dev/null +++ b/pyo3/tests/test_fetch.py @@ -0,0 +1,256 @@ +# Copyright (c) 2026 Databricks, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Buffered reads, pending I/O and result cleanup over a loopback SQL API.""" + +import base64 +import json +import threading +from collections import Counter +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from types import SimpleNamespace + +import pyarrow as pa +import pytest + +import databricks_sql_kernel as k + + +def arrow_bytes(batches): + schema = pa.schema([("n", pa.int64())]) + output = pa.BufferOutputStream() + with pa.ipc.new_stream(output, schema) as writer: + for rows in batches: + writer.write_batch( + pa.record_batch([pa.array(rows, pa.int64())], schema=schema) + ) + return output.getvalue().to_pybytes() + + +@pytest.fixture +def sql_api(): + state = SimpleNamespace( + batches=[[1, 2]], + mode="buffered", + requests=[], + chunk_requested=threading.Event(), + release_chunk=threading.Event(), + statement_closed=threading.Event(), + ) + statement_id = "00000001-0000-0000-0000-000000000001" + statement_path = f"/api/2.0/sql/statements/{statement_id}" + + class Handler(BaseHTTPRequestHandler): + def reply(self): + self.rfile.read(int(self.headers.get("Content-Length", 0))) + path = self.path.split("?")[0] + state.requests.append((self.command, path)) + status, response = 200, {} + if self.command == "POST" and path.endswith("/sessions"): + response = {"session_id": "00000000-0000-0000-0000-000000000001"} + elif self.command == "POST" and path.endswith("/statements"): + pending = state.mode != "buffered" + raw = arrow_bytes(state.batches) + count = sum(map(len, state.batches)) + response = { + "statement_id": statement_id, + "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": 2 if pending else 1, + "total_row_count": count + (2 if pending else 0), + }, + "result": { + "chunk_index": 0, + "row_offset": 0, + "row_count": count, + "attachment": base64.b64encode(raw).decode(), + }, + } + if pending: + response["result"]["next_chunk_index"] = 1 + if state.mode == "cloud": + response["result"] = {"external_links": [self.link(0)]} + if not state.batches: + response.pop("result") + state.response = response + elif self.command == "GET" and path == statement_path: + response = state.response + elif self.command == "DELETE" and path == statement_path: + state.statement_closed.set() + elif path == f"{statement_path}/result/chunks/1" and state.mode == "cloud": + response = {"external_links": [self.link(1)]} + elif path in (f"{statement_path}/result/chunks/1", "/storage/1"): + state.chunk_requested.set() + if not state.release_chunk.wait(5): + status, response = 408, {"message": "chunk gate timed out"} + elif state.mode == "error": + status, response = ( + 404, + {"error_code": "NOT_FOUND", "message": "missing chunk"}, + ) + elif state.mode == "cloud": + response = arrow_bytes([[3, 4]]) + else: + response = { + "chunk_index": 1, + "row_offset": 2, + "row_count": 2, + "attachment": base64.b64encode(arrow_bytes([[3, 4]])).decode(), + } + elif path == "/storage/0": + response = arrow_bytes([[1, 2]]) + encoded = ( + response + if isinstance(response, bytes) + else json.dumps(response).encode() + ) + self.send_response(status) + self.send_header("Content-Length", str(len(encoded))) + self.end_headers() + self.wfile.write(encoded) + + def link(self, index): + return { + "external_link": f"{state.host}/storage/{index}", + "chunk_index": index, + "row_offset": index * 2, + "row_count": 2, + "byte_count": len(arrow_bytes(state.batches if index == 0 else [[3, 4]])), + "next_chunk_index": 1 if index == 0 else None, + "expiration": "2099-01-01T00:00:00Z", + } + + do_POST = do_GET = do_DELETE = reply + + def log_message(self, *args): + pass + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + server.daemon_threads = True + state.host = f"http://127.0.0.1:{server.server_port}" + state.statement_path = statement_path + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + state.session = k.Session( + host=state.host, + http_path="/sql/1.0/warehouses/0000000000000001", + access_token="test-token", + telemetry_enabled=False, + request_timeout_secs=2, + retry_max_attempts=1, + ) + yield state + finally: + state.release_chunk.set() + if hasattr(state, "session"): + state.session.close() + server.shutdown() + server.server_close() + thread.join(timeout=5) + + +def execute(sql_api): + statement = sql_api.session.statement() + statement.set_sql("SELECT n") + return statement, statement.execute() + + +@pytest.mark.parametrize("batches", [[], [[1, 2]], [[], [1, 2], [3]]]) +def test_buffered_fetch_closes_once_after_exhaustion(sql_api, batches): + sql_api.batches = batches + statement, result = execute(sql_api) + schema = result.arrow_schema() + observed = [] + while (batch := result.fetch_next_batch()) is not None: + observed.append(batch.column(0).to_pylist()) + assert observed == batches + assert result.fetch_next_batch() is None + result.close() + result.close() + statement.close() + assert sql_api.statement_closed.wait(5) + assert Counter(sql_api.requests)["DELETE", sql_api.statement_path] == 1 + assert result.arrow_schema() == schema + with pytest.raises(k.KernelError, match="closed"): + result.fetch_next_batch() + + +@pytest.mark.parametrize("async_result", [False, True]) +@pytest.mark.parametrize("mode", ["inline", "cloud"]) +def test_pending_fetch_releases_gil_and_preserves_continuation( + sql_api, async_result, mode +): + sql_api.mode = mode + statement = sql_api.session.statement() + statement.set_sql("SELECT n") + owner = statement.submit() if async_result else statement.execute() + result = owner.await_result() if async_result else owner + assert result.fetch_next_batch().column(0).to_pylist() == [1, 2] + assert sql_api.chunk_requested.wait(5) + assert not sql_api.statement_closed.is_set() + timer = threading.Timer(0.05, sql_api.release_chunk.set) + timer.start() + try: + assert result.fetch_next_batch().column(0).to_pylist() == [3, 4] + finally: + timer.join(timeout=5) + assert result.fetch_next_batch() is None + result.close() + if async_result: + owner.close() + statement.close() + assert sql_api.statement_closed.wait(5) + assert Counter(sql_api.requests)["DELETE", sql_api.statement_path] == 1 + + +@pytest.mark.parametrize("mode", ["buffered", "error"]) +def test_partial_or_failed_fetch_retains_explicit_cleanup(sql_api, mode): + sql_api.mode = mode + sql_api.batches = [[1, 2], [3]] if mode == "buffered" else [[1, 2]] + statement, result = execute(sql_api) + assert result.fetch_next_batch().column(0).to_pylist() == [1, 2] + if mode == "error": + assert sql_api.chunk_requested.wait(5) + sql_api.release_chunk.set() + for _ in range(2): + with pytest.raises(k.KernelError, match="404|missing chunk"): + result.fetch_next_batch() + result.close() + statement.close() + assert sql_api.statement_closed.wait(5) + assert Counter(sql_api.requests)["DELETE", sql_api.statement_path] == 1 + + +def test_drained_close_releases_last_runtime_owner(sql_api): + statement, result = execute(sql_api) + assert result.fetch_all_arrow().column(0).to_pylist() == [1, 2] + statement.close() + sql_api.session.close() + result.close() + result.close() + with pytest.raises(k.KernelError, match="closed"): + result.fetch_next_batch() From 805bfac3a2249e5b152780670fbbe559ab8b4ee8 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 18 Nov 2026 00:07:04 +0000 Subject: [PATCH 2/9] fix(cloudfetch): release reader state guards before log callbacks Signed-off-by: Aakash Saravanan --- pyo3/src/fetch.rs | 5 +-- pyo3/src/lib.rs | 3 -- src/reader/cloudfetch/streaming_provider.rs | 42 ++++++++++++++++++--- 3 files changed, 39 insertions(+), 11 deletions(-) diff --git a/pyo3/src/fetch.rs b/pyo3/src/fetch.rs index 85c1eeab..42b8f086 100644 --- a/pyo3/src/fetch.rs +++ b/pyo3/src/fetch.rs @@ -40,12 +40,11 @@ fn own_batch(read: TryNextBatch<'_>) -> Result { match read { TryNextBatch::Ready(ResultBatch::Arrow(batch)) => Ok(BatchRead::Ready(batch.clone())), TryNextBatch::Ready(_) => { - Err(Error::invalid_argument() - .message("kernel returned a non-Arrow ResultBatch variant")) + Err(Error::invalid_state().message("kernel returned a non-Arrow ResultBatch variant")) } TryNextBatch::Pending => Ok(BatchRead::Pending), TryNextBatch::End => Ok(BatchRead::End), - _ => Err(Error::invalid_argument().message("kernel returned an unknown batch-read state")), + _ => Err(Error::invalid_state().message("kernel returned an unknown batch-read state")), } } diff --git a/pyo3/src/lib.rs b/pyo3/src/lib.rs index f42ffa85..9ce1afb1 100644 --- a/pyo3/src/lib.rs +++ b/pyo3/src/lib.rs @@ -22,9 +22,6 @@ //! Both synchronous `execute()` and async `submit()` paths supported. //! Built as the `databricks_sql_kernel` extension module via //! `maturin develop` / `maturin build`. -//! -//! The kernel's API is async — every method call from Python detaches -//! the GIL and `block_on`s on the session-owned tokio runtime. // `macros` is `#[macro_use]` so the `run_kernel!` / `alive!` / // `alive_mut!` macros are visible across the rest of the crate diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index b2683ca1..8c72c73d 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -673,18 +673,23 @@ impl StreamingCloudFetchProvider { /// blocked in `wait_for_chunk` is released, not just one — a /// terminal failure must not leave sibling waiters stuck. fn set_terminal_error(&self, error: Error) { - { + let first = { let mut slot = self.terminal_error.lock().unwrap(); if slot.is_none() { - error!("CloudFetch provider entering terminal error state: {error}"); - *slot = Some(error); + *slot = Some(error.clone()); + true + } else { + false } - // else: keep the first error; drop this one. - } + }; // Wake all current waiters so they observe the terminal state. // A waiter that registers *after* this checks `terminal_error` // on entry, so it never misses the signal. self.chunk_state_changed.notify_waiters(); + // Host log callbacks can acquire locks held by result consumers. + if first { + error!("CloudFetch provider entering terminal error state: {error}"); + } } /// Return a clone of the terminal link-fetch error, if one is set. @@ -1376,6 +1381,7 @@ impl StreamingCloudFetchProvider { .as_ref() .is_some_and(|prev| *prev != link.url); if url_changed || !link.is_expired() { + drop(entry); debug!( statement_id = %sid, "Concurrent refresh delivered a {} link for chunk {}; \ @@ -1426,6 +1432,7 @@ impl StreamingCloudFetchProvider { .as_ref() .is_some_and(|prev| *prev != link.url); if url_changed || !link.is_expired() { + drop(entry); debug!( statement_id = %sid, "Batched refresh for chunk {} skipped after claim — \ @@ -4243,11 +4250,36 @@ mod tests { /// failure does not overwrite the originally-persisted error. #[tokio::test] async fn first_terminal_error_wins() { + use tracing_subscriber::prelude::*; + + struct CheckLogLock { + provider: Arc, + logged: Arc, + } + + impl tracing_subscriber::Layer for CheckLogLock { + fn on_event( + &self, + _: &tracing::Event<'_>, + _: tracing_subscriber::layer::Context<'_, S>, + ) { + assert!(self.provider.terminal_error.try_lock().is_ok()); + self.logged.store(true, Ordering::Release); + } + } + let fetcher = FailingLinkFetcher::new(4, 2, 0); let provider = provider_with_failing_fetcher(fetcher, Some(4)); + let logged = Arc::new(AtomicBool::new(false)); + let subscriber = tracing_subscriber::registry().with(CheckLogLock { + provider: Arc::clone(&provider), + logged: Arc::clone(&logged), + }); + let _guard = tracing::subscriber::set_default(subscriber); provider.set_terminal_error(Error::io().message("first error")); provider.set_terminal_error(Error::io().message("second error")); + assert!(logged.load(Ordering::Acquire)); let stored = provider .terminal_error() From 2de5a43763c9b88373d20ec3bd0612cab81bf9a4 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 18 Nov 2026 00:24:51 +0000 Subject: [PATCH 3/9] test(pyo3): guard buffered fetch runtime bypass Signed-off-by: Aakash Saravanan --- pyo3/src/fetch.rs | 50 +++++++++++++++++++++++++++++++++++++++ pyo3/src/result_stream.rs | 13 +++------- pyo3/src/statement.rs | 13 +++------- 3 files changed, 56 insertions(+), 20 deletions(-) diff --git a/pyo3/src/fetch.rs b/pyo3/src/fetch.rs index 42b8f086..3effbdb2 100644 --- a/pyo3/src/fetch.rs +++ b/pyo3/src/fetch.rs @@ -19,6 +19,9 @@ //! `ResultStream` directly). Both call `next_batch` on the kernel //! stream and clone the Arrow `RecordBatch` out from under the //! borrow so the result can cross the GIL boundary as an owned value. +//! +//! A nonblocking probe holds the GIL through kernel post-processing, so large +//! batches requiring column rewrites can delay other Python threads. use arrow_array::RecordBatch; use arrow_pyarrow::ToPyArrow; @@ -56,6 +59,20 @@ pub(crate) fn try_next_batch_exec(exec: &mut ExecutedStatement) -> Result, + read: Result, + pending: impl FnOnce() -> Result> + pyo3::marker::Ungil, +) -> PyResult> { + match read.map_err(|error| crate::errors::to_py_err(py, error))? { + BatchRead::Ready(batch) => Ok(Some(batch)), + BatchRead::End => Ok(None), + BatchRead::Pending => py + .detach(pending) + .map_err(|error| crate::errors::to_py_err(py, error)), + } +} + /// Pull the next batch from the kernel stream and return it as an /// owned `RecordBatch`, or `None` if the stream is exhausted. /// @@ -150,3 +167,36 @@ pub(crate) fn batches_to_pyarrow_table<'py>( pa.getattr("Table")? .call_method1("from_batches", (py_batches, py_schema)) } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + #[test] + fn only_pending_reads_enter_the_runtime() { + let runtime = tokio::runtime::Builder::new_current_thread() + .build() + .unwrap(); + let entries = AtomicUsize::new(0); + let pending = || { + entries.fetch_add(1, Ordering::Relaxed); + runtime.block_on(async { Ok(None) }) + }; + Python::initialize(); + Python::attach(|py| { + let batch = RecordBatch::new_empty(Arc::new(Schema::empty())); + let ready = read_batch(py, Ok(BatchRead::Ready(batch.clone())), pending).unwrap(); + assert_eq!(ready, Some(batch)); + assert!(read_batch(py, Ok(BatchRead::End), pending) + .unwrap() + .is_none()); + assert_eq!(entries.load(Ordering::Relaxed), 0); + + assert!(read_batch(py, Ok(BatchRead::Pending), pending) + .unwrap() + .is_none()); + assert_eq!(entries.load(Ordering::Relaxed), 1); + }); + } +} diff --git a/pyo3/src/result_stream.rs b/pyo3/src/result_stream.rs index 67c37493..8e7d4f8c 100644 --- a/pyo3/src/result_stream.rs +++ b/pyo3/src/result_stream.rs @@ -76,16 +76,9 @@ impl ResultStream { if inner.exhausted { return Ok(None); } - let batch = match fetch::try_next_batch(&mut inner.stream) - .map_err(|error| crate::errors::to_py_err(py, error))? - { - fetch::BatchRead::Ready(batch) => Some(batch), - fetch::BatchRead::End => None, - fetch::BatchRead::Pending => { - let runtime = inner.runtime.clone(); - run_sync_kernel!(py, fetch::next_batch(&runtime, &mut inner.stream))? - } - }; + let batch = fetch::read_batch(py, fetch::try_next_batch(&mut inner.stream), || { + fetch::next_batch(&inner.runtime, &mut inner.stream) + })?; match batch { Some(b) => Ok(Some(b.to_pyarrow(py)?)), None => { diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 81f5dd91..fa0699eb 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -348,16 +348,9 @@ impl ExecutedStatement { if inner.exhausted { return Ok(None); } - let batch = match fetch::try_next_batch_exec(&mut inner.exec) - .map_err(|error| crate::errors::to_py_err(py, error))? - { - fetch::BatchRead::Ready(batch) => Some(batch), - fetch::BatchRead::End => None, - fetch::BatchRead::Pending => { - let runtime = inner.runtime.clone(); - run_sync_kernel!(py, fetch::next_batch_exec(&runtime, &mut inner.exec))? - } - }; + let batch = fetch::read_batch(py, fetch::try_next_batch_exec(&mut inner.exec), || { + fetch::next_batch_exec(&inner.runtime, &mut inner.exec) + })?; match batch { Some(b) => Ok(Some(b.to_pyarrow(py)?)), None => { From 95dda5444e2f2368b4276285e8a1ba39c94559c5 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 18 Nov 2026 00:41:24 +0000 Subject: [PATCH 4/9] fix(pyo3): use consistent batch conversion across fetch paths Share Arrow extraction for buffered, waiting, and draining reads. Exercise both refresh skip logs with callbacks that require a writable chunk shard. Signed-off-by: Aakash Saravanan --- pyo3/src/fetch.rs | 52 ++++--------- src/reader/cloudfetch/streaming_provider.rs | 81 +++++++++++++++++++++ 2 files changed, 95 insertions(+), 38 deletions(-) diff --git a/pyo3/src/fetch.rs b/pyo3/src/fetch.rs index 3effbdb2..5f2d5733 100644 --- a/pyo3/src/fetch.rs +++ b/pyo3/src/fetch.rs @@ -39,12 +39,16 @@ pub(crate) enum BatchRead { End, } +fn own_arrow_batch(batch: &ResultBatch) -> Result { + match batch { + ResultBatch::Arrow(batch) => Ok(batch.clone()), + _ => Err(Error::invalid_state().message("kernel returned a non-Arrow ResultBatch variant")), + } +} + fn own_batch(read: TryNextBatch<'_>) -> Result { match read { - TryNextBatch::Ready(ResultBatch::Arrow(batch)) => Ok(BatchRead::Ready(batch.clone())), - TryNextBatch::Ready(_) => { - Err(Error::invalid_state().message("kernel returned a non-Arrow ResultBatch variant")) - } + TryNextBatch::Ready(batch) => own_arrow_batch(batch).map(BatchRead::Ready), TryNextBatch::Pending => Ok(BatchRead::Pending), TryNextBatch::End => Ok(BatchRead::End), _ => Err(Error::invalid_state().message("kernel returned an unknown batch-read state")), @@ -82,29 +86,15 @@ pub(crate) fn next_batch( runtime: &Runtime, stream: &mut ResultStream, ) -> Result> { - runtime.block_on(async { - match stream.next_batch().await? { - Some(ResultBatch::Arrow(rb)) => Ok(Some(rb.clone())), - Some(_) => Err(Error::invalid_argument() - .message("kernel returned a non-Arrow ResultBatch variant")), - None => Ok(None), - } - }) + runtime.block_on(async { stream.next_batch().await?.map(own_arrow_batch).transpose() }) } /// Drain the kernel stream and collect every remaining batch. pub(crate) fn drain(runtime: &Runtime, stream: &mut ResultStream) -> Result> { runtime.block_on(async { let mut out = Vec::new(); - loop { - match stream.next_batch().await? { - Some(ResultBatch::Arrow(rb)) => out.push(rb.clone()), - Some(_) => { - return Err(Error::invalid_argument() - .message("kernel returned a non-Arrow ResultBatch variant")); - } - None => break, - } + while let Some(batch) = stream.next_batch().await? { + out.push(own_arrow_batch(batch)?); } Ok(out) }) @@ -117,14 +107,7 @@ pub(crate) fn next_batch_exec( runtime: &Runtime, exec: &mut ExecutedStatement, ) -> Result> { - runtime.block_on(async { - match exec.next_batch().await? { - Some(ResultBatch::Arrow(rb)) => Ok(Some(rb.clone())), - Some(_) => Err(Error::invalid_argument() - .message("kernel returned a non-Arrow ResultBatch variant")), - None => Ok(None), - } - }) + runtime.block_on(async { exec.next_batch().await?.map(own_arrow_batch).transpose() }) } /// Like [`drain`], but drives the `ExecutedStatement` so auto-close-on- @@ -136,15 +119,8 @@ pub(crate) fn drain_exec( ) -> Result> { runtime.block_on(async { let mut out = Vec::new(); - loop { - match exec.next_batch().await? { - Some(ResultBatch::Arrow(rb)) => out.push(rb.clone()), - Some(_) => { - return Err(Error::invalid_argument() - .message("kernel returned a non-Arrow ResultBatch variant")); - } - None => break, - } + while let Some(batch) = exec.next_batch().await? { + out.push(own_arrow_batch(batch)?); } Ok(out) }) diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index 8c72c73d..c9a14eae 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -3104,6 +3104,87 @@ mod tests { ); } + #[tokio::test] + async fn refresh_skip_logs_release_chunk_guard() { + use tracing_subscriber::prelude::*; + + struct CheckLogLock { + chunks: Arc>, + logged: Arc, + } + + impl tracing_subscriber::Layer for CheckLogLock { + fn on_event( + &self, + event: &tracing::Event<'_>, + _: tracing_subscriber::layer::Context<'_, S>, + ) { + event.record( + &mut |field: &tracing::field::Field, value: &dyn std::fmt::Debug| { + if field.name() != "message" { + return; + } + let message = format!("{value:?}"); + if message.starts_with("Concurrent refresh delivered") + || message.contains("skipped after claim") + { + assert!( + self.chunks.try_get_mut(&0).is_present(), + "refresh log callback must be able to write the chunk: {message}" + ); + self.logged.store(true, Ordering::Release); + } + }, + ); + } + } + + for contended in [false, true] { + let chunks = Arc::new(DashMap::new()); + let link = if contended { + expired_link(0) + } else { + create_test_link(0) + }; + chunks.insert(0, entry_with_state(link, ChunkState::UrlFetched)); + let mock = RefreshCountingMock::new(1); + let fetcher: Arc = mock.clone(); + let coordinator = Arc::new(RefreshCoordinator::default()); + coordinator.in_progress.store(contended, Ordering::Release); + let cancel = CancellationToken::new(); + let logged = Arc::new(AtomicBool::new(false)); + let subscriber = tracing_subscriber::registry().with(CheckLogLock { + chunks: Arc::clone(&chunks), + logged: Arc::clone(&logged), + }); + let _guard = tracing::subscriber::set_default(subscriber); + + let mut refresh = Box::pin(StreamingCloudFetchProvider::refresh_links_batch( + 0, + &fetcher, + &chunks, + &coordinator, + &cancel, + None, + )); + if contended { + assert!(futures::poll!(refresh.as_mut()).is_pending()); + chunks.insert( + 0, + entry_with_state(create_test_link(0), ChunkState::UrlFetched), + ); + coordinator.in_progress.store(false, Ordering::Release); + coordinator.done.notify_waiters(); + } + tokio::time::timeout(NO_HANG, refresh) + .await + .unwrap() + .unwrap(); + assert!(logged.load(Ordering::Acquire), "contended={contended}"); + assert_eq!(mock.refresh_calls.load(AtomicOrdering::SeqCst), 0); + } + } + #[tokio::test] async fn refresh_batch_disjoint_window_loser_retries_claim() { // Loser-of-claim disjoint-window gap (round-3 follow-up): From 1580981d13d1b793035e6f8585a3799ce6c95b4f Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 18 Nov 2026 21:13:38 +0000 Subject: [PATCH 5/9] docs(pyo3): clarify buffered fetch and logging lock order Signed-off-by: Aakash Saravanan --- pyo3/src/fetch.rs | 4 ++++ pyo3/src/logging.rs | 26 +++++++++++---------- src/reader/cloudfetch/streaming_provider.rs | 5 ++++ 3 files changed, 23 insertions(+), 12 deletions(-) diff --git a/pyo3/src/fetch.rs b/pyo3/src/fetch.rs index 5f2d5733..ed73dcd3 100644 --- a/pyo3/src/fetch.rs +++ b/pyo3/src/fetch.rs @@ -22,6 +22,10 @@ //! //! A nonblocking probe holds the GIL through kernel post-processing, so large //! batches requiring column rewrites can delay other Python threads. +//! +//! CloudFetch probes also take ordinary locks. Their holders must release +//! guards before logging or invoking host callbacks that can acquire the GIL, +//! to avoid deadlocking a Python caller waiting for the same lock. use arrow_array::RecordBatch; use arrow_pyarrow::ToPyArrow; diff --git a/pyo3/src/logging.rs b/pyo3/src/logging.rs index 0271f276..dc1a6752 100644 --- a/pyo3/src/logging.rs +++ b/pyo3/src/logging.rs @@ -37,16 +37,19 @@ //! logging.getLogger("databricks.sql.kernel").setLevel(logging.DEBUG) # kernel only //! ``` //! -//! ## Filtering happens before the GIL +//! ## GIL and filtering //! -//! Kernel events fire on tokio worker threads with the GIL released -//! (see `run_kernel!`). `pyo3_log` re-acquires the GIL per surviving -//! record, so we must drop below-threshold events *before* that -//! boundary. Two cheap gates do this: the global `log::max_level` -//! (set by `pyo3_log` from the Python loggers' effective levels) and -//! `pyo3_log`'s per-logger level cache. The customer's single knob -//! (`setLevel`) drives both — there is no separate Rust-side level -//! argument. +//! This bridge sets `log::max_level` to `Trace`; Python logger levels +//! control filtering through `pyo3_log`'s per-logger cache. Cached +//! below-threshold records can be rejected without acquiring the GIL. +//! A cache miss can acquire the GIL to resolve the logger and its level, +//! even if a Python logger set to WARNING discards the record. +//! Forwarding an enabled record also acquires the GIL. +//! +//! Events can originate on runtime workers or a Python caller holding +//! the GIL during a buffered fetch. Workers must release locks shared +//! with those callers before logging, regardless of Python log levels, +//! so the worker and caller cannot wait on each other's locks. //! //! ## Reconfiguration //! @@ -166,9 +169,8 @@ impl log::Log for ExitGuard { /// stays quiet, while a customer who turns on DEBUG to diagnose a /// connectivity / TLS issue gets the full wire-level picture in one /// shot, with no flag to flip and no support round-trip to ask for it. -/// The per-record GIL re-acquire cost of forwarding deps only -/// materializes when DEBUG is actually enabled on those loggers; a -/// customer can silence them with the standard +/// Uncached targets can acquire the GIL even if Python filters out +/// their records. A customer can silence dependency output with /// `logging.getLogger("hyper_util").setLevel(WARNING)`. /// /// Returns `true` if this call performed the install, `false` otherwise diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index c9a14eae..af28fd55 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -106,6 +106,11 @@ fn flush_pending(schema: &SchemaRef, pending: &mut Vec) -> Result, From d0b900489b6fb458e89a5676ec7acd27474a9748 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 18 Nov 2026 21:37:59 +0000 Subject: [PATCH 6/9] fix(cloudfetch): yield buffered reads on lock contention Use nonblocking buffer, shard and terminal-error lock attempts so Python can wait with the GIL released. Cover contended reads and runtime bypass through the real Python result handles. Signed-off-by: Aakash Saravanan --- pyo3/src/fetch.rs | 99 ++++++++- pyo3/src/logging.rs | 7 +- src/reader/cloudfetch/streaming_provider.rs | 228 ++++++++++++++++---- 3 files changed, 289 insertions(+), 45 deletions(-) diff --git a/pyo3/src/fetch.rs b/pyo3/src/fetch.rs index ed73dcd3..aa5269b6 100644 --- a/pyo3/src/fetch.rs +++ b/pyo3/src/fetch.rs @@ -23,9 +23,8 @@ //! A nonblocking probe holds the GIL through kernel post-processing, so large //! batches requiring column rewrites can delay other Python threads. //! -//! CloudFetch probes also take ordinary locks. Their holders must release -//! guards before logging or invoking host callbacks that can acquire the GIL, -//! to avoid deadlocking a Python caller waiting for the same lock. +//! Contended CloudFetch provider-state locks yield `Pending`, allowing the +//! fallback to wait with the GIL released. use arrow_array::RecordBatch; use arrow_pyarrow::ToPyArrow; @@ -179,4 +178,98 @@ mod tests { assert_eq!(entries.load(Ordering::Relaxed), 1); }); } + + #[test] + fn real_result_handles_return_eof_without_runtime_entry() { + use pyo3::types::PyDict; + use std::io::{BufRead, BufReader, Read, Write}; + use std::net::{TcpListener, TcpStream}; + use std::sync::atomic::AtomicBool; + use std::time::Duration; + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let stopped = Arc::new(AtomicBool::new(false)); + let stop = Arc::clone(&stopped); + let server = std::thread::spawn(move || { + let body = r#"{"session_id":"00000000-0000-0000-0000-000000000001","statement_id":"00000000-0000-0000-0000-000000000002","status":{"state":"SUCCEEDED"},"manifest":{"format":"ARROW_STREAM","schema":{"column_count":0,"columns":[]},"total_row_count":0,"total_chunk_count":0}}"#; + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + for stream in listener.incoming() { + if stop.load(Ordering::Acquire) { + break; + } + let mut stream = stream.unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(2))) + .unwrap(); + let mut request = BufReader::new(&mut stream); + let mut length = 0; + loop { + let mut line = String::new(); + if request.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" { + break; + } + if let Some((name, value)) = line.split_once(':') { + if name.eq_ignore_ascii_case("content-length") { + length = value.trim().parse().unwrap(); + } + } + } + if request.read_exact(&mut vec![0; length]).is_ok() { + let _ = stream.write_all(response.as_bytes()); + } + } + }); + Python::initialize(); + let checked = Python::attach(|py| -> PyResult<()> { + let kwargs = PyDict::new(py); + kwargs.set_item("host", format!("http://{address}"))?; + kwargs.set_item("http_path", "/sql/1.0/warehouses/0000000000000001")?; + kwargs.set_item("access_token", "test-token")?; + kwargs.set_item("telemetry_enabled", false)?; + kwargs.set_item("request_timeout_secs", 2)?; + kwargs.set_item("retry_max_attempts", 1)?; + let session = py + .get_type::() + .call((), Some(&kwargs))?; + let runtime = tokio::runtime::Builder::new_current_thread() + .build() + .unwrap(); + let mut checked = Ok(()); + for asynchronous in [false, true] { + let statement = session.call_method0("statement")?; + statement.call_method1("set_sql", ("SELECT 1",))?; + let owner = + statement.call_method0(if asynchronous { "submit" } else { "execute" })?; + let result = if asynchronous { + owner.call_method0("await_result")? + } else { + owner.clone() + }; + // Tokio rejects nested block_on calls, exposing an unconditional + // runtime entry through either real Python result handle. + checked = runtime.block_on(async { + assert!(result.call_method0("fetch_next_batch")?.is_none()); + Ok(()) + }); + result.call_method0("close")?; + if asynchronous { + owner.call_method0("close")?; + } + statement.call_method0("close")?; + if checked.is_err() { + break; + } + } + session.call_method0("close")?; + checked + }); + stopped.store(true, Ordering::Release); + let _ = TcpStream::connect(address); + server.join().unwrap(); + checked.unwrap(); + } } diff --git a/pyo3/src/logging.rs b/pyo3/src/logging.rs index dc1a6752..cdb331c6 100644 --- a/pyo3/src/logging.rs +++ b/pyo3/src/logging.rs @@ -47,9 +47,10 @@ //! Forwarding an enabled record also acquires the GIL. //! //! Events can originate on runtime workers or a Python caller holding -//! the GIL during a buffered fetch. Workers must release locks shared -//! with those callers before logging, regardless of Python log levels, -//! so the worker and caller cannot wait on each other's locks. +//! the GIL during a buffered fetch. Callers holding the GIL must avoid +//! waiting for locks held by a logging worker, regardless of Python log +//! levels. CloudFetch probes yield on contended provider-state locks +//! so the fallback can wait with the GIL released. //! //! ## Reconfiguration //! diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index af28fd55..b8897520 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -31,10 +31,10 @@ use crate::types::cloudfetch::{ use arrow_array::RecordBatch; use arrow_schema::SchemaRef; use arrow_select::concat::concat_batches; -use dashmap::DashMap; +use dashmap::{mapref::entry::Entry, DashMap}; use std::collections::VecDeque; use std::sync::atomic::{AtomicBool, AtomicI32, AtomicI64, AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex, OnceLock}; +use std::sync::{Arc, Mutex, OnceLock, TryLockError}; use tokio::sync::Notify; use tokio_util::sync::CancellationToken; @@ -107,10 +107,9 @@ fn flush_pending(schema: &SchemaRef, pending: &mut Vec) -> Result, @@ -550,8 +549,8 @@ impl StreamingCloudFetchProvider { } /// Return the next batch if it is already downloaded, without waiting for - /// chunk state to change. Download and link-fetch tasks continue on the - /// provider runtime while this returns `Pending` to the caller. + /// chunk state to change or for a contended provider-state lock. Download + /// and link-fetch tasks continue while this returns `Pending` to the caller. pub fn try_next_batch(self: &Arc) -> Result { use crate::reader::TryNextBatch; @@ -561,18 +560,33 @@ impl StreamingCloudFetchProvider { break Err(Error::invalid_state().message("Operation cancelled")); } - if let Some(batch) = self.take_buffered_batch() { + let mut buffer = match self.current_batch_buffer.try_lock() { + Err(TryLockError::WouldBlock) => break Ok(TryNextBatch::Pending), + result => result.unwrap(), + }; + if let Some(batch) = buffer.pop_front() { + drop(buffer); + let _ = self.schema.get_or_init(|| batch.schema()); break Ok(TryNextBatch::Ready(batch)); } let chunk_index = self.current_chunk_index.load(Ordering::Acquire); - if self.is_at_end(chunk_index) { - break Ok(TryNextBatch::End); - } - - let ready = if let Some(entry) = self.chunks.get(&chunk_index) { - match &entry.state { - ChunkState::Downloaded => true, + match self.chunks.try_entry(chunk_index) { + None => break Ok(TryNextBatch::Pending), + Some(Entry::Vacant(_)) if self.end_of_stream.load(Ordering::Acquire) => { + break Ok(TryNextBatch::End); + } + Some(Entry::Occupied(entry)) => match &entry.get().state { + ChunkState::Downloaded => { + // Both guards are acquired before removing data so a + // contended probe leaves every batch available to retry. + if let Some(batches) = entry.remove().batches { + buffer.extend(batches); + } + self.advance_chunk(); + released = true; + continue; + } ChunkState::DownloadFailed(error) => break Err(error.clone()), ChunkState::ProcessingFailed(error) => { break Err(Error::io().message(error.clone())) @@ -580,28 +594,19 @@ impl StreamingCloudFetchProvider { ChunkState::Cancelled => { break Err(Error::invalid_state().message("Operation cancelled")) } - _ => false, - } - } else { - false - }; - - if !ready { - if let Some(error) = self.terminal_error() { - break Err(error); - } - break Ok(TryNextBatch::Pending); + _ => {} + }, + Some(Entry::Vacant(_)) => {} } - - // Only the single result consumer removes chunks. Once a chunk is - // Downloaded its entry is terminal, so the remove cannot race a - // downloader changing it back to an earlier state. - if !self.release_downloaded_chunk(chunk_index) { - break Ok(TryNextBatch::Pending); + drop(buffer); + let terminal_error = match self.terminal_error.try_lock() { + Err(TryLockError::WouldBlock) => break Ok(TryNextBatch::Pending), + result => result.unwrap(), + }; + if let Some(error) = terminal_error.as_ref() { + break Err(error.clone()); } - released = true; - // Loop once to return the first batch, or advance across an empty - // downloaded chunk to Pending/End/the following ready chunk. + break Ok(TryNextBatch::Pending); }; // Refill the rolling window once, after the loop settles, rather than @@ -609,6 +614,12 @@ impl StreamingCloudFetchProvider { // schedule_downloads early-exits when the window is full and the current // batch (if any) is already buffered, so this must not block. if released { + debug!( + "Buffered downloaded chunks: chunks_in_memory={}/{}, consumer_at={}", + self.chunks_in_memory.load(Ordering::Acquire), + self.max_chunks_in_memory, + self.current_chunk_index.load(Ordering::Acquire), + ); // Detached spawn (vs. the blocking path's inline await) means two // rapid try_next_batch calls can overlap this refill, and a mixed // try_next_batch + next_batch caller can run it alongside next_batch's @@ -658,9 +669,7 @@ impl StreamingCloudFetchProvider { if let Some(batches) = entry.batches.take() { self.current_batch_buffer.lock().unwrap().extend(batches); } - let new_count = self.chunks_in_memory.fetch_sub(1, Ordering::Release) - 1; - let next_chunk = self.current_chunk_index.fetch_add(1, Ordering::Release) + 1; - self.metrics.record_chunk_iterated(); + let (new_count, next_chunk) = self.advance_chunk(); debug!( "Released chunk {}: chunks_in_memory={}/{}, consumer advancing to {}", chunk_index, new_count, self.max_chunks_in_memory, next_chunk @@ -668,6 +677,13 @@ impl StreamingCloudFetchProvider { true } + fn advance_chunk(&self) -> (usize, i64) { + let new_count = self.chunks_in_memory.fetch_sub(1, Ordering::Release) - 1; + let next_chunk = self.current_chunk_index.fetch_add(1, Ordering::Release) + 1; + self.metrics.record_chunk_iterated(); + (new_count, next_chunk) + } + /// Record the first terminal link-fetch failure and wake every waiter. /// /// Called from the link-fetch error paths once the transport's @@ -2721,6 +2737,140 @@ mod tests { ); } + #[tokio::test] + async fn try_next_batch_yields_on_lock_contention() { + use crate::reader::TryNextBatch; + + fn assert_pending(provider: &Arc, guard: G) { + let (sender, receiver) = std::sync::mpsc::channel(); + let provider = Arc::clone(provider); + let probe = std::thread::spawn(move || { + sender.send(provider.try_next_batch()).unwrap(); + }); + let outcome = receiver.recv_timeout(NO_HANG); + // Release before joining so a blocking regression fails by timeout. + drop(guard); + probe.join().unwrap(); + assert!(matches!( + outcome.expect("probe waited for a held lock").unwrap(), + TryNextBatch::Pending + )); + } + + enum HeldLock { + Buffer, + ChunkRead, + ChunkWrite, + EmptyShard, + TerminalError, + TerminalErrorAfterEmptyChunk, + } + + for held in [ + HeldLock::Buffer, + HeldLock::ChunkRead, + HeldLock::ChunkWrite, + HeldLock::EmptyShard, + HeldLock::TerminalError, + HeldLock::TerminalErrorAfterEmptyChunk, + ] { + let terminal = matches!( + held, + HeldLock::TerminalError | HeldLock::TerminalErrorAfterEmptyChunk + ); + let skipped = i64::from(matches!(held, HeldLock::TerminalErrorAfterEmptyChunk)); + let chunks = Arc::new(DashMap::new()); + if skipped > 0 { + chunks.insert( + 0, + entry_with_state(create_test_link(0), ChunkState::Downloaded), + ); + } + if !matches!(held, HeldLock::EmptyShard) { + let mut entry = entry_with_state( + create_test_link(skipped), + if terminal { + ChunkState::Downloading + } else { + ChunkState::Downloaded + }, + ); + entry.batches = Some(vec![make_batch(&[1]), make_batch(&[2])]); + chunks.insert(skipped, entry); + } + let provider = StreamingCloudFetchProvider::for_test_with_chunks( + Arc::new(MockLinkFetcher::new(2)), + unused_downloader(), + Arc::clone(&chunks), + true, + ); + provider + .chunks_in_memory + .store(chunks.len(), Ordering::Release); + if terminal { + *provider.terminal_error.lock().unwrap() = + Some(Error::unavailable().message("link fetch failed")); + } + if matches!(held, HeldLock::Buffer) { + provider + .current_batch_buffer + .lock() + .unwrap() + .push_back(make_batch(&[0])); + } + + match held { + HeldLock::Buffer => { + assert_pending(&provider, provider.current_batch_buffer.lock().unwrap()) + } + HeldLock::ChunkRead => assert_pending(&provider, chunks.get(&0).unwrap()), + HeldLock::ChunkWrite => assert_pending(&provider, chunks.get_mut(&0).unwrap()), + HeldLock::EmptyShard => assert_pending(&provider, chunks.entry(0)), + HeldLock::TerminalError | HeldLock::TerminalErrorAfterEmptyChunk => { + assert_pending(&provider, provider.terminal_error.lock().unwrap()); + } + } + assert_eq!( + provider.current_chunk_index.load(Ordering::Acquire), + skipped + ); + assert_eq!( + provider.chunks_in_memory.load(Ordering::Acquire), + chunks.len() + ); + assert_eq!( + provider + .metrics + .total_chunks_iterated + .load(Ordering::Acquire), + skipped as i32 + ); + if terminal { + let error = provider + .try_next_batch() + .expect_err("terminal error must survive contention"); + assert_eq!(error.code, ErrorCode::Unavailable); + assert_eq!(error.message, "link fetch failed"); + } else { + let expected = match held { + HeldLock::Buffer => vec![0, 1, 2], + HeldLock::EmptyShard => vec![], + _ => vec![1, 2], + }; + for value in expected { + match provider.try_next_batch().unwrap() { + TryNextBatch::Ready(batch) => assert_eq!(batch, make_batch(&[value])), + _ => panic!("buffered batches must survive contention in order"), + } + } + assert!(matches!( + provider.try_next_batch().unwrap(), + TryNextBatch::End + )); + } + } + } + /// A `Downloaded` chunk that decoded to zero batches must be skipped /// (the cursor advancing past it) so the caller sees the *next* /// chunk's data — not a spurious `Pending`/`End`. Guards the From 400c39baf40c0e75b4f67ad682779973e0ed0571 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 18 Nov 2026 21:43:48 +0000 Subject: [PATCH 7/9] test(pyo3): verify EOF cleanup before closing handles Signed-off-by: Aakash Saravanan --- pyo3/tests/test_fetch.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pyo3/tests/test_fetch.py b/pyo3/tests/test_fetch.py index 456d1949..79a54673 100644 --- a/pyo3/tests/test_fetch.py +++ b/pyo3/tests/test_fetch.py @@ -189,10 +189,11 @@ def test_buffered_fetch_closes_once_after_exhaustion(sql_api, batches): observed.append(batch.column(0).to_pylist()) assert observed == batches assert result.fetch_next_batch() is None + assert sql_api.statement_closed.wait(5) + assert Counter(sql_api.requests)["DELETE", sql_api.statement_path] == 1 result.close() result.close() statement.close() - assert sql_api.statement_closed.wait(5) assert Counter(sql_api.requests)["DELETE", sql_api.statement_path] == 1 assert result.arrow_schema() == schema with pytest.raises(k.KernelError, match="closed"): From 7cb521c48214885d6140526614e614986c36b962 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 19 Nov 2026 00:04:15 +0000 Subject: [PATCH 8/9] fix(cloudfetch): preserve continuation after empty chunks Continue the waiting fetch path past empty chunks and check EOF at the current cursor. Exercise the probe-to-wait handoff, delayed empty-chunk continuation, GIL release, and result cleanup before parent closure. Signed-off-by: Aakash Saravanan --- pyo3/src/fetch.rs | 10 +++ pyo3/tests/test_fetch.py | 23 ++++-- src/reader/cloudfetch/streaming_provider.rs | 85 +++++++++------------ 3 files changed, 63 insertions(+), 55 deletions(-) diff --git a/pyo3/src/fetch.rs b/pyo3/src/fetch.rs index aa5269b6..292284d7 100644 --- a/pyo3/src/fetch.rs +++ b/pyo3/src/fetch.rs @@ -160,6 +160,16 @@ mod tests { let entries = AtomicUsize::new(0); let pending = || { entries.fetch_add(1, Ordering::Relaxed); + let (sender, receiver) = std::sync::mpsc::channel(); + let worker = std::thread::spawn(move || { + Python::attach(|_| { + let _ = sender.send(()); + }); + }); + receiver + .recv_timeout(std::time::Duration::from_secs(5)) + .expect("pending fallback held the GIL"); + worker.join().unwrap(); runtime.block_on(async { Ok(None) }) }; Python::initialize(); diff --git a/pyo3/tests/test_fetch.py b/pyo3/tests/test_fetch.py index 79a54673..d6026656 100644 --- a/pyo3/tests/test_fetch.py +++ b/pyo3/tests/test_fetch.py @@ -79,7 +79,9 @@ def reply(self): } ], }, - "total_chunk_count": 2 if pending else 1, + "total_chunk_count": ( + 3 if state.mode == "cloud" else 2 if pending else 1 + ), "total_row_count": count + (2 if pending else 0), }, "result": { @@ -101,7 +103,9 @@ def reply(self): elif self.command == "DELETE" and path == statement_path: state.statement_closed.set() elif path == f"{statement_path}/result/chunks/1" and state.mode == "cloud": - response = {"external_links": [self.link(1)]} + response = {"external_links": [self.link(1), self.link(2)]} + elif path == "/storage/2": + response = arrow_bytes([[3, 4]]) elif path in (f"{statement_path}/result/chunks/1", "/storage/1"): state.chunk_requested.set() if not state.release_chunk.wait(5): @@ -112,7 +116,7 @@ def reply(self): {"error_code": "NOT_FOUND", "message": "missing chunk"}, ) elif state.mode == "cloud": - response = arrow_bytes([[3, 4]]) + response = arrow_bytes([]) else: response = { "chunk_index": 1, @@ -133,13 +137,14 @@ def reply(self): self.wfile.write(encoded) def link(self, index): + batches = state.batches if index == 0 else [] if index == 1 else [[3, 4]] return { "external_link": f"{state.host}/storage/{index}", "chunk_index": index, - "row_offset": index * 2, - "row_count": 2, - "byte_count": len(arrow_bytes(state.batches if index == 0 else [[3, 4]])), - "next_chunk_index": 1 if index == 0 else None, + "row_offset": 0 if index == 0 else 2, + "row_count": 0 if index == 1 else 2, + "byte_count": len(arrow_bytes(batches)), + "next_chunk_index": index + 1 if index < 2 else None, "expiration": "2099-01-01T00:00:00Z", } @@ -240,10 +245,12 @@ def test_partial_or_failed_fetch_retains_explicit_cleanup(sql_api, mode): for _ in range(2): with pytest.raises(k.KernelError, match="404|missing chunk"): result.fetch_next_batch() + assert not sql_api.statement_closed.is_set() result.close() - statement.close() assert sql_api.statement_closed.wait(5) assert Counter(sql_api.requests)["DELETE", sql_api.statement_path] == 1 + statement.close() + assert Counter(sql_api.requests)["DELETE", sql_api.statement_path] == 1 def test_drained_close_releases_last_runtime_owner(sql_api): diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index b8897520..854d916d 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -497,55 +497,38 @@ impl StreamingCloudFetchProvider { /// pre-merged during download (in background tasks), so each chunk /// typically yields a single large batch. pub async fn next_batch(&self) -> Result> { - // Check for cancellation - if self.cancel_token.is_cancelled() { - return Err(Error::invalid_state().message("Operation cancelled")); - } - - // Drain batch buffer first - if let Some(batch) = self.take_buffered_batch() { - return Ok(Some(batch)); - } - - // Buffer empty - need next chunk - let chunk_index = self.current_chunk_index.load(Ordering::Acquire); - - // Check if we've reached end of stream - if self.is_at_end(chunk_index) { - debug!("End of stream reached at chunk {}", chunk_index); - return Ok(None); - } - - // Wait for the chunk to be downloaded - self.wait_for_chunk(chunk_index).await?; - - // Get the chunk and move batches to buffer - if self.release_downloaded_chunk(chunk_index) { - // Schedule more downloads - self.schedule_downloads().await; + loop { if self.cancel_token.is_cancelled() { return Err(Error::invalid_state().message("Operation cancelled")); } - // Return first batch from buffer if let Some(batch) = self.take_buffered_batch() { return Ok(Some(batch)); } - } - // Check end of stream again - if self.end_of_stream.load(Ordering::Acquire) { - return Ok(None); - } + let chunk_index = self.current_chunk_index.load(Ordering::Acquire); + if self.is_at_end(chunk_index) { + debug!("End of stream reached at chunk {}", chunk_index); + return Ok(None); + } - // A terminal link-fetch failure that landed after the wait - // returned takes precedence over the generic "not found" - // message, so callers see the real cause deterministically. - if let Some(err) = self.terminal_error() { - return Err(err); - } + self.wait_for_chunk(chunk_index).await?; + if self.release_downloaded_chunk(chunk_index) { + self.schedule_downloads().await; + // An empty chunk can precede more data or a terminal error. + continue; + } + + if self.is_at_end(self.current_chunk_index.load(Ordering::Acquire)) { + return Ok(None); + } + if let Some(err) = self.terminal_error() { + return Err(err); + } - Err(Error::invalid_state().message(format!("Chunk {} not found after wait", chunk_index))) + return Err(Error::invalid_state() + .message(format!("Chunk {} not found after wait", chunk_index))); + } } /// Return the next batch if it is already downloaded, without waiting for @@ -2761,6 +2744,7 @@ mod tests { Buffer, ChunkRead, ChunkWrite, + EmptyChunkBeforeReady, EmptyShard, TerminalError, TerminalErrorAfterEmptyChunk, @@ -2770,6 +2754,7 @@ mod tests { HeldLock::Buffer, HeldLock::ChunkRead, HeldLock::ChunkWrite, + HeldLock::EmptyChunkBeforeReady, HeldLock::EmptyShard, HeldLock::TerminalError, HeldLock::TerminalErrorAfterEmptyChunk, @@ -2779,8 +2764,12 @@ mod tests { HeldLock::TerminalError | HeldLock::TerminalErrorAfterEmptyChunk ); let skipped = i64::from(matches!(held, HeldLock::TerminalErrorAfterEmptyChunk)); + let data_index = i64::from(matches!( + held, + HeldLock::TerminalErrorAfterEmptyChunk | HeldLock::EmptyChunkBeforeReady + )); let chunks = Arc::new(DashMap::new()); - if skipped > 0 { + if data_index > 0 { chunks.insert( 0, entry_with_state(create_test_link(0), ChunkState::Downloaded), @@ -2788,7 +2777,7 @@ mod tests { } if !matches!(held, HeldLock::EmptyShard) { let mut entry = entry_with_state( - create_test_link(skipped), + create_test_link(data_index), if terminal { ChunkState::Downloading } else { @@ -2796,7 +2785,7 @@ mod tests { }, ); entry.batches = Some(vec![make_batch(&[1]), make_batch(&[2])]); - chunks.insert(skipped, entry); + chunks.insert(data_index, entry); } let provider = StreamingCloudFetchProvider::for_test_with_chunks( Arc::new(MockLinkFetcher::new(2)), @@ -2823,7 +2812,9 @@ mod tests { HeldLock::Buffer => { assert_pending(&provider, provider.current_batch_buffer.lock().unwrap()) } - HeldLock::ChunkRead => assert_pending(&provider, chunks.get(&0).unwrap()), + HeldLock::ChunkRead | HeldLock::EmptyChunkBeforeReady => { + assert_pending(&provider, chunks.get(&0).unwrap()) + } HeldLock::ChunkWrite => assert_pending(&provider, chunks.get_mut(&0).unwrap()), HeldLock::EmptyShard => assert_pending(&provider, chunks.entry(0)), HeldLock::TerminalError | HeldLock::TerminalErrorAfterEmptyChunk => { @@ -2858,10 +2849,10 @@ mod tests { _ => vec![1, 2], }; for value in expected { - match provider.try_next_batch().unwrap() { - TryNextBatch::Ready(batch) => assert_eq!(batch, make_batch(&[value])), - _ => panic!("buffered batches must survive contention in order"), - } + assert_eq!( + provider.next_batch().await.unwrap(), + Some(make_batch(&[value])) + ); } assert!(matches!( provider.try_next_batch().unwrap(), From 1039133e94ec6220f5afb94ba9ff86ffea899b8e Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 19 Nov 2026 18:05:52 +0000 Subject: [PATCH 9/9] refactor(pyo3): simplify buffered reads and regression coverage Reuse the owned batch-read result and one local HTTP fixture across native and Python tests. Retain the existing unsupported-format error category and preserve earlier chunks before later link-fetch errors. Keep bounded contention and lifecycle checks while removing the redundant callback harness. Signed-off-by: Aakash Saravanan --- pyo3/src/fetch.rs | 173 ++++++---------- pyo3/src/result_stream.rs | 14 +- pyo3/src/statement.rs | 2 +- pyo3/tests/sql_api.py | 163 +++++++++++++++ pyo3/tests/test_fetch.py | 142 +------------ src/reader/cloudfetch/streaming_provider.rs | 209 ++++---------------- 6 files changed, 264 insertions(+), 439 deletions(-) create mode 100644 pyo3/tests/sql_api.py diff --git a/pyo3/src/fetch.rs b/pyo3/src/fetch.rs index 292284d7..64d39766 100644 --- a/pyo3/src/fetch.rs +++ b/pyo3/src/fetch.rs @@ -12,13 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Internal helpers for pulling batches out of a `ResultStream`. -//! -//! Shared by `ExecutedStatement` (drives the kernel `ExecutedStatement`'s -//! borrowed result stream) and `ResultStream` (owns its kernel -//! `ResultStream` directly). Both call `next_batch` on the kernel -//! stream and clone the Arrow `RecordBatch` out from under the -//! borrow so the result can cross the GIL boundary as an owned value. +//! Shared batch ownership and GIL handoff for both Python result handles. //! //! A nonblocking probe holds the GIL through kernel post-processing, so large //! batches requiring column rewrites can delay other Python threads. @@ -29,6 +23,7 @@ use arrow_array::RecordBatch; use arrow_pyarrow::ToPyArrow; use arrow_schema::Schema; +use databricks_sql_kernel::reader::TryNextBatch as BatchRead; use databricks_sql_kernel::{ Error, ExecutedStatement, Result, ResultBatch, ResultStream, TryNextBatch, }; @@ -36,21 +31,18 @@ use pyo3::prelude::*; use std::sync::Arc; use tokio::runtime::Runtime; -pub(crate) enum BatchRead { - Ready(RecordBatch), - Pending, - End, -} - fn own_arrow_batch(batch: &ResultBatch) -> Result { match batch { ResultBatch::Arrow(batch) => Ok(batch.clone()), - _ => Err(Error::invalid_state().message("kernel returned a non-Arrow ResultBatch variant")), + _ => { + Err(Error::invalid_argument() + .message("kernel returned a non-Arrow ResultBatch variant")) + } } } -fn own_batch(read: TryNextBatch<'_>) -> Result { - match read { +pub(crate) fn own_batch(read: Result>) -> Result { + match read? { TryNextBatch::Ready(batch) => own_arrow_batch(batch).map(BatchRead::Ready), TryNextBatch::Pending => Ok(BatchRead::Pending), TryNextBatch::End => Ok(BatchRead::End), @@ -58,26 +50,18 @@ fn own_batch(read: TryNextBatch<'_>) -> Result { } } -pub(crate) fn try_next_batch(stream: &mut ResultStream) -> Result { - own_batch(stream.try_next_batch()?) -} - -pub(crate) fn try_next_batch_exec(exec: &mut ExecutedStatement) -> Result { - own_batch(exec.try_next_batch()?) -} - pub(crate) fn read_batch( py: Python<'_>, read: Result, pending: impl FnOnce() -> Result> + pyo3::marker::Ungil, ) -> PyResult> { - match read.map_err(|error| crate::errors::to_py_err(py, error))? { + let result = match read.map_err(|error| crate::errors::to_py_err(py, error))? { BatchRead::Ready(batch) => Ok(Some(batch)), BatchRead::End => Ok(None), - BatchRead::Pending => py - .detach(pending) - .map_err(|error| crate::errors::to_py_err(py, error)), - } + BatchRead::Pending => py.detach(pending), + _ => Err(Error::invalid_state().message("kernel returned an unknown batch-read state")), + }; + result.map_err(|error| crate::errors::to_py_err(py, error)) } /// Pull the next batch from the kernel stream and return it as an @@ -192,94 +176,55 @@ mod tests { #[test] fn real_result_handles_return_eof_without_runtime_entry() { use pyo3::types::PyDict; - use std::io::{BufRead, BufReader, Read, Write}; - use std::net::{TcpListener, TcpStream}; - use std::sync::atomic::AtomicBool; - use std::time::Duration; - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let address = listener.local_addr().unwrap(); - let stopped = Arc::new(AtomicBool::new(false)); - let stop = Arc::clone(&stopped); - let server = std::thread::spawn(move || { - let body = r#"{"session_id":"00000000-0000-0000-0000-000000000001","statement_id":"00000000-0000-0000-0000-000000000002","status":{"state":"SUCCEEDED"},"manifest":{"format":"ARROW_STREAM","schema":{"column_count":0,"columns":[]},"total_row_count":0,"total_chunk_count":0}}"#; - let response = format!( - "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", - body.len() - ); - for stream in listener.incoming() { - if stop.load(Ordering::Acquire) { - break; - } - let mut stream = stream.unwrap(); - stream - .set_read_timeout(Some(Duration::from_secs(2))) - .unwrap(); - let mut request = BufReader::new(&mut stream); - let mut length = 0; - loop { - let mut line = String::new(); - if request.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" { - break; - } - if let Some((name, value)) = line.split_once(':') { - if name.eq_ignore_ascii_case("content-length") { - length = value.trim().parse().unwrap(); - } - } - } - if request.read_exact(&mut vec![0; length]).is_ok() { - let _ = stream.write_all(response.as_bytes()); - } - } - }); Python::initialize(); - let checked = Python::attach(|py| -> PyResult<()> { - let kwargs = PyDict::new(py); - kwargs.set_item("host", format!("http://{address}"))?; - kwargs.set_item("http_path", "/sql/1.0/warehouses/0000000000000001")?; - kwargs.set_item("access_token", "test-token")?; - kwargs.set_item("telemetry_enabled", false)?; - kwargs.set_item("request_timeout_secs", 2)?; - kwargs.set_item("retry_max_attempts", 1)?; - let session = py - .get_type::() - .call((), Some(&kwargs))?; - let runtime = tokio::runtime::Builder::new_current_thread() - .build() + Python::attach(|py| { + let globals = PyDict::new(py); + globals + .set_item("Session", py.get_type::()) .unwrap(); - let mut checked = Ok(()); - for asynchronous in [false, true] { - let statement = session.call_method0("statement")?; - statement.call_method1("set_sql", ("SELECT 1",))?; - let owner = - statement.call_method0(if asynchronous { "submit" } else { "execute" })?; - let result = if asynchronous { - owner.call_method0("await_result")? - } else { - owner.clone() - }; - // Tokio rejects nested block_on calls, exposing an unconditional - // runtime entry through either real Python result handle. - checked = runtime.block_on(async { - assert!(result.call_method0("fetch_next_batch")?.is_none()); - Ok(()) - }); - result.call_method0("close")?; - if asynchronous { - owner.call_method0("close")?; - } - statement.call_method0("close")?; - if checked.is_err() { - break; - } - } - session.call_method0("close")?; - checked + let fixture = std::ffi::CString::new(include_str!("../tests/sql_api.py")).unwrap(); + py.run(&fixture, Some(&globals), None).unwrap(); + py.run( + c"from contextlib import ExitStack\nresources = ExitStack()", + Some(&globals), + None, + ) + .unwrap(); + let checked = + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> PyResult<()> { + py.run( + c" +state = resources.enter_context(sql_api(Session)) +results = [] +for asynchronous in (False, True): + statement = state.session.statement() + resources.callback(statement.close) + statement.set_sql(\"SELECT 1\") + owner = statement.submit() if asynchronous else statement.execute() + resources.callback(owner.close) + result = owner.await_result() if asynchronous else owner + resources.callback(result.close) + results.append(result) +", + Some(&globals), + None, + )?; + let runtime = tokio::runtime::Builder::new_current_thread() + .build() + .unwrap(); + // Tokio rejects nested block_on calls through either real handle. + runtime.block_on(async { + py.run( + c"for result in results:\n assert result.fetch_next_batch() is None", + Some(&globals), + None, + ) + }) + })); + let cleanup = py.run(c"resources.close()", Some(&globals), None); + checked.unwrap().unwrap(); + cleanup.unwrap(); }); - stopped.store(true, Ordering::Release); - let _ = TcpStream::connect(address); - server.join().unwrap(); - checked.unwrap(); } } diff --git a/pyo3/src/result_stream.rs b/pyo3/src/result_stream.rs index 8e7d4f8c..1b5fc590 100644 --- a/pyo3/src/result_stream.rs +++ b/pyo3/src/result_stream.rs @@ -14,16 +14,8 @@ //! `ResultStream` — Python class wrapping a kernel `ResultStream`. //! -//! Returned by `Session.metadata().list_*` calls and (in future) -//! anywhere the kernel hands back a bare `ResultStream` without an -//! enclosing `ExecutedStatement`. Identical fetch surface to -//! `ExecutedStatement` (Arrow batches, drain-to-Table), minus the -//! statement_id / cancel hooks that only make sense for an executed -//! statement. -//! -//! The actual batch-pulling logic lives in `fetch::*` helpers so -//! `ExecutedStatement::fetch_next_batch` / `fetch_all_arrow` can call -//! the same code path through its `result_stream_mut()` borrow. +//! Returned by metadata calls and asynchronous statement reads. Server cleanup +//! belongs to the metadata close guard or the asynchronous statement owner. use crate::fetch; use crate::runtime::KernelRuntime; @@ -76,7 +68,7 @@ impl ResultStream { if inner.exhausted { return Ok(None); } - let batch = fetch::read_batch(py, fetch::try_next_batch(&mut inner.stream), || { + let batch = fetch::read_batch(py, fetch::own_batch(inner.stream.try_next_batch()), || { fetch::next_batch(&inner.runtime, &mut inner.stream) })?; match batch { diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index fa0699eb..2777b114 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -348,7 +348,7 @@ impl ExecutedStatement { if inner.exhausted { return Ok(None); } - let batch = fetch::read_batch(py, fetch::try_next_batch_exec(&mut inner.exec), || { + let batch = fetch::read_batch(py, fetch::own_batch(inner.exec.try_next_batch()), || { fetch::next_batch_exec(&inner.runtime, &mut inner.exec) })?; match batch { diff --git a/pyo3/tests/sql_api.py b/pyo3/tests/sql_api.py new file mode 100644 index 00000000..e4335bdf --- /dev/null +++ b/pyo3/tests/sql_api.py @@ -0,0 +1,163 @@ +# Copyright (c) 2026 Databricks, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Loopback SQL API shared by native binding and Python fetch tests.""" + +import base64 +import json +import threading +from contextlib import contextmanager +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from types import SimpleNamespace + + +@contextmanager +def sql_api(session_type, arrow_bytes=None): + state = SimpleNamespace( + batches=[[1, 2]] if arrow_bytes else [], + mode="buffered", + requests=[], + chunk_requested=threading.Event(), + release_chunk=threading.Event(), + statement_closed=threading.Event(), + ) + statement_id = "00000001-0000-0000-0000-000000000001" + statement_path = f"/api/2.0/sql/statements/{statement_id}" + + class Handler(BaseHTTPRequestHandler): + def reply(self): + self.rfile.read(int(self.headers.get("Content-Length", 0))) + path = self.path.split("?")[0] + state.requests.append((self.command, path)) + status, response = 200, {} + if self.command == "POST" and path.endswith("/sessions"): + response = {"session_id": "00000000-0000-0000-0000-000000000001"} + elif self.command == "POST" and path.endswith("/statements"): + pending = state.mode != "buffered" + raw = arrow_bytes(state.batches) if state.batches else b"" + count = sum(map(len, state.batches)) + response = { + "statement_id": statement_id, + "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": ( + 3 if state.mode == "cloud" else 2 if pending else 1 + ), + "total_row_count": count + (2 if pending else 0), + }, + "result": { + "chunk_index": 0, + "row_offset": 0, + "row_count": count, + "attachment": base64.b64encode(raw).decode(), + }, + } + if pending: + response["result"]["next_chunk_index"] = 1 + if state.mode == "cloud": + response["result"] = {"external_links": [self.link(0)]} + if not state.batches: + response.pop("result") + state.response = response + elif self.command == "GET" and path == statement_path: + response = state.response + elif self.command == "DELETE" and path == statement_path: + state.statement_closed.set() + elif path == f"{statement_path}/result/chunks/1" and state.mode == "cloud": + response = {"external_links": [self.link(1), self.link(2)]} + elif path == "/storage/2": + response = arrow_bytes([[3, 4]]) + elif path in (f"{statement_path}/result/chunks/1", "/storage/1"): + state.chunk_requested.set() + if not state.release_chunk.wait(5): + status, response = 408, {"message": "chunk gate timed out"} + elif state.mode == "error": + status, response = ( + 404, + {"error_code": "NOT_FOUND", "message": "missing chunk"}, + ) + elif state.mode == "cloud": + response = arrow_bytes([]) + else: + response = { + "chunk_index": 1, + "row_offset": 2, + "row_count": 2, + "attachment": base64.b64encode(arrow_bytes([[3, 4]])).decode(), + } + elif path == "/storage/0": + response = arrow_bytes([[1, 2]]) + encoded = ( + response + if isinstance(response, bytes) + else json.dumps(response).encode() + ) + self.send_response(status) + self.send_header("Content-Length", str(len(encoded))) + self.end_headers() + self.wfile.write(encoded) + + def link(self, index): + batches = state.batches if index == 0 else [] if index == 1 else [[3, 4]] + return { + "external_link": f"{state.host}/storage/{index}", + "chunk_index": index, + "row_offset": 0 if index == 0 else 2, + "row_count": 0 if index == 1 else 2, + "byte_count": len(arrow_bytes(batches)), + "next_chunk_index": index + 1 if index < 2 else None, + "expiration": "2099-01-01T00:00:00Z", + } + + do_POST = do_GET = do_DELETE = reply + + def log_message(self, *args): + pass + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + state.host = f"http://127.0.0.1:{server.server_port}" + state.statement_path = statement_path + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + state.session = session_type( + host=state.host, + http_path="/sql/1.0/warehouses/0000000000000001", + access_token="test-token", + telemetry_enabled=False, + request_timeout_secs=2, + retry_max_attempts=1, + ) + yield state + finally: + state.release_chunk.set() + try: + if hasattr(state, "session"): + state.session.close() + finally: + server.shutdown() + server.server_close() + thread.join(timeout=5) diff --git a/pyo3/tests/test_fetch.py b/pyo3/tests/test_fetch.py index d6026656..e23e5f76 100644 --- a/pyo3/tests/test_fetch.py +++ b/pyo3/tests/test_fetch.py @@ -14,17 +14,14 @@ """Buffered reads, pending I/O and result cleanup over a loopback SQL API.""" -import base64 -import json import threading from collections import Counter -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from types import SimpleNamespace import pyarrow as pa import pytest import databricks_sql_kernel as k +from sql_api import sql_api as local_sql_api def arrow_bytes(batches): @@ -38,144 +35,11 @@ def arrow_bytes(batches): return output.getvalue().to_pybytes() + @pytest.fixture def sql_api(): - state = SimpleNamespace( - batches=[[1, 2]], - mode="buffered", - requests=[], - chunk_requested=threading.Event(), - release_chunk=threading.Event(), - statement_closed=threading.Event(), - ) - statement_id = "00000001-0000-0000-0000-000000000001" - statement_path = f"/api/2.0/sql/statements/{statement_id}" - - class Handler(BaseHTTPRequestHandler): - def reply(self): - self.rfile.read(int(self.headers.get("Content-Length", 0))) - path = self.path.split("?")[0] - state.requests.append((self.command, path)) - status, response = 200, {} - if self.command == "POST" and path.endswith("/sessions"): - response = {"session_id": "00000000-0000-0000-0000-000000000001"} - elif self.command == "POST" and path.endswith("/statements"): - pending = state.mode != "buffered" - raw = arrow_bytes(state.batches) - count = sum(map(len, state.batches)) - response = { - "statement_id": statement_id, - "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": ( - 3 if state.mode == "cloud" else 2 if pending else 1 - ), - "total_row_count": count + (2 if pending else 0), - }, - "result": { - "chunk_index": 0, - "row_offset": 0, - "row_count": count, - "attachment": base64.b64encode(raw).decode(), - }, - } - if pending: - response["result"]["next_chunk_index"] = 1 - if state.mode == "cloud": - response["result"] = {"external_links": [self.link(0)]} - if not state.batches: - response.pop("result") - state.response = response - elif self.command == "GET" and path == statement_path: - response = state.response - elif self.command == "DELETE" and path == statement_path: - state.statement_closed.set() - elif path == f"{statement_path}/result/chunks/1" and state.mode == "cloud": - response = {"external_links": [self.link(1), self.link(2)]} - elif path == "/storage/2": - response = arrow_bytes([[3, 4]]) - elif path in (f"{statement_path}/result/chunks/1", "/storage/1"): - state.chunk_requested.set() - if not state.release_chunk.wait(5): - status, response = 408, {"message": "chunk gate timed out"} - elif state.mode == "error": - status, response = ( - 404, - {"error_code": "NOT_FOUND", "message": "missing chunk"}, - ) - elif state.mode == "cloud": - response = arrow_bytes([]) - else: - response = { - "chunk_index": 1, - "row_offset": 2, - "row_count": 2, - "attachment": base64.b64encode(arrow_bytes([[3, 4]])).decode(), - } - elif path == "/storage/0": - response = arrow_bytes([[1, 2]]) - encoded = ( - response - if isinstance(response, bytes) - else json.dumps(response).encode() - ) - self.send_response(status) - self.send_header("Content-Length", str(len(encoded))) - self.end_headers() - self.wfile.write(encoded) - - def link(self, index): - batches = state.batches if index == 0 else [] if index == 1 else [[3, 4]] - return { - "external_link": f"{state.host}/storage/{index}", - "chunk_index": index, - "row_offset": 0 if index == 0 else 2, - "row_count": 0 if index == 1 else 2, - "byte_count": len(arrow_bytes(batches)), - "next_chunk_index": index + 1 if index < 2 else None, - "expiration": "2099-01-01T00:00:00Z", - } - - do_POST = do_GET = do_DELETE = reply - - def log_message(self, *args): - pass - - server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) - server.daemon_threads = True - state.host = f"http://127.0.0.1:{server.server_port}" - state.statement_path = statement_path - thread = threading.Thread(target=server.serve_forever, daemon=True) - thread.start() - try: - state.session = k.Session( - host=state.host, - http_path="/sql/1.0/warehouses/0000000000000001", - access_token="test-token", - telemetry_enabled=False, - request_timeout_secs=2, - retry_max_attempts=1, - ) + with local_sql_api(k.Session, arrow_bytes) as state: yield state - finally: - state.release_chunk.set() - if hasattr(state, "session"): - state.session.close() - server.shutdown() - server.server_close() - thread.join(timeout=5) def execute(sql_api): diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index 854d916d..fc38026f 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -577,7 +577,7 @@ impl StreamingCloudFetchProvider { ChunkState::Cancelled => { break Err(Error::invalid_state().message("Operation cancelled")) } - _ => {} + _ => break Ok(TryNextBatch::Pending), }, Some(Entry::Vacant(_)) => {} } @@ -2670,54 +2670,41 @@ mod tests { )) } - /// `try_next_batch` must return `Pending` (without blocking) while the - /// head chunk is not yet `Downloaded`, then `Ready` once it flips, and - /// finally `End` after the last chunk is consumed. This exercises the - /// non-blocking chunk-state machine that diverges from `next_batch`. #[tokio::test] - async fn try_next_batch_pending_then_ready_then_end() { + async fn try_next_batch_preserves_chunk_order() { use crate::reader::TryNextBatch; - let chunks: Arc> = Arc::new(DashMap::new()); - // Chunk 0 present but still downloading — not ready to yield. + let chunks = Arc::new(DashMap::new()); chunks.insert( 0, entry_with_state(create_test_link(0), ChunkState::Downloading), ); - let fetcher: Arc = Arc::new(MockLinkFetcher::new(1)); let provider = StreamingCloudFetchProvider::for_test_with_chunks( - fetcher, + Arc::new(MockLinkFetcher::new(1)), unused_downloader(), Arc::clone(&chunks), - /* end_of_stream = */ true, + false, ); - // One chunk resident: `release_downloaded_chunk` decrements this. provider.chunks_in_memory.store(1, Ordering::Release); + *provider.terminal_error.lock().unwrap() = + Some(Error::unavailable().message("chunk 1 link fetch failed")); - // Not downloaded yet → Pending, and it must NOT block. - assert!( - matches!(provider.try_next_batch().unwrap(), TryNextBatch::Pending), - "a not-yet-Downloaded head chunk must report Pending" - ); - - // Flip the chunk to Downloaded with real batches, as a download - // task would. + assert!(matches!( + provider.try_next_batch().unwrap(), + TryNextBatch::Pending + )); { let mut entry = chunks.get_mut(&0).unwrap(); entry.state = ChunkState::Downloaded; entry.batches = Some(vec![make_batch(&[1, 2, 3])]); } - match provider.try_next_batch().unwrap() { - TryNextBatch::Ready(batch) => assert_eq!(batch.num_rows(), 3), - _ => panic!("expected Ready after chunk flipped to Downloaded"), + TryNextBatch::Ready(batch) => assert_eq!(batch, make_batch(&[1, 2, 3])), + _ => panic!("earlier rows must be returned before the link error"), } - - // Head chunk consumed; end_of_stream + no more chunks → End. - assert!( - matches!(provider.try_next_batch().unwrap(), TryNextBatch::End), - "after the only chunk is drained the stream must report End" - ); + let error = provider.try_next_batch().unwrap_err(); + assert_eq!(error.code, ErrorCode::Unavailable); + assert_eq!(error.message, "chunk 1 link fetch failed"); } #[tokio::test] @@ -2744,30 +2731,22 @@ mod tests { Buffer, ChunkRead, ChunkWrite, - EmptyChunkBeforeReady, EmptyShard, TerminalError, - TerminalErrorAfterEmptyChunk, } - for held in [ - HeldLock::Buffer, - HeldLock::ChunkRead, - HeldLock::ChunkWrite, - HeldLock::EmptyChunkBeforeReady, - HeldLock::EmptyShard, - HeldLock::TerminalError, - HeldLock::TerminalErrorAfterEmptyChunk, + for (held, empty_first) in [ + (HeldLock::Buffer, false), + (HeldLock::ChunkRead, false), + (HeldLock::ChunkWrite, false), + (HeldLock::ChunkRead, true), + (HeldLock::EmptyShard, false), + (HeldLock::TerminalError, false), + (HeldLock::TerminalError, true), ] { - let terminal = matches!( - held, - HeldLock::TerminalError | HeldLock::TerminalErrorAfterEmptyChunk - ); - let skipped = i64::from(matches!(held, HeldLock::TerminalErrorAfterEmptyChunk)); - let data_index = i64::from(matches!( - held, - HeldLock::TerminalErrorAfterEmptyChunk | HeldLock::EmptyChunkBeforeReady - )); + let terminal = matches!(held, HeldLock::TerminalError); + let skipped = i64::from(empty_first && terminal); + let data_index = i64::from(empty_first); let chunks = Arc::new(DashMap::new()); if data_index > 0 { chunks.insert( @@ -2775,15 +2754,9 @@ mod tests { entry_with_state(create_test_link(0), ChunkState::Downloaded), ); } - if !matches!(held, HeldLock::EmptyShard) { - let mut entry = entry_with_state( - create_test_link(data_index), - if terminal { - ChunkState::Downloading - } else { - ChunkState::Downloaded - }, - ); + if !matches!(held, HeldLock::EmptyShard | HeldLock::TerminalError) { + let mut entry = + entry_with_state(create_test_link(data_index), ChunkState::Downloaded); entry.batches = Some(vec![make_batch(&[1]), make_batch(&[2])]); chunks.insert(data_index, entry); } @@ -2791,7 +2764,7 @@ mod tests { Arc::new(MockLinkFetcher::new(2)), unused_downloader(), Arc::clone(&chunks), - true, + !terminal, ); provider .chunks_in_memory @@ -2812,12 +2785,10 @@ mod tests { HeldLock::Buffer => { assert_pending(&provider, provider.current_batch_buffer.lock().unwrap()) } - HeldLock::ChunkRead | HeldLock::EmptyChunkBeforeReady => { - assert_pending(&provider, chunks.get(&0).unwrap()) - } + HeldLock::ChunkRead => assert_pending(&provider, chunks.get(&0).unwrap()), HeldLock::ChunkWrite => assert_pending(&provider, chunks.get_mut(&0).unwrap()), HeldLock::EmptyShard => assert_pending(&provider, chunks.entry(0)), - HeldLock::TerminalError | HeldLock::TerminalErrorAfterEmptyChunk => { + HeldLock::TerminalError => { assert_pending(&provider, provider.terminal_error.lock().unwrap()); } } @@ -2830,11 +2801,8 @@ mod tests { chunks.len() ); assert_eq!( - provider - .metrics - .total_chunks_iterated - .load(Ordering::Acquire), - skipped as i32 + provider.metrics.snapshot().total_chunks_iterated, + Some(skipped as i32) ); if terminal { let error = provider @@ -3250,87 +3218,6 @@ mod tests { ); } - #[tokio::test] - async fn refresh_skip_logs_release_chunk_guard() { - use tracing_subscriber::prelude::*; - - struct CheckLogLock { - chunks: Arc>, - logged: Arc, - } - - impl tracing_subscriber::Layer for CheckLogLock { - fn on_event( - &self, - event: &tracing::Event<'_>, - _: tracing_subscriber::layer::Context<'_, S>, - ) { - event.record( - &mut |field: &tracing::field::Field, value: &dyn std::fmt::Debug| { - if field.name() != "message" { - return; - } - let message = format!("{value:?}"); - if message.starts_with("Concurrent refresh delivered") - || message.contains("skipped after claim") - { - assert!( - self.chunks.try_get_mut(&0).is_present(), - "refresh log callback must be able to write the chunk: {message}" - ); - self.logged.store(true, Ordering::Release); - } - }, - ); - } - } - - for contended in [false, true] { - let chunks = Arc::new(DashMap::new()); - let link = if contended { - expired_link(0) - } else { - create_test_link(0) - }; - chunks.insert(0, entry_with_state(link, ChunkState::UrlFetched)); - let mock = RefreshCountingMock::new(1); - let fetcher: Arc = mock.clone(); - let coordinator = Arc::new(RefreshCoordinator::default()); - coordinator.in_progress.store(contended, Ordering::Release); - let cancel = CancellationToken::new(); - let logged = Arc::new(AtomicBool::new(false)); - let subscriber = tracing_subscriber::registry().with(CheckLogLock { - chunks: Arc::clone(&chunks), - logged: Arc::clone(&logged), - }); - let _guard = tracing::subscriber::set_default(subscriber); - - let mut refresh = Box::pin(StreamingCloudFetchProvider::refresh_links_batch( - 0, - &fetcher, - &chunks, - &coordinator, - &cancel, - None, - )); - if contended { - assert!(futures::poll!(refresh.as_mut()).is_pending()); - chunks.insert( - 0, - entry_with_state(create_test_link(0), ChunkState::UrlFetched), - ); - coordinator.in_progress.store(false, Ordering::Release); - coordinator.done.notify_waiters(); - } - tokio::time::timeout(NO_HANG, refresh) - .await - .unwrap() - .unwrap(); - assert!(logged.load(Ordering::Acquire), "contended={contended}"); - assert_eq!(mock.refresh_calls.load(AtomicOrdering::SeqCst), 0); - } - } - #[tokio::test] async fn refresh_batch_disjoint_window_loser_retries_claim() { // Loser-of-claim disjoint-window gap (round-3 follow-up): @@ -4477,36 +4364,10 @@ mod tests { /// failure does not overwrite the originally-persisted error. #[tokio::test] async fn first_terminal_error_wins() { - use tracing_subscriber::prelude::*; - - struct CheckLogLock { - provider: Arc, - logged: Arc, - } - - impl tracing_subscriber::Layer for CheckLogLock { - fn on_event( - &self, - _: &tracing::Event<'_>, - _: tracing_subscriber::layer::Context<'_, S>, - ) { - assert!(self.provider.terminal_error.try_lock().is_ok()); - self.logged.store(true, Ordering::Release); - } - } - let fetcher = FailingLinkFetcher::new(4, 2, 0); let provider = provider_with_failing_fetcher(fetcher, Some(4)); - let logged = Arc::new(AtomicBool::new(false)); - let subscriber = tracing_subscriber::registry().with(CheckLogLock { - provider: Arc::clone(&provider), - logged: Arc::clone(&logged), - }); - let _guard = tracing::subscriber::set_default(subscriber); - provider.set_terminal_error(Error::io().message("first error")); provider.set_terminal_error(Error::io().message("second error")); - assert!(logged.load(Ordering::Acquire)); let stored = provider .terminal_error()