From 24e03b46b464bcbb97b569c3eac57eb01af9cb77 Mon Sep 17 00:00:00 2001 From: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:12:51 +0000 Subject: [PATCH] fix(python): release cancelled query streams --- python/python/lancedb/arrow.py | 4 + python/src/arrow.rs | 166 ++++++++++++++++++++++++++++++--- 2 files changed, 155 insertions(+), 15 deletions(-) diff --git a/python/python/lancedb/arrow.py b/python/python/lancedb/arrow.py index c5a278ead..f31794ac4 100644 --- a/python/python/lancedb/arrow.py +++ b/python/python/lancedb/arrow.py @@ -15,6 +15,10 @@ class AsyncRecordBatchReader: An async iterator over a stream of RecordBatches. Also allows access to the schema of the stream + + Cancelling an active batch read closes its native query stream. Further reads + of that stream raise ``RuntimeError``; run the query again to obtain a new + reader. """ def __init__( diff --git a/python/src/arrow.rs b/python/src/arrow.rs index f0b4bceed..c1b6c90ba 100644 --- a/python/src/arrow.rs +++ b/python/src/arrow.rs @@ -6,19 +6,22 @@ use std::sync::Arc; use crate::error::PythonErrorExt; use crate::runtime::future_into_py; use arrow::{ + array::RecordBatch, datatypes::SchemaRef, pyarrow::{IntoPyArrow, ToPyArrow}, }; use futures::stream::StreamExt; use lancedb::arrow::SendableRecordBatchStream; use pyo3::{ - Bound, Py, PyAny, PyRef, PyResult, Python, exceptions::PyStopAsyncIteration, pyclass, pymethods, + Bound, Py, PyAny, PyRef, PyResult, Python, + exceptions::{PyRuntimeError, PyStopAsyncIteration}, + pyclass, pymethods, }; #[pyclass] pub struct RecordBatchStream { schema: SchemaRef, - inner: Arc>, + inner: Arc>>, } impl RecordBatchStream { @@ -26,9 +29,26 @@ impl RecordBatchStream { let schema = inner.schema().clone(); Self { schema, - inner: Arc::new(tokio::sync::Mutex::new(inner)), + inner: Arc::new(tokio::sync::Mutex::new(Some(inner))), } } + + async fn next_batch( + inner: &tokio::sync::Mutex>, + ) -> PyResult { + let mut slot = inner.lock().await; + // Serialize reads with the mutex, but let this future own the stream. + // Cancellation must drop the parked execution and its cache loader guards + // even if Python keeps the reader alive. An empty slot marks cancellation. + let mut stream = slot + .take() + .ok_or_else(|| PyRuntimeError::new_err("Record batch stream was cancelled"))?; + let next = stream.next().await; + *slot = Some(stream); + drop(slot); + next.ok_or_else(|| PyStopAsyncIteration::new_err(""))? + .infer_error() + } } #[pymethods] @@ -48,18 +68,134 @@ impl RecordBatchStream { pub fn __anext__(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { - let inner_next = inner - .lock() - .await - .next() - .await - .ok_or_else(|| PyStopAsyncIteration::new_err(""))?; - Python::attach(|py| { - inner_next - .infer_error()? - .to_pyarrow(py) - .map(|obj| obj.unbind()) - }) + let batch = Self::next_batch(&inner).await?; + Python::attach(|py| batch.to_pyarrow(py).map(|obj| obj.unbind())) }) } } + +#[cfg(test)] +mod tests { + use super::*; + use arrow::datatypes::Schema; + use futures::{FutureExt, stream}; + use lancedb::arrow::SimpleRecordBatchStream; + use pyo3::types::{PyAnyMethods, PyDict, PyDictMethods}; + use tokio::sync::oneshot; + + struct NotifyOnDrop(Py); + + impl Drop for NotifyOnDrop { + fn drop(&mut self) { + Python::attach(|py| { + self.0.bind(py).call_method0("set").unwrap(); + }); + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn cancelled_read_drops_stream_while_reader_is_retained() { + Python::initialize(); + Python::attach(|py| { + let threading = py.import("threading").unwrap(); + let polled = threading.call_method0("Event").unwrap(); + let released = threading.call_method0("Event").unwrap(); + let on_poll = polled.clone().unbind(); + let on_drop = NotifyOnDrop(released.clone().unbind()); + // Model a cache loader guard held inside the stream's first poll. + let stream = stream::once(async move { + let _guard = on_drop; + Python::attach(|py| { + on_poll.bind(py).call_method0("set").unwrap(); + }); + futures::future::pending::>().await + }); + let reader = RecordBatchStream::new(Box::pin(SimpleRecordBatchStream::new( + stream, + Arc::new(Schema::empty()), + ))); + let locals = PyDict::new(py); + locals + .set_item("reader", Py::new(py, reader).unwrap()) + .unwrap(); + locals.set_item("polled", polled).unwrap(); + locals.set_item("released", released).unwrap(); + py.run( + c"import asyncio + +async def read(): + return await reader.__anext__() + +async def check(): + task = asyncio.create_task(read()) + assert await asyncio.to_thread(polled.wait, 5), 'stream was never polled' + assert task.cancel() + try: + await task + except asyncio.CancelledError: + pass + else: + raise AssertionError('read was not cancelled') + # Keep both reader and task alive: cancellation must release the parked + # execution without relying on Python reference counting or collection. + assert await asyncio.to_thread(released.wait, 5), 'stream was retained after cancellation' + try: + await reader.__anext__() + except RuntimeError as error: + assert 'cancelled' in str(error) + else: + raise AssertionError('cancelled stream did not raise RuntimeError') + +asyncio.run(check())", + Some(&locals), + None, + ) + .unwrap(); + }); + } + + #[tokio::test] + async fn cancelling_a_waiting_read_preserves_the_active_read() { + let schema = Arc::new(Schema::empty()); + let batch = RecordBatch::new_empty(schema.clone()); + let expected = batch.clone(); + let (send, receive) = oneshot::channel(); + let stream = stream::once(async move { + receive.await.unwrap(); + Ok(batch) + }); + let reader = RecordBatchStream::new(Box::pin(SimpleRecordBatchStream::new(stream, schema))); + + let mut active = Box::pin(RecordBatchStream::next_batch(&reader.inner)); + assert!(futures::poll!(active.as_mut()).is_pending()); + let mut waiting = Box::pin(RecordBatchStream::next_batch(&reader.inner)); + assert!(futures::poll!(waiting.as_mut()).is_pending()); + drop(waiting); + + send.send(()).unwrap(); + assert_eq!(active.await.unwrap(), expected); + } + + #[tokio::test] + async fn completed_reads_preserve_remaining_batches_and_exhaustion() { + let schema = Arc::new(Schema::empty()); + let batch = RecordBatch::new_empty(schema.clone()); + let stream = stream::iter([Ok(batch.clone()), Ok(batch.clone())]); + let reader = RecordBatchStream::new(Box::pin(SimpleRecordBatchStream::new(stream, schema))); + + for _ in 0..2 { + assert_eq!( + RecordBatchStream::next_batch(&reader.inner).await.unwrap(), + batch + ); + } + Python::initialize(); + for _ in 0..2 { + let error = RecordBatchStream::next_batch(&reader.inner) + .now_or_never() + .expect("an exhausted stream must not wait") + .unwrap_err(); + Python::attach(|py| assert!(error.is_instance_of::(py))); + } + } +}