fix: honor Enterprise query batch size limits (#5350)

Enterprise queries could return Arrow batches larger than the size
explicitly requested by the caller. The SDK now slices oversized batches
in the final query stream and keeps server-selected batch sizes when the
caller omits the limit or passes zero.

The search guide shows how to stream a full table or filtered scan in
one query using Python's `search().to_batches()`. It covers older
deployments that return buffered Arrow IPC files or enforce a query row
cap.

A local Enterprise 1.16.0 probe streamed all 131,073 rows from a pinned
snapshot in one query, with batches of at most 37 rows and the first
batch available before the Arrow end-of-stream marker. The probe ran
with Plan Executor enabled and disabled.

Related to OSS-3133.
This commit is contained in:
Xuanwo
2026-12-02 09:42:17 +00:00
committed by GitHub
parent 53a8c6973c
commit b5f35d5c56
13 changed files with 192 additions and 74 deletions
+1 -1
View File
@@ -297,7 +297,7 @@ class ResponseInterruptedError(HttpError):
Attributes
----------
batches: int
The number of batches returned before the interruption.
The number of Arrow batches decoded from the server before the interruption.
rows: int
The number of rows in those batches.
table_version: int or None
+2 -1
View File
@@ -307,7 +307,8 @@ class RemoteTable(Table):
validate_blob_mode(blob_mode)
raise NotImplementedError(
"to_arrow() is not supported in LanceDB Enterprise. "
"Use table.search().to_arrow() instead."
"Use table.search().to_batches() to stream results or "
"table.search().to_arrow() to materialize them."
)
def to_pandas(self, blob_mode: BlobMode = "lazy", **kwargs):
+49 -15
View File
@@ -3888,12 +3888,18 @@ def test_remote_python_only_messages():
with pytest.raises(NotImplementedError, match=next(iter(options))):
db.open_table("test", **options)
table = db.open_table("test")
for method in ["to_arrow", "to_pandas", "to_polars"]:
for method, guidance in {
"to_arrow": (
"Use table.search().to_batches() to stream results or "
"table.search().to_arrow() to materialize them."
),
"to_pandas": "Use table.search().to_pandas() instead.",
"to_polars": "Use table.search().to_polars() instead.",
}.items():
with pytest.raises(NotImplementedError) as error:
getattr(table, method)()
assert str(error.value) == (
f"{method}() is not supported in LanceDB Enterprise. "
f"Use table.search().{method}() instead."
f"{method}() is not supported in LanceDB Enterprise. {guidance}"
)
for method, expected in {
"compact_files": "compact_files() is a no-op in LanceDB Enterprise.",
@@ -4710,10 +4716,24 @@ def streamed_query_table(write_body):
yield db.open_table("test"), queries
def test_query_sync_to_batches_yields_before_the_body_is_complete():
batches = [pa.record_batch({"id": pa.array([i], pa.int32())}) for i in range(3)]
@pytest.mark.parametrize("batch_size", [None, 0, 37, 1024])
def test_query_sync_to_batches_yields_before_the_body_is_complete(batch_size):
server_batch_sizes = [1063, 81]
values = list(range(sum(server_batch_sizes)))
row_ids = [(1 << 32) + 2 * value for value in values]
results = pa.record_batch(
{
"id": pa.array(values, pa.int32()),
"_rowid": pa.array(row_ids, pa.uint64()),
}
)
first_server_size = server_batch_sizes[0]
batches = [
results.slice(0, first_server_size),
results.slice(first_server_size),
]
body = _arrow_stream(batches)
# The schema and first batch, without the 8-byte end-of-stream marker.
# Send the schema and first server batch without the end-of-stream marker.
head = _arrow_stream(batches[:1])[:-8]
first_batch_read = threading.Event()
waited_for_client = []
@@ -4725,13 +4745,24 @@ def test_query_sync_to_batches_yields_before_the_body_is_complete():
request.wfile.write(body[len(head) :])
with streamed_query_table(write_body) as (table, queries):
reader = table.search().to_batches()
assert reader.read_next_batch()["id"].to_pylist() == [0]
query = table.search().select(["id"]).with_row_id(True)
reader = query.to_batches(batch_size=batch_size)
first_batch = reader.read_next_batch()
first_batch_read.set()
assert reader.read_all()["id"].to_pylist() == [1, 2]
received = [first_batch, *reader]
sizes = [batch.num_rows for batch in received]
if batch_size:
assert all(0 < size <= batch_size for size in sizes)
else:
assert sizes == server_batch_sizes
result = pa.Table.from_batches(received)
assert result["id"].to_pylist() == values
assert result["_rowid"].to_pylist() == row_ids
# The wait times out if the client needs the whole body for the first batch.
assert waited_for_client == [True]
assert len(queries) == 1
assert queries[0]["Accept"] == (
"application/vnd.apache.arrow.stream, application/vnd.apache.arrow.file;q=0.9"
)
@@ -4739,8 +4770,9 @@ def test_query_sync_to_batches_yields_before_the_body_is_complete():
@pytest.mark.parametrize("abort", [False, True], ids=["clean_end", "abort"])
def test_query_sync_interrupted_response_raises(abort):
batches = [pa.record_batch({"id": pa.array([i], pa.int32())}) for i in range(3)]
head = _arrow_stream(batches[:1])[:-8]
values = list(range(45))
batch = pa.record_batch({"id": pa.array(values, pa.int32())})
head = _arrow_stream([batch])[:-8]
def write_body(request):
if abort:
@@ -4751,14 +4783,16 @@ def test_query_sync_interrupted_response_raises(abort):
request.wfile.write(head)
with streamed_query_table(write_body) as (table, queries):
reader = table.search().to_batches()
assert reader.read_next_batch()["id"].to_pylist() == [0]
reader = table.search().to_batches(batch_size=37)
received = []
with pytest.raises(ResponseInterruptedError) as exc_info:
reader.read_next_batch()
for batch in reader:
received.extend(batch["id"].to_pylist())
assert received == values
error = exc_info.value
assert isinstance(error, HttpError)
assert (error.batches, error.rows, error.table_version) == (1, 1, 7)
assert (error.batches, error.rows, error.table_version) == (1, len(values), 7)
assert error.request_id == queries[0]["x-request-id"]
assert error.is_transport_error is abort
assert len(queries) == 1
+5 -21
View File
@@ -102,13 +102,9 @@ fn query_execution_options(
max_batch_length: Option<u32>,
timeout: Option<Duration>,
) -> 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);
}
let mut options =
QueryExecutionOptions::default().with_optional_max_batch_length(max_batch_length);
options.timeout = timeout;
options
}
@@ -1060,13 +1056,7 @@ impl FTSQuery {
.full_text_search(self_.fts_query_for_execution());
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))
})
@@ -1351,13 +1341,7 @@ impl VectorQuery {
) -> PyResult<Bound<'_, PyAny>> {
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))
})