From 8b8778938fe0ae214dbc67eb73350078d9cc88ce Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 21 Nov 2026 06:25:05 +0800 Subject: [PATCH] perf(python): stream plain sync batches on demand (#5143) ## Problem Synchronous local `table.search().to_batches()` creates one Python future per batch through the background event loop. At the default 1024-row cap, a large scan pays that Python round trip thousands of times even though the Rust stream can produce the next batch immediately. ## Change Use a pull-driven synchronous reader for native, non-namespace, ordinary lazy plain scans. The query is executed once with the same `QueryExecutionOptions` as the async path: `None` keeps the 1024-row cap, `0` leaves sizing to the engine, and a positive value caps each returned batch. Each `__next__` releases the GIL, waits for exactly one batch from the same Rust stream through the reviewed `block_on_interruptible`, and stores the stream back on success. - No background producer and no Python `LOOP.run` per batch. - A read error, interrupt, EOF, or the last owner drops the stream. A normal early `break` can resume the same reader. - The public `pa.RecordBatchReader` still comes from `from_batches`, so the schema, Arrow capsule, and exception types stay unchanged. Existing PyArrow `close()` behavior is unchanged; the known PyArrow close issue is separately scoped. - Routing is limited to native, non-namespace, lazy plain scans. Vector, take, FTS/hybrid, remote, namespace, `to_arrow` direct eager routes, and Blob `bytes`/`descriptions` keep their existing paths. Take ordering from #5140 remains on the take path. - Forward explicit `scan_in_order` through the pull launch; base-only ordered `to_batches` results and the incompatible `order_by`/fragment behavior are included in the scan-order suite. - Adds a public RTE `to_batches` regression: the default LSM route sees pending memtable writes, while `use_rte(False)` remains base-only. ## Validation - `test_sync_pull_reader.py`, `test_merge_insert_lsm.py`, and `test_sync_query_direct.py`: 53 passed. - `test_query.py`, `test_blob.py`, and `test_blob_query_without_pylance.py`: 539 passed, 1 skipped. - `test_table.py`: 552 passed, 17 skipped. - `test_remote_db.py -k "to_batches or take"`: 16 passed. - `test_background_loop.py`: 4 passed. - Rust `cargo test --manifest-path python/Cargo.toml --lib sync_stream`: 5 passed. - `cargo check -j 1 --manifest-path python/Cargo.toml --lib --tests` passed; no full Rust doctests were run. A matched same-base release-with-debug streaming comparison is a follow-up and is not claimed here. Tracking: [OSS-2865](https://linear.app/lancedb/issue/OSS-2865) --- python/python/lancedb/_lancedb.pyi | 9 + python/python/lancedb/query.py | 36 ++- python/python/lancedb/table.py | 31 ++ python/python/tests/test_merge_insert_lsm.py | 19 ++ python/python/tests/test_sync_pull_reader.py | 195 ++++++++++++ python/src/lib.rs | 2 + python/src/query.rs | 46 ++- python/src/sync_stream.rs | 298 +++++++++++++++++++ 8 files changed, 628 insertions(+), 8 deletions(-) create mode 100644 python/python/tests/test_sync_pull_reader.py create mode 100644 python/src/sync_stream.rs diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index f40fbc30c..129304f0a 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -952,6 +952,12 @@ class RecordBatchStream: def __aiter__(self) -> "RecordBatchStream": ... async def __anext__(self) -> pa.RecordBatch: ... +class SyncRecordBatchStream: + @property + def schema(self) -> pa.Schema: ... + def __iter__(self) -> "SyncRecordBatchStream": ... + def __next__(self) -> pa.RecordBatch: ... + class ColumnOrdering(TypedDict): column_name: str ascending: bool @@ -977,6 +983,9 @@ class Query: async def execute( self, max_batch_length: Optional[int], timeout: Optional[timedelta] ) -> RecordBatchStream: ... + def execute_sync( + self, max_batch_length: Optional[int], timeout: Optional[timedelta] + ) -> SyncRecordBatchStream: ... async def execute_to_reader( self, max_batch_length: Optional[int], timeout: Optional[timedelta] ) -> pa.RecordBatchReader: ... diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 68598dd68..93f84aeca 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -1850,7 +1850,14 @@ class LanceQueryBuilder(ABC): ) -> pa.RecordBatchReader: query = self._query_for_scan(blob_sources, schema) reader = self._execute_query_prepared( - query, batch_size=batch_size, timeout=timeout + query, + batch_size=batch_size, + timeout=timeout, + pull_reader=( + blob_mode == "lazy" + and _query_is_plain_scan(query) + and not _query_needs_lance_scanner(self) + ), ) return self._batches_in_mode(reader, blob_mode, blob_sources, schema) @@ -1860,9 +1867,19 @@ class LanceQueryBuilder(ABC): *, batch_size: Optional[int] = None, timeout: Optional[timedelta] = None, + pull_reader: bool = False, ) -> pa.RecordBatchReader: if not _is_remote_query_table(self._table): query._blob_row_id_prepared = True + if ( + pull_reader + and not _is_remote_query_table(self._table) + and not self._table.namespace + and getattr(self._table, "_namespace_client", None) is None + ): + return self._table._execute_pull_query( + query, batch_size=batch_size, timeout=timeout + ) return self._table._execute_query(query, batch_size=batch_size, timeout=timeout) def _execute_arrow_prepared( @@ -4933,6 +4950,23 @@ class AsyncQuery(AsyncStandardQuery): super().__init__(inner, table) self._inner = inner + def _execute_batches_sync( + self, + *, + max_batch_length: Optional[int] = None, + timeout: Optional[timedelta] = None, + ) -> pa.RecordBatchReader: + """Execute a plain local scan with one Rust fetch per batch. + + The query starts once; each iteration asks the same Rust stream for a + single batch instead of submitting one Python future per batch to the + background event loop. The public reader type and schema come from the + same stream, so Arrow export and exception behavior stay unchanged. + """ + self._ensure_fragment_constraints_supported("to_batches()") + stream = self._inner.execute_sync(max_batch_length, timeout) + return pa.RecordBatchReader.from_batches(stream.schema, stream) + def scan_in_order(self, ordered: bool = True) -> Self: """Control whether an ordinary scan must preserve storage order. diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 529375f6e..c241ab725 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2961,6 +2961,16 @@ class Table(ABC): timeout: Optional[timedelta] = None, ) -> pa.RecordBatchReader: ... + def _execute_pull_query( + self, + query: Query, + *, + batch_size: Optional[int] = None, + timeout: Optional[timedelta] = None, + ) -> pa.RecordBatchReader: + """Execute a pull-driven batch query, falling back to the normal path.""" + return self._execute_query(query, batch_size=batch_size, timeout=timeout) + def _execute_arrow( self, query: Query, @@ -6047,6 +6057,27 @@ class LanceTable(Table): return pa.RecordBatchReader.from_batches(async_iter.schema, iter_sync()) + def _execute_pull_query( + self, + query: Query, + *, + batch_size: Optional[int] = None, + timeout: Optional[timedelta] = None, + ) -> pa.RecordBatchReader: + """Execute a plain local scan with one Rust fetch per batch. + + The caller has already checked that this is an embedded, non-namespace + plain lazy scan. A query shape that does not map to ``AsyncQuery`` + keeps the existing reader path instead of guessing at its semantics. + """ + async_query = self._table._sync_query_to_async(query) + async_query._blob_row_id_prepared = query._blob_row_id_prepared + if isinstance(async_query, AsyncQuery): + return async_query._execute_batches_sync( + max_batch_length=batch_size, timeout=timeout + ) + return self._execute_query(query, batch_size=batch_size, timeout=timeout) + def _execute_arrow( self, query: Query, diff --git a/python/python/tests/test_merge_insert_lsm.py b/python/python/tests/test_merge_insert_lsm.py index f5280383c..5b4114112 100644 --- a/python/python/tests/test_merge_insert_lsm.py +++ b/python/python/tests/test_merge_insert_lsm.py @@ -241,6 +241,25 @@ def test_lsm_read_sees_active_memtable(tmp_path): assert sorted(base_only["id"].to_pylist()) == [1, 2, 3] +def test_lsm_read_to_batches_sees_active_memtable(tmp_path): + db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0)) + table = db.create_table("t", _reader([1, 2, 3])) # base ids 1,2,3 + table.set_unenforced_primary_key("id") + table.enable_rte(RTEWriteSpec.unsharded()) + + _lsm_upsert(table, [4, 5]) # active memtable only, not committed to base + + # The sync batch reader keeps the default LSM route and its pending writes. + lsm = pa.Table.from_batches(list(table.search().to_batches(batch_size=2))) + assert sorted(lsm["id"].to_pylist()) == [1, 2, 3, 4, 5] + + # use_rte(False) still takes the base-only escape hatch through to_batches. + base_only = pa.Table.from_batches( + list(table.search().use_rte(False).to_batches(batch_size=2)) + ) + assert sorted(base_only["id"].to_pylist()) == [1, 2, 3] + + def test_lsm_read_dedup_newest_wins(tmp_path): db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0)) table = db.create_table("t", _reader([1, 2, 3])) # id 2 -> value 1 diff --git a/python/python/tests/test_sync_pull_reader.py b/python/python/tests/test_sync_pull_reader.py new file mode 100644 index 000000000..3994b11d2 --- /dev/null +++ b/python/python/tests/test_sync_pull_reader.py @@ -0,0 +1,195 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import gc +import time +from datetime import timedelta + +import pyarrow as pa +import pytest + +import lancedb +import lancedb.table as table_module +from lancedb.query import AsyncQuery + + +def _table(db, name="sync_pull_reader"): + return db.create_table( + name, + data=[{"id": i, "vector": [float(i), float(i)]} for i in range(10)], + ) + + +def _spy_on_pull_reader(monkeypatch): + calls = [] + real = AsyncQuery._execute_batches_sync + + def spy(self, *, max_batch_length=None, timeout=None): + calls.append((max_batch_length, timeout)) + return real(self, max_batch_length=max_batch_length, timeout=timeout) + + monkeypatch.setattr(AsyncQuery, "_execute_batches_sync", spy) + return calls + + +@pytest.mark.parametrize( + "batch_size,row_limit", + [ + (None, 1024), + (0, None), + (4, 4), + ], +) +def test_plain_sync_batches_use_pull_reader(mem_db, monkeypatch, batch_size, row_limit): + table = _table(mem_db) + calls = _spy_on_pull_reader(monkeypatch) + + reader = table.search().select(["id"]).to_batches(batch_size=batch_size) + + assert isinstance(reader, pa.RecordBatchReader) + assert calls == [(batch_size, None)] + batches = list(reader) + assert sum(batch.num_rows for batch in batches) == 10 + assert pa.Table.from_batches(batches).column("id").to_pylist() == list(range(10)) + if row_limit is not None: + assert all(batch.num_rows <= row_limit for batch in batches) + + +def test_scan_in_order_routes_through_pull_reader(tmp_db, monkeypatch): + table = tmp_db.create_table("ordered_pull_reader", pa.table({"id": [0, 1]})) + table.add(pa.table({"id": [2, 3]})) + table.add(pa.table({"id": [4, 5]})) + table.checkout(table.version) + calls = _spy_on_pull_reader(monkeypatch) + + reader = table.search().scan_in_order(True).select(["id"]).to_batches(batch_size=2) + + assert calls == [(2, None)] + assert [value for batch in reader for value in batch["id"].to_pylist()] == [ + 0, + 1, + 2, + 3, + 4, + 5, + ] + with pytest.raises(ValueError, match="nonempty order_by"): + table.search().scan_in_order(True).order_by("id").to_batches() + + +def test_plain_sync_batches_do_not_enter_background_loop(mem_db, monkeypatch): + table = _table(mem_db) + + def fail(*args, **kwargs): + raise AssertionError("plain sync batches entered the background event loop") + + monkeypatch.setattr(table_module.LOOP, "run", fail) + + reader = table.search().select(["id"]).to_batches(batch_size=4) + + assert sum(batch.num_rows for batch in reader) == 10 + + +@pytest.mark.parametrize( + "execute", + [ + lambda table: table.search().select(["id"]).to_arrow(), + lambda table: table.search([0.0, 0.0]).to_batches(), + lambda table: table.take_offsets([0]).to_batches(), + lambda table: table.search().select(["id"]).order_by(["id"]).to_batches(), + lambda table: ( + table.search().select(["id"]).to_batches(blob_mode="descriptions") + ), + ], +) +def test_other_sync_routes_keep_the_existing_reader(mem_db, monkeypatch, execute): + table = _table(mem_db) + calls = _spy_on_pull_reader(monkeypatch) + + execute(table) + + assert calls == [] + + +@pytest.mark.asyncio +async def test_async_batches_keep_the_existing_reader(monkeypatch): + db = await lancedb.connect_async("memory://") + table = await db.create_table( + "async_sync_pull_reader", data=[{"id": i} for i in range(4)] + ) + calls = _spy_on_pull_reader(monkeypatch) + + reader = await table.query().to_batches() + + total_rows = 0 + async for batch in reader: + total_rows += batch.num_rows + assert total_rows == 4 + assert calls == [] + + +def test_timeout_starts_on_first_read_and_spans_reads(tmp_path): + table = lancedb.connect(tmp_path).create_table( + "timeout_pull_reader", data=[{"id": i} for i in range(8)] + ) + reader = ( + table.search() + .select(["id"]) + .to_batches(batch_size=2, timeout=timedelta(milliseconds=200)) + ) + + # A slow consumer before the first poll must not count against the query: + # the timeout starts when the first batch is requested. + time.sleep(0.25) + first = reader.read_next_batch() + assert first.num_rows == 2 + + # The deadline spans reads, so a pause between batches expires it. + time.sleep(0.25) + with pytest.raises(RuntimeError, match="Query timeout"): + reader.read_next_batch() + + +def test_early_break_can_resume_the_same_reader(mem_db): + table = _table(mem_db) + reader = table.search().select(["id"]).to_batches(batch_size=2) + + first = next(iter(reader)) + rest = list(reader) + + assert pa.Table.from_batches([first, *rest]).column("id").to_pylist() == list( + range(10) + ) + + reader = table.search().select(["id"]).to_batches(batch_size=2) + for first in reader: + break + rest = list(reader) + assert pa.Table.from_batches([first, *rest]).column("id").to_pylist() == list( + range(10) + ) + + +def test_arrow_export_shares_cursor_with_the_last_owner(mem_db): + table = _table(mem_db) + reader = table.search().select(["id"]).to_batches(batch_size=2) + first = reader.read_next_batch() + + capsule = reader.__arrow_c_stream__() + del reader + gc.collect() + + imported = pa.RecordBatchReader._import_from_c_capsule(capsule) + rest = imported.read_all() + combined = pa.concat_tables([pa.Table.from_batches([first]), rest]) + assert combined.column("id").to_pylist() == list(range(10)) + + +def test_empty_result_preserves_the_query_schema(mem_db): + table = _table(mem_db) + query = table.search().select(["id"]).where("id < 0") + + reader = query.to_batches(batch_size=4) + + assert reader.schema == query.output_schema() + assert reader.read_all().num_rows == 0 diff --git a/python/src/lib.rs b/python/src/lib.rs index b0698d5e0..a8217d2b1 100644 --- a/python/src/lib.rs +++ b/python/src/lib.rs @@ -40,6 +40,7 @@ pub mod query; pub mod runtime; pub mod session; pub mod sql; +mod sync_stream; pub mod table; pub mod util; @@ -113,6 +114,7 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; diff --git a/python/src/query.rs b/python/src/query.rs index d8cfedfdb..f14276d74 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -7,6 +7,7 @@ use std::time::Duration; use crate::expr::PyExpr; use crate::runtime::future_into_py; +use crate::sync_stream::SyncRecordBatchStream; use crate::util::parse_distance_type; use crate::{arrow::RecordBatchStream, util::PyLanceDB}; use crate::{error::PythonErrorExt, index::class_name}; @@ -80,6 +81,20 @@ where Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind())) } +fn query_execution_options( + max_batch_length: Option, + timeout: Option, +) -> QueryExecutionOptions { + let mut options = QueryExecutionOptions::default(); + if let Some(max_batch_length) = max_batch_length { + options.max_batch_length = max_batch_length; + } + if let Some(timeout) = timeout { + options.timeout = Some(timeout); + } + options +} + impl<'a, 'py> FromPyObject<'a, 'py> for PyLanceDB { type Error = PyErr; @@ -709,18 +724,35 @@ impl Query { ) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { - let mut opts = QueryExecutionOptions::default(); - if let Some(max_batch_length) = max_batch_length { - opts.max_batch_length = max_batch_length; - } - if let Some(timeout) = timeout { - opts.timeout = Some(timeout); - } + let opts = query_execution_options(max_batch_length, timeout); let inner_stream = inner.execute_with_options(opts).await.infer_error()?; Ok(RecordBatchStream::new(inner_stream)) }) } + /// Execute this local query and return a pull-driven synchronous iterator. + /// + /// The query is started once. Each `__next__` fetches exactly one batch + /// from the caller's thread while the GIL is released. `None` keeps the + /// core's default 1024-row output cap, `0` lets the engine choose, and a + /// positive value caps each returned batch. + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_sync( + self_: PyRef<'_, Self>, + py: Python<'_>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult { + let inner = self_.inner.clone(); + let opts = query_execution_options(max_batch_length, timeout); + let stream = py.detach(move || { + crate::runtime::block_on_interruptible(async move { + inner.execute_with_options(opts).await.infer_error() + }) + })?; + Ok(SyncRecordBatchStream::new(stream)) + } + /// Execute this query eagerly and return an Arrow C Stream reader. /// /// The returned reader exposes batches already collected in Rust, so diff --git a/python/src/sync_stream.rs b/python/src/sync_stream.rs new file mode 100644 index 000000000..5180f7a73 --- /dev/null +++ b/python/src/sync_stream.rs @@ -0,0 +1,298 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! A pull-driven synchronous reader over a query's record batch stream. +//! +//! The synchronous Python API used to drive one future per batch through the +//! shared background event loop. This reader keeps the stream in Rust and +//! fetches exactly one batch from the caller's thread for each `__next__`, +//! while the caller's GIL is released. +//! +//! The stream is stored only while the reader is idle. Taking it out for a +//! poll means an error, EOF, interrupt, or a dropped last owner releases the +//! execution plan immediately instead of leaving a reader task behind. A +//! successful batch puts the stream back so an early `break` can resume +//! reading from the same cursor. + +use std::sync::Mutex; + +use arrow::datatypes::SchemaRef; +use arrow::pyarrow::{IntoPyArrow, ToPyArrow}; +use arrow::record_batch::RecordBatch; +use futures::StreamExt; +use lancedb::arrow::SendableRecordBatchStream; +use pyo3::{Py, PyAny, PyRef, PyResult, Python, pyclass, pymethods}; + +use crate::error::PythonErrorExt; +use crate::runtime::block_on_interruptible; + +/// Synchronous iterator over the batches of one query execution. +/// +/// Python wraps this in [`pyarrow.RecordBatchReader.from_batches`] so the +/// public return type, schema capsule, and exception types stay the same as +/// the existing sync reader. Creating the iterator does not poll the stream; +/// the first `__next__` starts any configured query timeout. +#[pyclass] +pub struct SyncRecordBatchStream { + schema: SchemaRef, + stream: Mutex>, +} + +impl SyncRecordBatchStream { + pub fn new(stream: SendableRecordBatchStream) -> Self { + let schema = stream.schema(); + Self { + schema, + stream: Mutex::new(Some(stream)), + } + } + + /// Take the stream and hand it to one owned, one-shot read future. + /// + /// The future owns the stream so an interrupt aborts it and drops the + /// execution plan with the future. A successful batch returns the stream + /// to the slot, which keeps an early `break` resumable. EOF and read + /// errors drop the stream before returning. The lock is held only while + /// taking or storing the stream, never while waiting, so another Python + /// thread cannot deadlock against a read that needs the GIL. + fn pull(&mut self) -> PyResult> { + match self.pull_with(|mut stream| { + block_on_interruptible(async move { + let next = stream.next().await; + Ok::<_, pyo3::PyErr>((stream, next)) + }) + })? { + Some(Ok(batch)) => Ok(Some(batch)), + Some(Err(error)) => Err(into_py_error(error)), + None => Ok(None), + } + } + + /// Shared state machine for one pull, with the wait injected for tests. + fn pull_with( + &mut self, + fetch: F, + ) -> Result>, pyo3::PyErr> + where + F: FnOnce( + SendableRecordBatchStream, + ) -> PyResult<( + SendableRecordBatchStream, + Option>, + )>, + { + let Some(stream) = self + .stream + .lock() + .expect("sync reader mutex poisoned") + .take() + else { + return Ok(None); + }; + let (stream, next) = fetch(stream)?; + match next { + Some(Ok(batch)) => { + *self.stream.lock().expect("sync reader mutex poisoned") = Some(stream); + Ok(Some(Ok(batch))) + } + Some(Err(error)) => { + drop(stream); + Ok(Some(Err(error))) + } + None => { + drop(stream); + Ok(None) + } + } + } + + fn release(&self) { + *self.stream.lock().expect("sync reader mutex poisoned") = None; + } +} + +#[pymethods] +impl SyncRecordBatchStream { + #[getter] + pub fn schema(&self, py: Python<'_>) -> PyResult> { + (*self.schema) + .clone() + .into_pyarrow(py) + .map(|obj| obj.unbind()) + } + + fn __iter__(self_: PyRef<'_, Self>) -> PyRef<'_, Self> { + self_ + } + + fn __next__(&mut self, py: Python<'_>) -> PyResult>> { + let batch = py.detach(|| self.pull())?; + let Some(batch) = batch else { + return Ok(None); + }; + let batch = match batch.to_pyarrow(py) { + Ok(batch) => batch, + Err(error) => { + self.release(); + return Err(error); + } + }; + // A signal arriving after the fetch still terminates the reader, so + // no execution plan outlives the KeyboardInterrupt. + if let Err(error) = py.check_signals() { + self.release(); + return Err(error); + } + Ok(Some(batch.unbind())) + } +} + +fn into_py_error(error: lancedb::Error) -> pyo3::PyErr { + match Err::<(), _>(error).infer_error() { + Ok(()) => unreachable!("infer_error returned Ok for an Err value"), + Err(error) => error, + } +} + +#[cfg(test)] +mod tests { + use std::collections::VecDeque; + use std::pin::Pin; + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::task::{Context, Poll}; + + use arrow::array::Int32Array; + use arrow::datatypes::{DataType, Field, Schema}; + use futures::Stream; + use lancedb::arrow::RecordBatchStream as LanceRecordBatchStream; + + use super::*; + + struct TestStream { + schema: SchemaRef, + batches: VecDeque>, + polls: Arc, + dropped: Arc, + } + + impl TestStream { + fn new(batches: Vec>) -> Self { + let schema = test_schema(); + Self { + schema, + batches: batches.into(), + polls: Arc::new(AtomicUsize::new(0)), + dropped: Arc::new(AtomicBool::new(false)), + } + } + } + + impl Stream for TestStream { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + self.polls.fetch_add(1, Ordering::SeqCst); + Poll::Ready(self.batches.pop_front()) + } + } + + impl LanceRecordBatchStream for TestStream { + fn schema(&self) -> SchemaRef { + Arc::clone(&self.schema) + } + } + + impl Drop for TestStream { + fn drop(&mut self) { + self.dropped.store(true, Ordering::SeqCst); + } + } + + fn test_schema() -> SchemaRef { + Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])) + } + + fn test_batch(value: i32) -> RecordBatch { + RecordBatch::try_new(test_schema(), vec![Arc::new(Int32Array::from(vec![value]))]).unwrap() + } + + fn boxed(stream: TestStream) -> SendableRecordBatchStream { + Box::pin(stream) + } + + fn pull_fake( + reader: &mut SyncRecordBatchStream, + ) -> Result>, pyo3::PyErr> { + reader.pull_with(|mut stream| { + let next = futures::executor::block_on(stream.next()); + Ok((stream, next)) + }) + } + + #[test] + fn creation_does_not_poll() { + let stream = TestStream::new(vec![Ok(test_batch(1))]); + let polls = Arc::clone(&stream.polls); + let _reader = SyncRecordBatchStream::new(boxed(stream)); + assert_eq!(polls.load(Ordering::SeqCst), 0); + } + + #[test] + fn one_pull_reads_one_batch_and_keeps_the_stream_resumable() { + let stream = TestStream::new(vec![ + Ok(test_batch(1)), + Ok(test_batch(2)), + Ok(test_batch(3)), + ]); + let polls = Arc::clone(&stream.polls); + let dropped = Arc::clone(&stream.dropped); + let mut reader = SyncRecordBatchStream::new(boxed(stream)); + + assert!(pull_fake(&mut reader).unwrap().unwrap().is_ok()); + assert_eq!(polls.load(Ordering::SeqCst), 1); + assert!(!dropped.load(Ordering::SeqCst)); + + assert!(pull_fake(&mut reader).unwrap().unwrap().is_ok()); + assert_eq!(polls.load(Ordering::SeqCst), 2); + assert!(!dropped.load(Ordering::SeqCst)); + } + + #[test] + fn eof_drops_the_stream_before_returning() { + let stream = TestStream::new(vec![Ok(test_batch(1))]); + let dropped = Arc::clone(&stream.dropped); + let mut reader = SyncRecordBatchStream::new(boxed(stream)); + + assert!(pull_fake(&mut reader).unwrap().unwrap().is_ok()); + assert!(!dropped.load(Ordering::SeqCst)); + assert!(pull_fake(&mut reader).unwrap().is_none()); + assert!(dropped.load(Ordering::SeqCst)); + assert!(pull_fake(&mut reader).unwrap().is_none()); + } + + #[test] + fn error_drops_the_stream_before_returning() { + let stream = TestStream::new(vec![Err(lancedb::Error::Runtime { + message: "read failed".to_string(), + })]); + let dropped = Arc::clone(&stream.dropped); + let mut reader = SyncRecordBatchStream::new(boxed(stream)); + + assert!(pull_fake(&mut reader).unwrap().unwrap().is_err()); + assert!(dropped.load(Ordering::SeqCst)); + assert!(pull_fake(&mut reader).unwrap().is_none()); + } + + #[test] + fn dropping_an_unread_reader_drops_the_stream_without_polling() { + let stream = TestStream::new(vec![Ok(test_batch(1))]); + let polls = Arc::clone(&stream.polls); + let dropped = Arc::clone(&stream.dropped); + let reader = SyncRecordBatchStream::new(boxed(stream)); + + drop(reader); + assert_eq!(polls.load(Ordering::SeqCst), 0); + assert!(dropped.load(Ordering::SeqCst)); + } +}