Commit Graph
1822 Commits
Author SHA1 Message Date
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
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
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
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
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
Preston ZhaoandPreston Zhao 3e31cd4eab test: lock in that delete keeps table indices (#5168)
`AsyncTable.delete` does not drop indexes. On current main the reported
failure does not reproduce: delete forwards to Lance `dataset.delete`,
and index retention comes from Lance (the retention change in
lance-format/lance#4033, which closed lance-format/lance#3940), not from
recreating indexes after the delete. Nothing in this repo's CI currently
asserts it, so these tests lock that behavior in at the LanceDB level:

- Vector (IVF_FLAT), BTree, and full-text indexes survive deleting a
subset of rows, `delete("true")`, and a later insert. After the partial
delete, `list_indices` and `index_stats` still report indexed rows, and
scalar, full-text, and vector search return the live rows and omit
deleted ones.
- The reported empty-table sequence: `connect_async` to a directory,
create an empty table from a schema, `create_index(column="txt",
config=BTree())` before any rows, add 10 rows, then `delete(where="txt =
'1'")`. `list_indices()` still has one BTree on `txt`, the table has 9
rows, and the same holds after `open_table`.

This is an alternative to the approach in #2471, which saved and
recreated every index inside `delete`. That was declined by a maintainer
because it leaves a window with no indexes, and it is unnecessary now
that Lance keeps them.

Tests only: `rust/lancedb/src/table/delete.rs` and
`python/python/tests/test_table.py`. Both are deterministic (single IVF
partition, exact vectors, distinct FTS tokens) and run in well under a
second.

Refs #2434

## Test plan

- [x] `cargo test --features remote -p lancedb --lib
table::delete::tests::delete_keeps_vector_scalar_and_fts_indices` (5
runs)
- [x] `cargo clippy --features remote -p lancedb --tests -- -D
warnings`, `cargo fmt --all -- --check`
- [x] `pytest` on the two new Python tests (5 runs)
- [x] `ruff format --check .` and `ruff check .` in `python/`

Written with Cursor (Grok).

Co-authored-by: Preston Zhao <195942578+canyang25@users.noreply.github.com>
2026-11-30 19:12:12 +08:00
dayan02dev b0aa0de889 fix(python): accept nullable merge_insert input on tables with a primary key (#5297)
## Why
After `set_unenforced_primary_key`, `merge_insert` from a DataFrame, a
list of dicts or an inferred-schema Arrow table fails, while `add()` of
the same rows works:

```python
t = db.create_table("t", pa.table({"id": pa.array(["a"]), "n": [1]}, schema=pa.schema([pa.field("id", pa.string(), False), pa.field("n", pa.int64())])))
t.set_unenforced_primary_key("id")
t.merge_insert("id").when_matched_update_all().when_not_matched_insert_all().execute([{"id": "b", "n": 2}])
# RuntimeError: lance error: LanceError(Schema): Primary key column and all its ancestors must not be nullable: Field(id=0, name=id, type=string)
```

`_align_field` copies the table field's metadata onto the nullable
source field, so the source schema marks a nullable `id` as the primary
key and Lance rejects it. merge_insert takes the key from the dataset
schema and rejects null keys on write, so the source doesn't need the
marker.

## What changed
`AsyncTable._do_merge` (used by sync, async and remote tables) drops the
primary-key markers from source fields that are nullable or under a
nullable struct. `create_table` and `add` are unchanged.

## Tests
New tests in `test_table.py` and `test_remote_db.py` fail without the
fix.

#5081 has the same message but a different cause in Lance
(lance-format/lance#11212).
2026-11-30 19:08:13 +08:00
DogerW 06828e2842 fix(python): handle JSON schema callbacks on LanceModel fields (#5300)
Fixes #5299.

Pydantic accepts a callback in `Field(json_schema_extra=...)` for
customizing a field's JSON Schema. Creating an Embedded table from a
model with such a field raised `AttributeError` when LanceDB tried to
read embedding metadata with `.get()`.

Read LanceDB metadata from mapping-style extras and leave callbacks to
Pydantic. The regression test creates a table with the expected Arrow
string column, then verifies that the callback still removes the field's
default from its JSON Schema.

### Validation

- The new test failed with the reported exception on `9a79107` before
the fix.
- All 97 tests in `test_pydantic.py` and
`test_embedding_field_metadata.py` passed on Python 3.11.15 with
Pydantic 2.13.4, using the checkout's Python sources and the published
0.42.0b38 native extension.
- Verified create, insert and read-back on Python 3.12.7 with Pydantic
2.14.4. Ruff lint and formatting checks passed for the Python SDK.
2026-11-30 19:07:29 +08:00
Alex Castillo González 9564431b57 fix(python): support Cohere embed-v4.0 in CohereEmbeddingFunction (#4805)
`CohereEmbeddingFunction(name="embed-v4.0")` raised `ValueError: Model
embed-v4.0 not supported`.

**Cause.** `ndims()` uses a closed list of v2/v3 model names and raises
for everything else, so Cohere's current embedding model was rejected.

**Fix.** Add `embed-v4.0` to `ndims()`, returning its default output
dimension (1536).

**Test.** `test_cohere_embed_v4_is_supported` creates the function with
`name="embed-v4.0"` and checks `ndims() == 1536`. It fails before the
change with the `ValueError` and passes after; the existing Cohere
default-model test still passes.

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


---------
2026-11-30 19:06:26 +08:00
Raunak Kumar Pandey f1320b8ef9 fix(python): skip null text when reranking with Jina (#5296)
Fixes #5295.

Vector results can include a row with a valid vector and null text. The
Jina text reranker would send that null in `documents`, although the API
requires text documents. Filter the Arrow table before extracting
request documents so returned indices still select the correct rows and
retain their original scores. When every candidate lacks text, return a
typed empty result without contacting Jina.

Both regression cases failed on the upstream Python source and passed
with the change. They cover a null before two valid documents, reordered
response indices, preservation of row IDs, distance and schema, and an
all-null input with no request. The local test loaded the exact source
reranker modules on top of LanceDB 0.41.0 with PyArrow 26.0.1 and a
mocked HTTP client. Ruff lint, formatting and whitespace checks passed.
This test did not use a live Jina service. AI assistance was used to
investigate and draft the change.

Signed-off-by: Raunak <raunakpandey1007@gmail.com>
2026-11-30 18:16:11 +08:00
Jack Ye 9a79107651 chore: align Lance revision for strict FTS prewarm 2026-11-29 18:38:40 -08:00
Xuanwo c55eaae0dc fix: explain Function catalog SDK compatibility errors (#5250)
An older Function catalog can reject the query generated by
`get_function` at `FORMAT`, or by `list_functions` at `LIMIT`. When the
operation receives its exact trailing-input diagnostic at submission,
append guidance on matching the Python SDK to the Enterprise build. Keep
the original SQL error, request ID, gRPC status and any build metadata
supplied by the server.

Compared 24 loopback Flight responses through the public synchronous and
asynchronous Python APIs against the published b38 wheel. Eight lookups
and listings gained the pairing guidance. The other 16 responses
preserved their error types and diagnostics, including authorization,
missing resources and unrelated parser failures. The candidate passed
122 Python tests and four Rust tests. Current catalog reads and opaque
continuation tokens also worked after build discovery returned 404.
2026-11-28 08:30:52 +08:00
Xuanwo 6283f83a92 fix(python): preserve omitted Function GPU counts (#5249)
`@function(gpu=True)` currently serializes `gpus_per_worker: 1` even
when the caller omits `gpu_count`. This prevents registration on servers
that support single-GPU Functions but reject an explicit GPU count
field.

Preserve omission through registration and runtime digest calculation.
The effective default is still one GPU per worker. With an explicit
`gpu_count=1` or `gpu_count=2`, the request and digest include the
declared count. As a result, the omitted and explicit-one forms now have
distinct runtime digests even though both request one GPU in practice.

The regression test captures the Flight SQL `CREATE FUNCTION` request
for CPU, omitted GPU count, and explicit counts of one and two. Only the
omitted-count case failed on the base revision. All 34 focused Python
tests and Ruff checks passed on the candidate Python source with a
compatible native extension. Local replay of the captured requests
against the registration admission code confirmed that the older
implementation accepts the omitted count and that the current
implementation resolves the four effective counts to 0, 1, 1 and 2.
2026-11-28 08:14:36 +08:00
Xuanwo e185dc8646 perf: raise the default Blob V2 direct-read threshold to 32 MiB (#5248)
Enterprise SDKs use an inclusive 32 MiB default for eligible Blob V2
direct reads. The paired field comparison with the 10 MiB SDK default
measured higher direct-read latency at 10 and 16 MiB. At 32 MiB, the
interval for the latency difference spanned zero. [SDK version used in
the field comparison](https://github.com/lancedb/lancedb/pull/5247)

The earlier mixed-load test measured lower Plan Executor cache pressure
with direct reads enabled at the 10 MiB cutoff. That result covers the
tested size mix. With the 32 MiB cutoff, reads from 10 MiB up to (but
excluding) 32 MiB go through the proxy, so the impact on executor
traffic and cache pressure depends on the workload's size distribution.

The existing internal override still takes precedence. Direct reads keep
the 16 MiB part size. The Node binding test verifies proxy routing one
byte below the default and two contiguous object-store ranges with a
matching SHA-256 at exactly 32 MiB.
2026-11-28 03:21:37 +08:00
Xuanwo 129028f300 perf: improve presigned Blob V2 reads (#5247)
## Behavior

Presigned Blob V2 reads retry an idempotent ranged GET once after a
recognized disconnect or timeout before the complete response headers
arrive. This includes an abrupt TLS EOF while receiving the headers. A
retry preserves the physical Range and the still-valid URL. Expiry
triggers resolution on the pinned snapshot. Once the complete headers
arrive, the existing status and body paths handle the response.
Enterprise connections default to a 300-second pool idle timeout and
presigned object-store connections default to 30 seconds. The existing
override applies to both pools.

Loopback TCP tests exercise FIN and RST on a reused connection, both
with zero response bytes and after a partial header. They verify the
send count with retries enabled and disabled, the exact replayed Range
and the payload digest. A truncated body after complete headers returns
an error after one send.

Direct reads over 16 MiB stream bounded physical ranges into their
corresponding slices of the final buffer. The per-read fan-out uses
Lance's `LANCE_IO_THREADS`, capped by the connection's existing
`LANCE_CLIENT_BLOB_REQUEST_CONCURRENCY` limit (8 by default). Each
request retains its permit through body consumption. The 10 MiB routing
threshold continues to apply to the full logical read.

The connection can reuse unexpired presigned locations for verified rows
under the same table, column, snapshot and request credentials. Range
offsets and sizes come from the resolver. The existing batch request
covers the requested rows of a shared Packed or Managed sidecar.
Reopening a verified row uses its prior resolution, and the first open
of each unseen SQL descriptor still authorizes just that row. The public
API and REST response format are unchanged.
2026-11-28 02:29:31 +08:00
Lance Release fdc8041b2a Bump version: 0.42.0-beta.37 → 0.42.0-beta.38 2026-11-27 09:41:44 +00:00
LanceDB Robot 6acc3b6d91 chore: update lance dependency to v16.0.0-beta.5 2026-11-27 01:39:42 -08:00
Henry Su fdfbb98a9c fix(python): give tied FTS scores full weight in hybrid normalization (#4858)
## Why

Hybrid search normalizes FTS scores with min-max. When all FTS scores
are equal (one match, or a tie), the range is 0 and every score became
0. `LinearCombinationReranker` treats 0 as a missing FTS match. So a
lone keyword match could rank below documents without the keyword. Fixes
#4857.

## What changed

- `_normalize_scores` takes a `tie_value` for the zero-range case. The
default stays 0, so vector distances are unchanged.
- The FTS leg passes `tie_value=1.0`, so tied FTS matches count as the
best FTS result.

## Scope

- Covers the zero-range case for both `normalize="score"` and
`normalize="rank"`.
- Leaves out how `_rank` breaks ties among equal scores. That is a
separate question.

## Blast Radius

The change only affects hybrid queries where every FTS hit has the same
score. RRF and MRR use list position, so their results don't change.
LinearCombination and custom score-based rerankers now give those hits
full FTS weight.

## Verification

- A new test in `test_hybrid_query.py` fails on main in both normalize
modes and passes with the fix.
- `pytest python/tests -m "not slow and not s3_test"`: 3272 passed, 167
skipped.
- `ruff format --check` and `ruff check` (0.9.9, the version pinned by
pre-commit) pass.
2026-11-27 16:23:03 +08:00
lancedb-gatefixer[bot] a663417fa9 fix: validate remote tag checkout branch and version (#4853)
Remote tag checkout discarded the tag's branch and pinned its version on
the handle's own branch without checking that the version existed. This
could read a different snapshot or leave the handle pinned to a
nonexistent version.

Resolve the complete tag reference and reject cross-branch tags with an
error naming both branches. For a tag on the handle's branch, reuse
numeric checkout to validate the version before committing the selector
and freshness state. This also protects Python's
`open_table(version=tag)`, which delegates to tag checkout. To read a
tag on another branch, obtain that branch's handle first with
`checkout_branch` in Rust or `table.branches.checkout(...)` in Python.
The Python checkout docstrings and tag-based versioning guide document
this requirement.

Add 17 regression cases covering cross-branch tags in both directions,
main-branch aliases, same-branch reads, and failed validation on
writable and pinned handles. Twelve cases failed against the original
implementation. Update the existing freshness and schema-cache tests for
the validation request.

Validation:

- `cargo test --locked --profile ci --features remote -p lancedb --lib
remote:: -- --quiet` — 921 tests passed using mocked remote endpoints.
- `cargo fmt --all` — passed.
- `cargo clippy --locked --profile ci --features remote -p lancedb
--tests --examples` — passed.
- Python documentation: Ruff lint and formatting checks passed for the
Python tree, using Ruff 0.15.20 from `python/uv.lock`. Python syntax
checks passed; executable ASTs are unchanged. Repository-wide `ruff
check .` reports 59 pre-existing errors in six unchanged
`docs/web-tests` files; unrelated formatter changes were excluded.

Fixes #4843

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


<!-- gatefixer-walkthrough:v1
head=35f8db881e36b83b9aab478cb5db72e485c9eca7 -->
## Change walkthrough

```mermaid
flowchart TD
    resolve["Resolve tag reference"] --> branch{"Same branch?"}
    branch -->|No| reject["Return branch error"]
    branch -->|Yes| validate["Describe tag version"]
    validate -->|Error| error["Return version error"]
    validate -->|Success| pin["Pin validated snapshot"]
```

The selector and freshness state commit together under the version lock.

**Read:** [branch
guard](https://github.com/lancedb/lancedb/blob/35f8db881e36b83b9aab478cb5db72e485c9eca7/rust/lancedb/src/remote/table.rs#L4075-L4092)
→ [validation and
commit](https://github.com/lancedb/lancedb/blob/35f8db881e36b83b9aab478cb5db72e485c9eca7/rust/lancedb/src/remote/table.rs#L2865-L2893)
→ [tag and branch
guidance](https://github.com/lancedb/lancedb/blob/35f8db881e36b83b9aab478cb5db72e485c9eca7/docs/web/management/table.mdx#L1745-L1755).

<sub>Snapshot:
[35f8db8](https://github.com/lancedb/lancedb/commit/35f8db881e36b83b9aab478cb5db72e485c9eca7)</sub>
<!-- gatefixer-walkthrough:end -->

---------

Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com>
2026-11-27 15:50:20 +08:00
Lance Release e38d8bef56 Bump version: 0.42.0-beta.36 → 0.42.0-beta.37 2026-11-27 03:36:01 +00:00
LanceDB RobotandXuanwo 344a4d1444 chore: update lance dependency to v16.0.0-beta.4 (#5242)
Update the Rust and Java Lance dependencies to
[v16.0.0-beta.4](https://github.com/lance-format/lance/releases/tag/v16.0.0-beta.4)
and pin Python tests to pylance 16.0.0b4. Make the Node.js Rust blob
parser helper private so strict workspace Clippy passes.

---------

Co-authored-by: Xuanwo <github@xuanwo.io>
2026-11-27 11:34:27 +08:00
Jack Ye b53bbd0bca fix(sql)!: request JSON for storage integration descriptions
Apply the reviewed storage integration change.
2026-11-26 17:31:51 -08:00
Jack Ye 00fc309a85 fix(sql)!: request JSON for function descriptions
Apply the reviewed function change.
2026-11-26 17:30:50 -08:00
Jack Ye 4498be55f5 fix(sql)!: request JSON for materialized view descriptions
Apply the reviewed materialized view change.
2026-11-26 17:30:32 -08:00
Lance Release 85dcf3a3c5 Bump version: 0.42.0-beta.35 → 0.42.0-beta.36 2026-11-26 15:06:40 +00:00
LanceDB Robot 2b193cc6ea chore: update lance dependency to v16.0.0-beta.3 (#5237)
Update Rust and Java dependencies to [Lance
v16.0.0-beta.3](https://github.com/lance-format/lance/releases/tag/v16.0.0-beta.3).
Pin Python tests to pylance 16.0.0b3 and refresh the lockfile.
2026-11-26 23:05:33 +08:00
Lance Release 0adfd22db1 Bump version: 0.42.0-beta.34 → 0.42.0-beta.35 2026-11-26 10:50:09 +00:00
LanceDB Robot c54d15ada1 chore: update lance dependency to v16.0.0-beta.2 (#5234)
Bump the Rust and Java Lance dependencies to v16.0.0-beta.2 and
synchronize the Python pylance requirements and lockfile with 16.0.0b2.

[Lance v16.0.0-beta.2
release](https://github.com/lance-format/lance/releases/tag/v16.0.0-beta.2)
2026-11-26 10:48:43 +00:00
Lance Release 9adb403656 Bump version: 0.42.0-beta.33 → 0.42.0-beta.34 2026-11-26 03:33:13 +00:00
Xuanwo 4a5c4a84a9 fix(python): preserve the requested package index on Function inspection (#5220)
Python callers inspecting a pinned Function version lose the explicit
primary package index URL even when the server includes it. Preserve
`runtime.environment.build.index_url` through `get_function` and
canonical JSON.

The requested build view contains only the explicit primary URL. Extra
indexes, other sources, and service defaults can still apply when that
view is absent. Compare the server's `runtime_digest` with the authored
runtime's digest for identity. The inspection view can omit inputs to
that digest.

Typed registration rejects nonempty build settings before issuing a
request. The existing decorator options and `refresh_lock` use the same
registration path.

Loopback Flight tests exercised sync and async pinned reads with a
primary index plus an extra index, and with only an extra index. They
also verified that typed submission rejects unsupported settings before
sending a request and still submits ordinary decorator definitions with
`refresh_lock`. A separate local replay verified pinned readback against
a published version with a credential-free primary index. The focused
suites passed 547 Python and 129 Rust tests, with three Rust tests
marked ignored.
2026-11-26 11:31:43 +08:00
Lance Release 7c3d68e951 Bump version: 0.42.0-beta.32 → 0.42.0-beta.33 2026-11-25 23:49:08 +00:00
Lance Release 7e1478b547 Bump version: 0.42.0-beta.31 → 0.42.0-beta.32 2026-11-25 21:41:10 +00:00
LanceDB RobotandXuanwo 17532bb8c3 chore: update lance dependency to v15.1.0-beta.2 (#5217)
Bump the Rust workspace and Java Lance dependencies to [Lance
v15.1.0-beta.2](https://github.com/lance-format/lance/releases/tag/v15.1.0-beta.2)
and pin the matching `pylance` beta in the Python test extra.

Raise the Rust toolchain and minimum supported version to 1.98.0 as
required by Lance, and address the new Clippy diagnostics.

Co-authored-by: Xuanwo <github@xuanwo.io>
2026-11-26 05:39:46 +08:00
Lance Release 8441dab874 Bump version: 0.42.0-beta.30 → 0.42.0-beta.31 2026-11-25 21:32:03 +00:00
LanceDB RobotandXuanwo da6aa8c779 chore: update lance dependency to v15.1.0-beta.1 (#5213)
Update the Rust workspace and Java dependencies to [Lance
v15.1.0-beta.1](https://github.com/lance-format/lance/releases/tag/v15.1.0-beta.1).
Pin the Python test extra to the matching pylance 15.1.0b1 release and
refresh the lockfile.

---------

Co-authored-by: Xuanwo <github@xuanwo.io>
2026-11-25 13:30:32 -08:00
Xuanwo 60519d42ce feat(remote): add presigned direct Blob V2 reads (#5210)
## What

Add a capability-gated client path for large Blob V2 reads over LanceDB
Enterprise:

- A successful `describe` advertises `x-lancedb-blob-locations: 1`; the
SDK then resolves pinned row locations through `POST
/v1/table/{id}/blob_locations/`.
- Whole reads (`fetch_blobs`) and seekable handles (`fetch_blob_files` /
`open_blob_file`) read presigned object-store URLs directly for eligible
values and ranges at or above a provisional internal 10 MiB threshold.
- Small ranges and `fetch_blob_ranges` stay on the existing proxy path,
including aggregate batches whose total exceeds the proxy byte limit.
- Shared `Packed` / `Managed` sidecars translate logical ranges to
physical offsets and validate the full numeric `Content-Range` tuple,
not just its start or total.
- Presigned traffic uses a separate HTTP client with no Enterprise
default headers, so service credentials never reach object storage.
- The first resolver response must carry a valid query-snapshot
identity. That identity is then required on every later partition and
preserved through object-URL refresh, proxy fallback and oversized
whole-value recovery. A resolver `503` falls back once to the proxy path
using any version and identity already pinned; other resolver errors
propagate. Object-store `503`s do not masquerade as resolver
unavailability.
- A read that starts without the capability reuses its supplied
`ReadSnapshot` if a later describe enables direct opening mid-operation.
- Version and query-snapshot pinning, NULL/order alignment and empty
values are preserved.

## Client network requirement

On Enterprise clusters that enable direct Blob reads, large values and
individual ranges may be fetched from short-lived object-store URLs
instead of the LanceDB proxy. Clients then need network access to the
object-store endpoint, including private endpoint routing, DNS, TLS
trust and egress rules, in addition to the LanceDB endpoint. Small reads
stay on the LanceDB proxy.

## Why

Large Blob V2 reads currently stream every payload byte through `Object
Store -> Plan Executor -> Query Node -> client`. That consumes internal
bandwidth, inflates PE/QN memory use and pollutes executor caches with
low-locality `.blob` data. This is the SDK half of ENT-4358; the server
implementation is in Sophon.

## Compatibility

No public SDK signatures change. Old clusters omit the capability header
and keep the existing proxy behaviour with zero extra round trips. The
10 MiB threshold is an internal prototype choice pending the paired
acceptance measurement; it is not a public knob.

## Validation

- `cargo check -p lancedb --quiet --features remote --tests` passes.
- `cargo test -p lancedb --quiet --features remote --lib
remote::table::blobs::tests` passes: 65 tests.
- New coverage includes direct whole reads, shared-sidecar physical
offsets and Content-Range rejection, small-range proxy routing, mixed
large/small range batches, resolver `503` fallback with pinned state, no
second resolver after fallback, object-store `503` not triggering proxy
fallback, missing/mismatched resolver identity rejection, resolver
identity preservation through refresh/proxy/oversized recovery,
supplied-snapshot reuse on mid-operation capability refresh, and
NULL/order/null-preserving paths.

A real-QN acceptance run with the candidate SDK binary is separate and
still pending deployment of the candidate server image.
2026-11-26 03:16:25 +08:00
147fdb25a0 feat(python): add two-phase shuffled reads (2PSR) to elastic dataloader (#5066)
Supersedes #4263, which I can no longer push to. This PR continues the
same branch, so the review history is there.

## Summary

Adds two-phase shuffled reads (2PSR) to `StreamingDataset`, enabled with
`block_size`:

1. **Block shuffle:** contiguous blocks of `block_size` live rows are
shuffled and assigned to splits. This replaces 1-phase's per-row take
with mostly contiguous range scans, which are much cheaper on object
storage.
2. **Bounded row shuffle:** each split shuffles rows over a rolling
window of `window_blocks` blocks. `max_shuffle_distance` bounds how far
a row can move.

The feature also supports `filter` (sparse takes of live rows),
`reshuffle_blocks_per_epoch`, resume and checkpointing, background block
prefetch, and multi-worker DataLoaders. 2PSR stays opt-in:
`block_size=None` keeps today's 1-phase behavior.

Since the last review round:

- **Fixed worker startup with small blocks.** The pickled dataset no
longer grows with the number of blocks; the block order is rebuilt in
`__setstate__`. Once that pickle passed the 64 KiB pipe buffer, spawned
DataLoader workers started one at a time (~280 s with 128 workers at
≤2,048-row blocks).
- **Fixed per-call block copies.** Each loaded block is combined into a
single chunk. Before, `take` on a multi-chunk block concatenated the
whole block on every call.
- **Fixed early eviction.** Blocks are evicted only behind the
contiguous prefix of rows already served. With `io_queue_depth > 1`,
calls can arrive out of order and previously evicted blocks that were
still needed, causing 5–40% extra reads.
- **New default:** `window_blocks` now defaults to 8, and the docstring
recommends `block_size=512` with DataLoader workers.

None of these fixes changes which rows are read or their order. A check
across 12 config, epoch and seed combinations on 8 ranks gave identical
per-rank order before and after.

## Benchmarks

Throughput was measured on EC2 i4i.32xlarge in us-west-2, reading a
FineWeb-Edu table of 4,096 B rows. Each number is the median of 3
trials, and each trial is a full pass. 2PSR used 512-row blocks, 256
splits, 128 workers and `io_queue_depth=4`. 1-phase used 32 splits, 8
workers and `io_queue_depth=32`.

| Storage | Rows | 2PSR | 1-phase | Speedup |
|---|---|---|---|---|
| S3 | 8.4M (34 GB) | 16.9 s | 230 s | 13.6× |
| S3 | 33.6M (137 GB) | 45.6 s | 781 s | 17.1× |
| S3 | 134M (550 GB) | 168 s | 3,098 s | 18.4× |
| Local NVMe | 8.4M | 16.4 s | 116 s | 7.1× |

On the 8.4M-row S3 table, 2PSR reads 1.5–2.0 GB/s at every block size
from 128 to 65,536 rows. A fit across the three S3 sizes gives 2PSR
about 7 s fixed cost plus 3.4 GB/s, and 1-phase about 39 s plus 0.18
GB/s. That puts the large-table limit near 19×.

Quality was measured by pretraining GPT-2 124M on 2^21 FineWeb-Edu docs
for 16 epochs on 8×H100. The table shows final validation loss, mean ±
SD over 3 seeds:

| Reader | Final val loss |
|---|---|
| 1-phase | 2.8464 ± 0.0006 |
| 2PSR, `block_size=128`, msd 4,096 | 2.8457 ± 0.0011 |
| 2PSR, `block_size=512`, msd 4,096 | 2.8457 ± 0.0007 |
| 2PSR, `block_size=2048`, msd 32,768 | 2.8466 ± 0.0009 |
| No shuffle (1 seed) | 2.8606 |

Every 2PSR config is within seed noise of 1-phase. The 95% confidence
intervals of the difference all include zero and are at most 13% of the
no-shuffle penalty. Training throughput was the same for every reader
(3.15–3.18M tok/s, GPU-bound).

## Testing

- `test_elastic_dataloader.py` and `test_permutation.py`: all 324 tests
pass after merging `main`. The new tests cover:
  - pickle size independent of block count;
  - single-chunk blocks;
  - no re-reads under out-of-order calls;
  - window defaults;
  - resume, filter, worker and checkpoint behavior.
- `ruff check` and `ruff format --check` are clean.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Xuanwo <github@xuanwo.io>
2026-11-25 09:08:39 -08:00
Yang Cen 757dcc0a6b feat(functions): declare multiple bindings in one add_columns call (#5202)
Allow Python callers to pass several registered Function applications to
`add_columns`. Rust callers can use `function_bindings` to submit the
same atomic declaration. An application can consume another output in
the mapping, including one declared later.

The SDK checks the Enterprise server's batch-declaration capability
before sending the mutation. Single-binding callers continue to use the
existing request shape. This change covers declaration only.

Coverage includes Python mapping validation, the Rust HTTP request with
dependent bindings, and older servers with missing or unknown capability
values. Correctness tests run in CI.
2026-11-25 13:39:57 +08:00
Lance Release a709c6db1e Bump version: 0.42.0-beta.29 → 0.42.0-beta.30 2026-11-25 03:11:25 +00:00
LanceDB Robot 73d44232d4 chore: update lance dependency to v15.0.0-beta.35 (#5201)
Bump the Rust Lance crates and Java lance-core to v15.0.0-beta.35, and
pin the Python tests to pylance 15.0.0b35. The Cargo and Python
lockfiles are refreshed for the [Lance
tag](https://github.com/lance-format/lance/tree/v15.0.0-beta.35).
2026-11-24 19:06:43 -08:00
LanceDB Robot 85522224f2 chore: update lance dependency to v15.0.0-beta.34 (#5199)
Updates the Rust and Java Lance dependencies to v15.0.0-beta.34 and pins
the Python test dependency to pylance 15.0.0b34. See the [Lance
release](https://github.com/lance-format/lance/releases/tag/v15.0.0-beta.34).
2026-11-25 08:05:02 +08:00
Tanay fc6dfca11a feat(python): add map() method to Permutation for dict-based transforms (#3264)
### Summary

Adds `Permutation.map(fn, *, batched=False)`, a dict-based alternative
to `with_transform` so users can write `fn(dict) -> dict` without
touching `pyarrow.RecordBatch`.

- `batched=False` (default): `fn` receives one row as a dict and returns
a dict.
- `batched=True`: `fn` receives the batch as `dict[str, list]` and
returns the same shape, with one value per input row.
- `map` calls can be chained. Callbacks run in order and the returned
dict replaces the row, so the next callback only sees what the previous
one returned. Unlike HuggingFace's `Dataset.map`, the output is not
merged into the row.
- A mapped permutation always yields `list[dict]`, whatever `batched`
is, so it works with the default `DataLoader` collate. Rows keep their
position, including duplicate offsets, and `take_offsets([])` returns
`[]`.
- `map` cannot be combined with an explicit `with_format` or
`with_transform`, in either order. Doing so raises `ValueError` when the
chain is built, whether or not the format's optional dependency is
installed.
- `select_columns`, `remove_columns` and `schema` describe the columns
read from the base table, which are the input of the first callback.
- The chain is stored in a module-level callable, so a mapped
permutation can be pickled into `spawn` `DataLoader` workers as long as
the callbacks themselves are picklable.
- `with_transform` remains available for direct Arrow access.

### Documentation

- Docstrings for `map`, `with_format` and `with_transform` cover the
mixing rule, with a `DataLoader` + `collate_fn` example on `map`.
- Adds a "Transforming rows with map" section to the Permutation guide.

### Testing

- `test_permutation.py`: chaining, mixing errors in both orders, output
validation, duplicate and empty offsets, projection and schema, and a
pickle round-trip for both `batched` modes.
- `test_permutation.py`: the mixing check with `polars` unimportable,
with pickles written before the `explicit_transform` flag, and with a
transform passed to the constructor.
- `test_torch.py`: a map chain read through `DataLoader(...,
multiprocessing_context="spawn", num_workers=1)`.

Closes [#3246](https://github.com/lancedb/lancedb/issues/3246)
2026-11-25 06:35:28 +08:00
Xuanwoandsaudademjj 7a8661759d fix(python): skip OpenAI embedding requests when no valid text remains (#5195)
## Summary

Follows up on #4005, which handled mixed batches in
`OpenAIEmbeddings.generate_embeddings`. On `main`, when the input batch
is empty (`[]`) or filtering leaves no valid texts (such as `[None,
""]`), `generate_embeddings` still imports the `openai` SDK and calls
`embeddings.create(input=[], ...)`.

- Return `[None] * len(texts)` early in
`python/python/lancedb/embeddings/openai.py` when no valid texts remain
(`[]` for empty input, one `None` per item when all inputs are
filtered), before importing the `openai` SDK or sending a request.
- Add regression tests in `python/python/tests/test_embeddings.py`
covering empty batches, all-filtered batches, and native-backed
`table.add(..., on_bad_vectors="null")` verifying rows are kept with
null vectors and no OpenAI request is made.

## Attribution

Successor to #3152. The early return and nullable ingestion test were
originally contributed by @saudademjj in #3152.

## Verification

- 3 new regression tests failed before the fix (observing
`embeddings.create(input=[], ...)`) and passed after.
- Related embedding test suite: `148 passed, 1 skipped, 9 deselected`
(mocked client only; no live OpenAI API calls).
- Ruff check and format checks are clean for the changed `python/` tree
(scoped to `python/` only).

Co-authored-by: saudademjj
<128795969+saudademjj@users.noreply.github.com>

Co-authored-by: saudademjj <128795969+saudademjj@users.noreply.github.com>
2026-11-24 23:14:13 +08:00
Sarwar BhuiyanandClaude Opus 5.5 5f87e18541 feat: create any registered Lance scalar index plugin by name (#5004)
Closes #4933

Adds a generic configuration for creating a scalar index of any type
recognized by a registered database plugin, using its type name and
optional JSON parameters. Index types without a dedicated SDK
configuration can use the same API.

- **Rust:** `Index::Plugin(PluginIndexBuilder)`, with JSON-object
parameters through `.params(...)` or `.params_json(...)`.
- **Python:** `ScalarPlugin(index_type, params=None)`, accepting a dict
or JSON-object string.
- **TypeScript:** `Index.plugin(indexType, params?)`, accepting an
object or JSON-object string.
- Type names are case-insensitive and surrounding whitespace is ignored.
Empty names and non-object parameters are rejected.
- Native index introspection preserves existing built-in types and
exposes other registered plugin types through `Custom`.

The guide and SDK references describe index creation, parameter
ownership, and errors consistently. They recommend a dedicated
configuration when one exists and refer readers to the plugin’s
documentation for parameter names and defaults. The TypeScript reference
is regenerated from its source JSDoc.

## Remote request format

Generic requests use `index_type: "PLUGIN"` and a separate upper-cased
`plugin_type`. Arbitrary parameters stay nested under `params`,
preserving omitted parameters versus an explicit empty object. This
separates the generic path from built-in handling and prevents
parameters from overwriting request fields.

## Validation

- 52 targeted tests passed: 15 Rust, 22 Python, and 15 TypeScript.
- Two Rust plugin doctests passed.
- Rust Clippy, the Node build and lint, changed-file Python lint,
TypeDoc generation, Vale, and the MkDocs SDK-reference build passed.
- Request tests cover Python sync/async calls, object and JSON-string
inputs, normalization, omitted and empty parameters, and collisions with
request metadata.
- Repository-wide Ruff reports existing findings in untouched
documentation examples. Strict Mintlify validation reports four missing
snippet-export warnings, also reproduced on the unmodified commit.

## Follow-ups

- Replace the built-in examples with a widely available custom plugin
when one is available, as discussed in review.
- Remote `list_indices()` and `index_stats()` still parse a fixed set of
type names; accepting unrecognized plugin types through a `Custom`
fallback remains separate.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 07:00:47 -08:00