From d8957238bf7c428a9fdda3350e3b02a627e487bc Mon Sep 17 00:00:00 2001 From: Sarwar Bhuiyan Date: Mon, 9 Nov 2026 20:40:59 -0500 Subject: [PATCH 1/5] fix(remote): stream query responses instead of buffering them (#4929) --- .../js/interfaces/QueryExecutionOptions.md | 3 + docs/src/python/python.md | 9 + nodejs/lancedb/query.ts | 3 + python/python/lancedb/query.py | 21 + python/python/lancedb/remote/errors.py | 58 ++ python/python/tests/test_errors.py | 12 + python/python/tests/test_remote_db.py | 95 +++ python/src/error.rs | 22 + rust/lancedb/src/error.rs | 167 ++++ rust/lancedb/src/query.rs | 9 + rust/lancedb/src/remote/table.rs | 114 ++- rust/lancedb/src/remote/table/ipc_stream.rs | 729 ++++++++++++++++++ rust/lancedb/src/utils/mod.rs | 16 + 13 files changed, 1216 insertions(+), 42 deletions(-) create mode 100644 rust/lancedb/src/remote/table/ipc_stream.rs diff --git a/docs/src/js/interfaces/QueryExecutionOptions.md b/docs/src/js/interfaces/QueryExecutionOptions.md index f18ada7aa..fb9bada29 100644 --- a/docs/src/js/interfaces/QueryExecutionOptions.md +++ b/docs/src/js/interfaces/QueryExecutionOptions.md @@ -64,3 +64,6 @@ optional timeoutMs: number; ``` Timeout for query execution in milliseconds + +The timeout also covers reading the results, so consuming them slowly can +exceed it. diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 7e5140928..7f28d8804 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -859,6 +859,13 @@ older server omits structured resource details. A structured `already_exists` response keeps its more specific `AlreadyExistsError` type. Both are subclasses of `HttpError`. +A remote query whose streamed response stops partway raises +`ResponseInterruptedError`, also a subclass of `HttpError`. It carries the number +of batches and rows already returned and, when the server reports it, the table +version the response reflected, so the query can be run again against that +version. It is never retried automatically, because the batches already returned +would be returned again. + SQL response failures raise `SqlError`, retaining the numeric `grpc_code` and `request_id`. Servers that report a recognized `x-lancedb-error-code` select a specific input-error subclass. HTTP failures use the corresponding `HttpError` @@ -926,6 +933,8 @@ generic HTTP/SQL exceptions with their transport status and current request ID. ::: lancedb.remote.errors.ConflictError +::: lancedb.remote.errors.ResponseInterruptedError + ::: lancedb.exceptions.MissingValueError ::: lancedb.exceptions.MissingColumnError diff --git a/nodejs/lancedb/query.ts b/nodejs/lancedb/query.ts index cbd927925..bb845276f 100644 --- a/nodejs/lancedb/query.ts +++ b/nodejs/lancedb/query.ts @@ -237,6 +237,9 @@ export interface QueryExecutionOptions { /** * Timeout for query execution in milliseconds + * + * The timeout also covers reading the results, so consuming them slowly can + * exceed it. */ timeoutMs?: number; diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 08ea3b9bc..4a3fea2e2 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -1335,6 +1335,9 @@ class LanceQueryBuilder(ABC): and also the "_distance" column which is the distance between the query vector and the returned vectors. + This collects all results in memory. To process a large result a batch + at a time, use [to_batches][lancedb.query.LanceQueryBuilder.to_batches]. + Parameters ---------- timeout: Optional[timedelta] @@ -1366,6 +1369,11 @@ class LanceQueryBuilder(ABC): ``fetch_blobs``. The ``"bytes"`` and ``"descriptions"`` modes hide automatic row ids. + A remote table decodes batches as they arrive when the server streams + query results. If the response stops partway, reading raises + [ResponseInterruptedError][lancedb.remote.errors.ResponseInterruptedError] + after the batches already returned, which are valid but incomplete. + Parameters ---------- batch_size: int @@ -1373,6 +1381,8 @@ class LanceQueryBuilder(ABC): timeout: Optional[timedelta] The maximum time to wait for the query to complete. If None, wait indefinitely. + The timeout also covers reading the batches, so consuming them + slowly can exceed it. blob_mode: str, default "lazy" ``"lazy"`` keeps blob descriptors and auto row ids for manual fetches. ``"descriptions"`` omits auto row ids. ``"bytes"`` fetches blob v2 @@ -2303,6 +2313,8 @@ class LanceVectorQueryBuilder(LanceQueryBuilder): timeout: timedelta, default None The maximum time to wait for the query to complete. If None, wait indefinitely. + The timeout also covers reading the batches, so consuming them + slowly can exceed it. blob_mode: str, default "lazy" Controls blob conversion as described in :meth:`LanceQueryBuilder.to_batches`. @@ -3570,6 +3582,11 @@ class AsyncQueryBase(object): """ Execute the query and return the results as an Apache Arrow RecordBatchReader. + A remote table decodes batches as they arrive when the server streams + query results. If the response stops partway, reading raises + [ResponseInterruptedError][lancedb.remote.errors.ResponseInterruptedError] + after the batches already returned, which are valid but incomplete. + Parameters ---------- @@ -3582,6 +3599,8 @@ class AsyncQueryBase(object): The maximum time to wait for the query to complete. If not specified, no timeout is applied. If the query does not complete within the specified time, an error will be raised. + The timeout also covers reading the batches, so consuming them + slowly can exceed it. blob_mode: str, default "lazy" ``"lazy"`` keeps blob descriptors and auto row ids for manual fetches. ``"descriptions"`` omits auto row ids. ``"bytes"`` fetches blob v2 @@ -5114,6 +5133,8 @@ class BaseQueryBuilder(object): The maximum time to wait for the query to complete. If not specified, no timeout is applied. If the query does not complete within the specified time, an error will be raised. + The timeout also covers reading the batches, so consuming them + slowly can exceed it. blob_mode: str, default "lazy" Controls blob conversion as described in :meth:`AsyncQueryBase.to_batches`. diff --git a/python/python/lancedb/remote/errors.py b/python/python/lancedb/remote/errors.py index 4dc835e53..ee92ddf53 100644 --- a/python/python/lancedb/remote/errors.py +++ b/python/python/lancedb/remote/errors.py @@ -286,6 +286,64 @@ class ConflictError(HttpError): """ +class ResponseInterruptedError(HttpError): + """A streamed query response stopped before the server finished sending it. + + The batches already returned are valid, but the result is incomplete. The + query is not retried automatically, because a new attempt would return those + rows a second time. To read the same data in a new attempt, check out + ``table_version`` first. + + Attributes + ---------- + batches: int + The number of batches returned before the interruption. + rows: int + The number of rows in those batches. + table_version: int or None + The table version the response reflected, if the server reported it. + + Examples + -------- + >>> error = ResponseInterruptedError("interrupted", "req-1", 2, 2048, 7) + >>> isinstance(error, HttpError) + True + >>> (error.rows, error.table_version) + (2048, 7) + """ + + # HttpError.__new__ takes HttpError's arguments, to choose a subclass. + def __new__(cls, *args, **kwargs): + return RuntimeError.__new__(cls) + + def __init__( + self, + message: str, + request_id: str, + batches: int, + rows: int, + table_version: Optional[int] = None, + is_transport_error: bool = False, + ): + super().__init__(message, request_id, is_transport_error=is_transport_error) + self.batches = batches + self.rows = rows + self.table_version = table_version + + def __reduce__(self) -> tuple[type, tuple]: + return ( + self.__class__, + ( + str(self), + self.request_id, + self.batches, + self.rows, + self.table_version, + self.is_transport_error, + ), + ) + + class TableNotFoundError(HttpError, ValueError, _NamespaceTableNotFoundError): """A remote table was not found. diff --git a/python/python/tests/test_errors.py b/python/python/tests/test_errors.py index d5e92731f..12a193074 100644 --- a/python/python/tests/test_errors.py +++ b/python/python/tests/test_errors.py @@ -15,6 +15,7 @@ from lancedb.remote.errors import ( HttpError, LanceDBClientError, NamespaceNotFoundError, + ResponseInterruptedError, RetryError, SecretNotFoundError, TableNotFoundError, @@ -73,6 +74,17 @@ def test_pickle_http_transport_error(): assert restored.request_id == "req-789" +def test_pickle_response_interrupted_error(): + err = ResponseInterruptedError("interrupted", "req-1", 2, 2048, 7, True) + restored = pickle.loads(pickle.dumps(err)) + assert type(restored) is ResponseInterruptedError + assert str(restored) == "interrupted" + assert restored.request_id == "req-1" + assert (restored.batches, restored.rows, restored.table_version) == (2, 2048, 7) + assert restored.is_transport_error is True + assert restored.status_code is None + + @pytest.mark.parametrize("error_code", [None, "conflict", "future_conflict_code"]) def test_http_conflict_error_preserves_reason_and_metadata(error_code): reason = "Conflict: branch 'exp' cannot be deleted, main depends on its files" diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 25d9db22a..685bc809d 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -48,6 +48,7 @@ from lancedb.remote.errors import ( ConflictError, HttpError, NamespaceNotFoundError, + ResponseInterruptedError, RetryError, ) import pytest @@ -3398,6 +3399,100 @@ def test_query_sync_minimal(): assert data == expected +def _arrow_stream(batches): + sink = pa.BufferOutputStream() + with pa.ipc.new_stream(sink, batches[0].schema) as writer: + for batch in batches: + writer.write_batch(batch) + return sink.getvalue().to_pybytes() + + +@contextlib.contextmanager +def streamed_query_table(write_body): + """Yield a remote table and the headers of each query request it sends. + + Queries get a 200 response with stream framing, whose body ``write_body`` + writes after the other headers. + """ + queries = [] + + def handler(request): + if request.path == "/v1/table/test/describe/": + id_field = {"name": "id", "type": {"type": "int32"}, "nullable": True} + schema = {"fields": [id_field]} + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps({"version": 7, "schema": schema}).encode()) + elif request.path == "/v1/table/test/query/": + queries.append(request.headers) + request.rfile.read(int(request.headers["Content-Length"])) + request.send_response(200) + request.send_header("Content-Type", "application/vnd.apache.arrow.stream") + request.send_header("x-lancedb-version", "7") + write_body(request) + else: + request.send_response(404) + request.end_headers() + + with mock_lancedb_connection(handler) as db: + 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)] + body = _arrow_stream(batches) + # The schema and first batch, without the 8-byte end-of-stream marker. + head = _arrow_stream(batches[:1])[:-8] + first_batch_read = threading.Event() + waited_for_client = [] + + def write_body(request): + request.end_headers() + request.wfile.write(head) + waited_for_client.append(first_batch_read.wait(10)) + 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] + first_batch_read.set() + assert reader.read_all()["id"].to_pylist() == [1, 2] + + # The wait times out if the client needs the whole body for the first batch. + assert waited_for_client == [True] + assert queries[0]["Accept"] == ( + "application/vnd.apache.arrow.stream, application/vnd.apache.arrow.file;q=0.9" + ) + + +@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] + + def write_body(request): + if abort: + # Closing before the promised length is a transport error. Otherwise + # the body ends cleanly, but without the end-of-stream marker. + request.send_header("Content-Length", str(len(head) + 100)) + request.end_headers() + 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] + with pytest.raises(ResponseInterruptedError) as exc_info: + reader.read_next_batch() + + error = exc_info.value + assert isinstance(error, HttpError) + assert (error.batches, error.rows, error.table_version) == (1, 1, 7) + assert error.request_id == queries[0]["x-request-id"] + assert error.is_transport_error is abort + assert len(queries) == 1 + + @pytest.mark.parametrize("query_type", ["auto", "vector", "hybrid"]) @pytest.mark.parametrize("vector_column_name", [None, "embedding"]) def test_query_sync_text_embedding(query_type, vector_column_name): diff --git a/python/src/error.rs b/python/src/error.rs index c4f20e884..1ac9f7ac3 100644 --- a/python/src/error.rs +++ b/python/src/error.rs @@ -168,6 +168,28 @@ impl PythonErrorExt for std::result::Result { err.setattr(intern!(py, "__cause__"), cause_err)?; Err(PyErr::from_value(err)) }), + LanceError::ResponseInterrupted { + request_id, + batches, + rows, + table_version, + source, + } => Python::attach(|py| { + let error = py + .import(intern!(py, "lancedb.remote.errors"))? + .getattr(intern!(py, "ResponseInterruptedError"))? + .call1(( + err.to_string(), + request_id, + *batches, + *rows, + *table_version, + is_transport_error(&**source), + ))?; + let cause = http_from_rust_error(py, &**source, request_id, None)?; + error.setattr(intern!(py, "__cause__"), cause)?; + Err(PyErr::from_value(error)) + }), LanceError::Sql { message, request_id, diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index cc5bd1f4e..7499641fc 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -205,6 +205,48 @@ fn http_timeout_hint(source: &(dyn std::error::Error + 'static)) -> &'static str } } +/// The error that ended a streamed response. +/// +/// It is shared so that a copy of [`Error::ResponseInterrupted`] keeps it: +/// DataFusion hands one error to every partition that reads the failed input. +/// It dereferences to the underlying error, which is also the next error in the +/// source chain. +#[cfg(feature = "remote")] +#[derive(Debug, Clone)] +pub struct InterruptionSource(Arc); + +#[cfg(feature = "remote")] +impl From for InterruptionSource { + fn from(source: BoxError) -> Self { + Self(source.into()) + } +} + +#[cfg(feature = "remote")] +impl std::ops::Deref for InterruptionSource { + type Target = dyn std::error::Error + Send + Sync; + + fn deref(&self) -> &Self::Target { + self.0.as_ref() + } +} + +#[cfg(feature = "remote")] +impl Display for InterruptionSource { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +// Not `Error`: an `Arc` in the source chain hides the error it holds from +// `downcast_ref`, and so would a wrapper that implements `Error`. +#[cfg(feature = "remote")] +impl snafu::AsErrorSource for InterruptionSource { + fn as_error_source(&self) -> &(dyn std::error::Error + 'static) { + self.0.as_ref() + } +} + /// Why a job failed, to whatever precision the backend provides. /// /// A job run in this process carries the error it failed with in [`Self::source`]. @@ -362,6 +404,27 @@ pub enum Error { source: Box, status_code: Option, }, + /// A streamed response stopped before the server signalled that it was complete. + /// + /// The batches already returned are valid, but the result is incomplete. The + /// request is not retried, because re-issuing it would return those batches + /// again. `table_version` is the table version the response reflected, when + /// the server reported one, so a caller can re-issue the request against it. + #[cfg(feature = "remote")] + #[snafu(display( + "Response for request_id={request_id} interrupted after {batches} batches \ + ({rows} rows): {source}{}", + http_timeout_hint(&**source) + ))] + ResponseInterrupted { + request_id: String, + /// Batches returned before the interruption. + batches: u64, + /// Rows in those batches. + rows: u64, + table_version: Option, + source: InterruptionSource, + }, #[snafu(display("Arrow error: {source}"))] Arrow { source: ArrowError }, #[snafu(display("LanceDBError: not supported: {message}"))] @@ -393,6 +456,20 @@ impl From for Error { match source { DataFusionError::ArrowError(source, _) => (*source).into(), DataFusionError::External(source) => Self::from_box_error(source), + // DataFusion adds context to an error, and shares one error between + // the partitions that read a failed input. An error of ours beneath + // either keeps its type; other errors keep the wrapper's message. + DataFusionError::Context(_, inner) if find_error(inner.as_ref()).is_some() => { + (*inner).into() + } + DataFusionError::Shared(shared) => match Arc::try_unwrap(shared) { + Ok(inner) => inner.into(), + Err(shared) => find_error(shared.as_ref()) + .and_then(Self::clone_shared) + .unwrap_or_else(|| Self::External { + source: Box::new(DataFusionError::Shared(shared)), + }), + }, other => Self::External { source: Box::new(other), }, @@ -400,6 +477,12 @@ impl From for Error { } } +/// The first error of ours in an error's source chain. +fn find_error<'a>(error: &'a (dyn std::error::Error + 'static)) -> Option<&'a Error> { + std::iter::successors(Some(error), |error| error.source()) + .find_map(|error| error.downcast_ref::()) +} + impl From for Error { fn from(source: lance::Error) -> Self { if has_unsupported_local_filesystem_source(&source) { @@ -509,6 +592,29 @@ impl Error { } } + /// A copy of an error that other partitions of a DataFusion plan still hold. + /// Only an interrupted response can be copied, because it shares its source. + fn clone_shared(&self) -> Option { + #[cfg(feature = "remote")] + if let Self::ResponseInterrupted { + request_id, + batches, + rows, + table_version, + source, + } = self + { + return Some(Self::ResponseInterrupted { + request_id: request_id.clone(), + batches: *batches, + rows: *rows, + table_version: *table_version, + source: source.clone(), + }); + } + None + } + fn from_box_error(mut source: Box) -> Self { source = match source.downcast::() { Ok(e) => match *e { @@ -619,6 +725,67 @@ mod tests { assert!(matches!(Error::from(source), Error::InvalidInput { .. })); } + /// DataFusion shares an error between the partitions that read a failed + /// input, and may add context to it. Whether or not another partition still + /// holds it, an interrupted response keeps its fields and its source. + #[cfg(feature = "remote")] + #[rstest::rstest] + fn shared_interruption_keeps_its_type_and_source( + #[values(false, true)] still_held: bool, + #[values(false, true)] with_context: bool, + ) { + let reset = BoxError::from(std::io::Error::from(std::io::ErrorKind::ConnectionReset)); + let interrupted = Error::ResponseInterrupted { + request_id: "req-1".into(), + batches: 2, + rows: 2048, + table_version: Some(7), + source: reset.into(), + }; + let shared = Arc::new(DataFusionError::External(Box::new(interrupted))); + let held = still_held.then(|| shared.clone()); + let mut error = DataFusionError::Shared(shared); + if with_context { + error = error.context("merging query results"); + } + + let error = Error::from(error); + + assert!( + matches!( + &error, + Error::ResponseInterrupted { + request_id, + batches: 2, + rows: 2048, + table_version: Some(7), + .. + } if request_id == "req-1" + ), + "{error:?}" + ); + let source = std::error::Error::source(&error).unwrap(); + assert_eq!( + source.downcast_ref::().map(|e| e.kind()), + Some(std::io::ErrorKind::ConnectionReset) + ); + drop(held); + } + + #[test] + fn other_shared_errors_keep_their_message() { + let shared = Arc::new(DataFusionError::Execution("boom".into())); + let _held = shared.clone(); + + let error = Error::from(DataFusionError::Shared(shared).context("merging")); + + assert!(matches!(error, Error::External { .. }), "{error:?}"); + assert_eq!( + error.to_string(), + "merging\ncaused by\nExecution error: boom" + ); + } + #[cfg(feature = "remote")] #[test] fn non_timeout_http_error_message_is_unchanged() { diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index ad2dbdcbf..f96e84e96 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -661,6 +661,10 @@ pub struct QueryExecutionOptions { /// By default, this is 1024 pub max_batch_length: u32, /// Max duration to wait for the query to execute before timing out. + /// + /// The timeout also covers reading the results, so a caller that consumes + /// the stream slowly can exceed it. For a remote table it counts from when + /// the query is sent, and the server is given the same timeout. pub timeout: Option, /// How distributed worker metrics should be displayed by /// [`ExecutableQuery::analyze_plan`]. @@ -747,6 +751,11 @@ pub trait ExecutableQuery { /// stream is consumed slowly (this constrains the maximum memory used by a /// single query. /// + /// A remote table decodes batches as they arrive when the server streams + /// query results. If the response stops partway, the stream ends with + /// `Error::ResponseInterrupted`. The batches already returned are valid but + /// incomplete, and the query is not retried. + /// /// For simpler access or row-based access we recommend creating extension traits /// to convert Arrow data into your internal data model. fn execute_with_options( diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index a19f4d0d9..6956905c4 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -3,6 +3,7 @@ pub mod blobs; pub mod insert; +mod ipc_stream; mod optimize; use self::insert::{RemoteWriteExec, WriteOp}; @@ -61,15 +62,15 @@ use crate::{ }, }; use arrow_array::{LargeBinaryArray, RecordBatch, RecordBatchReader}; -use arrow_ipc::reader::{FileReader, StreamReader}; -use arrow_schema::{ArrowError, DataType, SchemaRef}; +use arrow_ipc::reader::FileReader; +use arrow_schema::{DataType, SchemaRef}; use async_trait::async_trait; use chrono::{DateTime, Utc}; use datafusion_common::DataFusionError; use datafusion_physical_plan::stream::RecordBatchStreamAdapter; use datafusion_physical_plan::{ExecutionPlan, RecordBatchStream, SendableRecordBatchStream}; use futures::{StreamExt, TryStreamExt}; -use http::header::CONTENT_TYPE; +use http::header::{ACCEPT, CONTENT_TYPE}; use http::{HeaderName, StatusCode}; use lance::arrow::json::{JsonDataType, JsonSchema}; use lance::dataset::refs::TagContents; @@ -91,6 +92,10 @@ const MIN_VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-min-ve const MIN_TIMESTAMP_HEADER: HeaderName = HeaderName::from_static("x-lancedb-min-timestamp"); const MIN_READ_VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-min-read-version"); const VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-version"); +/// Asks for stream framing, which is decoded as it arrives. Servers that do not +/// stream query results ignore this and answer with file framing. +const QUERY_ACCEPT: &str = + "application/vnd.apache.arrow.stream, application/vnd.apache.arrow.file;q=0.9"; const METRIC_TYPE_KEY: &str = "metric_type"; const INDEX_TYPE_KEY: &str = "index_type"; const SCHEMA_CACHE_TTL: Duration = Duration::from_secs(30); @@ -1155,25 +1160,30 @@ impl RemoteTable { .map(str::to_owned); let framing = resolve_arrow_ipc_framing(content_type.as_deref(), request_id)?; - // Buffer the whole body. File framing keeps its footer at the end, so /query - // cannot decode incrementally. Stream framing could, via - // arrow_ipc::reader::StreamDecoder, but fetch_blobs concatenates every batch - // before returning, so no caller would see data sooner. - let body = response.bytes().await.err_to_http(request_id.into())?; - type IpcBatchIterator = - Box> + Send>; - let (schema, batches): (SchemaRef, IpcBatchIterator) = match framing { + match framing { ArrowIpcFraming::Stream => { - let reader = StreamReader::try_new(Cursor::new(body), None)?; - (reader.schema(), Box::new(reader)) + let table_version = response + .headers() + .get(&VERSION_HEADER) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse().ok()); + ipc_stream::read_ipc_stream( + response.bytes_stream(), + request_id.to_string(), + table_version, + ) + .await } ArrowIpcFraming::File => { + // File framing keeps its footer at the end, so the whole body is + // needed before anything can be decoded. + let body = response.bytes().await.err_to_http(request_id.into())?; let reader = FileReader::try_new(Cursor::new(body), None)?; - (reader.schema(), Box::new(reader)) + let schema = reader.schema(); + let stream = futures::stream::iter(reader).map_err(DataFusionError::from); + Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream))) } - }; - let stream = futures::stream::iter(batches).map_err(DataFusionError::from); - Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream))) + } } fn apply_query_params( @@ -1544,8 +1554,15 @@ impl RemoteTable { ) -> Result>>> { let mut request = self .client - .post(&format!("/v1/table/{}/query/", self.identifier)); + .post(&format!("/v1/table/{}/query/", self.identifier)) + .header(ACCEPT, QUERY_ACCEPT); + // The timeout bounds the whole query, including reading the response, as + // the server's own deadline for this request does. A deadline too far + // away to represent is never reached. + let deadline = options + .timeout + .and_then(|timeout| Some((tokio::time::Instant::now().checked_add(timeout)?, timeout))); if let Some(timeout) = options.timeout { // Also send to server, so it can abort the query if it takes too long. // (If it doesn't fit into u64, it's not worth sending anyways.) @@ -1569,28 +1586,28 @@ impl RemoteTable { }); let streams = futures::future::try_join_all(futures); - let streams = if let Some(timeout) = options.timeout { - let timeout_future = tokio::time::sleep(timeout); - tokio::pin!(timeout_future); - tokio::pin!(streams); - tokio::select! { - _ = &mut timeout_future => { - return Err(Error::Other { - message: format!("Query timeout after {} ms", timeout.as_millis()), - source: None, - }) - } - result = &mut streams => { - result? - } - } + let streams = if let Some((deadline, timeout)) = deadline { + tokio::time::timeout_at(deadline, streams) + .await + .map_err(|_| Error::Other { + message: format!("Query timeout after {} ms", timeout.as_millis()), + source: None, + })?? } else { streams.await? }; Ok(streams .into_iter() - .map(|stream| restore_projection_order(stream, &query.base().select)) + .map(|stream| { + let stream = restore_projection_order(stream, &query.base().select); + match deadline { + Some((deadline, timeout)) => { + Box::pin(TimeoutStream::with_deadline(stream, timeout, deadline)) + } + None => stream, + } + }) .collect()) } @@ -1714,8 +1731,9 @@ fn schema_from_description(schema: JsonSchema) -> Result { ))) } -/// How a response body frames its Arrow IPC payload. `/query` answers with file framing -/// and `fetch_blobs` with stream framing, so the reader is picked per response. +/// How a response body frames its Arrow IPC payload. `fetch_blobs` answers with stream +/// framing, and `/query` with stream framing only on servers that stream query results, +/// so the reader is picked per response. enum ArrowIpcFraming { File, Stream, @@ -4439,6 +4457,7 @@ mod tests { BinaryArray, Int32Array, Int64Array, RecordBatch, RecordBatchIterator, StringArray, StructArray, record_batch, }; + use arrow_ipc::reader::StreamReader; use arrow_schema::{DataType, Field, Schema}; use chrono::{DateTime, Utc}; use futures::{StreamExt, TryFutureExt, TryStreamExt, future::BoxFuture}; @@ -7093,25 +7112,36 @@ mod tests { assert_eq!(blobs.value(0), b"alpha"); } + // Read as a stream, a file's leading magic declares a message longer than the + // whole body, so the body ends before the stream does. #[rstest] - #[case(ARROW_STREAM_CONTENT_TYPE, write_ipc_file(&one_row_blob_batch("image")))] + #[case(ARROW_STREAM_CONTENT_TYPE, write_ipc_file(&one_row_blob_batch("image")), true)] #[case( ARROW_FILE_CONTENT_TYPE, - write_ipc_stream_uncompressed(&one_row_blob_batch("image")) + write_ipc_stream_uncompressed(&one_row_blob_batch("image")), + false )] #[tokio::test] async fn test_fetch_blobs_fails_when_the_body_contradicts_the_content_type( #[case] content_type: &'static str, #[case] body: Vec, + #[case] ends_early: bool, ) { let table = table_with_fetch_blobs_content_type(Some(content_type), body); let error = table.fetch_blobs("image", &[10]).await.unwrap_err(); - assert!( - matches!(error, Error::Arrow { .. }), - "expected an Arrow decode failure, got {error}" - ); + if ends_early { + assert!( + matches!(error, Error::ResponseInterrupted { batches: 0, .. }), + "expected an incomplete stream, got {error}" + ); + } else { + assert!( + matches!(error, Error::Arrow { .. }), + "expected an Arrow decode failure, got {error}" + ); + } } #[tokio::test] diff --git a/rust/lancedb/src/remote/table/ipc_stream.rs b/rust/lancedb/src/remote/table/ipc_stream.rs new file mode 100644 index 000000000..af31a9b28 --- /dev/null +++ b/rust/lancedb/src/remote/table/ipc_stream.rs @@ -0,0 +1,729 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Incremental decoding of response bodies that use Arrow IPC stream framing. + +use arrow_array::RecordBatch; +use arrow_buffer::Buffer; +use arrow_ipc::reader::StreamDecoder; +use bytes::Bytes; +use datafusion_common::DataFusionError; +use datafusion_physical_plan::SendableRecordBatchStream; +use datafusion_physical_plan::stream::RecordBatchStreamAdapter; +use futures::stream::BoxStream; +use futures::{Stream, StreamExt, TryStreamExt}; + +use crate::error::{BoxError, Error, Result}; + +/// Decode an Arrow IPC stream from a response body as its chunks arrive. +/// +/// Only the current chunk and the decoder's state are held, so memory is bounded +/// by the size of a batch rather than the size of the result. This waits for the +/// first batch, or for the end of an empty result, so a body that fails before +/// any data arrives fails the request itself. +/// +/// A complete body ends with the end-of-stream marker; the server aborts the body +/// without it when the query fails after sending headers. A body that ends early, +/// even between messages, is reported as [`Error::ResponseInterrupted`] and never +/// as a short result. +pub(super) async fn read_ipc_stream( + chunks: impl Stream> + Send + 'static, + request_id: String, + table_version: Option, +) -> Result +where + E: Into + 'static, +{ + let mut body = IpcStreamBody { + chunks: chunks.map_err(Into::into).boxed(), + chunk: Buffer::default(), + decoder: StreamDecoder::new(), + finished: false, + request_id, + table_version, + batches: 0, + rows: 0, + }; + let first = body.next_batch().await?; + // The schema is the first message, so only a body holding nothing but the + // end-of-stream marker can complete without one. + let schema = body.decoder.schema().ok_or_else(|| Error::Http { + source: "Arrow IPC stream ended without a schema".into(), + request_id: body.request_id.clone(), + status_code: None, + })?; + let rest = futures::stream::try_unfold(body, |mut body| async move { + Ok(body.next_batch().await?.map(|batch| (batch, body))) + }); + let batches = futures::stream::iter(first.map(Ok)) + .chain(rest) + .map_err(|error: Error| DataFusionError::External(Box::new(error))); + Ok(Box::pin(RecordBatchStreamAdapter::new(schema, batches))) +} + +struct IpcStreamBody { + chunks: BoxStream<'static, std::result::Result>, + /// The part of the current chunk that has not been decoded yet. + chunk: Buffer, + decoder: StreamDecoder, + /// Set once the body has ended with the end-of-stream marker. + finished: bool, + request_id: String, + table_version: Option, + batches: u64, + rows: u64, +} + +impl IpcStreamBody { + /// Decode until the next batch is complete. Returns `None` once the body + /// has ended with the end-of-stream marker. + async fn next_batch(&mut self) -> Result> { + while !self.finished { + if self.chunk.is_empty() { + match self.chunks.next().await { + Some(Ok(chunk)) => self.chunk = chunk.into(), + Some(Err(error)) => return Err(self.interrupted(error)), + None if read_end_of_stream(&mut self.decoder) => self.finished = true, + None => { + return Err(self.interrupted( + "the response ended before the Arrow end-of-stream marker".into(), + )); + } + } + continue; + } + // Decoding stops after each batch, keeping the rest of the chunk. + if let Some(batch) = self.decoder.decode(&mut self.chunk)? { + self.batches += 1; + self.rows += batch.num_rows() as u64; + return Ok(Some(batch)); + } + } + Ok(None) + } + + fn interrupted(&self, source: BoxError) -> Error { + Error::ResponseInterrupted { + request_id: self.request_id.clone(), + batches: self.batches, + rows: self.rows, + table_version: self.table_version, + source: source.into(), + } + } +} + +/// Whether the decoder has read the end-of-stream marker. +/// +/// [`StreamDecoder::finish`] also accepts input that stops between messages, +/// because the Arrow format lets a writer end a stream by closing it. A decoder +/// that has read the marker rejects any further input, which is the only way +/// its API tells the two apart. +fn read_end_of_stream(decoder: &mut StreamDecoder) -> bool { + decoder.finish().is_ok() && decoder.decode(&mut Buffer::from_slice_ref([0u8])).is_err() +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + use std::sync::{Arc, Mutex}; + use std::time::Duration; + + use arrow_array::builder::StringDictionaryBuilder; + use arrow_array::types::Int8Type; + use arrow_array::{ArrayRef, Int32Array, StringArray}; + use arrow_ipc::CompressionType; + use arrow_ipc::writer::{DictionaryHandling, FileWriter, IpcWriteOptions, StreamWriter}; + use arrow_schema::{DataType, Field, Schema, SchemaRef}; + use lance::arrow::json::JsonSchema; + use rstest::rstest; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::{TcpListener, TcpStream}; + use tokio::sync::mpsc; + + use super::*; + use crate::query::{ExecutableQuery, QueryExecutionOptions}; + use crate::remote::client::{ClientConfig, RetryConfig}; + use crate::remote::{ARROW_FILE_CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE}; + use crate::{Table, connect}; + + /// Three batches of two rows under a schema with metadata. The second batch's + /// dictionary extends the first one's, which writers can send as a delta, and + /// the third replaces it. + fn batches() -> Vec { + let schema = Arc::new(Schema::new_with_metadata( + vec![ + Field::new("id", DataType::Int32, false), + Field::new_dictionary("label", DataType::Int8, DataType::Utf8, false), + ], + HashMap::from([("origin".to_string(), "test".to_string())]), + )); + let labels: [(&[&str], [&str; 2]); 3] = [ + (&["a", "b"], ["a", "b"]), + (&["a", "b", "c"], ["c", "a"]), + (&["d"], ["d", "d"]), + ]; + labels + .into_iter() + .enumerate() + .map(|(i, (dictionary, values))| { + let dictionary = StringArray::from(dictionary.to_vec()); + let mut label = + StringDictionaryBuilder::::new_with_dictionary(2, &dictionary) + .unwrap(); + values + .into_iter() + .for_each(|value| label.append_value(value)); + let id = Int32Array::from(vec![2 * i as i32, 2 * i as i32 + 1]); + RecordBatch::try_new( + schema.clone(), + vec![Arc::new(id) as ArrayRef, Arc::new(label.finish())], + ) + .unwrap() + }) + .collect() + } + + /// An IPC stream cut where the server cuts it: after the schema, after each + /// batch with its dictionaries, and after the end-of-stream marker. + fn messages( + schema: &Schema, + batches: &[RecordBatch], + options: IpcWriteOptions, + ) -> Vec> { + let mut writer = StreamWriter::try_new_with_options(Vec::new(), schema, options).unwrap(); + let mut messages = vec![std::mem::take(writer.get_mut())]; + for batch in batches { + writer.write(batch).unwrap(); + messages.push(std::mem::take(writer.get_mut())); + } + writer.finish().unwrap(); + messages.push(std::mem::take(writer.get_mut())); + messages + } + + fn chunks(body: &[u8], size: usize) -> Vec> { + body.chunks(size) + .map(|chunk| Ok(Bytes::copy_from_slice(chunk))) + .collect() + } + + /// The schema, the batches yielded, and the error that ended the stream. + async fn read( + chunks: Vec>, + ) -> (Option, Vec, Option) { + let stream = + match read_ipc_stream(futures::stream::iter(chunks), "request".into(), Some(7)).await { + Ok(stream) => stream, + Err(error) => return (None, vec![], Some(error)), + }; + let schema = stream.schema(); + let results = stream.collect::>().await; + let (batches, errors): (Vec<_>, Vec<_>) = results.into_iter().partition(|r| r.is_ok()); + assert!(errors.len() <= 1, "the stream ends at its first error"); + let error = errors + .into_iter() + .next() + .map(|e| Error::from(e.unwrap_err())); + let batches = batches.into_iter().map(|r| r.unwrap()).collect(); + (Some(schema), batches, error) + } + + fn assert_interrupted(error: Option, expected_batches: u64, expected_rows: u64) { + match error { + Some(Error::ResponseInterrupted { + request_id, + batches, + rows, + table_version, + .. + }) => { + assert_eq!(request_id, "request"); + assert_eq!((batches, rows), (expected_batches, expected_rows)); + assert_eq!(table_version, Some(7)); + } + other => panic!("expected an interrupted response, got {other:?}"), + } + } + + // One-byte chunks split every message; a single chunk holds them all. + #[rstest] + #[case(1)] + #[case(7)] + #[case(usize::MAX)] + #[tokio::test] + async fn decodes_any_chunking(#[case] chunk_size: usize) { + let input = batches(); + let body = messages(&input[0].schema(), &input, IpcWriteOptions::default()).concat(); + + let (schema, output, error) = read(chunks(&body, chunk_size)).await; + + assert!(error.is_none(), "{error:?}"); + assert_eq!(schema.unwrap(), input[0].schema()); + assert_eq!(output, input); + } + + #[rstest] + #[case(IpcWriteOptions::default().with_dictionary_handling(DictionaryHandling::Delta))] + #[case(IpcWriteOptions::default().try_with_compression(Some(CompressionType::LZ4_FRAME)).unwrap())] + #[case(IpcWriteOptions::default().try_with_compression(Some(CompressionType::ZSTD)).unwrap())] + #[tokio::test] + async fn decodes_dictionary_deltas_and_compressed_batches(#[case] options: IpcWriteOptions) { + let input = batches(); + let body = messages(&input[0].schema(), &input, options).concat(); + + let (_, output, error) = read(chunks(&body, 5)).await; + + assert!(error.is_none(), "{error:?}"); + assert_eq!(output, input); + } + + /// The server answers an empty result with the schema and the end-of-stream marker. + #[tokio::test] + async fn empty_result_keeps_its_schema() { + let schema = batches()[0].schema(); + let body = messages(&schema, &[], IpcWriteOptions::default()).concat(); + + let (decoded, output, error) = read(chunks(&body, 3)).await; + + assert!(error.is_none(), "{error:?}"); + assert_eq!(decoded.unwrap(), schema); + assert!(output.is_empty()); + } + + #[tokio::test] + async fn body_ending_without_end_of_stream_is_interrupted() { + let input = batches(); + let messages = messages(&input[0].schema(), &input, IpcWriteOptions::default()); + let complete = messages[..messages.len() - 1].concat(); + let after_first_batch = messages[..2].concat().len(); + // Where the body stops, and how many batches it holds by then. + for (end, delivered) in [ + (complete.len(), 3), // between messages, after the last batch + (complete.len() - 3, 2), // inside the last batch + (after_first_batch, 1), // between messages + (messages[0].len(), 0), // after the schema + (messages[0].len() / 2, 0), // inside the schema + (0, 0), // an empty body + ] { + let (_, output, error) = read(chunks(&complete[..end], 4)).await; + assert_eq!(output, input[..delivered], "body cut at {end}"); + assert_interrupted(error, delivered as u64, 2 * delivered as u64); + } + } + + #[tokio::test] + async fn body_error_is_interrupted() { + let input = batches(); + let messages = messages(&input[0].schema(), &input, IpcWriteOptions::default()); + let mut body = chunks(&messages[..2].concat(), usize::MAX); + body.push(Err(std::io::Error::other("connection reset"))); + + let (_, output, error) = read(body).await; + + assert_eq!(output, input[..1]); + let message = error.as_ref().map(ToString::to_string).unwrap_or_default(); + assert!(message.contains("connection reset"), "{message}"); + assert_interrupted(error, 1, 2); + } + + #[tokio::test] + async fn malformed_body_is_an_arrow_error() { + let input = batches(); + let messages = messages(&input[0].schema(), &input, IpcWriteOptions::default()); + // A message whose metadata is not a flatbuffer. + let garbage = [&[0xff; 4][..], &8u32.to_le_bytes(), &[0xab; 8]].concat(); + // Anything after the end-of-stream marker. + let trailing = [messages.concat(), vec![0]].concat(); + for body in [[messages[0].clone(), garbage].concat(), trailing] { + let (_, _, error) = read(chunks(&body, usize::MAX)).await; + assert!(matches!(error, Some(Error::Arrow { .. })), "{error:?}"); + } + } + + /// What the test server does next for a query request. + enum Reply { + /// A complete response with this status and an empty body. + Status(u16), + /// Headers of a chunked body with this content type. + Head(Option<&'static str>), + Chunk(Vec), + /// The last chunk, ending the body cleanly. + End, + /// Close the connection in the middle of the body. + Abort, + } + + struct Server { + table: Table, + replies: mpsc::UnboundedSender, + /// Headers of each query request received. + queries: Arc>>>, + } + + impl Server { + fn reply(&self, replies: impl IntoIterator) { + replies + .into_iter() + .for_each(|reply| self.replies.send(reply).unwrap()); + } + } + + /// Serve table `t` over HTTP. Query requests are answered, in order, by the + /// replies the test sends. + async fn serve() -> Server { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let (replies, mut pending) = mpsc::unbounded_channel(); + let queries = Arc::new(Mutex::new(Vec::new())); + let received = queries.clone(); + tokio::spawn(async move { + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + let (path, headers) = read_request(&mut socket).await; + if path.ends_with("/describe/") { + let schema = Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new( + "vector", + DataType::new_fixed_size_list(DataType::Float32, 2, true), + false, + ), + ]); + let body = serde_json::json!({ + "version": 7, + "schema": JsonSchema::try_from(&schema).unwrap(), + }) + .to_string(); + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + socket.write_all(response.as_bytes()).await.unwrap(); + continue; + } + received.lock().unwrap().push(headers); + while let Some(reply) = pending.recv().await { + let last = !matches!(reply, Reply::Head(_) | Reply::Chunk(_)); + let bytes = match reply { + Reply::Status(status) => format!( + "HTTP/1.1 {status} Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ) + .into_bytes(), + Reply::Head(content_type) => format!( + "HTTP/1.1 200 OK\r\n{}Transfer-Encoding: chunked\r\n\ + x-lancedb-version: 7\r\nConnection: close\r\n\r\n", + content_type + .map(|value| format!("Content-Type: {value}\r\n")) + .unwrap_or_default() + ) + .into_bytes(), + Reply::Chunk(chunk) => { + [format!("{:x}\r\n", chunk.len()).into_bytes(), chunk, b"\r\n".into()] + .concat() + } + Reply::End => b"0\r\n\r\n".to_vec(), + Reply::Abort => break, + }; + // The client may have stopped reading. + if socket.write_all(&bytes).await.is_err() || last { + break; + } + } + } + }); + let db = connect("db://test") + .api_key("key") + .region("us-east-1") + .host_override(&format!("http://{address}")) + .client_config(ClientConfig { + retry_config: RetryConfig { + backoff_factor: Some(0.0), + backoff_jitter: Some(0.0), + ..Default::default() + }, + ..Default::default() + }) + .execute() + .await + .unwrap(); + let table = db.open_table("t").execute().await.unwrap(); + Server { + table, + replies, + queries, + } + } + + async fn read_request(socket: &mut TcpStream) -> (String, HashMap) { + let mut request = Vec::new(); + let mut buf = [0; 4096]; + let head_end = loop { + let n = socket.read(&mut buf).await.unwrap(); + assert!(n > 0, "connection closed before the request head"); + request.extend_from_slice(&buf[..n]); + if let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") { + break end + 4; + } + }; + let head = String::from_utf8(request[..head_end].to_vec()).unwrap(); + let mut lines = head.lines(); + let path = lines.next().unwrap().split(' ').nth(1).unwrap().to_string(); + let headers: HashMap<_, _> = lines + .filter_map(|line| line.split_once(':')) + .map(|(name, value)| (name.to_ascii_lowercase(), value.trim().to_string())) + .collect(); + let length: usize = headers + .get("content-length") + .map_or(0, |length| length.parse().unwrap()); + while request.len() < head_end + length { + let n = socket.read(&mut buf).await.unwrap(); + assert!(n > 0, "connection closed before the request body"); + request.extend_from_slice(&buf[..n]); + } + (path, headers) + } + + /// The query batches as the server sends them: `id` only. + fn id_messages() -> Vec> { + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let batches: Vec<_> = (0..3) + .map(|i| { + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![i]))]) + .unwrap() + }) + .collect(); + messages(&schema, &batches, IpcWriteOptions::default()) + } + + fn ids(batch: &RecordBatch) -> Vec { + batch["id"] + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + } + + #[tokio::test] + async fn first_batch_arrives_before_the_rest_of_the_body() { + let server = serve().await; + let messages = id_messages(); + server.reply([ + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages[..2].concat()), + ]); + + // The server sends the rest only after the first batch has been read. + let (results, first) = tokio::time::timeout(Duration::from_secs(10), async { + let mut results = server.table.query().execute().await.unwrap(); + let first = results.next().await.unwrap().unwrap(); + (results, first) + }) + .await + .expect("the first batch must not wait for the whole body"); + assert_eq!(ids(&first), [0]); + server.reply([Reply::Chunk(messages[2..].concat()), Reply::End]); + let rest = results.try_collect::>().await.unwrap(); + assert_eq!(rest.iter().flat_map(ids).collect::>(), [1, 2]); + + let queries = server.queries.lock().unwrap(); + assert_eq!(queries.len(), 1); + assert_eq!(queries[0]["accept"], super::super::QUERY_ACCEPT); + } + + /// A server abort, and a proxy that turns it into a clean end of the body, + /// both fail the query after the batches already read. Neither is retried. + #[rstest] + #[case::abort(Reply::Abort, true)] + #[case::clean_end(Reply::End, false)] + #[tokio::test] + async fn interrupted_body_is_typed_and_not_retried( + #[case] end: Reply, + #[case] transport_error: bool, + ) { + let server = serve().await; + let messages = id_messages(); + server.reply([ + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages[..2].concat()), + end, + ]); + + let mut results = server.table.query().execute().await.unwrap(); + assert_eq!(ids(&results.next().await.unwrap().unwrap()), [0]); + let error = results.next().await.unwrap().unwrap_err(); + assert!(results.next().await.is_none()); + + let Error::ResponseInterrupted { + request_id, + batches, + rows, + table_version, + source, + } = error + else { + panic!("expected an interrupted response, got {error:?}"); + }; + assert!(!request_id.is_empty()); + assert_eq!((batches, rows, table_version), (1, 1, Some(7))); + assert_eq!(source.is::(), transport_error, "{source}"); + assert_eq!(server.queries.lock().unwrap().len(), 1); + } + + /// Vector queries run through a DataFusion plan, which must keep the error's type. + #[tokio::test] + async fn vector_query_keeps_the_interruption_type() { + let server = serve().await; + let messages = id_messages(); + server.reply([ + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages[..2].concat()), + Reply::Abort, + ]); + + let results = server + .table + .query() + .nearest_to(&[0.0f32, 0.0]) + .unwrap() + .execute() + .await + .unwrap(); + let error = results.try_collect::>().await.unwrap_err(); + + assert!( + matches!(error, Error::ResponseInterrupted { batches: 1, .. }), + "{error:?}" + ); + } + + /// A server without multi-vector support gets a request per vector, and the + /// plan merging the responses shares an error between its partitions. + #[tokio::test] + async fn multi_vector_query_keeps_the_interruption() { + let server = serve().await; + let messages = id_messages(); + // Which vector gets which response does not matter. + server.reply([ + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages.concat()), + Reply::End, + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages[..2].concat()), + Reply::Abort, + ]); + + let results = server + .table + .query() + .nearest_to(&[0.0f32, 0.0]) + .unwrap() + .add_query_vector(&[1.0f32, 1.0]) + .unwrap() + .execute() + .await + .unwrap(); + let error = results.try_collect::>().await.unwrap_err(); + + let Error::ResponseInterrupted { + request_id, + batches, + rows, + table_version, + source, + } = error + else { + panic!("expected an interrupted response, got {error:?}"); + }; + assert!(!request_id.is_empty()); + assert_eq!((batches, rows, table_version), (1, 1, Some(7))); + assert!(source.is::(), "{source}"); + assert_eq!(server.queries.lock().unwrap().len(), 2); + } + + #[tokio::test] + async fn timeout_covers_reading_the_body() { + let server = serve().await; + let messages = id_messages(); + // The body stalls after the first batch. + server.reply([ + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages[..2].concat()), + ]); + + let options = QueryExecutionOptions { + timeout: Some(Duration::from_millis(500)), + ..Default::default() + }; + let mut results = server + .table + .query() + .execute_with_options(options) + .await + .unwrap(); + assert_eq!(ids(&results.next().await.unwrap().unwrap()), [0]); + let error = tokio::time::timeout(Duration::from_secs(10), results.next()) + .await + .expect("the timeout must end a stalled body") + .unwrap() + .unwrap_err(); + + assert!( + !matches!(error, Error::ResponseInterrupted { .. }), + "{error:?}" + ); + assert!( + error.to_string().contains("Query timeout after 500 ms"), + "{error}" + ); + assert_eq!( + server.queries.lock().unwrap()[0]["x-request-timeout-ms"], + "500" + ); + } + + /// Servers that do not stream query results answer with file framing, or + /// with no content type at all. + #[rstest] + #[case(Some(ARROW_FILE_CONTENT_TYPE))] + #[case(None)] + #[tokio::test] + async fn file_framing_is_still_read(#[case] content_type: Option<&'static str>) { + let server = serve().await; + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let batch = + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![4, 5]))]) + .unwrap(); + let mut writer = FileWriter::try_new(Vec::new(), &schema).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + server.reply([ + Reply::Head(content_type), + Reply::Chunk(writer.into_inner().unwrap()), + Reply::End, + ]); + + let results = server.table.query().execute().await.unwrap(); + let output = results.try_collect::>().await.unwrap(); + + assert_eq!(output, [batch]); + } + + #[tokio::test] + async fn failure_before_headers_is_retried() { + let server = serve().await; + server.reply([ + Reply::Status(503), + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(id_messages().concat()), + Reply::End, + ]); + + let results = server.table.query().execute().await.unwrap(); + let output = results.try_collect::>().await.unwrap(); + + assert_eq!(output.iter().flat_map(ids).collect::>(), [0, 1, 2]); + assert_eq!(server.queries.lock().unwrap().len(), 2); + } +} diff --git a/rust/lancedb/src/utils/mod.rs b/rust/lancedb/src/utils/mod.rs index 560fe858a..eedff924d 100644 --- a/rust/lancedb/src/utils/mod.rs +++ b/rust/lancedb/src/utils/mod.rs @@ -680,6 +680,22 @@ impl TimeoutStream { Box::pin(Self::new(inner, timeout)) } + /// Like [`Self::new`], but the stream expires at `deadline` rather than + /// `timeout` after its first poll. `timeout` is only used in the error. + pub fn with_deadline( + inner: SendableRecordBatchStream, + timeout: std::time::Duration, + deadline: tokio::time::Instant, + ) -> Self { + Self { + inner, + state: TimeoutState::Started { + deadline: Box::pin(tokio::time::sleep_until(deadline)), + timeout, + }, + } + } + fn timeout_error(timeout: &std::time::Duration) -> DataFusionError { DataFusionError::Execution(format!("Query timeout after {} ms", timeout.as_millis())) } From 0a5c36c1e2ead5baf87d62dfc36cada7ced0d581 Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Mon, 9 Nov 2026 21:55:58 -0800 Subject: [PATCH 2/5] feat: plan computed columns against the session's DataFusion functions (#4924) A computed column's expression is planned with Lance's default planner, so a function the embedder registers with DataFusion can't be declared, and the declared field drops the return-field metadata a function attaches, such as a logical type. Every site that plans a declaration (declare, validate, refresh, schema changes, view and table creation) now uses the DataFusion session the table's lance session carries, when there is one. The declared field keeps the expression's return-field metadata, without schema declarations such as a primary key. --- rust/lancedb/src/database/namespace.rs | 3 + rust/lancedb/src/materialized_view.rs | 13 +- rust/lancedb/src/materialized_view/refresh.rs | 2 +- rust/lancedb/src/table.rs | 13 +- rust/lancedb/src/table/add_columns.rs | 24 ++ rust/lancedb/src/table/computed_columns.rs | 260 +++++++++++++++--- rust/lancedb/src/table/refresh.rs | 8 +- rust/lancedb/src/table/schema_evolution.rs | 17 +- 8 files changed, 291 insertions(+), 49 deletions(-) diff --git a/rust/lancedb/src/database/namespace.rs b/rust/lancedb/src/database/namespace.rs index d93f73c64..4e61710ff 100644 --- a/rust/lancedb/src/database/namespace.rs +++ b/rust/lancedb/src/database/namespace.rs @@ -336,6 +336,9 @@ impl Database for LanceNamespaceDatabase { // Refuse a bad declaration before the namespace records a table. crate::table::computed_columns::ensure_declarations_are_planned( &request.data.arrow_schema(), + self.session + .as_deref() + .and_then(lance::session::Session::datafusion_session), )?; let mut table_id = request.namespace_path.clone(); table_id.push(request.name.clone()); diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index c263dc001..bd7fbb942 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -958,7 +958,7 @@ fn is_declaration(key: &str) -> bool { || crate::table::computed_columns::is_declaration_key(key) } -fn without_declarations(field: &ArrowField) -> ArrowField { +pub(crate) fn without_declarations(field: &ArrowField) -> ArrowField { let metadata: HashMap = field .metadata() .iter() @@ -1123,6 +1123,10 @@ impl PreparedDeclaration { /// are validated over the assembled schema, and read only columns the /// view holds (see [`PreparedDeclaration::input_column`]). /// + /// `session` holds the DataFusion functions a declaration may call, as + /// for [`AddColumnsBuilder::computed`](crate::table::AddColumnsBuilder::computed); + /// `None` plans against Lance's built-in functions only. + /// /// ```no_run /// # #![recursion_limit = "256"] /// # use std::collections::HashMap; @@ -1148,7 +1152,7 @@ impl PreparedDeclaration { /// (INPUTS_META_KEY.into(), format!("[\"{text}\"]")), /// ])); /// let view = prepared - /// .with_computed_columns(vec![(1, length)], &[])? + /// .with_computed_columns(vec![(1, length)], &[], None)? /// .create("lengths") /// .await?; /// view.refresh().execute().await?; // rows land with `length` NULL @@ -1160,6 +1164,7 @@ impl PreparedDeclaration { mut self, columns: Vec<(usize, ArrowField)>, bindings: &[FunctionBinding], + session: Option<&datafusion::execution::context::SessionContext>, ) -> Result { let invalid = |message: String| Error::InvalidInput { message }; if columns.is_empty() { @@ -1223,7 +1228,7 @@ impl PreparedDeclaration { } rewrite_column_definitions(&mut metadata, self.schema.as_ref(), &fields)?; let schema = ArrowSchema::new_with_metadata(fields, metadata); - ensure_declarations_are_planned(&schema)?; + ensure_declarations_are_planned(&schema, session)?; self.schema = Arc::new(schema); Ok(self) } @@ -2685,7 +2690,7 @@ mod tests { (INPUTS_META_KEY.into(), "[\"x\"]".into()), ])); let view = prepared - .with_computed_columns(vec![(1, doubled)], &[]) + .with_computed_columns(vec![(1, doubled)], &[], None) .unwrap() .create("m") .await diff --git a/rust/lancedb/src/materialized_view/refresh.rs b/rust/lancedb/src/materialized_view/refresh.rs index 1072b7684..8851d071e 100644 --- a/rust/lancedb/src/materialized_view/refresh.rs +++ b/rust/lancedb/src/materialized_view/refresh.rs @@ -133,7 +133,7 @@ pub(crate) async fn execute_refresh( })?; let physical = Arc::new(ArrowSchema::from(view_ds.schema())); - ensure_declarations_are_planned(&physical)?; + ensure_declarations_are_planned(&physical, view_ds.session().datafusion_session())?; if let Some(field) = physical .fields() .iter() diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index cc7b820f9..a58567b2e 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -3407,7 +3407,11 @@ impl NativeTable { namespace_client: Option>, pushdown_operations: HashSet, ) -> Result { - let batches = computed_columns::admit_create_source(batches)?; + let session = params.as_ref().and_then(|p| p.session.as_deref()); + let batches = computed_columns::admit_create_source( + batches, + session.and_then(lance::session::Session::datafusion_session), + )?; // Default params uses format v1. let params = params.unwrap_or(WriteParams { ..Default::default() @@ -3508,7 +3512,12 @@ impl NativeTable { pushdown_operations: HashSet, session: Option>, ) -> Result { - let batches = computed_columns::admit_create_source(batches)?; + let batches = computed_columns::admit_create_source( + batches, + session + .as_deref() + .and_then(lance::session::Session::datafusion_session), + )?; // Build table_id from namespace + name for the storage options provider let mut table_id = namespace.clone(); table_id.push(name.to_string()); diff --git a/rust/lancedb/src/table/add_columns.rs b/rust/lancedb/src/table/add_columns.rs index be319a8be..1b827bb37 100644 --- a/rust/lancedb/src/table/add_columns.rs +++ b/rust/lancedb/src/table/add_columns.rs @@ -89,6 +89,30 @@ impl AddColumnsBuilder { /// # Ok(()) /// # } /// ``` + /// + /// In LanceDB Embedded, an expression can also call functions registered + /// on a DataFusion `SessionContext` attached to the connection's Lance + /// session. They are not stored with the table, so attach them on every + /// connection that opens it. + /// + /// ```no_run + /// # use std::sync::Arc; + /// # use datafusion::execution::context::SessionContext; + /// # use datafusion::logical_expr::ScalarUDF; + /// # async fn declare(my_udf: ScalarUDF) -> Result<(), Box> { + /// let functions = SessionContext::new(); + /// functions.register_udf(my_udf); + /// let session = lance::session::Session::default().with_datafusion_session(functions); + /// let db = lancedb::connect("data/db") + /// .session(Arc::new(session)) + /// .execute() + /// .await?; + /// let table = db.open_table("t").execute().await?; + /// table.add_columns().computed("y", "my_udf(x)").execute().await?; + /// table.refresh_column("y").await?; + /// # Ok(()) + /// # } + /// ``` pub fn computed(mut self, name: impl Into, expression: impl Into) -> Self { self.computed.push((name.into(), expression.into())); self diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 0e02e7ce2..e6d7d432c 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -26,6 +26,7 @@ use std::collections::{BTreeSet, HashMap, HashSet}; use std::sync::Arc; use arrow_schema::{DataType, Field as ArrowField, Fields, Schema as ArrowSchema, SchemaRef}; +use datafusion::execution::context::SessionContext; use datafusion_common::{ScalarValue, tree_node::TreeNode}; use datafusion_expr::Expr; use datafusion_physical_plan::PhysicalExpr; @@ -40,6 +41,7 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; use crate::function::{FUNCTION_BLOB_V2_TYPE, FunctionApplication, FunctionBinding}; +use crate::materialized_view::without_declarations; use crate::utils::resolve_arrow_field_path; use crate::{Error, Result}; @@ -1640,8 +1642,12 @@ pub(crate) fn plan_function_application( /// /// Paths are compared at their root: a declaration reading `metadata` is /// invalidated by a change to `metadata.age` just as surely. -pub(crate) fn ensure_not_an_input(schema: &SchemaRef, paths: &[&str]) -> Result<()> { - ensure_not_an_input_of(schema, paths, &[]) +pub(crate) fn ensure_not_an_input( + schema: &SchemaRef, + paths: &[&str], + session: Option<&SessionContext>, +) -> Result<()> { + ensure_not_an_input_of(schema, paths, &[], session) } /// [`ensure_not_an_input`] where `removed` names columns whose own @@ -1651,6 +1657,7 @@ pub(crate) fn ensure_not_an_input_of( schema: &SchemaRef, paths: &[&str], removed: &[&str], + session: Option<&SessionContext>, ) -> Result<()> { // By identity, not spelling: a quoted path names the same column, while // a path *into* one removes no declaration at all. @@ -1668,7 +1675,7 @@ pub(crate) fn ensure_not_an_input_of( // The expression, not stored inputs, is the source of truth; an // expression that no longer parses proves nothing, so refuse. let inputs = match &declaration.kind { - ComputedColumnKind::Sql { expression } => Planner::new(schema.clone()) + ComputedColumnKind::Sql { expression } => session_planner(schema.clone(), session) .parse_expr(expression) .map(|parsed| Planner::column_names_in_expr(&parsed)) .map_err(|e| Error::InvalidInput { @@ -1760,7 +1767,10 @@ pub(crate) fn ensure_batch_writes_no_computed_values( /// Function declaration satisfies the binding contract, and no SQL /// declaration reads another computed column. What passes here is what /// `refresh_column` can execute. -pub(crate) fn ensure_declarations_are_planned(schema: &ArrowSchema) -> Result<()> { +pub(crate) fn ensure_declarations_are_planned( + schema: &ArrowSchema, + session: Option<&SessionContext>, +) -> Result<()> { let invalid = |message: String| Error::InvalidInput { message }; // A field with any declaration key is a declaration; a partial one is // not "no declaration", it is a broken one. @@ -1794,7 +1804,12 @@ pub(crate) fn ensure_declarations_are_planned(schema: &ArrowSchema) -> Result<() .filter(|f| f.name() != &column.name) .map(|f| f.as_ref().clone()) .collect(); - let bound = bind(Arc::new(ArrowSchema::new(others)), &column.name, expression)?; + let bound = bind( + Arc::new(ArrowSchema::new(others)), + &column.name, + expression, + session, + )?; if let Some(input) = bound.roots.iter().find(|r| declared.contains(*r)) { return Err(invalid(format!( "computed column '{}' reads computed column '{input}'", @@ -1944,6 +1959,17 @@ pub(crate) struct BoundExpression { pub blob_paths: Vec, /// A directly projected Blob v2 field whose semantics the output inherits. projected_blob_field: Option, + /// Field metadata of the expression's return field, e.g. a function's + /// logical type. + return_metadata: HashMap, +} + +/// Plans against `session`'s functions when given, else Lance's defaults. +fn session_planner(schema: SchemaRef, session: Option<&SessionContext>) -> Planner { + match session { + Some(session) => Planner::new_with_session(schema, session.clone()), + None => Planner::new(schema), + } } fn is_direct_field_projection(expr: &Expr) -> bool { @@ -2089,7 +2115,12 @@ fn referenced_blob_paths(schema: &ArrowSchema, inputs: &[String]) -> Result 0`), /// and the guard protecting the stored SQL has to see every column the text /// names, not just the ones the simplified form still reads. -pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result { +pub(crate) fn bind( + schema: SchemaRef, + column: &str, + expression: &str, + session: Option<&SessionContext>, +) -> Result { let invalid = |message: String| Error::InvalidExpression { column: column.to_string(), message, @@ -2102,7 +2133,7 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result< .into_iter() .collect::>(); let parsing_schema = blob_runtime_schema(schema.as_ref(), &all_blob_paths); - let planner = Planner::new(parsing_schema); + let planner = session_planner(parsing_schema, session); let parsed = planner .parse_expr(expression) .map_err(|e| invalid(e.to_string()))?; @@ -2171,22 +2202,22 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result< .map(|field| field.name().clone()) .collect(); - let runtime_planner = Planner::new(runtime_schema); + let runtime_planner = session_planner(runtime_schema, session); let optimized = runtime_planner .optimize_expr(parsed) .map_err(|e| invalid(e.to_string()))?; - let physical = Planner::new(read_schema.clone()) + let physical = session_planner(read_schema.clone(), session) .create_physical_expr(&optimized) .map_err(|e| invalid(e.to_string()))?; - let data_type = physical - .data_type(read_schema.as_ref()) + let return_field = physical + .return_field(read_schema.as_ref()) .map_err(|e| invalid(e.to_string()))?; Ok(BoundExpression { inputs, roots, physical, - data_type, + data_type: return_field.data_type().clone(), blob_paths: blob_paths .iter() .map(|path| { @@ -2195,6 +2226,7 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result< }) .collect(), projected_blob_field, + return_metadata: return_field.metadata().clone(), }) } @@ -2210,7 +2242,11 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result< /// batch may declare `a` and then `b = a + 1` in one commit. Refresh order /// then matters, and refresh enforces it: `b` is refused while `a` still has /// unfilled rows. -fn plan_declarations(schema: SchemaRef, columns: &[(String, String)]) -> Result> { +fn plan_declarations( + schema: SchemaRef, + columns: &[(String, String)], + session: Option<&SessionContext>, +) -> Result> { if columns.is_empty() { return Err(Error::InvalidInput { message: "at least one computed column is required".into(), @@ -2225,23 +2261,22 @@ fn plan_declarations(schema: SchemaRef, columns: &[(String, String)]) -> Result< return Err(Error::ColumnAlreadyExists { name: name.clone() }); } - let bound = bind(schema.clone(), name, expression)?; + let bound = bind(schema.clone(), name, expression, session)?; // Declared columns start entirely null, so nullability is a property // of the declaration rather than of what the expression yields. let computed_metadata = computed_column_metadata(expression, &bound.inputs); - let field = match bound.projected_blob_field { - Some(source) => { - let mut metadata = source.metadata().clone(); - metadata.retain(|key, _| !is_declaration_key(key)); - metadata.extend(computed_metadata); - source - .with_name(name) - .with_nullable(true) - .with_metadata(metadata) + let projected = match bound.projected_blob_field { + Some(source) => source.with_name(name), + None => { + ArrowField::new(name, bound.data_type, true).with_metadata(bound.return_metadata) } - None => ArrowField::new(name, bound.data_type, true).with_metadata(computed_metadata), }; + // Keep the source's descriptive metadata, not its schema declarations. + let projected = without_declarations(&projected); + let mut metadata = projected.metadata().clone(); + metadata.extend(computed_metadata); + let field = projected.with_nullable(true).with_metadata(metadata); schema = Arc::new(ArrowSchema::new_with_metadata( schema .fields() @@ -2257,8 +2292,12 @@ fn plan_declarations(schema: SchemaRef, columns: &[(String, String)]) -> Result< Ok(fields) } -pub(crate) fn plan(schema: SchemaRef, columns: &[(String, String)]) -> Result> { - plan_declarations(schema, columns) +pub(crate) fn plan( + schema: SchemaRef, + columns: &[(String, String)], + session: Option<&SessionContext>, +) -> Result> { + plan_declarations(schema, columns, session) } /// Run the schema-level checks of @@ -2267,6 +2306,11 @@ pub(crate) fn plan(schema: SchemaRef, columns: &[(String, String)]) -> Result Result Result<()> { +pub fn validate_declarations( + schema: SchemaRef, + columns: &[(String, String)], + session: Option<&SessionContext>, +) -> Result<()> { ensure_not_function_bound( schema.as_ref(), "schema evolution", columns.iter().map(|(name, _)| name), )?; - plan(schema, columns).map(drop) + plan(schema, columns, session).map(drop) } /// Build the transform that declares `columns` against `schema`. @@ -2302,8 +2350,9 @@ pub fn validate_declarations(schema: SchemaRef, columns: &[(String, String)]) -> pub(crate) fn declare( schema: SchemaRef, columns: &[(String, String)], + session: Option<&SessionContext>, ) -> Result { - let fields = plan_declarations(schema, columns)?; + let fields = plan_declarations(schema, columns, session)?; Ok(NewColumnTransform::AllNulls(Arc::new(ArrowSchema::new( fields, )))) @@ -2334,9 +2383,10 @@ pub(super) async fn add_foreign_kind(table: &crate::Table, name: &str, kind: &st /// created. pub(crate) fn admit_create_source( batches: S, + session: Option<&SessionContext>, ) -> Result> { let schema = batches.arrow_schema(); - ensure_declarations_are_planned(&schema)?; + ensure_declarations_are_planned(&schema, session)?; let declared = computed_columns(&schema) .into_iter() .map(|c| c.name) @@ -2496,7 +2546,7 @@ mod tests { )]), )); let declarations = vec![("a".to_string(), "x + 1".to_string())]; - assert!(super::validate_declarations(schema, &declarations).is_err()); + assert!(super::validate_declarations(schema, &declarations, None).is_err()); } #[test] @@ -2588,7 +2638,7 @@ mod tests { } } - use arrow_array::record_batch; + use arrow_array::{RecordBatch, record_batch}; use arrow_schema::{DataType, TimeUnit}; use futures::TryStreamExt; use lance::dataset::ColumnAlteration; @@ -2618,6 +2668,137 @@ mod tests { computed_columns(table.schema().await.unwrap().as_ref()) } + /// Echoes an Int32 and tags its return field, like a function with a + /// logical type. + #[derive(Debug, PartialEq, Eq, Hash)] + struct Tagged(datafusion_expr::Signature); + + impl datafusion_expr::ScalarUDFImpl for Tagged { + fn name(&self) -> &str { + "tagged" + } + + fn signature(&self) -> &datafusion_expr::Signature { + &self.0 + } + + fn return_type(&self, _: &[DataType]) -> datafusion_common::Result { + Ok(DataType::Int32) + } + + fn return_field_from_args( + &self, + _: datafusion_expr::ReturnFieldArgs, + ) -> datafusion_common::Result { + Ok(Arc::new( + ArrowField::new("tagged", DataType::Int32, true) + .with_metadata(HashMap::from([("tag".into(), "yes".into())])), + )) + } + + fn invoke_with_args( + &self, + args: datafusion_expr::ScalarFunctionArgs, + ) -> datafusion_common::Result { + Ok(args.args[0].clone()) + } + } + + #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] + async fn test_declarations_plan_against_the_session_functions() { + let functions = SessionContext::new(); + functions.register_udf(datafusion_expr::ScalarUDF::new_from_impl(Tagged( + datafusion_expr::Signature::exact( + vec![DataType::Int32], + datafusion_expr::Volatility::Immutable, + ), + ))); + let session = + Arc::new(lance::session::Session::default().with_datafusion_session(functions)); + let conn = connect("memory://") + .session(session) + .execute() + .await + .unwrap(); + let batch = record_batch!(("x", Int32, [1, 2, 3]), ("y", Int32, [4, 5, 6])).unwrap(); + let table = conn + .create_table("session_functions", batch) + .execute() + .await + .unwrap(); + + add_computed(&table, &[("t".into(), "tagged(x)".into())]) + .await + .unwrap(); + let schema = table.schema().await.unwrap(); + assert_eq!( + schema.field_with_name("t").unwrap().metadata().get("tag"), + Some(&"yes".to_string()) + ); + table.refresh_column("t").await.unwrap(); + // Dropping a column re-plans every declaration on the table. + table.drop_columns(&["y"]).await.unwrap(); + + let batches = table + .query() + .select(Select::columns(&["t"])) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let expected = record_batch!(("t", Int32, [1, 2, 3])).unwrap(); + assert_eq!(batches[0].column(0).as_ref(), expected.column(0).as_ref()); + + let plain = table_with_ints("no_session").await; + let err = add_computed(&plain, &[("t".into(), "tagged(x)".into())]) + .await + .unwrap_err(); + assert!(err.to_string().contains("tagged"), "{err}"); + } + + /// A projection keeps its source's descriptive metadata, not its schema + /// declarations: a copy of the primary key is not a primary key. + #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] + async fn test_projecting_the_primary_key_drops_its_declaration() { + let conn = connect("memory://").execute().await.unwrap(); + let ints = record_batch!(("x", Int32, [1, 2, 3])).unwrap(); + let schema = ArrowSchema::new(vec![ + ArrowField::new("x", DataType::Int32, false) + .with_metadata(HashMap::from([("note".into(), "kept".into())])), + ]); + let batch = RecordBatch::try_new(Arc::new(schema), ints.columns().to_vec()).unwrap(); + let table = conn + .create_table("key_projection", batch) + .execute() + .await + .unwrap(); + table.set_unenforced_primary_key(["x"]).await.unwrap(); + + add_computed(&table, &[("copy".into(), "x".into())]) + .await + .unwrap(); + let schema = table.schema().await.unwrap(); + let copy = schema.field_with_name("copy").unwrap(); + assert!( + !copy + .metadata() + .keys() + .any(|key| key.starts_with("lance-schema:")), + "{copy:?}" + ); + assert_eq!(copy.metadata().get("note"), Some(&"kept".to_string())); + } + #[tokio::test] #[cfg_attr( not(feature = "experimental-functions"), @@ -2658,6 +2839,7 @@ mod tests { ("first".to_string(), "image".to_string()), ("second".to_string(), "first".to_string()), ], + None, ) .unwrap(); @@ -2680,6 +2862,7 @@ mod tests { let fields = plan( schema, &[("payload".to_string(), "coalesce(image, image)".to_string())], + None, ) .unwrap(); @@ -2914,7 +3097,8 @@ mod tests { assert!( validate_declarations( table.schema().await.unwrap(), - &[("e".into(), "random()".into())] + &[("e".into(), "random()".into())], + None, ) .is_err() ); @@ -4803,7 +4987,7 @@ mod tests { let schema = declare_plan(&schema, &downstream, "fb_downstream"); ensure_supported_function_metadata(&schema).unwrap(); - ensure_declarations_are_planned(&schema).unwrap(); + ensure_declarations_are_planned(&schema, None).unwrap(); let bindings = function_bindings(&schema).unwrap(); assert!( computed_function_inputs(&schema, &bindings[0]) @@ -4868,7 +5052,7 @@ mod tests { let base = ArrowSchema::new(vec![ArrowField::new("x", DataType::Int32, true)]); let mut fields = base.fields().to_vec(); fields.extend( - plan(Arc::new(base), &[("doubled".into(), "x * 2".into())]) + plan(Arc::new(base), &[("doubled".into(), "x * 2".into())], None) .unwrap() .into_iter() .map(Arc::new), @@ -4887,7 +5071,7 @@ mod tests { .is_none_or(|metadata| !metadata.keys().any(|key| is_declaration_key(key))) ); let schema = Arc::new(declare_plan(&schema, &downstream, "fb_downstream")); - ensure_declarations_are_planned(&schema).unwrap(); + ensure_declarations_are_planned(&schema, None).unwrap(); let batch = RecordBatch::try_new( schema, vec![ diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index a8ae3c286..3c8ded1cf 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -308,6 +308,7 @@ async fn execute_refresh_column_with_source( schema.clone(), column, &expression, + dataset.session().datafusion_session(), )?); ensure_inputs_filled(&dataset, &schema, column, &bound).await?; let field = dataset @@ -490,7 +491,12 @@ async fn ensure_inputs_filled( ), }); }; - let input_bound = super::computed_columns::bind(schema.clone(), input, expression)?; + let input_bound = super::computed_columns::bind( + schema.clone(), + input, + expression, + dataset.session().datafusion_session(), + )?; let mut unfilled = 0u64; for fragment in dataset.get_fragments() { unfilled += count_fragment_gains(dataset, &fragment, &input_bound, input) diff --git a/rust/lancedb/src/table/schema_evolution.rs b/rust/lancedb/src/table/schema_evolution.rs index db4d6b91f..ab872c7fc 100644 --- a/rust/lancedb/src/table/schema_evolution.rs +++ b/rust/lancedb/src/table/schema_evolution.rs @@ -166,7 +166,9 @@ pub(crate) async fn execute_declare( .into(), }); } - let transform = computed_columns::declare(table.schema().await?, columns)?; + let session = table.dataset.get().await?.session(); + let transform = + computed_columns::declare(table.schema().await?, columns, session.datafusion_session())?; let NewColumnTransform::AllNulls(schema) = transform else { unreachable!("declarations are all-null") }; @@ -307,7 +309,11 @@ pub(crate) async fn execute_alter_columns( .filter(|alteration| alteration.rename.is_some() || alteration.data_type.is_some()) .map(|alteration| alteration.path.as_str()) .collect::>(); - computed_columns::ensure_not_an_input(&schema, &rebinding)?; + computed_columns::ensure_not_an_input( + &schema, + &rebinding, + dataset.session().datafusion_session(), + )?; let retyped = alterations .iter() .filter(|alteration| alteration.data_type.is_some()) @@ -344,7 +350,12 @@ pub(crate) async fn execute_drop_columns( let dropped = names.iter().map(String::as_str).collect::>(); ensure_not_embedding_column(&schema, "drop", dropped.iter().copied())?; computed_columns::ensure_not_bound_by(&unbinding.retained, "schema evolution", &dropped)?; - computed_columns::ensure_not_an_input_of(&schema, &dropped, &dropped)?; + computed_columns::ensure_not_an_input_of( + &schema, + &dropped, + &dropped, + dataset.session().datafusion_session(), + )?; if !unbinding.is_noop() { // The retirement commits before the projection, so the whole From 13e4cf7e58f78779b07919862a593ccd3098c1de Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Tue, 10 Nov 2026 15:22:56 +0800 Subject: [PATCH 3/5] feat: expose Function publication intervals in refresh options (#4928) Python refresh APIs currently reject `publication_interval_rows`, so callers cannot request incremental Function output publication through the SDK. Add the optional typed parameter through the sync/async Python APIs, PyO3, and Rust `RefreshColumnOptions`, and serialize it as a top-level Enterprise refresh option. An omitted value preserves the existing wire request and whole-fragment default. Positive values set a publication threshold; zero and negative Python values fail before a request is sent. Embedded refreshes reject the Enterprise-only option. Documentation describes a threshold rather than an exact number of rows per publication. Validation on the designated development host: - A matching baseline build reproduced the missing public keyword argument in both sync and async submission tests. - The updated PyO3 build passed 54 focused Python tests; Rust payload, invalid-option, and default-wire tests each passed. Rust formatting and Python Ruff checks passed. - The single signed delivery commit differs from that tested implementation only in a Rustdoc correction describing Embedded rejection; formatting passed again. No dependency pins or lockfiles changed. The matching SDK is prepared for the separate server validation of failure/cancellation retention and missing-only refill. Those end-to-end results are still pending and are not implied by these SDK tests. Refs [ENT-3733](https://linear.app/lancedb/issue/ENT-3733). --- .../feature-engineering/refresh-column.mdx | 32 +++++++++++++++++ python/python/lancedb/_lancedb.pyi | 2 ++ python/python/lancedb/remote/table.py | 4 +++ python/python/lancedb/table.py | 34 +++++++++++++++++++ python/python/tests/test_remote_db.py | 4 +++ python/python/tests/test_table.py | 1 + python/src/table.rs | 12 +++++-- rust/lancedb/src/remote/table.rs | 6 ++++ rust/lancedb/src/table.rs | 14 ++++++-- rust/lancedb/src/table/refresh.rs | 24 +++++++++++++ 10 files changed, 128 insertions(+), 5 deletions(-) diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index ac4ff93fe..0dfe3b33d 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -261,6 +261,38 @@ release. TypeScript does not expose GPU class discovery; pass `gpuClass` and `gpuCount` in the `refreshColumnAsync` options. +Completed Function outputs publish with their fragment by default. To opt into +a row-count publication threshold, set `publication_interval_rows` in Python or +`publication_interval_rows()` in Rust: + + +```python Python icon="python" +job = table.refresh_column_async( + "embedding", + publication_interval_rows=60, +) +job.wait() +``` + +```rust Rust icon="rust" +use lancedb::table::RefreshColumnOptions; + +let _job = table + .refresh_column_async_with_options( + "embedding", + RefreshColumnOptions::default().publication_interval_rows(60), + ) + .await?; +``` + + +The threshold is opt-in and must be greater than zero. The number of rows in an +individual publication can differ from this value depending on completed work +and Function batching; this is not an exact-N contract. Omit it to keep +whole-fragment publication. + +The TypeScript SDK does not expose the publication threshold option yet. + The job APIs also take the row filter and failure handling of the SQL `REFRESH COLUMN ... WHERE ... WITH (...)` form, so a refresh can be narrowed to new rows (see [what a filter recomputes](#partial)) and told to skip rows diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 2ac4dde58..f2d5285fa 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -619,6 +619,7 @@ class Table: *, where: Optional[str] = None, batch_size: Optional[int] = None, + publication_interval_rows: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[str] = None, @@ -636,6 +637,7 @@ class Table: *, where: Optional[str] = None, batch_size: Optional[int] = None, + publication_interval_rows: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[str] = None, diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 8f1f741fb..a963ab55e 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -1143,6 +1143,7 @@ class RemoteTable(Table): *, where: Optional[str] = None, batch_size: Optional[int] = None, + publication_interval_rows: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -1159,6 +1160,7 @@ class RemoteTable(Table): column, where=where, batch_size=batch_size, + publication_interval_rows=publication_interval_rows, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=retry_policy, @@ -1178,6 +1180,7 @@ class RemoteTable(Table): *, where: Optional[str] = None, batch_size: Optional[int] = None, + publication_interval_rows: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -1195,6 +1198,7 @@ class RemoteTable(Table): column, where=where, batch_size=batch_size, + publication_interval_rows=publication_interval_rows, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=retry_policy, diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 75975a2c3..06bace5b8 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -3178,6 +3178,7 @@ class Table(ABC): *, where: Optional[str] = None, batch_size: Optional[int] = None, + publication_interval_rows: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -3216,6 +3217,12 @@ class Table(ABC): Maximum rows per Function call on the remote server. Must be greater than zero. None uses the server default. Has no effect on local expression-backed columns. + publication_interval_rows: int, optional + Opt-in publication threshold for completed Function outputs. Must + be greater than zero. None keeps whole-fragment publication. The + actual publication boundary can be larger than this threshold + because it also depends on completed work and Function batching. + LanceDB Enterprise only; local refreshes reject this option. gpu_class: str, optional GPU class for Function workers. Must be a lowercase name of 1-63 letters, digits, or hyphens, without a leading or trailing hyphen. @@ -3263,6 +3270,7 @@ class Table(ABC): *, where: Optional[str] = None, batch_size: Optional[int] = None, + publication_interval_rows: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -3300,6 +3308,12 @@ class Table(ABC): greater than zero. None uses the server default. Lower this for slow Functions to stay within the executor's per-call deadline. Has no effect on local expression-backed columns. + publication_interval_rows: int, optional + Opt-in publication threshold for completed Function outputs. Must + be greater than zero. None keeps whole-fragment publication. The + actual publication boundary can be larger than this threshold + because it also depends on completed work and Function batching. + LanceDB Enterprise only; local refreshes reject this option. gpu_class: str, optional GPU class for Function workers. Must be a lowercase name of 1-63 letters, digits, or hyphens, without a leading or trailing hyphen. @@ -5442,6 +5456,7 @@ class LanceTable(Table): *, where: Optional[str] = None, batch_size: Optional[int] = None, + publication_interval_rows: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -5461,6 +5476,7 @@ class LanceTable(Table): column, where=where, batch_size=batch_size, + publication_interval_rows=publication_interval_rows, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=retry_policy, @@ -5480,6 +5496,7 @@ class LanceTable(Table): *, where: Optional[str] = None, batch_size: Optional[int] = None, + publication_interval_rows: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -5501,6 +5518,7 @@ class LanceTable(Table): column, where=where, batch_size=batch_size, + publication_interval_rows=publication_interval_rows, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=retry_policy, @@ -7865,6 +7883,7 @@ class AsyncTable: *, where: Optional[str] = None, batch_size: Optional[int] = None, + publication_interval_rows: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -7903,6 +7922,12 @@ class AsyncTable: Maximum rows per Function call on the remote server. Must be greater than zero. None uses the server default. Has no effect on local expression-backed columns. + publication_interval_rows: int, optional + Opt-in publication threshold for completed Function outputs. Must + be greater than zero. None keeps whole-fragment publication. The + actual publication boundary can be larger than this threshold + because it also depends on completed work and Function batching. + LanceDB Enterprise only; local refreshes reject this option. gpu_class: str, optional GPU class for Function workers. Must be a lowercase name of 1-63 letters, digits, or hyphens, without a leading or trailing hyphen. @@ -7945,6 +7970,7 @@ class AsyncTable: column, where=where, batch_size=batch_size, + publication_interval_rows=publication_interval_rows, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=None @@ -8054,6 +8080,7 @@ class AsyncTable: *, where: Optional[str] = None, batch_size: Optional[int] = None, + publication_interval_rows: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -8091,6 +8118,12 @@ class AsyncTable: greater than zero. None uses the server default. Lower this for slow Functions to stay within the executor's per-call deadline. Has no effect on local expression-backed columns. + publication_interval_rows: int, optional + Opt-in publication threshold for completed Function outputs. Must + be greater than zero. None keeps whole-fragment publication. The + actual publication boundary can be larger than this threshold + because it also depends on completed work and Function batching. + LanceDB Enterprise only; local refreshes reject this option. gpu_class: str, optional GPU class for Function workers. Must be a lowercase name of 1-63 letters, digits, or hyphens, without a leading or trailing hyphen. @@ -8150,6 +8183,7 @@ class AsyncTable: column, where=where, batch_size=batch_size, + publication_interval_rows=publication_interval_rows, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=None diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 685bc809d..671d0ff23 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -1863,6 +1863,7 @@ def test_remote_create_index_async_returns_job(): {"batch_size": None}, {"batch_size": 1}, {"batch_size": 8}, + {"publication_interval_rows": 60}, {"gpu_class": "a10g", "gpu_count": 2}, { "retry_policy": {"transient": True, "max_attempts": 3}, @@ -1911,6 +1912,7 @@ async def test_remote_refresh_async_returns_typed_terminal_result( expected["error_policy"] = refresh_kwargs["error_policy"] for key in ( "where", + "publication_interval_rows", "max_failed_fraction", "max_failed_rows", "row_timeout_seconds", @@ -2088,6 +2090,8 @@ def test_remote_refresh_async_forwards_progress_from_submitted_handle(): ({"max_failed_rows": -1}, "max_failed_rows"), ({"row_timeout_seconds": 0}, "row_timeout_seconds"), ({"init_timeout_seconds": -5}, "init_timeout_seconds"), + ({"publication_interval_rows": 0}, "publication_interval_rows"), + ({"publication_interval_rows": -1}, "publication_interval_rows"), ({"num_workers": 0}, "num_workers"), ( {"max_executor_processes_per_worker": -2}, diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 2a502fe62..157870bb5 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -5995,6 +5995,7 @@ def test_refresh_column_rejects_invalid_batch_size(tmp_path, method, batch_size) ({"max_failed_rows": 10}, "max_failed_rows"), ({"row_timeout_seconds": 30}, "row_timeout_seconds"), ({"init_timeout_seconds": 60}, "init_timeout_seconds"), + ({"publication_interval_rows": 60}, "publication_interval_rows"), ({"num_workers": 2}, "num_workers"), ({"max_executor_processes_per_worker": 2}, "max_executor_processes_per_worker"), ], diff --git a/python/src/table.rs b/python/src/table.rs index 92a6ef835..23c5b69d7 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -46,6 +46,7 @@ mod scannable; struct RefreshColumnArgs { where_clause: Option, batch_size: Option, + publication_interval_rows: Option, gpu_class: Option, gpu_count: Option, retry_policy: Option, @@ -73,6 +74,7 @@ fn refresh_column_options(args: RefreshColumnArgs) -> PyResult PyResult, column: String, r#where: Option, batch_size: Option, + publication_interval_rows: Option, gpu_class: Option, gpu_count: Option, retry_policy: Option, @@ -2227,6 +2232,7 @@ impl Table { let options = refresh_column_options(RefreshColumnArgs { where_clause: r#where, batch_size, + publication_interval_rows, gpu_class, gpu_count, retry_policy, @@ -2248,13 +2254,14 @@ impl Table { }) } - #[pyo3(signature = (column, *, r#where=None, batch_size=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))] + #[pyo3(signature = (column, *, r#where=None, batch_size=None, publication_interval_rows=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))] #[allow(clippy::too_many_arguments)] pub fn refresh_column_async( self_: PyRef<'_, Self>, column: String, r#where: Option, batch_size: Option, + publication_interval_rows: Option, gpu_class: Option, gpu_count: Option, retry_policy: Option, @@ -2269,6 +2276,7 @@ impl Table { let options = refresh_column_options(RefreshColumnArgs { where_clause: r#where, batch_size, + publication_interval_rows, gpu_class, gpu_count, retry_policy, diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 6956905c4..a69611306 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -11072,6 +11072,7 @@ mod tests { serde_json::json!({ "column": "quality", "where": "id % 2 = 0", + "publication_interval_rows": 60, "error_policy": "skip", "max_failed_fraction": 0.01, "max_failed_rows": 50, @@ -11088,6 +11089,7 @@ mod tests { }); let options = RefreshColumnOptions::default() .where_clause("id % 2 = 0") + .publication_interval_rows(60) .error_policy(FunctionErrorPolicy::Skip) .max_failed_fraction(0.01) .max_failed_rows(50) @@ -11135,6 +11137,10 @@ mod tests { RefreshColumnOptions::default().max_executor_processes_per_worker(0), "max_executor_processes_per_worker", ), + ( + RefreshColumnOptions::default().publication_interval_rows(0), + "publication_interval_rows", + ), ] { let error = table .refresh_column_async_with_options("quality", options) diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index a58567b2e..80b6bd7ad 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -2141,10 +2141,14 @@ impl Table { /// /// [`RefreshColumnOptions::batch_size()`] caps rows per Function call in /// LanceDB Enterprise and must be greater than zero when set. + /// [`RefreshColumnOptions::publication_interval_rows()`] sets an opt-in + /// row-count publication threshold for completed Function outputs; unset + /// keeps whole-fragment publication. /// [`RefreshColumnOptions::gpu_class()`] selects a GPU pool and /// [`RefreshColumnOptions::gpu_count()`] sets the aggregate GPU budget. - /// These options have no effect on expression-backed columns in LanceDB - /// Embedded. Remote refreshes require + /// Batch-size and GPU options have no effect on expression-backed columns + /// in LanceDB Embedded; a publication threshold is rejected there. + /// Remote refreshes require /// [`Table::refresh_column_async_with_options`]. /// /// ``` @@ -2201,12 +2205,16 @@ impl Table { /// Set [`RefreshColumnOptions::batch_size()`] to cap the rows each remote /// Function call receives, for example to keep slow Functions within the /// executor's per-call deadline. Set + /// [`RefreshColumnOptions::publication_interval_rows()`] to publish + /// completed Function outputs at a row-count threshold; unset keeps + /// whole-fragment publication. Set /// [`RefreshColumnOptions::gpu_class()`] and /// [`RefreshColumnOptions::gpu_count()`] to override the registered GPU /// class or set an aggregate GPU budget for Function workers. Unset values /// use the Function and server defaults; zero counts and malformed class /// names are rejected before submitting a job. Embedded expression - /// refreshes ignore all three options. + /// refreshes ignore the batch-size and GPU options, and reject publication + /// thresholds and other Enterprise-only options. /// /// ``` /// # use lancedb::{Table, table::RefreshColumnOptions}; diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index 3c8ded1cf..a8be34b17 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -100,6 +100,14 @@ pub struct RefreshColumnOptions { /// effect on expression-backed columns in LanceDB Embedded. #[serde(skip_serializing_if = "Option::is_none")] pub batch_size: Option, + /// Opt-in row-count threshold for publishing completed Function outputs. + /// + /// Must be greater than zero. `None` keeps whole-fragment publication. + /// Actual publication boundaries can be larger than this threshold because + /// they also depend on completed work and Function batching. LanceDB Embedded + /// rejects this option. + #[serde(skip_serializing_if = "Option::is_none")] + pub publication_interval_rows: Option, /// GPU class for Function workers in LanceDB Enterprise. /// /// `None` keeps the Function's registered class, or the deployment default @@ -174,6 +182,13 @@ impl RefreshColumnOptions { self } + /// Use `rows` as the opt-in publication threshold for completed Function + /// outputs. The actual publication boundary can be larger than this value. + pub fn publication_interval_rows(mut self, rows: u64) -> Self { + self.publication_interval_rows = Some(rows); + self + } + /// Request Function workers from `gpu_class`. pub fn gpu_class(mut self, gpu_class: impl Into) -> Self { self.gpu_class = Some(gpu_class.into()); @@ -201,6 +216,10 @@ impl RefreshColumnOptions { "max_executor_processes_per_worker", self.max_executor_processes_per_worker.is_some(), ), + ( + "publication_interval_rows", + self.publication_interval_rows.is_some(), + ), ] .into_iter() .find_map(|(name, set)| set.then_some(name)) @@ -253,6 +272,11 @@ impl RefreshColumnOptions { message: "batch_size must be greater than zero".into(), }); } + if self.publication_interval_rows == Some(0) { + return Err(Error::InvalidInput { + message: "publication_interval_rows must be greater than zero".into(), + }); + } if let Some(gpu_class) = &self.gpu_class { validate_gpu_class_name(gpu_class)?; } From e928e374d0ba8b7a813f709796ee7ae69365de54 Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Tue, 10 Nov 2026 00:25:41 -0800 Subject: [PATCH 4/5] chore: update lance dependency to v15.0.0-beta.16 (#4935) Update the Rust workspace, Java lance-core, and Python test dependency to [Lance v15.0.0-beta.16](https://github.com/lance-format/lance/releases/tag/v15.0.0-beta.16). Synchronize `python/uv.lock` with the published beta.16 wheels for Linux, macOS, and Windows. Run the native Linux x64 wheel build on an eight-core runner, matching the existing ARM build allocation, after its optimized build repeatedly exceeded the job deadline on the standard runner. The dependency update passed Clippy, formatting, and CI-script checks; the Python lockfile refresh/check passes. Fresh CI is running for the runner adjustment. Java dependency-resolution failures caused solely by publication lag are accepted for this upgrade. --------- Co-authored-by: Jack Ye --- .github/workflows/pypi-publish.yml | 2 +- Cargo.lock | 96 +++++++++++++++--------------- Cargo.toml | 30 +++++----- java/pom.xml | 2 +- python/pyproject.toml | 2 +- python/uv.lock | 14 ++--- 6 files changed, 73 insertions(+), 73 deletions(-) diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml index b2db765d0..5aea2ca30 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -44,7 +44,7 @@ jobs: - platform: x86_64 manylinux: "2_28" extra_args: "--features fp16kernels" - runner: ubuntu-22.04 + runner: ubuntu-2404-8x-x64 package_name: "lancedb" rustflags: "" # For successful fat LTO builds, we need a large runner to avoid OOM errors. diff --git a/Cargo.lock b/Cargo.lock index 893fb21d6..ad42d60b0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3765,8 +3765,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5243,8 +5243,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arc-swap", "arrow", @@ -5319,8 +5319,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "arrow-buffer", @@ -5342,7 +5342,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "arrow-buffer", @@ -5356,7 +5356,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "arrow-schema", @@ -5365,8 +5365,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrayref", "crunchy", @@ -5376,8 +5376,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "arrow-buffer", @@ -5415,8 +5415,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow", "arrow-array", @@ -5447,8 +5447,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow", "arrow-array", @@ -5473,8 +5473,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow", "arrow-array", @@ -5491,8 +5491,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "proc-macro2", "quote", @@ -5501,8 +5501,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-arith", "arrow-array", @@ -5535,8 +5535,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-arith", "arrow-array", @@ -5567,8 +5567,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "arrow-schema", @@ -5599,8 +5599,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arc-swap", "arrow", @@ -5671,8 +5671,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "arrow-schema", @@ -5695,8 +5695,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow", "arrow-array", @@ -5741,8 +5741,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "byteorder", "ethnum", @@ -5759,8 +5759,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5775,8 +5775,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow", "async-trait", @@ -5790,8 +5790,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arc-swap", "arrow", @@ -5845,8 +5845,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "arrow-buffer", @@ -5860,8 +5860,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow", "arrow-array", @@ -5902,8 +5902,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "arrow-schema", @@ -5916,8 +5916,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index ab8e86f97..e77e0ffd6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,21 +19,21 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.15", default-features = false, "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.15", default-features = false, "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.15", default-features = false, "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.16", default-features = false, "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.16", default-features = false, "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.16", default-features = false, "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" diff --git a/java/pom.xml b/java/pom.xml index 88b66b3ad..4d1dccdb4 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.15 + 15.0.0-beta.16 2.18.12 false 2.30.0 diff --git a/python/pyproject.toml b/python/pyproject.toml index 153d138b4..036acf075 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow>=16", "pyarrow-stubs>=16.0", - "pylance==15.0.0b15", + "pylance==15.0.0b16", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/uv.lock b/python/uv.lock index 2cd4ac496..a5ae1caf8 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -2147,7 +2147,7 @@ requires-dist = [ { name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" }, { name = "pydantic", specifier = ">=2.7.4,<3" }, { name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" }, - { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b15" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b16" }, { name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" }, { name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" }, { name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" }, @@ -4301,7 +4301,7 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b15" +version = "15.0.0b16" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -4312,11 +4312,11 @@ dependencies = [ { name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_29HO58/pylance-15.0.0b15-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:46c870c3d650f911eccb7406ec77f72fa448f80b2f827ff35dd86bbc0b9e08ca" }, - { url = "https://pypi.fury.io/lance-format/-/ver_OBkXR/pylance-15.0.0b15-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b3f418584cdee98d27aac538ebe5203051a0b78a98668aff22bc29aebe3dd3c9" }, - { url = "https://pypi.fury.io/lance-format/-/ver_TMbLm/pylance-15.0.0b15-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3656d52ba65d297b41f1973d1a3efbb888f761cf7c934ff15e0c1aecc560b2d5" }, - { url = "https://pypi.fury.io/lance-format/-/ver_mmYmR/pylance-15.0.0b15-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:a50d06e3a86d68acf8edf5a83736890a648a16a1cb8c8ccde9ef5b6c82ebef76" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1aYiTc/pylance-15.0.0b15-cp310-abi3-win_amd64.whl", hash = "sha256:6451499f0612d0326d54168bedcc6df29c1e0700c4f92902f5f00a6ecdf17745" }, + { url = "https://pypi.fury.io/lance-format/-/ver_uZ4Az/pylance-15.0.0b16-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:c4ed0ab9213082d9d8cc93aa09351e84574c76ddefc422a2ad073115bd9a1b43" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1nenYa/pylance-15.0.0b16-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7f28f7b757ade1e4b556e788bc77d4ffcc351a9c8c570b35f769c457e9cc13bf" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1cb3ns/pylance-15.0.0b16-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:49f358f3ddf33d76567f56d0e4a66c218dc1a2d2f06d37d779e13c87b1c3d9a6" }, + { url = "https://pypi.fury.io/lance-format/-/ver_g7LAk/pylance-15.0.0b16-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:288c1b41f5068990672c8c182b4b79d6389c1a907c59ef6047cbee494d1e34ec" }, + { url = "https://pypi.fury.io/lance-format/-/ver_12YRtQ/pylance-15.0.0b16-cp310-abi3-win_amd64.whl", hash = "sha256:fa69acdd0960280f6fe8a83ea992fc92e2ed5a0eeb5159b90493dfc76831f752" }, ] [[package]] From 3851938b6e21c9ac6de534e78dadd12d9bed4013 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Tue, 10 Nov 2026 08:26:43 +0000 Subject: [PATCH 5/5] =?UTF-8?q?Bump=20version:=200.42.0-beta.9=20=E2=86=92?= =?UTF-8?q?=200.42.0-beta.10?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index bbf036dc8..992d126d0 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.9" +current_version = "0.42.0-beta.10" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index ad42d60b0..56642301c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5930,7 +5930,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.9" +version = "0.42.0-beta.10" dependencies = [ "ahash", "anyhow", @@ -6041,7 +6041,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.9" +version = "0.42.0-beta.10" dependencies = [ "anyhow", "arrow-array", @@ -6084,7 +6084,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.9" +version = "0.42.0-beta.10" dependencies = [ "arrow-array", "arrow-buffer", @@ -6109,7 +6109,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.9" +version = "0.42.0-beta.10" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 6b0ac9492..3d3a3f8e1 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.42.0-beta.9 + 0.42.0-beta.10 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index f915a6a64..758e41acd 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.9 + 0.42.0-beta.10 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 4d1dccdb4..2f72f98a7 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.9 + 0.42.0-beta.10 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index d8f16adb1..47fc92237 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.9" +version = "0.42.0-beta.10" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index f04147d46..3761d6f4f 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.42.0-beta.9", + "version": "0.42.0-beta.10", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index af781ae92..5b7a167d0 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.42.0-beta.9", + "version": "0.42.0-beta.10", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index c08a81137..e902929bf 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.42.0-beta.9", + "version": "0.42.0-beta.10", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index 624b22de3..a54f47de3 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.42.0-beta.9", + "version": "0.42.0-beta.10", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index d200c24c3..cc1894e70 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.42.0-beta.9", + "version": "0.42.0-beta.10", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index a0b3cfd48..d5e0309d0 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.42.0-beta.9", + "version": "0.42.0-beta.10", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 0544af0c7..5e9698e7f 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.42.0-beta.9", + "version": "0.42.0-beta.10", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index c2424cd55..5579e1c55 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.9", + "version": "0.42.0-beta.10", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 2c577766b..102b0f67b 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.9" +version = "0.42.0-beta.10" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 6f5d45232..783216243 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.9" +version = "0.42.0-beta.10" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 601d0f58b..051db741a 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.9" +version = "0.42.0-beta.10" edition = "2021" license.workspace = true repository.workspace = true