mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
75cd232c557bd14743b28f2d410c8ef281d6881f
806
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
75cd232c55 |
test(python): exercise mixed persistence at latest v2
Reopen the persisted plan by destination, advance the mock base to v2, and verify a fresh latest remote handle still reads through the plan's recorded main/v1 coordinates. Keep sequential and duplicate-offset checks on the stored plan order, and require nonempty scan/gather evidence before asserting request versions. |
||
|
|
42d85b172f |
test(python): cover embedded plans over enterprise bases
Clarify that persist writes only the plan to an embedded destination while the base table may be Enterprise. Add a loopback regression that persists a plan from a mock remote base, checks the recorded main/v1 snapshot requests, and verifies public sequential and duplicate-offset reads preserve order. |
||
|
|
49dedd4329 |
fix: expose Function metadata in SDK job listings (#5096)
Expose affected columns, pinned Function name/version, completion time,
duration and failure summaries on `JobInfo` in the Rust, Python and
TypeScript SDKs. Values come from the listing response, so callers can
inspect recent computed column refreshes without opening every job.
Older servers keep optional values absent; measured zero durations stay
zero.
```python
latest = next((info for info in db.list_jobs(table="events", job_type="function_refresh") if "embedding" in info.columns), None)
if latest is not None:
print(latest.function_name, latest.function_version, latest.duration_millis)
if latest.failure is not None:
print(latest.failure.message)
```
Duration is creation-to-completion wall time, including queueing and
pauses. Adds listing response coverage across SDKs and documents the
metadata contract, including SQL `SHOW JOBS EXTENDED` for the expanded
listing. Plain `SHOW JOBS` preserves its original columns. Local builds
and tests were skipped as requested.
The dependency advisory check also fails on current main because
`libsais-rs 0.2.0` is yanked ([main
job](https://github.com/lancedb/lancedb/actions/runs/44470513618/job/135378545456));
this PR does not change dependencies.
This changes the public shape of Rust and TypeScript `JobInfo`: callers
constructing summaries must supply the added fields (including
TypeScript `columns`). TypeScript table filtering remains a separate
concern; the guide now shows its client-side selection and namespace
limitation alongside Python and Rust server-side filters.
Refs ENT-3903.
|
||
|
|
b44807e4db |
fix!: preserve job attempt lineage, retries, and lifecycle states
BREAKING CHANGE: JobDescription, JobEventsRequest, FunctionErrorsRequest, and FunctionErrors gain optional Rust metadata/cursor fields. Existing struct literals must initialize them; use None when unavailable. Preserve typed attempt state, pinned retry lineage, result decoders and freshness fences, and retained diagnostic paging across SDKs. Keep Python job data access method-only. |
||
|
|
bfb55c72e9 |
feat(python)!: make job data access method-only (#5095)
Make all Python `Job` and `AsyncJob` data access method-only. Cached property accessors are private and underscore-prefixed; public reads use `id()`, `state()`, `job_type()`, `creation_ms()`, `spec()`, `result()` and `failure()`. `checkout_latest()` refreshes the complete cached registry record in place and returns `None`. ```python job.checkout_latest() print(job.state(), job.result(), job.failure()) print(job.id(), job.job_type(), job.creation_ms(), job.spec()) ``` Cached read methods are synchronous on both handle types. Async handles use `await job.checkout_latest()` for the live refresh; event history remains a separate request through `events()`. Update Python SDK callers, tests and guides to use method calls, including progress/timeout handling and bounded repr. Cover method-only visibility and holistic snapshot freshness through both sync and async clients. BREAKING CHANGE: Python job data access now requires method calls, such as `job.state()` instead of `job.state`. No property compatibility aliases remain. Fixes https://linear.app/lancedb/issue/ENT-3902/sdk-make-cached-versus-live-job-accessors-unambiguous |
||
|
|
8dc03bd288 |
feat: add table.delta for version-to-version row changes (#5135)
Adds native `Table::delta(from_version, to_version=None)` and Python
sync/async `table.delta(...)` for version-to-version row changes.
`TableDelta` exposes streaming `inserted_rows()`, `updated_rows()`,
`upserted_rows()`, `deleted_row_ids()`, and `list_transactions()`.
Endpoints are resolved once on independent dataset handles.
`to_version=None` uses the table handle's visible snapshot, and the
handle's checkout is not changed. Only versions `>= 1` and tags on the
current branch are accepted; cross-branch tags, reversed ranges, version
0, and missing endpoints are rejected. Equal valid endpoints return
empty readers with the same schemas.
Row-level readers require stable row ids at both endpoints and report
the `storage_options={"new_table_enable_stable_row_ids": "true"}`
creation guidance when they are absent. `list_transactions()` does not
require stable row ids.
Row-level readers also fail closed when the range contains a `Restore`,
or when transaction history cannot prove the range is restore-free,
because restored rows can retain older row-version metadata that the
delta readers omit. The error directs consumers to a full rescan and
reinitializing the checkpoint at the range end version.
`list_transactions()` remains available for readable history. The
Versioning guide includes Python and Rust checkpoint-delta examples with
stable-row-ID setup and this Embedded limitation.
Embedded `branches.diff()` remains a separate API.
Refs OSS-2860
|
||
|
|
baea02eebd |
feat: add cleanup jobs and previews across SDKs (#5107)
LanceDB SDK users connected to Enterprise had no explicit API to submit durable cleanup or preview its work; Python's existing cleanup helper remained a warning-only no-op. This PR adds the SDK support for [ENT-2687](https://linear.app/lancedb/issue/ENT-2687) through public SQL and Job APIs. It requires a compatible Enterprise release supporting `VACUUM`, JSON preview and result format version 1. Existing cleanup/optimize helpers retain their behavior; the new APIs reject Embedded and historical-version handles. This was accomplished with the following changes: - Add `cleanup_async()` / `cleanupAsync()` and `explain_cleanup()` / `explainCleanup()` in Python sync/async, TypeScript and Rust. - Preserve the handle's namespace/branch and resolve retention as invocation → table/branch TTL → deployment default. Omission inherits, zero is explicit, and malformed options fail rather than being discarded. - Require one nonempty durable SQL receipt, preserving diagnostics without REST fallback, query-ID substitution or automatic resubmission after ambiguous acceptance. - Add versioned `CleanupPlan` estimates and `CleanupResult` measurements. Preview creates no cleanup job or reservation; results preserve known zero, unknown retry/recovery totals and nonfatal failed deletes, excluding auxiliary sweeps. - Retain typed results on reopening and reuse shared status/progress/events/wait/cancel APIs. Timeout leaves work running; cancellation cannot undo deletion or prove storage I/O stopped. - Document Ownership/parent Usage and required coordination at every retention value: disable/drain automatic cleanup and prevent competing cleanup, tag creation/update, branch creation and restore across all clients until completion. The server does not enforce exclusion; concurrent restore can leave the current table unreadable. - Update Python's legacy no-op warning and the maintenance, Python, Rust and generated TypeScript references. | Interface | Submit with seven-day retention | | --- | --- | | SQL | `VACUUM events WITH (min_age_seconds = 604800);` | | CLI | `lancedb admin table cleanup --table events --min-age-seconds 604800 --wait` | | Python | `job = table.cleanup_async(min_age_seconds=604800)` (use `await` with AsyncTable) | | TypeScript | `const job = await table.cleanupAsync({ minAgeSeconds: 604800 });` | | Rust | `let job = table.cleanup_async(CleanupOptions::new().min_age_seconds(604800)).await?;` | ### Testing Added submission/preview, validation, typed-result and reopening tests, and updated the legacy no-op warning assertion. Focused Python cleanup/Job and compaction/prewarm regressions passed, alongside **34 TypeScript** and **46 Rust** tests. **31 end-to-end scenarios** passed against a real Enterprise server, covering CLI/SQL/REST/SDK submission, retention precedence, restart/reopening, timeouts, cancellation and branch/namespace isolation. Local native SDK validation used a separate `libsais-rs 0.2.0` lockfile because the registry could not resolve `0.2.4`; this PR retains main's dependency pins and lockfile. |
||
|
|
8fd1c716d9 |
feat(python): persist permutation plans and reopen pinned snapshots (#5137)
## Summary Add `permutation_builder(base).persist(db, table_name, *, namespace_path=None, mode="create").execute()` for embedded local and object-store destinations. The native create request carries the namespace and create/overwrite mode, with no drop-before-create. The returned table keeps the destination connection context so it can be pickled and reopened directly, including namespaced and manifest-enabled connections. Persisted plans pickle by reference to their own branch and version, so a later overwrite or cross-branch checkout does not change what an existing pickle reads. In-memory plans, old serialized state, and shallow copies keep their existing behavior. `Permutation.base_version` and `base_branch` expose the recorded base snapshot from loaded metadata. Enterprise destinations remain rejected in v1 because reproducible remote plan ordering is follow-up work. ## Verification - `test_permutation.py`: 93 passed. - `test_torch.py`: 23 passed in a compatible torch 2.15 / NumPy 2.2 / PyArrow 26 environment using the abi3 extension. - S3 direct-result persistence/pickle test passed against a disposable loopback Moto server using the existing fixture's fake keys and explicit storage options. - Earlier targeted checks predate the live snapshot pin repair: Rust builder tests 12 passed; Rust check/clippy and Node type-check passed. - The live snapshot pin repair added private PyO3 glue and was verified with a rebuilt extension: `test_permutation.py` 93 passed, `test_torch.py` 23 passed, and one loopback S3 direct-result test passed. - `ruff format --check`, `ruff check`, `pyright`, `git diff --check`: passed. |
||
|
|
8b8778938f |
perf(python): stream plain sync batches on demand (#5143)
## Problem Synchronous local `table.search().to_batches()` creates one Python future per batch through the background event loop. At the default 1024-row cap, a large scan pays that Python round trip thousands of times even though the Rust stream can produce the next batch immediately. ## Change Use a pull-driven synchronous reader for native, non-namespace, ordinary lazy plain scans. The query is executed once with the same `QueryExecutionOptions` as the async path: `None` keeps the 1024-row cap, `0` leaves sizing to the engine, and a positive value caps each returned batch. Each `__next__` releases the GIL, waits for exactly one batch from the same Rust stream through the reviewed `block_on_interruptible`, and stores the stream back on success. - No background producer and no Python `LOOP.run` per batch. - A read error, interrupt, EOF, or the last owner drops the stream. A normal early `break` can resume the same reader. - The public `pa.RecordBatchReader` still comes from `from_batches`, so the schema, Arrow capsule, and exception types stay unchanged. Existing PyArrow `close()` behavior is unchanged; the known PyArrow close issue is separately scoped. - Routing is limited to native, non-namespace, lazy plain scans. Vector, take, FTS/hybrid, remote, namespace, `to_arrow` direct eager routes, and Blob `bytes`/`descriptions` keep their existing paths. Take ordering from #5140 remains on the take path. - Forward explicit `scan_in_order` through the pull launch; base-only ordered `to_batches` results and the incompatible `order_by`/fragment behavior are included in the scan-order suite. - Adds a public RTE `to_batches` regression: the default LSM route sees pending memtable writes, while `use_rte(False)` remains base-only. ## Validation - `test_sync_pull_reader.py`, `test_merge_insert_lsm.py`, and `test_sync_query_direct.py`: 53 passed. - `test_query.py`, `test_blob.py`, and `test_blob_query_without_pylance.py`: 539 passed, 1 skipped. - `test_table.py`: 552 passed, 17 skipped. - `test_remote_db.py -k "to_batches or take"`: 16 passed. - `test_background_loop.py`: 4 passed. - Rust `cargo test --manifest-path python/Cargo.toml --lib sync_stream`: 5 passed. - `cargo check -j 1 --manifest-path python/Cargo.toml --lib --tests` passed; no full Rust doctests were run. A matched same-base release-with-debug streaming comparison is a follow-up and is not claimed here. Tracking: [OSS-2865](https://linear.app/lancedb/issue/OSS-2865) |
||
|
|
c55b7c0390 |
feat!: add explicit scan order contract for local queries (#5138)
BREAKING CHANGE: `QueryRequest` now has a public `scan_in_order: Option<bool>` field. Existing code that constructs `QueryRequest` with an exhaustive struct literal must add `scan_in_order: None` to retain the previous backend default, or use `..Default::default()` where appropriate. Python defaults are unchanged: leaving `scan_in_order()` uncalled keeps `None`. ## Problem Plain Embedded LanceDB scans already use Lance's ordered scan on a fixed snapshot, but the storage-order contract was undocumented and callers had no way to require it. Explicit `order_by` sorts the whole result. Ranked, Enterprise, RTE/LSM, legacy scalar-index and namespace-pushdown paths cannot always preserve base manifest order. ## Behavior - `scan_in_order(true)` requires manifest order without adding a sort: fragments in manifest order, then rows in fragment order. - `true` disables scalar-index filter planning. Legacy scalar-index plans can materialize index rows in a different sequence, so filters are evaluated over the manifest-ordered scan instead. Filter semantics are unchanged, but the scan can read more data. Default filtered scans can still use those plans and may not preserve manifest order. - `scan_in_order(false)` permits the backend to scan unordered. It does **not** guarantee a different order; an explicit nonempty `order_by` still sorts. - Leaving the option unset preserves the backend default. The documented manifest-order default applies to an unfiltered base-only scan of a pinned Embedded table version. RTE tables scan the LSM by default and need `use_rte(false)` for the base-only guarantee. Enterprise and namespace-pushed scans have no order guarantee. - `true` conflicts with nonempty `order_by`, take queries, vector/full-text/hybrid/reranked queries, RTE/LSM reads, and Enterprise tables. These fail explicitly instead of silently dropping the requirement. Take conflict validation happens at the shared take-preparation boundary before offset or row-id selectors are stripped. - `with_fragments()` is rejected with `scan_in_order(true)` because fragment objects cannot be validated against the pinned dataset version. Use `fragment_ids()`, which resolves fragment ids from the manifest and preserves manifest order. Both sync and async pandas scanner paths share this rule. - Namespace `QueryTable` pushdown executes `true` against Embedded storage instead of dropping the order. The existing path preserves projection, filtering, limits, version/branch selection, and RTE routing; if Embedded storage cannot be read, the query fails. Supported entry points are plain Rust `Table::query()`, Python sync `table.search()` and async `table.query()`. The Python pandas scanner fast path forwards the option and disables scalar-index planning for explicit order. Existing takes and `with_fragments()` calls with `None` or `false` are unchanged. ## Validation - Rust: 6 `scan_in_order` tests, 32 take tests, 25 query-route tests. - Python: `test_query.py` and `test_namespace.py` 352 passed, 1 skipped against a matching extension. - Scoped `pytest --doctest-modules python/lancedb/query.py -k scan_in_order`: 2 passed. The Rust/Python examples create their own tables and are executable. - Regressions cover legacy 0.1 and stable BTREE tables with update and a filter admitting every row, across pinned versions before and after update; reversed `fragment_ids`; explicit `with_fragments()` rejection; and fixed-version multi-fragment reads with deletions, one-row batches, and limit/offset. No `SortExec` is added. - `cargo clippy --features remote --tests --examples`; `cargo fmt --check`; Ruff format/check; `git diff --check`. - Local checks ran on this branch. CI on this PR evaluates the merge with current `main`; no combined local binary validation is claimed here. Refs OSS-3109. |
||
|
|
0d2655edba |
test(python): isolate the background-loop fork scenario (#5142)
## Summary Follow-up to #5111. `test_forked_child_starts_background_loop_lazily` forked the shared pytest process. On CI that process may already own native Tokio/parking_lot state from earlier tests such as `test_authz.py`, so the forked child can crash in a non-Python native thread during `table_names()` for reasons unrelated to this scenario. Run the entire fork scenario in a fresh `python -c` subprocess. The parent still starts `LOOP` via `parent-before`, forks while holding `LOOP._start_lock` (released in `finally`), and the child still verifies that it sees no inherited loop, thread, or background threads before using the real native sync API (`connect("memory://")` / `table_names()`). The child must then gain exactly one live daemon thread, while the parent's original thread stays alive and serves `parent-after`. This is test isolation, not a production fix or a root-cause claim. The original assertions and cleanup are preserved, with a 40s outer timeout for `join(20)`, `terminate()` + `join(5)`, `queue.get(5)`, and diagnostics. ## CI evidence The failure was observed on a docs-only main run (`b4459f35`), so it is not caused by a product change in that run: - [Minimum dependencies job 136441279987](https://github.com/lancedb/lancedb/actions/runs/44780367013/job/136441279987): timed out at ~20s. - [Linux Python 3.13 job 136441280394](https://github.com/lancedb/lancedb/actions/runs/44780367013/job/136441280394): native SIGSEGV in a non-Python native thread during `table_names()` after `connect`, following `test_authz.py` in the same stage. ## Validation - `python/tests/test_background_loop.py`: 4 passed. - Same pytest process, `test_authz.py` followed by `test_background_loop.py`: 83 passed. - `uv run make check`: cargo fmt, ruff format, cargo clippy, and ruff check passed. No production code changes. |
||
|
|
668fb1e256 |
feat(python): add tag-based branch creation and default tag versions (#5136)
Python `tags.create()` now defaults `version` to the handle's currently visible version, including checked-out handles. Existing `from_ref` / `from_version` branch selection and explicit tag versions keep their current behavior. `branches.create()` gains keyword-only `from_tag`, so a branch can fork from a tag through the existing `Ref::Tag` path. This preserves the tag's actual branch snapshot; resolving only its numeric version could fork from `main` when both branches share a version number. `from_tag` conflicts with `from_ref` / `from_version` are rejected before `from_ref="main"` normalization. When `from_ref` names a tag instead of a branch, the native missing-branch failure keeps its classification and receives a static `from_tag=` hint without another lookup. A missing version and an ambiguous Enterprise 404 keep their original errors. The Python sync and async APIs, PyO3 binding, stubs and docstrings are updated together, with native Rust coverage for a tag on a branch that shares main's numeric version. Node.js `fromTag` and optional `version` will follow in a separate PR after this one. |
||
|
|
13fe33581e |
perf(python): add direct sync query execution (#5141)
## Summary Route ordinary local `table.search(...).to_arrow()` queries through private synchronous schema and eager-collection bindings instead of the Python background event loop. Plain scans, vector searches (including default vector-column inference), and native FTS in lazy Blob mode now complete with zero `LOOP.run` submissions. The synchronous path reuses the existing query lowering, core query execution, eager collector, Arrow ownership, projection validation, fragments, row ids, Blob finalization, reranking, and snapshot handling. It uses the generation-scoped Tokio runtime and `OutstandingGuard`, releases the GIL while waiting, checks CPython signals on the caller thread at a bounded interval, and aborts and drops collected state when a handler raises. Multi-threaded Tokio callback re-entry uses `block_in_place`; current-thread contexts return a Python error. Namespace, RemoteTable, Enterprise, streaming, take, and non-lazy Blob routing are unchanged. No public API is added. ## Benchmark Workload: 200,000 rows, 64 dimensions, BTREE on `id`, IVF_PQ on `vector`; 50 warmups + 500 calls, p50/p99 of three alternating runs. Build: `release-with-debug`. Baseline Python package from `03fc5404` ran against the same candidate extension as the candidate, so this isolates the Python event-loop route; a separately built matching baseline extension is a follow-up validation target. The host had competing Rust builds, so these numbers are preliminary, not isolated release throughput. | Workload | LOOP/schema per call before -> after | p50 before -> after | p99 before -> after | |---|---|---|---| | plain point lookup `to_arrow()` | 2 / 1 -> 0 / 1 | 2.32 / 3.26 / 2.64 ms -> 1.64 / 1.89 / 1.80 ms | 3.87 / 3.92 / 3.69 ms -> 2.42 / 2.63 / 2.62 ms | | indexed vector `to_arrow()` | 3 / 2 -> 0 / 2 | 5.20 / 5.13 / 3.79 ms -> 4.65 / 4.22 / 4.31 ms | 7.18 / 7.52 / 6.45 ms -> 6.29 / 6.01 / 6.43 ms | `to_batches()` remains on the existing streaming path. OSS-2868 1/2/4/8/16-thread scaling and fully matched build artifacts remain separate follow-up. ## Validation - `test_sync_query_direct.py`: plain/vector/native FTS with `LOOP.run` patched to fail, default vector inference, empty schema, timeout, single-worker progress-callback re-entry, and SIGINT/runtime reuse. - `test_query.py` with direct tests: 253 passed, 1 skipped. - `test_blob.py`: 266 passed, 1 skipped. - `test_fts.py` + `test_rerankers.py`: 163 passed, 13 skipped. - `test_table.py` + `test_namespace.py` + `test_sync_api_parity.py`: 649 passed, 17 skipped. - Remote query/blob/schema subset: 206 passed. - Runtime unit tests: 12 passed; `cargo check`, `cargo clippy`, `cargo fmt --check`, and Python ruff passed. The SIGINT case is marked slow and was run in focused validation; it is not part of the default suite. Refs OSS-2867 (non-closing). |
||
|
|
a3b6fecfd6 |
feat(python)!: preserve input order for take offsets (#5140)
## Summary Add an opt-in `preserve_order` flag to sync and async `take_offsets`. It exposes the existing Rust `TakeRestoreExec` ordering path and carries the flag through `QueryRequest`, `PyQueryRequest`, and the Python `Query` model. ## Behavior - Default `preserve_order=False` keeps the existing incremental, unspecified-order behavior. - `preserve_order=True` returns found rows in input order, including repeated offsets. - Missing non-negative offsets keep filter semantics and are omitted; negative offsets remain rejected by the existing `u64` contract. - Rust take queries apply `limit`/`offset` after order and repetition are restored. Python take builders and Query conversion do not expose pagination. - An explicit `order_by` conflicts with offset `preserve_order` and raises clearly. `take_row_ids` keeps its existing implicit ordering and explicit-sort behavior. - `__getitems__` is unchanged: it keeps its Python re-alignment and strict missing-offset (`ArrowIndexError`) behavior. ## Remote lookup The remote lookup sends only the deduplicated `_rowoffset IN (...)` filter and restores order/repetition client-side; there is no new wire field or backend extension. Namespace take queries stay on local execution, and RTE/LSM rejects the `_rowoffset` lookup loudly. ## Testing - Old reviewed head reproduced the serialization regression: `test_query_serialization_sync/async` failed because the Query model exposed `False` for an unset field. - Fixed by using `Optional[bool] = None` and mapping Rust `false` to absent in `PyQueryRequest`; explicit `True` still survives the actual round trip. - `python/tests/test_query.py`: 253 passed, 1 skipped. - Rust preserve-order tests: 3 passed; row-id/order-by tests: 27 passed. - Remote ordered Blob bytes, remote permutation, and Blob mode focused cases: 3 passed. - `cargo fmt --check`, `ruff format/check`, `py_compile`, and `git diff --check` passed. ## Migration `lancedb::query::QueryRequest` is a public non-`#[non_exhaustive]` struct. Downstream code that constructs it with an exhaustive struct literal must add `preserve_order: false` or use `..Default::default()`. The field is client-side metadata and is not sent over the remote protocol. Seekable Blob APIs, rollout, and ENT-4059 remain separate work. Refs OSS-2881 (non-closing). |
||
|
|
1658c8d762 |
feat(python)!: support vector columns in permutation torch formats (#5131)
BREAKING CHANGE: `Permutation.with_format("torch_row")` now uses PyTorch
dtype promotion instead of NumPy promotion. Mixed numeric columns can
change dtype, for example int64 and float32 now produce float32 instead
of float64. Cast columns before formatting when the old dtype matters.
Nullable scalar integer and floating columns still produce NaN; nulls in
nested fixed-size-list or tensor columns, and in bfloat16 columns, are
rejected.
## Problem
`Permutation.with_format("torch")`, `"torch_col"`, and `"torch_row"`
fail when the selected columns include a vector (`FixedSizeList`)
column, which is the column training workloads need. The conversion also
has to preserve Arrow slice offsets, logical `FixedShapeTensor` axes,
and visible nested nulls instead of flattening over them.
## Behavior
- Add `with_format("torch_dict")`: a dict of per-column `(B, *S)`
tensors, usable directly with a `DataLoader` identity collate. Tensors
share Arrow storage where the layout allows.
- Extend `torch` per-row dicts to nested `FixedSizeList` and
`FixedShapeTensor`; PyTorch's default collate stacks them back into `(B,
*S)` tensors.
- Preserve `torch_col` as `(C, B, *S)`, including a zero-copy
`unsqueeze(0)` view for one column.
- Preserve `torch_row` as per-row `(C, *S)` tensors, including `(1,)`
for one scalar column, with `torch.promote_types` for mixed numeric
dtypes. Nullable scalar integer and floating columns keep their previous
NaN behavior; nested fixed-size-list and tensor nulls are rejected.
- `torch_col` and `torch_row` reject heterogeneous sample shapes with
the field names, shapes, and guidance to `torch_dict`.
- Support nested fixed-size lists, `FixedShapeTensor` logical axis
permutations, boolean/integer/floating leaves, empty batches, and
nonzero slice offsets. `torch_dict`, `torch`, and `torch_col` reject
visible nulls.
- NumPy still returns one ndarray. Its pandas conversion may copy, may
promote mixed numeric columns to a common numeric dtype (for example
int64 and float32 to float64), and produces an object array for nested
or incompatible columns.
- `lance.bfloat16` is accepted only for a `FixedSizeBinary(2)` leaf
carrying the `ARROW:extension:name` metadata; offsets/length and byte
order are handled before viewing as `torch.bfloat16`. Unmarked binary
columns are rejected.
This is Python-only and does not change persistence, pickling, or public
method signatures.
## Validation
- `pyarrow 26.0.1`, `torch 2.15.0+cu132`, Python 3.12: `test_torch.py`
23 passed; `test_permutation.py` 84 passed.
- Minimum `pyarrow 16.0.0`, `torch 2.0.1+cpu`, Python 3.11: the nullable
scalar, mixed-dtype, null-rejection, and NumPy tests passed (4 focused
tests). The new NumPy test skips without pandas via
`pytest.importorskip`.
- The pre-existing fork DataLoader tests are flaky only when the full
`test_torch.py` file runs on the minimum stack; each passes when run
alone. Their failure is on the default Python format path and does not
exercise the changed format conversions.
- `ruff format`, `ruff check`, and `git diff --check` pass.
|
||
|
|
7eb40118ac |
fix(python): write enum members as their values in table.update (#5061)
`table.update(values=...)` fails for a member of an int- or float-valued Enum. `value_to_sql` dispatches it to the `int` or `float` handler, and `str()` returns the member name, so the SQL reads `priority = Priority.HIGH` as a field access. A plain Enum member raises `NotImplementedError`. #3232 stores a `(int, Enum)` field as int64 and #4357 writes Enum fields as their values on `add`, so only `update` disagrees. ```python class Priority(int, Enum): HIGH = 2 table = db.create_table("t", data=[{"id": 1, "priority": 1}]) table.update(values={"priority": Priority.HIGH}) # lancedb 0.41.0: ValueError: Invalid input, Execution error: Cannot access field at argument 1: type Int64 is not Struct, Map, or Null ``` The int and float handlers now convert with `int()` and `float()` first, and an `Enum` handler writes `value.value`. Str-valued members already worked, because `str.replace` returns a plain `str`. No issue is open for this. ``` $ cd python && pytest python/tests/test_util.py -k enum_members -q # |
||
|
|
03fc5404ae |
perf(python): deduplicate sync query preparation (#5130)
## Summary Sync query execution rebuilt schema-derived state several times inside one call: for vector-column inference, blob projection validation, row-id preparation, async handoff, and result finalization. A plain point lookup paid five schema reads and five background-loop submissions per `to_arrow()`. This change prepares the schema and projected blob sources once per execution and reuses them through scan setup, result finalization, and the async handoff. Sync-prepared queries tell the async layer that blob row ids are already resolved; nothing is cached between executions, so a reused builder still observes schema changes. Plain scans and explicit vector columns no longer read the schema just to infer a vector column, and the dead vector conversion in `LanceVectorQueryBuilder.to_batches()` is removed. Non-lazy vector `to_arrow()` stays on its lazy materialization path, so reranking and snapshot merging run once before the aggregate blob conversion. Async behavior, namespace routing, fragments, timeouts, and public APIs are unchanged. A direct synchronous Rust terminal remains follow-up work. ## Benchmark Workload: 200,000 rows, 64 dimensions, BTREE on `id`, IVF_PQ on `vector`; 50 warmups + 500 calls per run; p50 of three runs. Baseline and candidate Python packages ran against the same `release-no-lto` extension built at `a2176f9b`; only package source differed. Local NVMe, single host. | Workload | Loop/schema per call before -> after | p50 before -> after | |---|---|---| | plain point lookup `to_arrow()` | 5 / 5 -> 2 / 1 | 6.06 / 6.08 / 5.67 ms -> 3.26 / 3.26 / 3.33 ms | | indexed vector `to_arrow()` | 5 / 5 -> 3 / 2 | 8.82 / 8.21 / 8.35 ms -> 6.40 / 6.55 / 6.60 ms | | plain point lookup `to_batches().read_all()` | 6 / 4 -> 4 / 1 | 6.88 / 7.25 / 6.94 ms -> 4.37 / 4.80 / 3.76 ms | `release-no-lto` is a local comparison build, not a release-profile number. The branch includes a merge of current main (`a2176f9b`, #5129); the affected blob, reranker, FTS, query, and namespace checks were rerun against the merged tree. Refs OSS-2867 (non-closing). |
||
|
|
a2176f9bcd |
fix(python): preserve blob query snapshots and row-id guidance (#5129)
## Summary - Preserve the query snapshot carried by a remote query result when `fetch_blobs` or `fetch_blob_files` receives that result table, instead of reading row IDs from the table's current snapshot. - Send the expected `x-lancedb-query-snapshot` on the descriptor take used by `fetch_blob_files` and verify the response echo before decoding any descriptor. NULL and empty descriptors cannot escape unverified. - Point missing `_rowid` and missing row-id errors at `take_offsets(offsets, with_row_id=True)` for callers that have row positions, while keeping the existing missing/deleted row-id details. - Keep `fetch_blobs` row-ID based. Positional access and seekable video/DataLoader handle design remain separate work aligned with ENT-4059; this PR does not add `offsets=` or change that contract. - Document the behavior and keep empty row-id requests at zero I/O. ## Compatibility Server 0.5.0 is the basic remote Blob API floor. Snapshot-bound descriptor reads need the actual query identity echo from the serving node (Sophon #10211, present in tag v1.13.0). If identity cannot be verified, `fetch_blob_files` fails explicitly instead of accepting descriptors. Metadata-free row-id input keeps the existing current-snapshot behavior. This does not claim production rollout or real server testing. ## Testing - `python/tests/test_blob.py`: 249 passed, 1 skipped - `python/tests/test_remote_db.py -k blob`: 133 passed - Rust remote blob-file unit tests: 13 passed - `cargo check --features remote --tests --examples` - `cargo fmt --all --check`, `ruff format` and `ruff check` Refs OSS-2881 (non-closing). |
||
|
|
d46754cad4 |
feat: register blob bases during table creation (#5117)
## Summary `create_table` / `create_empty_table` now accept registered storage bases and the embedded opt-in for blob URIs outside them. A create with data registers `initial_bases` in the same commit, so external Blob v2 references no longer need an empty create followed by `add`. - Rust `CreateTableBuilder::initial_bases` / `allow_external_blob_outside_bases`, with `BasePath` re-exported. - PyO3 and Python sync/async create paths accept lightweight `BasePath`, dicts, and duck-typed `lance.DatasetBasePath`; `id=None` lets Lance assign an ID and explicit `0` or duplicate explicit IDs are rejected. - `blob_uri_array` builds the standard four-field `lance.blob.v2` array without pylance and keeps field metadata such as `lancedb:logical_type=mp4`. - Enterprise create rejects non-empty `initial_bases` and the true opt-in before normalization, input iteration, or HTTP; empty/false defaults remain an ordinary create. - Native namespace create merges namespace and connection storage options into the caller's store parameters instead of replacing them. This is reconciled with #5114's refresh layering, so caller-scoped options survive create, refresh, and reopen while namespace-vended values keep their precedence. - The outside-base opt-in applies to one write: setting it on create does not carry over to a later `add()`. ## Validation - `cargo fmt --all -- --check`, `cargo check --quiet --features remote --tests --examples`, `cargo clippy --quiet --features remote --tests --examples`. - Rust: `blob_integration` 66 passed, `database::namespace` 23, `connection::create_table` 16, `remote::db` 128. - Python: `test_blob.py` 263 passed / 1 skipped, `test_blob_array.py` 4, remote create 12, `test_db.py -k "pickle or create_table"` 15, `test_namespace.py -k "pickle or refresh or create"` 29, `test_table.py -k pickle` 8; ruff 0.9.9 and pyright from `python/`. - `test_blob.py` also passes with pylance and pandas removed (177 passed / 87 skipped), matching the CI no-pylance suite. The lightweight and dict create cases keep version, schema, reopen, and exact-range assertions there; only the pylance-only manifest introspection moved into the `DatasetBasePath` case. - Rust and sync Python two-base probes assert that base 1's scoped option fails its read while base 2 still returns exact bytes after reopen. A separate async namespace test covers create and reopen with exact ranges. - `test_namespace_refresh_layers_caller_scoped_options` covers the expired namespace seed: create-time `base_1.caller_scoped` survives refresh, vended `timeout` is replaced (7s to 8s), fresh namespace values appear, and reopen with the caller option returns exact blob range bytes through the registered base. - Updated `main` through #5127 (including #5114) is merged; `rust/lancedb/src/database/namespace.rs` and `rust/lancedb/src/table.rs` match `main`, and no #5114 code was stacked before it merged. ## Dependency note The Lance dependency stays pinned at the `v15.0.0-beta.25` release on `main`. With that pin, mixing an automatic base ID (`id=0`) and an explicit non-zero ID may still collide; the approved upstream fix is https://github.com/lance-format/lance/pull/11307. Use distinct explicit non-zero IDs for multi-base creates, or automatic IDs for every base, until a Lance release containing that fix is pinned. A failed mixed create can leave the table name listed but unopenable; retrying with distinct explicit IDs succeeds. Multi-base validation here uses explicit IDs and bootstrap uses a single automatic ID, so the mixed-ID case is not claimed as verified until a Lance release containing that fix is pinned. |
||
|
|
85f966a9a9 |
fix: add dataset path hint and sync open_table location (#5128)
## Summary - Expose `location=` on sync `LanceDBConnection.open_table()`, matching the existing async entry point while leaving remote and namespace APIs unchanged. - When a `ListingDatabase` connection URI ends in `.lance`, append a parent-directory and table-stem hint to the derived-URI `TableNotFound` error. The error classification and source chain are preserved, and no extra storage probes are made. Context: OSS-2858 remains canceled. This is only the narrow embedded DX follow-up; it does not add a top-level `lancedb.open_table(uri)` API. ## Verification - Rust targeted listing tests for the `.lance` hint and the explicit-location path. - Python sync `open_table` tests for `location=` and the `.lance` hint. - Pickle round-trip of a sync `location=` table after #5114. - `cargo check --features remote --tests --examples`, `cargo fmt --check`, Ruff format/check. |
||
|
|
9799686986 |
perf(python): add native eager collection for to_arrow (#5127)
## Summary `to_arrow()` currently collects results one Python future per batch: both sync and async paths call `to_batches()`, which crosses the Python/Rust bridge for every default 1024-row batch. Vector queries also materialize the whole native stream even when no reranker is configured. This adds a shared Rust eager collector. `execute_to_reader` collects the batches in Rust, asks the core to skip the default 1024-row output slicing, and exposes the result through the Arrow C Stream interface, so Python builds the Table without a Python future per batch. Sync and async `to_arrow`, including FTS, vector and hybrid eager paths, use it. `AsyncVectorQuery.to_batches` no longer materializes results when there is no reranker and now honors `max_batch_length`. Schema, empty results, timeout, cancellation, and error behavior are preserved. The existing fragment guard is enforced on the new fast path, and namespace-pushdown routing keeps its existing Python/Rust split. ## Benchmark Development-profile editable build, full scans on one revision, 1 warmup + 5 measured runs. Absolute values are not release-profile numbers; compare before/after on the same build. | Workload | Before | After | |---|---|---| | 5M rows x 3 columns, async | 3.054 s | 0.087 s (35.1x) | | 5M rows x 3 columns, sync | 3.462 s | 0.090 s (38.3x) | | 200k rows x 129 columns, async | 0.354 s | 0.082 s (4.3x) | | 200k rows x 129 columns, sync | 0.387 s | 0.085 s (4.5x) | The narrow scan returned 4,883 batches capped at 1,024 rows before and 611 batches up to 8,192 rows after. |
||
|
|
dcded7fb70 |
feat(python): default StreamingDataLoader workers to forkserver (#5112)
## Problem `StreamingDataLoader` left PyTorch's platform default in place for worker processes, which is `fork` on Linux. Forked workers inherit the parent process's native runtime and connections, which is the failure mode behind the fork-isolation work. ## Behavior When `num_workers > 0` and `multiprocessing_context` is omitted or `None`, workers now use `forkserver` when the platform provides it, otherwise `spawn`. Explicit start-method names and context objects are unchanged. With `num_workers == 0`, no context is selected, preserving PyTorch's single-process handling. Callbacks and worker state must be picklable under the selected start method, following PyTorch's DataLoader rules. Existing `StreamingDataset` serialization is sufficient for the default worker path. This does not change the explicit fork opt-in or the native client reopen path in #3851. |
||
|
|
ea4f1a38cf |
fix: keep nonempty order_by out of namespace query pushdown (#5122)
## Problem With namespace `QueryTable` pushdown enabled, a query with a nonempty `order_by` was sent to the namespace server even though the request schema has no `order_by` field. With `limit(1)` this returned the wrong top row instead of the requested ordering. ## Fix Treat a nonempty `order_by` as requiring local execution in both the Python and Rust namespace pushdown gates. `None` or an empty ordering still uses pushdown. Local execution preserves branch, version and RTE semantics; if local storage cannot be read, the query fails explicitly rather than silently dropping the ordering. ## Validation - Public Python sync `search().order_by(...).limit(1).to_arrow()` and async `query().order_by(...).limit(1).to_arrow()` against a namespace mock: returned id 1 with zero pushdown calls. - `python/tests/test_namespace.py`: 83 passed. - Rust namespace pushdown tests: 5 passed; `table::query::tests`: 21 passed. - `cargo fmt`, `cargo clippy`, and Ruff clean. Fixes [OSS-3126](https://linear.app/lancedb/issue/OSS-3126/bug-namespace-querytable-pushdown-silently-drops-order-by). |
||
|
|
56638a9e71 |
fix(python): reject Expr inputs on unregistered Function definitions (#5125)
`FunctionDefinition.__call__` ran the decorated Python callable with any
value it was given, so `my_function(value=col("value"))` executed user
code against an `Expr` or silently returned one, with errors such as
`float() argument must be a string or a real number, not 'Expr'`. A
column reference is not a local value: it binds only on a registered
`FunctionVersion`.
An unregistered definition now rejects `Expr` positional and keyword
arguments with `TypeError` before the callable runs, and names the
supported path: `create_function`/`create_function_async`, then
`col(...)` on the returned version. Plain Python and Arrow arguments,
and the class `__init__`/`__call__` lifecycle, are unchanged.
The Function authoring guide's batch example did not register either: a
`pyarrow.Array` annotation carries no element types, so `score_batch`
raised `TypeError` for missing `input_schema` and `output_schema`, and
the page claimed one `pa.RecordBatch` parameter could read several
columns. The example now passes both schemas, shows one `pa.Array`
parameter per input column for multi-column functions, and states that
`input_schema` matches parameters one to one, so a `RecordBatch`
parameter binds one input column. The GPU class example on the same page
had the same missing-schema defect and is fixed too.
Compatibility: code that passed `col(...)` to an unregistered definition
now gets `TypeError` instead of running user code against an `Expr`.
That call was never a supported binding and produced no usable result;
no supported call changes.
|
||
|
|
121de72cc4 |
fix(python): keep Permutation builder copies shallow (#5121)
## Summary `Permutation`'s `with_*` builders use `copy.copy`, but `Permutation` had no `__copy__`. Python therefore fell back to `__getstate__`/`__setstate__`, which calls `permutation_table.to_arrow()` (unsupported for remote tables) and rebuilds the base table and reader on every builder call. Add a targeted `__copy__` that shallow-copies the instance state. The copy keeps the existing table handles and reader and can change its own attributes without affecting the original. Pickle serialization and persist semantics are unchanged. Refs OSS-2857. The persist feature remains open. |
||
|
|
b9a2807049 |
fix(python): accept column names in order_by and validate early (#5119)
## Summary
- Accept column names, `(column_name, "asc"|"desc")` tuples,
`ColumnOrdering`, and `{"column_name": ...}` dicts in both sync and
async `order_by`, including mixed lists.
- Distinguish a bare direction tuple from a list of column names by
container type; `None` and `[]` clear ordering.
- Validate at setter time with actionable errors for unknown dict keys
and invalid directions.
- Export `ColumnOrdering` from `lancedb` and document the accepted forms
with examples.
- Reject non-empty ordering on sync hybrid queries explicitly instead of
silently ignoring it.
Fixes OSS-3108. Namespace pushdown (OSS-3126) is intentionally out of
scope.
## Tests
- `python/tests/test_query.py` (214 passed, 1 skipped)
- `python/tests/test_query.py -k order_by` (7 passed)
- `python/tests/test_fts.py -k order_by` (2 passed)
- `python/tests/test_remote_db.py::test_query_sync_maximal`
- `pytest --doctest-modules python/lancedb/query.py` (21 passed)
- `ruff format` / `ruff check`
|
||
|
|
164aec1753 |
fix(python): start background event loop lazily (#5111)
## Summary Importing `lancedb` currently starts a daemon thread running a private asyncio loop, even when the process never performs a synchronous database operation. Start that loop on the first actual coroutine submission instead. Concurrent first callers share one initialization, and a forked child resets the singleton to the unstarted state without touching the inherited thread or lock, then starts fresh work lazily on first use. The Rust-side runtime and the existing fork/reopen contracts are unchanged. ## Validation - New import, first-use, concurrent first-use, and fork parent/child coverage passes. - Existing import, debugger-inspection, cancellation, and remote fork tests pass. - `ruff format --check .` and `ruff check .` pass. |
||
|
|
28e9ebb3dd |
fix(python): reject unsupported fragment constraints (#5120)
`with_fragments()` / `fragment_ids()` were only honored by the embedded plain-scan blob Pandas path. Every other sync, async, and remote terminal could silently ignore the selection and scan the full table, and async query conversions plus FTS `count_rows()` could drop the constraint before execution. This change makes unsupported paths fail with `NotImplementedError` before I/O, preserves fragment state across async Standard/Vector/FTS/Hybrid conversions, and keeps the supported embedded blob `to_pandas()` behavior unchanged. The FTS `count_rows()` sync and async entry points now reject fragment constraints explicitly. Refs OSS-2859 |
||
|
|
5e9b17b639 |
feat(python): make native tables and connections picklable (#5114)
## Summary Adds `__getstate__`/`__setstate__` to native `LanceTable` and `LanceDBConnection` so a PyTorch `Dataset` that keeps both can cross `spawn` and `forkserver` worker boundaries. `Permutation` and `StreamingDataset` now delegate to the same table state representation while retaining compatibility with older pickle payloads. ## Pickle contract - Reconnects from the serialized connection and preserves the table name, namespace path, explicit storage overrides, location, index-cache setting, managed versioning and pushdown routing. - Standard mode reopens at latest; `checkout(version)` remains pinned to the resolved branch/version; branch handles preserve their branch. Cross-branch tag checkout records the actual live branch. - `read_consistency_interval=timedelta(0)` remains distinct from `None`. - `memory://` tables keep the existing Arrow snapshot export/rebuild behavior. - `Session` and unreconstructable custom namespace clients fail at `pickle.dumps` with an explicit `TypeError`; declared namespace configurations reconstruct, including an omitted properties map. - Namespace storage options keep caller-only overrides layered over the live provider, with vended values winning conflicts. Caller options survive refresh, refreshed credentials replace old vended values, an explicit provider remains selected on open, and an empty provider response stays empty rather than restoring an expired seed. - Declared Python namespace connections reopen through their connection provider instead of turning the reconstructed client into an explicit table provider. ## Verification - Fresh binding build with `uv run --extra tests --extra dev maturin develop --extras tests,dev`. - End-to-end `DataLoader` holding `self._db` and `self._table`: spawn and forkserver passed. - `test_namespace.py`: 90 passed; `test_table.py` + `test_db.py` + `test_permutation.py`: 700 passed, 17 skipped. - Focused namespace provider/pickle regressions: passed, including caller-only and vended keys after a declared-namespace refresh. - Rust `test_namespace_connection_with_storage_options` and `test_manifest_enabled_vend_input_storage_options`: passed. - `cargo clippy -p lancedb --features remote --tests --examples`, `cargo fmt --check`, exact CI Pyright (0 errors/0 warnings), and Ruff passed. - DataLoader Workers documentation updated; Vale reports 0 findings. ## Scope Does not change the fork hard-error policy, #3851, or direct `LanceNamespaceDBConnection` pickling. It does not claim changes to the existing namespace dir `index_cache_size` behavior. This supersedes the earlier draft #3486, which only moved the table-state portion. |
||
|
|
a9be4525a0 |
fix(python): accept optional discard_weight in split_hash (#5116)
### Problem `PermutationBuilder.split_hash()` raises `TypeError` when `discard_weight` is omitted because the Python wrapper forwards `None` while the PyO3 binding requires `u64`. The `_lancedb.pyi` stub also disagrees with the native signature: it omits `split_names` and types `discard_weight` as non-optional. ### Behavior The native binding accepts an optional `discard_weight` and treats omitted/`None` as `0`, so `split_hash(..., split_names=[...])` works without passing a discard weight. The stub now matches the binding. A regression test verifies that omitting `discard_weight` assigns every row exactly like explicit `0`. Fixes OSS-2856. |
||
|
|
4b428101dd |
feat: expose the RTREE index in the Python and TypeScript SDKs (#4942)
Part of #4554. Supersedes #4555. This exposes Lance's R-tree index in the Python and TypeScript SDKs. Python gets a `lancedb.index.RTree` config with an optional `page_size`, accepted by `create_index(config=...)` on local, async and remote tables. TypeScript gets `Index.rtree({ pageSize })` and `RTreeOptions`. Both map to the Rust crate's existing `Index::RTree`, so remote tables send `index_type: "RTREE"`. The index accelerates `ST_Intersects`, `ST_Contains`, `ST_Within`, `ST_Touches`, `ST_Crosses`, `ST_Overlaps`, `ST_Covers` and `ST_CoveredBy` filters between a GeoArrow column and a constant geometry, in either argument order, including as a prefilter on vector search. The scalar index docs page gets an R-tree section. `geo` is now a default feature of the Python and Node packages. Without it, a local table can neither build the index nor evaluate `ST_*` filters, and because wheels and npm packages are prebuilt, an opt-in Cargo feature would not reach users. pylance already ships with `geo` on. It adds pure-Rust crates under licenses that `deny.toml` already allows. `Cargo.lock` doesn't change, and the third-party license notices are regenerated. The cost is size: the macOS arm64 release wheel grows from 69.4 MB to 71.7 MB (+2.4 MB, +3.4%). The tests pin the constant-first predicate bug that held up #4555, which lance-format/lance#10080 fixed, in queries, `delete()` and `update()`, with and without the index. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
23f9d5a741 |
feat(sdk): support bound parameters in data prewarm (#5076)
Data prewarm methods accept filter expressions but cannot bind their
values, which forces applications to build literal SQL themselves. This
adds optional positional and named parameters to data-prewarm submission
and typed previews across Rust, Python, and TypeScript. Values use the
existing typed Arrow SQL transport and remain separate from the filter
text. Existing calls and job-handle behavior are preserved;
parameterized filters require a compatible LanceDB Enterprise server.
This was accomplished with the following changes:
- Add `PrewarmDataOptions::parameters(RecordBatch)` and forward the
batch through SQL submission and `EXPLAIN PREWARM` requests.
- Reuse Python's `QueryParameters` conversion for
synchronous/asynchronous, legacy/job-returning, and typed preview
methods.
- Add TypeScript positional-array, named-object, and explicit Arrow
parameter inputs, with safe scalar encoding and native IPC forwarding.
- Keep parameter values out of Rust option debug output and reject
invalid input before submission where possible.
- Add transport and codec regression tests, including injection-shaped
strings, typed Arrow values, legacy method forwarding, and typed preview
bindings.
- Document bound filters in the cache-prewarm guide with Python,
TypeScript, and Rust examples; update generic SQL parameter
documentation.
### Usage and behaviour
```python
job = table.prewarm_data_async(
["payload"], filter="id >= $minimum", parameters={"minimum": 1000}
)
job.wait()
```
```typescript
const job = await table.prewarmDataAsync({
columns: ["payload"], filter: "id >= $1", parameters: [1000],
});
await job.wait();
```
Python accepts a sequence, mapping, or one-row Arrow batch/table.
TypeScript accepts scalar arrays/objects or one-row Arrow input; safe
integers and bigint use Int64, fractional numbers use Float64. Rust
accepts a one-row Arrow batch. Parameters bind filter values, while
table identity, branch, and concurrency keep their existing interfaces.
Submission-only methods also forward bindings and retain their existing
return behavior. Typed preview helpers accept the same parameters
without creating a job.
### Testing
Python prewarm Flight transport tests pass (65 cases), Embedded
compatibility tests pass (6 cases), and focused Node parameter/prewarm
tests pass (45 cases, including ten codec and native-boundary cases).
Earlier matching-server verification passed 57 Python/SQL scenarios, 14
Node scenarios, and Rust SDK checks, covering selective and empty plans,
typed values, authorization, pinned branches, legacy methods, and
injection-shaped strings. A bound job also survives a full runtime
restart. The guide submission examples were also verified in Python,
TypeScript, and Rust; the TypeScript example type-checks. Live-server
checks used filesystem storage.
|
||
|
|
3907a492c0 |
feat(sdk): add typed data prewarm previews (#5075)
LanceDB SDKs can submit data prewarm jobs, but callers have to issue SQL directly to inspect a plan before warming. The existing text response does not provide a typed pruning contract. This adds metadata-only preview helpers across Rust, Python sync/async, and TypeScript, using a compatible Enterprise server’s structured SQL response. This was accomplished with the following changes: - Add `explain_prewarm_data(PrewarmDataOptions)`, Python `explain_prewarm_data(...)`, and TypeScript `explainPrewarmData(options)`. - Expose `PrewarmDataPlan` and `PrewarmPruningSummary`, preserving zero versus unknown counts and future pruning-mode strings. - Reuse submission options, identifier/filter validation, namespace and branch context, and Azure source-account hint handling. - Validate the versioned JSON response without parsing display text, submitting a warming job, polling HTTP job APIs, or falling back to REST. - Add API documentation, Flight SQL transport tests, Python sync/async response tests, and an opt-in live-service integration test. ### Usage and behaviour ```python plan = table.explain_prewarm_data(["payload"], filter="quality > 0.7") print(plan.table_version, plan.pruning.selected_fragments) ``` The helper returns a plan directly. It requires table Select plus database/namespace Usage and a server supporting `EXPLAIN (FORMAT JSON) PREWARM`. It reads metadata without creating a warming job. Selected ranges are conservative physical candidates; unknown counts remain `None`/`null`. A later submission resolves and plans its own snapshot. Historical-version and Embedded table handles are unsupported. |
||
|
|
96c25bd6b9 |
feat(nodejs): add Enterprise table override APIs (#5077)
Add TypeScript `getTableOverrides`, `updateTableOverrides`, and `resetTableOverrides` for LanceDB Enterprise tables, delegating to the shared Rust implementation used by Python. Document that updates perform GET → recursive local merge → full PUT. Unrelated fields are preserved from the read snapshot, but concurrent edits can be overwritten. CLI `set` and REST PUT retain replacement semantics. Fix an empty SDK update to return the current snapshot without a PUT. Live testing found that the previous implementation submitted an empty replacement and failed when no overrides were configured. The fix applies to Python, Rust, and TypeScript. Add mock HTTP/local coverage and an opt-in Enterprise integration suite for namespaces, branch isolation, REST replacement, validation failures, historical handles, and empty updates. |
||
|
|
a653d861ec |
fix(python): allow static diagnostic imports in Functions (#5084)
Functions previously rejected every `sys` or `importlib` import even when the source only used a statically visible diagnostic. Allow exactly `sys.stderr`, `sys.version_info`, and `importlib.metadata.version`, with direct imports, `from` imports, and aliases treated identically whether they appear at module level or inside the function or class body. Every other use of a namespace-access module still fails at decoration. The error now names the rejected operation, such as `sys.modules`, and lists the supported diagnostic operations. Tests package and execute the artifact offline for each import form, and reject unsupported attributes, submodules, dynamic attribute access, and rebinding. ENT-3918. |
||
|
|
16af729792 |
feat(sdk)!: add typed SQL job handles for compaction and data prewarm (#5056)
Remote data prewarm used REST even though SQL supported filters and concurrency, and both maintenance APIs returned after acceptance without exposing a consistent typed completion handle. Compaction's legacy statistics therefore could not describe the work committed by its durable job. This PR adds job-returning compaction and data-prewarm methods across Rust, Python sync/async and TypeScript, and moves data-prewarm submission to SQL. Legacy methods retain return-after-acceptance behavior; data prewarm now requires a compatible SQL PREWARM server and Flight SQL connectivity. This consolidates #5037, #5055 and #4906. This was accomplished with the following changes: - Added `compact_async()` / `compactAsync()` and `prewarm_data_async()` / `prewarmDataAsync()`, retaining the command receipt's durable job ID. - Added `PrewarmDataOptions` for columns, a metadata-pruning filter and concurrency; both operations inherit database, namespace and branch from the table handle. - Added filter/concurrency arguments to legacy Python `prewarm_data()` and a TypeScript `prewarmData(options)` overload, preserving the columns-array form and discarding the handle after acceptance. - Added typed `CompactionResult` and `PrewarmDataResult` decoding, including reopened jobs; missing result payloads fail explicitly and omitted measurements remain unknown. - Reused the shared Job lifecycle for status, refresh, progress callbacks, cancellation and events; Python maintenance progress bars display rewritten rows or completed executors. - Added TypeScript `wait({ timeoutMs, onProgress })` and Rust `wait_with_options(JobWaitOptions)`, complementing Python's existing timeout argument without cancelling the durable job. - Validated single unambiguous receipts, preserved compaction option presence/default inheritance, and returned actionable unsupported-server errors without dropping options or falling back to REST. - Updated native bindings, API references and maintenance documentation with job methods, result semantics, tuning and compatibility requirements. ### Usage and behaviour **New** = added here; **Enhanced** = existing support extended; **Existing** = already on main. This table describes remote SDK behavior; server-side SQL/CLI capabilities are prerequisites, not additions made by this SDK PR. | Surface | Capability | Compact | Data prewarm | Assessment | | --- | --- | --- | --- | --- | | Rust / Python sync+async / TypeScript | Submission transport | Existing SQL OPTIMIZE | **New:** REST → SQL PREWARM | Both now submit through SQL | | All SDKs | Durable job-returning API | **New:** `compact_async` / `compactAsync` | **New:** `prewarm_data_async` / `prewarmDataAsync` | Same lifecycle model | | All SDKs | Options and target scope | **New handle:** four existing compaction overrides, with omitted fields inherited | **New options:** columns/filter/concurrency | Namespace and branch preserved for both | | Python / TypeScript | Legacy convenience calls | Existing optimize acceptance behavior preserved | **Enhanced:** legacy methods accept filter/concurrency and use SQL | Return after acceptance; no completion wait | | All SDKs | Typed successful result | **New:** committed rows, file/fragment changes, partial commit and `more_work` | **New:** pinned version, fragments and executor outcomes | Different measurements are intentional | | All SDKs | Status / refresh / progress | Existing Job APIs reused by **new** maintenance handle | Existing Job APIs reused by **new** maintenance handle | HTTP monitoring remains | | Python / TypeScript | Progress presentation | **Enhanced:** rewrite rows/groups | **Enhanced:** executor progress | Shared callbacks; Python bars use operation counters | | All SDKs | Bounded wait | Python existing; **new** TS/Rust timeout controls | Same shared timeout support | Timeout stops this wait; job continues | | All SDKs | Reopen and await typed outcome | **New:** compaction result decoding on reopened handle | **New:** prewarm result decoding on reopened handle | Rust selects the typed result explicitly | | All SDKs | Cancel / events | Existing shared APIs available on **new** handle | Same | HTTP underneath; permissions unchanged | | All SDKs | Typed preview helper | Unavailable | Unavailable | General SQL where exposed; no helper added | | Authorization | Submission | Existing table Ownership plus parent Usage | SQL path uses Select plus parent Usage | Intentional difference | | All SDKs | Local / historical handles | New durable API rejects them | New durable API rejects them | Remote current-branch jobs only | ```python from datetime import timedelta # Legacy convenience call: returns None after acceptance. table.prewarm_data(["payload"], filter="id >= 1000", concurrency=4) warm = table.prewarm_data_async(["payload"], filter="id >= 1000", concurrency=4) warmed = warm.wait(timeout=timedelta(minutes=10), progress=print) print(warmed.table_version, warmed.executors_completed) compact = table.compact_async(compaction_options={"max_source_rows": 1000000}) committed = compact.wait(timeout=timedelta(minutes=10), progress=print) print(committed.rows_succeeded, committed.fragments_removed, committed.more_work) reopened_result = db.open_job(compact.id).wait() ``` ```typescript await table.prewarmData({ columns: ["payload"], filter: "id >= 1000", concurrency: 4 }); const job = await table.prewarmDataAsync({ columns: ["payload"], filter: "id >= 1000", concurrency: 4, }); const result = await job.wait({ timeoutMs: 600_000, onProgress: console.log }); ``` ```rust use std::time::Duration; use lancedb::job::JobWaitOptions; let job = table.compact_async(Default::default()).await?; let result = job.wait_with_options( JobWaitOptions::new().timeout(Duration::from_secs(600)), ).await?; ``` Python async tables await both submission and Job methods. Rust's legacy `prewarm_data(columns)` keeps its columns-only signature; use `PrewarmDataOptions` on the new job-returning method for filtering/concurrency. Wait deadlines cover pending status requests and polling delays. Existing `wait()`, TypeScript `wait(callback)` and Rust `wait_with_progress(callback)` remain supported. Status/progress/refresh/cancel/events still use generic HTTP job APIs; those endpoints and their read/event/cancel permissions must remain available. Cancelling or timing out does not roll back committed work. Compaction results describe committed rewrites and include deletion files in file counts. Prewarm results describe work against a pinned snapshot, with partial executors included in completed executors; nonempty byte/range measurements remain unknown. Missing results require compatible server/worker support rather than placeholder zero statistics. Filtering uses conservative metadata pruning, not an exact row-filter scan. ### Testing Six checked-in live Python sync/async cases pass against matching server/worker builds for compaction, job-returning prewarm and legacy filtered submission. Ten additional live Node scenarios pass for legacy/default/options forms, filters/concurrency, empty plans, validation, persisted specifications and readback. Targeted regressions pass: Python remote maintenance (80), shared jobs (82), local prewarm rejection (4); Node remote (107) and prewarm API cases (28), plus the previously exercised Rust remote regressions. Tests cover receipt parsing, typed results, reopening, unknown measurements, timeouts, and legacy calls returning None/undefined without polling. Dependency pins are unchanged. Azure account-hint acknowledgment was verified locally with filesystem storage; real Azure-backed storage still needs deployment-specific validation. |
||
|
|
fb34b1c783 |
feat(functions): add row failure recovery APIs (#5048)
Function failures currently require callers to assemble row predicates
and manage retry/version/quarantine state themselves. Add exact
failed-row retry and Function upgrades through the Rust and Python
refresh APIs, plus Python helpers for grouped causes, failing input
rows, quarantine, and per-row producing-version metadata.
```python
errors = table.function_errors(column="sharpness")
errors.summary()
errors.rows(columns=["frame_index", "frame"])
table.retry_failed("sharpness", function_version="2").wait()
table.quarantine_failed("sharpness", after_attempts=3)
table.retry_failed("sharpness", include_quarantined=True).wait()
table.function_provenance("sharpness")
```
`upgrade_column(..., recompute="failed" | "all" | "none")` keeps the
column available while selecting the intended work. `history=True` reads
retained past errors. Capability checks reject these operations on
servers that cannot honor the workflow, before any refresh is submitted.
Includes synchronous/asynchronous API and older-server compatibility
coverage. Formatting applied; local builds and tests were not run.
|
||
|
|
ba4e3ef3f9 |
feat: expose Function worker stack inspection (#5043)
Adds `Job::stack(worker_id)` in Rust and `Job.stack(worker_id)` /
`AsyncJob.stack(worker_id)` in Python for server-side Function jobs. The
response preserves capture availability, timestamps, truncation, and
session details; unsupported local or query handles retain their
existing unsupported-operation behavior. Refresh wrappers forward the
request to their tracked server job.
```python
evidence = job.stack("worker-id")
for session in evidence["stacks"]:
print(session["status"], session["stack"])
```
Requires a server implementing `/v1/jobs/stack` and system operate
privilege. The API propagates authorization and transport errors without
waiting for job completion. Existing progress snapshots already preserve
server warning fields.
Includes mocked request/response and synchronous/asynchronous Python
coverage. Local builds and tests were intentionally skipped as
requested.
|
||
|
|
e61252f4dc |
feat(python): capture Arrow and structured Function globals (#5044)
Function source packaging inlined only scalar literals and tuples of
them. A module-level PyArrow type shared by `output_schema=` and the
Function body, a label map, or a small NumPy weight vector failed at
decoration with an "unsupported global value" error and had to be
redefined inside the body. These globals are now captured:
```python
import numpy as np
import pyarrow as pa
from lancedb import function
OUT_TYPE = pa.struct([pa.field("label", pa.string()), pa.field("score", pa.int32())])
LABELS = {"pick": 0, "place": 1}
WEIGHTS = np.array([0.25, 0.75])
@function(
input_schema=pa.schema([pa.field("x", pa.int64(), nullable=False)]),
output_schema=pa.field("out", OUT_TYPE, nullable=False),
pip=["numpy"],
)
def judge(x: pa.Array) -> pa.Array:
score = int(WEIGHTS.sum() * 10)
rows = [{"label": "pick", "score": LABELS["pick"] + score}] * len(x)
return pa.array(rows, type=OUT_TYPE)
```
| Captured global | Rebuilt in the artifact as |
| --- | --- |
| `None`, `bool`, `int`, `str`, `bytes`, finite `float` | a literal
(unchanged) |
| tuple, list, dict, set, frozenset of supported values | a literal;
dicts keep insertion order, set elements are sorted by their source |
| PyArrow `DataType`, `Field`, `Schema` | `pa.ipc.read_schema` over the
value's IPC schema bytes, which keeps nullability, metadata, and nested
fields |
| NumPy array or scalar of a bool, integer, float16, float32, or float64
dtype | `np.array(<elements>, dtype=<dtype.str>)` or
`np.dtype(<dtype.str>).type(<item>)` |
- Each value is a copy taken when the decorator runs and rebuilt per
worker process, so values that share an object become separate copies.
Packaging does not depend on hash randomization.
- Each value is limited to 1 MiB of source and 32 levels of nesting.
Cycles and Python-defined Arrow extension types are rejected. The size
limit also applies to the existing literal captures.
- Unsupported values keep the error that names the global, its type, the
supported captures, and the remedy.
- `pyarrow` and `numpy` are imported under private aliases ahead of the
captured globals. The builtins used for empty sets and frozensets are
claimed, so a module that rebinds them fails packaging instead of
silently shadowing them.
Empty NumPy arrays are encoded directly from dtype and shape, so even
`(500_000, 0)` stays compact without expanding nested Python lists.
|
||
|
|
c7d972fe48 |
fix(python): explain blob descriptor copy guidance (#5060)
The descriptor-copy error only named the missing `data`/`uri` child. It now says that this shape is an SDK blob descriptor rather than payload bytes, and points to `blob_mode="bytes"` for supported materialization, `blob_mode="descriptions"` for inspection, and the row-id plus `fetch_blobs`/`fetch_blob_files` copy path while the source stays unchanged. This reuses the merged guidance from #4940 and the direct-materialization contract from #4973. Ray integration remains out of scope for ENT-3556. Refs ENT-3556 Test: `python/tests/test_blob.py` (210 passed, 39 skipped), including a regression that writes default lazy descriptor rows into a blob-schema table, checks the guidance, and confirms no target is created. `python/tests/test_util.py -k blob` (12 passed, 2 skipped). |
||
|
|
3aed07c396 |
fix(python): show Function registration progress and image details (#5040)
Report registration lifecycle and client elapsed time through existing job handles, and provide concise image inspection. Preserve quiet wait behavior, environment-lock forwarding, failure diagnostics and timeout recovery. |
||
|
|
1feec84d2b |
feat(python): expose FTS operators and match counts (#5042)
String full-text searches now accept `operator="AND"` or
`operator="OR"`, preserving the existing OR default. Sync and async FTS
builders expose `count_rows()` to count every match satisfying the
filter, independently of pagination, projection, ordering, and
reranking. Counting streams matching scores without reading document
columns; it can scan all matches.
```python
query = table.search("gripper closed", query_type="fts", operator="AND")
query = query.where("active = true")
matching_rows = query.count_rows()
page = query.limit(20).to_list()
query = await async_table.search("gripper closed", query_type="fts", operator="AND")
matching_rows = await query.where("active = true").count_rows()
```
Phrase searches keep the existing index default and now explain how to
rebuild an index with `FTS(with_position=True)`. AND requests retain
their operator through namespace pushdown and fail explicitly on older
remote servers that cannot represent it. Regression coverage includes
indexed and unindexed queries, filtered counts above the default limit,
pagination preservation, remote serialization, and phrase indexes with
and without positions.
|
||
|
|
f17a07a2cd |
feat: expose server-side job listing filters (#5041)
Expose server-side job filters and lazy Listing indexing, slicing, and length helpers. Document cache, cursor, and SDK/server compatibility behavior. |
||
|
|
e8a8dd1b2a |
feat(sql): use server-issued catalog listing tokens (#5026)
Migrates SQL-backed catalog listing APIs to `LIMIT ... FROM '<page-token>'` and server-issued Arrow continuation metadata. Namespace-specific APIs send an explicit `IN` schema clause, including `IN "public"` for root, so raw SQL can default to all namespaces. ```sql SHOW VIEWS LIMIT 100; SHOW VIEWS IN team$ml LIMIT 100; SHOW VIEWS IN team$ml LIMIT 100 FROM '<page-token>'; SHOW VIEWS IN other_db.team$ml LIMIT 100; ``` SDK clients forward opaque tokens unchanged, preserve empty continuations, and decode identifier columns by name. Removes legacy cursor reconstruction and updates the SQL reference and Python Flight fixture. Public docs cover optional direct schema paths, all-namespace defaults, and the shared pagination syntax across every catalog listing. |
||
|
|
e2f836da99 |
feat: expose per-call merge retry controls in Python and Node (#5015)
Python and Node callers could not disable precommit retries for one
merge without changing the connection. Add `execute(..., retries=0)` for
Python sync/async and `execute(data, { retries: 0 })` for TypeScript,
forwarding into the existing Rust control without persisting the
override. Ambiguous 5xx outcomes remain non-replayable; permitted merge
retries now log status and attempt at WARN, and the API docs explain
retry budgets and timeout boundaries.
Validation at `6001300` passed 70 Python HTTP cases, 36 Node HTTP cases,
14 local merge regressions per binding, and 34 scoped Rust tests, with
rebuilt native extensions, TypeScript compilation, Clippy, scoped
formatting/lint, and generated API docs. The public API and feature diff
are unchanged after integrating main and the reviewed ingestion guide;
that binding evidence is retained. Focused merged-tree validation
additionally passed 267 Rust merge/retry/provenance cases and the CI
fixtures. Existing root Ruff issues in docs/web-tests remain; local
fixtures do not establish live proxy/server cancellation behavior.
Refs #4256 and OSS-2370.
|
||
|
|
dc9eb269b1 |
feat(python): support map and decimal Function signatures (#5031)
Python Function declarations reject Arrow map and decimal types before registration. Accept `dict[str, T]`, nullable map values, explicit Arrow maps, and `Annotated[Decimal, pa.decimal128/256(...)]` using the existing canonical JSON representation. Preserve map key/value nullability and decimal precision/scale; reject unsupported map keys, sorted maps, nested Blob values, and a bare Decimal without precision/scale. This is the SDK map/decimal portion of ENT-3414. Server validation and SQL support are separate changes; older servers can still reject these signatures. Nullable scalar output support remains separate in #5030. Validation: 129 Function signature tests passed; 30 documentation tests passed with one existing skip. Ruff format/lint and diff checks passed. Python tests used the existing Python 3.13 environment and prebuilt native extension with this Python source overlaid; no Rust build or remote-server execution was performed. |
||
|
|
2499342fa1 |
feat(function): expose resolved environments and fresh lock requests (#5034)
Function registration clients cannot request fresh dependency resolution or inspect the measured environment returned by the server. Add `refresh_lock=True` to Python registration and preserve the requested runtime and measured environments in Rust/Python Function version readback. Registration forwards both `exist_ok` and `refresh_lock`; defaults remain unchanged. Single-platform versions retain `resolved_environment`. Multiarchitecture versions expose `resolved_environments`, keyed by OCI `os/architecture`, and the Python `environment_report` alias. Platforms are never flattened: absent entries mean unknown measurements, while measured empty package lists remain present. Registration waits emit scalar and per-platform server warnings once per Job; catalog reads do not repeat them. Requires matching server support, including Sophon #10344 for per-platform publication. Nine focused Python source-overlay tests and 29 documentation tests passed for the additive map change; one documentation test requiring a newer native `exist_ok` binding was excluded. These checks reuse a prebuilt extension and do not establish current native integration. PR CI exercises the Rust transport/readback and Python bindings. Live multiarchitecture registration and GPU acceptance remain separate. |
||
|
|
ea59f8acb6 |
feat(python): preserve Function timestamp and duration types (#5032)
Function declarations currently reject exact timestamp and duration types. Preserve their Arrow units and timezones in canonical signature JSON, including fixed-offset timezones and nested fields. Bare `datetime` and microsecond/no-timezone declarations keep their existing representation; `timedelta` requires an explicit unit. Compound temporal signatures require the Lance Namespace decoder in https://github.com/lance-format/lance/pull/11059 and corresponding server validation support. Older readers reject these signatures; this change does not upgrade server support or dependency pins. Validation: 128 Python signature tests and 30 documentation tests passed (one skipped), using the changed Python source with an existing native extension. No Rust rebuild or end-to-end Function registration/refresh was performed. |
||
|
|
12b95b59ab |
feat(function): support literal inputs in column declarations (#5021)
Function-column declarations now preserve constants such as
`fn(video=col("mp4"), num_frames=lit(16))` without changing its Function
version. Constants travel in the application inputs; column bindings,
request input schemas, and dependency tracking contain only columns.
Changing a constant uses a new column binding rather than rebaking the
Function.
Persisted bindings with literals use metadata version 2, which older
readers reject. Column-only bindings retain version 1. Python preserves
scalar literal identity, including null and unsigned integers, and
rejects composed expressions or values outside the canonical literal
domain.
This SDK change requires matching server declaration and execution
support, after a dedicated SDK dependency update. Native validation
passed 48 Rust metadata tests, four request-transport cases and 57
rebuilt Python tests on `a42d680`; 32 pre-existing experimental tests
remained ignored. The test-assertion correction passed its exact
regression and strict Clippy on `53ff80a2`. On `993fae7d`, the three
remote metadata compatibility regressions, native Python public-export
test and strict Clippy passed. These review corrections use v3 for
unknown-version rejection, cover existing v2 literal bindings through
remote mutation guards, and export `LiteralInputBinding`. The unchanged
native implementation and verified extension are reused. Matching server
execution and original-workload acceptance are not established by this
PR.
Refs ENT-3667.
|
||
|
|
f6f8119ba4 |
feat: expose structured Function refresh options in SDKs (#5047)
## Problem ENT-3267 still lacks typed refresh controls for `supervisor_resources` and `planning_workers` in Python, Rust, and Node, and Node has no `retry_policy` refresh option. Callers must drop to SQL for those controls. ## Change - Add canonical Rust `FunctionRefreshPodResources` and `FunctionRefreshPlanningConfig`, and serialize them through `RefreshColumnOptions`. - Expose both options in the Python sync/async wrappers and PyO3 binding. - Expose both options in the Node NAPI object and add a Node `retryPolicy` object backed by the existing Rust `FunctionRetryPolicy`. - Omitted options stay omitted; branch targeting continues through the table handle. No server, dependency, or pin changes are included. Client-side checks only reject non-positive structural values. Deployment resource limits and column-kind validation remain server-side. ## Validation `cargo fmt --all -- --check`, `python3 -m py_compile`, and `git diff --check` pass. No native build was run locally; CI compiles and tests the change. Generated JS API pages are unchanged. |