From e6b036cfee7ac019f1a9f44e157a0c00f0bad37b Mon Sep 17 00:00:00 2001
From: "lancedb-gatefixer[bot]"
<313497061+lancedb-gatefixer[bot]@users.noreply.github.com>
Date: Mon, 30 Nov 2026 20:33:28 +0800
Subject: [PATCH] fix(python): release cancelled query streams (#5104)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Cancelling an async batch read could leave its native query stream
parked inside a posting-list cache load while Python retained the
reader. Other full-text queries sharing those cache entries could then
wait indefinitely.
Give the active read future ownership of the stream while polling it,
restoring it to the reader after the poll completes. Cancellation that
interrupts the active native read drops the stream and releases its
cache loader guards even when the reader and cancelled task remain
referenced. Further reads then raise `RuntimeError`. Completion can race
with cancellation and leave the stream open, so callers should always
discard the reader after cancelling a read and run the query again.
Cancelling a read waiting for the mutex preserves the active read.
Validation:
- Added an asyncio cancellation regression through PyO3 that failed
before the fix (`stream was retained after cancellation`) and now passes
while retaining both the reader and task.
- `cargo test --quiet -p lancedb-python --lib arrow::tests`: 3 passed,
covering cancellation, a queued read, and normal batches/exhaustion.
- Rebuilt the Python extension after merging current `main`; `cd python
&& uv run --no-sync --extra tests pytest
python/tests/test_eager_collector.py python/tests/test_fts.py
python/tests/test_query.py python/tests/test_sync_query_direct.py -q -m
'not slow and not s3_test'`: 381 passed, 2 deselected.
- `cargo clippy --quiet -p lancedb-python --tests -- -D warnings`,
`cargo fmt --all`, Python package Ruff lint/format checks, and `git diff
--check` passed.
- Repository-wide `ruff check .` reports 59 existing errors in
docs/web-tests; no unrelated files are changed.
Fixes #5025
## Change walkthrough
```mermaid
flowchart TD
A[Acquire read mutex] --> B[Take stream ownership]
B --> C[Poll next batch]
C -->|Completed| D[Restore stream]
C -->|Interrupted| E[Drop parked execution]
E --> F[Later reads raise RuntimeError]
```
Completion can race with cancellation; always discard the reader after
cancelling a read.
**Read:** [stream
ownership](https://github.com/lancedb/lancedb/blob/5ebef1c5c4947a49a024f09c452ded756b29ad82/python/src/arrow.rs#L41-L56)
· [reader cancellation
guidance](https://github.com/lancedb/lancedb/blob/5ebef1c5c4947a49a024f09c452ded756b29ad82/python/python/lancedb/arrow.py#L13-L23)
· [asyncio cancellation
regression](https://github.com/lancedb/lancedb/blob/5ebef1c5c4947a49a024f09c452ded756b29ad82/python/src/arrow.rs#L164-L223)
Snapshot:
[5ebef1c](https://github.com/lancedb/lancedb/commit/5ebef1c5c4947a49a024f09c452ded756b29ad82)
---------
Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com>
---
python/python/lancedb/arrow.py | 6 ++
python/src/arrow.rs | 166 ++++++++++++++++++++++++++++++---
2 files changed, 157 insertions(+), 15 deletions(-)
diff --git a/python/python/lancedb/arrow.py b/python/python/lancedb/arrow.py
index c5a278ead..e691b1720 100644
--- a/python/python/lancedb/arrow.py
+++ b/python/python/lancedb/arrow.py
@@ -15,6 +15,12 @@ class AsyncRecordBatchReader:
An async iterator over a stream of RecordBatches.
Also allows access to the schema of the stream
+
+ After cancelling a batch read, discard this reader and run the query again
+ to obtain a new reader. For native query streams, cancellation that
+ interrupts an active read closes the stream, and further reads raise
+ ``RuntimeError``. Completion can race with cancellation, so later reads
+ may still return batches.
"""
def __init__(
diff --git a/python/src/arrow.rs b/python/src/arrow.rs
index a4de3a911..0903d0cb3 100644
--- a/python/src/arrow.rs
+++ b/python/src/arrow.rs
@@ -7,6 +7,7 @@ use std::time::Duration;
use crate::error::PythonErrorExt;
use crate::runtime::{block_on_interruptible, future_into_py};
use arrow::{
+ array::RecordBatch,
datatypes::SchemaRef,
pyarrow::{IntoPyArrow, ToPyArrow},
record_batch::{RecordBatchIterator, RecordBatchReader as ArrowRecordBatchReader},
@@ -17,13 +18,15 @@ use lancedb::{
query::{ExecutableQuery, QueryExecutionOptions},
};
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 {
@@ -31,9 +34,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