mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
38573202026104f49c8c971383859c2f85212f42
1827
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
3857320202 |
perf(python): avoid redundant output_schema planning and eager-path bypass in to_pandas (#5361)
### Summary & Reasoning Embedded Python `to_pandas()` previously incurred three avoidable bottlenecks on tables without blob columns: 1. **Unconditional `output_schema()` re-planning**: Both sync and async `to_pandas()` invoked `output_schema()` before execution, running the full Rust/DataFusion physical query planner (`create_plan()` — dataset lookup, row count, SQL/subquery prep, index loading, plan construction) only to discard the plan and build it a second time. For sync queries, `_output_schema()` also hopped across `LOOP.run(...)`, bypassing the direct `execute_to_reader_sync` fast path. 2. **Async eager-collector bypass**: `AsyncQueryBase.to_pandas()` rewrote the default `blob_mode="lazy"` to `"descriptions"`, causing `to_arrow()` to skip `#5127`'s native eager collector (`execute_to_reader`) and fall back to per-batch `to_batches()` streaming (1,024-row slicing and one Python future per batch). Sync `LanceTakeQueryBuilder.to_pandas()` hit the same path via `BaseQueryBuilder`. 3. **Redundant `table.schema` fetches and `to_query_request()` vector FFI clones**: Blob row-id and source checks cloned query requests across FFI and fetched `table.schema` multiple times per execution (2x on non-hybrid, 4x-5x on hybrid / WAL-PK tables) even when the table schema contained no blob columns or `with_row_id()` was already set. ### Chosen Direction & Trade-Offs - **Schema-gated fast path**: `schema_has_blob_field(table_schema)` matches strictly schema-declared blob columns (including nested structs and lists), so a query over a non-blob table cannot produce blob output fields. Fetching `table_schema` once and gating `output_schema()` and `blob_mode` rewrites on it avoids double planning, keeps non-blob `to_pandas()` and `to_arrow(blob_mode="descriptions"|"bytes")` on the eager collector, and brings execution down to a single schema fetch (including across hybrid child legs and WAL-PK retries). - **Conservative on blob tables & unbound queries**: Tables containing blob columns still run `output_schema()` so projected/quoted/nested blob edge cases keep identical behavior (while reusing the pre-fetched schema to avoid extra schema fetches). Unbound `AsyncQueryBase` (`table=None`) keeps the conservative fallback. - **Preserving overrides & monkeypatches**: Internal schema-threaded helpers are only entered when built-in `to_arrow`/`to_batches` methods have not been overridden or monkeypatched (including hybrid child legs), so custom subclasses without `blob_mode` and test spies behave identically. - **Enterprise tables**: Early Enterprise execution paths are unchanged (preserving zero extra schema requests in `"lazy"` mode and existing `_blob_paths` / snapshot behavior). - **Out of scope**: Skipping `output_schema()` when a query on a blob table projects only non-blob columns, and Rust-side `create_plan()` optimizations. ### Benchmarks Measured on **AMD Ryzen 9 7950X3D**, runner and child processes pinned to **CCD0 (`ProcessorAffinity = 0xFFFF`, logical CPUs 0-15, verified via `GetProcessAffinityMask`)**, interleaved **`A -> B -> B -> A`** cells on shared datasets and the exact same compiled `_lancedb.pyd` extension (`A` = `c3f005f7`, `B` = patched): | Workload | Baseline `A` (med / p95) | Candidate `B` (med / p95) | Speedup | Per-cell medians (`A1, B1, B2, A2`) | | :--- | ---: | ---: | ---: | :--- | | Sync indexed vector `10k x 128d` `limit(10)` (`n=100`/cell) | `6.541 ms` / `6.834 ms` | `5.196 ms` / `5.439 ms` | **1.26x (-20.6%)** | `6.627, 5.148, 5.249, 6.464 ms` | | Async indexed vector `10k x 128d` `limit(10)` (`n=100`/cell) | `6.835 ms` / `8.063 ms` | `5.358 ms` / `5.632 ms` | **1.28x (-21.6%)** | `6.924, 5.323, 5.410, 6.790 ms` | | Sync scan `500k x 3` (`n=10`/cell) | `11.027 ms` / `11.901 ms` | `9.543 ms` / `10.253 ms` | **1.16x (-13.5%)** | `10.769, 9.452, 9.591, 11.134 ms` | | Async scan `500k x 3` (`n=10`/cell) | `152.783 ms` / `154.980 ms` | `9.447 ms` / `9.817 ms` | **16.17x (-93.8%)** | `151.034, 9.602, 9.431, 154.107 ms` | ### Verification - **Executed on Windows host**: - Targeted pytest suite (11 files covering sync direct, eager collector, query, blob, blob-without-pylance, hybrid, WAL hybrid, FTS wand factor, Enterprise `test_remote_db.py`, namespace, and table tests): **2,150 passed, 0 failed, 21 skipped** (0 missing-`pandas`/`pylance` skips; skips limited to Linux `sched_setaffinity`/`fork`, optional `av`/`torch`, and `experimental_functions`). - No-`pandas` / no-`pylance` parity check (blocking `pandas` and `lance` imports on `test_sync_query_direct.py`, `test_eager_collector.py`, `test_wal_hybrid.py`): **21 passed, 0 failed, 6 skipped**. - Doctests on `python/lancedb/query.py`: **23 passed, 0 failed**. - `ruff==0.9.9 format --check .` and `ruff==0.9.9 check .`: passed. - `pyright --pythonplatform Linux`: 0 errors; diff-scoped `pyright` on `python/lancedb/query.py`: 0 errors across all changed lines. - `typos` on all modified files: passed. - **Pending CI**: Full cross-platform Python matrix (Linux/macOS/Windows), Linux-only `sched_setaffinity`/`fork` tests, and CI commitlint/license-header workflows. --------- Co-authored-by: Xuanwo <github@xuanwo.io> |
||
|
|
3d765d3729 |
fix(python): skip null and empty texts in Gemini text embeddings (#5369)
## Summary
A table with a `gemini-text` embedding function can contain rows whose
source text is null or empty. `GeminiText.generate_embeddings` built a
`{"parts": [{"text": None}]}` content entry for each of them and sent it
to `embed_content`, so a single missing text could fail the request for
the whole batch.
Skip null and empty texts before building the request, as #5233 does for
Ollama and #4919 for Bedrock. Embed only the remaining texts and put
each embedding back at its original position, so a skipped row gets
`None` while the other rows keep their vectors. When every text is null
or empty, return `None` for each without calling the API. If the service
returns a different number of embeddings than texts sent, raise a
`ValueError` instead of misaligning rows.
The optional L2 normalization for truncated `gemini-embedding-001`
vectors still runs on the returned embeddings only.
## Verification
- Added `test_source_embeddings_skip_null_and_empty_texts` to
`tests/test_gemini_text_embeddings.py`, using the file's existing
`fake_genai` fixture:
- `["a", None, "", "b"]`: only `["a", "b"]` is sent, and the result is
`[vec_a, None, None, vec_b]`;
- `[None, ""]`: no request is sent and the result is `[None, None]`.
- With `main`'s `gemini_text.py`, the new test fails and the existing 8
tests pass; with this change, all 9 pass. I ran the file against LanceDB
0.42.1 with `main`'s and then the changed `gemini_text.py` copied over
the installed module. I did not call the live Gemini API.
- Repository Ruff lint and format checks pass.
|
||
|
|
feff86a08d |
feat(query): stream query results with optional total hits (#5354)
## Summary An Embedded query can stream one page of results and report how many visible rows matched before offset and limit. This adds Rust `execute_with_metadata`, Python sync and async `to_result`, and TypeScript `toResult`. The existing query terminals continue to use their existing execution paths. Tracking defaults to Off. An exact count returns `eq(N)`. A positive cap C returns `eq(N)` below C and `gte(C)` as soon as C matches are proven, including equality. TypeScript exposes counts as bigint. Counts use the same snapshot as the result batches. The accessor reports pending until the stream reaches successful EOF. Explicit counts can add work after the last batch, especially when full-text counting needs to scan visible text. Closing an unfinished result cancels execution. Stream and metadata failures retain interruption details, including the request ID. Embedded supports scalar and row-level lexical counts. Unordered FTS retains its existing top-k and scoring policy. Enterprise and unsupported query shapes return a typed error when a count is requested. ## Dependency #5352 merged Lance v16.0.0-beta.7 into main, including [Lance #11680](https://github.com/lance-format/lance/pull/11680). This PR uses that dependency and its lockfiles. ## Validation The Linux-tested revision `bc39ad7ac` and rebased revision `24f4e90c2` have the same Git tree. The only change in `6932b3082` is the Python namespace regression fixture, which now resolves the local table without the optional pylance package. The revised test passed on managed Linux with CPython 3.11.18 both with pylance and pandas installed and after removing both packages. Managed Linux runs used the unmodified manifests and lockfiles from #5352 and the published `pylance 16.0.0b7` wheel. - The Rust metadata suite passed 57 tests, with two existing ignores. Coverage includes unordered FTS plans, top-k scores, physical row addresses under pagination, pending-read cancellation, and interruption after the last batch. - Python query, remote and namespace suites passed 1,163 tests. One optional slow test requires PyTorch, which was unavailable on this VM. The Node query, remote, table and error suites passed 913 tests, with three experimental cases skipped. - Regression tests reproduced the failures on the previous revision and verified the fixes. Python sync reranking and namespace FTS preserve an explicit empty page. Python sync and async scans expose `_rowaddr` alongside the pre-pagination count. Explicit counts are rejected before TypeScript auto-search issues an Enterprise request or invokes a vector embedding provider. Python and Node retain the server's 1,063-row first batch in Off mode. - A custom Python namespace opened through the public API receives the same computed projection in Off mode as with `to_batches()`. A Node result interrupted after another SDK load retains its original error class and request ID. Both regressions were reproduced on the prior revision. - Workspace Clippy, formatting, Ruff, Biome, TypeScript checks, TypeDoc and strict MkDocs passed. All 287 generated TypeDoc files matched the committed files byte for byte. |
||
|
|
d87b721604 |
fix(python): support legacy StringView JSON writes (#5357)
PyArrow 16.1 is in the Python SDK's supported range and cannot cast `StringView` to UTF-8. For a JSON column, sanitized `add()` and `merge_insert()` fail at that cast before Lance can encode the input as JSONB. Convert top-level JSON `StringView` columns at the shared Python cast boundary. Use Arrow's cast when available and materialize UTF-8 values when the kernel is missing. The aligned column carries `arrow.json` metadata and preserves nulls. Both write regressions fail on PyArrow 16.1 before the fix and pass after it. They consume multiple batches and verify JSON queries after reopening. The RTE JSON upsert regression also exercises `StringView` input. This carries forward [LH-kevin’s fix](https://github.com/lancedb/lancedb/commit/481e13d95c3471c80a781ba4e0b21004afbb246b). Related to #4038 and #4035. Co-authored-by: LH-kevin <186923068+LH-kevin@users.noreply.github.com> --------- Co-authored-by: LH-kevin <186923068+LH-kevin@users.noreply.github.com> |
||
|
|
0a14761f0e |
feat(python): open blob files by row offset (#5356)
Open seekable Blob files by row position with `table.take_blob_files(column, offsets, *, buffer_size=None)` on synchronous and asynchronous Embedded and Enterprise tables. Results follow the requested order, duplicate offsets have independent cursors, and NULL and empty values stay distinct. An invalid offset rejects the entire batch. Enterprise resolves positions and descriptors together and verifies one snapshot across descriptor queries, location resolution, and authenticated byte reads. Eligible ranges use the existing presigned read path when the gateway advertises it. Refs [OSS-2881](https://linear.app/lancedb/issue/OSS-2881). ## Validation - On Enterprise 1.16.0, the same locked wheel passed both sync and async reads of 1,025 distinct offsets after a deletion. The offsets matched an independent ordered query, and the two descriptor chunks and subsequent authenticated requests matched the pinned version and snapshot identity. - Both APIs returned byte-for-byte matches for 37-byte proxy reads and a 32 MiB presigned object-store read. The large reads used zero gateway byte requests. An independent range check returned two object-store HTTP 206 responses with matching physical ranges and bytes. - The wheel passed 23 focused Python tests. The Rust library check and all 81 Enterprise Blob module tests passed, including nested NULL and strict snapshot echo cases. Runtime evidence is from commit `f56c359ba7874cd75c52169491166a941251510f` with Lance `16.0.0-beta.6`, wheel SHA-256 `9abbbfe584513432547d237dcf7b684b479b35cad07c48cd9899d381f0e80423`. The merge preview with `main` at `ff556729` is clean. [#5352](https://github.com/lancedb/lancedb/pull/5352) updates the integration dependencies to Lance `16.0.0-beta.7` and `object_store` `0.14.2`. Those pins are outside the tested wheel's coverage. The synthetic test table was removed from the catalog. Its physical storage cleanup is tracked separately. |
||
|
|
eea95c8778 |
feat(python): support SigLIP image search with OpenCLIP (#5355)
## Summary - Use the existing OpenCLIP provider with the SigLIP SO400M checkpoint to embed image files and search them from Python. - Accept filesystem path objects for vector queries and preserve Windows drive letters and special characters in image ingestion paths. String queries continue to use the text encoder. - Add sync and async regression tests and a generated, runnable documentation example. Refs #4767 ## Validation - Embedding suite with 122 passing tests, CI-pinned Ruff, Linux-targeted Pyright, and strict MkDocs. - The real SigLIP checkpoint returned 1,152-dimensional unit-normalized vectors and ranked the matching image first. The Windows smoke test used the non-mapped safetensors reader and one shared model instance. - Five row-address tests also failed with the preview native extension on the unmodified base. The source-built CI run will cover these tests. |
||
|
|
c85647526c |
fix: encode JSON in RTE merge_insert (#5353)
Unsharded RTE `merge_insert` reaches the shard writer with JSON text,
which fails the writer’s `LargeBinary` schema check. Encode Arrow JSON
with Lance’s JSONB converter before schema alignment so plain JSON text
and `arrow.json` can both be upserted. Require an explicit JSON
extension on binary input before schema alignment can attach the
destination’s JSONB metadata.
The Python regression tests query the updated and inserted rows after
reopening the table and verify that invalid JSON and unmarked binary
writes leave the existing data intact. Overwrite tests cover schema
replacement in both directions between plain Arrow strings and typed
JSON.
PyArrow 16.1 still raises `Unsupported cast from string_view to utf8`
for `StringView` input on sanitized append and merge paths. Ordinary
UTF-8 RTE upserts and default Arrow append with `StringView` pass on
that version.
The RTE conversion and regression build on LH-kevin’s
[
|
||
|
|
ff556729ab |
chore: update lance dependency to v16.0.0-beta.7 (#5352)
Update the Rust and Java Lance dependencies to [v16.0.0-beta.7](https://github.com/lance-format/lance/releases/tag/v16.0.0-beta.7) and pin Python tests to pylance 16.0.0b7. Use the published object_store 0.14.2 release to match Lance's multipart API. |
||
|
|
b5f35d5c56 |
fix: honor Enterprise query batch size limits (#5350)
Enterprise queries could return Arrow batches larger than the size explicitly requested by the caller. The SDK now slices oversized batches in the final query stream and keeps server-selected batch sizes when the caller omits the limit or passes zero. The search guide shows how to stream a full table or filtered scan in one query using Python's `search().to_batches()`. It covers older deployments that return buffered Arrow IPC files or enforce a query row cap. A local Enterprise 1.16.0 probe streamed all 131,073 rows from a pinned snapshot in one query, with batches of at most 37 rows and the first batch available before the Arrow end-of-stream marker. The probe ran with Plan Executor enabled and disabled. Related to OSS-3133. |
||
|
|
53a8c6973c |
fix(python): return optimize stats from sync table and forward compaction options (#4830)
## Summary This PR fixes return value and argument forwarding inconsistencies in the Python `Table.optimize()` implementation: 1. `LanceTable.optimize()` now returns `OptimizeStats` produced by the underlying optimization process, matching `AsyncTable.optimize()` behavior. Previously, the return value was dropped by `LOOP.run(...)`, causing `table.optimize()` to always return `None`. 2. `Table.optimize` (abstract base class), `LanceTable.optimize`, and `RemoteTable.optimize` now annotate `-> OptimizeStats` return types. 3. `RemoteTable.optimize()` now properly forwards `compaction_options` to the underlying table optimize handle. Previously, `compaction_options` was accepted in the method signature but omitted in the delegation call. Refs #4397. ## Root Cause & Problem - In `python/python/lancedb/table.py`, `LanceTable.optimize()` called `LOOP.run(self._table._do_optimize(...))` as a standalone statement without a `return`. Because `LOOP.run` returns the result of the coroutine, callers of synchronous `table.optimize()` received `None` even though compaction and prune statistics (`OptimizeStats`) were generated. - In `python/python/lancedb/remote/table.py`, `RemoteTable.optimize()` accepted `compaction_options: Optional[CompactionOptions] = None` in its method definition, but the call to `self._table.optimize()` omitted `compaction_options=compaction_options`. - In `Table` (ABC), `optimize()` was missing return type annotations, preventing type checkers from inferring `OptimizeStats`. ## Technical Solution - Updated `LanceTable.optimize()` in `python/python/lancedb/table.py` to `return LOOP.run(...)` and added the return type annotation `-> OptimizeStats:`. - Added `-> OptimizeStats:` return type annotation to `Table.optimize()` in `python/python/lancedb/table.py`. - Updated `RemoteTable.optimize()` in `python/python/lancedb/remote/table.py` to forward `compaction_options=compaction_options` to `self._table.optimize(...)` and added `-> OptimizeStats:` return type annotation. - Added `OptimizeStats` to `TYPE_CHECKING` imports in `python/python/lancedb/remote/table.py`. - Added regression tests in `test_table_signatures.py` to verify argument forwarding (`compaction_options`) and stats return on both local and remote tables. - Updated `test_sync_optimize` and `test_sync_optimize_in_async` in `test_table.py` to assert that non-None `OptimizeStats` containing compaction and prune stats are returned. ## Test Plan - Focused signature and argument forwarding test suite: Ran `pytest python/tests/test_table_signatures.py` (40 passed in 5.05s). - Focused sync and async optimize test suite: Ran `pytest python/tests/test_table.py -k "test_sync_optimize"` (2 passed in 3.30s). Ran `pytest python/tests/test_table.py -k "test_optimize"` (25 passed in 7.69s). - Linting and formatting: Ran `ruff check` on modified files (passed with 0 errors). Ran `ruff format --check` on modified files (passed with 4 files formatted). |
||
|
|
50c66c66d5 |
fix(python): return row addresses from embedded scans (#5344)
## Problem Embedded Python queries accept `with_row_address()`, but ordinary sync and async scans omit `_rowaddr`. ## Fix Pass the existing option to the Lance scanner for Embedded base-table scans. Embedded namespace queries that request addresses use the Embedded scanner. An RTE scan reports that addresses require `use_rte(False)` to read the base table. ## Validation The two-fragment tests verify sync batches and async Arrow results, `uint64` physical addresses, projection, and default and explicit disabling. Stable row IDs confirm that `_rowaddr` is distinct from `_rowid`. Additional tests cover namespace routing, RTE and vector/FTS builder conversion. All applicable checks passed for `64dd3c0e`. The baseline test run stopped at the `stats()` fixture and did not reach the query assertions. Tracks OSS-2972. |
||
|
|
16c934a827 |
docs(python): document single-commit RecordBatchReader appends (#5349)
Python callers can pass a `pyarrow.RecordBatchReader` to `add()` to commit multiple batches as one table version. The insert guide shows the synchronous and asynchronous calls, when to use separate calls for independently acknowledged flushes, and the server protocol and catalog requirements for Enterprise multipart uploads. Both examples advanced the table by one version on the Enterprise 1.16.0 directory and manifest catalogs with Python SDK 0.42.1. |
||
|
|
585e598092 | Bump version: 0.43.0-beta.0 → 0.43.0-beta.1 | ||
|
|
9b3398e31b |
fix(python): skip null texts when reranking with AssetFeed (#5346)
## Summary A vector, full-text, or hybrid search can return rows whose reranking text column is ull. AssetFeedReranker._rerank currently forwards None values inside the JSON documents list to the AssetFeed rerank API, which rejects or misaligns results when null texts are present, still makes an HTTP request when every candidate text is ull, and counts null rows against MAX_DOCUMENTS = 100. This aligns AssetFeedReranker with the existing null-filtering pattern in #5283 (Cohere), #5296 (Jina), #5336 (VoyageAI), and #5337 (watsonx.ai): - Filter out rows where esult_set[self.column] is null before self._handle_empty_results(result_set) and MAX_DOCUMENTS validation, so returned AssetFeed result indices select the exact matching rows and keep all original columns. - Return an empty loat32-scored result table without calling the AssetFeed API when all candidate rows have null text. - Document in AssetFeedReranker that rows with null values in column are omitted from the reranked results. ## Verification - Added unit tests in python/python/tests/test_assetfeed_reranker.py: - est_nullable_documents (["first document", None, "last document"] and [None, None, None]): verifies only non-null strings are sent, row IDs/scores/_distance/ loat32 _relevance_score align cleanly, and all-null inputs skip the HTTP request. - est_null_documents_excluded_before_max_documents_check: verifies 100 valid documents plus 1 null row pass MAX_DOCUMENTS validation after null filtering. - Ran pytest -o addopts="" --noconftest -v python/python/tests/test_assetfeed_reranker.py on Python 3.11.18 + PyArrow 26.0.1 (15 passed in 1.16s with lancedb._lancedb stubbed in the scratch test runner because Windows Application Control on the local test machine blocks the unsigned native Rust .pyd binary; mocked HTTP session, no live AssetFeed API calls). - Verified uff check and uff format --check pass cleanly on both changed files. |
||
|
|
5373da5760 |
fix: explain Flight SQL endpoint errors during function registration (#5342)
## Summary Function registration uses Flight SQL. If the SDK has no usable SQL URI or cannot establish a connection, it points to the cluster’s published Flight SQL URI and the Public SQL or PrivateLink SQL settings. The diagnostic retains the original exception type, cause text, and request ID when present. ## Validation - Built main (`0abc7d48`) and the SDK change (`4bfdbb217`) in the same isolated Linux VM with the locked Python environment. The final commit updates only the test assertion for platform-dependent connection errors. - Compared 22 calls against a healthy HTTPS REST fixture and Flight endpoints. The expected five registration failures gained the hint. After accounting for request IDs, all original errors and successful results matched. - New regression tests on main had two expected failures and three passing controls. The SDK change passed 86 tests with 16 skipped across registration, Function catalog, SQL, and view creation. Rust formatting and Ruff passed. - All 50 GitHub checks passed on `7c2dad8bc`, including the [Python workflow](https://github.com/lancedb/lancedb/actions/runs/46796061600) and the [Rust macOS 26 rerun](https://github.com/lancedb/lancedb/actions/runs/46796061943/job/143185732469). |
||
|
|
9bdb1b7219 |
fix(python): honor bad-vector policies for inferred vector columns (#5243)
Fixes #5241 ## Summary Python inferred fixed-size vectors from names such as `text_embedding`, but the bad-vector sanitizer used a narrower naming rule. Ragged rows could reach Arrow and fail the cast, and schema inference could accept an `embedding` row containing NaN. Use the schema-inference name check when selecting floating-point vectors for sanitization. When a target schema exists, apply the expanded naming rule to fixed-size lists so an explicitly variable-length column such as `embedding_history` keeps its list semantics. Creation now rejects NaNs in these inferred vectors under the default `error` policy. The `drop`, `fill`, and `null` policies handle them during creation, append, and overwrite. The four streaming bad-vector policy regression cases come from [#5003](https://github.com/lancedb/lancedb/pull/5003). Fixes #5241. ## Testing Tests: `/bin/sh -c 'cd python && PYTHONPATH=python UV_PROJECT_ENVIRONMENT=/tmp/osscout-lancedb-venv uv run --no-sync pytest python/tests/test_table.py -k bad_vectors_in_name_inferred_columns -q --tb=short'`. Result: Existing related tests on base, cd python && PYTHONPATH=python UV_PROJECT_ENVIRONMENT=/tmp/osscout-lancedb-venv uv run --no-sync pytest python/tests/test_table.py -k 'bad_vectors or with_nans or null_elements or empty_fixed_size_list or integer_embeddings or infer' -q — exit 0, 75 passed, 501 deselected in 1.18s. Result: Base regression, cd python && PYTHONPATH=python UV_PROJECT_ENVIRONMENT=/tmp/osscout-lancedb-venv uv run --no-sync pytest python/tests/test_table.py -k bad_vectors_in_name_inferred_columns -q --tb=short — exit 1, 19 failed, 9 passed, 576 deselected in 5.29s. The nine default vector controls passed. Output is in OSSCOUT_BASE.log. Result: Patched regression, cd python && PYTHONPATH=python UV_PROJECT_ENVIRONMENT=/tmp/osscout-lancedb-venv uv run --no-sync pytest python/tests/test_table.py -k bad_vectors_in_name_inferred_columns -q --tb=short — exit 0, 28 passed, 576 deselected in 0.54s. Output is in OSSCOUT_PATCHED.log. Result: Patched affected modules, cd python && PYTHONPATH=python UV_PROJECT_ENVIRONMENT=/tmp/osscout-lancedb-venv uv run --no-sync pytest python/tests/test_table.py python/tests/test_util.py python/tests/test_embeddings.py -m 'not slow and not s3_test' -q --tb=short — exit 0, 822 passed, 19 skipped, 8 deselected, 32 warnings in 15.11s. Result: Patched namespace creation checks, cd python && PYTHONPATH=python UV_PROJECT_ENVIRONMENT=/tmp/osscout-lancedb-venv uv run --no-sync pytest python/tests/test_namespace.py -k create_table -m 'not slow and not s3_test' -q --tb=short — exit 0, 5 passed, 89 deselected, 4 warnings in 0.20s. Result: From the repository root, /tmp/osscout-lancedb-venv/bin/ruff format python/python/lancedb/table.py python/python/tests/test_table.py left both files unchanged. /tmp/osscout-lancedb-venv/bin/ruff check python passed. Result: From the repository root, /tmp/osscout-lancedb-venv/bin/ruff format --check . and /tmp/osscout-lancedb-venv/bin/ruff check . --output-format concise flagged six files for reformatting and 59 lint findings, respectively, all under unchanged docs/web-tests paths. Result: git diff --check passed. Regression coverage: `python/python/tests/test_table.py`. <!-- oss-scout-job:job-f4fee21f-9051-4409-b66f-195dad93a5df --> --------- Signed-off-by: wangshun <96341168+xixi-box@users.noreply.github.com> Co-authored-by: Xuanwo <github@xuanwo.io> Co-authored-by: Aditya Gupta <84338325+MaiAditya@users.noreply.github.com> |
||
|
|
c3f005f7ff |
fix(python): skip null texts when reranking with watsonx.ai (#5337)
## Summary A vector, full-text or hybrid search can return a row whose reranking text is null. `WatsonxReranker` sent that null in the `inputs` list it passes to `Rerank.generate`, although watsonx.ai reranks a list of strings, so one row with missing text broke reranking for every other row. Filter rows with null text out of the Arrow table before building the request, so the indices watsonx.ai returns still select the right rows and keep their original columns. When every candidate has null text, return an empty scored table without calling the API. The class docstring now says that rows with a null `column` value are left out of the reranked results. This is the same change as #5283 (Cohere) and #5296 (Jina), applied to the watsonx.ai reranker. [watsonx.ai text rerank API](https://cloud.ibm.com/apidocs/watsonx-ai#text-rerank) ## Verification - Added `test_watsonx_reranker_nullable_documents`, run through a real local table and `table.search(...).rerank(...)`, with two cases: - a null between two valid documents, where the mocked client returns reordered indices: only the two valid texts are sent, and the result keeps the correct row IDs, scores, `_distance` column and `float32` `_relevance_score`; - all-null input, where the client is never called and an empty typed result comes back. - Both cases fail on `main` and pass with this change. - Ran against LanceDB 0.42.1 with the changed reranker module copied over the installed one. The installed `watsonx.py` is identical to `main`. I did not call the live watsonx.ai API. - Repository Ruff lint and format checks pass. |
||
|
|
c5a67c3d78 |
fix(python): skip null texts when reranking with VoyageAI (#5336)
## Summary A vector, full-text or hybrid search can return a row whose reranking text is null. `VoyageAIReranker` sent that null in its `documents` list, although the Voyage rerank API takes a list of strings, so one row with missing text broke reranking for every other row. Filter rows with null text out of the Arrow table before building the request, so the indices Voyage returns still select the right rows and keep their original columns. When every candidate has null text, return an empty scored table without calling the API. The class docstring now says that rows with a null `column` value are left out of the reranked results. This is the same change as #5283 (Cohere) and #5296 (Jina), applied to the VoyageAI reranker. [Voyage AI reranker API](https://docs.voyageai.com/reference/reranker-api) ## Verification - Added `test_voyageai_reranker_nullable_documents`, run through a real local table and `table.search(...).rerank(...)`, with two cases: - a null between two valid documents, where the mocked client returns reordered indices: only the two valid texts are sent, and the result keeps the correct row IDs, scores, `_distance` column and `float32` `_relevance_score`; - all-null input, where the client is never called and an empty typed result comes back. - Both cases fail on `main` and pass with this change. - Ran against LanceDB 0.42.1 with the changed reranker module copied over the installed one. The installed `voyageai.py` is identical to `main`. I did not call the live Voyage API. - Repository Ruff lint and format checks pass. |
||
|
|
193c9d8e2e |
docs: fail docs build on warnings (#3707)
## Summary - run the existing MkDocs deployment build in strict mode - turn documentation warnings, including unresolved references, into CI failures instead of deploying them ## Why The docs workflow currently completes when MkDocs emits warnings. Using MkDocs' built-in strict mode makes the deployment stop on those warnings and surfaces documentation problems immediately. This addresses the warning-detection portion of #572 without adding another dependency or duplicating the docs build. ## Validation - `git diff --check` - parsed `.github/workflows/docs.yml` with PyYAML - full `mkdocs build --strict` was not run locally because MkDocs is not installed; the existing docs workflow has the required dependencies --------- Co-authored-by: Will Jones <willjones127@gmail.com> Co-authored-by: Xuanwo <github@xuanwo.io> |
||
|
|
ec230318f6 |
fix: point the compaction warning at the current docs page (#4913)
Refs #4371 The link checker flags `https://docs.lancedb.com/performance#compaction-and-cleanup` because that section no longer exists. Compaction has its own page now, and its "When to run it" section (`#when`) covers the warning this link is attached to: tables with many small fragments. This points `DocLink::Compaction` at `/maintenance/compaction#when` and updates the two tests that hard-code the URL. The anchor exists on the published site and in `docs/web/maintenance/compaction.mdx`, so `test_all_doc_links_resolve_in_repo_docs` still holds. Tests: `python -m unittest ci.tests.test_extract_sdk_doc_links` and `cargo test -p lancedb --lib docs::tests::` pass locally. Co-authored-by: Xuanwo <github@xuanwo.io> |
||
|
|
2cc9cdfac4 | Bump version: 0.42.0-beta.38 → 0.43.0-beta.0 | ||
|
|
155457d0e5 |
feat(query): allow unordered vector and full-text search results (#5328)
## Summary Callers that consume every selected hit can relax the final output order with `ordered_results(false)` in Rust, `ordered_results(False)` in Python, or `orderedResults(false)` in TypeScript. Ranked output remains the default. The option preserves top-k selection, each hit’s score and projected columns, and the existing rules for ties at the cutoff. Embedded passes eligible queries to the Lance scanner. Enterprise sends `"ordered": false` for eligible searches and omits the field by default. Explicit sorting, positive offsets, batch vector queries and inputs to hybrid fusion or reranking keep their existing order. ## Validation A managed Linux preview passed 8 Rust wire cases, 4 Embedded Python cases, 10 HTTP mock cases and all 52 TypeScript query tests. The preview used a candidate Lance revision. Project CI on this PR validates the integration with the official Lance `v16.0.0-beta.6`. Uses the official Lance dependency from #5327, now merged into `main`. |
||
|
|
0da2b7b307 |
test(python): re-enable tests skipped on Windows that now pass (#5326)
Several Python tests are skipped on Windows, so the Windows CI job never
runs them. I ran them on Windows and they pass now, so this PR removes
the skips:
- `test_db.py`: the four `namespace_client` tests ("Namespace client
issues")
- `test_table.py`: `test_consistency` ("directory namespace is not
supported on Windows yet")
- `test_namespace_integration.py`:
`test_namespace_create_schema_only_with_provider`
- `docs/test_search.py`: the five FTS tests that pointed at
lancedb/lance#3905, which was closed in June 2025
Two of the `namespace_client` tests still failed on Windows, but only
because of how they checked the root. `namespace_id()` returns a Rust
debug string like `DirectoryNamespace { root: "C:\Users\..." }`, so the
backslashes are escaped and `str(tmp_path) in namespace_id()` was false.
The assertion now escapes them the same way first. On POSIX paths that
is a no-op, so the check is unchanged there.
No library code changes.
### Testing
On Windows 11, Python 3.12, with the `lancedb==0.42.1` wheel:
- The 17 re-enabled test cases pass. I ran them 6 times in a row and
they passed every time, including `test_consistency` with the 0.1 s
interval.
- Full suite (`-m "not slow and not s3_test"`): 4777 passed, 205
skipped, 0 failures.
- `ruff check` and `ruff format --check` pass.
I found this with help from Claude Code (Claude Opus 5.5) while running
the test suite on Windows. I checked each change and ran the tests
myself.
|
||
|
|
1b7537c007 |
chore: update lance dependency to v16.0.0-beta.6 (#5327)
Bump the Rust and Java Lance dependencies to [v16.0.0-beta.6](https://github.com/lance-format/lance/releases/tag/v16.0.0-beta.6) and pin Python tests to pylance 16.0.0b6. Remove four redundant Rust visibility modifiers flagged by strict Clippy. The [Java publication workflow](https://github.com/lance-format/lance/actions/runs/46611272196) completed successfully. On December 1 at 10:20 UTC, both Maven artifact URLs returned HTTP 200. The published POM declares `org.lance:lance-core:16.0.0-beta.6`, and a range request to the JAR returned its ZIP header. [POM](https://maven.lance.org/org/lance/lance-core/16.0.0-beta.6/lance-core-16.0.0-beta.6.pom) · [JAR](https://maven.lance.org/org/lance/lance-core/16.0.0-beta.6/lance-core-16.0.0-beta.6.jar) |
||
|
|
76c8bf335a |
fix: expose branch create_at and metadata in branches.list() for node and python (#4914)
Fixes #4849. **Problem** - TypeScript SDK: `Branches.list()` returned napi class instances whose fields live on the prototype, so `console.log`, spread and `JSON.stringify` showed `{}` (the exact symptom in the docs example). `create_at` and `metadata`, which Lance already stores for every branch, were not exposed at all. - Python SDK: the `Branches.list()` dicts also dropped `create_at` and `metadata`. **Change** - `nodejs/src/table.rs`: `BranchContents` stays a runtime napi class export and gains `create_at` (Unix seconds) and `metadata`, populated from the stored Lance branch contents. The `metadata` getter defines every key as an own enumerable data property (`napi_define_properties`), so keys like `__proto__` that ordinary map conversion would route to the prototype setter are preserved. - `nodejs/lancedb/table.ts`: the `Branches.list()` wrapper promotes all fields (`parentBranch`, `parentVersion`, `createAt`, `manifestSize`, `metadata`) to own enumerable properties on each returned instance by reusing the class getters and setters, so spread and `JSON.stringify` see them while `instanceof` keeps working. Its return type is `ListedBranchContents`, which guarantees `createAt` and `metadata`. - Public typing: the exported `BranchContents` type keeps its released shape (`parentBranch`/`parentVersion`/`manifestSize` only), so values and interfaces written against it stay assignable and extendable, including a view whose `createAt` is a `Date` and an interface that extends `BranchContents` with its own `metadata`. `ListedBranchContents extends BranchContents` adds `createAt` and `metadata` as required fields, and the exported `BranchContents` constructor value has its `prototype` typed as `BranchContents`, so the class value and `instanceof` checks are unchanged. - `python/src/table.rs`: `Branches.list()` dicts now include `create_at` and `metadata`. - Docs: regenerated TypeScript API reference for the new shape, and the branching guide now documents `createAt`/`create_at` (Unix seconds) and `metadata`. **Tests** - `nodejs/__test__/table.test.ts`: a branch whose stored ref file carries non-empty metadata (including a `__proto__` key) and a known creation time in Unix seconds is listed with both, as a `BranchContents` instance with own enumerable fields, surviving spread and a JSON round-trip with every metadata key intact. A second test covers the consumer type contracts with `tsc`: a released-shape value with an extra `createAt: Date` stays assignable to `BranchContents`, an interface extending `BranchContents` can declare its own `metadata` shape, the exported constructor's `prototype` is typed as `BranchContents`, and `branches.list()` results guarantee `createAt` and `metadata`. - `python/python/tests/test_table.py::test_branches`: same non-empty-metadata (with `__proto__`) and known-`create_at` coverage. - Verified locally on Linux x86_64: `tsc -b`, Biome checks, regenerated docs diff limited to the `BranchContents` pages, node branches suite (34 passed), python `test_branches` (4 passed, 1 skipped). --------- Co-authored-by: tomwangcn <tomwangcn@users.noreply.github.com> |
||
|
|
a85cb92ffd |
feat: support vector-only and FTS-only reranking (#3024)
Add rerank_vector() and rerank_fts() methods to Reranker trait, allowing rerankers to work with single search modes instead of only hybrid search. Implemented for: - RRFReranker (Rust and Python) - LinearCombinationReranker (Python) Resolves TODO at rust/lancedb/src/rerankers.rs:55 Changes: - Extended Reranker trait with default implementations - Added unit tests for new methods - Updated documentation with examples --------- Co-authored-by: Xuanwo <github@xuanwo.io> |
||
|
|
34e33ecf64 |
fix(python): preserve Arrow values when merging hybrid reranker scores (#5323)
An Embedded hybrid query using `RRFReranker(return_score="all")` can change unrelated result columns. On 0.42.1, a `time64[ns]` value of 1001 ns comes back as 1000 ns with pandas installed. A fixed-shape tensor created with `FixedShapeTensorArray.from_numpy_ndarray` raises `NotImplementedError` during the same query. Both columns round-trip with the default relevance score. The shared reranker merge converts every result row to a Python object to combine `_distance` and `_score`. This change looks up row positions by `_rowid` and takes rows and scores directly from the Arrow columns. A hit in both searches keeps the vector row and receives the FTS score. The regression tests run a hybrid search against an in-memory table and compare the returned Arrow arrays with the inputs. ### Testing - Both new cases failed before the change and passed after it. Also verified the fix with pandas uninstalled. - The two new cases and both existing rank-fusion score tests also passed with the minimum supported PyArrow 16.0.0. - Ran the checkout's rerankers with the 0.42.1 SDK and native extension. `test_rerankers.py` and `test_typesafe_reranker.py` had 158 passes and 17 skips. Including `test_hybrid_query.py` gave 187 passes and 17 skips, with the same 14 failures seen before this change against the release SDK. - Python Ruff checks and formatting for both changed files passed. |
||
|
|
4e4ae3eb19 |
fix(python): preserve NumPy timedelta units in table updates (#5317)
Fixes #5316. Writing `np.timedelta64(3_000_000, "ns")` to a millisecond duration column succeeds but stores 3,000,000 ms. NumPy duration scalars also match the integer serializer, which drops the unit before the update reaches Arrow. Give `np.timedelta64` its own serializer. It reads the dtype's unit and multiplier, then reuses the Arrow duration serializer. Weeks through minutes are expressed in seconds. Calendar and sub-nanosecond units raise a conversion error, and `NaT` writes a null. The regression tests read back Arrow's integer counts to check cross-unit writes, exact nanoseconds, a negative value with a scaled dtype, and nulls. They also check that rejected inputs leave the stored value intact. ### Validation - Reproduced the incorrect stored value on the published 0.42.1 Python SDK. - Ran the checkout's converter with the 0.42.1 SDK and native extension. Before the fix, seven of the eight new regression cases failed. After the fix, all 74 update-value tests and 24 related SQL conversion and update tests passed. Also verified four asynchronous updates against an Embedded table. - Ruff lint and formatting checks passed for the Python SDK. The overflow check and additional NumPy duration conversion tests come from #5319. Co-authored-by: tonydzi <194927794+tonydzi@users.noreply.github.com> --------- Co-authored-by: Xuanwo <github@xuanwo.io> Co-authored-by: tonydzi <194927794+tonydzi@users.noreply.github.com> |
||
|
|
bb8e83e69a |
feat(fts): add WAND factor support for FTS and hybrid search (#4894)
Fixes #4754 Add wand_factor support across synchronous and asynchronous FTS and hybrid query APIs, with finite non-negative value validation, PyO3 propagation, query serialization support, and namespace execution fallback when a custom factor is configured. Add tests covering default behavior, custom values, validation, clearing the factor, sync/async execution, serialization round-trips, and namespace routing. --------- Co-authored-by: Xuanwo <github@xuanwo.io> |
||
|
|
7509718f02 |
fix(python): create an empty table when a vector column has no rows to infer from (#5205)
This PR fixes [issue #5204](https://github.com/lancedb/lancedb/issues/5204). Fixes #5204 `create_table(name, data=...)` hung forever when `data` was an Arrow table with zero rows and a variable-length list column named like a vector (`vector`, `embedding`). With no `schema=`, `_infer_target_schema` peeks the first batch to infer the vector dimension. On a reader with no batches, `peek_reader` raises `StopIteration`. That happens inside `asyncio.to_thread`, where a `StopIteration` can't be set on the Future, so `create_table` never returned. With no rows the dimension can't be inferred, the same case as an all-null vector column, which already keeps the variable-length list. So `_infer_target_schema` now returns the input schema unchanged when the reader has no batches. ## Testing `test_infer_target_schema_empty_reader` covers `list<float32>` `vector`, `large_list<float64>` `embedding` and `list<int32>` `vector`. All three fail on main with `StopIteration` and pass with the fix. ``` pytest python/tests/test_util.py # 142 passed, 1 skipped pytest python/tests/test_table.py python/tests/test_db.py -m "not slow and not s3_test" # 636 passed, 17 skipped pre-commit run --files <changed files> # ruff, typos, whitespace: passed ``` I ran these with main's `python/` over the extension from the 0.42.0b26 wheel, since I don't have a Rust toolchain here, and with pylance 14.0.3 because the pinned 15.0.0b35 wasn't on the indexes I could reach. With the fix, the reproduction from the issue creates the table: 0 rows, `vector: list<item: float>`. The Node.js SDK has no equivalent peek on empty input (its empty-data path requires a schema), so no change there. --------- Co-authored-by: Lenin Mookiah <2639584+leninworld@users.noreply.github.com> |
||
|
|
6907440bc1 |
fix(python): split Cohere embedding requests into batches of 96 (#4834)
Fixes a failure when adding 97 or more rows with a Cohere embedding function on SDK releases that do not batch. **Cause:** `CohereEmbeddingFunction.generate_embeddings` sends all texts to `client.embed`. Cohere's endpoint accepts at most 96 texts per call, and some releases (for example 5.0.0 to 5.1.2) send them as a single request. **Fix:** clients that batch on their own (4.x, and releases whose `embed` takes `batching`) get the full input, which keeps their concurrent requests. Other clients get chunks of 96, concatenated in order. **Test:** one test uses a client without batching and checks calls of 96/96/8. A second runs the installed SDK against a local transport and checks request sizes, order and concurrency where the SDK supports it. --- Disclosure: this change was prepared with AI assistance (Claude Code). --------- |
||
|
|
80c889cd9e |
docs: explain merge insert execution costs (#4501)
resolves #4258 ## Summary - document how indexed partial-column merges patch columns across touched fragments - explain how full-scan merges rewrite rows and can materialize the target table - describe the index-coverage, batching, and memory tradeoffs - align the Python, Rust, and TypeScript `use_index` API documentation ## Verification - `git diff --check` - Ruff 0.15.20 formatting check for `python/python/lancedb/merge.py` - Biome 1.9.4 check for `nodejs/lancedb/merge.ts` - reviewed the rendered MDX structure and cross-SDK wording The TypeDoc generation command was also attempted. It cannot complete in this checkout because the Rust-generated `nodejs/lancedb/native.d.ts` artifact is absent and Rust tooling is not installed; TypeDoc stops on the resulting pre-existing module-resolution errors before generating output. --------- Signed-off-by: Himanshu S <me.mrhimanshu@gmail.com> Co-authored-by: Himanshu <18554133+mrhimanshu@users.noreply.github.com> Co-authored-by: Himanshu S <me.mrhimanshu@gmail.com> |
||
|
|
c9faa78cc6 |
feat(python): add free-threaded CPython 3.15 wheel support (#4961)
## Problem The existing `cp310-abi3` wheel cannot be installed on free-threaded CPython 3.15. ## Changes - Keep `abi3-py310` in the default Cargo feature set and provide a separate native free-threaded build profile with the same Python distribution features. - Build and validate `cp315-cp315t` release wheels for Linux x86-64 and ARM64, macOS ARM64, and Windows x64; collect them with the existing release artifacts. - Add a Linux 3.15t CI job and tests for GIL state, concurrent operations, and persistence. The existing regular-Python jobs retain the full test suite. - Validate compressed manylinux platform tags against the expanded `WHEEL` metadata and use workspace-relative wheel paths in Python CI. ## Validation - Built and validated Windows x64 `lancedb-0.42.0b10-cp310-abi3-win_amd64.whl` and `lancedb-0.42.0b10-cp315-cp315t-win_amd64.whl` with Maturin 1.15.0 and `--profile ci`. - On the current PR commit `eecf193`, rebuilt the Windows x64 native wheel, installed it on official CPython 3.15.0t, and ran `python -m pytest python/python/tests/test_free_threaded.py -q`: 2 passed, including GIL state and concurrent database operations. - On the current PR commit, built a native Linux x86-64 `cp315-cp315t` wheel with Maturin 1.15.0 and `--profile ci`, validated its wheel metadata, installed it on CPython 3.15.2t, and ran `python -m pytest python/tests/test_free_threaded.py -q`: 2 passed. This local Linux wheel uses the native `linux_x86_64` platform tag, not a manylinux tag. - Cargo feature regression check, Ruff, Python syntax, workflow YAML parsing, and `git diff --check` passed. - `python -m unittest discover -s ci/tests -p test_check_python_wheel.py -v`: 4 passed on Windows and WSL Linux, including compressed manylinux tags and mismatched metadata. The workflow's corrected wheel glob was also checked from the `python` directory under WSL, and the two free-threaded runtime tests passed from that directory on Windows. The local ABI3 regression wheel was built before the rebase. The native Windows and Linux free-threaded wheels and concurrency tests were built from the current PR commit `eecf193`. The macOS and Linux manylinux release artifacts still need validation in upstream CI. The full test extra pulls optional dependencies requiring source builds on 3.15t, so the new job installs the wheel and focused test dependencies; regular jobs still run the full suite. The complete CI-script suite passed locally on WSL Linux at commit `eecf193`: `python3 -m unittest discover -s ci/tests -v` ran 39 tests successfully with Rust 1.97, a user-space GCC toolchain, and Python's `packaging` module. The upstream CI-script run is marked `action_required`. Closes #4641 |
||
|
|
d9db83de65 |
fix!: guard remote index routes against dot segments (#5013)
BREAKING CHANGE: Older Enterprise index listings that require per-index
statistics now omit historical entries with empty names, `.` or `..`.
Remote index operations reject these unaddressable names. Operators
needing to remove such entries can use server-side maintenance; direct
native access also supports cleanup. Ordinary index names and
`exist_ok=True` reuse require no migration.
Fixes #5007
Remote index URLs previously allowed `.` and `..` as path segments.
Reqwest normalizes them, so dropping an index named `..` could send the
table-level drop request and delete the table.
Guard the remote statistics, prewarm, and drop routes against empty
names, `.` and `..`, then percent-encode all other names. Index creation
retains its existing name policy on both backends, including names such
as `Customer lookup` and `café_idx` and reuse through `exist_ok=True`.
The same remote guard applies on checked-out branches.
Enriched Enterprise listings retain these entries without issuing stats
requests. Native cleanup is covered by a regression test. API
documentation explains these limits, and website release guidance
remains a non-rendering draft.
Validation:
- Before the review fix, 12 of 15 focused regressions failed,
reproducing valid-name rejection, generated-name reuse failure, and
mixed legacy-list failure.
- 60 focused Rust tests passed, covering unsafe routes, encoded names,
mixed legacy/enriched listings, generated names, native and Enterprise
lifecycles, checked-out branches, and `exist_ok` preservation of index
identity, definition, and table version.
- Rebuilt the Python extension in the uv-managed environment from
`python/uv.lock`; all 28 targeted Python tests passed, including both
names and synchronous/asynchronous `exist_ok` reuse.
- Node native build, TypeScript type checking, lint/format checks, four
targeted index tests, and generated API documentation passed.
- Rust formatting, Clippy (`remote`, tests and examples), Python
formatting/lint, repository-wide Typos 1.26.0, and `git diff --check`
passed. Native builds used the repository `ci` profile with
`remote,lancedb/metrics-otel` enabled for Python and Node.
- Repository-root Ruff lint reports 59 existing errors in unchanged
`docs/web-tests`; Python-package lint passes.
<!-- lance-gatekeeper-fix:v1 agent=1ef05de7bc00306ccd6f8a60b9a81003
generation=1 -->
<!-- gatefixer-walkthrough:v1
head=6b25e10810ea1d11a4ef56be63c4ef50225f65d6 -->
## Change walkthrough
```mermaid
flowchart TD
entry["Listed index"] --> typed{"Type available?"}
typed -->|Yes| include["Include index"]
typed -->|No| safe{"Addressable name?"}
safe -->|No| omit["Omit entry"]
safe -->|Yes| stats["Encode and fetch stats"]
stats --> include
```
Creation preserves existing name support; remote routes reject only
empty names, `.` and `..`.
**Read:** [Route
guard](https://github.com/lancedb/lancedb/blob/6b25e10810ea1d11a4ef56be63c4ef50225f65d6/rust/lancedb/src/remote/table.rs#L102-L112)
→ [Listing
fallback](https://github.com/lancedb/lancedb/blob/6b25e10810ea1d11a4ef56be63c4ef50225f65d6/rust/lancedb/src/remote/table.rs#L2534-L2596)
→ [Index-preservation
regression](https://github.com/lancedb/lancedb/blob/6b25e10810ea1d11a4ef56be63c4ef50225f65d6/rust/lancedb/src/table/create_index.rs#L1431-L1481).
<sub>Snapshot:
[
|
||
|
|
97c88659f4 |
fix(python)!: fetch minimum rank-fusion window per side in hybrid search (#4772)
BREAKING CHANGE: Executing or analyzing an async Python hybrid query
with `limit(0)` now raises `ValueError` before either search runs. In
0.41.0, `offset(2).limit(0).to_arrow()` returned a typed empty table
after retrieval and reranking. Skip query execution and `analyze_plan()`
when the requested page size is zero.
Refs #4758
## Problem
Each side of a hybrid query fetched only `limit + offset` rows before
rank fusion, so asking for fewer results could return a different top
result instead of just a shorter list.
Repro (lancedb 0.41.0, 300 rows, RRF reranker):
- `limit=1` -> top id 294
- `limit=10` -> top id 269
## Fix
With the default RRF reranker, both hybrid paths
(`LanceHybridQueryBuilder._create_query_builders` and
`AsyncHybridQuery._create_child_queries`) now fetch `max(limit + offset,
DEFAULT_HYBRID_RANK_WINDOW)` rows per side, with
`DEFAULT_HYBRID_RANK_WINDOW = 50`. The requested limit/offset window is
still sliced out of the fused results as before. This implements option
1 from the issue: a fixed minimum window, no new API surface.
Custom and model rerankers keep the caller's `limit + offset` budget per
side, since every candidate is sent to them (for example
`OpenaiReranker` puts all merged texts in one prompt). Callers who want
a wider window for those rerankers can raise `limit()`. An explicit
`limit(0)` never gets the floor. In the async builder it raises
`ValueError` before schema discovery or either sub-query runs, with or
without an offset, so neither Embedded nor Enterprise retrieves or
scores anything. On main, async `limit(0)` was rejected by the native
`k` check only without an offset; `offset(2).limit(0)` fetched and
reranked two rows per side and returned nothing. The sync builder still
treats `limit(0)` as the default of 10, as before.
Trade-off: default RRF queries with small limits now fetch up to 50 rows
per side, and their result orderings can change, which is the bug being
fixed.
## Tests
- `test_hybrid_query_top_result_stable_across_limits` and its async
mirror (issue repro): fail on base, pass with the fix
- `test_hybrid_query_custom_reranker_keeps_candidate_budget` and its
async mirror: a recording reranker receives 1 vector and 1 FTS candidate
for `limit(1)` and 5 of each for `offset(2).limit(3)`
- `test_async_hybrid_query_default_rrf_candidate_window`: default RRF
receives 50 of each for `limit(1)`
- `test_async_hybrid_query_empty_page_does_not_fetch_candidates` (offset
0 and 2): `limit(0)` raises, and neither sub-query nor the reranker runs
- `test_remote_db.py::test_async_hybrid_zero_limit_sends_no_query`
(offset 0 and 2): `limit(0)` raises and no `/query/` request is sent;
fails on
|
||
|
|
83af5dec3e |
fix(python): pass gemini-text retrieval_document title via EmbedContentConfig (#5239)
Fixes #5235 ### Summary Restores the pre-#3250 Gemini `RETRIEVAL_DOCUMENT` request format by passing `title` via `types.EmbedContentConfig(title=...)` rather than prepending `{"text": "Embedding of a document"}` as a content part in `contents`. ### Problem When `GeminiText` migrated to `google-genai` in #3250, `"Embedding of a document"` was placed inside `contents` as an extra `Part` (`{"parts": [{"text": "Embedding of a document"}, {"text": text}]}`). That embeds the literal placeholder phrase into every stored document vector while `retrieval_query` embeds only the query text, creating asymmetric representations. ### Changes - **`python/python/lancedb/embeddings/gemini_text.py`:** Always send `{"parts": [{"text": text}]}` in `contents`, and set `config_kwargs["title"] = kwargs.get("title", "Embedding of a document")` on `types.EmbedContentConfig` when `task_type.lower() == "retrieval_document"`. - **`python/python/tests/test_gemini.py`:** Updated `test_generate_embeddings_retrieval_document` to verify `contents` holds only the document text while `EmbedContentConfig` receives `title="Embedding of a document"`, and added `test_generate_embeddings_retrieval_query_omits_title` to ensure query requests omit `title`. > **Release Note / Migration Note:** Document vectors generated with `gemini-text` (`source_task_type="retrieval_document"`) since `0.31.0` included the literal `"Embedding of a document"` part in their content payload; existing tables using `gemini-text` should re-embed documents for consistent similarity scores. ### Verification - `pytest -v python/python/tests/test_gemini.py` (`7 passed`) - Verified wire payload via `google-genai` `httpx` request capture (`content.parts` contains only document text; `title` is serialized as top-level request field on `RETRIEVAL_DOCUMENT` and omitted on `RETRIEVAL_QUERY`) - `ruff check --config python/pyproject.toml` & `ruff format --check` (`0 issues`) |
||
|
|
058ed93618 |
feat(python): support table checkout by timestamp (#5221)
Python callers can pass a `datetime` to `Table.checkout()` and `AsyncTable.checkout()` to read several tables as of a single cutoff. Each table is pinned to the highest retained version on its current branch whose reported commit timestamp is at or before the cutoff. A cutoff before all retained versions raises `ValueError`. The Rust `Table::checkout_as_of` method scans the branch's retained history and compares the commit timestamps at the precision supplied by the backend. On Embedded it resolves and checks out the version on the same dataset. If a concurrent tag checkout moves the handle to another branch, it retries there before pinning the handle. On Enterprise it follows all version-history pages on the same branch before checking out the selected version. Servers that report only whole milliseconds can group commits on opposite sides of a cutoff. For an exact reread, record both the branch and version of each input after checkout, then reopen the table with both values. Python interprets naive datetimes in the system's local time zone and honors explicit UTC offsets. The website guide includes a draft paragraph for the SDK release. Closes #2293. ## Validation - Built the Windows x64 native extension from this checkout with the repository's `ci` profile and CPython 3.12. - `test_table.py` passed 558 tests with 20 skips. `test_remote_db.py` passed 759 tests with 2 skips using its HTTP test server. - The new tests cover two tables at one cutoff, pinning after later writes, recovery with `checkout_latest()`, a cutoff before the first version, non-UTC input, tied commits, and a commit one nanosecond past the cutoff. All three also passed with `TZ=EST5EDT`. - A real Embedded handle switching branches during timestamp lookup selected the wrong branch version in 40/40 attempts before the concurrency fix and the expected version in 40/40 attempts afterward. The Rust regression test forces that interleaving with a filesystem-backed table. - A two-page Enterprise HTTP fixture reproduced checkout at v1 with the previous SDK and confirmed checkout at v2 after the fix. The Rust regression asserts the branch and continuation token on page two and reads back the pinned version. A separate test covers empty intermediate pages and repeated tokens. - Both Rust branch checkout tests and the `Table::checkout_as_of` doctest passed with the `remote` feature enabled. - Python SDK Ruff checks and formatting, Pyright, Rust formatting, and Vale passed. Repository-wide Ruff reports 59 existing diagnostics in the unchanged `docs/web-tests` files. --------- Co-authored-by: lipeih <lipeihan@eazytec.com> |
||
|
|
04bf27af9d |
feat: support IN subqueries in Embedded search filters (#5223)
Fixes #5222 ## Summary Embedded vector and full-text searches rejected `IN (SELECT ...)` because Lance's scanner parsed the filter as a single-table expression. A team-scoped search with `limit(1)` needs to rank eligible documents using keys from the sharing table. Resolve unqualified lookup tables through the originating database and use DataFusion to evaluate the predicate on the search snapshot. Pass the matching row IDs to Lance before ranking. The syntax applies to base-table prefilters within one namespace. Literal filters use the existing scanner path. ## Tests Tests: `/bin/sh -c 'cd nodejs && corepack pnpm test --runInBand __test__/query.test.ts -t '"'"'prefilters by keys from another table'"'"''`. Result: cd nodejs && corepack pnpm test --runInBand __test__/query.test.ts on the exact-HEAD published native binary before adding tests: 41 passed. Result: cd nodejs && corepack pnpm test --runInBand __test__/query.test.ts -t 'prefilters by keys from another table' on the exact-HEAD published native binary: 2 failed with the reported unsupported SQL expression, exit 1 (OSSCOUT_BASE.log). Result: cd nodejs && corepack pnpm lint: passed after correcting new fixture key style. Result: cargo fmt --all && git diff --check: passed. Result: cd nodejs && corepack pnpm test --runInBand --runTestsByPath __test__/expr.test.ts __test__/remote.test.ts on the exact-HEAD published native binary: 179 passed across 2 suites. Result: cd nodejs && corepack pnpm tsc && corepack pnpm run docs with the exact-HEAD native declarations: passed, with no generated documentation changes. Result: cd nodejs && corepack pnpm build:debug --profile ci && corepack pnpm tsc: passed from the patched source. Result: cd nodejs && corepack pnpm test --runInBand __test__/query.test.ts -t 'prefilters by keys from another table' on the source-built patch: 2 passed, exit 0 (OSSCOUT_PATCHED.log). Result: cd nodejs && corepack pnpm test --runInBand --runTestsByPath __test__/query.test.ts __test__/expr.test.ts __test__/remote.test.ts on the source-built patch: 225 passed across 3 suites, exit 0 (OSSCOUT_PATCHED.log). Result: cd nodejs && corepack pnpm run docs on the source-built patch: passed, with no generated documentation changes. Regression coverage: `nodejs/__test__/query.test.ts`. <!-- oss-scout-job:job-2628acdb-66f3-4d91-8a6e-d5d15e92bde7 --> --------- Signed-off-by: wangshun <96341168+xixi-box@users.noreply.github.com> |
||
|
|
5db0513dd0 |
fix: validate scalar index types with Lance trainers (#5147)
Fixes #5133 ## What changed Use Lance's scalar training requests to validate resolved Arrow fields and share the same Auto index selection across Embedded and Enterprise. Auto chooses IVF_PQ for vector fields and BTree for supported scalar fields. ## Why LanceDB's copied type lists rejected Binary, LargeBinary, and LargeUtf8 fields that Lance can index. Explicit and automatic BTree creation now accept those fields. BTree and ZoneMap retain a targeted guard on the Arrow Null type because the pinned Lance build drops IS NULL matches after either index is created. FTS and Bitmap continue to check the relevant Arrow extension metadata. Refs #5133. ## How it was tested Tests: `cargo test --profile ci --locked --features remote -p lancedb --lib table::create_index::tests::test_create_btree_on_binary -- --exact`. Result: cargo test --profile ci --locked --features remote -p lancedb --lib table::create_index::tests::test_create_btree_on_binary -- --exact (base): expected failure, 0 passed and 1 failed, exit 101. Result: cargo test --profile ci --locked --features remote -p lancedb --lib table::create_index::tests:: (base): 28 existing cases passed, and only the new regression failed, exit 101. Result: target/ci/deps/lancedb-bb9dc6b24005d6a0 remote::table::tests::test_create_index remote::table::tests::test_create_list_element_fts_requires_server_support remote::table::tests::test_branch_create_index utils::tests::test_fts_field_logical_type_validation (base binary): 14 passed, exit 0. Result: cargo test --profile ci --locked --features remote -p lancedb --lib --no-run (patched): an initial build exposed missing Enterprise imports, which were restored before a successful rebuild. Result: cargo test --profile ci --locked --features remote -p lancedb --lib table::create_index::tests::test_create_btree_on_binary -- --exact (patched): 1 passed, 0 failed, exit 0 in both runs. Result: cargo test --profile ci --locked --features remote -p lancedb --lib -- table::create_index::tests:: remote::table::tests::test_create_index remote::table::tests::test_create_list_element_fts_requires_server_support remote::table::tests::test_branch_create_index remote::table::tests::test_list_indices_fts_public_list_path remote::table::tests::test_list_indices_nested_field_paths index::tests:: utils::tests:: (patched): 61 passed, 0 failed, exit 0. Result: LANCE_FTS_FORMAT_VERSION=bad cargo test --profile ci --locked --features remote -p lancedb --lib utils::tests::test_fts_field_logical_type_validation -- --exact (patched): 1 passed, 0 failed, exit 0. Result: /tmp/osscout-candidate/null-probe (direct probe using the pinned Lance build): IS NULL matched 2 rows before indexing, 0 after building a BTree or ZoneMap, and 2 after building a Bitmap. Result: cargo fmt --all -- --check and git diff --check passed. Regression coverage: `rust/lancedb/src/table/create_index.rs`. <!-- oss-scout-job:job-aa1c056f-6c0a-4141-adae-fe30d5ef896a --> --------- Signed-off-by: wangshun <96341168+xixi-box@users.noreply.github.com> |
||
|
|
3a1d7c267b |
fix(python): use flat validation aliases after nested choices (#5270)
Closes #5269 ## Summary Embedded tables store Pydantic field names. To reconstruct an aliased field, use a flat validation alias when the stored row has the field name and none of the supplied aliases resolves. The follow-up checks the full nested path. A `profile` value that is null or lacks `userId` allows fallback to the stored `user_id`. A supplied `profile.userId` takes precedence, including when its value is null. Before adding a flat alias, check whether it would make an earlier nested choice resolve. For an address stored as Paris with an alternate address in Rome, adding `shipping` would make `shipping.alternate` take precedence. Use `destination` in that case so the result includes the complete stored address. ## Validation - Reproduced the shortened Rome address and both missing-profile failures on the prior PR commit. The six synchronous and asynchronous cases pass with the follow-up. - Covered a safe same-root fallback, supplied nested values, the original flat-alias regression, and shared-key guards. - Passed all 99 Pydantic tests on Pydantic 2.14.4 with the Embedded native library. On the minimum supported Pydantic 2.7.4, 96 tests passed and three newer-version cases were skipped. - Passed the repository-pinned Ruff lint and format checks. Independent reviewers repeated the native round trips and test coverage. |
||
|
|
e6b036cfee |
fix(python): release cancelled query streams (#5104)
Cancelling an async batch read could leave its native query stream
parked inside a posting-list cache load while Python retained the
reader. Other full-text queries sharing those cache entries could then
wait indefinitely.
Give the active read future ownership of the stream while polling it,
restoring it to the reader after the poll completes. Cancellation that
interrupts the active native read drops the stream and releases its
cache loader guards even when the reader and cancelled task remain
referenced. Further reads then raise `RuntimeError`. Completion can race
with cancellation and leave the stream open, so callers should always
discard the reader after cancelling a read and run the query again.
Cancelling a read waiting for the mutex preserves the active read.
Validation:
- Added an asyncio cancellation regression through PyO3 that failed
before the fix (`stream was retained after cancellation`) and now passes
while retaining both the reader and task.
- `cargo test --quiet -p lancedb-python --lib arrow::tests`: 3 passed,
covering cancellation, a queued read, and normal batches/exhaustion.
- Rebuilt the Python extension after merging current `main`; `cd python
&& uv run --no-sync --extra tests pytest
python/tests/test_eager_collector.py python/tests/test_fts.py
python/tests/test_query.py python/tests/test_sync_query_direct.py -q -m
'not slow and not s3_test'`: 381 passed, 2 deselected.
- `cargo clippy --quiet -p lancedb-python --tests -- -D warnings`,
`cargo fmt --all`, Python package Ruff lint/format checks, and `git diff
--check` passed.
- Repository-wide `ruff check .` reports 59 existing errors in
docs/web-tests; no unrelated files are changed.
Fixes #5025
<!-- lance-gatekeeper-fix:v1 agent=052d2342ef138cbaec75426da7e364e8
generation=1 -->
<!-- gatefixer-walkthrough:v1
head=5ebef1c5c4947a49a024f09c452ded756b29ad82 -->
## Change walkthrough
```mermaid
flowchart TD
A[Acquire read mutex] --> B[Take stream ownership]
B --> C[Poll next batch]
C -->|Completed| D[Restore stream]
C -->|Interrupted| E[Drop parked execution]
E --> F[Later reads raise RuntimeError]
```
Completion can race with cancellation; always discard the reader after
cancelling a read.
**Read:** [stream
ownership](https://github.com/lancedb/lancedb/blob/5ebef1c5c4947a49a024f09c452ded756b29ad82/python/src/arrow.rs#L41-L56)
· [reader cancellation
guidance](https://github.com/lancedb/lancedb/blob/5ebef1c5c4947a49a024f09c452ded756b29ad82/python/python/lancedb/arrow.py#L13-L23)
· [asyncio cancellation
regression](https://github.com/lancedb/lancedb/blob/5ebef1c5c4947a49a024f09c452ded756b29ad82/python/src/arrow.rs#L164-L223)
<sub>Snapshot:
[
|
||
|
|
4632bce81b |
fix(python)!: let rename_columns reuse a name freed by the same call (#4936)
BREAKING CHANGE: Every source name in the map must exist in the input
selection. A name created by another entry in the same map is no longer
a valid source.
With `a` present and `x` and `y` absent, `rename_columns({"a": "x", "x":
"y"})` used to apply `a -> x` and then `x -> y`, returning the data
under `y`. It now raises `ValueError: Cannot rename column 'x' because
it does not exist` because `x` is absent from the input.
Migration: rename directly with `{"a": "y"}`, or use two successive
`rename_column("a", "x")` and `rename_column("x", "y")` calls when the
ordered behavior is intended. The docstring states this rule and a test
pins it.
This is marked with `!` for release notes and labeled `breaking-change`.
## Why
`Permutation.rename_columns` applied its map one entry at a time by
calling `rename_column` in a loop. Each entry was validated against the
intermediate state left by the previous ones, so a map in which one
column's new name is another entry's old name was rejected:
```
perm.rename_columns({"id": "value", "value": "data"})
ValueError: Cannot rename column `id` to `value` because a column with that name already exists
```
The name is free once the whole map is applied, which is the only state
a caller can observe. Column swaps were impossible for the same reason.
The method documents renaming a *map* of columns, so the map should be
one rename.
## Change
Validate the map against its final state: collect the names that survive
unchanged plus the new names accepted so far, and reject only a genuine
collision with either. Then build the new selection from the original
one in a single pass, so no entry sees another's intermediate result.
The source name is checked against the original selection, which
produces the breaking change above.
Existing behaviour is preserved: renaming to a name that survives the
call still raises; renaming a column that does not exist still raises;
two entries mapping to the same target still raises; error messages are
unchanged, and `rename_column` itself is untouched.
## Testing
`test_rename_columns_frees_names_for_the_same_call` covers chained
rename, full swap, the ordered-source rejection above, a repeated target
(still an error, and `self` is never modified), `None` keys/values, and
the empty-map no-op.
`test_rename_columns_empty_map_keeps_pinned_version` covers the
pinned-version behavior.
`test_permutation.py`: **83 passed**, rename subset **8 passed**. The
native extension in this checkout was too old to import the branch's
Python package, so the tests ran against the 0.41.0 wheel's native
module with the branch's `permutation.py` overlaid; the changed method
is pure Python.
Signed-off-by: simpleqt <2015900818@qq.com>
|
||
|
|
d31c1568e0 |
fix(python)!: compute JinaEmbeddings.ndims() per model (#4840)
BREAKING CHANGE: `JinaEmbeddings.ndims()` previously returned 768 for unlisted model names. It now raises `ValueError`. When creating a schema with an unlisted model, pass its documented output width to `Vector(width)`. Fixes the `# TODO: fix hardcoding` in `JinaEmbeddings.ndims()` (same kind of fix as #4737, which made the OpenAI-compatible models use their real dimension). **Root cause:** `ndims()` returned 768 for every model. Any model whose default output is not 768 (jina-clip-v2 and jina-embeddings-v3: 1024, jina-embeddings-v4: 2048, jina-embeddings-v2-small-en: 512) produced a vector column of the wrong size. **Fix:** per-model lookup table of default output dimensions, only for models whose dimension is documented (model configs on Hugging Face `hidden_size`/`projection_dim`, and https://jina.ai/models/ pages). Unknown models raise a `ValueError` listing the supported names instead of silently guessing 768. The default `jina-clip-v1` still returns 768. When appending to a table, generated vectors are validated against the width of the stored fixed-size column, so existing tables that use an unlisted model keep working. **Test:** `python/tests/test_jina_embeddings.py` (no network, no API key), including reopening a table with an unlisted model, appending a matching vector and rejecting a mismatched width. This change was prepared with an AI coding assistant (Claude). --------- Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com> |
||
|
|
8a27234be2 |
feat(python): add AssetFeed reranker (#5258)
Adds `AssetFeedReranker`, which calls the AssetFeed Cohere-style `/rerank` endpoint (`assetfeed/assetfeed-rerank-v1`). It follows `JinaReranker` (plain `requests`, no new dependency) and supports vector, FTS and hybrid search with the same `return_score` options as the Cohere reranker. - Key from `api_key` or `ASSETFEED_API_KEY`. - The API accepts up to 100 documents per request. More raises a clear error before any request. - `top_n` is only sent when set. Python and docs only (`integrations/reranking/assetfeed`). ### Testing - `test_assetfeed_reranker.py`: 12 tests with a mocked session, no network. - `test_rerankers.py`, `test_reranker_credentials.py`: pass. `ruff check` passes. - Not tested live: no API key was used. |
||
|
|
747a62114c |
fix(python): keep rows when Permutation.iter gets short reader batches (#5156)
## What changed `Permutation.iter()` now passes the reader batches through a small `_rebatch()` helper in `python/python/lancedb/permutation.py`. It regroups short batches into batches of exactly `batch_size` rows before `transform_fn` runs. Full batches with nothing pending are passed through without a copy, and empty batches are dropped. Only the final remainder is subject to `skip_last_batch`. The `iter()` docstring now states this. ## Why Fixes #5155 `iter()` checked `batch.num_rows == batch_size` on every batch, but the Rust `PermutationReader` only bounds batches by `batch_size`. When a split is read, the plan batches are filtered, so short batches show up in the middle of the stream. `for batch in permutation` (`skip_last_batch=True`) then dropped them silently: with `split_hash` it returned 0 of 502 rows, and a shuffled random split lost a batch in the middle. With `skip_last_batch=False` the rows came through but in batches smaller than `batch_size`. The fix is in Python because the exact batch size is a promise of the Python API (`test_iter_basic`, `test_iter_skip_last_batch`); the Rust reader tests assert `<=`. The TypeScript SDK has no `Permutation`. ## How it was tested Run in a `python:3.12-slim` container with the `0.42.0b21` nightly wheel and the Python sources from this branch copied over it (no Rust change, so no `maturin develop`). - New test `test_iter_keeps_rows_from_short_reader_batches` iterates a `split_hash` permutation with and without `skip_last_batch` and checks batch sizes and row ids. On `main` it fails with `assert [18, 18, 19, 20, 18, 20, ...] == [37, 37, 37, 37, 37, 37, ...]`. - New test `test_rebatch_regroups_short_and_empty_batches` covers empty batches in the middle and at the end, a batch larger than `batch_size`, the final remainder, an empty stream, and the schema. - With the fix: both new tests pass in 5 consecutive runs, and `test_permutation.py` passes (96 passed). - With `permutation.py` restored from `main`, only `test_iter_keeps_rows_from_short_reader_batches` fails (1 failed, 94 passed). - `ruff format --check .` and `ruff check .` in `python/` with ruff 0.9.9: clean. - `pyright` CI config does not include `permutation.py` or the tests. Running it on the file directly reports no new errors in the changed code. `test_torch.py` was skipped because torch is not installed in the container. Written with help from Claude Code. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
c806fc8708 |
fix!: return a single row from Permutation.__getitem__ (#5165)
BREAKING CHANGE: `Permutation.__getitem__` now returns a single row instead of a one-element list for list-producing formats (such as the default `"python"` format), so callers using `perm[i][0]` should switch to `perm[i]` or use `take_offsets([i])` to keep a one-row batch; out-of-bounds indexing now raises `IndexError`, and out-of-window identity `take_offsets` now raises `InvalidInput` (Python `ValueError`).
## Summary
`Permutation.__getitem__` documented a single row but returned `take_offsets([index])` after the current transform. The default transform is `batch.to_pylist()`, so `perm[0]` was a one-element list, which breaks per-index consumers like `torch.utils.data.DataLoader`.
An integer index now returns one row. List-producing transforms unwrap that element. Batch-shaped results stay as produced, so `with_format("arrow")[0]` is still a one-row `RecordBatch`. `__getitems__` and multi-row `take_offsets` still return the transformed batch. Negative indexes count from the end, and an out-of-range `__getitem__` raises `IndexError`.
### Identity permutation window
Identity `take_offsets` ignored `with_skip` and `with_take` and sent offsets straight to the base table. `len()` and `iter()` already honored that window, so a 10-row identity permutation with `with_skip(3).with_take(4)` iterated ids 3–6 while `perm[0]`, `take_offsets([0])`, and a DataLoader returned id 0. The identity reader now applies the same window. An offset outside it is an `InvalidInput` error (Python `ValueError`), matching a permutation-table reader whose offset is missing from the window map. On an identity permutation with no skip or take, an offset past the table length is now that error instead of an empty batch.
Related: #2996 (closed, but `perm[0]` still returned a list on current main)
Supersedes #3117, which is stale and only unwrapped the list in Python without the window fix.
## Test plan
- [x] `cargo fmt --all -- --check`
- [x] `cargo clippy --features remote -p lancedb --all-targets -- -D warnings`
- [x] `cargo test --features remote -p lancedb --lib dataloader` (52 passed, including new window tests)
- [x] `pytest python/tests/test_permutation.py python/tests/test_torch.py` (permutation + torch: 130 passed)
- [x] `ruff format --check` and `ruff check` in `python/`
Written with Cursor (Grok).
Co-authored-by: Maxwell Calkin <101308415+MaxwellCalkin@users.noreply.github.com>
|
||
|
|
41637c646e |
feat(python): add AssetFeed embedding provider (#5257)
Adds an `assetfeed` text embedding provider for the AssetFeed embeddings API (`assetfeed/assetfeed-embed-v1`). It uses the existing optional `openai` client with AssetFeed's OpenAI-compatible endpoint, as the `nvidia` provider does. - Documents are embedded with `input_type="document"`, searches with `input_type="query"`. - `dim` is 1024 (default), 512 or 256. Batches are at most 64 inputs. - The key comes from `ASSETFEED_API_KEY` or an `api_key` registry variable reference. - Response count, indices, dimensions and values are checked. Null and empty text get a null vector without a request. - Each request is retried on its own with LanceDB's retry policy. Python and docs only (`integrations/embedding/assetfeed`). No dependency changes. ### Testing - `test_assetfeed_embeddings.py`: 18 mocked-HTTP tests through the real OpenAI client, no network. They cover request shape, batching, response order, null inputs, a local table, retries and invalid responses. - Registry and trust suites: pass. `ruff check` passes. - Not tested live: no API key was used. --- |
||
|
|
84e0f53836 |
feat(python): register live LanceDB tables with DataFusion (#5203)
Python DataFusion queries over a provider registered from
`table.to_lance()` read a fixed Lance snapshot. An append from another
connection doesn't show up in later queries unless the application
registers a new provider.
Register a LanceDB Embedded `Table` or `AsyncTable` directly with
DataFusion 55.x using `ctx.register_table("items", table)`. The provider
shares the LanceDB table handle, so each new scan follows its read
consistency interval and checked-out version. The provider supports SQL
reads. Re-register after a schema change.
The binding checks the DataFusion FFI major before reading the
consumer's capsule and keeps scan planning and execution on the LanceDB
Tokio runtime. DataFusion remains an optional Python dependency.
Closes #2707.
Validation on Windows x64 with CPython 3.12 and DataFusion 55.0.0:
- Rebuilt the Python extension with the repository's `ci` profile.
- `pytest python/tests/docs/test_guide_tables.py -q`: 6 passed, 2
skipped. The regression covers a second connection writing into a
registered table, both manual and automatic refresh, version pinning,
async table registration, and incompatible DataFusion versions.
- A separate smoke test confirmed refresh with a positive read
consistency interval.
- Cargo formatting, Python Ruff, and Pyright (Linux target) passed.
Co-authored-by: lipeih <lipeihan@eazytec.com>
|
||
|
|
2e09dc1144 |
fix(python): add opt-in normalization for truncated gemini embeddings (#4827)
`gemini-embedding-001` returns only its full 3072-dimensional output normalized. Reduced outputs, including the 768 default of `GeminiText`, are not unit length, and the [Gemini embeddings docs](https://ai.google.dev/gemini-api/docs/embeddings) say to normalize them manually. **Change:** a new `normalize` setting on `gemini-text`, off by default. With `normalize=True`, outputs of `gemini-embedding-001` (also spelled `models/gemini-embedding-001`) below 3072 dimensions are L2-normalized. The setting is saved in the table's embedding function config. When it is omitted, vectors are stored and queried as before, so existing tables need no migration. **Tests:** `test_gemini_text_embeddings.py` stubs the Gemini client. It covers the opt-in for both model spellings, the cases left untouched, and text search plus append after reopening both a table without the setting and a table created with `normalize=True`. This change was prepared with the help of an AI assistant (Claude), and the submitter is responsible for it. --------- Signed-off-by: Alex Castillo <alex.castillog33@gmail.com> Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com> |
||
|
|
7c6ffe94c2 |
fix(python): skip null texts when reranking with Cohere (#5283)
## Summary An Embedded vector search can include a row whose reranking text is null. The Cohere reranker sent that null in its documents array, which made the request invalid and prevented the remaining documents from being ranked. Filter null texts before building the request. Apply Cohere's result indexes to the same filtered Arrow table so the scores follow the correct rows. When every candidate has null text, return an empty scored table without sending a request. [Cohere Rerank API v1 document types](https://docs.cohere.com/v1/reference/rerank) Closes #5284. ## Verification - Reproduced with an Embedded table, the installed Cohere SDK and an in-process HTTP transport that enforced the documented document types. The base sent `["first", null, "last"]` and received the fixture's 400 response. The fix sent `["first", "last"]` and returned the original row IDs in the reranker's order. - Added Embedded search regressions for mixed and all-null candidate sets. Both fail on the parent and pass after the change. - Passed 12 relevant reranker tests and the repository-pinned Ruff lint and format checks. A second reviewer independently reran the 12 tests. |