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
+21
View File
@@ -187,6 +187,27 @@ def test_filter_search():
assert all(row["category"] == "animals" for row in rows)
def test_scan_batches():
import lancedb
db = lancedb.connect("memory://")
table = db.create_table(
"documents",
[
{"text": "A puppy playing in the park", "category": "animals"},
{"text": "A dog resting at home", "category": "animals"},
{"text": "A guide to growing tomatoes", "category": "gardening"},
],
)
# --8<-- [start:scan_batches]
query = table.search().select(["text", "category"]).with_row_id(True)
rows_read = 0
for batch in query.to_batches(batch_size=1024):
rows_read += batch.num_rows
# --8<-- [end:scan_batches]
assert rows_read == 3
def test_query_plan():
from tempfile import TemporaryDirectory
+22
View File
@@ -86,7 +86,29 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.iter()
.all(|v| v == Some("animals"))
}));
assert_eq!(scan_batches(&table).await?, 3);
// --8<-- [start:example_tail]
Ok(())
}
// --8<-- [end:example_tail]
// --8<-- [start:scan_batches]
async fn scan_batches(table: &lancedb::Table) -> lancedb::Result<usize> {
use futures::TryStreamExt;
use lancedb::query::{ExecutableQuery, QueryBase, QueryExecutionOptions, Select};
let query = table
.query()
.select(Select::columns(&["text", "category"]))
.with_row_id();
let mut options = QueryExecutionOptions::default();
options.max_batch_length = 1024;
let mut batches = query.execute_with_options(options).await?;
let mut rows_read = 0;
while let Some(batch) = batches.try_next().await? {
rows_read += batch.num_rows();
}
Ok(rows_read)
}
// --8<-- [end:scan_batches]
+38 -9
View File
@@ -8,7 +8,8 @@ availability:
enterprise: available
---
import { PyVectorSearch, TsVectorSearchBody, TsVectorSearchTail } from '/snippets/search_examples.mdx';
import { PyScanBatches, PyVectorSearch, TsVectorSearchBody, TsVectorSearchTail } from '/snippets/search_examples.mdx';
import { RsScanBatches } from '/snippets/search_filter_search.mdx';
import { RsExampleBody as RsVectorSearchBody, RsExampleTail as RsVectorSearchTail } from '/snippets/search_vector_search.mdx';
LanceDB supports vector, full-text and hybrid search. Use vector search to find
@@ -98,15 +99,43 @@ never returned.
## Read large result sets in batches {#avoid-materializing-the-whole-table}
Materializing all rows at once can exhaust application memory. For exports and
training reads, use bounded queries or the batch-reading interfaces described
in [Data loading](/training/data-loading). The SDK buffers Enterprise
query responses before exposing batches. Set a query limit rather than relying
on batch iteration alone to bound memory.
For an export or a full table scan, build a query without a search term or
vector and read the results one batch at a time. LanceDB Enterprise runs one
query, so the scan needs no key column, index or pagination. The examples
read the `text` and `category` columns from an open table.
Direct Lance dataset access through Python's `table.to_lance()` is a LanceDB
Embedded interface. Use the SDK query builders for reads that need to work with
both LanceDB Embedded and LanceDB Enterprise.
<CodeGroup>
<CodeBlock filename="Python" language="python" icon="python">
{PyScanBatches}
</CodeBlock>
<CodeBlock filename="Rust" language="rust" icon="rust">
{RsScanBatches}
</CodeBlock>
</CodeGroup>
The row ID option includes `_rowid` in each batch. To restrict the scan, add a
predicate with `where()` in Python or `only_if()` in Rust. Omit `limit()` to read
every matching row. Use `limit(n)` to cap the total number of rows.
Python's `batch_size` and Rust's `max_batch_length` cap the rows per batch
delivered to the application. The SDK decodes each server batch at its original
size before slicing it. In TypeScript, `for await (const batch of table.query())`
uses the default batch sizing. TypeScript's `maxBatchLength` option is available
on `toArrow()` and `toArray()`, which collect the full result.
Use a current SDK with LanceDB Enterprise 1.16.0 or later for this workflow. SDK
0.42.0 introduced streaming Arrow IPC query responses. Python and Rust SDKs
through 0.42.1 may return Enterprise batches larger than the requested cap.
Older deployments can return buffered Arrow IPC files or reject scans without
`limit()` if they enforce a query row cap.
To pin a retained version, call `table.checkout(version)` in Python or
`table.checkout(version).await?` in Rust before building the query. If the
stream is interrupted, the batches already read are a partial result. Python
raises `ResponseInterruptedError` and Rust returns `Error::ResponseInterrupted`.
For training, see [Data loading](/training/data-loading). Python's
`table.to_lance()` gives direct Lance dataset access in LanceDB Embedded.
## Investigate a slow query {#diagnostics}
+2
View File
@@ -6,6 +6,8 @@ export const PyHybridSearch = "table = db.create_table(\n \"documents\",\n
export const PyQueryPlan = "table = db.create_table(\n \"documents\",\n [\n {\n \"id\": 1,\n \"text\": \"A puppy playing in the park\",\n \"category\": \"animals\",\n \"vector\": [1.0, 0.0],\n },\n {\n \"id\": 2,\n \"text\": \"A dog resting at home\",\n \"category\": \"animals\",\n \"vector\": [0.9, 0.1],\n },\n {\n \"id\": 3,\n \"text\": \"A guide to growing tomatoes\",\n \"category\": \"gardening\",\n \"vector\": [0.0, 1.0],\n },\n ],\n)\nquery = table.search([1.0, 0.0]).select([\"id\", \"text\", \"_distance\"]).limit(2)\nprint(\"Plan:\", query.explain_plan())\nprint(\"Measured execution:\", query.analyze_plan())\nrows = query.to_list()\nprint(rows)\n";
export const PyScanBatches = "query = table.search().select([\"text\", \"category\"]).with_row_id(True)\nrows_read = 0\nfor batch in query.to_batches(batch_size=1024):\n rows_read += batch.num_rows\n";
export const PyTextSearch = "table = db.create_table(\n \"documents\",\n [\n {\n \"id\": 1,\n \"text\": \"A puppy playing in the park\",\n \"category\": \"animals\",\n },\n {\n \"id\": 2,\n \"text\": \"A dog resting at home\",\n \"category\": \"animals\",\n },\n {\n \"id\": 3,\n \"text\": \"A guide to growing tomatoes\",\n \"category\": \"gardening\",\n },\n ],\n)\ntable.create_index(\"text\", config=FTS())\nrows = (\n table.search(\"puppy\", query_type=\"fts\", fts_columns=\"text\")\n .select([\"id\", \"text\", \"_score\"])\n .limit(2)\n .to_list()\n)\nprint(rows)\n";
export const PyVectorSearch = "table = db.create_table(\n \"documents\",\n [\n {\n \"id\": 1,\n \"text\": \"A puppy playing in the park\",\n \"category\": \"animals\",\n \"vector\": [1.0, 0.0],\n },\n {\n \"id\": 2,\n \"text\": \"A dog resting at home\",\n \"category\": \"animals\",\n \"vector\": [0.9, 0.1],\n },\n {\n \"id\": 3,\n \"text\": \"A guide to growing tomatoes\",\n \"category\": \"gardening\",\n \"vector\": [0.0, 1.0],\n },\n ],\n)\nrows = (\n table.search([1.0, 0.0])\n .distance_type(\"l2\")\n .select([\"id\", \"text\", \"_distance\"])\n .limit(2)\n .to_list()\n)\nprint(rows)\n";
@@ -4,3 +4,5 @@ export const RsExampleBody = "use arrow_array::types::Float32Type;\nuse arrow_ar
export const RsExampleTail = " Ok(())\n}\n";
export const RsScanBatches = "async fn scan_batches(table: &lancedb::Table) -> lancedb::Result<usize> {\n use futures::TryStreamExt;\n use lancedb::query::{ExecutableQuery, QueryBase, QueryExecutionOptions, Select};\n\n let query = table\n .query()\n .select(Select::columns(&[\"text\", \"category\"]))\n .with_row_id();\n let mut options = QueryExecutionOptions::default();\n options.max_batch_length = 1024;\n\n let mut batches = query.execute_with_options(options).await?;\n let mut rows_read = 0;\n while let Some(batch) = batches.try_next().await? {\n rows_read += batch.num_rows();\n }\n Ok(rows_read)\n}\n";
+4 -8
View File
@@ -203,10 +203,8 @@ impl Query {
timeout_ms: Option<u32>,
with_row_id: Option<bool>,
) -> napi::Result<RecordBatchIterator> {
let mut execution_opts = QueryExecutionOptions::default();
if let Some(max_batch_length) = max_batch_length {
execution_opts.max_batch_length = max_batch_length;
}
let mut execution_opts =
QueryExecutionOptions::default().with_optional_max_batch_length(max_batch_length);
if let Some(timeout_ms) = timeout_ms {
execution_opts.timeout = Some(std::time::Duration::from_millis(timeout_ms as u64))
}
@@ -446,10 +444,8 @@ impl VectorQuery {
timeout_ms: Option<u32>,
with_row_id: Option<bool>,
) -> napi::Result<RecordBatchIterator> {
let mut execution_opts = QueryExecutionOptions::default();
if let Some(max_batch_length) = max_batch_length {
execution_opts.max_batch_length = max_batch_length;
}
let mut execution_opts =
QueryExecutionOptions::default().with_optional_max_batch_length(max_batch_length);
if let Some(timeout_ms) = timeout_ms {
execution_opts.timeout = Some(std::time::Duration::from_millis(timeout_ms as u64))
}
+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))
})
+1 -1
View File
@@ -513,7 +513,7 @@ pub enum Error {
))]
ResponseInterrupted {
request_id: String,
/// Batches returned before the interruption.
/// Arrow batches decoded from the server before the interruption.
batches: u64,
/// Rows in those batches.
rows: u64,
+20 -4
View File
@@ -703,7 +703,7 @@ pub struct QueryExecutionOptions {
/// and so the performance penalty of reading smaller batches
/// is typically very small.
///
/// By default, this is 1024
/// The default value is 1024. Zero leaves the batch size to the engine.
pub max_batch_length: u32,
/// Max duration to wait for the query to execute before timing out.
///
@@ -717,6 +717,9 @@ pub struct QueryExecutionOptions {
/// This only affects remote distributed query plans. Local query execution
/// ignores this option.
pub analyze_plan_distributed_metrics: AnalyzePlanDistributedMetrics,
// An omitted batch length keeps the server's batch sizes for Enterprise
// queries. Embedded queries and takes still use the numeric default.
pub(crate) use_server_batch_length: bool,
}
impl Default for QueryExecutionOptions {
@@ -725,11 +728,20 @@ impl Default for QueryExecutionOptions {
max_batch_length: 1024,
timeout: None,
analyze_plan_distributed_metrics: AnalyzePlanDistributedMetrics::Aggregate,
use_server_batch_length: false,
}
}
}
impl QueryExecutionOptions {
/// Preserve the execution path's default when the caller omits a batch length.
#[doc(hidden)]
pub fn with_optional_max_batch_length(mut self, max_batch_length: Option<u32>) -> Self {
self.use_server_batch_length = max_batch_length.is_none();
self.max_batch_length = max_batch_length.unwrap_or(Self::default().max_batch_length);
self
}
fn without_output_batch_length_limit(&self) -> Self {
let mut options = self.clone();
options.max_batch_length = 0;
@@ -775,11 +787,15 @@ pub trait ExecutableQuery {
options: QueryExecutionOptions,
) -> impl Future<Output = Result<Arc<dyn ExecutionPlan>>> + Send;
/// Execute the query with default options and return results
/// Execute the query with default options and return results.
///
/// See [`ExecutableQuery::execute_with_options`] for more details.
/// Embedded queries and takes use the default maximum batch length.
/// To cap batches from an Enterprise query response, pass a positive
/// `max_batch_length` to [`ExecutableQuery::execute_with_options`].
fn execute(&self) -> impl Future<Output = Result<SendableRecordBatchStream>> + Send {
self.execute_with_options(QueryExecutionOptions::default())
self.execute_with_options(
QueryExecutionOptions::default().with_optional_max_batch_length(None),
)
}
/// Execute the query and return results
+25 -14
View File
@@ -1959,7 +1959,10 @@ impl<S: HttpSend> RemoteTable<S> {
&self,
query: &AnyQuery,
options: &QueryExecutionOptions,
) -> Result<Vec<Pin<Box<dyn RecordBatchStream + Send>>>> {
) -> Result<(
Vec<SendableRecordBatchStream>,
Option<(tokio::time::Instant, Duration)>,
)> {
if let AnyQuery::VectorQuery(query) = query
&& query.query_vector.len() > 1
&& query.base.reranker.is_some()
@@ -2039,7 +2042,7 @@ impl<S: HttpSend> RemoteTable<S> {
== first.schema().metadata().get("lancedb:query_snapshot")
})
});
Ok(streams
let streams = streams
.into_iter()
.map(|stream| {
// Ordinary descriptor queries remain usable during an upgrade.
@@ -2060,7 +2063,8 @@ impl<S: HttpSend> RemoteTable<S> {
None => stream,
}
})
.collect())
.collect();
Ok((streams, deadline))
}
fn prepare_query_bodies(
@@ -3725,7 +3729,7 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
.await;
}
let streams = self.execute_query(query, &options).await?;
let (streams, _) = self.execute_query(query, &options).await?;
if streams.len() == 1 {
let stream = streams.into_iter().next().unwrap();
Ok(Arc::new(OneShotExec::new(stream)))
@@ -3763,24 +3767,31 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
return Ok(DatasetRecordBatchStream::new(inner));
}
let streams = self.execute_query(query, &options).await?;
if streams.len() == 1 {
Ok(DatasetRecordBatchStream::new(
streams.into_iter().next().unwrap(),
))
let (streams, deadline) = self.execute_query(query, &options).await?;
let stream = if streams.len() == 1 {
streams.into_iter().next().unwrap()
} else {
let stream_execs = streams
.into_iter()
.map(|stream| Arc::new(OneShotExec::new(stream)) as Arc<dyn ExecutionPlan>)
.collect();
let plan = create_multi_vector_plan(stream_execs)?;
execute_plan(plan, Default::default())?
};
Ok(DatasetRecordBatchStream::new(execute_plan(
plan,
Default::default(),
)?))
if options.use_server_batch_length || options.max_batch_length == 0 {
return Ok(DatasetRecordBatchStream::new(stream));
}
// A multi-vector plan can coalesce batches, so cap the final output.
let stream = MaxBatchLengthStream::new_boxed(stream, options.max_batch_length as usize);
// Keep the original deadline when the consumer reads buffered slices.
let stream: SendableRecordBatchStream = if let Some((deadline, timeout)) = deadline {
Box::pin(TimeoutStream::with_deadline(stream, timeout, deadline))
} else {
stream
};
Ok(DatasetRecordBatchStream::new(stream))
}
async fn blob_columns(&self) -> Result<Vec<String>> {