Commit Graph
3822 Commits
Author SHA1 Message Date
c90382e9c4 fix(node): handle rejected job progress callbacks (#5272)
Fixes #5271

## Summary

A promise returned from a job progress callback could reject outside the
SDK's synchronous error handler. This calls the observer synchronously
as before and attaches a rejection handler without awaiting it.

## Validation

- The regression test holds the observer promise open until `Job.wait`
completes, then rejects it and verifies the warning.
- All 4 tests in `nodejs/__test__/job.test.ts` pass using the native job
boundary stub and the published matching beta native declarations.
- A separate actual Node run with `--unhandled-rejections=strict` exits
at the observer error on main. It logs the error and continues with the
patch.
- Biome lint and format checks passed on the two changed files. `git
diff --check` passed.

---------

Co-authored-by: Divyam Talwar <237515611+DivyamTalwar@users.noreply.github.com>
Co-authored-by: Divyam Talwar <DivyamTalwar@users.noreply.github.com>
2026-11-30 21:46:02 +08:00
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>
2026-11-30 21:23:27 +08:00
Juampi 0ba8b6f0a8 docs: add Firecrawl integration page (#4706)
I work at Firecrawl. This adds a Firecrawl page to Integrations > Data
Platforms & Frameworks: a Python recipe that crawls a site with
Firecrawl, stores the pages as Markdown chunks with their source URL in
a LanceDB table that embeds them through the embedding registry,
searches the table, and then adds web search results to the same table.

It follows the docs workflow in CONTRIBUTING.md:

- The example is a test, `docs/web-tests/py/test_firecrawl.py`, split
into five `--8<--` snippets. Like the other integration snippets that
need a provider key, it skips unless `FIRECRAWL_API_KEY` is set.
- `docs/web/snippets/firecrawl.mdx` is generated from it with `uv run
docs/web-tests/mdx_snippets_gen.py -s docs/web-tests/py -s
docs/web-tests/ts -s docs/web-tests/rs -o docs/web/snippets`. The
generator also rewrites other snippet files on current `main` without
this change, so I left those out.
- `docs/web/integrations/data/firecrawl.mdx` imports the snippets with
`<CodeBlock>` like the dlt page, and every heading has an explicit
`{#anchor}`.
- `docs/web/docs.json` adds the page at the end of the Data Platforms &
Frameworks group.

The embedding function is `sentence-transformers` with
`all-MiniLM-L6-v2`, so the recipe needs no API key besides Firecrawl's.
Each Firecrawl call passes `integration="_lancedb"`, a label that tells
Firecrawl a request came from this guide; the page says it is optional.
It needs `firecrawl-py` 4.3.3 or later.

## Testing

```
$ FIRECRAWL_API_KEY=... pytest docs/web-tests/py/test_firecrawl.py -v
test_firecrawl.py::test_firecrawl_crawl_and_search PASSED     (lancedb 0.40.0, Python 3.12)
$ pytest docs/web-tests/py/test_firecrawl.py -rs              (no key)
SKIPPED [1] Set FIRECRAWL_API_KEY to run this integration snippet
$ ruff format --check docs/web-tests/py/test_firecrawl.py && ruff check docs/web-tests/py/test_firecrawl.py
1 file already formatted
All checks passed!
```

Regenerating the snippets from the test produces the same
`docs/web/snippets/firecrawl.mdx`. I have not run the Mintlify site
checks (`mint validate`, broken-links), so please run them in CI or on
your side.

I drafted this with an AI coding assistant and ran the test above
myself.
2026-11-30 21:13:16 +08:00
Haocheng LiuandHaocheng Liu 80582fb87d docs: fix training and dedupe examples (#4932)
## Summary

- Save per-rank dataset checkpoints to separate files and load the
matching file when resuming.
- Add the missing LanceDB import to the data loader example.
- Correct the count of distinct rows in the deduplication example.

## Validation

- `git diff --check`
- Parsed the Python snippets in the affected training pages with
`ast.parse`.

---------

Co-authored-by: Haocheng Liu <haocheng.liu@general-int.com>
2026-11-30 21:09:38 +08:00
David Turner 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
2026-11-30 21:07:25 +08:00
lancedb-gatefixer[bot] 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:
[6b25e10](https://github.com/lancedb/lancedb/commit/6b25e10810ea1d11a4ef56be63c4ef50225f65d6)</sub>
<!-- gatefixer-walkthrough:end -->

---------

Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com>
2026-11-30 20:51:19 +08:00
Sudhir Vissa 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 281fdc7, passes on this head
- `test_remote_db.py::test_query_sync_hybrid` now expects `k=50` for the
default RRF request with `limit(42)`
- `test_hybrid_query.py`: 30 passed, 1 failed. The failure is
pre-existing and unrelated
(`test_hybrid_query_with_stale_fixed_size_binary_prefilter` needs the
`lance` package)
- `test_wal_hybrid.py`: 15 passed
- `ruff check` and `ruff format --check` clean on the touched files

Local runs used the lancedb 0.41.0 wheel with this PR's `query.py` diff
applied, since main needs a newer native extension than the published
wheel. `test_query_sync_hybrid` and the new remote zero-limit test were
run from an extracted copy because `test_remote_db.py` imports
`lancedb.graph`, which 0.41.0 does not have.

---------

Signed-off-by: shadowmodder <sudhirvissa@gmail.com>
Signed-off-by: Sudhir Vissa <sudhirvissa@gmail.com>
2026-11-30 20:42:12 +08:00
Ömer 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`)
2026-11-30 20:41:06 +08:00
lipeh1andlipeih 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>
2026-11-30 20:40:10 +08:00
Ayanna Bansal 14e49a6710 fix(node): infer a timestamp type for Date values (#5232)
`createTable` and `makeArrowTable` reject a JavaScript `Date` when no
schema is given:

```ts
await db.createTable("events", [{ id: 1, created: new Date() }]);
// Error: Failed to infer data type for field created at row 0. Consider providing an explicit schema.
```

Row validation already lets `Date` through as a supported value, and the
same rows work with an explicit `Timestamp` schema, but `inferType` has
no branch for it, so inference gives up.

This change:

- infers `Timestamp<MILLISECOND>` for a `Date`, which is also what
Apache Arrow's own `vectorFromArray` infers and matches the precision of
a JS `Date`. A list of dates is inferred as a list even when the column
name looks like a vector column;
- writes `Timestamp(ms)` columns, and lists of them at any depth, as
signed 64-bit values in `makeVector`. `apache-arrow@15.0.0` rounds the
high 32 bits of a negative timestamp toward zero, so `new Date(-1)` came
back as 4294967295. This already affected an explicit `Timestamp(ms)`
schema on Arrow 15; inference would have made it easier to hit. `Date`,
integer and bigint values take the new path; anything else (fractional
numbers, strings, list values that are not arrays or typed arrays) is
left to Arrow exactly as before;
- rejects an Invalid Date with a clear error. Arrow 15 stored it as
1970-01-01 and newer versions threw a BigInt conversion error;
- documents the new rule in the `makeArrowTable` docstring and the
generated API page.

Not changed (explicit schemas only, behaviour as before this PR):
timestamp units other than milliseconds, timestamps inside a
`List<Struct>`, `FixedSizeList` or `Map`, and `Date` query parameters in
`sql.ts`. On Arrow 15 these still go through Arrow's conversion. I can
follow up on them separately if wanted.

Tested:
- New tests in `__test__/arrow.test.ts`: the type is inferred; values
and nulls round-trip; a `Date` mixed with a string is still rejected;
dates before 1970 survive IPC as scalars, in lists, nested lists and
structs, with and without a schema; epoch numbers, bigints and typed
arrays keep working in explicit timestamp columns; Invalid Date is
rejected in every shape.
- `jest __test__/arrow.test.ts` passes with `apache-arrow` resolved to
15.0.0, 16.0.0, 17.0.0 and 21.2.0 (swapped the way the `arrow-compat` CI
job does). On 15.0.0 the pre-1970 tests fail without the workaround. CI
does not run Arrow 15, so on newer versions the Invalid Date test is
what fails if a shape stops reaching the new writer.
- `jest __test__/table.test.ts`, `biome ci .`, `tsc -b` and `pnpm run
docs` pass.
- Checked by hand that `createTable` then `add` with `Date` values
stores and returns them.

I ran the TypeScript tests against the published 0.42.0-beta.34 native
binary; I did not rebuild the Rust side, which this change does not
touch.
2026-11-30 20:38:59 +08:00
wangshun 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>
2026-11-30 20:38:51 +08:00
wangshun 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>
2026-11-30 20:38:43 +08:00
Divyam Talwar 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.
2026-11-30 20:33:36 +08:00
lancedb-gatefixer[bot] 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:
[5ebef1c](https://github.com/lancedb/lancedb/commit/5ebef1c5c4947a49a024f09c452ded756b29ad82)</sub>
<!-- gatefixer-walkthrough:end -->

---------

Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com>
2026-11-30 20:33:28 +08:00
Divakant Pandey 42415ae0ff feat(rust): convert between serde structs and Arrow data (#4910)
Closes #1101.

Rust users currently have to build `RecordBatch`es by hand to write to a
table, and read results back as Arrow arrays. This adds an optional
`serde` feature, built on `serde_arrow` (`arrow-59`, matching our arrow
line), laid out like the `polars` feature:

- `lancedb::arrow::from_structs(&[T]) -> Result<RecordBatch>` derives
the schema from `T`. Strings, lists and binaries use the 32-bit offset
types (`Utf8`, `List`, `Binary`) rather than `serde_arrow`'s `Large*`
defaults.
- `lancedb::arrow::from_structs_with_schema(&[T], SchemaRef)` serializes
against an explicit schema and keeps its metadata.
- `lancedb::arrow::IntoStructs` adds `into_structs::<T>()` on
`SendableRecordBatchStream`, mirroring `IntoPolars`. `serde_arrow` must
be able to read every selected column, and `T`'s Serde rules then apply
(derived `Deserialize` ignores extra readable columns such as
`_distance`, while `QueryBase::select` can project only the needed
columns).

Both functions return a `RecordBatch`, which is already `Scannable`, so
`add` and `create_table` need no changes. A wrapper type implementing
`Scannable` would have to convert inside `schema()`, which can't return
an error.

One caveat, covered in the docs and the example: serde has no fixed-size
sequence type that maps to Arrow, so `Vec<f32>` traces to
`List<Float32>` and `[f32; N]` traces to a struct. Appending to an
existing table works because the write path casts to the table's
`FixedSizeList` column. Creating a table from a traced batch leaves the
vector column as a `List`, so it can't be searched;
`from_structs_with_schema` is the way to create tables with vectors.
Happy to add a vector-column shorthand instead if you'd prefer that API.

`serde_arrow` and its `marrow` dependency are MIT. The `arrow-59`
feature will need bumping with the workspace arrow version, the same as
the `polars` pin.

Testing:
- Unit tests in `arrow::serde_tests`: traced schema types, empty input,
metadata preserved, wrong vector dimension error, add + read-back round
trip including nested struct and `Option` fields, create + vector search
into structs with `_distance`, missing column error, `Select::columns`
projection (including non-UTC timestamp exclusion and
`#[serde(deny_unknown_fields)]`).
- Doctests for all three APIs, and `examples/serde.rs`.
- `cargo fmt --all -- --check`
- `cargo test -p lancedb --features serde --locked --lib serde_tests`
and `--doc arrow::`
2026-11-30 20:33:20 +08:00
陈志谦 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>
2026-11-30 20:27:20 +08:00
Alex Castillo GonzálezandClaude Sonnet 5.5 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>
2026-11-30 20:23:42 +08:00
Kevin Dong 2ff3bee923 feat(node): expose ZoneMap and BloomFilter index configs (#4962)
## Summary

Refs #4931 (TypeScript portion).

Expose the existing Rust ZoneMap and BloomFilter builders through
`Index.zoneMap()` and `Index.bloomFilter({ numberOfItems?, probability?
})` for Embedded and Enterprise tables. Export `BloomFilterOptions`,
reject values that cannot be converted losslessly from a positive
JavaScript safe integer to Rust `u64`, and retain the core builder's
probability validation and defaults.

Include API examples, generated documentation, and the ZoneMap
table-capability compatibility warning. Synchronize with main while
preserving its RTree/plugin factories and source-bearing Blob APIs. The
Python portion remains separate.

## Validation

- Built the new native binding on macOS 15.7.9 / arm64 with Rust 1.98.0,
Node 24.22.1, the repository `ci` profile, locked dependencies, and
Rust's bundled LLD scoped to the Node binding. Both lockfiles match
main.
- Four full affected Jest suites: **819 passed, 3 existing
experimental-feature cases skipped**. Coverage includes index
creation/listing, range and membership plans/results, option boundaries,
Enterprise HTTP request bodies, and the newly merged Blob descriptor
API.
- Passed TypeScript compilation, Biome check/format for all 85 Node
files, generated API documentation with warnings treated as errors, Rust
formatting, and `git diff --check`.
- Independent execution in a separate writable snapshot: 56
reviewer-designed boundary cases passed on each of Node 22 and 24; 815
adjacent repository tests passed, with 3 existing skips. TypeScript,
generated docs, Biome, and the compiled package entry point passed. The
final source tree, complete diff, and freshly built native artifact
hashes matched; no actionable findings remained.

The final documentation correction was checked against the pinned Lance
source. TypeScript compilation, Biome, generated API documentation, and
all 19 index option tests passed again. Two real Embedded table probes
confirmed that default ZoneMap creation on string and binary columns
leaves the v1 reader and writer capability bits unset; the string range
query used the scalar index and returned the expected rows. A fresh
independent snapshot also passed the string/binary lifecycle probes on
Node 22 and 24 (24 manifest observations), the 19 repository index
tests, and the documentation/type/lint checks.

Enterprise checks use mock HTTP endpoints. The native linker reports
C-library minimum-macOS-version warnings, so these runs do not establish
compatibility with older macOS versions.

## Merge Danger

**Door:** two-way

The SDK additions can be reverted. ZoneMap write seeds use v0 by
default. A commit that explicitly sets `lance.zone_write_seeds.version`
to `"1"` activates a persistent reader and writer capability; readers
and writers must support it before opting in. Dropping the index or
restoring an older version does not remove that capability from
subsequent snapshots.

**Blast Radius:** TypeScript

Adds index configuration factories and NAPI bindings; reuses existing
core index creation and Enterprise serialization.
2026-11-30 20:23:00 +08:00
Nikolai Vysotskyi 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.
2026-11-30 20:22:28 +08:00
Aiman MalibandClaude Opus 5.5 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>
2026-11-30 20:20:01 +08:00
Preston ZhaoandMaxwell Calkin 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>
2026-11-30 20:18:58 +08:00
Nikolai Vysotskyi 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.

---
2026-11-30 20:18:29 +08:00
wangshun d0dfa0d8f0 fix(java): fall back to curl when Maven Wrapper wget fails (#5231)
Fixes #5224

The Java beta release job stopped before Maven started. The job log
shows that the wrapper cache was empty and wget failed to fetch the
Maven distribution. The wrapper exited immediately even when curl was
available. [Issue #5224](https://github.com/lancedb/lancedb/issues/5224)

Use the existing curl download path when wget fails and curl is
installed. Keep wget as the first choice and continue using the same
distribution URL, archive validation, and cache. The wrapper still exits
with an error if it cannot download the archive.

Tests: `python3 -m unittest discover -s ci/tests -p
test_maven_wrapper.py -v`.
Result: Base: python3 -m unittest discover -s ci/tests -p
test_maven_wrapper.py -v exited 1. The fallback regression reproduced
the terminal wget error, and the successful-wget case passed.
Result: Patched: python3 -m unittest discover -s ci/tests -p
test_maven_wrapper.py -v exited 0. Both wrapper tests passed, including
the cached invocation in the fallback test.
Result: Patched: python3 -m unittest discover -s ci/tests -v exited 0
with Ran 40 tests and OK.
Result: Base: (cd java && JAVA_HOME=/usr/lib/jvm/temurin-17-jdk-amd64
./mvnw --batch-mode test -pl lancedb-core) exited 0 with 37 tests, 0
failures, 0 errors, and 0 skipped.
Result: Patched: (cd java && JAVA_HOME=/usr/lib/jvm/temurin-17-jdk-amd64
./mvnw --batch-mode -Dspotless.skip=true clean test -pl lancedb-core)
exited 0 with 37 tests, 0 failures, 0 errors, and 0 skipped. Surefire
XML reports are in java/lancedb-core/target/surefire-reports/.
Result: Patched: The Temurin 8 cold-cache deployment command in
setup_steps exited 0 and reported BUILD SUCCESS for lancedb-parent and
lancedb-core after logging 'wget download failed, trying curl'. Both
POMs and all three JARs were present in the file repository.
Result: Patched: uvx ruff format --check ci/tests/test_maven_wrapper.py,
uvx ruff check ci/tests/test_maven_wrapper.py, sh -n java/mvnw,
shellcheck java/mvnw, and git diff --check passed.
Regression coverage: `ci/tests/test_maven_wrapper.py`.
<!-- oss-scout-job:job-71b2ce3e-46b8-467c-8342-2f1d491dd63c -->

Signed-off-by: wangshun <96341168+xixi-box@users.noreply.github.com>
2026-11-30 20:18:20 +08:00
lipeh1andlipeih 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>
2026-11-30 20:18:12 +08:00
Alex Castillo GonzálezandClaude Sonnet 5.5 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>
2026-11-30 20:14:45 +08:00
Divyam Talwar 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.
2026-11-30 20:13:28 +08:00
Divyam TalwarandDivyam Talwar ea2d9a0440 fix(node): exclude padding from Transformers embedding pooling (#5282)
## Summary

Use Transformers.js mean pooling with the tokenizer's attention mask so
padding positions do not contribute to source and query embeddings.

## Validation

- A deterministic model and tokenizer fixture uses actual
Transformers.js Tensor objects and compares the same short text embedded
alone and in a padded batch. On main its vector changes from `[1, 5]` to
`[50.5, 102.5]`. With the fix it stays `[1, 5]` and the longer text's
expected vector remains `[4, 8]`.
- Existing Transformers and embedding Jest suites on Node 24: 20 passed,
1 skipped (OpenAI key required). TypeScript build and Biome checks
passed.
- Used Transformers.js 4.3.2 with the ONNX Web tensor runtime for
fixture-only tests. Model downloads and inference were disabled.

Fixes https://github.com/lancedb/lancedb/issues/5281

---------

Co-authored-by: Divyam Talwar <DivyamTalwar@users.noreply.github.com>
2026-11-30 20:13:20 +08:00
4abb2b282c fix(node): retain deferred query promise failures until execution (#5280)
## Summary

Observe Promise-backed query preparation when the builder stores it,
including promises produced by fluent modifiers. Terminal operations
still await the original promise and receive its original rejection.

## Validation

- Both delayed-execution regressions fail on main. The new tests
exercise a plain Promise-backed builder and a builder with chained
filters, and check rejection identity.
- Native Jest query suite: 43 passed. TypeScript compilation with
`--noEmit` and Biome checks passed.
- Ran real embedded direct-Promise and forced string-vector queries with
Node's strict unhandled rejection mode. Both baseline processes exit
before execution. With the fix each process survives the delay, receives
the expected error when awaited, and successfully executes a control
query.

Fixes https://github.com/lancedb/lancedb/issues/5279

---------

Co-authored-by: Divyam Talwar <DivyamTalwar@users.noreply.github.com>
Co-authored-by: Divyam Talwar <152021174+DivyamTalwar@users.noreply.github.com>
2026-11-30 20:13:11 +08:00
Divyam TalwarandDivyam Talwar e2f6ba1b69 fix(python): accept null Ollama client options (#5278)
## What changed

Treat explicit null for `ollama_client_kwargs` the same as omitted
options. The field is optional, but the first embedding call tried to
unpack `None` as keyword arguments and failed before making a request.
Existing option mappings still pass through to the Ollama SDK.

## Verification

- The new regression uses the real Ollama 0.6.2 SDK and a loopback HTTP
server. Main's Python provider raises `TypeError` before any request.
The patched call sends one `POST /api/embed` and returns the expected
vector.
- All 16 Ollama tests passed with the 0.42.0b38 native wheel and current
Python sources. An independent rerun of the exact Python provider also
passed all 16 tests.
- Ruff formatting, Ruff lint, and the Git diff check passed.

Closes #5277.

Co-authored-by: Divyam Talwar <DivyamTalwar@users.noreply.github.com>
2026-11-30 20:13:02 +08:00
Divyam TalwarandDivyam Talwar 760a6ac2a8 fix(python): align OpenAI reranking scores by row index (#5268)
Closes #5267

## Summary

- Assign a stable position to each document passed to the OpenAI
reranker. Use the returned positions to attach scores to the original
rows, including when their text is identical or the response is
reordered.
- Check for missing, duplicate, and out-of-range positions before
attaching scores.

## Validation

- Invoked the public reranker with real Arrow rows and a mocked Chat
Completions response. The original code conflates two rows with
identical text. The fix returns each row with its own score and sends
both positions in the request.
- Reranker suite: 41 passed, 13 skipped. Ruff lint, format, and the
independent focused rerun passed. No live provider request was made.

---------

Co-authored-by: Divyam Talwar <DivyamTalwar@users.noreply.github.com>
2026-11-30 20:12:53 +08:00
Divyam Talwar 3e9941fc7c fix(python): honor deduplicate in multivector rerankers (#5266)
Closes #5265

## Summary

- Honor `deduplicate=False` in both multivector rank fusers. Each
retained row keeps its original distance and receives the same fused
score as other rows for its ID.
- Preserve the existing default deduplication and rank calculation.

## Validation

- Both new regression cases fail on main and pass with the fix. They
exercise repeated rows, distinct distances, stable fused scores, and
default deduplication.
- Full Python reranker test module: 42 passed, 13 skipped. Ruff and `git
diff --check` passed.
2026-11-30 20:12:44 +08:00
Divyam TalwarandDivyam Talwar e435593602 fix(python): convert Arrow record batches to Torch tensors (#5264)
Fixes #5263

## Summary

- Send an Arrow record batch's array columns directly through DLPack.
- For table columns, keep the existing one-chunk conversion and
multiple-chunk error. Use a typed empty array for a column with zero
chunks.
- Cover sliced record batches, equivalent one-chunk tables, empty table
shape and dtype, and the multiple-chunk guard.

## Validation

- Verified the record-batch and empty-table tests fail on `main`. All
three `tbl_to_tensor` tests pass with PyArrow 26.0.1 and CPU Torch
2.10.0.
- Ruff check, Ruff format check, and `git diff --check` pass.

Co-authored-by: Divyam Talwar <237515611+DivyamTalwar@users.noreply.github.com>
2026-11-30 20:12:36 +08:00
Divyam Talwar fd745ac4f3 fix(python): honor a zero limit in synchronous plain scans (#5262)
Fixes #5261.

## Problem

Calling `limit(0)` on a synchronous ordinary scan clears the limit and
returns every matching row. The same plain scan in the async SDK returns
zero rows.

## Changes

- Pass zero through to the native query for synchronous plain scans.
Keep explicit `None` as an unlimited scan.
- Verify that an empty Arrow table and batch stream retain their
requested projection.

## Validation

- The new regression on `main` returned one row instead of an empty
projected table. It passes with the patch.
- Ran 18 query tests covering plain scans, projection, ordering, stream
output and the existing vector no-limit case.
- Also checked Arrow, batches and pandas against a real in-memory table
using the `0.42.0b38` native wheel. Zero returns an empty `id`
projection in all three. Async zero and synchronous `None` retain their
existing meanings.
- Ruff formatting and lint passed.

AI-assisted implementation and testing.
2026-11-30 20:12:27 +08:00
Divyam Talwar 70ab010a47 fix(python): preserve row alignment for OpenAI embeddings (#5260)
Fixes #5259.

## Problem

The Python OpenAI adapter pairs the response list and the input batch by
position. An OpenAI-compatible endpoint that returns the data items in a
different order from their `index` values causes LanceDB to write
otherwise valid embeddings to the wrong rows.

## Changes

- Map response indices back to the original source rows, including when
empty inputs were filtered out of the request.
- Preserve the existing null result for a missing embedding and reject
duplicate or out-of-range indices before writing rows.

## Validation

- Tested `Table.add()` and `to_arrow()` using the real OpenAI Python SDK
and a loopback OpenAI-compatible endpoint. On `main`, `alpha` and `beta`
received each other's vectors. With this patch each row retained its
vector.
- `pytest -c python/pyproject.toml
python/python/tests/test_embeddings.py -q -k openai` passed 20 tests.
Two live provider tests were skipped because no API key was supplied.
- Ruff lint and formatting passed. The Python source used the
release-matching `0.42.0b38` native wheel.

AI-assisted investigation, implementation and testing.
2026-11-30 20:12:19 +08:00
Divyam Talwar 2d7dceaad1 fix(python): preserve local paths for Jina image embeddings (#5256)
Fixes #5255.

## Problem

The Python Jina adapter treats local paths as URL paths when opening an
image. This strips a literal `#` and anything after it from a filename.
It also passes the encoded path from a `file:` URI straight to Pillow,
so a URI returned by `Path.as_uri()` fails for filenames containing
spaces or non-ASCII characters.

## Changes

- Pass filesystem paths to Pillow as supplied and convert explicit
`file:` URI paths with Python's platform-specific `url2pathname`.
- Cover a path containing a literal `#` and a file URI for a filename
containing spaces, Unicode, `#`, and `%`.

## Validation

- Both filename regressions fail on `main` with `FileNotFoundError` and
pass after the change.
- `pytest python/tests/test_embeddings.py -q -k jina` passed all three
selected tests, using the matching `0.42.0b38` native extension and the
Python sources from this checkout. The Jina API call is stubbed in the
regression.
- Ruff formatting and lint checks passed for both changed files.

AI-assisted implementation and testing.
2026-11-30 20:12:11 +08:00
Olexandr88 3b8584cd7d fix(namespace): map rename_table errors to typed errors (#5254)
`LanceNamespaceDatabase::rename_table` wrapped every namespace error in
a generic `Error::Runtime`, so renaming a missing table did not return
`TableNotFound`, unlike `drop_table`.

- Map errors through `map_namespace_lance_error`, so a missing source
table returns `Error::TableNotFound`.
- When the destination name is taken, report `TableAlreadyExists` with
the destination name, not the source name.
- Other errors no longer carry the "Failed to rename table:" prefix.

Tests: `test_namespace_rename_missing_table_returns_not_found` fails on
main with `Runtime { "Failed to rename table: Namespace error: Table not
found ..." }` and passes with this change.
`test_namespace_rename_to_existing_table_returns_already_exists` covers
the destination-name case.
2026-11-30 20:12:00 +08:00
Christopher Krah 8c101f49b9 fix(python): give tied scores the same rank in hybrid rank normalization (#5253)
Refs #4857, which expected tied FTS matches to count as the best FTS
result in both normalize modes. #4858 fixed the zero-range case and left
the tie-breaking in `_rank` open. With `normalize="rank"`, `_rank`
numbers equal scores in argsort order. Of two matches with the same BM25
score, argsort order alone picks the one that gets the lowest rank and
normalizes to 0, the value `LinearCombinationReranker` gives a document
without the keyword:

```python
rows = [{"text": "zebra apple", "vector": [5.0, 5.0]},
        {"text": "zebra grape", "vector": [5.0, 5.1]},
        {"text": "cherry plum", "vector": [0.0, 0.0]}]
# both zebra rows: _score 0.4700036
(tbl.search(query_type="hybrid").vector([0.0, 0.0]).text("zebra")
    .rerank(LinearCombinationReranker(weight=0.3), normalize="rank"))
# fdc8041, 0.42.0b38: zebra grape 0.70, cherry plum 0.30, zebra apple 0.15
# this change:        zebra apple 0.85, zebra grape 0.70, cherry plum 0.30
# normalize="score" already gives the second order
```

Equal scores now share the average of their ranks, as
`scipy.stats.rankdata` does by default. Without ties the ranks are
unchanged, and RRF and MRR do not read them. This also covers equal
vector distances. An untied lowest FTS hit still normalizes to the fill
value, and this PR leaves that as it is.

```
$ cd python && pytest python/tests/test_hybrid_query.py -q   # fdc8041 + 0.42.0b38 native module
30 passed, 1 skipped in 1.48s
# query.py reverted, tests kept: 2 failed (test_hybrid_tied_fts_matches_share_fts_weight[rank], test_rank_gives_tied_scores_the_same_rank)
$ ruff format --check . && ruff check .   # ruff 0.9.9, as CI pins
198 files already formatted
All checks passed!
$ pytest python/tests -m "not slow and not s3_test" -q -n 4   # fresh data/ dir each side
# fdc8041:     11 failed, 4474 passed, 375 skipped, 3 errors
# this change: 12 failed, 4476 passed, 375 skipped, 3 errors
# same 11 on both sides (namespace and stable-row-id tests, missing extras); the 12th, test_table.py::test_merge_insert, passed alone 3 times and in test_table.py -n 4
$ pytest --doctest-modules python/lancedb/query.py -q
23 passed
$ pyright   # 1.1.395: 5 errors in __init__.py and schema.py, the same at fdc8041; query.py is outside the include list
```

@Xuanwo, I picked the average over the best rank of the group, because
the average treats both directions the same. If you want tied FTS
matches to all get the top rank, I will change one line.

Signed-off-by: Christopher Krah <48338417+chrikrah@users.noreply.github.com>
2026-11-30 20:11:51 +08:00
Aiman MalibandClaude Opus 5.5 00bf2a0c0b fix(python): reject pylance writes on checked-out versions (#5252)
## What changed

`LanceTable` gets a small `_ensure_mutable()` helper in
`python/python/lancedb/table.py`. It raises the same `ValueError` as the
native `ensure_mutable()` ("Invalid input, table cannot be modified when
a specific version is checked out") when the handle is pinned with
`checkout()`. It is called before the write is handed to pylance in
`compact_files()`, `merge()`, `cleanup_old_versions()` and both
accelerator branches of `create_index()`.

## Why

Fixes #5251

These methods write through `self.to_lance()` and then call
`checkout_latest()`, so they skip the read-only check that `add()`,
`optimize()` and `merge_insert()` (#4851) apply. On a pinned handle,
`compact_files()` committed to the live table and unpinned the handle,
`merge()` failed with a retryable commit conflict, and
`cleanup_old_versions()` pruned versions while `optimize()` refused to.
The pinned state is only known on the Python side (`_checkout_version`),
so the check is done there.

The TypeScript SDK and Rust have no pylance write path; their writes
already go through `ensure_mutable()`. No public API changes, so no docs
update.

## How it was tested

Run in a `python:3.12-slim` container with the `0.42.0b38` nightly
wheel, pylance `15.1.0b2`, and the Python sources from this branch
copied over the wheel (no Rust change, so no `maturin develop`).

- New tests in `test_table.py`:
`test_pylance_writes_rejected_on_checked_out_version` (parametrized over
`compact_files`, `cleanup_old_versions`, `merge`) checks the error, that
the handle stays on its version, and that the latest version is
untouched. `test_accelerated_index_rejected_on_checked_out_version`
covers both accelerator branches with the mocked `to_lance` used by
`test_create_ivfrq_index_accelerator`.
- On `main` the tests fail: `DID NOT RAISE ValueError` for
`compact_files` and the accelerator index, and `OSError: Retryable
commit conflict for version 3` for `merge`.
- With the fix: the 4 new tests pass in 5 consecutive runs, and
`test_table.py` passes (563 passed, 17 skipped).
- With the `_ensure_mutable()` calls removed, exactly the 4 new tests
fail and no other test in `test_table.py` changes.
- `ruff format --check` and `ruff check` on the two changed files:
clean. No Rust or TypeScript files are touched.

Written with help from Claude Code.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 20:11:42 +08:00
Long Jin a3ad6bd882 fix(python): apply hybrid reranker weights when a search leg is empty (#5245)
## Summary

Apply the configured hybrid weight and missing-score penalty when one of
the
two search legs returns no results. The mixed-leg path already applies
those
weights to a row matched by only one modality.

With `weight=0.25` and `fill=0.4`, a normalized vector distance of 0.2
currently
receives a relevance of 0.80 if FTS returns no results and 0.65 if FTS
returns an
unrelated result. Both cases now return 0.65. The same rule applies when
the
vector leg is empty. Missing raw scores still return as Arrow nulls.

## Validation

Added regression coverage for both empty-leg directions. Each case
compares the
single-leg score with the score for the same row when an unrelated
result
appears on the other leg and checks the raw score and row ID.

- With the release extension built from the base commit (0.42.0b37),
both new
cases fail at the base and pass with this change. The focused reranker
and
  related hybrid controls report 17 passed and one skipped.
- A local LanceDB hybrid search verifies that score and rank
normalization
both preserve the relevance of unchanged vector hits, along with row
IDs,
  raw distances, and null raw FTS scores.
- Ruff 0.9.9 lint and format checks pass for both changed files.
2026-11-30 20:11:33 +08:00
Christopher Krah d6a2dad539 fix(python): skip null and empty texts in Ollama embeddings (#5233)
With the Ollama embedding function, one row whose source text is `None`
fails the whole `table.add`, even with `on_bad_vectors="null"`. The
`ollama` client rejects `None` in `input`, and the retry wrapper retries
that validation error 7 times, so on the default settings the call
sleeps about 106 s before it raises. `generate_embeddings` is typed
`list[Union[np.array, None]]`, and the OpenAI function already returns
`None` for null and empty texts. This does the same in
`OllamaEmbeddings.generate_embeddings` and, as OpenAI does since #5195,
sends no request when no text is left. That reverses
`test_ollama_generate_embeddings_empty_array` from #4605, which pinned
one request for an empty batch so a model error still surfaces. That
error now waits for the first real text. No issue is open for this.

```python
emb = get_registry().get("ollama").create()
class Doc(LanceModel):
    text: Optional[str] = emb.SourceField()
    vector: Optional[Vector(3)] = emb.VectorField()

tbl.add([{"text": None}], on_bad_vectors="null")
# cb7f1bad: RuntimeError: ... ('Maximum number of retries (7) exceeded.', 2 validation errors for EmbedRequest)  106.3s
# this change: [{'text': None, 'vector': None}], no request sent
```

```
$ cd python && pytest python/tests/test_ollama_embeddings.py -q   # cb7f1bad: 15 passed
16 passed in 0.17s
$ pytest python/tests/test_ollama_embeddings.py -q   # ollama.py reverted, tests kept
2 failed, 14 passed in 0.24s
$ ruff format --check . && ruff check .   # ruff 0.9.9, as CI pins
204 files already formatted
All checks passed!
$ pytest python/tests -m "not slow and not s3_test" -q --ignore=python/tests/test_torch.py   # cb7f1bad: 4828 passed, 128 skipped
15 failed, 4814 passed, 128 skipped, 75 deselected, 401 warnings in 182.68s (0:03:02)
# the 15 are docs/ tests that hit the data/ dir a previous run left behind
# not run: test_torch.py, remote and s3 tests; ollama.py is outside pyright's include list
```

@Xuanwo, from the code `gemini_text.py` and `cohere.py` pass `None`
straight to their APIs too. I can send the same change for them next.

---------

Signed-off-by: Christopher Krah <48338417+chrikrah@users.noreply.github.com>
2026-11-30 20:11:23 +08:00
小哥不太逍遥 94b1360257 fix(rust): prevent panics and NaN bypass in dataloader split and shuffle validation (#5219)
## Summary

Fixes multiple panics and a `NaN` validation bypass in the dataloader
permutation split and shuffle configuration validation
(`rust/lancedb/src/dataloader/permutation/split.rs` and
`rust/lancedb/src/dataloader/permutation/shuffle.rs`), returning
`Error::InvalidInput` cleanly instead of crashing.

## Root Cause

Invalid configurations passed through Rust, Python, or Node.js bindings
could bypass validation or panic during validation/execution:

1. **`SplitSizes::Fixed(0)` divide-by-zero panic**:
`SplitSizes::validate()` evaluated `(num_rows / num_splits) == 0`
without first checking `*num_splits == 0`, panicking with integer
division by zero inside `validate()`.
2. **Empty `SplitSizes::Percentages` / `SplitSizes::Counts`
out-of-bounds panic**: Both passed `validate()` with `Ok(())` and later
panicked with index out of bounds (`split_sizes[split_id]`) in
`Splitter::sequential_split_id()`.
3. **`SplitSizes::Percentages` `NaN` bypass**: Because IEEE 754
comparisons with `NaN` return `false`,
`SplitSizes::Percentages(vec![f64::NAN])` bypassed `< 0.0 || > 1.0`, `<
1.0`, and `sum > 1.0` checks in `validate()`.
4. **Unchecked `u64` summation overflow**: `SplitSizes::Counts` and
`SplitStrategy::Hash` summed weights/counts with `.sum::<u64>()` / `+`,
panicking on overflow in debug builds or wrapping in release builds.
5. **`Shuffler::shuffle()` divide-by-zero panics**: The `clump_size ==
0` check lived only inside `do_shuffle()`, so inputs routed through
`in_memory_shuffle()` (when `num_rows < max_rows_per_file`, the default
path for datasets under 1M/10M rows) panicked in `shuffle_batch()` at
`.div_ceil(0)`. Similarly, `max_rows_per_file == 0` panicked in
`do_shuffle()` at `num_rows.div_ceil(0)`.

## Changes

- `rust/lancedb/src/dataloader/permutation/split.rs`:
- Reject `*num_splits == 0`, empty `Percentages`/`Counts`,
non-finite/`NaN` percentages via `!(0.0..=1.0).contains(percentage)`,
and overflowing `Counts` sums in `SplitSizes::validate()`.
- Reject `clump_size == Some(0)` in `SplitStrategy::Random` and
overflowing weight sums in `SplitStrategy::Hash` inside
`SplitStrategy::validate()`.
- `rust/lancedb/src/dataloader/permutation/shuffle.rs`:
- Validate `max_rows_per_file == 0` and `clump_size == Some(0)` upfront
at the entry of `Shuffler::shuffle()` so both in-memory and external
shuffle paths return `Error::InvalidInput` cleanly before creating
temporary directories or dividing.
- Add unit tests in `split.rs` and `shuffle.rs` covering all invalid
configurations end-to-end.

## Verification

- Confirmed all 5 new tests fail on `main` prior to the fix (including
division-by-zero panics at `split.rs:670`, `shuffle.rs:92`, and
`shuffle.rs:131`).
- Verified the full `dataloader::permutation::` unit test suite passes
after the fix:
- `cargo test --profile ci --locked -p lancedb --lib
dataloader::permutation::` (`54 passed; 0 failed`)
  - `cargo fmt --all -- --check`
  - `cargo clippy --profile ci --locked -p lancedb --lib --tests`
2026-11-30 20:11:15 +08:00
小哥不太逍遥 ab6a9a8d61 fix(rust): advance BackgroundCache generation on seed, fetch start, and peek (#5212)
## Summary

Fixes stale-state overwrite and cache-wipe races in `BackgroundCache`
(`rust/lancedb/src/utils/background_cache.rs`) by advancing
`cache.generation` on every state transition out of or into a fetch
epoch.

## Root Cause

`BackgroundCache` tracks a monotonic `generation` counter so delayed
background tasks cannot clobber newer cache states, but previously
`generation` was only incremented in `invalidate()`:

1. **`seed()` did not advance `generation`**: If a caller invoked
`seed(value)` while an earlier fetch was still in flight, the in-flight
task still matched `cache.generation == generation` when it completed.
On `Ok(stale)`, it silently overwrote the seeded value with stale data;
on `Err(_)`, `State::Current` fell into `_ => None` and cleared the
seeded cache to `State::Empty`.
2. **`determine_action()`'s `future.peek()` transition and
`start_fetch()` did not advance `generation`**: When a caller consumed a
completed fetch via `future.peek()` before the fetch's spawned task
acquired the mutex (and potentially started a subsequent fetch), the
earlier fetch's delayed spawned task still observed the same
`generation`. On `Ok`, it could overwrite a newer in-flight fetch with
stale data; on `Err`, it could clear a newer `State::Refreshing` entry
and break single-flight coalescing.

## Changes

- Advance `cache.generation` via `wrapping_add(1)` in `seed()`,
`invalidate()`, `start_fetch()`, and the `future.peek()` transition in
`determine_action()`.
- Update the `generation` and `seed()` comments to document the
state-transition invariant.
- Add 4 deterministic async unit tests covering:
  - `test_seed_during_inflight_fetch_prevents_stale_overwrite`
  - `test_seed_during_inflight_fetch_error_preserves_seeded_value`
-
`test_peek_transition_prevents_delayed_task_from_clobbering_next_fetch`
-
`test_peek_transition_prevents_delayed_error_task_from_wiping_next_fetch`

## Verification

- Confirmed all 4 new unit tests fail on `main` prior to the fix (`4
failed`, reproducing stale overwrite, seeded cache wipe, in-flight fetch
clobbering, and broken coalescing).
- Verified all 19 tests pass after the fix:
- `cargo test --profile ci --locked -p lancedb --lib
utils::background_cache` (`19 passed; 0 failed`)
  - `cargo fmt --all -- --check`
  - `cargo clippy --profile ci --locked -p lancedb --lib --tests`
2026-11-30 20:11:05 +08:00
adityashankarv af34021f32 fix(python): drop unrequested _rowid from hybrid return_score=all (#5206)
Fixes #5200

A sync hybrid search reranked with `RRFReranker(return_score="all")`
returned `_rowid` even when the caller never asked for it. An explicit
`with_row_id(False)` before `rerank()` did not remove it.

`LanceHybridQueryBuilder.rerank()` set `self._with_row_id = True` when
the reranker used `return_score="all"`. `_finish_hybrid_results` then
treated `_rowid` as user-requested, because `_user_requested_row_id()`
only looks at that flag. The reranker does need row ids internally to
fuse the two legs and restore `_distance` / `_score`, but `_run_hybrid`
already requests them on both legs. The column should be dropped at
the end unless the caller asked for it.

The async builder already did this: `AsyncHybridQuery.rerank()` never
set `_with_row_id`, and `_run_hybrid` drops `_rowid` unless
`_user_requested_row_id()` is true. This PR aligns the sync path with
that behavior by removing the assignment. I also updated the nearby
comments that said `rerank(return_score="all")` turned `_with_row_id`
on.

## Tests

Added sync and async regressions in `python/tests/test_hybrid_query.py`:

- `return_score="all"` without `with_row_id` keeps `_distance`,
  `_score`, and `_relevance_score`, and omits `_rowid`.
- Sync also checks an explicit `with_row_id(False)`.
- `with_row_id(True)` (async: `with_row_id()`) still returns `_rowid`.

## How tested

Python 3.13.5, `lancedb==0.42.0b30` wheel from
`https://pypi.fury.io/lancedb/`, with `PYTHONPATH` pointed at
`python/python` from this checkout so the edited files were the ones
under test. The Rust extension was not rebuilt.

Issue repro, before this change:

- default `RRFReranker()`: `['text', 'vector', '_relevance_score']`
- `return_score="all"`: included `_rowid`
- `with_row_id(False).rerank(... return_score="all")`: still included
`_rowid`

After this change, the same two `return_score="all"` calls return
`['text', 'vector', '_distance', '_score', '_relevance_score']`.
`with_row_id(True)` still returns `_rowid`.

- `pytest python/tests/test_hybrid_query.py
python/tests/test_rerankers.py python/tests/test_wal_hybrid.py`: 82
passed, 14 skipped
- `ruff format --check python` and `ruff check python`: passed

Not run: a remote/Enterprise client, or an RTE table on the
primary-key fallback path.

## AI assistance

I used an AI coding assistant (Grok Bot) to investigate the issue,
draft the patch and tests, and help write this description. I reviewed
the change, reproduced the bug before and after, and ran the tests and
linters above myself.
2026-11-30 20:07:55 +08:00
Zain QureshiandClaude Opus 5.5 058d5c3f4c fix(nodejs): reject fractional branch versions (#5167)
Refs #4848

## Problem

With the table at version 2, `branches.create("exp", undefined, 1.5)`
silently forked from version 1 and left the new branch missing the
second row. With `exp` at version 3, both `branches.checkout("exp",
2.5)` and `openTable("my_table", undefined, { branch: "exp", version:
2.5 })` returned version 2 and its two rows. N-API coerced these
arguments to `i64` before Rust could validate them
(`nodejs/src/table.rs:2698` and `nodejs/src/table.rs:2743`).

## Change

`Branches.create` and `Branches.checkout` now use the existing
TypeScript integer validator before calling N-API
(`nodejs/lancedb/table.ts:2759` and `nodejs/lancedb/table.ts:2773`).
Creation rejects with `fromVersion must be a non-negative integer` and
creates no branch. Both reads reject with `version must be a
non-negative integer` because opening a named branch delegates to the
same checkout method (`nodejs/lancedb/connection.ts:830`).

Tag-based creation rejects a simultaneous source version through the
native source conflict check (`nodejs/src/table.rs:2701`). With no
branch or with `branch: "main"`, `openTable` uses `Table.checkout`
(`nodejs/lancedb/connection.ts:832`). That separate numeric checkout
path and tag version validation are covered by #4916.

## Tests

Ran from `nodejs` on macOS arm64 using the published beta.26 native
binding built from the base revision. The two regressions failed on the
base. The patched branch run passed 34 tests, and the Node suite passed
1,885 tests with 27 skipped. Live Enterprise and S3 integrations were
outside this run.

```sh
env -u OPENAI_API_KEY -u LANCEDB_API_KEY -u S3_TEST ./node_modules/.bin/jest --runInBand --runTestsByPath __test__/table.test.ts --testNamePattern='branch' --no-verbose
env -u OPENAI_API_KEY -u LANCEDB_API_KEY -u S3_TEST ./node_modules/.bin/jest --runInBand --no-verbose
./node_modules/.bin/tsc -b
./node_modules/.bin/tsc --noEmit -p __test__/tsconfig.json
./node_modules/.bin/biome ci .
```

The package's TypeDoc and postprocessing commands also passed, and the
generated JavaScript API reference matched the checked-in files.

Prepared with AI assistance (Codex and Claude Code) and reviewed with
GitHub Copilot.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 20:07:05 +08:00
lancedb-gatefixer[bot] 2d4e0fb3f2 fix: preserve branch scope during Embedded tag time travel (#4852)
Embedded tag checkout replaced the handle's only branch identity. After
reading a tag on another branch, `checkout_latest()` followed that
branch and subsequent writes or restores could commit there.

Keep the handle's original branch and Lance `BranchIdentifier`
separately from its visible snapshot. A branch name alone cannot
distinguish the original branch from a replacement after deletion and
reuse. Cross-branch tags remain readable, and Python pickle and snapshot
copies preserve both identities. `checkout_latest()` reattaches to the
original branch, so later appends stay there. `current_branch()`
continues to report the visible snapshot's branch.

Validate the retained identity before `checkout_latest()` changes the
handle or `restore(tag)` commits; a reused branch name is rejected
without changing either branch tip. Independent and query snapshot
copies retain this identity too. Reject an ambiguous cross-branch
restore before committing. To restore on the tag's branch, first open a
handle there with `branches.checkout(...)` or Rust's
`checkout_branch(...)`. Update Rust, Python sync/async, TypeScript,
generated API documentation, and the tag-based versioning guide for this
behavior.

Python pickle state also carries the original `BranchIdentifier` through
reopening. A foreign snapshot stays readable if the originating branch
is replaced while serialized, but latest checkout and restore reject the
replacement. Latest and same-branch pinned handles validate the saved
identity before reopening returns. Older pickle states without the
identifier keep their existing reopen behavior; they cannot validate an
identity that was never saved.

Validation:

- All 12 new branch-name reuse regression cases failed before the
identity fix and pass afterward. They cover latest checkout and restore,
direct handles and snapshot copies, all three consistency modes, and
unchanged versions and contents on both branch tips. Query snapshot
identity retention is also covered.
- All 8 new Python pickle regression cases failed before the
serialization fix and pass afterward. They replace the branch while the
handle is serialized, cover latest checkout and restore across three
consistency modes, verify unchanged tips, and reject replacement data
when reopening latest or same-branch pinned handles.
- 494 Rust table tests and 23 dataset consistency tests passed with
`--features remote --profile ci`; Clippy for the core and Python
bindings, Rust formatting, and `git diff --check` passed.
- 62 targeted Python tag, branch, pickle, and restore tests passed in
the uv-managed environment after rebuilding the extension. An additional
compatibility check verified that older pickle states without the
identifier still reopen and return to the original branch.
- Earlier SDK validation: 9 targeted Node tests passed, including the
cross-branch regression. Node native build, TypeScript compilation,
lint/format checks, and API documentation generation passed. TypeScript
sources are unchanged in this Python pickle follow-up.
- Python package Ruff lint/format checks passed; repository-wide Ruff
reported 59 pre-existing findings in untouched `docs/web-tests/` files.
Vale 3.24.0 found no prose issues on the changed guide lines.

Fixes #4842

<!-- lance-gatekeeper-fix:v1 agent=c1c6448a3f02ec6db445df5e3d8dd77f
generation=1 -->


<!-- gatefixer-walkthrough:v1
head=078eceadbedc15cf179d9d4dcce249c83e7010f9 -->
## Change walkthrough

```mermaid
flowchart LR
    A["Save original identity"] --> B["Reopen visible snapshot"]
    B --> C{"Foreign snapshot?"}
    C -->|No| D["Validate before return"]
    C -->|Yes| E["Retain saved identity"]
    E --> F["Validate latest or restore"]
```

**Read:** [Serialize and
reopen](https://github.com/lancedb/lancedb/blob/078eceadbedc15cf179d9d4dcce249c83e7010f9/python/python/lancedb/table.py#L4541-L4594)
→ [Reinstate identity
safely](https://github.com/lancedb/lancedb/blob/078eceadbedc15cf179d9d4dcce249c83e7010f9/rust/lancedb/src/table/dataset.rs#L278-L307)
→ [Serialized-handle
regressions](https://github.com/lancedb/lancedb/blob/078eceadbedc15cf179d9d4dcce249c83e7010f9/python/python/tests/test_table.py#L1300-L1360).

<sub>Snapshot:
[078ecea](https://github.com/lancedb/lancedb/commit/078eceadbedc15cf179d9d4dcce249c83e7010f9)</sub>
<!-- gatefixer-walkthrough:end -->

---------

Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com>
2026-11-30 20:05:58 +08:00
Christopher Krah c0d46c31ba fix(python): map a Literal with None to a nullable field (#4927)
`pydantic_to_schema` raises on `Literal["a", "b", None]`, a field
pydantic accepts with `None`. [PEP
586](https://peps.python.org/pep-0586/#legal-parameters-for-literal-at-type-check-time)
reads it as `Union[Literal["a", "b"], None]`, the same type as
`Optional[Literal["a", "b"]]`, which #4678 maps to a nullable `utf8`.
The `None` is the optional part, not a second value type, so #4678's
rule that `Literal["a", 1]` raises does not cover it. The Literal branch
counted `NoneType` anyway and raised "All values of a Literal must have
the same type".

Before, on `1157a07`:

```
$ python probe.py
Optional[Literal]: pyarrow.Field<kind: string>
pydantic accepts None: kind=None
Literal[..., None]: TypeError: Converting Pydantic type to Arrow Type: unsupported type typing.Literal['a', 'b', None]. All values of a Literal must have the same type.
```

After, the last line prints `pyarrow.Field<kind: string>`, nullable. No
issue exists for this.

<details><summary>probe.py</summary>

```python
from typing import Literal, Optional
from lancedb.pydantic import LanceModel, pydantic_to_schema

class Opt(LanceModel):
    kind: Optional[Literal["a", "b"]] = None

class Lit(LanceModel):
    kind: Literal["a", "b", None] = None

print("Optional[Literal]:", pydantic_to_schema(Opt).field("kind"))
print("pydantic accepts None:", Lit(kind=None))
try:
    print("Literal[..., None]:", pydantic_to_schema(Lit).field("kind"))
except TypeError as e:
    print("Literal[..., None]: TypeError:", e)
```

</details>

The fix has two halves, and each test fails without one of them.
`_unwrap_optional_annotation` turns `Literal["a", None]` into
`Literal["a"]`, so the field and a list item become nullable. The
Literal branch skips `None` when it collects value types, so
`Optional[Literal["a", None]]` maps too. A mixed `Literal["a", 1, None]`
still raises, and so does a bare `Literal[None]`.

### Verification

```
# Python 3.12, lancedb 0.42.0b9 wheel from pypi.fury.io (the version at 1157a07), its _lancedb.abi3.so in the tree
$ PYTHONPATH=. python -m pytest -q -p no:cacheprovider tests/test_pydantic.py
this branch:                         87 passed
pydantic.py reverted, tests kept:    2 failed, 85 passed   (TypeError: ... must have the same type)
None kept in the value types only:   1 failed, 86 passed
unwrap change reverted only:         2 failed, 85 passed   (status not nullable; the write fails)
$ PYTHONPATH=. python -m pytest -q -p no:cacheprovider tests/test_pydantic.py tests/test_table.py tests/test_db.py
1157a07:      8 failed, 650 passed, 17 skipped
this branch:  8 failed, 652 passed, 17 skipped   # the same 8 in test_table.py (blob, merge, compact, namespace) on both
$ ruff format --check <both files> && ruff check <both files>      # ruff 0.9.9, as CI pins it
2 files already formatted
All checks passed!
# not run: the Rust build, the full suite; pyright's include list leaves out pydantic.py
```

@Xuanwo, you merged #4678. I left a bare `Literal[None]` raising, since
a column that can only hold null has no value type to store. Does that
match how you want it?

---------

Signed-off-by: Christopher Krah <48338417+chrikrah@users.noreply.github.com>
2026-11-30 19:16:26 +08:00
Tomwang.eth 855bec2a57 fix(node): make tags.list() values plain serializable objects (#4915)
Related: #4849 (same defect class on `branches.list()`, fixed in #4914).

**Problem**
`Tags.list()` returns napi class instances whose fields live on the
prototype, so `console.log`, spread and `JSON.stringify` show `{}` — the
documented example (`{ "v1": { version: 1, manifestSize: ... } }`)
doesn't match what users actually see. Property access
(`tags["v1"].version`) works, which is why the existing tests didn't
catch it.

**Change**
- `TagContents` stays a runtime napi class export: existing ESM named
imports of `TagContents` and `instanceof` checks keep working, and
existing TypeScript values remain assignable to it.
- `nodejs/lancedb/table.ts` post-processes `Tags.prototype.list()`
results, promoting `version` and `manifestSize` to own enumerable
properties on each returned instance by reusing the class getters and
setters. Values are now enumerable, spreadable and JSON-serializable
with no fields added, removed or renamed.
- TS-only: the Python SDK already returns proper dicts with both fields.

**Tests**
- New regression test in `nodejs/__test__/table.test.ts` covers the
named import and `instanceof` alongside own-enumerable keys, spread and
a JSON round-trip through `tags.list()`.
- The tag tests from #5145 are kept and pass against this change.
- Verified locally on Linux x86_64: `tsc -b`, Biome checks, and the
focused tags suite (4 passed), including `tags.create(name)` /
`tags.create(name, null)` behavior.
2026-11-30 19:14:23 +08:00
Jyotishman Dasandrishi02102017 163177f6a5 fix(python): report iterator schema mismatches in create_table (#4921)
When `create_table()` is given an iterator and a later item can't be
cast to the schema of the first one, the user gets an `AttributeError`
instead of the intended schema-mismatch error:

```python
def batches():
    yield [{"id": 1, "text": "a"}]
    yield [{"id": "two", "text": "b"}]

db.create_table("t", batches())
# RuntimeError: ... Unknown error: 'list' object has no attribute 'schema'
```

The same happens with pandas DataFrames, and with `table.add(...,
on_bad_vectors="drop" | "fill" | "null")`, which goes through the same
helper. A plain `table.add(batches())` already reports the mismatch
correctly.

The cause is in `_iterator_to_reader`: the error message reads `.schema`
from the raw item the iterator yielded rather than from the Arrow table
it was converted to. This PR uses the converted table's schema, as
`scannable._from_iterable` already does, and adds a regression test in
`test_db.py` that fails without the change.

With the fix, the error is:

```
Input iterator yielded a batch with schema that does not match the schema of other batches.
Expected:
id: int64
text: string
Got:
id: string
text: string
```

Tested with `pytest python/tests/test_db.py python/tests/test_table.py
-m "not slow and not s3_test"` (574 passed, 17 skipped) and ruff on the
changed files.

---------

Co-authored-by: rishi02102017 <rishi02102017@users.noreply.github.com>
2026-11-30 19:14:15 +08:00
Alex Castillo González f639e178a1 fix(python): skip empty or null texts in bedrock-text embeddings (#4919)
With `bedrock-text`, a single empty or null cell in the source column
makes `add()` fail while computing embeddings, before `on_bad_vectors`
gets a chance to run, so `on_bad_vectors="drop"`, `"null"` and `"fill"`
have no effect.

**Root cause:** `BedRockText.generate_embeddings` sends every text to
`invoke_model`, including empty strings and `None`. Bedrock rejects an
empty `inputText` (minimum length 1), and the error is re-raised as a
`ValueError`. The `openai`, `oci_genai` and `nvidia` functions already
return `None` for such entries, and `table.py` passes `None` vectors on
to `on_bad_vectors`.

**Fix:** skip `None` and empty strings in `generate_embeddings` and put
`None` in their slot (other values, such as `False`, are still sent, so
their input error reaches the caller); the other texts are embedded as
before and keep their positions. With the default
`on_bad_vectors="error"`, `add()` still raises, now with the bad-vector
error that points at `on_bad_vectors` instead of a boto3 error.

**Tests:** `test_embeddings_bedrock.py` uses a fake bedrock-runtime
client that rejects an empty `inputText`, and checks `["alpha", "" /
None, "be"]` returns `[[5.0], None, [2.0]]` with only two calls made.
Both cases fail on `main` and pass with the change. An `add()` through
the same fake client with `drop`, `null` and `fill` fails on `main` and
succeeds here (2, 4 and 4 of 4 rows). A `table.add()` with a `False`
source under `on_bad_vectors="drop"` checks that the non-string input
error still reaches the caller. None of this was run against live
Bedrock.

This change was prepared with the help of an AI assistant (Claude), and
the submitter is responsible for it.


---------
2026-11-30 19:14:08 +08:00
Alex Castillo González fc13fd6e98 fix(nodejs): batch OpenAI embedding requests to 2048 inputs (#4833)
`OpenAIEmbeddingFunction.computeSourceEmbeddings` in the Node SDK sent
every row in a single `embeddings.create` call. `makeArrowTable` passes
the whole source column at once, and the OpenAI embeddings endpoint
accepts at most 2048 inputs per request, so `table.add` (or
`createTable`) with more than 2048 rows and an `openai` embedding
function fails with a 400.

This splits the input into chunks of at most 2048 and concatenates the
results in order. Inputs of 2048 rows or fewer still make one request,
as before.

Test: `nodejs/__test__/embedding_openai.test.ts` mocks `openai`
(rejecting requests with more than 2048 inputs) and checks that 5000
rows produce 5000 embeddings, in order, over three calls (2048, 2048,
904). It fails without the change and passes with it.

This change was prepared with AI assistance (Claude Code).
2026-11-30 19:14:00 +08:00