diff --git a/pyo3/src/fetch.rs b/pyo3/src/fetch.rs index 9e7d859c..64d39766 100644 --- a/pyo3/src/fetch.rs +++ b/pyo3/src/fetch.rs @@ -12,22 +12,58 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Internal helpers for pulling batches out of a `ResultStream`. +//! Shared batch ownership and GIL handoff for both Python result handles. //! -//! 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. +//! A nonblocking probe holds the GIL through kernel post-processing, so large +//! batches requiring column rewrites can delay other Python threads. +//! +//! Contended CloudFetch provider-state locks yield `Pending`, allowing the +//! fallback to wait with the GIL released. 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::reader::TryNextBatch as BatchRead; +use databricks_sql_kernel::{ + Error, ExecutedStatement, Result, ResultBatch, ResultStream, TryNextBatch, +}; use pyo3::prelude::*; use std::sync::Arc; use tokio::runtime::Runtime; +fn own_arrow_batch(batch: &ResultBatch) -> Result { + match batch { + ResultBatch::Arrow(batch) => Ok(batch.clone()), + _ => { + Err(Error::invalid_argument() + .message("kernel returned a non-Arrow ResultBatch variant")) + } + } +} + +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), + _ => Err(Error::invalid_state().message("kernel returned an unknown batch-read state")), + } +} + +pub(crate) fn read_batch( + py: Python<'_>, + read: Result, + pending: impl FnOnce() -> Result> + pyo3::marker::Ungil, +) -> PyResult> { + 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), + _ => 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 /// owned `RecordBatch`, or `None` if the stream is exhausted. /// @@ -37,29 +73,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) }) @@ -72,14 +94,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- @@ -91,15 +106,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) }) @@ -122,3 +130,101 @@ 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); + 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(); + 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); + }); + } + + #[test] + fn real_result_handles_return_eof_without_runtime_entry() { + use pyo3::types::PyDict; + + Python::initialize(); + Python::attach(|py| { + let globals = PyDict::new(py); + globals + .set_item("Session", py.get_type::()) + .unwrap(); + 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(); + }); + } +} 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/pyo3/src/logging.rs b/pyo3/src/logging.rs index 0271f276..cdb331c6 100644 --- a/pyo3/src/logging.rs +++ b/pyo3/src/logging.rs @@ -37,16 +37,20 @@ //! 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. 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 //! @@ -166,9 +170,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/pyo3/src/result_stream.rs b/pyo3/src/result_stream.rs index cd193bb9..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,8 +68,9 @@ 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 = fetch::read_batch(py, fetch::own_batch(inner.stream.try_next_batch()), || { + 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 7f2dc3e8..2777b114 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -348,11 +348,9 @@ 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 = fetch::read_batch(py, fetch::own_batch(inner.exec.try_next_batch()), || { + fetch::next_batch_exec(&inner.runtime, &mut inner.exec) + })?; match batch { Some(b) => Ok(Some(b.to_pyarrow(py)?)), None => { @@ -397,7 +395,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/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 new file mode 100644 index 00000000..e23e5f76 --- /dev/null +++ b/pyo3/tests/test_fetch.py @@ -0,0 +1,128 @@ +# 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 threading +from collections import Counter + +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): + 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(): + with local_sql_api(k.Session, arrow_bytes) as state: + yield state + + +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 + 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 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() + assert not sql_api.statement_closed.is_set() + result.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): + 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() diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index b2683ca1..fc38026f 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; @@ -106,6 +106,10 @@ fn flush_pending(schema: &SchemaRef, pending: &mut Vec) -> Result, @@ -493,60 +497,43 @@ 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 - /// 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; @@ -556,18 +543,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())) @@ -575,28 +577,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); + _ => 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 @@ -604,6 +597,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 @@ -653,9 +652,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 @@ -663,6 +660,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 @@ -673,18 +677,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 +1385,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 +1436,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 — \ @@ -2659,54 +2670,164 @@ 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"), } + let error = provider.try_next_batch().unwrap_err(); + assert_eq!(error.code, ErrorCode::Unavailable); + assert_eq!(error.message, "chunk 1 link fetch failed"); + } - // 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" - ); + #[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, + } + + 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); + 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( + 0, + entry_with_state(create_test_link(0), 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); + } + let provider = StreamingCloudFetchProvider::for_test_with_chunks( + Arc::new(MockLinkFetcher::new(2)), + unused_downloader(), + Arc::clone(&chunks), + !terminal, + ); + 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 => { + 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.snapshot().total_chunks_iterated, + Some(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 { + assert_eq!( + provider.next_batch().await.unwrap(), + Some(make_batch(&[value])) + ); + } + assert!(matches!( + provider.try_next_batch().unwrap(), + TryNextBatch::End + )); + } + } } /// A `Downloaded` chunk that decoded to zero batches must be skipped @@ -4245,7 +4366,6 @@ mod tests { async fn first_terminal_error_wins() { let fetcher = FailingLinkFetcher::new(4, 2, 0); let provider = provider_with_failing_fetcher(fetcher, Some(4)); - provider.set_terminal_error(Error::io().message("first error")); provider.set_terminal_error(Error::io().message("second error"));